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 analyz... |
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... |
<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'... |
<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.... |
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. @para... |
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(datn... |
<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(m... |
<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... |
<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 = 'ot... |
<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 Statu... |
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 =... |
<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 la... |
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, updat... |
<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 rec... |
# 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 + ... |
<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 ... |
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 ---... |
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.d... |
<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 si... |
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 Paramet... |
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):
featu... |
<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:
ra... |
<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 Comma... |
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 = ... |
<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("Authenticatio... |
<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:
... |
<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... |
<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)
... |
<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 Na... |
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+\((.+)\)$',
... |
<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 cha... |
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... |
<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... |
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.split... |
<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 counte... |
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,
... |
<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... |
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"
... |
<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.*\... |
<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',)
... |
<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 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:
... |
<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'] == ... |
<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... |
<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,
... |
<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 de... |
<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 res... |
<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)
p... |
<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... |
<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_par... |
<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, pa... |
<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 ... |
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.... |
<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, prop... |
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 call... |
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. Whe... |
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)]
... |
<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... |
<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 ... |
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 ... |
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... |
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)))
... |
<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.__... |
<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 [`c... |
<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... |
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
... |
<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 ... |
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(... |
<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 o... |
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:
... |
<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 retur... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.