body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
2acb15398f8b1bd3305034733a67f059d741c841d9050ac68087fbe7720dcde9
def get_dataset_labels(self, dataset_obj): u'\n Use creator-*, admin-* labels for proposed datasets\n ' if dataset_obj.notes.startswith(u'Proposed:'): labels = [(u'creator-%s' % dataset_obj.creator_user_id)] if dataset_obj.owner_org: return (labels + [(u'admin-%s' % dataset_obj.owner_org)]) return labels return super(ExampleIPermissionLabelsPlugin, self).get_dataset_labels(dataset_obj)
Use creator-*, admin-* labels for proposed datasets
ckanext/example_ipermissionlabels/plugin.py
get_dataset_labels
larrycameron80/ckan
2,805
python
def get_dataset_labels(self, dataset_obj): u'\n \n ' if dataset_obj.notes.startswith(u'Proposed:'): labels = [(u'creator-%s' % dataset_obj.creator_user_id)] if dataset_obj.owner_org: return (labels + [(u'admin-%s' % dataset_obj.owner_org)]) return labels return super(ExampleIPermissionLabelsPlugin, self).get_dataset_labels(dataset_obj)
def get_dataset_labels(self, dataset_obj): u'\n \n ' if dataset_obj.notes.startswith(u'Proposed:'): labels = [(u'creator-%s' % dataset_obj.creator_user_id)] if dataset_obj.owner_org: return (labels + [(u'admin-%s' % dataset_obj.owner_org)]) return labels return super(ExampleIPermissionLabelsPlugin, self).get_dataset_labels(dataset_obj)<|docstring|>Use creator-*, admin-* labels for proposed datasets<|endoftext|>
aa4801b10b7a333c99dbe711ba67663255ed7cd5c697d2a4aacf3c50c8750f60
def get_user_dataset_labels(self, user_obj): u'\n Include admin-* labels for users in addition to default labels\n creator-*, member-* and public\n ' labels = super(ExampleIPermissionLabelsPlugin, self).get_user_dataset_labels(user_obj) if user_obj: orgs = get_action(u'organization_list_for_user')({u'user': user_obj.id}, {u'permission': u'admin'}) labels.extend(((u'admin-%s' % o['id']) for o in orgs)) return labels
Include admin-* labels for users in addition to default labels creator-*, member-* and public
ckanext/example_ipermissionlabels/plugin.py
get_user_dataset_labels
larrycameron80/ckan
2,805
python
def get_user_dataset_labels(self, user_obj): u'\n Include admin-* labels for users in addition to default labels\n creator-*, member-* and public\n ' labels = super(ExampleIPermissionLabelsPlugin, self).get_user_dataset_labels(user_obj) if user_obj: orgs = get_action(u'organization_list_for_user')({u'user': user_obj.id}, {u'permission': u'admin'}) labels.extend(((u'admin-%s' % o['id']) for o in orgs)) return labels
def get_user_dataset_labels(self, user_obj): u'\n Include admin-* labels for users in addition to default labels\n creator-*, member-* and public\n ' labels = super(ExampleIPermissionLabelsPlugin, self).get_user_dataset_labels(user_obj) if user_obj: orgs = get_action(u'organization_list_for_user')({u'user': user_obj.id}, {u'permission': u'admin'}) labels.extend(((u'admin-%s' % o['id']) for o in orgs)) return labels<|docstring|>Include admin-* labels for users in addition to default labels creator-*, member-* and public<|endoftext|>
8a8c107df9f01c4460765658bb45ae20aed4d1e20028860f51b1f292f7f54286
def _test_array_like_same(self, like_func, array): '\n Tests of *_array_like where shape, strides, dtype, and flags should\n all be equal.\n ' array_like = like_func(array) self.assertEqual(array.shape, array_like.shape) self.assertEqual(array.strides, array_like.strides) self.assertEqual(array.dtype, array_like.dtype) self.assertEqual(array.flags['C_CONTIGUOUS'], array_like.flags['C_CONTIGUOUS']) self.assertEqual(array.flags['F_CONTIGUOUS'], array_like.flags['F_CONTIGUOUS'])
Tests of *_array_like where shape, strides, dtype, and flags should all be equal.
numba/cuda/tests/cudapy/test_array.py
_test_array_like_same
castarco/numba
6,620
python
def _test_array_like_same(self, like_func, array): '\n Tests of *_array_like where shape, strides, dtype, and flags should\n all be equal.\n ' array_like = like_func(array) self.assertEqual(array.shape, array_like.shape) self.assertEqual(array.strides, array_like.strides) self.assertEqual(array.dtype, array_like.dtype) self.assertEqual(array.flags['C_CONTIGUOUS'], array_like.flags['C_CONTIGUOUS']) self.assertEqual(array.flags['F_CONTIGUOUS'], array_like.flags['F_CONTIGUOUS'])
def _test_array_like_same(self, like_func, array): '\n Tests of *_array_like where shape, strides, dtype, and flags should\n all be equal.\n ' array_like = like_func(array) self.assertEqual(array.shape, array_like.shape) self.assertEqual(array.strides, array_like.strides) self.assertEqual(array.dtype, array_like.dtype) self.assertEqual(array.flags['C_CONTIGUOUS'], array_like.flags['C_CONTIGUOUS']) self.assertEqual(array.flags['F_CONTIGUOUS'], array_like.flags['F_CONTIGUOUS'])<|docstring|>Tests of *_array_like where shape, strides, dtype, and flags should all be equal.<|endoftext|>
6e47cb77af3de8e78b7f29ac5352064b8cddae935d042f2a1d92488c665a78a0
def _test_array_like_view(self, like_func, view, d_view): '\n Tests of device_array_like where the original array is a view - the\n strides should not be equal because a contiguous array is expected.\n ' nb_like = like_func(d_view) self.assertEqual(d_view.shape, nb_like.shape) self.assertEqual(d_view.dtype, nb_like.dtype) np_like = np.zeros_like(view) self.assertEqual(nb_like.strides, np_like.strides) self.assertEqual(nb_like.flags['C_CONTIGUOUS'], np_like.flags['C_CONTIGUOUS']) self.assertEqual(nb_like.flags['F_CONTIGUOUS'], np_like.flags['F_CONTIGUOUS'])
Tests of device_array_like where the original array is a view - the strides should not be equal because a contiguous array is expected.
numba/cuda/tests/cudapy/test_array.py
_test_array_like_view
castarco/numba
6,620
python
def _test_array_like_view(self, like_func, view, d_view): '\n Tests of device_array_like where the original array is a view - the\n strides should not be equal because a contiguous array is expected.\n ' nb_like = like_func(d_view) self.assertEqual(d_view.shape, nb_like.shape) self.assertEqual(d_view.dtype, nb_like.dtype) np_like = np.zeros_like(view) self.assertEqual(nb_like.strides, np_like.strides) self.assertEqual(nb_like.flags['C_CONTIGUOUS'], np_like.flags['C_CONTIGUOUS']) self.assertEqual(nb_like.flags['F_CONTIGUOUS'], np_like.flags['F_CONTIGUOUS'])
def _test_array_like_view(self, like_func, view, d_view): '\n Tests of device_array_like where the original array is a view - the\n strides should not be equal because a contiguous array is expected.\n ' nb_like = like_func(d_view) self.assertEqual(d_view.shape, nb_like.shape) self.assertEqual(d_view.dtype, nb_like.dtype) np_like = np.zeros_like(view) self.assertEqual(nb_like.strides, np_like.strides) self.assertEqual(nb_like.flags['C_CONTIGUOUS'], np_like.flags['C_CONTIGUOUS']) self.assertEqual(nb_like.flags['F_CONTIGUOUS'], np_like.flags['F_CONTIGUOUS'])<|docstring|>Tests of device_array_like where the original array is a view - the strides should not be equal because a contiguous array is expected.<|endoftext|>
3722d300d16e64ecf373aa2a84436c91f13b7abf10e368a973ed17a7944732bc
@staticmethod def connectionDB(fileDB): '\n Create a database connection to the SQLite database specified by fileDB\n\n :param fileDB: Database SQLite file\n :type fileDB: str\n :return: Connection object and cursor object or None\n ' try: dbName = (fileDB + '.db') connection = sqlite3.connect(dbName) cursor = connection.cursor() print('Connection successful to', dbName) return (connection, cursor) except sqlite3.Error as e: print('Error to connection:', e) return None
Create a database connection to the SQLite database specified by fileDB :param fileDB: Database SQLite file :type fileDB: str :return: Connection object and cursor object or None
src/final/Data.py
connectionDB
lrodrin/TFG
2
python
@staticmethod def connectionDB(fileDB): '\n Create a database connection to the SQLite database specified by fileDB\n\n :param fileDB: Database SQLite file\n :type fileDB: str\n :return: Connection object and cursor object or None\n ' try: dbName = (fileDB + '.db') connection = sqlite3.connect(dbName) cursor = connection.cursor() print('Connection successful to', dbName) return (connection, cursor) except sqlite3.Error as e: print('Error to connection:', e) return None
@staticmethod def connectionDB(fileDB): '\n Create a database connection to the SQLite database specified by fileDB\n\n :param fileDB: Database SQLite file\n :type fileDB: str\n :return: Connection object and cursor object or None\n ' try: dbName = (fileDB + '.db') connection = sqlite3.connect(dbName) cursor = connection.cursor() print('Connection successful to', dbName) return (connection, cursor) except sqlite3.Error as e: print('Error to connection:', e) return None<|docstring|>Create a database connection to the SQLite database specified by fileDB :param fileDB: Database SQLite file :type fileDB: str :return: Connection object and cursor object or None<|endoftext|>
261b6dc20015e9335bd8ecf8b739db98f35e5fb5a7ff94a5e7855bbf33f6a6eb
@staticmethod def openFile(dataFile): '\n Open data file specified by dataFile\n\n :param dataFile: Data file\n :type dataFile: str\n :return: File object or None\n :rtype: file\n ' try: file = open(dataFile, 'r') print(('File %s opened' % dataFile)) return file except IOError as e: print('Error to open file:', e) return None
Open data file specified by dataFile :param dataFile: Data file :type dataFile: str :return: File object or None :rtype: file
src/final/Data.py
openFile
lrodrin/TFG
2
python
@staticmethod def openFile(dataFile): '\n Open data file specified by dataFile\n\n :param dataFile: Data file\n :type dataFile: str\n :return: File object or None\n :rtype: file\n ' try: file = open(dataFile, 'r') print(('File %s opened' % dataFile)) return file except IOError as e: print('Error to open file:', e) return None
@staticmethod def openFile(dataFile): '\n Open data file specified by dataFile\n\n :param dataFile: Data file\n :type dataFile: str\n :return: File object or None\n :rtype: file\n ' try: file = open(dataFile, 'r') print(('File %s opened' % dataFile)) return file except IOError as e: print('Error to open file:', e) return None<|docstring|>Open data file specified by dataFile :param dataFile: Data file :type dataFile: str :return: File object or None :rtype: file<|endoftext|>
5aae7f6b1d2c5da9e148158944225631143edd7c2724fdc5ddc0d8bdaa8c3028
@staticmethod def getDataFile(dataFile, fileType): '\n Get data from data file specified by dataFile\n\n :param dataFile: Data file\n :param fileType: File type\n :type dataFile: file\n :type fileType: str\n :return: Column names and lines from dataFile\n ' columnNames = str() lines = dataFile.readlines() if (fileType == 'TXT'): header = lines[0].replace('\n', '') for word in header.split(' '): columnNames += (word + ', ') elif (fileType == 'ARFF'): for line in lines: if line.startswith('@attribute'): columnNames += (line.split(' ')[1] + ', ') return (columnNames, lines)
Get data from data file specified by dataFile :param dataFile: Data file :param fileType: File type :type dataFile: file :type fileType: str :return: Column names and lines from dataFile
src/final/Data.py
getDataFile
lrodrin/TFG
2
python
@staticmethod def getDataFile(dataFile, fileType): '\n Get data from data file specified by dataFile\n\n :param dataFile: Data file\n :param fileType: File type\n :type dataFile: file\n :type fileType: str\n :return: Column names and lines from dataFile\n ' columnNames = str() lines = dataFile.readlines() if (fileType == 'TXT'): header = lines[0].replace('\n', ) for word in header.split(' '): columnNames += (word + ', ') elif (fileType == 'ARFF'): for line in lines: if line.startswith('@attribute'): columnNames += (line.split(' ')[1] + ', ') return (columnNames, lines)
@staticmethod def getDataFile(dataFile, fileType): '\n Get data from data file specified by dataFile\n\n :param dataFile: Data file\n :param fileType: File type\n :type dataFile: file\n :type fileType: str\n :return: Column names and lines from dataFile\n ' columnNames = str() lines = dataFile.readlines() if (fileType == 'TXT'): header = lines[0].replace('\n', ) for word in header.split(' '): columnNames += (word + ', ') elif (fileType == 'ARFF'): for line in lines: if line.startswith('@attribute'): columnNames += (line.split(' ')[1] + ', ') return (columnNames, lines)<|docstring|>Get data from data file specified by dataFile :param dataFile: Data file :param fileType: File type :type dataFile: file :type fileType: str :return: Column names and lines from dataFile<|endoftext|>
2932c305549949e265a52ee82f975acc4fcd5abfdce1c335ea073167c6113b73
@staticmethod def createTable(cursor, tableName, columnNames): '\n Create a table specified by tableName in a SQLite database\n\n :param cursor: Connection cursor\n :param tableName: Table name\n :param columnNames: Column names\n :type tableName: str\n :type columnNames: str\n ' try: query = 'CREATE TABLE {0} ({1});'.format(str(tableName), str(columnNames[0:(- 2)])) cursor.execute(query) except sqlite3.Error as e: print('Error to create table:', e)
Create a table specified by tableName in a SQLite database :param cursor: Connection cursor :param tableName: Table name :param columnNames: Column names :type tableName: str :type columnNames: str
src/final/Data.py
createTable
lrodrin/TFG
2
python
@staticmethod def createTable(cursor, tableName, columnNames): '\n Create a table specified by tableName in a SQLite database\n\n :param cursor: Connection cursor\n :param tableName: Table name\n :param columnNames: Column names\n :type tableName: str\n :type columnNames: str\n ' try: query = 'CREATE TABLE {0} ({1});'.format(str(tableName), str(columnNames[0:(- 2)])) cursor.execute(query) except sqlite3.Error as e: print('Error to create table:', e)
@staticmethod def createTable(cursor, tableName, columnNames): '\n Create a table specified by tableName in a SQLite database\n\n :param cursor: Connection cursor\n :param tableName: Table name\n :param columnNames: Column names\n :type tableName: str\n :type columnNames: str\n ' try: query = 'CREATE TABLE {0} ({1});'.format(str(tableName), str(columnNames[0:(- 2)])) cursor.execute(query) except sqlite3.Error as e: print('Error to create table:', e)<|docstring|>Create a table specified by tableName in a SQLite database :param cursor: Connection cursor :param tableName: Table name :param columnNames: Column names :type tableName: str :type columnNames: str<|endoftext|>
c4925c6932113f63bc0bbbb38ac5f2b5c89c00e91e9e5ff5d884523043e00da5
@staticmethod def insertDataTXT(tableName, columnNames, lines, cursor, connection): '\n Insert values to a table specified by tableName in a SQLite database from a TXT file\n\n :param tableName: Table name\n :param columnNames: Column names\n :param lines: Lines from a data file\n :param cursor: Cursor object\n :param connection: Connection object\n :type tableName: str\n :type columnNames: str\n ' values = str() for line in range(1, len(lines)): for column in lines[line].split(' '): if (':' in column): values += ("'%s'," % column.split(':')[1]) elif ('=' in column): values += ("'%s'," % column.split('=')[1]) else: values += ("'%s'," % column) try: query = 'INSERT INTO {0} ({1}) VALUES ({2});'.format(str(tableName), str(columnNames[0:(- 2)]), str(values[0:(- 1)]).replace('\n', '')) cursor.execute(query) connection.commit() values = str() except sqlite3.Error as e: print('Error to insert in txt file:', e)
Insert values to a table specified by tableName in a SQLite database from a TXT file :param tableName: Table name :param columnNames: Column names :param lines: Lines from a data file :param cursor: Cursor object :param connection: Connection object :type tableName: str :type columnNames: str
src/final/Data.py
insertDataTXT
lrodrin/TFG
2
python
@staticmethod def insertDataTXT(tableName, columnNames, lines, cursor, connection): '\n Insert values to a table specified by tableName in a SQLite database from a TXT file\n\n :param tableName: Table name\n :param columnNames: Column names\n :param lines: Lines from a data file\n :param cursor: Cursor object\n :param connection: Connection object\n :type tableName: str\n :type columnNames: str\n ' values = str() for line in range(1, len(lines)): for column in lines[line].split(' '): if (':' in column): values += ("'%s'," % column.split(':')[1]) elif ('=' in column): values += ("'%s'," % column.split('=')[1]) else: values += ("'%s'," % column) try: query = 'INSERT INTO {0} ({1}) VALUES ({2});'.format(str(tableName), str(columnNames[0:(- 2)]), str(values[0:(- 1)]).replace('\n', )) cursor.execute(query) connection.commit() values = str() except sqlite3.Error as e: print('Error to insert in txt file:', e)
@staticmethod def insertDataTXT(tableName, columnNames, lines, cursor, connection): '\n Insert values to a table specified by tableName in a SQLite database from a TXT file\n\n :param tableName: Table name\n :param columnNames: Column names\n :param lines: Lines from a data file\n :param cursor: Cursor object\n :param connection: Connection object\n :type tableName: str\n :type columnNames: str\n ' values = str() for line in range(1, len(lines)): for column in lines[line].split(' '): if (':' in column): values += ("'%s'," % column.split(':')[1]) elif ('=' in column): values += ("'%s'," % column.split('=')[1]) else: values += ("'%s'," % column) try: query = 'INSERT INTO {0} ({1}) VALUES ({2});'.format(str(tableName), str(columnNames[0:(- 2)]), str(values[0:(- 1)]).replace('\n', )) cursor.execute(query) connection.commit() values = str() except sqlite3.Error as e: print('Error to insert in txt file:', e)<|docstring|>Insert values to a table specified by tableName in a SQLite database from a TXT file :param tableName: Table name :param columnNames: Column names :param lines: Lines from a data file :param cursor: Cursor object :param connection: Connection object :type tableName: str :type columnNames: str<|endoftext|>
6fd31fa8a32ad178b5fc1f3e814e914efa91d8a8e7216b43bb5c5feade0f7137
@staticmethod def insertDataARFF(tableName, columnNames, lines, cursor, connection): '\n Insert values to a table specified by tableName in SQLite database from an ARFF file\n\n :param tableName: Table name\n :param columnNames: Column names\n :param lines: Lines from a data file\n :param cursor: Cursor object\n :param connection: Connection object\n :type tableName: str\n :type columnNames: str\n ' values = str() for line in lines: if (len(line) != 0): if ((not line.startswith('@')) and (not line.startswith('\n')) and (not line.startswith('%'))): for word in line.split(','): word = "'{0}'".format(word.replace('\n', '')) values += (word + ',') try: query = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(str(tableName), str(columnNames[0:(- 2)]), str(values[0:(- 1)]).replace('\n', '')) cursor.execute(query) connection.commit() values = str() except sqlite3.Error as e: print('Error to insert in arff file:', e)
Insert values to a table specified by tableName in SQLite database from an ARFF file :param tableName: Table name :param columnNames: Column names :param lines: Lines from a data file :param cursor: Cursor object :param connection: Connection object :type tableName: str :type columnNames: str
src/final/Data.py
insertDataARFF
lrodrin/TFG
2
python
@staticmethod def insertDataARFF(tableName, columnNames, lines, cursor, connection): '\n Insert values to a table specified by tableName in SQLite database from an ARFF file\n\n :param tableName: Table name\n :param columnNames: Column names\n :param lines: Lines from a data file\n :param cursor: Cursor object\n :param connection: Connection object\n :type tableName: str\n :type columnNames: str\n ' values = str() for line in lines: if (len(line) != 0): if ((not line.startswith('@')) and (not line.startswith('\n')) and (not line.startswith('%'))): for word in line.split(','): word = "'{0}'".format(word.replace('\n', )) values += (word + ',') try: query = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(str(tableName), str(columnNames[0:(- 2)]), str(values[0:(- 1)]).replace('\n', )) cursor.execute(query) connection.commit() values = str() except sqlite3.Error as e: print('Error to insert in arff file:', e)
@staticmethod def insertDataARFF(tableName, columnNames, lines, cursor, connection): '\n Insert values to a table specified by tableName in SQLite database from an ARFF file\n\n :param tableName: Table name\n :param columnNames: Column names\n :param lines: Lines from a data file\n :param cursor: Cursor object\n :param connection: Connection object\n :type tableName: str\n :type columnNames: str\n ' values = str() for line in lines: if (len(line) != 0): if ((not line.startswith('@')) and (not line.startswith('\n')) and (not line.startswith('%'))): for word in line.split(','): word = "'{0}'".format(word.replace('\n', )) values += (word + ',') try: query = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(str(tableName), str(columnNames[0:(- 2)]), str(values[0:(- 1)]).replace('\n', )) cursor.execute(query) connection.commit() values = str() except sqlite3.Error as e: print('Error to insert in arff file:', e)<|docstring|>Insert values to a table specified by tableName in SQLite database from an ARFF file :param tableName: Table name :param columnNames: Column names :param lines: Lines from a data file :param cursor: Cursor object :param connection: Connection object :type tableName: str :type columnNames: str<|endoftext|>
1241e5b11bceb7f33139b8d1838c19b67353ae4cbe596086b1748b2cc69a2473
@staticmethod def selectData(tableName, cursor): '\n Select all the rows from a table specified by tableName\n\n :param tableName: Table name\n :param cursor: Cursor object\n :type tableName: str\n :return: Column names and all rows from tableName or None\n ' try: query = 'SELECT * FROM {0};'.format(str(tableName)) cursor.execute(query) columnNames = [description[0] for description in cursor.description] rows = cursor.fetchall() return (columnNames, rows) except sqlite3.Error as e: print(('Error to select in table name %s: %s' % (tableName, e))) return None
Select all the rows from a table specified by tableName :param tableName: Table name :param cursor: Cursor object :type tableName: str :return: Column names and all rows from tableName or None
src/final/Data.py
selectData
lrodrin/TFG
2
python
@staticmethod def selectData(tableName, cursor): '\n Select all the rows from a table specified by tableName\n\n :param tableName: Table name\n :param cursor: Cursor object\n :type tableName: str\n :return: Column names and all rows from tableName or None\n ' try: query = 'SELECT * FROM {0};'.format(str(tableName)) cursor.execute(query) columnNames = [description[0] for description in cursor.description] rows = cursor.fetchall() return (columnNames, rows) except sqlite3.Error as e: print(('Error to select in table name %s: %s' % (tableName, e))) return None
@staticmethod def selectData(tableName, cursor): '\n Select all the rows from a table specified by tableName\n\n :param tableName: Table name\n :param cursor: Cursor object\n :type tableName: str\n :return: Column names and all rows from tableName or None\n ' try: query = 'SELECT * FROM {0};'.format(str(tableName)) cursor.execute(query) columnNames = [description[0] for description in cursor.description] rows = cursor.fetchall() return (columnNames, rows) except sqlite3.Error as e: print(('Error to select in table name %s: %s' % (tableName, e))) return None<|docstring|>Select all the rows from a table specified by tableName :param tableName: Table name :param cursor: Cursor object :type tableName: str :return: Column names and all rows from tableName or None<|endoftext|>
1808583751df7de08512003f55c3bf8fcadfbea19cefa6664dd3f6cc2c60ac41
@staticmethod def getTableNamesDB(cursor): '\n Return a list of all the table names from a SQLite database\n \n :param cursor: Cursor object\n :return: List of table names\n :rtype: list\n ' tablesNameList = list() query = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY Name" cursor.execute(query) tables = map((lambda t: t[0]), cursor.fetchall()) for table in tables: tablesNameList.append(table) return tablesNameList
Return a list of all the table names from a SQLite database :param cursor: Cursor object :return: List of table names :rtype: list
src/final/Data.py
getTableNamesDB
lrodrin/TFG
2
python
@staticmethod def getTableNamesDB(cursor): '\n Return a list of all the table names from a SQLite database\n \n :param cursor: Cursor object\n :return: List of table names\n :rtype: list\n ' tablesNameList = list() query = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY Name" cursor.execute(query) tables = map((lambda t: t[0]), cursor.fetchall()) for table in tables: tablesNameList.append(table) return tablesNameList
@staticmethod def getTableNamesDB(cursor): '\n Return a list of all the table names from a SQLite database\n \n :param cursor: Cursor object\n :return: List of table names\n :rtype: list\n ' tablesNameList = list() query = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY Name" cursor.execute(query) tables = map((lambda t: t[0]), cursor.fetchall()) for table in tables: tablesNameList.append(table) return tablesNameList<|docstring|>Return a list of all the table names from a SQLite database :param cursor: Cursor object :return: List of table names :rtype: list<|endoftext|>
09fcfd6532d81f9e80f15568a62fb60863f895b933184aef94f4e60f22e9d52b
@staticmethod def convertDataToSet(dataFile): '\n Convert lines from data file specified by dataFile to sets\n\n :param dataFile: Data file\n :type dataFile: file\n :return: List of all the lines converted to sets\n :rtype: list\n ' subset = set() moreFrequentSubsets = list() for line in dataFile.readlines(): for word in line.split(' '): if (not word.startswith('(')): subset.add(word) moreFrequentSubsets.append(frozenset(subset)) subset = set() return moreFrequentSubsets
Convert lines from data file specified by dataFile to sets :param dataFile: Data file :type dataFile: file :return: List of all the lines converted to sets :rtype: list
src/final/Data.py
convertDataToSet
lrodrin/TFG
2
python
@staticmethod def convertDataToSet(dataFile): '\n Convert lines from data file specified by dataFile to sets\n\n :param dataFile: Data file\n :type dataFile: file\n :return: List of all the lines converted to sets\n :rtype: list\n ' subset = set() moreFrequentSubsets = list() for line in dataFile.readlines(): for word in line.split(' '): if (not word.startswith('(')): subset.add(word) moreFrequentSubsets.append(frozenset(subset)) subset = set() return moreFrequentSubsets
@staticmethod def convertDataToSet(dataFile): '\n Convert lines from data file specified by dataFile to sets\n\n :param dataFile: Data file\n :type dataFile: file\n :return: List of all the lines converted to sets\n :rtype: list\n ' subset = set() moreFrequentSubsets = list() for line in dataFile.readlines(): for word in line.split(' '): if (not word.startswith('(')): subset.add(word) moreFrequentSubsets.append(frozenset(subset)) subset = set() return moreFrequentSubsets<|docstring|>Convert lines from data file specified by dataFile to sets :param dataFile: Data file :type dataFile: file :return: List of all the lines converted to sets :rtype: list<|endoftext|>
c2aebeff4815415fb076a63a2e173877c66e19b8171169e481afd81d0ea8f655
def test_fix_stim(): 'Test fixing stim STI016 for Neuromag.' raw = read_raw_fif(raw_fname, preload=True) raw._data[(raw.ch_names.index('STI 014'), :3)] = [0, (- 32765), 0] with pytest.warns(RuntimeWarning, match='STI016'): events = find_events(raw, 'STI 014') assert_array_equal(events[0], [(raw.first_samp + 1), 0, 32765]) events = find_events(raw, 'STI 014', uint_cast=True) assert_array_equal(events[0], [(raw.first_samp + 1), 0, 32771])
Test fixing stim STI016 for Neuromag.
mne/tests/test_event.py
test_fix_stim
hofaflo/mne-python
1,953
python
def test_fix_stim(): raw = read_raw_fif(raw_fname, preload=True) raw._data[(raw.ch_names.index('STI 014'), :3)] = [0, (- 32765), 0] with pytest.warns(RuntimeWarning, match='STI016'): events = find_events(raw, 'STI 014') assert_array_equal(events[0], [(raw.first_samp + 1), 0, 32765]) events = find_events(raw, 'STI 014', uint_cast=True) assert_array_equal(events[0], [(raw.first_samp + 1), 0, 32771])
def test_fix_stim(): raw = read_raw_fif(raw_fname, preload=True) raw._data[(raw.ch_names.index('STI 014'), :3)] = [0, (- 32765), 0] with pytest.warns(RuntimeWarning, match='STI016'): events = find_events(raw, 'STI 014') assert_array_equal(events[0], [(raw.first_samp + 1), 0, 32765]) events = find_events(raw, 'STI 014', uint_cast=True) assert_array_equal(events[0], [(raw.first_samp + 1), 0, 32771])<|docstring|>Test fixing stim STI016 for Neuromag.<|endoftext|>
581fad2ab8327776459c51c6b967f05d928dc073887d12ca63f7add30afb827f
def test_add_events(): 'Test adding events to a Raw file.' raw = read_raw_fif(raw_fname) events = np.array([[raw.first_samp, 0, 1]]) pytest.raises(RuntimeError, raw.add_events, events, 'STI 014') raw = read_raw_fif(raw_fname, preload=True) orig_events = find_events(raw, 'STI 014') events = np.array([raw.first_samp, 0, 1]) pytest.raises(ValueError, raw.add_events, events, 'STI 014') events[0] = ((raw.first_samp + raw.n_times) + 1) events = events[(np.newaxis, :)] pytest.raises(ValueError, raw.add_events, events, 'STI 014') events[(0, 0)] = (raw.first_samp - 1) pytest.raises(ValueError, raw.add_events, events, 'STI 014') events[(0, 0)] = (raw.first_samp + 1) pytest.raises(ValueError, raw.add_events, events, 'STI FOO') raw.add_events(events, 'STI 014') new_events = find_events(raw, 'STI 014') assert_array_equal(new_events, np.concatenate((events, orig_events))) raw.add_events(events, 'STI 014', replace=True) new_events = find_events(raw, 'STI 014') assert_array_equal(new_events, events)
Test adding events to a Raw file.
mne/tests/test_event.py
test_add_events
hofaflo/mne-python
1,953
python
def test_add_events(): raw = read_raw_fif(raw_fname) events = np.array([[raw.first_samp, 0, 1]]) pytest.raises(RuntimeError, raw.add_events, events, 'STI 014') raw = read_raw_fif(raw_fname, preload=True) orig_events = find_events(raw, 'STI 014') events = np.array([raw.first_samp, 0, 1]) pytest.raises(ValueError, raw.add_events, events, 'STI 014') events[0] = ((raw.first_samp + raw.n_times) + 1) events = events[(np.newaxis, :)] pytest.raises(ValueError, raw.add_events, events, 'STI 014') events[(0, 0)] = (raw.first_samp - 1) pytest.raises(ValueError, raw.add_events, events, 'STI 014') events[(0, 0)] = (raw.first_samp + 1) pytest.raises(ValueError, raw.add_events, events, 'STI FOO') raw.add_events(events, 'STI 014') new_events = find_events(raw, 'STI 014') assert_array_equal(new_events, np.concatenate((events, orig_events))) raw.add_events(events, 'STI 014', replace=True) new_events = find_events(raw, 'STI 014') assert_array_equal(new_events, events)
def test_add_events(): raw = read_raw_fif(raw_fname) events = np.array([[raw.first_samp, 0, 1]]) pytest.raises(RuntimeError, raw.add_events, events, 'STI 014') raw = read_raw_fif(raw_fname, preload=True) orig_events = find_events(raw, 'STI 014') events = np.array([raw.first_samp, 0, 1]) pytest.raises(ValueError, raw.add_events, events, 'STI 014') events[0] = ((raw.first_samp + raw.n_times) + 1) events = events[(np.newaxis, :)] pytest.raises(ValueError, raw.add_events, events, 'STI 014') events[(0, 0)] = (raw.first_samp - 1) pytest.raises(ValueError, raw.add_events, events, 'STI 014') events[(0, 0)] = (raw.first_samp + 1) pytest.raises(ValueError, raw.add_events, events, 'STI FOO') raw.add_events(events, 'STI 014') new_events = find_events(raw, 'STI 014') assert_array_equal(new_events, np.concatenate((events, orig_events))) raw.add_events(events, 'STI 014', replace=True) new_events = find_events(raw, 'STI 014') assert_array_equal(new_events, events)<|docstring|>Test adding events to a Raw file.<|endoftext|>
b6d1a59ab183296154edd2d88d681cdbec9a6f2a896069e1c4dd2be002e5f189
def test_merge_events(): 'Test event merging.' events_orig = [[1, 0, 1], [3, 0, 2], [10, 0, 3], [20, 0, 4]] events_replacement = [[1, 0, 12], [3, 0, 12], [10, 0, 34], [20, 0, 34]] events_no_replacement = [[1, 0, 1], [1, 0, 12], [1, 0, 1234], [3, 0, 2], [3, 0, 12], [3, 0, 1234], [10, 0, 3], [10, 0, 34], [10, 0, 1234], [20, 0, 4], [20, 0, 34], [20, 0, 1234]] for (replace_events, events_good) in [(True, events_replacement), (False, events_no_replacement)]: events = merge_events(events_orig, [1, 2], 12, replace_events) events = merge_events(events, [3, 4], 34, replace_events) events = merge_events(events, [1, 2, 3, 4], 1234, replace_events) assert_array_equal(events, events_good)
Test event merging.
mne/tests/test_event.py
test_merge_events
hofaflo/mne-python
1,953
python
def test_merge_events(): events_orig = [[1, 0, 1], [3, 0, 2], [10, 0, 3], [20, 0, 4]] events_replacement = [[1, 0, 12], [3, 0, 12], [10, 0, 34], [20, 0, 34]] events_no_replacement = [[1, 0, 1], [1, 0, 12], [1, 0, 1234], [3, 0, 2], [3, 0, 12], [3, 0, 1234], [10, 0, 3], [10, 0, 34], [10, 0, 1234], [20, 0, 4], [20, 0, 34], [20, 0, 1234]] for (replace_events, events_good) in [(True, events_replacement), (False, events_no_replacement)]: events = merge_events(events_orig, [1, 2], 12, replace_events) events = merge_events(events, [3, 4], 34, replace_events) events = merge_events(events, [1, 2, 3, 4], 1234, replace_events) assert_array_equal(events, events_good)
def test_merge_events(): events_orig = [[1, 0, 1], [3, 0, 2], [10, 0, 3], [20, 0, 4]] events_replacement = [[1, 0, 12], [3, 0, 12], [10, 0, 34], [20, 0, 34]] events_no_replacement = [[1, 0, 1], [1, 0, 12], [1, 0, 1234], [3, 0, 2], [3, 0, 12], [3, 0, 1234], [10, 0, 3], [10, 0, 34], [10, 0, 1234], [20, 0, 4], [20, 0, 34], [20, 0, 1234]] for (replace_events, events_good) in [(True, events_replacement), (False, events_no_replacement)]: events = merge_events(events_orig, [1, 2], 12, replace_events) events = merge_events(events, [3, 4], 34, replace_events) events = merge_events(events, [1, 2, 3, 4], 1234, replace_events) assert_array_equal(events, events_good)<|docstring|>Test event merging.<|endoftext|>
a6db8d14edea04bea76c9ed89f9f1b0091ba7806402b1598b9386f1a0d3e3b0e
def test_io_events(tmpdir): 'Test IO for events.' events = read_events(fname) fname_temp = tmpdir.join('events-eve.fif') write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) events2 = read_events(fname_gz) assert_array_almost_equal(events, events2) fname_temp += '.gz' write_events(fname_temp, events2) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname_temp = str(tmpdir.join('events.eve')) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) with pytest.warns(RuntimeWarning, match='first row of'): events2 = read_events(fname_txt_mpr, mask=0, mask_type='not_and') assert_array_almost_equal(events, events2) events2 = read_events(fname_old_txt) assert_array_almost_equal(events, events2) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname_temp = tmpdir.join('events-eve.fif') a = read_events(fname_temp, include=1) b = read_events(fname_temp, include=[1]) c = read_events(fname_temp, exclude=[2, 3, 4, 5, 32]) d = read_events(fname_temp, include=1, exclude=[2, 3]) assert_array_equal(a, b) assert_array_equal(a, c) assert_array_equal(a, d) events2 = events.copy() events2[(:, (- 1))] = range(events2.shape[0]) write_events(fname_temp, events2) events3 = read_events(fname_temp, mask=None) assert_array_almost_equal(events2, events3) events = read_events(fname_1) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname_temp = str(tmpdir.join('events.eve')) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname2 = tmpdir.join('test-bad-name.fif') with pytest.warns(RuntimeWarning, match='-eve.fif'): write_events(fname2, events) with pytest.warns(RuntimeWarning, match='-eve.fif'): read_events(fname2) with pytest.raises(RuntimeError, match='No event_id'): read_events(fname, return_event_id=True)
Test IO for events.
mne/tests/test_event.py
test_io_events
hofaflo/mne-python
1,953
python
def test_io_events(tmpdir): events = read_events(fname) fname_temp = tmpdir.join('events-eve.fif') write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) events2 = read_events(fname_gz) assert_array_almost_equal(events, events2) fname_temp += '.gz' write_events(fname_temp, events2) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname_temp = str(tmpdir.join('events.eve')) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) with pytest.warns(RuntimeWarning, match='first row of'): events2 = read_events(fname_txt_mpr, mask=0, mask_type='not_and') assert_array_almost_equal(events, events2) events2 = read_events(fname_old_txt) assert_array_almost_equal(events, events2) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname_temp = tmpdir.join('events-eve.fif') a = read_events(fname_temp, include=1) b = read_events(fname_temp, include=[1]) c = read_events(fname_temp, exclude=[2, 3, 4, 5, 32]) d = read_events(fname_temp, include=1, exclude=[2, 3]) assert_array_equal(a, b) assert_array_equal(a, c) assert_array_equal(a, d) events2 = events.copy() events2[(:, (- 1))] = range(events2.shape[0]) write_events(fname_temp, events2) events3 = read_events(fname_temp, mask=None) assert_array_almost_equal(events2, events3) events = read_events(fname_1) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname_temp = str(tmpdir.join('events.eve')) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname2 = tmpdir.join('test-bad-name.fif') with pytest.warns(RuntimeWarning, match='-eve.fif'): write_events(fname2, events) with pytest.warns(RuntimeWarning, match='-eve.fif'): read_events(fname2) with pytest.raises(RuntimeError, match='No event_id'): read_events(fname, return_event_id=True)
def test_io_events(tmpdir): events = read_events(fname) fname_temp = tmpdir.join('events-eve.fif') write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) events2 = read_events(fname_gz) assert_array_almost_equal(events, events2) fname_temp += '.gz' write_events(fname_temp, events2) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname_temp = str(tmpdir.join('events.eve')) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) with pytest.warns(RuntimeWarning, match='first row of'): events2 = read_events(fname_txt_mpr, mask=0, mask_type='not_and') assert_array_almost_equal(events, events2) events2 = read_events(fname_old_txt) assert_array_almost_equal(events, events2) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname_temp = tmpdir.join('events-eve.fif') a = read_events(fname_temp, include=1) b = read_events(fname_temp, include=[1]) c = read_events(fname_temp, exclude=[2, 3, 4, 5, 32]) d = read_events(fname_temp, include=1, exclude=[2, 3]) assert_array_equal(a, b) assert_array_equal(a, c) assert_array_equal(a, d) events2 = events.copy() events2[(:, (- 1))] = range(events2.shape[0]) write_events(fname_temp, events2) events3 = read_events(fname_temp, mask=None) assert_array_almost_equal(events2, events3) events = read_events(fname_1) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname_temp = str(tmpdir.join('events.eve')) write_events(fname_temp, events) events2 = read_events(fname_temp) assert_array_almost_equal(events, events2) fname2 = tmpdir.join('test-bad-name.fif') with pytest.warns(RuntimeWarning, match='-eve.fif'): write_events(fname2, events) with pytest.warns(RuntimeWarning, match='-eve.fif'): read_events(fname2) with pytest.raises(RuntimeError, match='No event_id'): read_events(fname, return_event_id=True)<|docstring|>Test IO for events.<|endoftext|>
c80f6e5efca0d082789ae0b9d6e937f99301b9912782a3a8a87648ba82e99a0d
def test_io_c_annot(): 'Test I/O of MNE-C -annot.fif files.' raw = read_raw_fif(fname_raw) (sfreq, first_samp) = (raw.info['sfreq'], raw.first_samp) events = read_events(fname_c_annot) (events_2, event_id) = read_events(fname_c_annot, return_event_id=True) assert_array_equal(events_2, events) expected = ((np.arange(2, 5) * sfreq) + first_samp) assert_allclose(events[(:, 0)], expected, atol=3) expected = {'Two sec': 1001, 'Three and four sec': 1002} assert (event_id == expected)
Test I/O of MNE-C -annot.fif files.
mne/tests/test_event.py
test_io_c_annot
hofaflo/mne-python
1,953
python
def test_io_c_annot(): raw = read_raw_fif(fname_raw) (sfreq, first_samp) = (raw.info['sfreq'], raw.first_samp) events = read_events(fname_c_annot) (events_2, event_id) = read_events(fname_c_annot, return_event_id=True) assert_array_equal(events_2, events) expected = ((np.arange(2, 5) * sfreq) + first_samp) assert_allclose(events[(:, 0)], expected, atol=3) expected = {'Two sec': 1001, 'Three and four sec': 1002} assert (event_id == expected)
def test_io_c_annot(): raw = read_raw_fif(fname_raw) (sfreq, first_samp) = (raw.info['sfreq'], raw.first_samp) events = read_events(fname_c_annot) (events_2, event_id) = read_events(fname_c_annot, return_event_id=True) assert_array_equal(events_2, events) expected = ((np.arange(2, 5) * sfreq) + first_samp) assert_allclose(events[(:, 0)], expected, atol=3) expected = {'Two sec': 1001, 'Three and four sec': 1002} assert (event_id == expected)<|docstring|>Test I/O of MNE-C -annot.fif files.<|endoftext|>
4a3e4734069ffb7fcf0003b5b0f39fc10ef5befb60b3450ba173eb5ffa004eac
def test_find_events(): 'Test find events in raw file.' events = read_events(fname) raw = read_raw_fif(raw_fname, preload=True) extra_ends = ['', '_1'] orig_envs = [os.getenv(('MNE_STIM_CHANNEL%s' % s)) for s in extra_ends] os.environ['MNE_STIM_CHANNEL'] = 'STI 014' if ('MNE_STIM_CHANNEL_1' in os.environ): del os.environ['MNE_STIM_CHANNEL_1'] events2 = find_events(raw) assert_array_almost_equal(events, events2) events11 = find_events(raw, mask=3, mask_type='not_and') with pytest.warns(RuntimeWarning, match='events masked'): events22 = read_events(fname, mask=3, mask_type='not_and') assert_array_equal(events11, events22) raw._first_samps[0] = 0 raw.info['sfreq'] = 1000 stim_channel = 'STI 014' stim_channel_idx = pick_channels(raw.info['ch_names'], include=[stim_channel]) raw._data[(stim_channel_idx, :5)] = np.arange(5) raw._data[(stim_channel_idx, 5:)] = 0 pytest.raises(TypeError, find_events, raw, mask='0', mask_type='and') pytest.raises(ValueError, find_events, raw, mask=0, mask_type='blah') assert_array_equal(find_events(raw, shortest_event=1, mask=1, mask_type='not_and'), [[2, 0, 2], [4, 2, 4]]) assert_array_equal(find_events(raw, shortest_event=1, mask=2, mask_type='not_and'), [[1, 0, 1], [3, 0, 1], [4, 1, 4]]) assert_array_equal(find_events(raw, shortest_event=1, mask=3, mask_type='not_and'), [[4, 0, 4]]) assert_array_equal(find_events(raw, shortest_event=1, mask=4, mask_type='not_and'), [[1, 0, 1], [2, 1, 2], [3, 2, 3]]) assert_array_equal(find_events(raw, shortest_event=1, mask=1, mask_type='and'), [[1, 0, 1], [3, 0, 1]]) assert_array_equal(find_events(raw, shortest_event=1, mask=2, mask_type='and'), [[2, 0, 2]]) assert_array_equal(find_events(raw, shortest_event=1, mask=3, mask_type='and'), [[1, 0, 1], [2, 1, 2], [3, 2, 3]]) assert_array_equal(find_events(raw, shortest_event=1, mask=4, mask_type='and'), [[4, 0, 4]]) raw._data[(stim_channel_idx, :)] = 0 assert_array_equal(find_events(raw), np.empty((0, 3), dtype='int32')) raw._data[(stim_channel_idx, :4)] = 1 assert_array_equal(find_events(raw), np.empty((0, 3), dtype='int32')) raw._data[(stim_channel_idx, (- 1):)] = 9 assert_array_equal(find_events(raw), [[14399, 0, 9]]) raw._data[(stim_channel_idx, 10:20)] = 5 raw._data[(stim_channel_idx, 20:30)] = 6 raw._data[(stim_channel_idx, 30:32)] = 5 raw._data[(stim_channel_idx, 40)] = 6 assert_array_equal(find_events(raw, consecutive=False), [[10, 0, 5], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, consecutive=True), [[10, 0, 5], [20, 5, 6], [30, 6, 5], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw), [[10, 0, 5], [20, 5, 6], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, output='offset', consecutive=False), [[31, 0, 5], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, output='offset', consecutive=True), [[19, 6, 5], [29, 5, 6], [31, 0, 5], [40, 0, 6], [14399, 0, 9]]) pytest.raises(ValueError, find_events, raw, output='step', consecutive=True) assert_array_equal(find_events(raw, output='step', consecutive=True, shortest_event=1), [[10, 0, 5], [20, 5, 6], [30, 6, 5], [32, 5, 0], [40, 0, 6], [41, 6, 0], [14399, 0, 9], [14400, 9, 0]]) assert_array_equal(find_events(raw, output='offset'), [[19, 6, 5], [31, 0, 6], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, consecutive=False, min_duration=0.002), [[10, 0, 5]]) assert_array_equal(find_events(raw, consecutive=True, min_duration=0.002), [[10, 0, 5], [20, 5, 6], [30, 6, 5]]) assert_array_equal(find_events(raw, output='offset', consecutive=False, min_duration=0.002), [[31, 0, 5]]) assert_array_equal(find_events(raw, output='offset', consecutive=True, min_duration=0.002), [[19, 6, 5], [29, 5, 6], [31, 0, 5]]) assert_array_equal(find_events(raw, consecutive=True, min_duration=0.003), [[10, 0, 5], [20, 5, 6]]) raw._data[(stim_channel_idx, :)] = 0 raw._data[(stim_channel_idx, 0)] = 1 raw._data[(stim_channel_idx, 10)] = 4 raw._data[(stim_channel_idx, 11:20)] = 5 assert_array_equal(find_stim_steps(raw, pad_start=0, merge=0, stim_channel=stim_channel), [[0, 0, 1], [1, 1, 0], [10, 0, 4], [11, 4, 5], [20, 5, 0]]) assert_array_equal(find_stim_steps(raw, merge=(- 1), stim_channel=stim_channel), [[1, 1, 0], [10, 0, 5], [20, 5, 0]]) assert_array_equal(find_stim_steps(raw, merge=1, stim_channel=stim_channel), [[1, 1, 0], [11, 0, 5], [20, 5, 0]]) for (s, o) in zip(extra_ends, orig_envs): if (o is not None): os.environ[('MNE_STIM_CHANNEL%s' % s)] = o raw._data[(stim_channel_idx, 1:101)] = np.zeros(100) raw._data[(stim_channel_idx, 10:11)] = 1 raw._data[(stim_channel_idx, 30:31)] = 3 stim_channel2 = 'STI 015' stim_channel2_idx = pick_channels(raw.info['ch_names'], include=[stim_channel2]) raw._data[(stim_channel2_idx, :)] = 0 raw._data[(stim_channel2_idx, :100)] = raw._data[(stim_channel_idx, 5:105)] events1 = find_events(raw, stim_channel='STI 014') events2 = events1.copy() events2[(:, 0)] -= 5 events = find_events(raw, stim_channel=['STI 014', stim_channel2]) assert_array_equal(events[::2], events2) assert_array_equal(events[1::2], events1) info = create_info(['MYSTI'], 1000, 'stim') data = np.zeros((1, 1000)) raw = RawArray(data, info) data[(0, :10)] = 100 data[(0, 30:40)] = 200 assert_array_equal(find_events(raw, 'MYSTI'), [[30, 0, 200]]) assert_array_equal(find_events(raw, 'MYSTI', initial_event=True), [[0, 0, 100], [30, 0, 200]]) raw = read_raw_fif(raw_fname, preload=True) raw.pick_types(meg=True, stim=False) with pytest.raises(ValueError, match="'stim_channel'"): find_events(raw) raw.set_annotations(Annotations(0, 2, 'test')) with pytest.raises(ValueError, match='mne.events_from_annotations'): find_events(raw)
Test find events in raw file.
mne/tests/test_event.py
test_find_events
hofaflo/mne-python
1,953
python
def test_find_events(): events = read_events(fname) raw = read_raw_fif(raw_fname, preload=True) extra_ends = [, '_1'] orig_envs = [os.getenv(('MNE_STIM_CHANNEL%s' % s)) for s in extra_ends] os.environ['MNE_STIM_CHANNEL'] = 'STI 014' if ('MNE_STIM_CHANNEL_1' in os.environ): del os.environ['MNE_STIM_CHANNEL_1'] events2 = find_events(raw) assert_array_almost_equal(events, events2) events11 = find_events(raw, mask=3, mask_type='not_and') with pytest.warns(RuntimeWarning, match='events masked'): events22 = read_events(fname, mask=3, mask_type='not_and') assert_array_equal(events11, events22) raw._first_samps[0] = 0 raw.info['sfreq'] = 1000 stim_channel = 'STI 014' stim_channel_idx = pick_channels(raw.info['ch_names'], include=[stim_channel]) raw._data[(stim_channel_idx, :5)] = np.arange(5) raw._data[(stim_channel_idx, 5:)] = 0 pytest.raises(TypeError, find_events, raw, mask='0', mask_type='and') pytest.raises(ValueError, find_events, raw, mask=0, mask_type='blah') assert_array_equal(find_events(raw, shortest_event=1, mask=1, mask_type='not_and'), [[2, 0, 2], [4, 2, 4]]) assert_array_equal(find_events(raw, shortest_event=1, mask=2, mask_type='not_and'), [[1, 0, 1], [3, 0, 1], [4, 1, 4]]) assert_array_equal(find_events(raw, shortest_event=1, mask=3, mask_type='not_and'), [[4, 0, 4]]) assert_array_equal(find_events(raw, shortest_event=1, mask=4, mask_type='not_and'), [[1, 0, 1], [2, 1, 2], [3, 2, 3]]) assert_array_equal(find_events(raw, shortest_event=1, mask=1, mask_type='and'), [[1, 0, 1], [3, 0, 1]]) assert_array_equal(find_events(raw, shortest_event=1, mask=2, mask_type='and'), [[2, 0, 2]]) assert_array_equal(find_events(raw, shortest_event=1, mask=3, mask_type='and'), [[1, 0, 1], [2, 1, 2], [3, 2, 3]]) assert_array_equal(find_events(raw, shortest_event=1, mask=4, mask_type='and'), [[4, 0, 4]]) raw._data[(stim_channel_idx, :)] = 0 assert_array_equal(find_events(raw), np.empty((0, 3), dtype='int32')) raw._data[(stim_channel_idx, :4)] = 1 assert_array_equal(find_events(raw), np.empty((0, 3), dtype='int32')) raw._data[(stim_channel_idx, (- 1):)] = 9 assert_array_equal(find_events(raw), [[14399, 0, 9]]) raw._data[(stim_channel_idx, 10:20)] = 5 raw._data[(stim_channel_idx, 20:30)] = 6 raw._data[(stim_channel_idx, 30:32)] = 5 raw._data[(stim_channel_idx, 40)] = 6 assert_array_equal(find_events(raw, consecutive=False), [[10, 0, 5], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, consecutive=True), [[10, 0, 5], [20, 5, 6], [30, 6, 5], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw), [[10, 0, 5], [20, 5, 6], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, output='offset', consecutive=False), [[31, 0, 5], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, output='offset', consecutive=True), [[19, 6, 5], [29, 5, 6], [31, 0, 5], [40, 0, 6], [14399, 0, 9]]) pytest.raises(ValueError, find_events, raw, output='step', consecutive=True) assert_array_equal(find_events(raw, output='step', consecutive=True, shortest_event=1), [[10, 0, 5], [20, 5, 6], [30, 6, 5], [32, 5, 0], [40, 0, 6], [41, 6, 0], [14399, 0, 9], [14400, 9, 0]]) assert_array_equal(find_events(raw, output='offset'), [[19, 6, 5], [31, 0, 6], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, consecutive=False, min_duration=0.002), [[10, 0, 5]]) assert_array_equal(find_events(raw, consecutive=True, min_duration=0.002), [[10, 0, 5], [20, 5, 6], [30, 6, 5]]) assert_array_equal(find_events(raw, output='offset', consecutive=False, min_duration=0.002), [[31, 0, 5]]) assert_array_equal(find_events(raw, output='offset', consecutive=True, min_duration=0.002), [[19, 6, 5], [29, 5, 6], [31, 0, 5]]) assert_array_equal(find_events(raw, consecutive=True, min_duration=0.003), [[10, 0, 5], [20, 5, 6]]) raw._data[(stim_channel_idx, :)] = 0 raw._data[(stim_channel_idx, 0)] = 1 raw._data[(stim_channel_idx, 10)] = 4 raw._data[(stim_channel_idx, 11:20)] = 5 assert_array_equal(find_stim_steps(raw, pad_start=0, merge=0, stim_channel=stim_channel), [[0, 0, 1], [1, 1, 0], [10, 0, 4], [11, 4, 5], [20, 5, 0]]) assert_array_equal(find_stim_steps(raw, merge=(- 1), stim_channel=stim_channel), [[1, 1, 0], [10, 0, 5], [20, 5, 0]]) assert_array_equal(find_stim_steps(raw, merge=1, stim_channel=stim_channel), [[1, 1, 0], [11, 0, 5], [20, 5, 0]]) for (s, o) in zip(extra_ends, orig_envs): if (o is not None): os.environ[('MNE_STIM_CHANNEL%s' % s)] = o raw._data[(stim_channel_idx, 1:101)] = np.zeros(100) raw._data[(stim_channel_idx, 10:11)] = 1 raw._data[(stim_channel_idx, 30:31)] = 3 stim_channel2 = 'STI 015' stim_channel2_idx = pick_channels(raw.info['ch_names'], include=[stim_channel2]) raw._data[(stim_channel2_idx, :)] = 0 raw._data[(stim_channel2_idx, :100)] = raw._data[(stim_channel_idx, 5:105)] events1 = find_events(raw, stim_channel='STI 014') events2 = events1.copy() events2[(:, 0)] -= 5 events = find_events(raw, stim_channel=['STI 014', stim_channel2]) assert_array_equal(events[::2], events2) assert_array_equal(events[1::2], events1) info = create_info(['MYSTI'], 1000, 'stim') data = np.zeros((1, 1000)) raw = RawArray(data, info) data[(0, :10)] = 100 data[(0, 30:40)] = 200 assert_array_equal(find_events(raw, 'MYSTI'), [[30, 0, 200]]) assert_array_equal(find_events(raw, 'MYSTI', initial_event=True), [[0, 0, 100], [30, 0, 200]]) raw = read_raw_fif(raw_fname, preload=True) raw.pick_types(meg=True, stim=False) with pytest.raises(ValueError, match="'stim_channel'"): find_events(raw) raw.set_annotations(Annotations(0, 2, 'test')) with pytest.raises(ValueError, match='mne.events_from_annotations'): find_events(raw)
def test_find_events(): events = read_events(fname) raw = read_raw_fif(raw_fname, preload=True) extra_ends = [, '_1'] orig_envs = [os.getenv(('MNE_STIM_CHANNEL%s' % s)) for s in extra_ends] os.environ['MNE_STIM_CHANNEL'] = 'STI 014' if ('MNE_STIM_CHANNEL_1' in os.environ): del os.environ['MNE_STIM_CHANNEL_1'] events2 = find_events(raw) assert_array_almost_equal(events, events2) events11 = find_events(raw, mask=3, mask_type='not_and') with pytest.warns(RuntimeWarning, match='events masked'): events22 = read_events(fname, mask=3, mask_type='not_and') assert_array_equal(events11, events22) raw._first_samps[0] = 0 raw.info['sfreq'] = 1000 stim_channel = 'STI 014' stim_channel_idx = pick_channels(raw.info['ch_names'], include=[stim_channel]) raw._data[(stim_channel_idx, :5)] = np.arange(5) raw._data[(stim_channel_idx, 5:)] = 0 pytest.raises(TypeError, find_events, raw, mask='0', mask_type='and') pytest.raises(ValueError, find_events, raw, mask=0, mask_type='blah') assert_array_equal(find_events(raw, shortest_event=1, mask=1, mask_type='not_and'), [[2, 0, 2], [4, 2, 4]]) assert_array_equal(find_events(raw, shortest_event=1, mask=2, mask_type='not_and'), [[1, 0, 1], [3, 0, 1], [4, 1, 4]]) assert_array_equal(find_events(raw, shortest_event=1, mask=3, mask_type='not_and'), [[4, 0, 4]]) assert_array_equal(find_events(raw, shortest_event=1, mask=4, mask_type='not_and'), [[1, 0, 1], [2, 1, 2], [3, 2, 3]]) assert_array_equal(find_events(raw, shortest_event=1, mask=1, mask_type='and'), [[1, 0, 1], [3, 0, 1]]) assert_array_equal(find_events(raw, shortest_event=1, mask=2, mask_type='and'), [[2, 0, 2]]) assert_array_equal(find_events(raw, shortest_event=1, mask=3, mask_type='and'), [[1, 0, 1], [2, 1, 2], [3, 2, 3]]) assert_array_equal(find_events(raw, shortest_event=1, mask=4, mask_type='and'), [[4, 0, 4]]) raw._data[(stim_channel_idx, :)] = 0 assert_array_equal(find_events(raw), np.empty((0, 3), dtype='int32')) raw._data[(stim_channel_idx, :4)] = 1 assert_array_equal(find_events(raw), np.empty((0, 3), dtype='int32')) raw._data[(stim_channel_idx, (- 1):)] = 9 assert_array_equal(find_events(raw), [[14399, 0, 9]]) raw._data[(stim_channel_idx, 10:20)] = 5 raw._data[(stim_channel_idx, 20:30)] = 6 raw._data[(stim_channel_idx, 30:32)] = 5 raw._data[(stim_channel_idx, 40)] = 6 assert_array_equal(find_events(raw, consecutive=False), [[10, 0, 5], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, consecutive=True), [[10, 0, 5], [20, 5, 6], [30, 6, 5], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw), [[10, 0, 5], [20, 5, 6], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, output='offset', consecutive=False), [[31, 0, 5], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, output='offset', consecutive=True), [[19, 6, 5], [29, 5, 6], [31, 0, 5], [40, 0, 6], [14399, 0, 9]]) pytest.raises(ValueError, find_events, raw, output='step', consecutive=True) assert_array_equal(find_events(raw, output='step', consecutive=True, shortest_event=1), [[10, 0, 5], [20, 5, 6], [30, 6, 5], [32, 5, 0], [40, 0, 6], [41, 6, 0], [14399, 0, 9], [14400, 9, 0]]) assert_array_equal(find_events(raw, output='offset'), [[19, 6, 5], [31, 0, 6], [40, 0, 6], [14399, 0, 9]]) assert_array_equal(find_events(raw, consecutive=False, min_duration=0.002), [[10, 0, 5]]) assert_array_equal(find_events(raw, consecutive=True, min_duration=0.002), [[10, 0, 5], [20, 5, 6], [30, 6, 5]]) assert_array_equal(find_events(raw, output='offset', consecutive=False, min_duration=0.002), [[31, 0, 5]]) assert_array_equal(find_events(raw, output='offset', consecutive=True, min_duration=0.002), [[19, 6, 5], [29, 5, 6], [31, 0, 5]]) assert_array_equal(find_events(raw, consecutive=True, min_duration=0.003), [[10, 0, 5], [20, 5, 6]]) raw._data[(stim_channel_idx, :)] = 0 raw._data[(stim_channel_idx, 0)] = 1 raw._data[(stim_channel_idx, 10)] = 4 raw._data[(stim_channel_idx, 11:20)] = 5 assert_array_equal(find_stim_steps(raw, pad_start=0, merge=0, stim_channel=stim_channel), [[0, 0, 1], [1, 1, 0], [10, 0, 4], [11, 4, 5], [20, 5, 0]]) assert_array_equal(find_stim_steps(raw, merge=(- 1), stim_channel=stim_channel), [[1, 1, 0], [10, 0, 5], [20, 5, 0]]) assert_array_equal(find_stim_steps(raw, merge=1, stim_channel=stim_channel), [[1, 1, 0], [11, 0, 5], [20, 5, 0]]) for (s, o) in zip(extra_ends, orig_envs): if (o is not None): os.environ[('MNE_STIM_CHANNEL%s' % s)] = o raw._data[(stim_channel_idx, 1:101)] = np.zeros(100) raw._data[(stim_channel_idx, 10:11)] = 1 raw._data[(stim_channel_idx, 30:31)] = 3 stim_channel2 = 'STI 015' stim_channel2_idx = pick_channels(raw.info['ch_names'], include=[stim_channel2]) raw._data[(stim_channel2_idx, :)] = 0 raw._data[(stim_channel2_idx, :100)] = raw._data[(stim_channel_idx, 5:105)] events1 = find_events(raw, stim_channel='STI 014') events2 = events1.copy() events2[(:, 0)] -= 5 events = find_events(raw, stim_channel=['STI 014', stim_channel2]) assert_array_equal(events[::2], events2) assert_array_equal(events[1::2], events1) info = create_info(['MYSTI'], 1000, 'stim') data = np.zeros((1, 1000)) raw = RawArray(data, info) data[(0, :10)] = 100 data[(0, 30:40)] = 200 assert_array_equal(find_events(raw, 'MYSTI'), [[30, 0, 200]]) assert_array_equal(find_events(raw, 'MYSTI', initial_event=True), [[0, 0, 100], [30, 0, 200]]) raw = read_raw_fif(raw_fname, preload=True) raw.pick_types(meg=True, stim=False) with pytest.raises(ValueError, match="'stim_channel'"): find_events(raw) raw.set_annotations(Annotations(0, 2, 'test')) with pytest.raises(ValueError, match='mne.events_from_annotations'): find_events(raw)<|docstring|>Test find events in raw file.<|endoftext|>
f84e4f729fbecd069ffc11909c9ddc5c42044e23c87c00baf23c6ec1cf2a8254
def test_pick_events(): 'Test pick events in a events ndarray.' events = np.array([[1, 0, 1], [2, 1, 0], [3, 0, 4], [4, 4, 2], [5, 2, 0]]) assert_array_equal(pick_events(events, include=[1, 4], exclude=4), [[1, 0, 1], [3, 0, 4]]) assert_array_equal(pick_events(events, exclude=[0, 2]), [[1, 0, 1], [3, 0, 4]]) assert_array_equal(pick_events(events, include=[1, 2], step=True), [[1, 0, 1], [2, 1, 0], [4, 4, 2], [5, 2, 0]])
Test pick events in a events ndarray.
mne/tests/test_event.py
test_pick_events
hofaflo/mne-python
1,953
python
def test_pick_events(): events = np.array([[1, 0, 1], [2, 1, 0], [3, 0, 4], [4, 4, 2], [5, 2, 0]]) assert_array_equal(pick_events(events, include=[1, 4], exclude=4), [[1, 0, 1], [3, 0, 4]]) assert_array_equal(pick_events(events, exclude=[0, 2]), [[1, 0, 1], [3, 0, 4]]) assert_array_equal(pick_events(events, include=[1, 2], step=True), [[1, 0, 1], [2, 1, 0], [4, 4, 2], [5, 2, 0]])
def test_pick_events(): events = np.array([[1, 0, 1], [2, 1, 0], [3, 0, 4], [4, 4, 2], [5, 2, 0]]) assert_array_equal(pick_events(events, include=[1, 4], exclude=4), [[1, 0, 1], [3, 0, 4]]) assert_array_equal(pick_events(events, exclude=[0, 2]), [[1, 0, 1], [3, 0, 4]]) assert_array_equal(pick_events(events, include=[1, 2], step=True), [[1, 0, 1], [2, 1, 0], [4, 4, 2], [5, 2, 0]])<|docstring|>Test pick events in a events ndarray.<|endoftext|>
276e28e8b276a87c60e2e67574881edc104834460192b8fda310befe901aae6f
def test_make_fixed_length_events(): 'Test making events of a fixed length.' raw = read_raw_fif(raw_fname) events = make_fixed_length_events(raw, id=1) assert (events.shape[1] == 3) events_zero = make_fixed_length_events(raw, 1, first_samp=False) assert_equal(events_zero[(0, 0)], 0) assert_array_equal(events_zero[(:, 0)], (events[(:, 0)] - raw.first_samp)) (tmin, tmax) = raw.times[[0, (- 1)]] duration = (tmax - tmin) events = make_fixed_length_events(raw, 1, tmin, tmax, duration) assert_equal(events.shape[0], 1) pytest.raises(ValueError, make_fixed_length_events, raw, 1, tmin, (tmax - 0.001), duration) pytest.raises(TypeError, make_fixed_length_events, raw, 2.3) pytest.raises(TypeError, make_fixed_length_events, 'not raw', 2) pytest.raises(TypeError, make_fixed_length_events, raw, 23, tmin, tmax, 'abc') data = np.random.RandomState(0).randn(1, 27768) info = create_info(1, 155.4499969482422) raw = RawArray(data, info) events = make_fixed_length_events(raw, 1, duration=raw.times[(- 1)]) assert (events[(0, 0)] == 0) assert (len(events) == 1) raw = RawArray(data[(:, :21216)], info) events = make_fixed_length_events(raw, 1, duration=raw.times[(- 1)]) assert (events[(0, 0)] == 0) assert (len(events) == 1) cov = compute_raw_covariance(raw, tstep=None) expected = np.cov(data[(:, :21216)]) assert_allclose(cov['data'], expected, atol=1e-12) events = make_fixed_length_events(raw, 1, duration=1) assert (len(events) == 136) events_ol = make_fixed_length_events(raw, 1, duration=1, overlap=0.5) assert (len(events_ol) == 271) events_ol_2 = make_fixed_length_events(raw, 1, duration=1, overlap=0.9) assert (len(events_ol_2) == 1355) assert_array_equal(events_ol_2[(:, 0)], np.unique(events_ol_2[(:, 0)])) with pytest.raises(ValueError, match='overlap must be'): make_fixed_length_events(raw, 1, duration=1, overlap=1.1)
Test making events of a fixed length.
mne/tests/test_event.py
test_make_fixed_length_events
hofaflo/mne-python
1,953
python
def test_make_fixed_length_events(): raw = read_raw_fif(raw_fname) events = make_fixed_length_events(raw, id=1) assert (events.shape[1] == 3) events_zero = make_fixed_length_events(raw, 1, first_samp=False) assert_equal(events_zero[(0, 0)], 0) assert_array_equal(events_zero[(:, 0)], (events[(:, 0)] - raw.first_samp)) (tmin, tmax) = raw.times[[0, (- 1)]] duration = (tmax - tmin) events = make_fixed_length_events(raw, 1, tmin, tmax, duration) assert_equal(events.shape[0], 1) pytest.raises(ValueError, make_fixed_length_events, raw, 1, tmin, (tmax - 0.001), duration) pytest.raises(TypeError, make_fixed_length_events, raw, 2.3) pytest.raises(TypeError, make_fixed_length_events, 'not raw', 2) pytest.raises(TypeError, make_fixed_length_events, raw, 23, tmin, tmax, 'abc') data = np.random.RandomState(0).randn(1, 27768) info = create_info(1, 155.4499969482422) raw = RawArray(data, info) events = make_fixed_length_events(raw, 1, duration=raw.times[(- 1)]) assert (events[(0, 0)] == 0) assert (len(events) == 1) raw = RawArray(data[(:, :21216)], info) events = make_fixed_length_events(raw, 1, duration=raw.times[(- 1)]) assert (events[(0, 0)] == 0) assert (len(events) == 1) cov = compute_raw_covariance(raw, tstep=None) expected = np.cov(data[(:, :21216)]) assert_allclose(cov['data'], expected, atol=1e-12) events = make_fixed_length_events(raw, 1, duration=1) assert (len(events) == 136) events_ol = make_fixed_length_events(raw, 1, duration=1, overlap=0.5) assert (len(events_ol) == 271) events_ol_2 = make_fixed_length_events(raw, 1, duration=1, overlap=0.9) assert (len(events_ol_2) == 1355) assert_array_equal(events_ol_2[(:, 0)], np.unique(events_ol_2[(:, 0)])) with pytest.raises(ValueError, match='overlap must be'): make_fixed_length_events(raw, 1, duration=1, overlap=1.1)
def test_make_fixed_length_events(): raw = read_raw_fif(raw_fname) events = make_fixed_length_events(raw, id=1) assert (events.shape[1] == 3) events_zero = make_fixed_length_events(raw, 1, first_samp=False) assert_equal(events_zero[(0, 0)], 0) assert_array_equal(events_zero[(:, 0)], (events[(:, 0)] - raw.first_samp)) (tmin, tmax) = raw.times[[0, (- 1)]] duration = (tmax - tmin) events = make_fixed_length_events(raw, 1, tmin, tmax, duration) assert_equal(events.shape[0], 1) pytest.raises(ValueError, make_fixed_length_events, raw, 1, tmin, (tmax - 0.001), duration) pytest.raises(TypeError, make_fixed_length_events, raw, 2.3) pytest.raises(TypeError, make_fixed_length_events, 'not raw', 2) pytest.raises(TypeError, make_fixed_length_events, raw, 23, tmin, tmax, 'abc') data = np.random.RandomState(0).randn(1, 27768) info = create_info(1, 155.4499969482422) raw = RawArray(data, info) events = make_fixed_length_events(raw, 1, duration=raw.times[(- 1)]) assert (events[(0, 0)] == 0) assert (len(events) == 1) raw = RawArray(data[(:, :21216)], info) events = make_fixed_length_events(raw, 1, duration=raw.times[(- 1)]) assert (events[(0, 0)] == 0) assert (len(events) == 1) cov = compute_raw_covariance(raw, tstep=None) expected = np.cov(data[(:, :21216)]) assert_allclose(cov['data'], expected, atol=1e-12) events = make_fixed_length_events(raw, 1, duration=1) assert (len(events) == 136) events_ol = make_fixed_length_events(raw, 1, duration=1, overlap=0.5) assert (len(events_ol) == 271) events_ol_2 = make_fixed_length_events(raw, 1, duration=1, overlap=0.9) assert (len(events_ol_2) == 1355) assert_array_equal(events_ol_2[(:, 0)], np.unique(events_ol_2[(:, 0)])) with pytest.raises(ValueError, match='overlap must be'): make_fixed_length_events(raw, 1, duration=1, overlap=1.1)<|docstring|>Test making events of a fixed length.<|endoftext|>
149178ea2fd98a3d4dd4a90f774fc6d360e311334cab08a5e7fdfb036a70784b
def test_define_events(): 'Test defining response events.' events = read_events(fname) raw = read_raw_fif(raw_fname) (events_, _) = define_target_events(events, 5, 32, raw.info['sfreq'], 0.2, 0.7, 42, 99) n_target = events[(events[(:, 2)] == 5)].shape[0] n_miss = events_[(events_[(:, 2)] == 99)].shape[0] n_target_ = events_[(events_[(:, 2)] == 42)].shape[0] assert (n_target_ == (n_target - n_miss)) events = np.array([[0, 0, 1], [375, 0, 2], [500, 0, 1], [875, 0, 3], [1000, 0, 1], [1375, 0, 3], [1100, 0, 1], [1475, 0, 2], [1500, 0, 1], [1875, 0, 2]]) true_lag_nofill = [1500.0, 1500.0, 1500.0] true_lag_fill = [1500.0, np.nan, np.nan, 1500.0, 1500.0] (n, lag_nofill) = define_target_events(events, 1, 2, 250.0, 1.4, 1.6, 5) (n, lag_fill) = define_target_events(events, 1, 2, 250.0, 1.4, 1.6, 5, 99) assert_array_equal(true_lag_fill, lag_fill) assert_array_equal(true_lag_nofill, lag_nofill)
Test defining response events.
mne/tests/test_event.py
test_define_events
hofaflo/mne-python
1,953
python
def test_define_events(): events = read_events(fname) raw = read_raw_fif(raw_fname) (events_, _) = define_target_events(events, 5, 32, raw.info['sfreq'], 0.2, 0.7, 42, 99) n_target = events[(events[(:, 2)] == 5)].shape[0] n_miss = events_[(events_[(:, 2)] == 99)].shape[0] n_target_ = events_[(events_[(:, 2)] == 42)].shape[0] assert (n_target_ == (n_target - n_miss)) events = np.array([[0, 0, 1], [375, 0, 2], [500, 0, 1], [875, 0, 3], [1000, 0, 1], [1375, 0, 3], [1100, 0, 1], [1475, 0, 2], [1500, 0, 1], [1875, 0, 2]]) true_lag_nofill = [1500.0, 1500.0, 1500.0] true_lag_fill = [1500.0, np.nan, np.nan, 1500.0, 1500.0] (n, lag_nofill) = define_target_events(events, 1, 2, 250.0, 1.4, 1.6, 5) (n, lag_fill) = define_target_events(events, 1, 2, 250.0, 1.4, 1.6, 5, 99) assert_array_equal(true_lag_fill, lag_fill) assert_array_equal(true_lag_nofill, lag_nofill)
def test_define_events(): events = read_events(fname) raw = read_raw_fif(raw_fname) (events_, _) = define_target_events(events, 5, 32, raw.info['sfreq'], 0.2, 0.7, 42, 99) n_target = events[(events[(:, 2)] == 5)].shape[0] n_miss = events_[(events_[(:, 2)] == 99)].shape[0] n_target_ = events_[(events_[(:, 2)] == 42)].shape[0] assert (n_target_ == (n_target - n_miss)) events = np.array([[0, 0, 1], [375, 0, 2], [500, 0, 1], [875, 0, 3], [1000, 0, 1], [1375, 0, 3], [1100, 0, 1], [1475, 0, 2], [1500, 0, 1], [1875, 0, 2]]) true_lag_nofill = [1500.0, 1500.0, 1500.0] true_lag_fill = [1500.0, np.nan, np.nan, 1500.0, 1500.0] (n, lag_nofill) = define_target_events(events, 1, 2, 250.0, 1.4, 1.6, 5) (n, lag_fill) = define_target_events(events, 1, 2, 250.0, 1.4, 1.6, 5, 99) assert_array_equal(true_lag_fill, lag_fill) assert_array_equal(true_lag_nofill, lag_nofill)<|docstring|>Test defining response events.<|endoftext|>
31b2af251e188e37f26ea2937abb57cefd55aeab6dc5ab5055517559b232b865
@testing.requires_testing_data def test_acqparser(): 'Test AcqParserFIF.' pytest.raises(ValueError, AcqParserFIF, {'acq_pars': ''}) pytest.raises(ValueError, AcqParserFIF, {'acq_pars': 'baaa'}) pytest.raises(ValueError, AcqParserFIF, {'acq_pars': 'ERFVersion\n1'}) raw = read_raw_fif(raw_fname, preload=False) acqp = AcqParserFIF(raw.info) assert repr(acqp) assert acqp.compat assert_equal(len(acqp.categories), 6) assert_equal(len(acqp._categories), 17) assert_equal(len(acqp.events), 6) assert_equal(len(acqp._events), 17) assert acqp['Surprise visual'] raw = read_raw_fif(fname_raw_elekta, preload=False) acqp = raw.acqparser assert (acqp is raw.acqparser) assert repr(acqp) assert (not acqp.compat) pytest.raises(KeyError, acqp.__getitem__, 'does not exist') pytest.raises(KeyError, acqp.get_condition, raw, 'foo') pytest.raises(TypeError, acqp.__getitem__, 0) assert_equal(len(acqp), 7) assert_equal(len(acqp.categories), 7) assert_equal(len(acqp._categories), 32) assert_equal(len(acqp.events), 6) assert_equal(len(acqp._events), 32) assert acqp['Test event 5']
Test AcqParserFIF.
mne/tests/test_event.py
test_acqparser
hofaflo/mne-python
1,953
python
@testing.requires_testing_data def test_acqparser(): pytest.raises(ValueError, AcqParserFIF, {'acq_pars': }) pytest.raises(ValueError, AcqParserFIF, {'acq_pars': 'baaa'}) pytest.raises(ValueError, AcqParserFIF, {'acq_pars': 'ERFVersion\n1'}) raw = read_raw_fif(raw_fname, preload=False) acqp = AcqParserFIF(raw.info) assert repr(acqp) assert acqp.compat assert_equal(len(acqp.categories), 6) assert_equal(len(acqp._categories), 17) assert_equal(len(acqp.events), 6) assert_equal(len(acqp._events), 17) assert acqp['Surprise visual'] raw = read_raw_fif(fname_raw_elekta, preload=False) acqp = raw.acqparser assert (acqp is raw.acqparser) assert repr(acqp) assert (not acqp.compat) pytest.raises(KeyError, acqp.__getitem__, 'does not exist') pytest.raises(KeyError, acqp.get_condition, raw, 'foo') pytest.raises(TypeError, acqp.__getitem__, 0) assert_equal(len(acqp), 7) assert_equal(len(acqp.categories), 7) assert_equal(len(acqp._categories), 32) assert_equal(len(acqp.events), 6) assert_equal(len(acqp._events), 32) assert acqp['Test event 5']
@testing.requires_testing_data def test_acqparser(): pytest.raises(ValueError, AcqParserFIF, {'acq_pars': }) pytest.raises(ValueError, AcqParserFIF, {'acq_pars': 'baaa'}) pytest.raises(ValueError, AcqParserFIF, {'acq_pars': 'ERFVersion\n1'}) raw = read_raw_fif(raw_fname, preload=False) acqp = AcqParserFIF(raw.info) assert repr(acqp) assert acqp.compat assert_equal(len(acqp.categories), 6) assert_equal(len(acqp._categories), 17) assert_equal(len(acqp.events), 6) assert_equal(len(acqp._events), 17) assert acqp['Surprise visual'] raw = read_raw_fif(fname_raw_elekta, preload=False) acqp = raw.acqparser assert (acqp is raw.acqparser) assert repr(acqp) assert (not acqp.compat) pytest.raises(KeyError, acqp.__getitem__, 'does not exist') pytest.raises(KeyError, acqp.get_condition, raw, 'foo') pytest.raises(TypeError, acqp.__getitem__, 0) assert_equal(len(acqp), 7) assert_equal(len(acqp.categories), 7) assert_equal(len(acqp._categories), 32) assert_equal(len(acqp.events), 6) assert_equal(len(acqp._events), 32) assert acqp['Test event 5']<|docstring|>Test AcqParserFIF.<|endoftext|>
0b9328d18a21f4163f29390bdd8f362fbe73496918170711d534806f79cabbb1
@testing.requires_testing_data def test_acqparser_averaging(): 'Test averaging with AcqParserFIF vs. Elekta software.' raw = read_raw_fif(fname_raw_elekta, preload=True) acqp = AcqParserFIF(raw.info) for cat in acqp.categories: cond = acqp.get_condition(raw, cat) eps = Epochs(raw, baseline=((- 0.05), 0), **cond) ev = eps.average() ev_ref = read_evokeds(fname_ave_elekta, cat['comment'], baseline=((- 0.05), 0), proj=False) ev_mag = ev.copy() ev_mag.pick_channels(['MEG0111']) ev_grad = ev.copy() ev_grad.pick_channels(['MEG2643', 'MEG1622']) ev_ref_mag = ev_ref.copy() ev_ref_mag.pick_channels(['MEG0111']) ev_ref_grad = ev_ref.copy() ev_ref_grad.pick_channels(['MEG2643', 'MEG1622']) assert_allclose(ev_mag.data, ev_ref_mag.data, rtol=0, atol=1e-15) assert (ev_grad.ch_names[::(- 1)] == ev_ref_grad.ch_names) assert_allclose(ev_grad.data[::(- 1)], ev_ref_grad.data, rtol=0, atol=1e-13)
Test averaging with AcqParserFIF vs. Elekta software.
mne/tests/test_event.py
test_acqparser_averaging
hofaflo/mne-python
1,953
python
@testing.requires_testing_data def test_acqparser_averaging(): raw = read_raw_fif(fname_raw_elekta, preload=True) acqp = AcqParserFIF(raw.info) for cat in acqp.categories: cond = acqp.get_condition(raw, cat) eps = Epochs(raw, baseline=((- 0.05), 0), **cond) ev = eps.average() ev_ref = read_evokeds(fname_ave_elekta, cat['comment'], baseline=((- 0.05), 0), proj=False) ev_mag = ev.copy() ev_mag.pick_channels(['MEG0111']) ev_grad = ev.copy() ev_grad.pick_channels(['MEG2643', 'MEG1622']) ev_ref_mag = ev_ref.copy() ev_ref_mag.pick_channels(['MEG0111']) ev_ref_grad = ev_ref.copy() ev_ref_grad.pick_channels(['MEG2643', 'MEG1622']) assert_allclose(ev_mag.data, ev_ref_mag.data, rtol=0, atol=1e-15) assert (ev_grad.ch_names[::(- 1)] == ev_ref_grad.ch_names) assert_allclose(ev_grad.data[::(- 1)], ev_ref_grad.data, rtol=0, atol=1e-13)
@testing.requires_testing_data def test_acqparser_averaging(): raw = read_raw_fif(fname_raw_elekta, preload=True) acqp = AcqParserFIF(raw.info) for cat in acqp.categories: cond = acqp.get_condition(raw, cat) eps = Epochs(raw, baseline=((- 0.05), 0), **cond) ev = eps.average() ev_ref = read_evokeds(fname_ave_elekta, cat['comment'], baseline=((- 0.05), 0), proj=False) ev_mag = ev.copy() ev_mag.pick_channels(['MEG0111']) ev_grad = ev.copy() ev_grad.pick_channels(['MEG2643', 'MEG1622']) ev_ref_mag = ev_ref.copy() ev_ref_mag.pick_channels(['MEG0111']) ev_ref_grad = ev_ref.copy() ev_ref_grad.pick_channels(['MEG2643', 'MEG1622']) assert_allclose(ev_mag.data, ev_ref_mag.data, rtol=0, atol=1e-15) assert (ev_grad.ch_names[::(- 1)] == ev_ref_grad.ch_names) assert_allclose(ev_grad.data[::(- 1)], ev_ref_grad.data, rtol=0, atol=1e-13)<|docstring|>Test averaging with AcqParserFIF vs. Elekta software.<|endoftext|>
68a3b02f24af8184aedfa7d6b59031b7c1e9c52b228c51d72a52091a2c719253
def test_shift_time_events(): 'Test events latency shift by a given amount.' events = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) EXPECTED = [1, 2, 3] new_events = shift_time_events(events, ids=None, tshift=1, sfreq=1) assert all((new_events[(:, 0)] == EXPECTED)) events = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) EXPECTED = [0, 2, 3] new_events = shift_time_events(events, ids=[1, 2], tshift=1, sfreq=1) assert all((new_events[(:, 0)] == EXPECTED))
Test events latency shift by a given amount.
mne/tests/test_event.py
test_shift_time_events
hofaflo/mne-python
1,953
python
def test_shift_time_events(): events = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) EXPECTED = [1, 2, 3] new_events = shift_time_events(events, ids=None, tshift=1, sfreq=1) assert all((new_events[(:, 0)] == EXPECTED)) events = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) EXPECTED = [0, 2, 3] new_events = shift_time_events(events, ids=[1, 2], tshift=1, sfreq=1) assert all((new_events[(:, 0)] == EXPECTED))
def test_shift_time_events(): events = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) EXPECTED = [1, 2, 3] new_events = shift_time_events(events, ids=None, tshift=1, sfreq=1) assert all((new_events[(:, 0)] == EXPECTED)) events = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) EXPECTED = [0, 2, 3] new_events = shift_time_events(events, ids=[1, 2], tshift=1, sfreq=1) assert all((new_events[(:, 0)] == EXPECTED))<|docstring|>Test events latency shift by a given amount.<|endoftext|>
07869b7ecb45753484082eb64f48e6c78f9d9b7e197c07236cc844647d33dc37
def display(self, string, direction=None): 'Outputs the given string to the UI.' if (direction is None): cursor = '' elif (direction == 'in'): cursor = '<<< ' elif (direction == 'out'): cursor = '>>> ' output = (((self.output.text + u'\n') + cursor) + string) self.output.document = Document(text=output, cursor_position=len(output))
Outputs the given string to the UI.
wsh/connection.py
display
pinntech/wsh
0
python
def display(self, string, direction=None): if (direction is None): cursor = elif (direction == 'in'): cursor = '<<< ' elif (direction == 'out'): cursor = '>>> ' output = (((self.output.text + u'\n') + cursor) + string) self.output.document = Document(text=output, cursor_position=len(output))
def display(self, string, direction=None): if (direction is None): cursor = elif (direction == 'in'): cursor = '<<< ' elif (direction == 'out'): cursor = '>>> ' output = (((self.output.text + u'\n') + cursor) + string) self.output.document = Document(text=output, cursor_position=len(output))<|docstring|>Outputs the given string to the UI.<|endoftext|>
ecfccf6b998ba4002e3ec8cfbf5719700912aefacdb6f20a79c8018a5634e3f2
def info(self, string): 'Output given string as info, which is a right justified text element.' width = click.get_terminal_size()[0] output = string.rjust(width) output = ((self.output.text + '\n') + output) self.output.document = Document(text=output, cursor_position=len(output))
Output given string as info, which is a right justified text element.
wsh/connection.py
info
pinntech/wsh
0
python
def info(self, string): width = click.get_terminal_size()[0] output = string.rjust(width) output = ((self.output.text + '\n') + output) self.output.document = Document(text=output, cursor_position=len(output))
def info(self, string): width = click.get_terminal_size()[0] output = string.rjust(width) output = ((self.output.text + '\n') + output) self.output.document = Document(text=output, cursor_position=len(output))<|docstring|>Output given string as info, which is a right justified text element.<|endoftext|>
2f1c39e737357af03e58e30ce6b6ad82865bb89bdfabe050b35e21cecb82b11d
def send(self, sender, **kw): 'Send a data payload to the server.' data = kw['data'] self.ws.send(data) try: json_data = json.loads(data) self.display('sent', direction='out') self.display(json.dumps(json_data, indent=2)) except Exception: self.display('sent', direction='out') self.display(data)
Send a data payload to the server.
wsh/connection.py
send
pinntech/wsh
0
python
def send(self, sender, **kw): data = kw['data'] self.ws.send(data) try: json_data = json.loads(data) self.display('sent', direction='out') self.display(json.dumps(json_data, indent=2)) except Exception: self.display('sent', direction='out') self.display(data)
def send(self, sender, **kw): data = kw['data'] self.ws.send(data) try: json_data = json.loads(data) self.display('sent', direction='out') self.display(json.dumps(json_data, indent=2)) except Exception: self.display('sent', direction='out') self.display(data)<|docstring|>Send a data payload to the server.<|endoftext|>
271baa7f9a01bbdf1c31bc44df3182b13259d29c28393fd52373f9a5335b335a
def close(self, sender, **kw): 'Close connection to the server.' self.ws.close()
Close connection to the server.
wsh/connection.py
close
pinntech/wsh
0
python
def close(self, sender, **kw): self.ws.close()
def close(self, sender, **kw): self.ws.close()<|docstring|>Close connection to the server.<|endoftext|>
02203531afcc8324063a03fbd36d5df5b9d7e31b8a76855547b83f54b064760b
def die(message): '\n Print error and dies\n ' logger.error(message) sys.exit(errno.EAGAIN)
Print error and dies
core/utils.py
die
brezerk/book_analyzer
0
python
def die(message): '\n \n ' logger.error(message) sys.exit(errno.EAGAIN)
def die(message): '\n \n ' logger.error(message) sys.exit(errno.EAGAIN)<|docstring|>Print error and dies<|endoftext|>
87aeef36a75f5b7df6970de5f5c977fb61f73cb87ed7cd5d77fedc2ccf632fda
@distributed_trace def list(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> Iterable['_models.PrivateLinkResourceListResult']: 'Returns the list of private link resources.\n\n :param resource_group_name: The name of the resource group containing the Kusto cluster.\n :type resource_group_name: str\n :param cluster_name: The name of the Kusto cluster.\n :type cluster_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either PrivateLinkResourceListResult or the result of\n cls(response)\n :rtype:\n ~azure.core.paging.ItemPaged[~kusto_management_client.models.PrivateLinkResourceListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if (not next_link): request = build_list_request(subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, cluster_name=cluster_name, template_url=self.list.metadata['url']) request = _convert_request(request) request.url = self._client.format_url(request.url) else: request = build_list_request(subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, cluster_name=cluster_name, template_url=next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = 'GET' return request def extract_data(pipeline_response): deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return (None, iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data)
Returns the list of private link resources. :param resource_group_name: The name of the resource group containing the Kusto cluster. :type resource_group_name: str :param cluster_name: The name of the Kusto cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateLinkResourceListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~kusto_management_client.models.PrivateLinkResourceListResult] :raises: ~azure.core.exceptions.HttpResponseError
sdk/kusto/azure-mgmt-kusto/azure/mgmt/kusto/operations/_private_link_resources_operations.py
list
automagically/azure-sdk-for-python
1
python
@distributed_trace def list(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> Iterable['_models.PrivateLinkResourceListResult']: 'Returns the list of private link resources.\n\n :param resource_group_name: The name of the resource group containing the Kusto cluster.\n :type resource_group_name: str\n :param cluster_name: The name of the Kusto cluster.\n :type cluster_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either PrivateLinkResourceListResult or the result of\n cls(response)\n :rtype:\n ~azure.core.paging.ItemPaged[~kusto_management_client.models.PrivateLinkResourceListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if (not next_link): request = build_list_request(subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, cluster_name=cluster_name, template_url=self.list.metadata['url']) request = _convert_request(request) request.url = self._client.format_url(request.url) else: request = build_list_request(subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, cluster_name=cluster_name, template_url=next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = 'GET' return request def extract_data(pipeline_response): deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return (None, iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data)
@distributed_trace def list(self, resource_group_name: str, cluster_name: str, **kwargs: Any) -> Iterable['_models.PrivateLinkResourceListResult']: 'Returns the list of private link resources.\n\n :param resource_group_name: The name of the resource group containing the Kusto cluster.\n :type resource_group_name: str\n :param cluster_name: The name of the Kusto cluster.\n :type cluster_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either PrivateLinkResourceListResult or the result of\n cls(response)\n :rtype:\n ~azure.core.paging.ItemPaged[~kusto_management_client.models.PrivateLinkResourceListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if (not next_link): request = build_list_request(subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, cluster_name=cluster_name, template_url=self.list.metadata['url']) request = _convert_request(request) request.url = self._client.format_url(request.url) else: request = build_list_request(subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, cluster_name=cluster_name, template_url=next_link) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = 'GET' return request def extract_data(pipeline_response): deserialized = self._deserialize('PrivateLinkResourceListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return (None, iter(list_of_elem)) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged(get_next, extract_data)<|docstring|>Returns the list of private link resources. :param resource_group_name: The name of the resource group containing the Kusto cluster. :type resource_group_name: str :param cluster_name: The name of the Kusto cluster. :type cluster_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either PrivateLinkResourceListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~kusto_management_client.models.PrivateLinkResourceListResult] :raises: ~azure.core.exceptions.HttpResponseError<|endoftext|>
96d5998ac13934e877068652dff18529ce3d7d2f9096d663a208b0ff8e891a86
@distributed_trace def get(self, resource_group_name: str, cluster_name: str, private_link_resource_name: str, **kwargs: Any) -> '_models.PrivateLinkResource': 'Gets a private link resource.\n\n :param resource_group_name: The name of the resource group containing the Kusto cluster.\n :type resource_group_name: str\n :param cluster_name: The name of the Kusto cluster.\n :type cluster_name: str\n :param private_link_resource_name: The name of the private link resource.\n :type private_link_resource_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: PrivateLinkResource, or the result of cls(response)\n :rtype: ~kusto_management_client.models.PrivateLinkResource\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) request = build_get_request(subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, cluster_name=cluster_name, private_link_resource_name=private_link_resource_name, template_url=self.get.metadata['url']) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PrivateLinkResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
Gets a private link resource. :param resource_group_name: The name of the resource group containing the Kusto cluster. :type resource_group_name: str :param cluster_name: The name of the Kusto cluster. :type cluster_name: str :param private_link_resource_name: The name of the private link resource. :type private_link_resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateLinkResource, or the result of cls(response) :rtype: ~kusto_management_client.models.PrivateLinkResource :raises: ~azure.core.exceptions.HttpResponseError
sdk/kusto/azure-mgmt-kusto/azure/mgmt/kusto/operations/_private_link_resources_operations.py
get
automagically/azure-sdk-for-python
1
python
@distributed_trace def get(self, resource_group_name: str, cluster_name: str, private_link_resource_name: str, **kwargs: Any) -> '_models.PrivateLinkResource': 'Gets a private link resource.\n\n :param resource_group_name: The name of the resource group containing the Kusto cluster.\n :type resource_group_name: str\n :param cluster_name: The name of the Kusto cluster.\n :type cluster_name: str\n :param private_link_resource_name: The name of the private link resource.\n :type private_link_resource_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: PrivateLinkResource, or the result of cls(response)\n :rtype: ~kusto_management_client.models.PrivateLinkResource\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) request = build_get_request(subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, cluster_name=cluster_name, private_link_resource_name=private_link_resource_name, template_url=self.get.metadata['url']) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PrivateLinkResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
@distributed_trace def get(self, resource_group_name: str, cluster_name: str, private_link_resource_name: str, **kwargs: Any) -> '_models.PrivateLinkResource': 'Gets a private link resource.\n\n :param resource_group_name: The name of the resource group containing the Kusto cluster.\n :type resource_group_name: str\n :param cluster_name: The name of the Kusto cluster.\n :type cluster_name: str\n :param private_link_resource_name: The name of the private link resource.\n :type private_link_resource_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: PrivateLinkResource, or the result of cls(response)\n :rtype: ~kusto_management_client.models.PrivateLinkResource\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) request = build_get_request(subscription_id=self._config.subscription_id, resource_group_name=resource_group_name, cluster_name=cluster_name, private_link_resource_name=private_link_resource_name, template_url=self.get.metadata['url']) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('PrivateLinkResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized<|docstring|>Gets a private link resource. :param resource_group_name: The name of the resource group containing the Kusto cluster. :type resource_group_name: str :param cluster_name: The name of the Kusto cluster. :type cluster_name: str :param private_link_resource_name: The name of the private link resource. :type private_link_resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: PrivateLinkResource, or the result of cls(response) :rtype: ~kusto_management_client.models.PrivateLinkResource :raises: ~azure.core.exceptions.HttpResponseError<|endoftext|>
6c9012aec192b863e7c3ecd6da41011dde28b228981969629663fb003bdd54ad
def __init__(self, principalId): ' Constructor. ' self.principal = principal.Principal(principalId) self.grantedPrivileges = list() self.deniedPrivileges = list()
Constructor.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
__init__
schlauch/DataFinder
9
python
def __init__(self, principalId): ' ' self.principal = principal.Principal(principalId) self.grantedPrivileges = list() self.deniedPrivileges = list()
def __init__(self, principalId): ' ' self.principal = principal.Principal(principalId) self.grantedPrivileges = list() self.deniedPrivileges = list()<|docstring|>Constructor.<|endoftext|>
9c9e290fbddc2b9e9f25bf60355c2209b930a3b792bf88ab371cb5348c882142
def setUp(self): ' Creates the required test environment. ' self._principalMock = SimpleMock(identifier='id') self._acl = acl.AccessControlList()
Creates the required test environment.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
setUp
schlauch/DataFinder
9
python
def setUp(self): ' ' self._principalMock = SimpleMock(identifier='id') self._acl = acl.AccessControlList()
def setUp(self): ' ' self._principalMock = SimpleMock(identifier='id') self._acl = acl.AccessControlList()<|docstring|>Creates the required test environment.<|endoftext|>
f6e70d2e1ff2cc5fae7edb2150d96d769f96c1a8aa1a9c311d6da70c5beaa8ea
def testPrincipalsAttribute(self): ' Tests the principals attribute. ' self.assertEquals(self._acl.principals, list()) self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.principals, [self._principalMock]) principals = self._acl.principals principals.remove(self._principalMock) self.assertEquals(principals, list()) self.assertEquals(self._acl.principals, [self._principalMock])
Tests the principals attribute.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testPrincipalsAttribute
schlauch/DataFinder
9
python
def testPrincipalsAttribute(self): ' ' self.assertEquals(self._acl.principals, list()) self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.principals, [self._principalMock]) principals = self._acl.principals principals.remove(self._principalMock) self.assertEquals(principals, list()) self.assertEquals(self._acl.principals, [self._principalMock])
def testPrincipalsAttribute(self): ' ' self.assertEquals(self._acl.principals, list()) self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.principals, [self._principalMock]) principals = self._acl.principals principals.remove(self._principalMock) self.assertEquals(principals, list()) self.assertEquals(self._acl.principals, [self._principalMock])<|docstring|>Tests the principals attribute.<|endoftext|>
c5f7b8d64bdb26c49dd6859b47ad66e2da48aadff6f385e4d70e68c1becf0dc5
def testGrantPrivilege(self): ' Tests granting of privileges. ' self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.getGrantedPrivileges(self._principalMock), set([self._SUPPORTED_PRIVILEGE])) self.assertRaises(PrivilegeError, self._acl.grantPrivilege, self._principalMock, self._UNSUPPORTED_PRIVILEGE)
Tests granting of privileges.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testGrantPrivilege
schlauch/DataFinder
9
python
def testGrantPrivilege(self): ' ' self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.getGrantedPrivileges(self._principalMock), set([self._SUPPORTED_PRIVILEGE])) self.assertRaises(PrivilegeError, self._acl.grantPrivilege, self._principalMock, self._UNSUPPORTED_PRIVILEGE)
def testGrantPrivilege(self): ' ' self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.getGrantedPrivileges(self._principalMock), set([self._SUPPORTED_PRIVILEGE])) self.assertRaises(PrivilegeError, self._acl.grantPrivilege, self._principalMock, self._UNSUPPORTED_PRIVILEGE)<|docstring|>Tests granting of privileges.<|endoftext|>
b18116a6e8c841cde9ba3882039c84b35c62a99d16f1a1b3fcba735107f09580
def testDenyPrivilege(self): ' Tests denying of privileges. ' self._acl.denyPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.denyPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.denyPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.getDeniedPrivileges(self._principalMock), set([self._SUPPORTED_PRIVILEGE])) self.assertRaises(PrivilegeError, self._acl.denyPrivilege, self._principalMock, self._UNSUPPORTED_PRIVILEGE)
Tests denying of privileges.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testDenyPrivilege
schlauch/DataFinder
9
python
def testDenyPrivilege(self): ' ' self._acl.denyPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.denyPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.denyPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.getDeniedPrivileges(self._principalMock), set([self._SUPPORTED_PRIVILEGE])) self.assertRaises(PrivilegeError, self._acl.denyPrivilege, self._principalMock, self._UNSUPPORTED_PRIVILEGE)
def testDenyPrivilege(self): ' ' self._acl.denyPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.denyPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self._acl.denyPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.getDeniedPrivileges(self._principalMock), set([self._SUPPORTED_PRIVILEGE])) self.assertRaises(PrivilegeError, self._acl.denyPrivilege, self._principalMock, self._UNSUPPORTED_PRIVILEGE)<|docstring|>Tests denying of privileges.<|endoftext|>
14c37fa2b631364a02eef0d1cf4672fe727b24416054b2cdd22e4f612bf497fc
def testToPersistenceFormat(self): ' Tests the mapping into the persistence format. ' self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.getGrantedPrivileges(self._principalMock), set([self._SUPPORTED_PRIVILEGE])) self.assertEquals(len(self._acl.toPersistenceFormat()), 1)
Tests the mapping into the persistence format.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testToPersistenceFormat
schlauch/DataFinder
9
python
def testToPersistenceFormat(self): ' ' self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.getGrantedPrivileges(self._principalMock), set([self._SUPPORTED_PRIVILEGE])) self.assertEquals(len(self._acl.toPersistenceFormat()), 1)
def testToPersistenceFormat(self): ' ' self._acl.grantPrivilege(self._principalMock, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl.getGrantedPrivileges(self._principalMock), set([self._SUPPORTED_PRIVILEGE])) self.assertEquals(len(self._acl.toPersistenceFormat()), 1)<|docstring|>Tests the mapping into the persistence format.<|endoftext|>
9c12517aed1c3397d76b2494bbcabe7cbfe82e19942e9e6e90ec742b95fd06f6
def testCreate(self): ' Tests the creation of ACL. ' newAcl = self._acl.create([_PersistenceAceMock('a'), _PersistenceAceMock('b'), _PersistenceAceMock('c')]) self.assertEquals(len(newAcl.principals), 3) invalidPrivAce = _PersistenceAceMock('a') invalidPrivAce.grantedPrivileges = [self._UNSUPPORTED_PRIVILEGE] self.assertRaises(PrivilegeError, self._acl.create, [invalidPrivAce]) invalidPrincipalAce = _PersistenceAceMock('a') invalidPrincipalAce.principal = SimpleMock('a') self.assertRaises(PrincipalError, self._acl.create, [invalidPrincipalAce])
Tests the creation of ACL.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testCreate
schlauch/DataFinder
9
python
def testCreate(self): ' ' newAcl = self._acl.create([_PersistenceAceMock('a'), _PersistenceAceMock('b'), _PersistenceAceMock('c')]) self.assertEquals(len(newAcl.principals), 3) invalidPrivAce = _PersistenceAceMock('a') invalidPrivAce.grantedPrivileges = [self._UNSUPPORTED_PRIVILEGE] self.assertRaises(PrivilegeError, self._acl.create, [invalidPrivAce]) invalidPrincipalAce = _PersistenceAceMock('a') invalidPrincipalAce.principal = SimpleMock('a') self.assertRaises(PrincipalError, self._acl.create, [invalidPrincipalAce])
def testCreate(self): ' ' newAcl = self._acl.create([_PersistenceAceMock('a'), _PersistenceAceMock('b'), _PersistenceAceMock('c')]) self.assertEquals(len(newAcl.principals), 3) invalidPrivAce = _PersistenceAceMock('a') invalidPrivAce.grantedPrivileges = [self._UNSUPPORTED_PRIVILEGE] self.assertRaises(PrivilegeError, self._acl.create, [invalidPrivAce]) invalidPrincipalAce = _PersistenceAceMock('a') invalidPrincipalAce.principal = SimpleMock('a') self.assertRaises(PrincipalError, self._acl.create, [invalidPrincipalAce])<|docstring|>Tests the creation of ACL.<|endoftext|>
002a896ed6f9db1fae85a2930a39fa24e051eed6990ef6339a971218959e56e9
def testComparison(self): ' Tests the comparison of two instances. ' self.assertEquals(self._acl, self._acl) anotherAcl = acl.AccessControlList() self.assertEquals(self._acl, anotherAcl) aPrincipal = SimpleMock(identifier='aPrincipal') anotherAcl.grantPrivilege(aPrincipal, self._SUPPORTED_PRIVILEGE) self.assertNotEquals(self._acl, anotherAcl) self._acl.grantPrivilege(aPrincipal, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl, anotherAcl) anotherPrincipal = SimpleMock(identifier='anotherPrincipal') self._acl.grantPrivilege(anotherPrincipal, self._SUPPORTED_PRIVILEGE) anotherAcl.grantPrivilege(anotherPrincipal, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl, anotherAcl) self._acl.setIndex(aPrincipal, 1) self.assertNotEquals(self._acl, anotherAcl) self.assertEquals(self._acl, deepcopy(self._acl))
Tests the comparison of two instances.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testComparison
schlauch/DataFinder
9
python
def testComparison(self): ' ' self.assertEquals(self._acl, self._acl) anotherAcl = acl.AccessControlList() self.assertEquals(self._acl, anotherAcl) aPrincipal = SimpleMock(identifier='aPrincipal') anotherAcl.grantPrivilege(aPrincipal, self._SUPPORTED_PRIVILEGE) self.assertNotEquals(self._acl, anotherAcl) self._acl.grantPrivilege(aPrincipal, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl, anotherAcl) anotherPrincipal = SimpleMock(identifier='anotherPrincipal') self._acl.grantPrivilege(anotherPrincipal, self._SUPPORTED_PRIVILEGE) anotherAcl.grantPrivilege(anotherPrincipal, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl, anotherAcl) self._acl.setIndex(aPrincipal, 1) self.assertNotEquals(self._acl, anotherAcl) self.assertEquals(self._acl, deepcopy(self._acl))
def testComparison(self): ' ' self.assertEquals(self._acl, self._acl) anotherAcl = acl.AccessControlList() self.assertEquals(self._acl, anotherAcl) aPrincipal = SimpleMock(identifier='aPrincipal') anotherAcl.grantPrivilege(aPrincipal, self._SUPPORTED_PRIVILEGE) self.assertNotEquals(self._acl, anotherAcl) self._acl.grantPrivilege(aPrincipal, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl, anotherAcl) anotherPrincipal = SimpleMock(identifier='anotherPrincipal') self._acl.grantPrivilege(anotherPrincipal, self._SUPPORTED_PRIVILEGE) anotherAcl.grantPrivilege(anotherPrincipal, self._SUPPORTED_PRIVILEGE) self.assertEquals(self._acl, anotherAcl) self._acl.setIndex(aPrincipal, 1) self.assertNotEquals(self._acl, anotherAcl) self.assertEquals(self._acl, deepcopy(self._acl))<|docstring|>Tests the comparison of two instances.<|endoftext|>
3650daee8045826de993190a9c83e3f86138b64d866ecc45fcf1232ca2cdeaa9
def testContentAccessLevel(self): ' Checks content access level handling. ' self._acl.setContentAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setContentAccessLevel(self._principalMock, READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setContentAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), FULL_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL)
Checks content access level handling.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testContentAccessLevel
schlauch/DataFinder
9
python
def testContentAccessLevel(self): ' ' self._acl.setContentAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setContentAccessLevel(self._principalMock, READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setContentAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), FULL_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL)
def testContentAccessLevel(self): ' ' self._acl.setContentAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setContentAccessLevel(self._principalMock, READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setContentAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), FULL_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL)<|docstring|>Checks content access level handling.<|endoftext|>
05e80fe250d22f36772eee5143dd5eb6d58fa89f439a9429e3bbaaa13e73bc52
def testPropertiesAccessLevel(self): ' Checks properties access level handling. ' self._acl.setPropertiesAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setPropertiesAccessLevel(self._principalMock, READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setPropertiesAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), FULL_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL)
Checks properties access level handling.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testPropertiesAccessLevel
schlauch/DataFinder
9
python
def testPropertiesAccessLevel(self): ' ' self._acl.setPropertiesAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setPropertiesAccessLevel(self._principalMock, READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setPropertiesAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), FULL_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL)
def testPropertiesAccessLevel(self): ' ' self._acl.setPropertiesAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setPropertiesAccessLevel(self._principalMock, READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setPropertiesAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), FULL_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL)<|docstring|>Checks properties access level handling.<|endoftext|>
2c58fe73c2c66cead5b164d0f301f3a62f6a9f363146e840924faddc99b15fb6
def testAdministrationAccessLevel(self): ' Checks administration access level handling. ' self._acl.setAdministrationAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setAdministrationAccessLevel(self._principalMock, READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self._acl.setAdministrationAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), FULL_ACCESS_LEVEL)
Checks administration access level handling.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testAdministrationAccessLevel
schlauch/DataFinder
9
python
def testAdministrationAccessLevel(self): ' ' self._acl.setAdministrationAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setAdministrationAccessLevel(self._principalMock, READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self._acl.setAdministrationAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), FULL_ACCESS_LEVEL)
def testAdministrationAccessLevel(self): ' ' self._acl.setAdministrationAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self._acl.setAdministrationAccessLevel(self._principalMock, READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self._acl.setAdministrationAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), NONE_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), FULL_ACCESS_LEVEL)<|docstring|>Checks administration access level handling.<|endoftext|>
bfd5b30f23f0a40452d5464db5e40e2af0732ec21e64e9d7be409548289cce80
def testClearPrivileges(self): ' Tests clearing of privileges. ' self._acl.setAdministrationAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(len(self._acl.principals), 1) self._acl.clearPrivileges(self._principalMock) self.assertEquals(len(self._acl.principals), 0)
Tests clearing of privileges.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testClearPrivileges
schlauch/DataFinder
9
python
def testClearPrivileges(self): ' ' self._acl.setAdministrationAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(len(self._acl.principals), 1) self._acl.clearPrivileges(self._principalMock) self.assertEquals(len(self._acl.principals), 0)
def testClearPrivileges(self): ' ' self._acl.setAdministrationAccessLevel(self._principalMock, NONE_ACCESS_LEVEL) self.assertEquals(len(self._acl.principals), 1) self._acl.clearPrivileges(self._principalMock) self.assertEquals(len(self._acl.principals), 0)<|docstring|>Tests clearing of privileges.<|endoftext|>
b6fd088778c7cc4b75eee714bffabab2774733fcfb3edd75aad93b7e6e72ac57
def testIndex(self): ' Tests the index handling. ' self._acl.setContentAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.getIndex(self._principalMock), 0) anotherPrincipal = SimpleMock(identifier='anotherPrincipal') self._acl.setContentAccessLevel(anotherPrincipal, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.getIndex(anotherPrincipal), 1) self._acl.setIndex(self._principalMock, 1) self.assertEquals(self._acl.getIndex(anotherPrincipal), 0) self.assertEquals(self._acl.getIndex(self._principalMock), 1) self._acl.setIndex(anotherPrincipal, 3) self.assertEquals(self._acl.getIndex(anotherPrincipal), 1) self.assertEquals(self._acl.getIndex(self._principalMock), 0) self._acl.clearPrivileges(self._principalMock) self._acl.clearPrivileges(anotherPrincipal) self.assertRaises(ValueError, self._acl.getIndex, self._principalMock)
Tests the index handling.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testIndex
schlauch/DataFinder
9
python
def testIndex(self): ' ' self._acl.setContentAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.getIndex(self._principalMock), 0) anotherPrincipal = SimpleMock(identifier='anotherPrincipal') self._acl.setContentAccessLevel(anotherPrincipal, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.getIndex(anotherPrincipal), 1) self._acl.setIndex(self._principalMock, 1) self.assertEquals(self._acl.getIndex(anotherPrincipal), 0) self.assertEquals(self._acl.getIndex(self._principalMock), 1) self._acl.setIndex(anotherPrincipal, 3) self.assertEquals(self._acl.getIndex(anotherPrincipal), 1) self.assertEquals(self._acl.getIndex(self._principalMock), 0) self._acl.clearPrivileges(self._principalMock) self._acl.clearPrivileges(anotherPrincipal) self.assertRaises(ValueError, self._acl.getIndex, self._principalMock)
def testIndex(self): ' ' self._acl.setContentAccessLevel(self._principalMock, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.getIndex(self._principalMock), 0) anotherPrincipal = SimpleMock(identifier='anotherPrincipal') self._acl.setContentAccessLevel(anotherPrincipal, FULL_ACCESS_LEVEL) self.assertEquals(self._acl.getIndex(anotherPrincipal), 1) self._acl.setIndex(self._principalMock, 1) self.assertEquals(self._acl.getIndex(anotherPrincipal), 0) self.assertEquals(self._acl.getIndex(self._principalMock), 1) self._acl.setIndex(anotherPrincipal, 3) self.assertEquals(self._acl.getIndex(anotherPrincipal), 1) self.assertEquals(self._acl.getIndex(self._principalMock), 0) self._acl.clearPrivileges(self._principalMock) self._acl.clearPrivileges(anotherPrincipal) self.assertRaises(ValueError, self._acl.getIndex, self._principalMock)<|docstring|>Tests the index handling.<|endoftext|>
a0569816ee175bbd9a284a1b1a8d7cc28c7f09f2c6d14def537860a920f62b0f
def testAddDefaultPrincipal(self): ' Tests the default principal adding method. ' self._acl.addDefaultPrincipal(self._principalMock) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL)
Tests the default principal adding method.
test/unittest/datafinder_test/core/item/privileges/acl_test.py
testAddDefaultPrincipal
schlauch/DataFinder
9
python
def testAddDefaultPrincipal(self): ' ' self._acl.addDefaultPrincipal(self._principalMock) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL)
def testAddDefaultPrincipal(self): ' ' self._acl.addDefaultPrincipal(self._principalMock) self.assertEquals(self._acl.contentAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.propertiesAccessLevel(self._principalMock), READ_ONLY_ACCESS_LEVEL) self.assertEquals(self._acl.administrationAccessLevel(self._principalMock), NONE_ACCESS_LEVEL)<|docstring|>Tests the default principal adding method.<|endoftext|>
82d5d3feed478510698b73a7b907acd41acb424c758a8eea6e11a53c0334d57e
def setup(bot: tbb.TravusBotBase): 'Setup function ran when module is loaded.' bot.add_cog(CoreFunctionalityCog(bot)) bot.add_command_help(CoreFunctionalityCog.botconfig_prefix, 'Core', None, ['$', 'bot!', 'bot ?', 'remove']) bot.add_command_help(CoreFunctionalityCog.botconfig_deletemessages, 'Core', None, ['enable', 'y', 'disable', 'n']) bot.add_command_help(CoreFunctionalityCog.module_list, 'Core', {'perms': ['Administrator']}, ['']) bot.add_command_help(CoreFunctionalityCog.module_load, 'Core', {'perms': ['Administrator']}, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.module_unload, 'Core', {'perms': ['Administrator']}, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.module_reload, 'Core', {'perms': ['Administrator']}, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.default, 'Core', None, ['list', 'add', 'remove']) bot.add_command_help(CoreFunctionalityCog.default_list, 'Core', None, ['']) bot.add_command_help(CoreFunctionalityCog.default_add, 'Core', None, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.default_remove, 'Core', None, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.command_enable, 'Core', {'perms': ['Administrator']}, ['balance', 'pay']) bot.add_command_help(CoreFunctionalityCog.command_disable, 'Core', {'perms': ['Administrator']}, ['balance', 'pay']) bot.add_command_help(CoreFunctionalityCog.command_show, 'Core', {'perms': ['Administrator']}, ['module', 'balance']) bot.add_command_help(CoreFunctionalityCog.command_hide, 'Core', {'perms': ['Administrator']}, ['module', 'balance']) bot.add_command_help(CoreFunctionalityCog.about, 'Core', None, ['', 'fun']) bot.add_command_help(CoreFunctionalityCog.usage, 'Core', None, ['', 'dev']) bot.add_command_help(CoreFunctionalityCog.config, 'Core', {'perms': ['Administrator']}, ['get', 'set', 'unset']) bot.add_command_help(CoreFunctionalityCog.config_get, 'Core', {'perms': ['Administrator']}, ['alert_channel']) bot.add_command_help(CoreFunctionalityCog.config_unset, 'Core', {'perms': ['Administrator']}, ['alert_channel']) bot.add_command_help(CoreFunctionalityCog.shutdown, 'Core', None, ['', '1h', '1h30m', '10m-30s', '2m30s']) bot.add_command_help(CoreFunctionalityCog.botconfig, 'Core', None, ['prefix', 'deletemessages', 'description', 'credits']) bot.add_command_help(CoreFunctionalityCog.botconfig_description, 'Core', None, ['remove', 'This is a sample description.']) bot.add_command_help(CoreFunctionalityCog.module, 'Core', {'perms': ['Administrator']}, ['list', 'load', 'unload', 'reload']) bot.add_command_help(CoreFunctionalityCog.command, 'Core', {'perms': ['Administrator']}, ['enable', 'disable', 'show', 'hide']) bot.add_command_help(CoreFunctionalityCog.config_set, 'Core', {'perms': ['Administrator']}, ['alert_channel 353246496952418305']) bot.add_command_help(CoreFunctionalityCog.botconfig_credits, 'Core', None, ['remove', '`\n```\n[Person](URL):\n\tBot Profile Image\n``'])
Setup function ran when module is loaded.
core_commands.py
setup
Travus/Travus_Bot_Base
2
python
def setup(bot: tbb.TravusBotBase): bot.add_cog(CoreFunctionalityCog(bot)) bot.add_command_help(CoreFunctionalityCog.botconfig_prefix, 'Core', None, ['$', 'bot!', 'bot ?', 'remove']) bot.add_command_help(CoreFunctionalityCog.botconfig_deletemessages, 'Core', None, ['enable', 'y', 'disable', 'n']) bot.add_command_help(CoreFunctionalityCog.module_list, 'Core', {'perms': ['Administrator']}, []) bot.add_command_help(CoreFunctionalityCog.module_load, 'Core', {'perms': ['Administrator']}, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.module_unload, 'Core', {'perms': ['Administrator']}, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.module_reload, 'Core', {'perms': ['Administrator']}, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.default, 'Core', None, ['list', 'add', 'remove']) bot.add_command_help(CoreFunctionalityCog.default_list, 'Core', None, []) bot.add_command_help(CoreFunctionalityCog.default_add, 'Core', None, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.default_remove, 'Core', None, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.command_enable, 'Core', {'perms': ['Administrator']}, ['balance', 'pay']) bot.add_command_help(CoreFunctionalityCog.command_disable, 'Core', {'perms': ['Administrator']}, ['balance', 'pay']) bot.add_command_help(CoreFunctionalityCog.command_show, 'Core', {'perms': ['Administrator']}, ['module', 'balance']) bot.add_command_help(CoreFunctionalityCog.command_hide, 'Core', {'perms': ['Administrator']}, ['module', 'balance']) bot.add_command_help(CoreFunctionalityCog.about, 'Core', None, [, 'fun']) bot.add_command_help(CoreFunctionalityCog.usage, 'Core', None, [, 'dev']) bot.add_command_help(CoreFunctionalityCog.config, 'Core', {'perms': ['Administrator']}, ['get', 'set', 'unset']) bot.add_command_help(CoreFunctionalityCog.config_get, 'Core', {'perms': ['Administrator']}, ['alert_channel']) bot.add_command_help(CoreFunctionalityCog.config_unset, 'Core', {'perms': ['Administrator']}, ['alert_channel']) bot.add_command_help(CoreFunctionalityCog.shutdown, 'Core', None, [, '1h', '1h30m', '10m-30s', '2m30s']) bot.add_command_help(CoreFunctionalityCog.botconfig, 'Core', None, ['prefix', 'deletemessages', 'description', 'credits']) bot.add_command_help(CoreFunctionalityCog.botconfig_description, 'Core', None, ['remove', 'This is a sample description.']) bot.add_command_help(CoreFunctionalityCog.module, 'Core', {'perms': ['Administrator']}, ['list', 'load', 'unload', 'reload']) bot.add_command_help(CoreFunctionalityCog.command, 'Core', {'perms': ['Administrator']}, ['enable', 'disable', 'show', 'hide']) bot.add_command_help(CoreFunctionalityCog.config_set, 'Core', {'perms': ['Administrator']}, ['alert_channel 353246496952418305']) bot.add_command_help(CoreFunctionalityCog.botconfig_credits, 'Core', None, ['remove', '`\n```\n[Person](URL):\n\tBot Profile Image\n``'])
def setup(bot: tbb.TravusBotBase): bot.add_cog(CoreFunctionalityCog(bot)) bot.add_command_help(CoreFunctionalityCog.botconfig_prefix, 'Core', None, ['$', 'bot!', 'bot ?', 'remove']) bot.add_command_help(CoreFunctionalityCog.botconfig_deletemessages, 'Core', None, ['enable', 'y', 'disable', 'n']) bot.add_command_help(CoreFunctionalityCog.module_list, 'Core', {'perms': ['Administrator']}, []) bot.add_command_help(CoreFunctionalityCog.module_load, 'Core', {'perms': ['Administrator']}, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.module_unload, 'Core', {'perms': ['Administrator']}, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.module_reload, 'Core', {'perms': ['Administrator']}, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.default, 'Core', None, ['list', 'add', 'remove']) bot.add_command_help(CoreFunctionalityCog.default_list, 'Core', None, []) bot.add_command_help(CoreFunctionalityCog.default_add, 'Core', None, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.default_remove, 'Core', None, ['fun', 'economy']) bot.add_command_help(CoreFunctionalityCog.command_enable, 'Core', {'perms': ['Administrator']}, ['balance', 'pay']) bot.add_command_help(CoreFunctionalityCog.command_disable, 'Core', {'perms': ['Administrator']}, ['balance', 'pay']) bot.add_command_help(CoreFunctionalityCog.command_show, 'Core', {'perms': ['Administrator']}, ['module', 'balance']) bot.add_command_help(CoreFunctionalityCog.command_hide, 'Core', {'perms': ['Administrator']}, ['module', 'balance']) bot.add_command_help(CoreFunctionalityCog.about, 'Core', None, [, 'fun']) bot.add_command_help(CoreFunctionalityCog.usage, 'Core', None, [, 'dev']) bot.add_command_help(CoreFunctionalityCog.config, 'Core', {'perms': ['Administrator']}, ['get', 'set', 'unset']) bot.add_command_help(CoreFunctionalityCog.config_get, 'Core', {'perms': ['Administrator']}, ['alert_channel']) bot.add_command_help(CoreFunctionalityCog.config_unset, 'Core', {'perms': ['Administrator']}, ['alert_channel']) bot.add_command_help(CoreFunctionalityCog.shutdown, 'Core', None, [, '1h', '1h30m', '10m-30s', '2m30s']) bot.add_command_help(CoreFunctionalityCog.botconfig, 'Core', None, ['prefix', 'deletemessages', 'description', 'credits']) bot.add_command_help(CoreFunctionalityCog.botconfig_description, 'Core', None, ['remove', 'This is a sample description.']) bot.add_command_help(CoreFunctionalityCog.module, 'Core', {'perms': ['Administrator']}, ['list', 'load', 'unload', 'reload']) bot.add_command_help(CoreFunctionalityCog.command, 'Core', {'perms': ['Administrator']}, ['enable', 'disable', 'show', 'hide']) bot.add_command_help(CoreFunctionalityCog.config_set, 'Core', {'perms': ['Administrator']}, ['alert_channel 353246496952418305']) bot.add_command_help(CoreFunctionalityCog.botconfig_credits, 'Core', None, ['remove', '`\n```\n[Person](URL):\n\tBot Profile Image\n``'])<|docstring|>Setup function ran when module is loaded.<|endoftext|>
cd8cf89e7e4a08859d6ea7f08f8567e02b7aa7530a8ce1f3a9ea129efe4034ae
def teardown(bot: tbb.TravusBotBase): 'Teardown function ran when module is unloaded.' bot.remove_cog('CoreFunctionalityCog') bot.remove_command_help(CoreFunctionalityCog)
Teardown function ran when module is unloaded.
core_commands.py
teardown
Travus/Travus_Bot_Base
2
python
def teardown(bot: tbb.TravusBotBase): bot.remove_cog('CoreFunctionalityCog') bot.remove_command_help(CoreFunctionalityCog)
def teardown(bot: tbb.TravusBotBase): bot.remove_cog('CoreFunctionalityCog') bot.remove_command_help(CoreFunctionalityCog)<|docstring|>Teardown function ran when module is unloaded.<|endoftext|>
f894926d6e4b862691f7681484a0c8dc81f498ac7479f248b678b9dea85feb4c
def __init__(self, bot: tbb.TravusBotBase): 'Initialization function loading bot object for cog.' self.bot = bot self.log = logging.getLogger('core_commands') self.log.setLevel(logging.INFO)
Initialization function loading bot object for cog.
core_commands.py
__init__
Travus/Travus_Bot_Base
2
python
def __init__(self, bot: tbb.TravusBotBase): self.bot = bot self.log = logging.getLogger('core_commands') self.log.setLevel(logging.INFO)
def __init__(self, bot: tbb.TravusBotBase): self.bot = bot self.log = logging.getLogger('core_commands') self.log.setLevel(logging.INFO)<|docstring|>Initialization function loading bot object for cog.<|endoftext|>
f88bcc80936b05349605d62937ca9cfaa751e6bb66f7958a6c824f898ba57cd6
async def _module_operation(self, ctx: commands.Context, operation: str, mod: str): 'To avoid code duplication in the except blocks all module command functionality is grouped together.' async def load(): 'Contains the logic for loading a module.' if (f'{mod}.py' in listdir('modules')): self.bot.load_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully loaded.')) self.log.info(f"{ctx.author.id}: loaded '{mod}' module.") else: (await ctx.send(f'No `{mod_name}` module was found.')) async def unload(): 'Contains the logic for unloading a module.' self.bot.unload_extension(f'modules.{mod}') (await ctx.send(f'Module `{mod_name}` successfully unloaded.')) self.log.info(f"{ctx.author.id}: unloaded '{mod}' module.") async def reload(): 'Contains the logic for reloading a module.' if (f'{mod}.py' in listdir('modules')): self.bot.reload_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully reloaded.')) self.log.info(f"{ctx.author.id}: reloaded '{mod}' module.") elif (mod in self.bot.modules): (await ctx.send(f'The `{mod_name}` module file is no longer found on disk. Reload canceled.')) else: (await ctx.send(f'No `{mod_name}` module was found.')) old_help = dict(self.bot.help) old_modules = dict(self.bot.modules) self.bot.extension_ctx = ctx mod_name = clean(ctx, mod, False, True) try: if (operation == 'load'): (await load()) elif (operation == 'unload'): (await unload()) elif (operation == 'reload'): (await reload()) except commands.ExtensionAlreadyLoaded: (await ctx.send(f'The `{mod_name}` module was already loaded.')) except commands.ExtensionNotLoaded: (await ctx.send(f'No `{mod_name}` module is loaded.')) except commands.ExtensionFailed as e: self.bot.help = old_help self.bot.modules = old_modules if isinstance(e.original, tbb.DependencyError): missing_deps = [f'`{clean(ctx, elem, False, True)}`' for elem in e.original.missing_dependencies] (await ctx.send(f"Module `{mod_name}` requires these missing dependencies: {', '.join(missing_deps)}")) else: (await ctx.send('**Error! Something went really wrong! Contact module maintainer.**\nError logged to console and stored in module error command.')) self.log.error(f'''{ctx.author.id}: tried loading '{mod}' module, and it failed: {str(e)}''') self.bot.last_module_error = f'''The `{clean(ctx, mod, False)}` module failed while loading. The error was: {clean(ctx, str(e))}''' except Exception as e: self.bot.help = old_help self.bot.modules = old_modules (await ctx.send('**Error! Something went really wrong! Contact module maintainer.**\nError logged to console and stored in module error command.')) if isinstance(e, commands.ExtensionNotFound): e = e.__cause__ self.log.error(f'''{ctx.author.id}: tried loading '{mod}' module, and it failed: {str(e)}''') self.bot.last_module_error = f'''The `{clean(ctx, mod, False)}` module failed while loading. The error was: {clean(ctx, str(e))}''' finally: self.bot.extension_ctx = None
To avoid code duplication in the except blocks all module command functionality is grouped together.
core_commands.py
_module_operation
Travus/Travus_Bot_Base
2
python
async def _module_operation(self, ctx: commands.Context, operation: str, mod: str): async def load(): 'Contains the logic for loading a module.' if (f'{mod}.py' in listdir('modules')): self.bot.load_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully loaded.')) self.log.info(f"{ctx.author.id}: loaded '{mod}' module.") else: (await ctx.send(f'No `{mod_name}` module was found.')) async def unload(): 'Contains the logic for unloading a module.' self.bot.unload_extension(f'modules.{mod}') (await ctx.send(f'Module `{mod_name}` successfully unloaded.')) self.log.info(f"{ctx.author.id}: unloaded '{mod}' module.") async def reload(): 'Contains the logic for reloading a module.' if (f'{mod}.py' in listdir('modules')): self.bot.reload_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully reloaded.')) self.log.info(f"{ctx.author.id}: reloaded '{mod}' module.") elif (mod in self.bot.modules): (await ctx.send(f'The `{mod_name}` module file is no longer found on disk. Reload canceled.')) else: (await ctx.send(f'No `{mod_name}` module was found.')) old_help = dict(self.bot.help) old_modules = dict(self.bot.modules) self.bot.extension_ctx = ctx mod_name = clean(ctx, mod, False, True) try: if (operation == 'load'): (await load()) elif (operation == 'unload'): (await unload()) elif (operation == 'reload'): (await reload()) except commands.ExtensionAlreadyLoaded: (await ctx.send(f'The `{mod_name}` module was already loaded.')) except commands.ExtensionNotLoaded: (await ctx.send(f'No `{mod_name}` module is loaded.')) except commands.ExtensionFailed as e: self.bot.help = old_help self.bot.modules = old_modules if isinstance(e.original, tbb.DependencyError): missing_deps = [f'`{clean(ctx, elem, False, True)}`' for elem in e.original.missing_dependencies] (await ctx.send(f"Module `{mod_name}` requires these missing dependencies: {', '.join(missing_deps)}")) else: (await ctx.send('**Error! Something went really wrong! Contact module maintainer.**\nError logged to console and stored in module error command.')) self.log.error(f'{ctx.author.id}: tried loading '{mod}' module, and it failed: {str(e)}') self.bot.last_module_error = f'The `{clean(ctx, mod, False)}` module failed while loading. The error was: {clean(ctx, str(e))}' except Exception as e: self.bot.help = old_help self.bot.modules = old_modules (await ctx.send('**Error! Something went really wrong! Contact module maintainer.**\nError logged to console and stored in module error command.')) if isinstance(e, commands.ExtensionNotFound): e = e.__cause__ self.log.error(f'{ctx.author.id}: tried loading '{mod}' module, and it failed: {str(e)}') self.bot.last_module_error = f'The `{clean(ctx, mod, False)}` module failed while loading. The error was: {clean(ctx, str(e))}' finally: self.bot.extension_ctx = None
async def _module_operation(self, ctx: commands.Context, operation: str, mod: str): async def load(): 'Contains the logic for loading a module.' if (f'{mod}.py' in listdir('modules')): self.bot.load_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully loaded.')) self.log.info(f"{ctx.author.id}: loaded '{mod}' module.") else: (await ctx.send(f'No `{mod_name}` module was found.')) async def unload(): 'Contains the logic for unloading a module.' self.bot.unload_extension(f'modules.{mod}') (await ctx.send(f'Module `{mod_name}` successfully unloaded.')) self.log.info(f"{ctx.author.id}: unloaded '{mod}' module.") async def reload(): 'Contains the logic for reloading a module.' if (f'{mod}.py' in listdir('modules')): self.bot.reload_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully reloaded.')) self.log.info(f"{ctx.author.id}: reloaded '{mod}' module.") elif (mod in self.bot.modules): (await ctx.send(f'The `{mod_name}` module file is no longer found on disk. Reload canceled.')) else: (await ctx.send(f'No `{mod_name}` module was found.')) old_help = dict(self.bot.help) old_modules = dict(self.bot.modules) self.bot.extension_ctx = ctx mod_name = clean(ctx, mod, False, True) try: if (operation == 'load'): (await load()) elif (operation == 'unload'): (await unload()) elif (operation == 'reload'): (await reload()) except commands.ExtensionAlreadyLoaded: (await ctx.send(f'The `{mod_name}` module was already loaded.')) except commands.ExtensionNotLoaded: (await ctx.send(f'No `{mod_name}` module is loaded.')) except commands.ExtensionFailed as e: self.bot.help = old_help self.bot.modules = old_modules if isinstance(e.original, tbb.DependencyError): missing_deps = [f'`{clean(ctx, elem, False, True)}`' for elem in e.original.missing_dependencies] (await ctx.send(f"Module `{mod_name}` requires these missing dependencies: {', '.join(missing_deps)}")) else: (await ctx.send('**Error! Something went really wrong! Contact module maintainer.**\nError logged to console and stored in module error command.')) self.log.error(f'{ctx.author.id}: tried loading '{mod}' module, and it failed: {str(e)}') self.bot.last_module_error = f'The `{clean(ctx, mod, False)}` module failed while loading. The error was: {clean(ctx, str(e))}' except Exception as e: self.bot.help = old_help self.bot.modules = old_modules (await ctx.send('**Error! Something went really wrong! Contact module maintainer.**\nError logged to console and stored in module error command.')) if isinstance(e, commands.ExtensionNotFound): e = e.__cause__ self.log.error(f'{ctx.author.id}: tried loading '{mod}' module, and it failed: {str(e)}') self.bot.last_module_error = f'The `{clean(ctx, mod, False)}` module failed while loading. The error was: {clean(ctx, str(e))}' finally: self.bot.extension_ctx = None<|docstring|>To avoid code duplication in the except blocks all module command functionality is grouped together.<|endoftext|>
dabcdec04110d9adb85bc35d0051ec46ef628e11fe6fbdc482a84a5ce731945d
@commands.is_owner() @commands.group(invoke_without_command=True, name='botconfig', usage='<prefix/deletemessages/description/credits>') async def botconfig(self, ctx: commands.Context): "This command sets the bot's prefix, command trigger deletion behaviour, description and additional credits\n section. Fore more information check the help entry of one of these subcommands; `prefix`, `deletemessages`,\n `description`, `credits`." raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')
This command sets the bot's prefix, command trigger deletion behaviour, description and additional credits section. Fore more information check the help entry of one of these subcommands; `prefix`, `deletemessages`, `description`, `credits`.
core_commands.py
botconfig
Travus/Travus_Bot_Base
2
python
@commands.is_owner() @commands.group(invoke_without_command=True, name='botconfig', usage='<prefix/deletemessages/description/credits>') async def botconfig(self, ctx: commands.Context): "This command sets the bot's prefix, command trigger deletion behaviour, description and additional credits\n section. Fore more information check the help entry of one of these subcommands; `prefix`, `deletemessages`,\n `description`, `credits`." raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')
@commands.is_owner() @commands.group(invoke_without_command=True, name='botconfig', usage='<prefix/deletemessages/description/credits>') async def botconfig(self, ctx: commands.Context): "This command sets the bot's prefix, command trigger deletion behaviour, description and additional credits\n section. Fore more information check the help entry of one of these subcommands; `prefix`, `deletemessages`,\n `description`, `credits`." raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')<|docstring|>This command sets the bot's prefix, command trigger deletion behaviour, description and additional credits section. Fore more information check the help entry of one of these subcommands; `prefix`, `deletemessages`, `description`, `credits`.<|endoftext|>
0df5c65e7f8ff4580f67443fb1e4c6081f57e8a52f4a30d3aaa0d8434b1c616a
@commands.is_owner() @botconfig.command(name='prefix', usage='<NEW PREFIX/remove>') async def botconfig_prefix(self, ctx: commands.Context, *, new_prefix: str): 'This command changes the bot prefix. The default prefix is `!`. Prefixes can be everything from symbols to\n words or a combination of the two, and can even include spaces, though they cannot start or end with spaces\n since Discord removes empty space at the start and end of messages. The prefix is saved across reboots. Setting\n the prefix to `remove` will remove the prefix. The bot will always listen to pings as if they were a prefix,\n regardless of if there is another prefix set or not. Maximum prefix length is 20.' if (len(new_prefix) > 20): (await ctx.send('The maximum prefix length is 20.')) return self.bot.prefix = (new_prefix if (new_prefix.lower() != 'remove') else None) activity = Activity(type=ActivityType.listening, name=(f'prefix: {new_prefix}' if (new_prefix.lower() != 'remove') else 'pings only')) (await self.bot.change_presence(activity=activity)) async with self.bot.db.acquire() as conn: (await conn.execute("UPDATE settings SET value = $1 WHERE key = 'prefix'", (new_prefix if (new_prefix.lower() != 'remove') else ''))) if (new_prefix.lower() != 'remove'): (await ctx.send(f'The bot prefix has successfully been changed to `{new_prefix}`.')) else: (await ctx.send('The bot is now only listens to pings.'))
This command changes the bot prefix. The default prefix is `!`. Prefixes can be everything from symbols to words or a combination of the two, and can even include spaces, though they cannot start or end with spaces since Discord removes empty space at the start and end of messages. The prefix is saved across reboots. Setting the prefix to `remove` will remove the prefix. The bot will always listen to pings as if they were a prefix, regardless of if there is another prefix set or not. Maximum prefix length is 20.
core_commands.py
botconfig_prefix
Travus/Travus_Bot_Base
2
python
@commands.is_owner() @botconfig.command(name='prefix', usage='<NEW PREFIX/remove>') async def botconfig_prefix(self, ctx: commands.Context, *, new_prefix: str): 'This command changes the bot prefix. The default prefix is `!`. Prefixes can be everything from symbols to\n words or a combination of the two, and can even include spaces, though they cannot start or end with spaces\n since Discord removes empty space at the start and end of messages. The prefix is saved across reboots. Setting\n the prefix to `remove` will remove the prefix. The bot will always listen to pings as if they were a prefix,\n regardless of if there is another prefix set or not. Maximum prefix length is 20.' if (len(new_prefix) > 20): (await ctx.send('The maximum prefix length is 20.')) return self.bot.prefix = (new_prefix if (new_prefix.lower() != 'remove') else None) activity = Activity(type=ActivityType.listening, name=(f'prefix: {new_prefix}' if (new_prefix.lower() != 'remove') else 'pings only')) (await self.bot.change_presence(activity=activity)) async with self.bot.db.acquire() as conn: (await conn.execute("UPDATE settings SET value = $1 WHERE key = 'prefix'", (new_prefix if (new_prefix.lower() != 'remove') else ))) if (new_prefix.lower() != 'remove'): (await ctx.send(f'The bot prefix has successfully been changed to `{new_prefix}`.')) else: (await ctx.send('The bot is now only listens to pings.'))
@commands.is_owner() @botconfig.command(name='prefix', usage='<NEW PREFIX/remove>') async def botconfig_prefix(self, ctx: commands.Context, *, new_prefix: str): 'This command changes the bot prefix. The default prefix is `!`. Prefixes can be everything from symbols to\n words or a combination of the two, and can even include spaces, though they cannot start or end with spaces\n since Discord removes empty space at the start and end of messages. The prefix is saved across reboots. Setting\n the prefix to `remove` will remove the prefix. The bot will always listen to pings as if they were a prefix,\n regardless of if there is another prefix set or not. Maximum prefix length is 20.' if (len(new_prefix) > 20): (await ctx.send('The maximum prefix length is 20.')) return self.bot.prefix = (new_prefix if (new_prefix.lower() != 'remove') else None) activity = Activity(type=ActivityType.listening, name=(f'prefix: {new_prefix}' if (new_prefix.lower() != 'remove') else 'pings only')) (await self.bot.change_presence(activity=activity)) async with self.bot.db.acquire() as conn: (await conn.execute("UPDATE settings SET value = $1 WHERE key = 'prefix'", (new_prefix if (new_prefix.lower() != 'remove') else ))) if (new_prefix.lower() != 'remove'): (await ctx.send(f'The bot prefix has successfully been changed to `{new_prefix}`.')) else: (await ctx.send('The bot is now only listens to pings.'))<|docstring|>This command changes the bot prefix. The default prefix is `!`. Prefixes can be everything from symbols to words or a combination of the two, and can even include spaces, though they cannot start or end with spaces since Discord removes empty space at the start and end of messages. The prefix is saved across reboots. Setting the prefix to `remove` will remove the prefix. The bot will always listen to pings as if they were a prefix, regardless of if there is another prefix set or not. Maximum prefix length is 20.<|endoftext|>
3295dc49f9b0dd71e8c35bbaeb54e586f2ff814bacf8528da7f3a1448b1d4d66
@commands.is_owner() @botconfig.command(name='deletemessages', aliases=['deletemsgs', 'deletecommands', 'deletecmds', 'delmessages', 'delmsgs', 'delcommands', 'delcmds'], usage='<enable/disable>') async def botconfig_deletemessages(self, ctx: commands.Context, operation: str): 'This command sets the behaviour for deletion of command triggers. If this is enabled then messages that\n trigger commands will be deleted. Is this is disabled then the bot will not delete messages that trigger\n commands. Per default this is enabled. This setting is saved across restarts.' op = operation.lower() async with self.bot.db.acquire() as conn: if (op in ['enable', 'true', 'on', 'yes', 'y', '+', '1']): if self.bot.delete_messages: (await ctx.send('The bot is already deleting command triggers.')) return (await conn.execute("UPDATE settings SET value = '1' WHERE key = 'delete_messages'")) self.bot.delete_messages = 1 (await ctx.send('Now deleting command triggers.')) elif (op in ['disable', 'false', 'off', 'no', 'n', '-', '0']): if (not self.bot.delete_messages): (await ctx.send('The bot is already not deleting command triggers.')) return (await conn.execute("UPDATE settings SET value = '0' WHERE key = 'delete_messages'")) self.bot.delete_messages = 0 (await ctx.send('No longer deleting command triggers.')) else: raise commands.BadArgument('Operation not supported.')
This command sets the behaviour for deletion of command triggers. If this is enabled then messages that trigger commands will be deleted. Is this is disabled then the bot will not delete messages that trigger commands. Per default this is enabled. This setting is saved across restarts.
core_commands.py
botconfig_deletemessages
Travus/Travus_Bot_Base
2
python
@commands.is_owner() @botconfig.command(name='deletemessages', aliases=['deletemsgs', 'deletecommands', 'deletecmds', 'delmessages', 'delmsgs', 'delcommands', 'delcmds'], usage='<enable/disable>') async def botconfig_deletemessages(self, ctx: commands.Context, operation: str): 'This command sets the behaviour for deletion of command triggers. If this is enabled then messages that\n trigger commands will be deleted. Is this is disabled then the bot will not delete messages that trigger\n commands. Per default this is enabled. This setting is saved across restarts.' op = operation.lower() async with self.bot.db.acquire() as conn: if (op in ['enable', 'true', 'on', 'yes', 'y', '+', '1']): if self.bot.delete_messages: (await ctx.send('The bot is already deleting command triggers.')) return (await conn.execute("UPDATE settings SET value = '1' WHERE key = 'delete_messages'")) self.bot.delete_messages = 1 (await ctx.send('Now deleting command triggers.')) elif (op in ['disable', 'false', 'off', 'no', 'n', '-', '0']): if (not self.bot.delete_messages): (await ctx.send('The bot is already not deleting command triggers.')) return (await conn.execute("UPDATE settings SET value = '0' WHERE key = 'delete_messages'")) self.bot.delete_messages = 0 (await ctx.send('No longer deleting command triggers.')) else: raise commands.BadArgument('Operation not supported.')
@commands.is_owner() @botconfig.command(name='deletemessages', aliases=['deletemsgs', 'deletecommands', 'deletecmds', 'delmessages', 'delmsgs', 'delcommands', 'delcmds'], usage='<enable/disable>') async def botconfig_deletemessages(self, ctx: commands.Context, operation: str): 'This command sets the behaviour for deletion of command triggers. If this is enabled then messages that\n trigger commands will be deleted. Is this is disabled then the bot will not delete messages that trigger\n commands. Per default this is enabled. This setting is saved across restarts.' op = operation.lower() async with self.bot.db.acquire() as conn: if (op in ['enable', 'true', 'on', 'yes', 'y', '+', '1']): if self.bot.delete_messages: (await ctx.send('The bot is already deleting command triggers.')) return (await conn.execute("UPDATE settings SET value = '1' WHERE key = 'delete_messages'")) self.bot.delete_messages = 1 (await ctx.send('Now deleting command triggers.')) elif (op in ['disable', 'false', 'off', 'no', 'n', '-', '0']): if (not self.bot.delete_messages): (await ctx.send('The bot is already not deleting command triggers.')) return (await conn.execute("UPDATE settings SET value = '0' WHERE key = 'delete_messages'")) self.bot.delete_messages = 0 (await ctx.send('No longer deleting command triggers.')) else: raise commands.BadArgument('Operation not supported.')<|docstring|>This command sets the behaviour for deletion of command triggers. If this is enabled then messages that trigger commands will be deleted. Is this is disabled then the bot will not delete messages that trigger commands. Per default this is enabled. This setting is saved across restarts.<|endoftext|>
bf6e20ddd7f2dcc6fe6211099cac6b5bc9735040cb34d08472284f00b8240fb0
@commands.is_owner() @botconfig.command(name='description', aliases=['desc'], usage='<DESCRIPTION/remove>') async def botconfig_description(self, ctx: commands.Context, *, description: str): 'This command sets the bot description that is used by the about command. The description can technically be\n up to 4096 characters long, keep however in mind that Discord messages have a maximum length of 4000 characters\n (2000 without Nitro). If `remove` is sent along then the description will be removed. The special keyword\n `_prefix_` wil be replaced by the current bot prefix.' async with self.bot.db.acquire() as conn: if (description.lower() == 'remove'): (await conn.execute("UPDATE settings SET value = '' WHERE key = 'bot_description'")) self.bot.modules[self.bot.user.name.lower()].description = 'No description for the bot found. Set description with `botconfig` command.' (await ctx.send('The description has been removed.')) else: (await conn.execute("UPDATE settings SET value = $1 WHERE key = 'bot_description'", description)) self.bot.modules[self.bot.user.name.lower()].description = description (await ctx.send('The description has been set.'))
This command sets the bot description that is used by the about command. The description can technically be up to 4096 characters long, keep however in mind that Discord messages have a maximum length of 4000 characters (2000 without Nitro). If `remove` is sent along then the description will be removed. The special keyword `_prefix_` wil be replaced by the current bot prefix.
core_commands.py
botconfig_description
Travus/Travus_Bot_Base
2
python
@commands.is_owner() @botconfig.command(name='description', aliases=['desc'], usage='<DESCRIPTION/remove>') async def botconfig_description(self, ctx: commands.Context, *, description: str): 'This command sets the bot description that is used by the about command. The description can technically be\n up to 4096 characters long, keep however in mind that Discord messages have a maximum length of 4000 characters\n (2000 without Nitro). If `remove` is sent along then the description will be removed. The special keyword\n `_prefix_` wil be replaced by the current bot prefix.' async with self.bot.db.acquire() as conn: if (description.lower() == 'remove'): (await conn.execute("UPDATE settings SET value = WHERE key = 'bot_description'")) self.bot.modules[self.bot.user.name.lower()].description = 'No description for the bot found. Set description with `botconfig` command.' (await ctx.send('The description has been removed.')) else: (await conn.execute("UPDATE settings SET value = $1 WHERE key = 'bot_description'", description)) self.bot.modules[self.bot.user.name.lower()].description = description (await ctx.send('The description has been set.'))
@commands.is_owner() @botconfig.command(name='description', aliases=['desc'], usage='<DESCRIPTION/remove>') async def botconfig_description(self, ctx: commands.Context, *, description: str): 'This command sets the bot description that is used by the about command. The description can technically be\n up to 4096 characters long, keep however in mind that Discord messages have a maximum length of 4000 characters\n (2000 without Nitro). If `remove` is sent along then the description will be removed. The special keyword\n `_prefix_` wil be replaced by the current bot prefix.' async with self.bot.db.acquire() as conn: if (description.lower() == 'remove'): (await conn.execute("UPDATE settings SET value = WHERE key = 'bot_description'")) self.bot.modules[self.bot.user.name.lower()].description = 'No description for the bot found. Set description with `botconfig` command.' (await ctx.send('The description has been removed.')) else: (await conn.execute("UPDATE settings SET value = $1 WHERE key = 'bot_description'", description)) self.bot.modules[self.bot.user.name.lower()].description = description (await ctx.send('The description has been set.'))<|docstring|>This command sets the bot description that is used by the about command. The description can technically be up to 4096 characters long, keep however in mind that Discord messages have a maximum length of 4000 characters (2000 without Nitro). If `remove` is sent along then the description will be removed. The special keyword `_prefix_` wil be replaced by the current bot prefix.<|endoftext|>
ffdc4bfb0be93fb43d55d91b9bb12c515632182b38f77e0818cf01b1a69cb6ef
@commands.is_owner() @botconfig.command(name='credits', usage='<CREDITS/remove> *OBS: See help command entry!*') async def botconfig_credits(self, ctx: commands.Context, *, description: str): 'This command sets the additional credits section of the about command. The additional credits section can be\n at most 1024 characters long, and supports both new lines, indents and embedded links. Indents of 5 spaces are\n recommended. Embedded links should look like so; `[displayed text](URL)`. The credits should be passed inside a\n multi-line code block in order for new lines and tabs to work correctly. If `remove` is passed instead then the\n additional credits section is removed.' description = description.strip() async with self.bot.db.acquire() as conn: if (description.lower() == 'remove'): (await conn.execute("UPDATE settings SET value = '' WHERE key = 'additional_credits'")) self.bot.modules[self.bot.user.name.lower()].credits = None (await ctx.send('The additional credits section has been removed.')) return if ((description.count('```') != 2) or (description[:3] != '```') or (description[(- 3):] != '```')): (await ctx.send('Credits must be fully encased in a multi-line code block.')) return description = description.strip('```').strip() description = description.replace(' ', '\u202f') if (len(description) > 1024): (await ctx.send('Credits too long. Credits can be at most 1024 characters long.')) return (await conn.execute("UPDATE settings SET value = $1 WHERE key = 'additional_credits'", description)) self.bot.modules[self.bot.user.name.lower()].credits = description (await ctx.send('The additional credits section has been set.'))
This command sets the additional credits section of the about command. The additional credits section can be at most 1024 characters long, and supports both new lines, indents and embedded links. Indents of 5 spaces are recommended. Embedded links should look like so; `[displayed text](URL)`. The credits should be passed inside a multi-line code block in order for new lines and tabs to work correctly. If `remove` is passed instead then the additional credits section is removed.
core_commands.py
botconfig_credits
Travus/Travus_Bot_Base
2
python
@commands.is_owner() @botconfig.command(name='credits', usage='<CREDITS/remove> *OBS: See help command entry!*') async def botconfig_credits(self, ctx: commands.Context, *, description: str): 'This command sets the additional credits section of the about command. The additional credits section can be\n at most 1024 characters long, and supports both new lines, indents and embedded links. Indents of 5 spaces are\n recommended. Embedded links should look like so; `[displayed text](URL)`. The credits should be passed inside a\n multi-line code block in order for new lines and tabs to work correctly. If `remove` is passed instead then the\n additional credits section is removed.' description = description.strip() async with self.bot.db.acquire() as conn: if (description.lower() == 'remove'): (await conn.execute("UPDATE settings SET value = WHERE key = 'additional_credits'")) self.bot.modules[self.bot.user.name.lower()].credits = None (await ctx.send('The additional credits section has been removed.')) return if ((description.count('```') != 2) or (description[:3] != '```') or (description[(- 3):] != '```')): (await ctx.send('Credits must be fully encased in a multi-line code block.')) return description = description.strip('```').strip() description = description.replace(' ', '\u202f') if (len(description) > 1024): (await ctx.send('Credits too long. Credits can be at most 1024 characters long.')) return (await conn.execute("UPDATE settings SET value = $1 WHERE key = 'additional_credits'", description)) self.bot.modules[self.bot.user.name.lower()].credits = description (await ctx.send('The additional credits section has been set.'))
@commands.is_owner() @botconfig.command(name='credits', usage='<CREDITS/remove> *OBS: See help command entry!*') async def botconfig_credits(self, ctx: commands.Context, *, description: str): 'This command sets the additional credits section of the about command. The additional credits section can be\n at most 1024 characters long, and supports both new lines, indents and embedded links. Indents of 5 spaces are\n recommended. Embedded links should look like so; `[displayed text](URL)`. The credits should be passed inside a\n multi-line code block in order for new lines and tabs to work correctly. If `remove` is passed instead then the\n additional credits section is removed.' description = description.strip() async with self.bot.db.acquire() as conn: if (description.lower() == 'remove'): (await conn.execute("UPDATE settings SET value = WHERE key = 'additional_credits'")) self.bot.modules[self.bot.user.name.lower()].credits = None (await ctx.send('The additional credits section has been removed.')) return if ((description.count('```') != 2) or (description[:3] != '```') or (description[(- 3):] != '```')): (await ctx.send('Credits must be fully encased in a multi-line code block.')) return description = description.strip('```').strip() description = description.replace(' ', '\u202f') if (len(description) > 1024): (await ctx.send('Credits too long. Credits can be at most 1024 characters long.')) return (await conn.execute("UPDATE settings SET value = $1 WHERE key = 'additional_credits'", description)) self.bot.modules[self.bot.user.name.lower()].credits = description (await ctx.send('The additional credits section has been set.'))<|docstring|>This command sets the additional credits section of the about command. The additional credits section can be at most 1024 characters long, and supports both new lines, indents and embedded links. Indents of 5 spaces are recommended. Embedded links should look like so; `[displayed text](URL)`. The credits should be passed inside a multi-line code block in order for new lines and tabs to work correctly. If `remove` is passed instead then the additional credits section is removed.<|endoftext|>
972700dfe638ab9fe0ee78e462d347cb2ee1e56bc91ca29da099d5d3611497fc
@commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name='module', aliases=['modules'], usage='<list/load/unload/reload/error>') async def module(self, ctx: commands.Context): "This command can load, unload, reload and list available modules. It can also show any errors that occur\n during the loading process. Modules contain added functionality, such as commands. The intended purpose for\n modules is to extend the bot's functionality in semi-independent packages so that parts of the bot's\n functionality can be removed or restarted without affecting the rest of the bot's functionality. See the help\n text for the subcommands for more info." raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')
This command can load, unload, reload and list available modules. It can also show any errors that occur during the loading process. Modules contain added functionality, such as commands. The intended purpose for modules is to extend the bot's functionality in semi-independent packages so that parts of the bot's functionality can be removed or restarted without affecting the rest of the bot's functionality. See the help text for the subcommands for more info.
core_commands.py
module
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name='module', aliases=['modules'], usage='<list/load/unload/reload/error>') async def module(self, ctx: commands.Context): "This command can load, unload, reload and list available modules. It can also show any errors that occur\n during the loading process. Modules contain added functionality, such as commands. The intended purpose for\n modules is to extend the bot's functionality in semi-independent packages so that parts of the bot's\n functionality can be removed or restarted without affecting the rest of the bot's functionality. See the help\n text for the subcommands for more info." raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')
@commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name='module', aliases=['modules'], usage='<list/load/unload/reload/error>') async def module(self, ctx: commands.Context): "This command can load, unload, reload and list available modules. It can also show any errors that occur\n during the loading process. Modules contain added functionality, such as commands. The intended purpose for\n modules is to extend the bot's functionality in semi-independent packages so that parts of the bot's\n functionality can be removed or restarted without affecting the rest of the bot's functionality. See the help\n text for the subcommands for more info." raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')<|docstring|>This command can load, unload, reload and list available modules. It can also show any errors that occur during the loading process. Modules contain added functionality, such as commands. The intended purpose for modules is to extend the bot's functionality in semi-independent packages so that parts of the bot's functionality can be removed or restarted without affecting the rest of the bot's functionality. See the help text for the subcommands for more info.<|endoftext|>
deb8a9c9bdd0cd010ee94990d9a0c2a6eb3d90282a2fb31c8fe145cecaacdbe1
@commands.has_permissions(administrator=True) @module.command(name='list') async def module_list(self, ctx: commands.Context): 'This command lists all currently loaded and available modules. For the bot to find new modules they need to\n be placed inside the modules folder inside the bot directory. Modules listed by this command can be loaded,\n unloaded and reloaded by the respective commands for this. See help text for `module load`, `module unload`\n and `module reload` for more info on this.' loaded_modules = ([f"`{clean(ctx, mod.replace('modules.', ''), False, True)}`, " for mod in self.bot.extensions if (mod != 'core_commands')] or ['None, ']) available_modules = [f"`{clean(ctx, mod, False, True).replace('.py', '')}`, " for mod in listdir('modules') if mod.endswith('.py')] available_modules = ([mod for mod in available_modules if (mod not in loaded_modules)] or ['None, ']) loaded_modules[(- 1)] = loaded_modules[(- 1)][:(- 2)] available_modules[(- 1)] = available_modules[(- 1)][:(- 2)] paginator = commands.Paginator(prefix='', suffix='', linesep='') paginator.add_line('Loaded modules: ') for mod in loaded_modules: paginator.add_line(mod) paginator.add_line('\nAvailable Modules: ') for mod in available_modules: paginator.add_line(mod) for page in paginator.pages: (await ctx.send(page))
This command lists all currently loaded and available modules. For the bot to find new modules they need to be placed inside the modules folder inside the bot directory. Modules listed by this command can be loaded, unloaded and reloaded by the respective commands for this. See help text for `module load`, `module unload` and `module reload` for more info on this.
core_commands.py
module_list
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @module.command(name='list') async def module_list(self, ctx: commands.Context): 'This command lists all currently loaded and available modules. For the bot to find new modules they need to\n be placed inside the modules folder inside the bot directory. Modules listed by this command can be loaded,\n unloaded and reloaded by the respective commands for this. See help text for `module load`, `module unload`\n and `module reload` for more info on this.' loaded_modules = ([f"`{clean(ctx, mod.replace('modules.', ), False, True)}`, " for mod in self.bot.extensions if (mod != 'core_commands')] or ['None, ']) available_modules = [f"`{clean(ctx, mod, False, True).replace('.py', )}`, " for mod in listdir('modules') if mod.endswith('.py')] available_modules = ([mod for mod in available_modules if (mod not in loaded_modules)] or ['None, ']) loaded_modules[(- 1)] = loaded_modules[(- 1)][:(- 2)] available_modules[(- 1)] = available_modules[(- 1)][:(- 2)] paginator = commands.Paginator(prefix=, suffix=, linesep=) paginator.add_line('Loaded modules: ') for mod in loaded_modules: paginator.add_line(mod) paginator.add_line('\nAvailable Modules: ') for mod in available_modules: paginator.add_line(mod) for page in paginator.pages: (await ctx.send(page))
@commands.has_permissions(administrator=True) @module.command(name='list') async def module_list(self, ctx: commands.Context): 'This command lists all currently loaded and available modules. For the bot to find new modules they need to\n be placed inside the modules folder inside the bot directory. Modules listed by this command can be loaded,\n unloaded and reloaded by the respective commands for this. See help text for `module load`, `module unload`\n and `module reload` for more info on this.' loaded_modules = ([f"`{clean(ctx, mod.replace('modules.', ), False, True)}`, " for mod in self.bot.extensions if (mod != 'core_commands')] or ['None, ']) available_modules = [f"`{clean(ctx, mod, False, True).replace('.py', )}`, " for mod in listdir('modules') if mod.endswith('.py')] available_modules = ([mod for mod in available_modules if (mod not in loaded_modules)] or ['None, ']) loaded_modules[(- 1)] = loaded_modules[(- 1)][:(- 2)] available_modules[(- 1)] = available_modules[(- 1)][:(- 2)] paginator = commands.Paginator(prefix=, suffix=, linesep=) paginator.add_line('Loaded modules: ') for mod in loaded_modules: paginator.add_line(mod) paginator.add_line('\nAvailable Modules: ') for mod in available_modules: paginator.add_line(mod) for page in paginator.pages: (await ctx.send(page))<|docstring|>This command lists all currently loaded and available modules. For the bot to find new modules they need to be placed inside the modules folder inside the bot directory. Modules listed by this command can be loaded, unloaded and reloaded by the respective commands for this. See help text for `module load`, `module unload` and `module reload` for more info on this.<|endoftext|>
18bf0e97961217e51506a177596dffcdbaf9b05a00b664d44ed57ab41763f255
@commands.has_permissions(administrator=True) @module.command(name='load', aliases=['l'], usage='<MODULE NAME>') async def module_load(self, ctx: commands.Context, *, mod: str): 'This command loads modules. Modules should be located inside the module folder in the bot directory. The\n `module list` command can be used to show all modules available for loading. Once a module is loaded the\n functionality defined in the module file will be added to the bot. If an error is encountered during the\n loading process the user will be informed and the `module error` command can then be used to see the error\n details. The module will then not be loaded. If you want modules to stay loaded after restarts, see the\n `default` command.' (await self._module_operation(ctx, 'load', mod))
This command loads modules. Modules should be located inside the module folder in the bot directory. The `module list` command can be used to show all modules available for loading. Once a module is loaded the functionality defined in the module file will be added to the bot. If an error is encountered during the loading process the user will be informed and the `module error` command can then be used to see the error details. The module will then not be loaded. If you want modules to stay loaded after restarts, see the `default` command.
core_commands.py
module_load
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @module.command(name='load', aliases=['l'], usage='<MODULE NAME>') async def module_load(self, ctx: commands.Context, *, mod: str): 'This command loads modules. Modules should be located inside the module folder in the bot directory. The\n `module list` command can be used to show all modules available for loading. Once a module is loaded the\n functionality defined in the module file will be added to the bot. If an error is encountered during the\n loading process the user will be informed and the `module error` command can then be used to see the error\n details. The module will then not be loaded. If you want modules to stay loaded after restarts, see the\n `default` command.' (await self._module_operation(ctx, 'load', mod))
@commands.has_permissions(administrator=True) @module.command(name='load', aliases=['l'], usage='<MODULE NAME>') async def module_load(self, ctx: commands.Context, *, mod: str): 'This command loads modules. Modules should be located inside the module folder in the bot directory. The\n `module list` command can be used to show all modules available for loading. Once a module is loaded the\n functionality defined in the module file will be added to the bot. If an error is encountered during the\n loading process the user will be informed and the `module error` command can then be used to see the error\n details. The module will then not be loaded. If you want modules to stay loaded after restarts, see the\n `default` command.' (await self._module_operation(ctx, 'load', mod))<|docstring|>This command loads modules. Modules should be located inside the module folder in the bot directory. The `module list` command can be used to show all modules available for loading. Once a module is loaded the functionality defined in the module file will be added to the bot. If an error is encountered during the loading process the user will be informed and the `module error` command can then be used to see the error details. The module will then not be loaded. If you want modules to stay loaded after restarts, see the `default` command.<|endoftext|>
f6a499d0bdad6bde405a737bd9abfcd31d2be8b6f7c139c6348d3a8f605e5802
@commands.has_permissions(administrator=True) @module.command(name='unload', aliases=['ul'], usage='<MODULE NAME>') async def module_unload(self, ctx: commands.Context, *, mod: str): "This command unloads modules. When a loaded module is unloaded it's functionality will be removed. You can\n use the `module list` command to see all currently loaded modules. This will not prevent default modules from\n being loaded when the bot starts. See the `default` command for removing modules starting with the bot." (await self._module_operation(ctx, 'unload', mod))
This command unloads modules. When a loaded module is unloaded it's functionality will be removed. You can use the `module list` command to see all currently loaded modules. This will not prevent default modules from being loaded when the bot starts. See the `default` command for removing modules starting with the bot.
core_commands.py
module_unload
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @module.command(name='unload', aliases=['ul'], usage='<MODULE NAME>') async def module_unload(self, ctx: commands.Context, *, mod: str): "This command unloads modules. When a loaded module is unloaded it's functionality will be removed. You can\n use the `module list` command to see all currently loaded modules. This will not prevent default modules from\n being loaded when the bot starts. See the `default` command for removing modules starting with the bot." (await self._module_operation(ctx, 'unload', mod))
@commands.has_permissions(administrator=True) @module.command(name='unload', aliases=['ul'], usage='<MODULE NAME>') async def module_unload(self, ctx: commands.Context, *, mod: str): "This command unloads modules. When a loaded module is unloaded it's functionality will be removed. You can\n use the `module list` command to see all currently loaded modules. This will not prevent default modules from\n being loaded when the bot starts. See the `default` command for removing modules starting with the bot." (await self._module_operation(ctx, 'unload', mod))<|docstring|>This command unloads modules. When a loaded module is unloaded it's functionality will be removed. You can use the `module list` command to see all currently loaded modules. This will not prevent default modules from being loaded when the bot starts. See the `default` command for removing modules starting with the bot.<|endoftext|>
acd570db99fae8b8defe85e0d35781ac643862727992c78e01f8ab6a01cfbf0a
@commands.has_permissions(administrator=True) @module.command(name='reload', aliases=['rl'], usage='<MODULE NAME>') async def module_reload(self, ctx: commands.Context, *, mod: str): 'This command reloads a module that is currently loaded. This will unload and load the module in one command.\n If the module is no longer present or the loading process encounters an error the module will not be reloaded\n and the functionality from before the reload will be retained and the user informed, the `module error` command\n can then be used to see the error details. You can use the module list command to see all currently loaded\n modules.' (await self._module_operation(ctx, 'reload', mod))
This command reloads a module that is currently loaded. This will unload and load the module in one command. If the module is no longer present or the loading process encounters an error the module will not be reloaded and the functionality from before the reload will be retained and the user informed, the `module error` command can then be used to see the error details. You can use the module list command to see all currently loaded modules.
core_commands.py
module_reload
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @module.command(name='reload', aliases=['rl'], usage='<MODULE NAME>') async def module_reload(self, ctx: commands.Context, *, mod: str): 'This command reloads a module that is currently loaded. This will unload and load the module in one command.\n If the module is no longer present or the loading process encounters an error the module will not be reloaded\n and the functionality from before the reload will be retained and the user informed, the `module error` command\n can then be used to see the error details. You can use the module list command to see all currently loaded\n modules.' (await self._module_operation(ctx, 'reload', mod))
@commands.has_permissions(administrator=True) @module.command(name='reload', aliases=['rl'], usage='<MODULE NAME>') async def module_reload(self, ctx: commands.Context, *, mod: str): 'This command reloads a module that is currently loaded. This will unload and load the module in one command.\n If the module is no longer present or the loading process encounters an error the module will not be reloaded\n and the functionality from before the reload will be retained and the user informed, the `module error` command\n can then be used to see the error details. You can use the module list command to see all currently loaded\n modules.' (await self._module_operation(ctx, 'reload', mod))<|docstring|>This command reloads a module that is currently loaded. This will unload and load the module in one command. If the module is no longer present or the loading process encounters an error the module will not be reloaded and the functionality from before the reload will be retained and the user informed, the `module error` command can then be used to see the error details. You can use the module list command to see all currently loaded modules.<|endoftext|>
5ab7e66dd4e7764c10ebd380ff9f36e81e7956c3ce4fa1d5a66e77c23d344822
@commands.has_permissions(administrator=True) @module.command(name='error') async def module_error(self, ctx: commands.Context): 'This command will show the last error that was encountered during the module load or reloading process. This\n information will also be logged to the console when the error first is encountered. This command retains this\n information until another error replaces it, or the bot shuts down.' if self.bot.last_module_error: (await ctx.send(self.bot.last_module_error[:1999])) else: (await ctx.send('There have not been any errors loading modules since the last restart.'))
This command will show the last error that was encountered during the module load or reloading process. This information will also be logged to the console when the error first is encountered. This command retains this information until another error replaces it, or the bot shuts down.
core_commands.py
module_error
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @module.command(name='error') async def module_error(self, ctx: commands.Context): 'This command will show the last error that was encountered during the module load or reloading process. This\n information will also be logged to the console when the error first is encountered. This command retains this\n information until another error replaces it, or the bot shuts down.' if self.bot.last_module_error: (await ctx.send(self.bot.last_module_error[:1999])) else: (await ctx.send('There have not been any errors loading modules since the last restart.'))
@commands.has_permissions(administrator=True) @module.command(name='error') async def module_error(self, ctx: commands.Context): 'This command will show the last error that was encountered during the module load or reloading process. This\n information will also be logged to the console when the error first is encountered. This command retains this\n information until another error replaces it, or the bot shuts down.' if self.bot.last_module_error: (await ctx.send(self.bot.last_module_error[:1999])) else: (await ctx.send('There have not been any errors loading modules since the last restart.'))<|docstring|>This command will show the last error that was encountered during the module load or reloading process. This information will also be logged to the console when the error first is encountered. This command retains this information until another error replaces it, or the bot shuts down.<|endoftext|>
acc2103e2f842a19dd93cda6e2f82ad8f0c75b065a9d5d71e0fa47007cc67152
@commands.is_owner() @commands.group(invoke_without_command=True, name='default', aliases=['defaults'], usage='<add/remove/list>') async def default(self, ctx: commands.Context): 'This command is used to add, remove or list default modules. Modules contain added functionality, such as\n commands. Default modules are loaded automatically when the bot starts and as such any functionality in them\n will be available as soon as the bot is online. For more info see the help text of the subcommands.' raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')
This command is used to add, remove or list default modules. Modules contain added functionality, such as commands. Default modules are loaded automatically when the bot starts and as such any functionality in them will be available as soon as the bot is online. For more info see the help text of the subcommands.
core_commands.py
default
Travus/Travus_Bot_Base
2
python
@commands.is_owner() @commands.group(invoke_without_command=True, name='default', aliases=['defaults'], usage='<add/remove/list>') async def default(self, ctx: commands.Context): 'This command is used to add, remove or list default modules. Modules contain added functionality, such as\n commands. Default modules are loaded automatically when the bot starts and as such any functionality in them\n will be available as soon as the bot is online. For more info see the help text of the subcommands.' raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')
@commands.is_owner() @commands.group(invoke_without_command=True, name='default', aliases=['defaults'], usage='<add/remove/list>') async def default(self, ctx: commands.Context): 'This command is used to add, remove or list default modules. Modules contain added functionality, such as\n commands. Default modules are loaded automatically when the bot starts and as such any functionality in them\n will be available as soon as the bot is online. For more info see the help text of the subcommands.' raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')<|docstring|>This command is used to add, remove or list default modules. Modules contain added functionality, such as commands. Default modules are loaded automatically when the bot starts and as such any functionality in them will be available as soon as the bot is online. For more info see the help text of the subcommands.<|endoftext|>
88af6c2d6e3ce57521d9966117bd61399067f2e9250973e4c971369074592bcf
@commands.is_owner() @default.command(name='list') async def default_list(self, ctx: commands.Context): 'This command lists all current default modules. For more information on modules see the help text for the\n `module` command. All modules in this list start as soon as the bot is launched. For a list of all available or\n loaded modules see the `module list` command.' async with self.bot.db.acquire() as conn: result = (await conn.fetch('SELECT module FROM default_modules')) result = ([f"`{clean(ctx, val['module'], False, True)}`, " for val in result] or ['None, ']) result[(- 1)] = result[(- 1)][:(- 2)] paginator = commands.Paginator(prefix='', suffix='', linesep='') paginator.add_line('Default modules: ') for mod in result: paginator.add_line(mod) for page in paginator.pages: (await ctx.send(page))
This command lists all current default modules. For more information on modules see the help text for the `module` command. All modules in this list start as soon as the bot is launched. For a list of all available or loaded modules see the `module list` command.
core_commands.py
default_list
Travus/Travus_Bot_Base
2
python
@commands.is_owner() @default.command(name='list') async def default_list(self, ctx: commands.Context): 'This command lists all current default modules. For more information on modules see the help text for the\n `module` command. All modules in this list start as soon as the bot is launched. For a list of all available or\n loaded modules see the `module list` command.' async with self.bot.db.acquire() as conn: result = (await conn.fetch('SELECT module FROM default_modules')) result = ([f"`{clean(ctx, val['module'], False, True)}`, " for val in result] or ['None, ']) result[(- 1)] = result[(- 1)][:(- 2)] paginator = commands.Paginator(prefix=, suffix=, linesep=) paginator.add_line('Default modules: ') for mod in result: paginator.add_line(mod) for page in paginator.pages: (await ctx.send(page))
@commands.is_owner() @default.command(name='list') async def default_list(self, ctx: commands.Context): 'This command lists all current default modules. For more information on modules see the help text for the\n `module` command. All modules in this list start as soon as the bot is launched. For a list of all available or\n loaded modules see the `module list` command.' async with self.bot.db.acquire() as conn: result = (await conn.fetch('SELECT module FROM default_modules')) result = ([f"`{clean(ctx, val['module'], False, True)}`, " for val in result] or ['None, ']) result[(- 1)] = result[(- 1)][:(- 2)] paginator = commands.Paginator(prefix=, suffix=, linesep=) paginator.add_line('Default modules: ') for mod in result: paginator.add_line(mod) for page in paginator.pages: (await ctx.send(page))<|docstring|>This command lists all current default modules. For more information on modules see the help text for the `module` command. All modules in this list start as soon as the bot is launched. For a list of all available or loaded modules see the `module list` command.<|endoftext|>
7c8530b046f0145e0efaa0519105e1cb51b633ee658b26252cd3eda061c73e12
@commands.is_owner() @default.command(name='add', usage='<MODULE NAME>') async def default_add(self, ctx: commands.Context, *, mod: str): 'This command adds a module to the list of default modules. Modules in this list are loaded automatically\n once the bot starts. This command does not load modules if they are not already loaded until the bot is started\n the next time. For that, see the `module load` command. For a list of existing default modules, see the\n `default list` command. For more info on modules see the help text for the `module` command.' if (f'{mod}.py' in listdir('modules')): try: async with self.bot.db.acquire() as conn: (await conn.execute('INSERT INTO default_modules VALUES ($1)', mod)) (await ctx.send(f'The `{clean(ctx, mod, False, True)}` module is now a default module.')) except IntegrityConstraintViolationError: (await ctx.send(f'The `{clean(ctx, mod, False, True)}` module is already a default module.')) else: (await ctx.send(f'No `{clean(ctx, mod, False, True)}` module was found.'))
This command adds a module to the list of default modules. Modules in this list are loaded automatically once the bot starts. This command does not load modules if they are not already loaded until the bot is started the next time. For that, see the `module load` command. For a list of existing default modules, see the `default list` command. For more info on modules see the help text for the `module` command.
core_commands.py
default_add
Travus/Travus_Bot_Base
2
python
@commands.is_owner() @default.command(name='add', usage='<MODULE NAME>') async def default_add(self, ctx: commands.Context, *, mod: str): 'This command adds a module to the list of default modules. Modules in this list are loaded automatically\n once the bot starts. This command does not load modules if they are not already loaded until the bot is started\n the next time. For that, see the `module load` command. For a list of existing default modules, see the\n `default list` command. For more info on modules see the help text for the `module` command.' if (f'{mod}.py' in listdir('modules')): try: async with self.bot.db.acquire() as conn: (await conn.execute('INSERT INTO default_modules VALUES ($1)', mod)) (await ctx.send(f'The `{clean(ctx, mod, False, True)}` module is now a default module.')) except IntegrityConstraintViolationError: (await ctx.send(f'The `{clean(ctx, mod, False, True)}` module is already a default module.')) else: (await ctx.send(f'No `{clean(ctx, mod, False, True)}` module was found.'))
@commands.is_owner() @default.command(name='add', usage='<MODULE NAME>') async def default_add(self, ctx: commands.Context, *, mod: str): 'This command adds a module to the list of default modules. Modules in this list are loaded automatically\n once the bot starts. This command does not load modules if they are not already loaded until the bot is started\n the next time. For that, see the `module load` command. For a list of existing default modules, see the\n `default list` command. For more info on modules see the help text for the `module` command.' if (f'{mod}.py' in listdir('modules')): try: async with self.bot.db.acquire() as conn: (await conn.execute('INSERT INTO default_modules VALUES ($1)', mod)) (await ctx.send(f'The `{clean(ctx, mod, False, True)}` module is now a default module.')) except IntegrityConstraintViolationError: (await ctx.send(f'The `{clean(ctx, mod, False, True)}` module is already a default module.')) else: (await ctx.send(f'No `{clean(ctx, mod, False, True)}` module was found.'))<|docstring|>This command adds a module to the list of default modules. Modules in this list are loaded automatically once the bot starts. This command does not load modules if they are not already loaded until the bot is started the next time. For that, see the `module load` command. For a list of existing default modules, see the `default list` command. For more info on modules see the help text for the `module` command.<|endoftext|>
d9b1fe8c1f79c66df987eafe241d1049d781b4d3d7f3a0b6628af8b4617363ba
@commands.is_owner() @default.command(name='remove', usage='<MODULE NAME>') async def default_remove(self, ctx: commands.Context, *, mod: str): 'This command removes a module from the list of default modules. Once removed from this list the module will\n no longer automatically be loaded when the bot starts. This command will not unload commands that are already\n loaded. For that, see the `module unload` command. For a list of existing default modules, see the\n `default list` command. For more info on modules see the help text for the `module` command.' async with self.bot.db.acquire() as conn: result = (await conn.fetchval('SELECT module FROM default_modules WHERE module = $1', mod)) if result: (await conn.execute('DELETE FROM default_modules WHERE module = $1', mod)) (await ctx.send(f'Removed `{clean(ctx, mod, False, True)}` module from default modules.')) else: (await ctx.send(f'No `{clean(ctx, mod, False, True)}` module in default modules.'))
This command removes a module from the list of default modules. Once removed from this list the module will no longer automatically be loaded when the bot starts. This command will not unload commands that are already loaded. For that, see the `module unload` command. For a list of existing default modules, see the `default list` command. For more info on modules see the help text for the `module` command.
core_commands.py
default_remove
Travus/Travus_Bot_Base
2
python
@commands.is_owner() @default.command(name='remove', usage='<MODULE NAME>') async def default_remove(self, ctx: commands.Context, *, mod: str): 'This command removes a module from the list of default modules. Once removed from this list the module will\n no longer automatically be loaded when the bot starts. This command will not unload commands that are already\n loaded. For that, see the `module unload` command. For a list of existing default modules, see the\n `default list` command. For more info on modules see the help text for the `module` command.' async with self.bot.db.acquire() as conn: result = (await conn.fetchval('SELECT module FROM default_modules WHERE module = $1', mod)) if result: (await conn.execute('DELETE FROM default_modules WHERE module = $1', mod)) (await ctx.send(f'Removed `{clean(ctx, mod, False, True)}` module from default modules.')) else: (await ctx.send(f'No `{clean(ctx, mod, False, True)}` module in default modules.'))
@commands.is_owner() @default.command(name='remove', usage='<MODULE NAME>') async def default_remove(self, ctx: commands.Context, *, mod: str): 'This command removes a module from the list of default modules. Once removed from this list the module will\n no longer automatically be loaded when the bot starts. This command will not unload commands that are already\n loaded. For that, see the `module unload` command. For a list of existing default modules, see the\n `default list` command. For more info on modules see the help text for the `module` command.' async with self.bot.db.acquire() as conn: result = (await conn.fetchval('SELECT module FROM default_modules WHERE module = $1', mod)) if result: (await conn.execute('DELETE FROM default_modules WHERE module = $1', mod)) (await ctx.send(f'Removed `{clean(ctx, mod, False, True)}` module from default modules.')) else: (await ctx.send(f'No `{clean(ctx, mod, False, True)}` module in default modules.'))<|docstring|>This command removes a module from the list of default modules. Once removed from this list the module will no longer automatically be loaded when the bot starts. This command will not unload commands that are already loaded. For that, see the `module unload` command. For a list of existing default modules, see the `default list` command. For more info on modules see the help text for the `module` command.<|endoftext|>
3aa6fb795bba83a9a02b7dad3ce72a7abcdc2241a40e3e7c54a257c79e661bbb
@commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name='command', aliases=['commands'], usage='<enable/disable/show/hide>') async def command(self, ctx: commands.Context): "This command disables, enables, hides and shows other commands. Hiding commands means they don't show up in\n the overall help command list. Disabling a command means it can't be used. Disabled commands also do not show\n up in the overall help command list and the specific help text for the command will not be viewable. Core\n commands cannot be disabled. These settings are saved across restarts." raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')
This command disables, enables, hides and shows other commands. Hiding commands means they don't show up in the overall help command list. Disabling a command means it can't be used. Disabled commands also do not show up in the overall help command list and the specific help text for the command will not be viewable. Core commands cannot be disabled. These settings are saved across restarts.
core_commands.py
command
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name='command', aliases=['commands'], usage='<enable/disable/show/hide>') async def command(self, ctx: commands.Context): "This command disables, enables, hides and shows other commands. Hiding commands means they don't show up in\n the overall help command list. Disabling a command means it can't be used. Disabled commands also do not show\n up in the overall help command list and the specific help text for the command will not be viewable. Core\n commands cannot be disabled. These settings are saved across restarts." raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')
@commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name='command', aliases=['commands'], usage='<enable/disable/show/hide>') async def command(self, ctx: commands.Context): "This command disables, enables, hides and shows other commands. Hiding commands means they don't show up in\n the overall help command list. Disabling a command means it can't be used. Disabled commands also do not show\n up in the overall help command list and the specific help text for the command will not be viewable. Core\n commands cannot be disabled. These settings are saved across restarts." raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')<|docstring|>This command disables, enables, hides and shows other commands. Hiding commands means they don't show up in the overall help command list. Disabling a command means it can't be used. Disabled commands also do not show up in the overall help command list and the specific help text for the command will not be viewable. Core commands cannot be disabled. These settings are saved across restarts.<|endoftext|>
865afcde0e262e495ef119ac0ee327c16b6d11834ee4740d8e389bb2d6413895
async def _command_get_state(self, command: commands.Command) -> int: 'Helper function for command command that gets the state of the command.' async with self.bot.db.acquire() as conn: cog_com_name = f"{((command.cog.__class__.__name__ + '.') if command.cog else '')}{command.name}" response = (await conn.fetchval('SELECT state FROM command_states WHERE command = $1', cog_com_name)) if (response is None): (await conn.execute('INSERT INTO command_states VALUES ($1, $2)', cog_com_name, 0)) response = 0 return response
Helper function for command command that gets the state of the command.
core_commands.py
_command_get_state
Travus/Travus_Bot_Base
2
python
async def _command_get_state(self, command: commands.Command) -> int: async with self.bot.db.acquire() as conn: cog_com_name = f"{((command.cog.__class__.__name__ + '.') if command.cog else )}{command.name}" response = (await conn.fetchval('SELECT state FROM command_states WHERE command = $1', cog_com_name)) if (response is None): (await conn.execute('INSERT INTO command_states VALUES ($1, $2)', cog_com_name, 0)) response = 0 return response
async def _command_get_state(self, command: commands.Command) -> int: async with self.bot.db.acquire() as conn: cog_com_name = f"{((command.cog.__class__.__name__ + '.') if command.cog else )}{command.name}" response = (await conn.fetchval('SELECT state FROM command_states WHERE command = $1', cog_com_name)) if (response is None): (await conn.execute('INSERT INTO command_states VALUES ($1, $2)', cog_com_name, 0)) response = 0 return response<|docstring|>Helper function for command command that gets the state of the command.<|endoftext|>
e649cda2d347d13ea208c852285b509793100ba37721094bc0861770ac67914d
async def _command_set_state(self, command: commands.Command, state: int): 'Helper function for command command that sets the state of the command.' async with self.bot.db.acquire() as conn: (await conn.execute('UPDATE command_states SET state = $1 WHERE command = $2', state, f"{((command.cog.__class__.__name__ + '.') if command.cog else '')}{command.name}"))
Helper function for command command that sets the state of the command.
core_commands.py
_command_set_state
Travus/Travus_Bot_Base
2
python
async def _command_set_state(self, command: commands.Command, state: int): async with self.bot.db.acquire() as conn: (await conn.execute('UPDATE command_states SET state = $1 WHERE command = $2', state, f"{((command.cog.__class__.__name__ + '.') if command.cog else )}{command.name}"))
async def _command_set_state(self, command: commands.Command, state: int): async with self.bot.db.acquire() as conn: (await conn.execute('UPDATE command_states SET state = $1 WHERE command = $2', state, f"{((command.cog.__class__.__name__ + '.') if command.cog else )}{command.name}"))<|docstring|>Helper function for command command that sets the state of the command.<|endoftext|>
790f8f80182c639a45200b7add207bbde45c44ecd6d54b476e57dc89a311c03a
@commands.has_permissions(administrator=True) @command.command(name='enable', usage='<COMMAND NAME>') async def command_enable(self, ctx: commands.Context, *, command_name: str): "This command enables commands which have previously been disabled. This will allow them to be used again.\n It will also add the command back into the list of commands shown by the help command and re-enable the\n viewing of it's help text given the command has help text and it has not otherwise been hidden." if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if self.bot.all_commands[command_name].enabled: (await ctx.send(f'The `{clean(ctx, command_name)}` command is already enabled.')) else: self.bot.all_commands[command_name].enabled = True (await self._command_set_state(self.bot.all_commands[command_name], (0 if (state == 2) else 1))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now enabled.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))
This command enables commands which have previously been disabled. This will allow them to be used again. It will also add the command back into the list of commands shown by the help command and re-enable the viewing of it's help text given the command has help text and it has not otherwise been hidden.
core_commands.py
command_enable
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @command.command(name='enable', usage='<COMMAND NAME>') async def command_enable(self, ctx: commands.Context, *, command_name: str): "This command enables commands which have previously been disabled. This will allow them to be used again.\n It will also add the command back into the list of commands shown by the help command and re-enable the\n viewing of it's help text given the command has help text and it has not otherwise been hidden." if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if self.bot.all_commands[command_name].enabled: (await ctx.send(f'The `{clean(ctx, command_name)}` command is already enabled.')) else: self.bot.all_commands[command_name].enabled = True (await self._command_set_state(self.bot.all_commands[command_name], (0 if (state == 2) else 1))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now enabled.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))
@commands.has_permissions(administrator=True) @command.command(name='enable', usage='<COMMAND NAME>') async def command_enable(self, ctx: commands.Context, *, command_name: str): "This command enables commands which have previously been disabled. This will allow them to be used again.\n It will also add the command back into the list of commands shown by the help command and re-enable the\n viewing of it's help text given the command has help text and it has not otherwise been hidden." if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if self.bot.all_commands[command_name].enabled: (await ctx.send(f'The `{clean(ctx, command_name)}` command is already enabled.')) else: self.bot.all_commands[command_name].enabled = True (await self._command_set_state(self.bot.all_commands[command_name], (0 if (state == 2) else 1))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now enabled.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))<|docstring|>This command enables commands which have previously been disabled. This will allow them to be used again. It will also add the command back into the list of commands shown by the help command and re-enable the viewing of it's help text given the command has help text and it has not otherwise been hidden.<|endoftext|>
79266c55ca67ea589ae3a4161ab4545e5cc1fce14ab511604db1d53fd98e90d4
@commands.has_permissions(administrator=True) @command.command(name='disable', usage='<COMMAND NAME>') async def command_disable(self, ctx: commands.Context, *, command_name: str): "This command can disable other commands. Disabled commands cannot be used and are removed from the\n list of commands shown by the help command. The command's help text will also not be viewable. Core\n commands cannot be disabled. Disabled commands can be re-enabled with the `command enable` command." if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if ((command_name in self.bot.help.keys()) and (self.bot.help[command_name].category.lower() == 'core')): (await ctx.send('Core commands cannot be disabled.')) elif (not self.bot.all_commands[command_name].enabled): (await ctx.send(f'The `{clean(ctx, command_name)}` command is already disabled.')) else: self.bot.all_commands[command_name].enabled = False (await self._command_set_state(self.bot.all_commands[command_name], (2 if (state == 0) else 3))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now disabled.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))
This command can disable other commands. Disabled commands cannot be used and are removed from the list of commands shown by the help command. The command's help text will also not be viewable. Core commands cannot be disabled. Disabled commands can be re-enabled with the `command enable` command.
core_commands.py
command_disable
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @command.command(name='disable', usage='<COMMAND NAME>') async def command_disable(self, ctx: commands.Context, *, command_name: str): "This command can disable other commands. Disabled commands cannot be used and are removed from the\n list of commands shown by the help command. The command's help text will also not be viewable. Core\n commands cannot be disabled. Disabled commands can be re-enabled with the `command enable` command." if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if ((command_name in self.bot.help.keys()) and (self.bot.help[command_name].category.lower() == 'core')): (await ctx.send('Core commands cannot be disabled.')) elif (not self.bot.all_commands[command_name].enabled): (await ctx.send(f'The `{clean(ctx, command_name)}` command is already disabled.')) else: self.bot.all_commands[command_name].enabled = False (await self._command_set_state(self.bot.all_commands[command_name], (2 if (state == 0) else 3))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now disabled.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))
@commands.has_permissions(administrator=True) @command.command(name='disable', usage='<COMMAND NAME>') async def command_disable(self, ctx: commands.Context, *, command_name: str): "This command can disable other commands. Disabled commands cannot be used and are removed from the\n list of commands shown by the help command. The command's help text will also not be viewable. Core\n commands cannot be disabled. Disabled commands can be re-enabled with the `command enable` command." if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if ((command_name in self.bot.help.keys()) and (self.bot.help[command_name].category.lower() == 'core')): (await ctx.send('Core commands cannot be disabled.')) elif (not self.bot.all_commands[command_name].enabled): (await ctx.send(f'The `{clean(ctx, command_name)}` command is already disabled.')) else: self.bot.all_commands[command_name].enabled = False (await self._command_set_state(self.bot.all_commands[command_name], (2 if (state == 0) else 3))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now disabled.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))<|docstring|>This command can disable other commands. Disabled commands cannot be used and are removed from the list of commands shown by the help command. The command's help text will also not be viewable. Core commands cannot be disabled. Disabled commands can be re-enabled with the `command enable` command.<|endoftext|>
28f980f4d0d72e78a89a5b40d3627ca7f6ca224986a02050177522bb69d2b93c
@commands.has_permissions(administrator=True) @command.command(name='show', usage='<COMMAND NAME>') async def command_show(self, ctx: commands.Context, *, command_name: str): 'This command will show commands which have previously been hidden, reversing the hiding of the\n command. This will add the command back into the list of commands shown by the help command. This\n will not re-enable the command if it has been disabled. Showing disabled commands alone will not\n be enough to re-add them to the help list since disabling them also hides them from the help list.\n See the `command enable` command to re-enable disabled commands.' if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if (not self.bot.all_commands[command_name].hidden): (await ctx.send(f'The `{clean(ctx, command_name)}` command is already shown.')) else: self.bot.all_commands[command_name].hidden = False (await self._command_set_state(self.bot.all_commands[command_name], (0 if (state == 1) else 2))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now shown.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))
This command will show commands which have previously been hidden, reversing the hiding of the command. This will add the command back into the list of commands shown by the help command. This will not re-enable the command if it has been disabled. Showing disabled commands alone will not be enough to re-add them to the help list since disabling them also hides them from the help list. See the `command enable` command to re-enable disabled commands.
core_commands.py
command_show
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @command.command(name='show', usage='<COMMAND NAME>') async def command_show(self, ctx: commands.Context, *, command_name: str): 'This command will show commands which have previously been hidden, reversing the hiding of the\n command. This will add the command back into the list of commands shown by the help command. This\n will not re-enable the command if it has been disabled. Showing disabled commands alone will not\n be enough to re-add them to the help list since disabling them also hides them from the help list.\n See the `command enable` command to re-enable disabled commands.' if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if (not self.bot.all_commands[command_name].hidden): (await ctx.send(f'The `{clean(ctx, command_name)}` command is already shown.')) else: self.bot.all_commands[command_name].hidden = False (await self._command_set_state(self.bot.all_commands[command_name], (0 if (state == 1) else 2))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now shown.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))
@commands.has_permissions(administrator=True) @command.command(name='show', usage='<COMMAND NAME>') async def command_show(self, ctx: commands.Context, *, command_name: str): 'This command will show commands which have previously been hidden, reversing the hiding of the\n command. This will add the command back into the list of commands shown by the help command. This\n will not re-enable the command if it has been disabled. Showing disabled commands alone will not\n be enough to re-add them to the help list since disabling them also hides them from the help list.\n See the `command enable` command to re-enable disabled commands.' if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if (not self.bot.all_commands[command_name].hidden): (await ctx.send(f'The `{clean(ctx, command_name)}` command is already shown.')) else: self.bot.all_commands[command_name].hidden = False (await self._command_set_state(self.bot.all_commands[command_name], (0 if (state == 1) else 2))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now shown.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))<|docstring|>This command will show commands which have previously been hidden, reversing the hiding of the command. This will add the command back into the list of commands shown by the help command. This will not re-enable the command if it has been disabled. Showing disabled commands alone will not be enough to re-add them to the help list since disabling them also hides them from the help list. See the `command enable` command to re-enable disabled commands.<|endoftext|>
48ffe4fb4e0da337b86ab56f35db3fd3e19cb538b1e331afdb32821f15ef1d4b
@commands.has_permissions(administrator=True) @command.command(name='hide', usage='<COMMAND NAME>') async def command_hide(self, ctx: commands.Context, *, command_name: str): "This command will hide commands from the list of commands shown by the help command. It will\n not disable the viewing of the help text for the command if someone already knows it's name.\n Commands who have been hidden can be un-hidden with the `command show` command." if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if self.bot.all_commands[command_name].hidden: (await ctx.send(f'The `{clean(ctx, command_name)}` command is already hidden.')) else: self.bot.all_commands[command_name].hidden = True (await self._command_set_state(self.bot.all_commands[command_name], (1 if (state == 0) else 3))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now hidden.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))
This command will hide commands from the list of commands shown by the help command. It will not disable the viewing of the help text for the command if someone already knows it's name. Commands who have been hidden can be un-hidden with the `command show` command.
core_commands.py
command_hide
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @command.command(name='hide', usage='<COMMAND NAME>') async def command_hide(self, ctx: commands.Context, *, command_name: str): "This command will hide commands from the list of commands shown by the help command. It will\n not disable the viewing of the help text for the command if someone already knows it's name.\n Commands who have been hidden can be un-hidden with the `command show` command." if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if self.bot.all_commands[command_name].hidden: (await ctx.send(f'The `{clean(ctx, command_name)}` command is already hidden.')) else: self.bot.all_commands[command_name].hidden = True (await self._command_set_state(self.bot.all_commands[command_name], (1 if (state == 0) else 3))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now hidden.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))
@commands.has_permissions(administrator=True) @command.command(name='hide', usage='<COMMAND NAME>') async def command_hide(self, ctx: commands.Context, *, command_name: str): "This command will hide commands from the list of commands shown by the help command. It will\n not disable the viewing of the help text for the command if someone already knows it's name.\n Commands who have been hidden can be un-hidden with the `command show` command." if (command_name in self.bot.all_commands.keys()): state = (await self._command_get_state(self.bot.all_commands[command_name])) if self.bot.all_commands[command_name].hidden: (await ctx.send(f'The `{clean(ctx, command_name)}` command is already hidden.')) else: self.bot.all_commands[command_name].hidden = True (await self._command_set_state(self.bot.all_commands[command_name], (1 if (state == 0) else 3))) (await ctx.send(f'The `{clean(ctx, command_name)}` command is now hidden.')) else: (await ctx.send(f'No `{clean(ctx, command_name)}` command found.'))<|docstring|>This command will hide commands from the list of commands shown by the help command. It will not disable the viewing of the help text for the command if someone already knows it's name. Commands who have been hidden can be un-hidden with the `command show` command.<|endoftext|>
bd9353081692a35b328a2e84547034865403ec40d4b376875e7ea9b85cdb1203
@commands.command(name='about', alias=['info'], usage='(MODULE NAME)') async def about(self, ctx: commands.Context, *, module_name: str=None): "This command gives information about modules, such as a description, authors, and other credits. Module\n authors can even add a small image to be displayed alongside this info. If no module name is given or the\n bot's name is used then information about the bot itself is shown." if (module_name is None): if (self.bot.user.name.lower() in self.bot.modules.keys()): embed = self.bot.modules[self.bot.user.name.lower()].make_about_embed(ctx) (await ctx.send(embed=embed)) else: raise RuntimeError('Bot info module not found.') elif (module_name.lower() in self.bot.modules.keys()): embed = self.bot.modules[module_name.lower()].make_about_embed(ctx) (await ctx.send(embed=embed)) else: response = f'No information for `{clean(ctx, module_name)}` module was found.' if (module_name not in [mod.replace('modules.', '') for mod in self.bot.extensions.keys()]): response += '\nAdditionally no module with this name is loaded.' (await ctx.send(response))
This command gives information about modules, such as a description, authors, and other credits. Module authors can even add a small image to be displayed alongside this info. If no module name is given or the bot's name is used then information about the bot itself is shown.
core_commands.py
about
Travus/Travus_Bot_Base
2
python
@commands.command(name='about', alias=['info'], usage='(MODULE NAME)') async def about(self, ctx: commands.Context, *, module_name: str=None): "This command gives information about modules, such as a description, authors, and other credits. Module\n authors can even add a small image to be displayed alongside this info. If no module name is given or the\n bot's name is used then information about the bot itself is shown." if (module_name is None): if (self.bot.user.name.lower() in self.bot.modules.keys()): embed = self.bot.modules[self.bot.user.name.lower()].make_about_embed(ctx) (await ctx.send(embed=embed)) else: raise RuntimeError('Bot info module not found.') elif (module_name.lower() in self.bot.modules.keys()): embed = self.bot.modules[module_name.lower()].make_about_embed(ctx) (await ctx.send(embed=embed)) else: response = f'No information for `{clean(ctx, module_name)}` module was found.' if (module_name not in [mod.replace('modules.', ) for mod in self.bot.extensions.keys()]): response += '\nAdditionally no module with this name is loaded.' (await ctx.send(response))
@commands.command(name='about', alias=['info'], usage='(MODULE NAME)') async def about(self, ctx: commands.Context, *, module_name: str=None): "This command gives information about modules, such as a description, authors, and other credits. Module\n authors can even add a small image to be displayed alongside this info. If no module name is given or the\n bot's name is used then information about the bot itself is shown." if (module_name is None): if (self.bot.user.name.lower() in self.bot.modules.keys()): embed = self.bot.modules[self.bot.user.name.lower()].make_about_embed(ctx) (await ctx.send(embed=embed)) else: raise RuntimeError('Bot info module not found.') elif (module_name.lower() in self.bot.modules.keys()): embed = self.bot.modules[module_name.lower()].make_about_embed(ctx) (await ctx.send(embed=embed)) else: response = f'No information for `{clean(ctx, module_name)}` module was found.' if (module_name not in [mod.replace('modules.', ) for mod in self.bot.extensions.keys()]): response += '\nAdditionally no module with this name is loaded.' (await ctx.send(response))<|docstring|>This command gives information about modules, such as a description, authors, and other credits. Module authors can even add a small image to be displayed alongside this info. If no module name is given or the bot's name is used then information about the bot itself is shown.<|endoftext|>
17c3b294b2f17c40c8d7d58e1be3d553654500373a9ddd93f0fcd0e7b0c9f5ee
@commands.command(name='usage', usage='(MODULE NAME)') async def usage(self, ctx: commands.Context, *, module_name: str=None): 'This command explains how a module is intended to be used. If no module name is given it will\n show some basic information about usage of the bot itself.' if ((module_name is None) or (module_name.lower() in [self.bot.user.name.lower(), 'core_commands', 'core commands'])): pref = self.bot.get_bot_prefix() response = f'''**How To Use:** This bot features a variety of commands. You can get a list of all commands you have access to with the `{pref}help` command. In order to use a command your message has to start with the *bot prefix*, the bot prefix is currently set to `{pref}`. Simply type this prefix, followed by a command name, and you will run the command. For more information on individual commands, run `{pref}help` followed by the command name. This will give you info on the command, along with some examples of it and any aliases the command might have. You might not have access to all commands everywhere, the help command will only tell you about commands you have access to in that channel, and commands you can run only in the DMs with the bot. DM only commands will be labeled as such by the help command. Some commands accept extra input, an example would be how the help command accepts a command name. You can usually see an example of how the command is used on the command's help page. If you use a command incorrectly by missing some input or sending invalid input, it will send you the expected input. This is how to read the expected input: Arguments encased in `<>` are obligatory. Arguments encased in `()` are optional and can be skipped. Arguments written in all uppercase are placeholders like names. Arguments not written in uppercase are exact values. If an argument lists multiple things separated by `/` then any one of them is valid. The `<>` and `()` symbols are not part of the command. Sample expected input: `{pref}about (MODULE NAME)` Here `{pref}about` is the command, and it takes an optional argument. The argument is written in all uppercase, so it is a placeholder. In other words you are expected to replace 'MODULE NAME' with the actual name of a module. Since the module name is optional, sending just `{pref}about` is also a valid command.''' (await ctx.send(response)) elif (module_name.lower() in self.bot.modules.keys()): usage = self.bot.modules[module_name.lower()].usage if (usage is None): (await ctx.send(f'The `{clean(ctx, module_name)}` module does not have its usage defined.')) else: usage_content = usage() if isinstance(usage_content, str): (await ctx.send((usage_content if (len(usage_content) < 1950) else f'{usage_content[:1949]}...'))) elif isinstance(usage_content, Embed): (await ctx.send(embed=usage_content)) else: response = f'No information for `{clean(ctx, module_name)}` module was found.' if (module_name not in [mod.replace('modules.', '') for mod in self.bot.extensions.keys()]): response += '\nAdditionally no module with this name is loaded.' (await ctx.send(response))
This command explains how a module is intended to be used. If no module name is given it will show some basic information about usage of the bot itself.
core_commands.py
usage
Travus/Travus_Bot_Base
2
python
@commands.command(name='usage', usage='(MODULE NAME)') async def usage(self, ctx: commands.Context, *, module_name: str=None): 'This command explains how a module is intended to be used. If no module name is given it will\n show some basic information about usage of the bot itself.' if ((module_name is None) or (module_name.lower() in [self.bot.user.name.lower(), 'core_commands', 'core commands'])): pref = self.bot.get_bot_prefix() response = f'**How To Use:** This bot features a variety of commands. You can get a list of all commands you have access to with the `{pref}help` command. In order to use a command your message has to start with the *bot prefix*, the bot prefix is currently set to `{pref}`. Simply type this prefix, followed by a command name, and you will run the command. For more information on individual commands, run `{pref}help` followed by the command name. This will give you info on the command, along with some examples of it and any aliases the command might have. You might not have access to all commands everywhere, the help command will only tell you about commands you have access to in that channel, and commands you can run only in the DMs with the bot. DM only commands will be labeled as such by the help command. Some commands accept extra input, an example would be how the help command accepts a command name. You can usually see an example of how the command is used on the command's help page. If you use a command incorrectly by missing some input or sending invalid input, it will send you the expected input. This is how to read the expected input: Arguments encased in `<>` are obligatory. Arguments encased in `()` are optional and can be skipped. Arguments written in all uppercase are placeholders like names. Arguments not written in uppercase are exact values. If an argument lists multiple things separated by `/` then any one of them is valid. The `<>` and `()` symbols are not part of the command. Sample expected input: `{pref}about (MODULE NAME)` Here `{pref}about` is the command, and it takes an optional argument. The argument is written in all uppercase, so it is a placeholder. In other words you are expected to replace 'MODULE NAME' with the actual name of a module. Since the module name is optional, sending just `{pref}about` is also a valid command.' (await ctx.send(response)) elif (module_name.lower() in self.bot.modules.keys()): usage = self.bot.modules[module_name.lower()].usage if (usage is None): (await ctx.send(f'The `{clean(ctx, module_name)}` module does not have its usage defined.')) else: usage_content = usage() if isinstance(usage_content, str): (await ctx.send((usage_content if (len(usage_content) < 1950) else f'{usage_content[:1949]}...'))) elif isinstance(usage_content, Embed): (await ctx.send(embed=usage_content)) else: response = f'No information for `{clean(ctx, module_name)}` module was found.' if (module_name not in [mod.replace('modules.', ) for mod in self.bot.extensions.keys()]): response += '\nAdditionally no module with this name is loaded.' (await ctx.send(response))
@commands.command(name='usage', usage='(MODULE NAME)') async def usage(self, ctx: commands.Context, *, module_name: str=None): 'This command explains how a module is intended to be used. If no module name is given it will\n show some basic information about usage of the bot itself.' if ((module_name is None) or (module_name.lower() in [self.bot.user.name.lower(), 'core_commands', 'core commands'])): pref = self.bot.get_bot_prefix() response = f'**How To Use:** This bot features a variety of commands. You can get a list of all commands you have access to with the `{pref}help` command. In order to use a command your message has to start with the *bot prefix*, the bot prefix is currently set to `{pref}`. Simply type this prefix, followed by a command name, and you will run the command. For more information on individual commands, run `{pref}help` followed by the command name. This will give you info on the command, along with some examples of it and any aliases the command might have. You might not have access to all commands everywhere, the help command will only tell you about commands you have access to in that channel, and commands you can run only in the DMs with the bot. DM only commands will be labeled as such by the help command. Some commands accept extra input, an example would be how the help command accepts a command name. You can usually see an example of how the command is used on the command's help page. If you use a command incorrectly by missing some input or sending invalid input, it will send you the expected input. This is how to read the expected input: Arguments encased in `<>` are obligatory. Arguments encased in `()` are optional and can be skipped. Arguments written in all uppercase are placeholders like names. Arguments not written in uppercase are exact values. If an argument lists multiple things separated by `/` then any one of them is valid. The `<>` and `()` symbols are not part of the command. Sample expected input: `{pref}about (MODULE NAME)` Here `{pref}about` is the command, and it takes an optional argument. The argument is written in all uppercase, so it is a placeholder. In other words you are expected to replace 'MODULE NAME' with the actual name of a module. Since the module name is optional, sending just `{pref}about` is also a valid command.' (await ctx.send(response)) elif (module_name.lower() in self.bot.modules.keys()): usage = self.bot.modules[module_name.lower()].usage if (usage is None): (await ctx.send(f'The `{clean(ctx, module_name)}` module does not have its usage defined.')) else: usage_content = usage() if isinstance(usage_content, str): (await ctx.send((usage_content if (len(usage_content) < 1950) else f'{usage_content[:1949]}...'))) elif isinstance(usage_content, Embed): (await ctx.send(embed=usage_content)) else: response = f'No information for `{clean(ctx, module_name)}` module was found.' if (module_name not in [mod.replace('modules.', ) for mod in self.bot.extensions.keys()]): response += '\nAdditionally no module with this name is loaded.' (await ctx.send(response))<|docstring|>This command explains how a module is intended to be used. If no module name is given it will show some basic information about usage of the bot itself.<|endoftext|>
af9c25ed33a177b44b3adcc039363aca86d1cbd21537bded97755ecf4c8e9303
@commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name='config', usage='<get/set/unset>') async def config(self, ctx: commands.Context): 'This command is used to get, set and unset configuration options used by other modules or commands. All\n config options are saves as strings. Converting them to the proper type is up to the module or command that\n uses them. See the help text for the subcommands for more info.' raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')
This command is used to get, set and unset configuration options used by other modules or commands. All config options are saves as strings. Converting them to the proper type is up to the module or command that uses them. See the help text for the subcommands for more info.
core_commands.py
config
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name='config', usage='<get/set/unset>') async def config(self, ctx: commands.Context): 'This command is used to get, set and unset configuration options used by other modules or commands. All\n config options are saves as strings. Converting them to the proper type is up to the module or command that\n uses them. See the help text for the subcommands for more info.' raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')
@commands.has_permissions(administrator=True) @commands.group(invoke_without_command=True, name='config', usage='<get/set/unset>') async def config(self, ctx: commands.Context): 'This command is used to get, set and unset configuration options used by other modules or commands. All\n config options are saves as strings. Converting them to the proper type is up to the module or command that\n uses them. See the help text for the subcommands for more info.' raise commands.BadArgument(f'No subcommand given for {ctx.command.name}.')<|docstring|>This command is used to get, set and unset configuration options used by other modules or commands. All config options are saves as strings. Converting them to the proper type is up to the module or command that uses them. See the help text for the subcommands for more info.<|endoftext|>
9a25e00616faaec6d85e4d24120e311aa4233ae6030c366e78f8b6813577406b
@commands.has_permissions(administrator=True) @config.command(name='get', usage='<CONFIG_OPTION/all>') async def config_get(self, ctx: commands.Context, option: str): 'This command is used to get the value of config options. Using this, one can check what configuration\n options are set to. Using the keyword `all` instead of an option name will print all options and their\n values.' option = option.lower() if (option == 'all'): if (not self.bot.config): (await ctx.send('No configuration options are set.')) return paginator = commands.Paginator() for line in [f'{key}: {value}' for (key, value) in self.bot.config.items()]: line = tbb.clean(ctx, line, False, True) paginator.add_line((line if (len(line) < 1992) else f'{line[:1989]}...')) for page in paginator.pages: (await ctx.send(page)) elif (option.lower() in self.bot.config): value = tbb.clean(ctx, self.bot.config[option], False, True) option = tbb.clean(ctx, option, False, True) line = f'Option: `{option}`, value: `{value}`' (await ctx.send((line if (len(line) < 1994) else f'{line[:1991]}...'))) else: option = tbb.clean(ctx, option, False, True) (await ctx.send(f'No configuration option `{(option if (len(option) < 1960) else option[:1959])}...` is set.'))
This command is used to get the value of config options. Using this, one can check what configuration options are set to. Using the keyword `all` instead of an option name will print all options and their values.
core_commands.py
config_get
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @config.command(name='get', usage='<CONFIG_OPTION/all>') async def config_get(self, ctx: commands.Context, option: str): 'This command is used to get the value of config options. Using this, one can check what configuration\n options are set to. Using the keyword `all` instead of an option name will print all options and their\n values.' option = option.lower() if (option == 'all'): if (not self.bot.config): (await ctx.send('No configuration options are set.')) return paginator = commands.Paginator() for line in [f'{key}: {value}' for (key, value) in self.bot.config.items()]: line = tbb.clean(ctx, line, False, True) paginator.add_line((line if (len(line) < 1992) else f'{line[:1989]}...')) for page in paginator.pages: (await ctx.send(page)) elif (option.lower() in self.bot.config): value = tbb.clean(ctx, self.bot.config[option], False, True) option = tbb.clean(ctx, option, False, True) line = f'Option: `{option}`, value: `{value}`' (await ctx.send((line if (len(line) < 1994) else f'{line[:1991]}...'))) else: option = tbb.clean(ctx, option, False, True) (await ctx.send(f'No configuration option `{(option if (len(option) < 1960) else option[:1959])}...` is set.'))
@commands.has_permissions(administrator=True) @config.command(name='get', usage='<CONFIG_OPTION/all>') async def config_get(self, ctx: commands.Context, option: str): 'This command is used to get the value of config options. Using this, one can check what configuration\n options are set to. Using the keyword `all` instead of an option name will print all options and their\n values.' option = option.lower() if (option == 'all'): if (not self.bot.config): (await ctx.send('No configuration options are set.')) return paginator = commands.Paginator() for line in [f'{key}: {value}' for (key, value) in self.bot.config.items()]: line = tbb.clean(ctx, line, False, True) paginator.add_line((line if (len(line) < 1992) else f'{line[:1989]}...')) for page in paginator.pages: (await ctx.send(page)) elif (option.lower() in self.bot.config): value = tbb.clean(ctx, self.bot.config[option], False, True) option = tbb.clean(ctx, option, False, True) line = f'Option: `{option}`, value: `{value}`' (await ctx.send((line if (len(line) < 1994) else f'{line[:1991]}...'))) else: option = tbb.clean(ctx, option, False, True) (await ctx.send(f'No configuration option `{(option if (len(option) < 1960) else option[:1959])}...` is set.'))<|docstring|>This command is used to get the value of config options. Using this, one can check what configuration options are set to. Using the keyword `all` instead of an option name will print all options and their values.<|endoftext|>
d87ab0f5113687dc2865474246b52c3633194516cd6114252c0683232b5798de
@commands.has_permissions(administrator=True) @config.command(name='set', usage='CONFIG_OPTION> <VALUE>') async def config_set(self, ctx: commands.Context, option: str, *, value: str): 'This command sets a configuration option. Configuration options are used by other modules or commands.\n Setting an option which already exists will overwrite the option. Setting an option which does not exist will\n create it. The keyword all cannot be used as a configuration option as it is used by the get command to get all\n options.' option = option.lower() if (option == 'all'): (await ctx.send('The keyword `all` cannot be used as a configuration option.')) else: self.bot.config[option] = value async with self.bot.db.acquire() as conn: (await conn.execute('INSERT INTO config VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = $2', option, value)) option = tbb.clean(ctx, option, False, True) value = tbb.clean(ctx, value, False, True) line = f'Configuration option `{option}` has been set to `{value}`.' (await ctx.send((line if (len(line) < 2000) else f'{line[:1996]}...')))
This command sets a configuration option. Configuration options are used by other modules or commands. Setting an option which already exists will overwrite the option. Setting an option which does not exist will create it. The keyword all cannot be used as a configuration option as it is used by the get command to get all options.
core_commands.py
config_set
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @config.command(name='set', usage='CONFIG_OPTION> <VALUE>') async def config_set(self, ctx: commands.Context, option: str, *, value: str): 'This command sets a configuration option. Configuration options are used by other modules or commands.\n Setting an option which already exists will overwrite the option. Setting an option which does not exist will\n create it. The keyword all cannot be used as a configuration option as it is used by the get command to get all\n options.' option = option.lower() if (option == 'all'): (await ctx.send('The keyword `all` cannot be used as a configuration option.')) else: self.bot.config[option] = value async with self.bot.db.acquire() as conn: (await conn.execute('INSERT INTO config VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = $2', option, value)) option = tbb.clean(ctx, option, False, True) value = tbb.clean(ctx, value, False, True) line = f'Configuration option `{option}` has been set to `{value}`.' (await ctx.send((line if (len(line) < 2000) else f'{line[:1996]}...')))
@commands.has_permissions(administrator=True) @config.command(name='set', usage='CONFIG_OPTION> <VALUE>') async def config_set(self, ctx: commands.Context, option: str, *, value: str): 'This command sets a configuration option. Configuration options are used by other modules or commands.\n Setting an option which already exists will overwrite the option. Setting an option which does not exist will\n create it. The keyword all cannot be used as a configuration option as it is used by the get command to get all\n options.' option = option.lower() if (option == 'all'): (await ctx.send('The keyword `all` cannot be used as a configuration option.')) else: self.bot.config[option] = value async with self.bot.db.acquire() as conn: (await conn.execute('INSERT INTO config VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = $2', option, value)) option = tbb.clean(ctx, option, False, True) value = tbb.clean(ctx, value, False, True) line = f'Configuration option `{option}` has been set to `{value}`.' (await ctx.send((line if (len(line) < 2000) else f'{line[:1996]}...')))<|docstring|>This command sets a configuration option. Configuration options are used by other modules or commands. Setting an option which already exists will overwrite the option. Setting an option which does not exist will create it. The keyword all cannot be used as a configuration option as it is used by the get command to get all options.<|endoftext|>
7948e5e94307cd6c6079af149d8e7a7f357f58c1f152ca30463b74d3397e8059
@commands.has_permissions(administrator=True) @config.command(name='unset', usage='<CONFIG_OPTION> <VALUE>') async def config_unset(self, ctx: commands.Context, option: str): 'This command allows for the removal of configuration options. Removing configuration options which are\n required by commands or modules will stop these from working.' option = option.lower() if (option in self.bot.config): del self.bot.config[option] async with self.bot.db.acquire() as conn: (await conn.execute('DELETE FROM config WHERE key = $1', option)) option = tbb.clean(ctx, option, False, True) line = f'Configuration option `{option}` has been unset.' (await ctx.send((line if (len(line) < 2000) else f'{line[:1996]}...'))) else: option = tbb.clean(ctx, option, False, True) line = f'No configuration option `{option}` exists.' (await ctx.send((line if (len(line) < 2000) else f'{line[:1996]}...')))
This command allows for the removal of configuration options. Removing configuration options which are required by commands or modules will stop these from working.
core_commands.py
config_unset
Travus/Travus_Bot_Base
2
python
@commands.has_permissions(administrator=True) @config.command(name='unset', usage='<CONFIG_OPTION> <VALUE>') async def config_unset(self, ctx: commands.Context, option: str): 'This command allows for the removal of configuration options. Removing configuration options which are\n required by commands or modules will stop these from working.' option = option.lower() if (option in self.bot.config): del self.bot.config[option] async with self.bot.db.acquire() as conn: (await conn.execute('DELETE FROM config WHERE key = $1', option)) option = tbb.clean(ctx, option, False, True) line = f'Configuration option `{option}` has been unset.' (await ctx.send((line if (len(line) < 2000) else f'{line[:1996]}...'))) else: option = tbb.clean(ctx, option, False, True) line = f'No configuration option `{option}` exists.' (await ctx.send((line if (len(line) < 2000) else f'{line[:1996]}...')))
@commands.has_permissions(administrator=True) @config.command(name='unset', usage='<CONFIG_OPTION> <VALUE>') async def config_unset(self, ctx: commands.Context, option: str): 'This command allows for the removal of configuration options. Removing configuration options which are\n required by commands or modules will stop these from working.' option = option.lower() if (option in self.bot.config): del self.bot.config[option] async with self.bot.db.acquire() as conn: (await conn.execute('DELETE FROM config WHERE key = $1', option)) option = tbb.clean(ctx, option, False, True) line = f'Configuration option `{option}` has been unset.' (await ctx.send((line if (len(line) < 2000) else f'{line[:1996]}...'))) else: option = tbb.clean(ctx, option, False, True) line = f'No configuration option `{option}` exists.' (await ctx.send((line if (len(line) < 2000) else f'{line[:1996]}...')))<|docstring|>This command allows for the removal of configuration options. Removing configuration options which are required by commands or modules will stop these from working.<|endoftext|>
a9e56263cae071da584a53397b6526417a9e6b602e8ec664c250057e5aa8d4a0
@commands.is_owner() @commands.command(name='shutdown', aliases=['goodbye', 'goodnight'], usage='(TIME BEFORE SHUTDOWN)') async def shutdown(self, ctx: commands.Context, countdown: str=None): 'This command turns the bot off. A delay can be set causing the bot to wait before shutting down. The time\n uses a format of numbers followed by units, see examples for details. Times supported are weeks (w), days (d),\n hours (h), minutes (m) and seconds (s), and even negative numbers. For this command the delay must be between\n 0 seconds and 24 hours. Supplying no time will cause the bot to shut down immediately. Once started, a shutdown\n cannot be stopped.' if (countdown is None): (await ctx.send('Goodbye!')) (await self.bot.close()) (await self.bot.db.close()) else: try: time = tbb.parse_time(countdown, 0, 86400, True) (await ctx.send(f'Shutdown will commence in {time} seconds.')) (await asleep(time)) (await ctx.send('Shutting down!')) (await self.bot.logout()) (await self.bot.db.close()) except ValueError as e: if (str(e) in ['Time too short.', 'Time too long.']): (await ctx.send('The time for this command must be between 0 seconds to 24 hours.')) else: (await ctx.send('The time could not be parsed correctly.')) self.log.error(f'{ctx.author.id}: {str(e)}') self.bot.last_error = f'{ctx.author.id}: {str(e)}'
This command turns the bot off. A delay can be set causing the bot to wait before shutting down. The time uses a format of numbers followed by units, see examples for details. Times supported are weeks (w), days (d), hours (h), minutes (m) and seconds (s), and even negative numbers. For this command the delay must be between 0 seconds and 24 hours. Supplying no time will cause the bot to shut down immediately. Once started, a shutdown cannot be stopped.
core_commands.py
shutdown
Travus/Travus_Bot_Base
2
python
@commands.is_owner() @commands.command(name='shutdown', aliases=['goodbye', 'goodnight'], usage='(TIME BEFORE SHUTDOWN)') async def shutdown(self, ctx: commands.Context, countdown: str=None): 'This command turns the bot off. A delay can be set causing the bot to wait before shutting down. The time\n uses a format of numbers followed by units, see examples for details. Times supported are weeks (w), days (d),\n hours (h), minutes (m) and seconds (s), and even negative numbers. For this command the delay must be between\n 0 seconds and 24 hours. Supplying no time will cause the bot to shut down immediately. Once started, a shutdown\n cannot be stopped.' if (countdown is None): (await ctx.send('Goodbye!')) (await self.bot.close()) (await self.bot.db.close()) else: try: time = tbb.parse_time(countdown, 0, 86400, True) (await ctx.send(f'Shutdown will commence in {time} seconds.')) (await asleep(time)) (await ctx.send('Shutting down!')) (await self.bot.logout()) (await self.bot.db.close()) except ValueError as e: if (str(e) in ['Time too short.', 'Time too long.']): (await ctx.send('The time for this command must be between 0 seconds to 24 hours.')) else: (await ctx.send('The time could not be parsed correctly.')) self.log.error(f'{ctx.author.id}: {str(e)}') self.bot.last_error = f'{ctx.author.id}: {str(e)}'
@commands.is_owner() @commands.command(name='shutdown', aliases=['goodbye', 'goodnight'], usage='(TIME BEFORE SHUTDOWN)') async def shutdown(self, ctx: commands.Context, countdown: str=None): 'This command turns the bot off. A delay can be set causing the bot to wait before shutting down. The time\n uses a format of numbers followed by units, see examples for details. Times supported are weeks (w), days (d),\n hours (h), minutes (m) and seconds (s), and even negative numbers. For this command the delay must be between\n 0 seconds and 24 hours. Supplying no time will cause the bot to shut down immediately. Once started, a shutdown\n cannot be stopped.' if (countdown is None): (await ctx.send('Goodbye!')) (await self.bot.close()) (await self.bot.db.close()) else: try: time = tbb.parse_time(countdown, 0, 86400, True) (await ctx.send(f'Shutdown will commence in {time} seconds.')) (await asleep(time)) (await ctx.send('Shutting down!')) (await self.bot.logout()) (await self.bot.db.close()) except ValueError as e: if (str(e) in ['Time too short.', 'Time too long.']): (await ctx.send('The time for this command must be between 0 seconds to 24 hours.')) else: (await ctx.send('The time could not be parsed correctly.')) self.log.error(f'{ctx.author.id}: {str(e)}') self.bot.last_error = f'{ctx.author.id}: {str(e)}'<|docstring|>This command turns the bot off. A delay can be set causing the bot to wait before shutting down. The time uses a format of numbers followed by units, see examples for details. Times supported are weeks (w), days (d), hours (h), minutes (m) and seconds (s), and even negative numbers. For this command the delay must be between 0 seconds and 24 hours. Supplying no time will cause the bot to shut down immediately. Once started, a shutdown cannot be stopped.<|endoftext|>
b08b40ad2b940c1aefda9259b57b7c58da60aad8724bcad29add63dcbb421a5d
async def load(): 'Contains the logic for loading a module.' if (f'{mod}.py' in listdir('modules')): self.bot.load_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully loaded.')) self.log.info(f"{ctx.author.id}: loaded '{mod}' module.") else: (await ctx.send(f'No `{mod_name}` module was found.'))
Contains the logic for loading a module.
core_commands.py
load
Travus/Travus_Bot_Base
2
python
async def load(): if (f'{mod}.py' in listdir('modules')): self.bot.load_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully loaded.')) self.log.info(f"{ctx.author.id}: loaded '{mod}' module.") else: (await ctx.send(f'No `{mod_name}` module was found.'))
async def load(): if (f'{mod}.py' in listdir('modules')): self.bot.load_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully loaded.')) self.log.info(f"{ctx.author.id}: loaded '{mod}' module.") else: (await ctx.send(f'No `{mod_name}` module was found.'))<|docstring|>Contains the logic for loading a module.<|endoftext|>
09298ab5c419c1b82bb5520a3b4010be1709326558f21855d50f432fe9a4366b
async def unload(): 'Contains the logic for unloading a module.' self.bot.unload_extension(f'modules.{mod}') (await ctx.send(f'Module `{mod_name}` successfully unloaded.')) self.log.info(f"{ctx.author.id}: unloaded '{mod}' module.")
Contains the logic for unloading a module.
core_commands.py
unload
Travus/Travus_Bot_Base
2
python
async def unload(): self.bot.unload_extension(f'modules.{mod}') (await ctx.send(f'Module `{mod_name}` successfully unloaded.')) self.log.info(f"{ctx.author.id}: unloaded '{mod}' module.")
async def unload(): self.bot.unload_extension(f'modules.{mod}') (await ctx.send(f'Module `{mod_name}` successfully unloaded.')) self.log.info(f"{ctx.author.id}: unloaded '{mod}' module.")<|docstring|>Contains the logic for unloading a module.<|endoftext|>
f5d68f2dff9ce094b9000c649f9d61efdd2b6655d6f717c2a0b71d7d705813c1
async def reload(): 'Contains the logic for reloading a module.' if (f'{mod}.py' in listdir('modules')): self.bot.reload_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully reloaded.')) self.log.info(f"{ctx.author.id}: reloaded '{mod}' module.") elif (mod in self.bot.modules): (await ctx.send(f'The `{mod_name}` module file is no longer found on disk. Reload canceled.')) else: (await ctx.send(f'No `{mod_name}` module was found.'))
Contains the logic for reloading a module.
core_commands.py
reload
Travus/Travus_Bot_Base
2
python
async def reload(): if (f'{mod}.py' in listdir('modules')): self.bot.reload_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully reloaded.')) self.log.info(f"{ctx.author.id}: reloaded '{mod}' module.") elif (mod in self.bot.modules): (await ctx.send(f'The `{mod_name}` module file is no longer found on disk. Reload canceled.')) else: (await ctx.send(f'No `{mod_name}` module was found.'))
async def reload(): if (f'{mod}.py' in listdir('modules')): self.bot.reload_extension(f'modules.{mod}') (await self.bot.update_command_states()) (await ctx.send(f'Module `{mod_name}` successfully reloaded.')) self.log.info(f"{ctx.author.id}: reloaded '{mod}' module.") elif (mod in self.bot.modules): (await ctx.send(f'The `{mod_name}` module file is no longer found on disk. Reload canceled.')) else: (await ctx.send(f'No `{mod_name}` module was found.'))<|docstring|>Contains the logic for reloading a module.<|endoftext|>
9cecccf7a495b0685d93748e868b3a360e2b24053f0e8a093df959ab245bd4d0
def bprop_to_augm(prim: Primitive, fn: FunctionType) -> Graph: 'Given a function for the bprop, make the augmented function.' info = NamedDebugInfo(prim=prim, name=prim.name) bprop = parse(fn) bprop.debug.name = None bprop.debug.about = About(info, 'grad_bprop') bprop.output = bprop.apply(primops.cons_tuple, (), bprop.output) (*args, dout) = bprop.parameters with About(info, 'grad_fprop'): outer = Graph() outer.transforms['primal'] = prim outer.output = Constant(None) mng = manage(bprop, outer) transf_args = [] for p in args: with About(p.debug, 'grad_fprop'): outer_p = outer.add_parameter() with About(p.debug, 'equiv'): transf_p = outer.apply(primops.Jinv, outer_p) mng.replace(p, transf_p) transf_args.append(transf_p) with About(dout.debug, 'grad_sens'): new_dout = bprop.add_parameter() mng.replace(dout, new_dout) bprop.parameters = [new_dout] result = outer.apply(primops.J, outer.apply(prim, *transf_args)) outer.output = outer.apply(primops.cons_tuple, result, outer.apply(primops.cons_tuple, bprop, ())) return clone(outer)
Given a function for the bprop, make the augmented function.
myia/prim/grad_implementations.py
bprop_to_augm
bartvm/myia
0
python
def bprop_to_augm(prim: Primitive, fn: FunctionType) -> Graph: info = NamedDebugInfo(prim=prim, name=prim.name) bprop = parse(fn) bprop.debug.name = None bprop.debug.about = About(info, 'grad_bprop') bprop.output = bprop.apply(primops.cons_tuple, (), bprop.output) (*args, dout) = bprop.parameters with About(info, 'grad_fprop'): outer = Graph() outer.transforms['primal'] = prim outer.output = Constant(None) mng = manage(bprop, outer) transf_args = [] for p in args: with About(p.debug, 'grad_fprop'): outer_p = outer.add_parameter() with About(p.debug, 'equiv'): transf_p = outer.apply(primops.Jinv, outer_p) mng.replace(p, transf_p) transf_args.append(transf_p) with About(dout.debug, 'grad_sens'): new_dout = bprop.add_parameter() mng.replace(dout, new_dout) bprop.parameters = [new_dout] result = outer.apply(primops.J, outer.apply(prim, *transf_args)) outer.output = outer.apply(primops.cons_tuple, result, outer.apply(primops.cons_tuple, bprop, ())) return clone(outer)
def bprop_to_augm(prim: Primitive, fn: FunctionType) -> Graph: info = NamedDebugInfo(prim=prim, name=prim.name) bprop = parse(fn) bprop.debug.name = None bprop.debug.about = About(info, 'grad_bprop') bprop.output = bprop.apply(primops.cons_tuple, (), bprop.output) (*args, dout) = bprop.parameters with About(info, 'grad_fprop'): outer = Graph() outer.transforms['primal'] = prim outer.output = Constant(None) mng = manage(bprop, outer) transf_args = [] for p in args: with About(p.debug, 'grad_fprop'): outer_p = outer.add_parameter() with About(p.debug, 'equiv'): transf_p = outer.apply(primops.Jinv, outer_p) mng.replace(p, transf_p) transf_args.append(transf_p) with About(dout.debug, 'grad_sens'): new_dout = bprop.add_parameter() mng.replace(dout, new_dout) bprop.parameters = [new_dout] result = outer.apply(primops.J, outer.apply(prim, *transf_args)) outer.output = outer.apply(primops.cons_tuple, result, outer.apply(primops.cons_tuple, bprop, ())) return clone(outer)<|docstring|>Given a function for the bprop, make the augmented function.<|endoftext|>
b62e292c130902034a191427551f4f6ef1b81f25de0647dfcb095667bd8bcd59
def register_bprop(prim): 'Register an augmented function for prim, given a backpropagator.' def deco(fn): fn2 = bprop_to_augm(prim, fn) return register(prim)(fn2) return deco
Register an augmented function for prim, given a backpropagator.
myia/prim/grad_implementations.py
register_bprop
bartvm/myia
0
python
def register_bprop(prim): def deco(fn): fn2 = bprop_to_augm(prim, fn) return register(prim)(fn2) return deco
def register_bprop(prim): def deco(fn): fn2 = bprop_to_augm(prim, fn) return register(prim)(fn2) return deco<|docstring|>Register an augmented function for prim, given a backpropagator.<|endoftext|>
96939db84b12397368ddf23d98c9decb95dcb44ac71f2bb3d55e8e7445d47a35
def register_augm(prim): 'Register an augmented function for prim.' from ..debug.label import short_labeler, short_relation_symbols as syms def deco(fn): fn2 = parse(fn) for g in manage(fn2, weak=True).graphs: name = short_labeler.name(g) name = name.replace('__fprop__', syms['grad_fprop']) g.debug.name = name.replace('__bprop__', syms['grad_bprop']) fn2.transforms['primal'] = prim return register(prim)(fn2) return deco
Register an augmented function for prim.
myia/prim/grad_implementations.py
register_augm
bartvm/myia
0
python
def register_augm(prim): from ..debug.label import short_labeler, short_relation_symbols as syms def deco(fn): fn2 = parse(fn) for g in manage(fn2, weak=True).graphs: name = short_labeler.name(g) name = name.replace('__fprop__', syms['grad_fprop']) g.debug.name = name.replace('__bprop__', syms['grad_bprop']) fn2.transforms['primal'] = prim return register(prim)(fn2) return deco
def register_augm(prim): from ..debug.label import short_labeler, short_relation_symbols as syms def deco(fn): fn2 = parse(fn) for g in manage(fn2, weak=True).graphs: name = short_labeler.name(g) name = name.replace('__fprop__', syms['grad_fprop']) g.debug.name = name.replace('__bprop__', syms['grad_bprop']) fn2.transforms['primal'] = prim return register(prim)(fn2) return deco<|docstring|>Register an augmented function for prim.<|endoftext|>
6dd0fc47b249b6735b3967037086ed632b688712fb815919015fe58b03850b1d
@register_bprop(primops.add) def bprop_add(x, y, dz): 'Backpropagator for primitive `add`.' return (dz, dz)
Backpropagator for primitive `add`.
myia/prim/grad_implementations.py
bprop_add
bartvm/myia
0
python
@register_bprop(primops.add) def bprop_add(x, y, dz): return (dz, dz)
@register_bprop(primops.add) def bprop_add(x, y, dz): return (dz, dz)<|docstring|>Backpropagator for primitive `add`.<|endoftext|>
df41264269371473ec66fe8cdd722890a53305f4eda40f92839e8f0e54d9ea14
@register_bprop(primops.sub) def bprop_sub(x, y, dz): 'Backpropagator for primitive `sub`.' return (dz, (- dz))
Backpropagator for primitive `sub`.
myia/prim/grad_implementations.py
bprop_sub
bartvm/myia
0
python
@register_bprop(primops.sub) def bprop_sub(x, y, dz): return (dz, (- dz))
@register_bprop(primops.sub) def bprop_sub(x, y, dz): return (dz, (- dz))<|docstring|>Backpropagator for primitive `sub`.<|endoftext|>
22f15a5752fda340e6a5e7a208ace713f956b4b48a80302f41328dc477e73fe8
@register_bprop(primops.mul) def bprop_mul(x, y, dz): 'Backpropagator for primitive `mul`.' return ((dz * y), (dz * x))
Backpropagator for primitive `mul`.
myia/prim/grad_implementations.py
bprop_mul
bartvm/myia
0
python
@register_bprop(primops.mul) def bprop_mul(x, y, dz): return ((dz * y), (dz * x))
@register_bprop(primops.mul) def bprop_mul(x, y, dz): return ((dz * y), (dz * x))<|docstring|>Backpropagator for primitive `mul`.<|endoftext|>
65ae29e6220c279ea99a9a5f5135acb973a985da9043a23d213d881a30d6c92f
@register_bprop(primops.div) def bprop_div(x, y, dz): 'Backpropagator for primitive `div`.' return ((dz / y), (((- dz) * x) / (y * y)))
Backpropagator for primitive `div`.
myia/prim/grad_implementations.py
bprop_div
bartvm/myia
0
python
@register_bprop(primops.div) def bprop_div(x, y, dz): return ((dz / y), (((- dz) * x) / (y * y)))
@register_bprop(primops.div) def bprop_div(x, y, dz): return ((dz / y), (((- dz) * x) / (y * y)))<|docstring|>Backpropagator for primitive `div`.<|endoftext|>
5f1c60b11aecc62d93ac9aae41e6282ca06941d3a9ea0256ab4a5bf5ea5881ce
@register_bprop(primops.pow) def bprop_pow(x, y, dz): 'Backpropagator for primitive `pow`.' return ((dz * (y * (x ** (y - 1)))), ((dz * log(x)) * (x ** y)))
Backpropagator for primitive `pow`.
myia/prim/grad_implementations.py
bprop_pow
bartvm/myia
0
python
@register_bprop(primops.pow) def bprop_pow(x, y, dz): return ((dz * (y * (x ** (y - 1)))), ((dz * log(x)) * (x ** y)))
@register_bprop(primops.pow) def bprop_pow(x, y, dz): return ((dz * (y * (x ** (y - 1)))), ((dz * log(x)) * (x ** y)))<|docstring|>Backpropagator for primitive `pow`.<|endoftext|>
1f4858d954aba856ce091ec6c41dba57d308e15a6ba7987407c14d49642fa952
@register_bprop(primops.uadd) def bprop_uadd(x, dz): 'Backpropagator for primitive `uadd`.' return (dz,)
Backpropagator for primitive `uadd`.
myia/prim/grad_implementations.py
bprop_uadd
bartvm/myia
0
python
@register_bprop(primops.uadd) def bprop_uadd(x, dz): return (dz,)
@register_bprop(primops.uadd) def bprop_uadd(x, dz): return (dz,)<|docstring|>Backpropagator for primitive `uadd`.<|endoftext|>
3bcf07eeabceacd7b3d1a555bf881fcb7ebbf06e11cb18afb7658e7d4499de4d
@register_bprop(primops.usub) def bprop_usub(x, dz): 'Backpropagator for primitive `usub`.' return ((- dz),)
Backpropagator for primitive `usub`.
myia/prim/grad_implementations.py
bprop_usub
bartvm/myia
0
python
@register_bprop(primops.usub) def bprop_usub(x, dz): return ((- dz),)
@register_bprop(primops.usub) def bprop_usub(x, dz): return ((- dz),)<|docstring|>Backpropagator for primitive `usub`.<|endoftext|>
1729e4ee7f5077b3faf3c85bd26a90e4ea5c1210d100a477aa99a3e7c6c138a1
@register_bprop(primops.gt) def bprop_gt(x, y, dz): 'Backpropagator for primitive `gt`.' return (zeros_like(x), zeros_like(y))
Backpropagator for primitive `gt`.
myia/prim/grad_implementations.py
bprop_gt
bartvm/myia
0
python
@register_bprop(primops.gt) def bprop_gt(x, y, dz): return (zeros_like(x), zeros_like(y))
@register_bprop(primops.gt) def bprop_gt(x, y, dz): return (zeros_like(x), zeros_like(y))<|docstring|>Backpropagator for primitive `gt`.<|endoftext|>
dbca8e8c466106c629172ba39f95ef0961c7b5b050b42e4330aeee750ec06c8f
@register_bprop(primops.lt) def bprop_lt(x, y, dz): 'Backpropagator for primitive `lt`.' return (zeros_like(x), zeros_like(y))
Backpropagator for primitive `lt`.
myia/prim/grad_implementations.py
bprop_lt
bartvm/myia
0
python
@register_bprop(primops.lt) def bprop_lt(x, y, dz): return (zeros_like(x), zeros_like(y))
@register_bprop(primops.lt) def bprop_lt(x, y, dz): return (zeros_like(x), zeros_like(y))<|docstring|>Backpropagator for primitive `lt`.<|endoftext|>
285b9cf89c4ec201671af49e15758b6054c491bf76405f36c247d1368a533259
@register_bprop(primops.ge) def bprop_ge(x, y, dz): 'Backpropagator for primitive `ge`.' return (zeros_like(x), zeros_like(y))
Backpropagator for primitive `ge`.
myia/prim/grad_implementations.py
bprop_ge
bartvm/myia
0
python
@register_bprop(primops.ge) def bprop_ge(x, y, dz): return (zeros_like(x), zeros_like(y))
@register_bprop(primops.ge) def bprop_ge(x, y, dz): return (zeros_like(x), zeros_like(y))<|docstring|>Backpropagator for primitive `ge`.<|endoftext|>
8c504a673a4fe67c626b9baec94df5a13541a6f010efc795b785faf3d5361b86
@register_bprop(primops.le) def bprop_le(x, y, dz): 'Backpropagator for primitive `le`.' return (zeros_like(x), zeros_like(y))
Backpropagator for primitive `le`.
myia/prim/grad_implementations.py
bprop_le
bartvm/myia
0
python
@register_bprop(primops.le) def bprop_le(x, y, dz): return (zeros_like(x), zeros_like(y))
@register_bprop(primops.le) def bprop_le(x, y, dz): return (zeros_like(x), zeros_like(y))<|docstring|>Backpropagator for primitive `le`.<|endoftext|>
569ebc58063d69c471bf914cd45799007882334d2a74b5c991f817be1eb68a77
@register_bprop(primops.cons_tuple) def bprop_cons_tuple(_head, _tail, dz): 'Backpropagator for primitive `cons_tuple`.' return (head(dz), tail(dz))
Backpropagator for primitive `cons_tuple`.
myia/prim/grad_implementations.py
bprop_cons_tuple
bartvm/myia
0
python
@register_bprop(primops.cons_tuple) def bprop_cons_tuple(_head, _tail, dz): return (head(dz), tail(dz))
@register_bprop(primops.cons_tuple) def bprop_cons_tuple(_head, _tail, dz): return (head(dz), tail(dz))<|docstring|>Backpropagator for primitive `cons_tuple`.<|endoftext|>
33772793c95a270dddf794f230d5cf142dd16bc9b6e081aa1e71980cdf128c96
@register_bprop(primops.head) def bprop_head(tup, dz): 'Backpropagator for primitive `head`.' return (cons_tuple(dz, zeros_like(tail(tup))),)
Backpropagator for primitive `head`.
myia/prim/grad_implementations.py
bprop_head
bartvm/myia
0
python
@register_bprop(primops.head) def bprop_head(tup, dz): return (cons_tuple(dz, zeros_like(tail(tup))),)
@register_bprop(primops.head) def bprop_head(tup, dz): return (cons_tuple(dz, zeros_like(tail(tup))),)<|docstring|>Backpropagator for primitive `head`.<|endoftext|>
f3bc52846fd81fd7c3b215e978e6033c9ee14831972731b496811e8573053c11
@register_bprop(primops.tail) def bprop_tail(tup, dz): 'Backpropagator for primitive `tail`.' return (cons_tuple(zeros_like(head(tup)), dz),)
Backpropagator for primitive `tail`.
myia/prim/grad_implementations.py
bprop_tail
bartvm/myia
0
python
@register_bprop(primops.tail) def bprop_tail(tup, dz): return (cons_tuple(zeros_like(head(tup)), dz),)
@register_bprop(primops.tail) def bprop_tail(tup, dz): return (cons_tuple(zeros_like(head(tup)), dz),)<|docstring|>Backpropagator for primitive `tail`.<|endoftext|>
ad6fc2d8cfed7da397a1964a3cf0dfd4fc306f488129cea8ed6d7c8bef13d1f2
@register_bprop(primops.getitem) def bprop_getitem(data, idx, dz): 'Backpropagator for primitive `getitem`.' return (setitem(zeros_like(data), idx, dz), zeros_like(idx))
Backpropagator for primitive `getitem`.
myia/prim/grad_implementations.py
bprop_getitem
bartvm/myia
0
python
@register_bprop(primops.getitem) def bprop_getitem(data, idx, dz): return (setitem(zeros_like(data), idx, dz), zeros_like(idx))
@register_bprop(primops.getitem) def bprop_getitem(data, idx, dz): return (setitem(zeros_like(data), idx, dz), zeros_like(idx))<|docstring|>Backpropagator for primitive `getitem`.<|endoftext|>