text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accuracy_helper(egg, match='exact', distance='euclidean', features=None):
""" Computes proportion of words recalled Parameters egg : quail.Egg Data to analyze match : str (exact, best or smooth) Matching approach to compute recall matrix. If exact, the presented and recalled items must be identical (default). If best, the recalled item that is most similar to the presented items will be selected. If smooth, a weighted average of all presented items will be used, where the weights are derived from the similarity between the recalled item and each presented item. distance : str The distance function used to compare presented and recalled items. Applies only to 'best' and 'smooth' matching approaches. Can be any distance function supported by numpy.spatial.distance.cdist. Returns prop_recalled : numpy array proportion of words recalled """ |
def acc(lst):
return len([i for i in np.unique(lst) if i>=0])/(egg.list_length)
opts = dict(match=match, distance=distance, features=features)
if match is 'exact':
opts.update({'features' : 'item'})
recmat = recall_matrix(egg, **opts)
if match in ['exact', 'best']:
result = [acc(lst) for lst in recmat]
elif match is 'smooth':
result = np.mean(recmat, axis=1)
else:
raise ValueError('Match must be set to exact, best or smooth.')
return np.nanmean(result, axis=0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect(self):
"""Establish connection to PostgreSQL Database.""" |
if self._connParams:
self._conn = psycopg2.connect(**self._connParams)
else:
self._conn = psycopg2.connect('')
try:
ver_str = self._conn.get_parameter_status('server_version')
except AttributeError:
ver_str = self.getParam('server_version')
self._version = util.SoftwareVersion(ver_str) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _createStatsDict(self, headers, rows):
"""Utility method that returns database stats as a nested dictionary. @param headers: List of columns in query result. @param rows: List of rows in query result. @return: Nested dictionary of values. First key is the database name and the second key is the statistics counter name. """ |
dbstats = {}
for row in rows:
dbstats[row[0]] = dict(zip(headers[1:], row[1:]))
return dbstats |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _createTotalsDict(self, headers, rows):
"""Utility method that returns totals for database statistics. @param headers: List of columns in query result. @param rows: List of rows in query result. @return: Dictionary of totals for each statistics column. """ |
totals = [sum(col) for col in zip(*rows)[1:]]
return dict(zip(headers[1:], totals)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _simpleQuery(self, query):
"""Executes simple query which returns a single column. @param query: Query string. @return: Query result string. """ |
cur = self._conn.cursor()
cur.execute(query)
row = cur.fetchone()
return util.parse_value(row[0]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getConnectionStats(self):
"""Returns dictionary with number of connections for each database. @return: Dictionary of database connection statistics. """ |
cur = self._conn.cursor()
cur.execute("""SELECT datname,numbackends FROM pg_stat_database;""")
rows = cur.fetchall()
if rows:
return dict(rows)
else:
return {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getDatabaseStats(self):
"""Returns database block read, transaction and tuple stats for each database. @return: Nested dictionary of stats. """ |
headers = ('datname', 'numbackends', 'xact_commit', 'xact_rollback',
'blks_read', 'blks_hit', 'tup_returned', 'tup_fetched',
'tup_inserted', 'tup_updated', 'tup_deleted', 'disk_size')
cur = self._conn.cursor()
cur.execute("SELECT %s, pg_database_size(datname) FROM pg_stat_database;"
% ",".join(headers[:-1]))
rows = cur.fetchall()
dbstats = self._createStatsDict(headers, rows)
totals = self._createTotalsDict(headers, rows)
return {'databases': dbstats, 'totals': totals} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getLockStatsMode(self):
"""Returns the number of active lock discriminated by lock mode. @return: : Dictionary of stats. """ |
info_dict = {'all': dict(zip(self.lockModes, (0,) * len(self.lockModes))),
'wait': dict(zip(self.lockModes, (0,) * len(self.lockModes)))}
cur = self._conn.cursor()
cur.execute("SELECT TRIM(mode, 'Lock'), granted, COUNT(*) FROM pg_locks "
"GROUP BY TRIM(mode, 'Lock'), granted;")
rows = cur.fetchall()
for (mode, granted, cnt) in rows:
info_dict['all'][mode] += cnt
if not granted:
info_dict['wait'][mode] += cnt
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getLockStatsDB(self):
"""Returns the number of active lock discriminated by database. @return: : Dictionary of stats. """ |
info_dict = {'all': {},
'wait': {}}
cur = self._conn.cursor()
cur.execute("SELECT d.datname, l.granted, COUNT(*) FROM pg_database d "
"JOIN pg_locks l ON d.oid=l.database "
"GROUP BY d.datname, l.granted;")
rows = cur.fetchall()
for (db, granted, cnt) in rows:
info_dict['all'][db] = info_dict['all'].get(db, 0) + cnt
if not granted:
info_dict['wait'][db] = info_dict['wait'].get(db, 0) + cnt
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getBgWriterStats(self):
"""Returns Global Background Writer and Checkpoint Activity stats. @return: Nested dictionary of stats. """ |
info_dict = {}
if self.checkVersion('8.3'):
cur = self._conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("SELECT * FROM pg_stat_bgwriter")
info_dict = cur.fetchone()
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect(self):
"""Establish connection to MySQL Database.""" |
if self._connParams:
self._conn = MySQLdb.connect(**self._connParams)
else:
self._conn = MySQLdb.connect('') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getStorageEngines(self):
"""Returns list of supported storage engines. @return: List of storage engine names. """ |
cur = self._conn.cursor()
cur.execute("""SHOW STORAGE ENGINES;""")
rows = cur.fetchall()
if rows:
return [row[0].lower() for row in rows if row[1] in ['YES', 'DEFAULT']]
else:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getParams(self):
"""Returns dictionary of all run-time parameters. @return: Dictionary of all Run-time parameters. """ |
cur = self._conn.cursor()
cur.execute("SHOW GLOBAL VARIABLES")
rows = cur.fetchall()
info_dict = {}
for row in rows:
key = row[0]
val = util.parse_value(row[1])
info_dict[key] = val
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getProcessStatus(self):
"""Returns number of processes discriminated by state. @return: Dictionary mapping process state to number of processes. """ |
info_dict = {}
cur = self._conn.cursor()
cur.execute("""SHOW FULL PROCESSLIST;""")
rows = cur.fetchall()
if rows:
for row in rows:
if row[6] == '':
state = 'idle'
elif row[6] is None:
state = 'other'
else:
state = str(row[6]).replace(' ', '_').lower()
info_dict[state] = info_dict.get(state, 0) + 1
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getProcessDatabase(self):
"""Returns number of processes discriminated by database name. @return: Dictionary mapping database name to number of processes. """ |
info_dict = {}
cur = self._conn.cursor()
cur.execute("""SHOW FULL PROCESSLIST;""")
rows = cur.fetchall()
if rows:
for row in rows:
db = row[3]
info_dict[db] = info_dict.get(db, 0) + 1
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getDatabases(self):
"""Returns list of databases. @return: List of databases. """ |
cur = self._conn.cursor()
cur.execute("""SHOW DATABASES;""")
rows = cur.fetchall()
if rows:
return [row[0] for row in rows]
else:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _retrieve(self):
"""Query Apache Tomcat Server Status Page in XML format and return the result as an ElementTree object. @return: ElementTree object of Status Page XML. """ |
url = "%s://%s:%d/manager/status" % (self._proto, self._host, self._port)
params = {}
params['XML'] = 'true'
response = util.get_url(url, self._user, self._password, params)
tree = ElementTree.XML(response)
return tree |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getMemoryStats(self):
"""Return JVM Memory Stats for Apache Tomcat Server. @return: Dictionary of memory utilization stats. """ |
if self._statusxml is None:
self.initStats()
node = self._statusxml.find('jvm/memory')
memstats = {}
if node is not None:
for (key,val) in node.items():
memstats[key] = util.parse_value(val)
return memstats |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getConnectorStats(self):
"""Return dictionary of Connector Stats for Apache Tomcat Server. @return: Nested dictionary of Connector Stats. """ |
if self._statusxml is None:
self.initStats()
connnodes = self._statusxml.findall('connector')
connstats = {}
if connnodes:
for connnode in connnodes:
namestr = connnode.get('name')
if namestr is not None:
mobj = re.match('(.*)-(\d+)', namestr)
if mobj:
proto = mobj.group(1)
port = int(mobj.group(2))
connstats[port] = {'proto': proto}
for tag in ('threadInfo', 'requestInfo'):
stats = {}
node = connnode.find(tag)
if node is not None:
for (key,val) in node.items():
if re.search('Time$', key):
stats[key] = float(val) / 1000.0
else:
stats[key] = util.parse_value(val)
if stats:
connstats[port][tag] = stats
return connstats |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(filepath, update=True):
""" Loads eggs, fried eggs ands example data Parameters filepath : str Location of file update : bool If true, updates egg to latest format Returns data : quail.Egg or quail.FriedEgg Data loaded from disk """ |
if filepath == 'automatic' or filepath == 'example':
fpath = os.path.dirname(os.path.abspath(__file__)) + '/data/automatic.egg'
return load_egg(fpath)
elif filepath == 'manual':
fpath = os.path.dirname(os.path.abspath(__file__)) + '/data/manual.egg'
return load_egg(fpath, update=False)
elif filepath == 'naturalistic':
fpath = os.path.dirname(os.path.abspath(__file__)) + '/data/naturalistic.egg'
elif filepath.split('.')[-1]=='egg':
return load_egg(filepath, update=update)
elif filepath.split('.')[-1]=='fegg':
return load_fegg(filepath, update=False)
else:
raise ValueError('Could not load file.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_example_data(dataset='automatic'):
""" Loads example data The automatic and manual example data are eggs containing 30 subjects who completed a free recall experiment as described here: https://psyarxiv.com/psh48/. The subjects studied 8 lists of 16 words each and then performed a free recall test. The naturalistic example data is is an egg containing 17 subjects who viewed and verbally recounted an episode of the BBC series Sherlock, as described here: https://www.nature.com/articles/nn.4450. We fit a topic model to hand-annotated text-descriptions of scenes from the video and used the model to transform both the scene descriptions and manual transcriptions of each subject's verbal recall. We then used a Hidden Markov Model to segment the video model and the recall models, by subject, into k events. Parameters dataset : str The dataset to load. Can be 'automatic', 'manual', or 'naturalistic'. The free recall audio recordings for the 'automatic' dataset was transcribed by Google Cloud Speech and the 'manual' dataset was transcribed by humans. The 'naturalistic' dataset was transcribed by humans and transformed as described above. Returns data : quail.Egg Example data """ |
# can only be auto or manual
assert dataset in ['automatic', 'manual', 'naturalistic'], "Dataset can only be automatic, manual, or naturalistic"
if dataset == 'naturalistic':
# open naturalistic egg
egg = Egg(**dd.io.load(os.path.dirname(os.path.abspath(__file__)) + '/data/' + dataset + '.egg'))
else:
# open pickled egg
try:
with open(os.path.dirname(os.path.abspath(__file__)) + '/data/' + dataset + '.egg', 'rb') as handle:
egg = pickle.load(handle)
except:
f = dd.io.load(os.path.dirname(os.path.abspath(__file__)) + '/data/' + dataset + '.egg')
egg = Egg(pres=f['pres'], rec=f['rec'], dist_funcs=f['dist_funcs'],
subjgroup=f['subjgroup'], subjname=f['subjname'],
listgroup=f['listgroup'], listname=f['listname'],
date_created=f['date_created'])
return egg.crack() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spsolve(A, b):
"""Solve the sparse linear system Ax=b, where b may be a vector or a matrix. Parameters A : ndarray or sparse matrix The square matrix A will be converted into CSC or CSR form b : ndarray or sparse matrix The matrix or vector representing the right hand side of the equation. Returns ------- x : ndarray or sparse matrix the solution of the sparse linear equation. If b is a vector, then x is a vector of size A.shape[0] If b is a matrix, then x is a matrix of size (A.shape[0],)+b.shape[1:] """ |
x = UmfpackLU(A).solve(b)
if b.ndim == 2 and b.shape[1] == 1:
# compatibility with scipy.sparse.spsolve quirk
return x.ravel()
else:
return x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve(self, b):
""" Solve linear equation A x = b for x Parameters b : ndarray Right-hand side of the matrix equation. Can be vector or a matrix. Returns ------- x : ndarray Solution to the matrix equation """ |
if isspmatrix(b):
b = b.toarray()
if b.shape[0] != self._A.shape[1]:
raise ValueError("Shape of b is not compatible with that of A")
b_arr = asarray(b, dtype=self._A.dtype).reshape(b.shape[0], -1)
x = np.zeros((self._A.shape[0], b_arr.shape[1]), dtype=self._A.dtype)
for j in range(b_arr.shape[1]):
x[:,j] = self.umf.solve(UMFPACK_A, self._A, b_arr[:,j], autoTranspose=True)
return x.reshape((self._A.shape[0],) + b.shape[1:]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_sparse(self, B):
""" Solve linear equation of the form A X = B. Where B and X are sparse matrices. Parameters B : any scipy.sparse matrix Right-hand side of the matrix equation. Note: it will be converted to csc_matrix via `.tocsc()`. Returns ------- X : csc_matrix Solution to the matrix equation as a csc_matrix """ |
B = B.tocsc()
cols = list()
for j in xrange(B.shape[1]):
col = self.solve(B[:,j])
cols.append(csc_matrix(col))
return hstack(cols) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recall_matrix(egg, match='exact', distance='euclidean', features=None):
""" Computes recall matrix given list of presented and list of recalled words Parameters egg : quail.Egg Data to analyze match : str (exact, best or smooth) Matching approach to compute recall matrix. If exact, the presented and recalled items must be identical (default). If best, the recalled item that is most similar to the presented items will be selected. If smooth, a weighted average of all presented items will be used, where the weights are derived from the similarity between the recalled item and each presented item. distance : str The distance function used to compare presented and recalled items. Applies only to 'best' and 'smooth' matching approaches. Can be any distance function supported by numpy.spatial.distance.cdist. Returns recall_matrix : list of lists of ints each integer represents the presentation position of the recalled word in a given list in order of recall 0s represent recalled words not presented negative ints represent words recalled from previous lists """ |
if match in ['best', 'smooth']:
if not features:
features = [k for k,v in egg.pres.loc[0][0].values[0].items() if k!='item']
if not features:
raise('No features found. Cannot match with best or smooth strategy')
if not isinstance(features, list):
features = [features]
if match=='exact':
features=['item']
return _recmat_exact(egg.pres, egg.rec, features)
else:
return _recmat_smooth(egg.pres, egg.rec, features, distance, match) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect(self):
"""Connect to Asterisk Manager Interface.""" |
try:
if sys.version_info[:2] >= (2,6):
self._conn = telnetlib.Telnet(self._amihost, self._amiport,
connTimeout)
else:
self._conn = telnetlib.Telnet(self._amihost, self._amiport)
except:
raise Exception(
"Connection to Asterisk Manager Interface on "
"host %s and port %s failed."
% (self._amihost, self._amiport)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getGreeting(self):
"""Read and parse Asterisk Manager Interface Greeting to determine and set Manager Interface version. """ |
greeting = self._conn.read_until("\r\n", connTimeout)
mobj = re.match('Asterisk Call Manager\/([\d\.]+)\s*$', greeting)
if mobj:
self._ami_version = util.SoftwareVersion(mobj.group(1))
else:
raise Exception("Asterisk Manager Interface version cannot be determined.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _initAsteriskVersion(self):
"""Query Asterisk Manager Interface for Asterisk Version to configure system for compatibility with multiple versions . CLI Command - core show version """ |
if self._ami_version > util.SoftwareVersion('1.0'):
cmd = "core show version"
else:
cmd = "show version"
cmdresp = self.executeCommand(cmd)
mobj = re.match('Asterisk\s*(SVN-branch-|\s)(\d+(\.\d+)*)', cmdresp)
if mobj:
self._asterisk_version = util.SoftwareVersion(mobj.group(2))
else:
raise Exception('Asterisk version cannot be determined.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _login(self):
"""Login to Asterisk Manager Interface.""" |
self._sendAction("login", (
("Username", self._amiuser),
("Secret", self._amipass),
("Events", "off"),
))
resp = self._getResponse()
if resp.get("Response") == "Success":
return True
else:
raise Exception("Authentication to Asterisk Manager Interface Failed.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _initModuleList(self):
"""Query Asterisk Manager Interface to initialize internal list of loaded modules. CLI Command - core show modules """ |
if self.checkVersion('1.4'):
cmd = "module show"
else:
cmd = "show modules"
cmdresp = self.executeCommand(cmd)
self._modules = set()
for line in cmdresp.splitlines()[1:-1]:
mobj = re.match('\s*(\S+)\s', line)
if mobj:
self._modules.add(mobj.group(1).lower()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _initApplicationList(self):
"""Query Asterisk Manager Interface to initialize internal list of available applications. CLI Command - core show applications """ |
if self.checkVersion('1.4'):
cmd = "core show applications"
else:
cmd = "show applications"
cmdresp = self.executeCommand(cmd)
self._applications = set()
for line in cmdresp.splitlines()[1:-1]:
mobj = re.match('\s*(\S+):', line)
if mobj:
self._applications.add(mobj.group(1).lower()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _initChannelTypesList(self):
"""Query Asterisk Manager Interface to initialize internal list of supported channel types. CLI Command - core show applications """ |
if self.checkVersion('1.4'):
cmd = "core show channeltypes"
else:
cmd = "show channeltypes"
cmdresp = self.executeCommand(cmd)
self._chantypes = set()
for line in cmdresp.splitlines()[2:]:
mobj = re.match('\s*(\S+)\s+.*\s+(yes|no)\s+', line)
if mobj:
self._chantypes.add(mobj.group(1).lower()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hasModule(self, mod):
"""Returns True if mod is among the loaded modules. @param mod: Module name. @return: Boolean """ |
if self._modules is None:
self._initModuleList()
return mod in self._modules |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hasApplication(self, app):
"""Returns True if app is among the loaded modules. @param app: Module name. @return: Boolean """ |
if self._applications is None:
self._initApplicationList()
return app in self._applications |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hasChannelType(self, chan):
"""Returns True if chan is among the supported channel types. @param app: Module name. @return: Boolean """ |
if self._chantypes is None:
self._initChannelTypesList()
return chan in self._chantypes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getCodecList(self):
"""Query Asterisk Manager Interface for defined codecs. CLI Command - core show codecs @return: Dictionary - Short Name -> (Type, Long Name) """ |
if self.checkVersion('1.4'):
cmd = "core show codecs"
else:
cmd = "show codecs"
cmdresp = self.executeCommand(cmd)
info_dict = {}
for line in cmdresp.splitlines():
mobj = re.match('\s*(\d+)\s+\((.+)\)\s+\((.+)\)\s+(\w+)\s+(\w+)\s+\((.+)\)$',
line)
if mobj:
info_dict[mobj.group(5)] = (mobj.group(4), mobj.group(6))
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getChannelStats(self, chantypes=('dahdi', 'zap', 'sip', 'iax2', 'local')):
"""Query Asterisk Manager Interface for Channel Stats. CLI Command - core show channels @return: Dictionary of statistics counters for channels. Number of active channels for each channel type. """ |
if self.checkVersion('1.4'):
cmd = "core show channels"
else:
cmd = "show channels"
cmdresp = self.executeCommand(cmd)
info_dict ={}
for chanstr in chantypes:
chan = chanstr.lower()
if chan in ('zap', 'dahdi'):
info_dict['dahdi'] = 0
info_dict['mix'] = 0
else:
info_dict[chan] = 0
for k in ('active_calls', 'active_channels', 'calls_processed'):
info_dict[k] = 0
regexstr = ('(%s)\/(\w+)' % '|'.join(chantypes))
for line in cmdresp.splitlines():
mobj = re.match(regexstr,
line, re.IGNORECASE)
if mobj:
chan_type = mobj.group(1).lower()
chan_id = mobj.group(2).lower()
if chan_type == 'dahdi' or chan_type == 'zap':
if chan_id == 'pseudo':
info_dict['mix'] += 1
else:
info_dict['dahdi'] += 1
else:
info_dict[chan_type] += 1
continue
mobj = re.match('(\d+)\s+(active channel|active call|calls processed)',
line, re.IGNORECASE)
if mobj:
if mobj.group(2) == 'active channel':
info_dict['active_channels'] = int(mobj.group(1))
elif mobj.group(2) == 'active call':
info_dict['active_calls'] = int(mobj.group(1))
elif mobj.group(2) == 'calls processed':
info_dict['calls_processed'] = int(mobj.group(1))
continue
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getConferenceStats(self):
"""Query Asterisk Manager Interface for Conference Room Stats. CLI Command - meetme list @return: Dictionary of statistics counters for Conference Rooms. """ |
if not self.hasConference():
return None
if self.checkVersion('1.6'):
cmd = "meetme list"
else:
cmd = "meetme"
cmdresp = self.executeCommand(cmd)
info_dict = dict(active_conferences = 0, conference_users = 0)
for line in cmdresp.splitlines():
mobj = re.match('\w+\s+0(\d+)\s', line)
if mobj:
info_dict['active_conferences'] += 1
info_dict['conference_users'] += int(mobj.group(1))
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getVoicemailStats(self):
"""Query Asterisk Manager Interface for Voicemail Stats. CLI Command - voicemail show users @return: Dictionary of statistics counters for Voicemail Accounts. """ |
if not self.hasVoicemail():
return None
if self.checkVersion('1.4'):
cmd = "voicemail show users"
else:
cmd = "show voicemail users"
cmdresp = self.executeCommand(cmd)
info_dict = dict(accounts = 0, avg_messages = 0, max_messages = 0,
total_messages = 0)
for line in cmdresp.splitlines():
mobj = re.match('\w+\s+\w+\s+.*\s+(\d+)\s*$', line)
if mobj:
msgs = int(mobj.group(1))
info_dict['accounts'] += 1
info_dict['total_messages'] += msgs
if msgs > info_dict['max_messages']:
info_dict['max_messages'] = msgs
if info_dict['accounts'] > 0:
info_dict['avg_messages'] = (float(info_dict['total_messages'])
/ info_dict['accounts'])
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getTrunkStats(self, trunkList):
"""Query Asterisk Manager Interface for Trunk Stats. CLI Command - core show channels @param trunkList: List of tuples of one of the two following types: (Trunk Name, Regular Expression) (Trunk Name, Regular Expression, MIN, MAX) @return: Dictionary of trunk utilization statistics. """ |
re_list = []
info_dict = {}
for filt in trunkList:
info_dict[filt[0]] = 0
re_list.append(re.compile(filt[1], re.IGNORECASE))
if self.checkVersion('1.4'):
cmd = "core show channels"
else:
cmd = "show channels"
cmdresp = self.executeCommand(cmd)
for line in cmdresp.splitlines():
for idx in range(len(re_list)):
recomp = re_list[idx]
trunkid = trunkList[idx][0]
mobj = recomp.match(line)
if mobj:
if len(trunkList[idx]) == 2:
info_dict[trunkid] += 1
continue
elif len(trunkList[idx]) == 4:
num = mobj.groupdict().get('num')
if num is not None:
(vmin,vmax) = trunkList[idx][2:4]
if int(num) >= int(vmin) and int(num) <= int(vmax):
info_dict[trunkid] += 1
continue
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getFaxStatsCounters(self):
"""Query Asterisk Manager Interface for Fax Stats. CLI Command - fax show stats @return: Dictionary of fax stats. """ |
if not self.hasFax():
return None
info_dict = {}
cmdresp = self.executeCommand('fax show stats')
ctxt = 'general'
for section in cmdresp.strip().split('\n\n')[1:]:
i = 0
for line in section.splitlines():
mobj = re.match('(\S.*\S)\s*:\s*(\d+)\s*$', line)
if mobj:
if not info_dict.has_key(ctxt):
info_dict[ctxt] = {}
info_dict[ctxt][mobj.group(1).lower()] = int(mobj.group(2).lower())
elif i == 0:
ctxt = line.strip().lower()
i += 1
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getFaxStatsSessions(self):
"""Query Asterisk Manager Interface for Fax Stats. CLI Command - fax show sessions @return: Dictionary of fax stats. """ |
if not self.hasFax():
return None
info_dict = {}
info_dict['total'] = 0
fax_types = ('g.711', 't.38')
fax_operations = ('send', 'recv')
fax_states = ('uninitialized', 'initialized', 'open',
'active', 'inactive', 'complete', 'unknown',)
info_dict['type'] = dict([(k,0) for k in fax_types])
info_dict['operation'] = dict([(k,0) for k in fax_operations])
info_dict['state'] = dict([(k,0) for k in fax_states])
cmdresp = self.executeCommand('fax show sessions')
sections = cmdresp.strip().split('\n\n')
if len(sections) >= 3:
for line in sections[1][1:]:
cols = re.split('\s\s+', line)
if len(cols) == 7:
info_dict['total'] += 1
if cols[3].lower() in fax_types:
info_dict['type'][cols[3].lower()] += 1
if cols[4] == 'receive':
info_dict['operation']['recv'] += 1
elif cols[4] == 'send':
info_dict['operation']['send'] += 1
if cols[5].lower() in fax_states:
info_dict['state'][cols[5].lower()] += 1
return info_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simulate_list(nwords=16, nrec=10, ncats=4):
"""A function to simulate a list""" |
# load wordpool
wp = pd.read_csv('data/cut_wordpool.csv')
# get one list
wp = wp[wp['GROUP']==np.random.choice(list(range(16)), 1)[0]].sample(16)
wp['COLOR'] = [[int(np.random.rand() * 255) for i in range(3)] for i in range(16)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def engineIncluded(self, name):
"""Utility method to check if a storage engine is included in graphs. @param name: Name of storage engine. @return: Returns True if included in graphs, False otherwise. """ |
if self._engines is None:
self._engines = self._dbconn.getStorageEngines()
return self.envCheckFilter('engine', name) and name in self._engines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getSpaceUse(self):
"""Get disk space usage. @return: Dictionary of filesystem space utilization stats for filesystems. """ |
stats = {}
try:
out = subprocess.Popen([dfCmd, "-Pk"],
stdout=subprocess.PIPE).communicate()[0]
except:
raise Exception('Execution of command %s failed.' % dfCmd)
lines = out.splitlines()
if len(lines) > 1:
for line in lines[1:]:
fsstats = {}
cols = line.split()
fsstats['device'] = cols[0]
fsstats['type'] = self._fstypeDict[cols[5]]
fsstats['total'] = 1024 * int(cols[1])
fsstats['inuse'] = 1024 * int(cols[2])
fsstats['avail'] = 1024 * int(cols[3])
fsstats['inuse_pcent'] = int(cols[4][:-1])
stats[cols[5]] = fsstats
return stats |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, host, port):
"""Connects via a RS-485 to Ethernet adapter.""" |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
self._reader = sock.makefile(mode='rb')
self._writer = sock.makefile(mode='wb') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_key(self, key):
"""Sends a key.""" |
_LOGGER.info('Queueing key %s', key)
frame = self._get_key_event_frame(key)
# Queue it to send immediately following the reception
# of a keep-alive packet in an attempt to avoid bus collisions.
self._send_queue.put({'frame': frame}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def states(self):
"""Returns a set containing the enabled states.""" |
state_list = []
for state in States:
if state.value & self._states != 0:
state_list.append(state)
if (self._flashing_states & States.FILTER) != 0:
state_list.append(States.FILTER_LOW_SPEED)
return state_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_state(self, state):
"""Returns True if the specified state is enabled.""" |
# Check to see if we have a change request pending; if we do
# return the value we expect it to change to.
for data in list(self._send_queue.queue):
desired_states = data['desired_states']
for desired_state in desired_states:
if desired_state['state'] == state:
return desired_state['enabled']
if state == States.FILTER_LOW_SPEED:
return (States.FILTER.value & self._flashing_states) != 0
return (state.value & self._states) != 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trace(function, *args, **k) : """Decorates a function by tracing the begining and end of the function execution, if doTrace global is True""" |
if doTrace : print ("> "+function.__name__, args, k)
result = function(*args, **k)
if doTrace : print ("< "+function.__name__, args, k, "->", result)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chol(A):
"""
Calculate the lower triangular matrix of the Cholesky decomposition of
a symmetric, positive-definite matrix.
""" |
A = np.array(A)
assert A.shape[0] == A.shape[1], "Input matrix must be square"
L = [[0.0] * len(A) for _ in range(len(A))]
for i in range(len(A)):
for j in range(i + 1):
s = sum(L[i][k] * L[j][k] for k in range(j))
L[i][j] = (
(A[i][i] - s) ** 0.5 if (i == j) else (1.0 / L[j][j] * (A[i][j] - s))
)
return np.array(L) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get(self, uri, params={}):
'''A generic method to make GET requests to the OpenDNS Investigate API
on the given URI.
'''
return self._session.get(urljoin(Investigate.BASE_URL, uri),
params=params, headers=self._auth_header, proxies=self.proxies
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def post(self, uri, params={}, data={}):
'''A generic method to make POST requests to the OpenDNS Investigate API
on the given URI.
'''
return self._session.post(
urljoin(Investigate.BASE_URL, uri),
params=params, data=data, headers=self._auth_header,
proxies=self.proxies
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def categorization(self, domains, labels=False):
'''Get the domain status and categorization of a domain or list of domains.
'domains' can be either a single domain, or a list of domains.
Setting 'labels' to True will give back categorizations in human-readable
form.
For more detail, see https://investigate.umbrella.com/docs/api#categorization
'''
if type(domains) is str:
return self._get_categorization(domains, labels)
elif type(domains) is list:
return self._post_categorization(domains, labels)
else:
raise Investigate.DOMAIN_ERR |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def cooccurrences(self, domain):
'''Get the cooccurrences of the given domain.
For details, see https://investigate.umbrella.com/docs/api#co-occurrences
'''
uri = self._uris["cooccurrences"].format(domain)
return self.get_parse(uri) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def related(self, domain):
'''Get the related domains of the given domain.
For details, see https://investigate.umbrella.com/docs/api#relatedDomains
'''
uri = self._uris["related"].format(domain)
return self.get_parse(uri) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def security(self, domain):
'''Get the Security Information for the given domain.
For details, see https://investigate.umbrella.com/docs/api#securityInfo
'''
uri = self._uris["security"].format(domain)
return self.get_parse(uri) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def domain_whois(self, domain):
'''Gets whois information for a domain'''
uri = self._uris["whois_domain"].format(domain)
resp_json = self.get_parse(uri)
return resp_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def domain_whois_history(self, domain, limit=None):
'''Gets whois history for a domain'''
params = dict()
if limit is not None:
params['limit'] = limit
uri = self._uris["whois_domain_history"].format(domain)
resp_json = self.get_parse(uri, params)
return resp_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ns_whois(self, nameservers, limit=DEFAULT_LIMIT, offset=DEFAULT_OFFSET, sort_field=DEFAULT_SORT):
'''Gets the domains that have been registered with a nameserver or
nameservers'''
if not isinstance(nameservers, list):
uri = self._uris["whois_ns"].format(nameservers)
params = {'limit': limit, 'offset': offset, 'sortField': sort_field}
else:
uri = self._uris["whois_ns"].format('')
params = {'emailList' : ','.join(nameservers), 'limit': limit, 'offset': offset, 'sortField': sort_field}
resp_json = self.get_parse(uri, params=params)
return resp_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def search(self, pattern, start=None, limit=None, include_category=None):
'''Searches for domains that match a given pattern'''
params = dict()
if start is None:
start = datetime.timedelta(days=30)
if isinstance(start, datetime.timedelta):
params['start'] = int(time.mktime((datetime.datetime.utcnow() - start).timetuple()) * 1000)
elif isinstance(start, datetime.datetime):
params['start'] = int(time.mktime(start.timetuple()) * 1000)
else:
raise Investigate.SEARCH_ERR
if limit is not None and isinstance(limit, int):
params['limit'] = limit
if include_category is not None and isinstance(include_category, bool):
params['includeCategory'] = str(include_category).lower()
uri = self._uris['search'].format(quote_plus(pattern))
return self.get_parse(uri, params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def samples(self, anystring, limit=None, offset=None, sortby=None):
'''Return an object representing the samples identified by the input domain, IP, or URL'''
uri = self._uris['samples'].format(anystring)
params = {'limit': limit, 'offset': offset, 'sortby': sortby}
return self.get_parse(uri, params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sample(self, hash, limit=None, offset=None):
'''Return an object representing the sample identified by the input hash, or an empty object if that sample is not found'''
uri = self._uris['sample'].format(hash)
params = {'limit': limit, 'offset': offset}
return self.get_parse(uri, params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def as_for_ip(self, ip):
'''Gets the AS information for a given IP address.'''
if not Investigate.IP_PATTERN.match(ip):
raise Investigate.IP_ERR
uri = self._uris["as_for_ip"].format(ip)
resp_json = self.get_parse(uri)
return resp_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def prefixes_for_asn(self, asn):
'''Gets the AS information for a given ASN. Return the CIDR and geolocation associated with the AS.'''
uri = self._uris["prefixes_for_asn"].format(asn)
resp_json = self.get_parse(uri)
return resp_json |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acosh(x):
""" Inverse hyperbolic cosine """ |
if isinstance(x, UncertainFunction):
mcpts = np.arccosh(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.arccosh(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def asinh(x):
""" Inverse hyperbolic sine """ |
if isinstance(x, UncertainFunction):
mcpts = np.arcsinh(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.arcsinh(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def atanh(x):
""" Inverse hyperbolic tangent """ |
if isinstance(x, UncertainFunction):
mcpts = np.arctanh(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.arctanh(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def degrees(x):
""" Convert radians to degrees """ |
if isinstance(x, UncertainFunction):
mcpts = np.degrees(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.degrees(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fabs(x):
""" Absolute value function """ |
if isinstance(x, UncertainFunction):
mcpts = np.fabs(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.fabs(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hypot(x, y):
""" Calculate the hypotenuse given two "legs" of a right triangle """ |
if isinstance(x, UncertainFunction) or isinstance(x, UncertainFunction):
ufx = to_uncertain_func(x)
ufy = to_uncertain_func(y)
mcpts = np.hypot(ufx._mcpts, ufy._mcpts)
return UncertainFunction(mcpts)
else:
return np.hypot(x, y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log10(x):
""" Base-10 logarithm """ |
if isinstance(x, UncertainFunction):
mcpts = np.log10(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.log10(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def radians(x):
""" Convert degrees to radians """ |
if isinstance(x, UncertainFunction):
mcpts = np.radians(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.radians(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sqrt(x):
""" Square-root function """ |
if isinstance(x, UncertainFunction):
mcpts = np.sqrt(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.sqrt(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trunc(x):
""" Truncate the values to the integer value without rounding """ |
if isinstance(x, UncertainFunction):
mcpts = np.trunc(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.trunc(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def var(self):
""" Variance value as a result of an uncertainty calculation """ |
mn = self.mean
vr = np.mean((self._mcpts - mn) ** 2)
return vr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_hat(self, path):
# pylint: disable=no-self-use """Loads the hat from a picture at path. Args: path: The path to load from Returns: The hat data. """ |
hat = cv2.imread(path, cv2.IMREAD_UNCHANGED)
if hat is None:
raise ValueError('No hat image found at `{}`'.format(path))
b, g, r, a = cv2.split(hat)
return cv2.merge((r, g, b, a)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_faces(self, image, draw_box=False):
"""Uses a haarcascade to detect faces inside an image. Args: image: The image. draw_box: If True, the image will be marked with a rectangle. Return: The faces as returned by OpenCV's detectMultiScale method for cascades. """ |
frame_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
faces = self.cascade.detectMultiScale(
frame_gray,
scaleFactor=1.3,
minNeighbors=5,
minSize=(50, 50),
flags=0)
if draw_box:
for x, y, w, h in faces:
cv2.rectangle(image, (x, y),
(x + w, y + h), (0, 255, 0), 2)
return faces |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def changed(self, message=None, *args):
"""Marks the object as changed. If a `parent` attribute is set, the `changed()` method on the parent will be called, propagating the change notification up the chain. The message (if provided) will be debug logged. """ |
if message is not None:
self.logger.debug('%s: %s', self._repr(), message % args)
self.logger.debug('%s: changed', self._repr())
if self.parent is not None:
self.parent.changed()
elif isinstance(self, Mutable):
super(TrackedObject, self).changed() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(cls, origin_type):
"""Decorator for mutation tracker registration. The provided `origin_type` is mapped to the decorated class such that future calls to `convert()` will convert the object of `origin_type` to an instance of the decorated class. """ |
def decorator(tracked_type):
"""Adds the decorated class to the `_type_mapping` dictionary."""
cls._type_mapping[origin_type] = tracked_type
return tracked_type
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(cls, obj, parent):
"""Converts objects to registered tracked types This checks the type of the given object against the registered tracked types. When a match is found, the given object will be converted to the tracked type, its parent set to the provided parent, and returned. If its type does not occur in the registered types mapping, the object is returned unchanged. """ |
replacement_type = cls._type_mapping.get(type(obj))
if replacement_type is not None:
new = replacement_type(obj)
new.parent = parent
return new
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_items(self, items):
"""Generator like `convert_iterable`, but for 2-tuple iterators.""" |
return ((key, self.convert(value, self)) for key, value in items) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_mapping(self, mapping):
"""Convenience method to track either a dict or a 2-tuple iterator.""" |
if isinstance(mapping, dict):
return self.convert_items(iteritems(mapping))
return self.convert_items(mapping) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def md2rst(md_lines):
'Only converts headers'
lvl2header_char = {1: '=', 2: '-', 3: '~'}
for md_line in md_lines:
if md_line.startswith('#'):
header_indent, header_text = md_line.split(' ', 1)
yield header_text
header_char = lvl2header_char[len(header_indent)]
yield header_char * len(header_text)
else:
yield md_line |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def aslist(generator):
'Function decorator to transform a generator into a list'
def wrapper(*args, **kwargs):
return list(generator(*args, **kwargs))
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coerce(cls, key, value):
"""Convert plain dictionary to NestedMutable.""" |
if value is None:
return value
if isinstance(value, cls):
return value
if isinstance(value, dict):
return NestedMutableDict.coerce(key, value)
if isinstance(value, list):
return NestedMutableList.coerce(key, value)
return super(cls).coerce(key, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_mod_function(mod, fun):
"""Checks if a function in a module was declared in that module. http://stackoverflow.com/a/1107150/3004221 Args: mod: the module fun: the function """ |
return inspect.isfunction(fun) and inspect.getmodule(fun) == mod |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_mod_class(mod, cls):
"""Checks if a class in a module was declared in that module. Args: mod: the module cls: the class """ |
return inspect.isclass(cls) and inspect.getmodule(cls) == mod |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_functions(mod_name):
"""Lists all functions declared in a module. http://stackoverflow.com/a/1107150/3004221 Args: mod_name: the module name Returns: A list of functions declared in that module. """ |
mod = sys.modules[mod_name]
return [func.__name__ for func in mod.__dict__.values()
if is_mod_function(mod, func)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_classes(mod_name):
"""Lists all classes declared in a module. Args: mod_name: the module name Returns: A list of functions declared in that module. """ |
mod = sys.modules[mod_name]
return [cls.__name__ for cls in mod.__dict__.values()
if is_mod_class(mod, cls)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_linenumbers(functions, module, searchstr='def {}(image):
\n'):
"""Returns a dictionary which maps function names to line numbers. Args: functions: a list of function names module: the module to look the functions up searchstr: the string to search for Returns: A dictionary with functions as keys and their line numbers as values. """ |
lines = inspect.getsourcelines(module)[0]
line_numbers = {}
for function in functions:
try:
line_numbers[function] = lines.index(
searchstr.format(function)) + 1
except ValueError:
print(r'Can not find `{}`'.format(searchstr.format(function)))
line_numbers[function] = 0
return line_numbers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_doc(fun):
"""Formats the documentation in a nicer way and for notebook cells.""" |
SEPARATOR = '============================='
func = cvloop.functions.__dict__[fun]
doc_lines = ['{}'.format(l).strip() for l in func.__doc__.split('\n')]
if hasattr(func, '__init__'):
doc_lines.append(SEPARATOR)
doc_lines += ['{}'.format(l).strip() for l in
func.__init__.__doc__.split('\n')]
mod_lines = []
argblock = False
returnblock = False
for line in doc_lines:
if line == SEPARATOR:
mod_lines.append('\n#### `{}.__init__(...)`:\n\n'.format(fun))
elif 'Args:' in line:
argblock = True
if GENERATE_ARGS:
mod_lines.append('**{}**\n'.format(line))
elif 'Returns:' in line:
returnblock = True
mod_lines.append('\n**{}**'.format(line))
elif not argblock and not returnblock:
mod_lines.append('{}\n'.format(line))
elif argblock and not returnblock and ':' in line:
if GENERATE_ARGS:
mod_lines.append('- *{}:* {}\n'.format(
*line.split(':')))
elif returnblock:
mod_lines.append(line)
else:
mod_lines.append('{}\n'.format(line))
return mod_lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Main function creates the cvloop.functions example notebook.""" |
notebook = {
'cells': [
{
'cell_type': 'markdown',
'metadata': {},
'source': [
'# cvloop functions\n\n',
'This notebook shows an overview over all cvloop ',
'functions provided in the [`cvloop.functions` module](',
'https://github.com/shoeffner/cvloop/blob/',
'develop/cvloop/functions.py).'
]
},
],
'nbformat': 4,
'nbformat_minor': 1,
'metadata': {
'language_info': {
'codemirror_mode': {
'name': 'ipython',
'version': 3
},
'file_extension': '.py',
'mimetype': 'text/x-python',
'name': 'python',
'nbconvert_exporter': 'python',
'pygments_lexer': 'ipython3',
'version': '3.5.1+'
}
}
}
classes = list_classes('cvloop.functions')
functions = list_functions('cvloop.functions')
line_numbers_cls = get_linenumbers(classes, cvloop.functions,
'class {}:\n')
line_numbers = get_linenumbers(functions, cvloop.functions)
for cls in classes:
line_number = line_numbers_cls[cls]
notebook['cells'].append(create_description_cell(cls, line_number))
notebook['cells'].append(create_code_cell(cls, isclass=True))
for func in functions:
line_number = line_numbers[func]
notebook['cells'].append(create_description_cell(func, line_number))
notebook['cells'].append(create_code_cell(func))
with open(sys.argv[1], 'w') as nfile:
json.dump(notebook, nfile, indent=4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_axes(axes, title, size, cmap=None):
"""Prepares an axes object for clean plotting. Removes x and y axes labels and ticks, sets the aspect ratio to be equal, uses the size to determine the drawing area and fills the image with random colors as visual feedback. Creates an AxesImage to be shown inside the axes object and sets the needed properties. Args: axes: The axes object to modify. title: The title. size: The size of the expected image. cmap: The colormap if a custom color map is needed. (Default: None) Returns: The AxesImage's handle. """ |
if axes is None:
return None
# prepare axis itself
axes.set_xlim([0, size[1]])
axes.set_ylim([size[0], 0])
axes.set_aspect('equal')
axes.axis('off')
if isinstance(cmap, str):
title = '{} (cmap: {})'.format(title, cmap)
axes.set_title(title)
# prepare image data
axes_image = image.AxesImage(axes, cmap=cmap,
extent=(0, size[1], size[0], 0))
axes_image.set_data(np.random.random((size[0], size[1], 3)))
axes.add_image(axes_image)
return axes_image |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_event_handlers(self):
"""Connects event handlers to the figure.""" |
self.figure.canvas.mpl_connect('close_event', self.evt_release)
self.figure.canvas.mpl_connect('pause_event', self.evt_toggle_pause) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evt_toggle_pause(self, *args):
# pylint: disable=unused-argument """Pauses and resumes the video source.""" |
if self.event_source._timer is None: # noqa: e501 pylint: disable=protected-access
self.event_source.start()
else:
self.event_source.stop() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_info(self, capture):
"""Prints information about the unprocessed image. Reads one frame from the source to determine image colors, dimensions and data types. Args: capture: the source to read from. """ |
self.frame_offset += 1
ret, frame = capture.read()
if ret:
print('Capture Information')
print('\tDimensions (HxW): {}x{}'.format(*frame.shape[0:2]))
print('\tColor channels: {}'.format(frame.shape[2] if
len(frame.shape) > 2 else 1))
print('\tColor range: {}-{}'.format(np.min(frame),
np.max(frame)))
print('\tdtype: {}'.format(frame.dtype))
else:
print('No source found.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def determine_size(self, capture):
"""Determines the height and width of the image source. If no dimensions are available, this method defaults to a resolution of 640x480, thus returns (480, 640). If capture has a get method it is assumed to understand `cv2.CAP_PROP_FRAME_WIDTH` and `cv2.CAP_PROP_FRAME_HEIGHT` to get the information. Otherwise it reads one frame from the source to determine image dimensions. Args: capture: the source to read from. Returns: A tuple containing integers of height and width (simple casts). """ |
width = 640
height = 480
if capture and hasattr(capture, 'get'):
width = capture.get(cv2.CAP_PROP_FRAME_WIDTH)
height = capture.get(cv2.CAP_PROP_FRAME_HEIGHT)
else:
self.frame_offset += 1
ret, frame = capture.read()
if ret:
width = frame.shape[1]
height = frame.shape[0]
return (int(height), int(width)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_draw(self):
"""Initializes the drawing of the frames by setting the images to random colors. This function is called by TimedAnimation. """ |
if self.original is not None:
self.original.set_data(np.random.random((10, 10, 3)))
self.processed.set_data(np.random.random((10, 10, 3))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_frame(self):
"""Reads a frame and converts the color if needed. In case no frame is available, i.e. self.capture.read() returns False as the first return value, the event_source of the TimedAnimation is stopped, and if possible the capture source released. Returns: None if stopped, otherwise the color converted source image. """ |
ret, frame = self.capture.read()
if not ret:
self.event_source.stop()
try:
self.capture.release()
except AttributeError:
# has no release method, thus just pass
pass
return None
if self.convert_color != -1 and is_color_image(frame):
return cv2.cvtColor(frame, self.convert_color)
return frame |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.