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 |
|---|---|---|---|---|---|---|---|---|---|
ac4dff7f99df3fefa8964a087108395b137a2215fd62605d087a19fca5cefd9b | @pytest.mark.parametrize('op', ['add', 'truediv', 'and_', 'xor', 'or_', 'lshift', 'rshift', 'mod', 'mul', 'rshift', 'sub', 'lt', 'le', 'eq', 'ne', 'gt', 'ge'])
def test_binop_two_signals_raw(target, simulator, op):
'\n Test that we can and two output signals for an expect\n '
if (op == 'mod'):
pytest.skip('urem missing from coreir verilog backend')
BinaryOpCircuit = gen_binary_op_circuit(op)
tester = fault.Tester(BinaryOpCircuit)
for _ in range(5):
(I0, I1) = gen_random_inputs(op)
tester.poke(tester._circuit.I0, I0)
tester.poke(tester._circuit.I1, I1)
tester.eval()
tester.expect(tester._circuit.O, getattr(operator, op)(tester.peek(tester._circuit.I0_out), tester.peek(tester._circuit.I1_out)))
run_test(tester, target, simulator) | Test that we can and two output signals for an expect | tests/test_expressions.py | test_binop_two_signals_raw | standanley/fault | 0 | python | @pytest.mark.parametrize('op', ['add', 'truediv', 'and_', 'xor', 'or_', 'lshift', 'rshift', 'mod', 'mul', 'rshift', 'sub', 'lt', 'le', 'eq', 'ne', 'gt', 'ge'])
def test_binop_two_signals_raw(target, simulator, op):
'\n \n '
if (op == 'mod'):
pytest.skip('urem missing from coreir verilog backend')
BinaryOpCircuit = gen_binary_op_circuit(op)
tester = fault.Tester(BinaryOpCircuit)
for _ in range(5):
(I0, I1) = gen_random_inputs(op)
tester.poke(tester._circuit.I0, I0)
tester.poke(tester._circuit.I1, I1)
tester.eval()
tester.expect(tester._circuit.O, getattr(operator, op)(tester.peek(tester._circuit.I0_out), tester.peek(tester._circuit.I1_out)))
run_test(tester, target, simulator) | @pytest.mark.parametrize('op', ['add', 'truediv', 'and_', 'xor', 'or_', 'lshift', 'rshift', 'mod', 'mul', 'rshift', 'sub', 'lt', 'le', 'eq', 'ne', 'gt', 'ge'])
def test_binop_two_signals_raw(target, simulator, op):
'\n \n '
if (op == 'mod'):
pytest.skip('urem missing from coreir verilog backend')
BinaryOpCircuit = gen_binary_op_circuit(op)
tester = fault.Tester(BinaryOpCircuit)
for _ in range(5):
(I0, I1) = gen_random_inputs(op)
tester.poke(tester._circuit.I0, I0)
tester.poke(tester._circuit.I1, I1)
tester.eval()
tester.expect(tester._circuit.O, getattr(operator, op)(tester.peek(tester._circuit.I0_out), tester.peek(tester._circuit.I1_out)))
run_test(tester, target, simulator)<|docstring|>Test that we can and two output signals for an expect<|endoftext|> |
3531d761356c6877426e5c9a3fae019c756b6b7be5cfd4641aef7b48bcf961c6 | def correct_rate(head_entity, topK_entity_idx, answers):
'\n :param head_entity: number index\n :param topK_entity_idx: topK list[number]\n :param answers: list[number]\n :return:\n '
points = 0
for candid in topK_entity_idx:
if ((candid != head_entity) and (candid in answers)):
points += 1
return (points / len(topK_entity_idx)) | :param head_entity: number index
:param topK_entity_idx: topK list[number]
:param answers: list[number]
:return: | answer_filtering_module/train.py | correct_rate | albert-jin/Rec-KGQA | 14 | python | def correct_rate(head_entity, topK_entity_idx, answers):
'\n :param head_entity: number index\n :param topK_entity_idx: topK list[number]\n :param answers: list[number]\n :return:\n '
points = 0
for candid in topK_entity_idx:
if ((candid != head_entity) and (candid in answers)):
points += 1
return (points / len(topK_entity_idx)) | def correct_rate(head_entity, topK_entity_idx, answers):
'\n :param head_entity: number index\n :param topK_entity_idx: topK list[number]\n :param answers: list[number]\n :return:\n '
points = 0
for candid in topK_entity_idx:
if ((candid != head_entity) and (candid in answers)):
points += 1
return (points / len(topK_entity_idx))<|docstring|>:param head_entity: number index
:param topK_entity_idx: topK list[number]
:param answers: list[number]
:return:<|endoftext|> |
dea077c38405f0e2d7f5ac625ed5c23521550f33f1ad9b9b5dfde0f20e1480c9 | def loadEngine():
'\n Creates an SQL engine instance.\n '
url = ''
server_info_path = ''
if ('api' in os.getcwd()):
server_info_path += '../'
if ('server' in os.getcwd()):
server_info_path += '../'
with open((server_info_path + 'server_info'), 'r') as f:
url = f.readline().strip()
e = MySQLEngine(url=('mysql+py' + url))
return e | Creates an SQL engine instance. | db/mysql_engine.py | loadEngine | nikwalia/schedule-generator | 1 | python | def loadEngine():
'\n \n '
url =
server_info_path =
if ('api' in os.getcwd()):
server_info_path += '../'
if ('server' in os.getcwd()):
server_info_path += '../'
with open((server_info_path + 'server_info'), 'r') as f:
url = f.readline().strip()
e = MySQLEngine(url=('mysql+py' + url))
return e | def loadEngine():
'\n \n '
url =
server_info_path =
if ('api' in os.getcwd()):
server_info_path += '../'
if ('server' in os.getcwd()):
server_info_path += '../'
with open((server_info_path + 'server_info'), 'r') as f:
url = f.readline().strip()
e = MySQLEngine(url=('mysql+py' + url))
return e<|docstring|>Creates an SQL engine instance.<|endoftext|> |
df9677212bf1e80a19d249201348ba12774acdf435f274d283bf118a2e778eb2 | def __init__(self, **kwargs):
'\n Store connection URL, create interaction instance, and establish connection.\n \n :param kwargs: contains information for connecting to DB\n '
if ('url' in kwargs):
self.__url = kwargs['url']
else:
self.__url = ((((('mysql://' + kwargs['username']) + ':') + kwargs['password']) + '@') + kwargs['server'])
self.__engine = create_engine(self.__url)
self.__connection = None | Store connection URL, create interaction instance, and establish connection.
:param kwargs: contains information for connecting to DB | db/mysql_engine.py | __init__ | nikwalia/schedule-generator | 1 | python | def __init__(self, **kwargs):
'\n Store connection URL, create interaction instance, and establish connection.\n \n :param kwargs: contains information for connecting to DB\n '
if ('url' in kwargs):
self.__url = kwargs['url']
else:
self.__url = ((((('mysql://' + kwargs['username']) + ':') + kwargs['password']) + '@') + kwargs['server'])
self.__engine = create_engine(self.__url)
self.__connection = None | def __init__(self, **kwargs):
'\n Store connection URL, create interaction instance, and establish connection.\n \n :param kwargs: contains information for connecting to DB\n '
if ('url' in kwargs):
self.__url = kwargs['url']
else:
self.__url = ((((('mysql://' + kwargs['username']) + ':') + kwargs['password']) + '@') + kwargs['server'])
self.__engine = create_engine(self.__url)
self.__connection = None<|docstring|>Store connection URL, create interaction instance, and establish connection.
:param kwargs: contains information for connecting to DB<|endoftext|> |
8c815403bae37a67cd35e39cb4d6dd7131ba5ad7be67356955692b73711e766c | def __del__(self):
'\n Destructor. Closes connection, then deletes members.\n '
del self.__connection
del self.__engine
del self.__url | Destructor. Closes connection, then deletes members. | db/mysql_engine.py | __del__ | nikwalia/schedule-generator | 1 | python | def __del__(self):
'\n \n '
del self.__connection
del self.__engine
del self.__url | def __del__(self):
'\n \n '
del self.__connection
del self.__engine
del self.__url<|docstring|>Destructor. Closes connection, then deletes members.<|endoftext|> |
691e32fac9822a80f870b0b72f07263fce1264db3bbbe82be255c5b6bca8037d | def open(self):
'\n Opens a connection if it was manually closed.\n '
if (self.__engine is None):
self.__engine = create_engine(self.__url) | Opens a connection if it was manually closed. | db/mysql_engine.py | open | nikwalia/schedule-generator | 1 | python | def open(self):
'\n \n '
if (self.__engine is None):
self.__engine = create_engine(self.__url) | def open(self):
'\n \n '
if (self.__engine is None):
self.__engine = create_engine(self.__url)<|docstring|>Opens a connection if it was manually closed.<|endoftext|> |
390028b1d3da5c200f8f5222c07663ee7f3a7dbfe709eba57576766541a6ffca | def close(self):
'\n Manually closes a connection. Should be used only in debug when engine is not automatically deleted.\n '
if (self.__engine is not None):
self.__engine = None | Manually closes a connection. Should be used only in debug when engine is not automatically deleted. | db/mysql_engine.py | close | nikwalia/schedule-generator | 1 | python | def close(self):
'\n \n '
if (self.__engine is not None):
self.__engine = None | def close(self):
'\n \n '
if (self.__engine is not None):
self.__engine = None<|docstring|>Manually closes a connection. Should be used only in debug when engine is not automatically deleted.<|endoftext|> |
1b742fd4bd39df54ab1b51ca59f688d3fccb6f474bdb105840c5e1f6c05d634d | def is_open(self):
'\n Checks if the connection is already open\n '
return ((self.__connection is not None) and (self.__engine is not None)) | Checks if the connection is already open | db/mysql_engine.py | is_open | nikwalia/schedule-generator | 1 | python | def is_open(self):
'\n \n '
return ((self.__connection is not None) and (self.__engine is not None)) | def is_open(self):
'\n \n '
return ((self.__connection is not None) and (self.__engine is not None))<|docstring|>Checks if the connection is already open<|endoftext|> |
8188c983edd3a58dc007b0bce2eb41945cd75295de29277a8362f0f8b30c6887 | def wrapped_query(self, query: str):
'\n Gets data and returns it in a Pandas dataframe\n \n :param query: string query to execute\n \n :return: Pandas DataFrame containing query results\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
if ('SELECT' not in query):
raise ValueError('Retrieving data only')
_res = self.__connection.execute(query)
_table_headers = _res.keys()
_dat = []
for _row in _res:
_dat.append(_row)
if (self.__connection is not None):
self.__connection.close()
self.__connection = None
return pd.DataFrame(_dat, columns=_table_headers) | Gets data and returns it in a Pandas dataframe
:param query: string query to execute
:return: Pandas DataFrame containing query results | db/mysql_engine.py | wrapped_query | nikwalia/schedule-generator | 1 | python | def wrapped_query(self, query: str):
'\n Gets data and returns it in a Pandas dataframe\n \n :param query: string query to execute\n \n :return: Pandas DataFrame containing query results\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
if ('SELECT' not in query):
raise ValueError('Retrieving data only')
_res = self.__connection.execute(query)
_table_headers = _res.keys()
_dat = []
for _row in _res:
_dat.append(_row)
if (self.__connection is not None):
self.__connection.close()
self.__connection = None
return pd.DataFrame(_dat, columns=_table_headers) | def wrapped_query(self, query: str):
'\n Gets data and returns it in a Pandas dataframe\n \n :param query: string query to execute\n \n :return: Pandas DataFrame containing query results\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
if ('SELECT' not in query):
raise ValueError('Retrieving data only')
_res = self.__connection.execute(query)
_table_headers = _res.keys()
_dat = []
for _row in _res:
_dat.append(_row)
if (self.__connection is not None):
self.__connection.close()
self.__connection = None
return pd.DataFrame(_dat, columns=_table_headers)<|docstring|>Gets data and returns it in a Pandas dataframe
:param query: string query to execute
:return: Pandas DataFrame containing query results<|endoftext|> |
d11feba8e84809b04f89884677f3f74a8ae06d412ad4e2bc7ac906f908a3bde1 | def raw_operation(self, query: str, return_val=False):
'\n Executes a raw MySQL command\n \n :param query: string query to execute\n :param return_val: boolean of whether the query will return something.\n Defaults to False.\n \n :return: Pandas DataFrame if return_val == True\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
if return_val:
res = self.__connection.execute(query)
out = []
for row in res:
out.append(row)
return out
else:
self.__connection.execute(query)
self.__connection.close()
self.__connection = None | Executes a raw MySQL command
:param query: string query to execute
:param return_val: boolean of whether the query will return something.
Defaults to False.
:return: Pandas DataFrame if return_val == True | db/mysql_engine.py | raw_operation | nikwalia/schedule-generator | 1 | python | def raw_operation(self, query: str, return_val=False):
'\n Executes a raw MySQL command\n \n :param query: string query to execute\n :param return_val: boolean of whether the query will return something.\n Defaults to False.\n \n :return: Pandas DataFrame if return_val == True\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
if return_val:
res = self.__connection.execute(query)
out = []
for row in res:
out.append(row)
return out
else:
self.__connection.execute(query)
self.__connection.close()
self.__connection = None | def raw_operation(self, query: str, return_val=False):
'\n Executes a raw MySQL command\n \n :param query: string query to execute\n :param return_val: boolean of whether the query will return something.\n Defaults to False.\n \n :return: Pandas DataFrame if return_val == True\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
if return_val:
res = self.__connection.execute(query)
out = []
for row in res:
out.append(row)
return out
else:
self.__connection.execute(query)
self.__connection.close()
self.__connection = None<|docstring|>Executes a raw MySQL command
:param query: string query to execute
:param return_val: boolean of whether the query will return something.
Defaults to False.
:return: Pandas DataFrame if return_val == True<|endoftext|> |
0a9e58726fea34aacffdf963a2e5363184fd03d6e852769767c4786b8027189e | def stored_proc(self, stored_proc: str, input_args: list, output_arg_length: int):
'\n Call a stored procedure. Note that this does not support INOUT arguments.\n\n :param stored_proc: name of stored procedure\n :param input_args: args to pass into stored procedure\n :output_arg_length: number of arguments to return. can be 0.\n :returns: results of the stored procedure\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
_query_tuple = []
for elem in input_args:
if isinstance(elem, str):
_query_tuple.append("'{}'")
else:
_query_tuple.append('{}')
_output_tuple = []
for i in range(output_arg_length):
_output_tuple.append('@res{}'.format(i))
_query_tuple.extend(_output_tuple)
_command = 'CALL {}({});'.format(stored_proc, ', '.join(_query_tuple).format(*input_args))
self.__connection.execute(_command)
if (output_arg_length > 0):
_output = []
_res_command = (('SELECT ' + ', '.join(_output_tuple)) + ';')
_results = self.__connection.execute(_res_command)
for _res in _results:
_output.append(_res)
self.__connection.close()
self.__connection = None
return _output | Call a stored procedure. Note that this does not support INOUT arguments.
:param stored_proc: name of stored procedure
:param input_args: args to pass into stored procedure
:output_arg_length: number of arguments to return. can be 0.
:returns: results of the stored procedure | db/mysql_engine.py | stored_proc | nikwalia/schedule-generator | 1 | python | def stored_proc(self, stored_proc: str, input_args: list, output_arg_length: int):
'\n Call a stored procedure. Note that this does not support INOUT arguments.\n\n :param stored_proc: name of stored procedure\n :param input_args: args to pass into stored procedure\n :output_arg_length: number of arguments to return. can be 0.\n :returns: results of the stored procedure\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
_query_tuple = []
for elem in input_args:
if isinstance(elem, str):
_query_tuple.append("'{}'")
else:
_query_tuple.append('{}')
_output_tuple = []
for i in range(output_arg_length):
_output_tuple.append('@res{}'.format(i))
_query_tuple.extend(_output_tuple)
_command = 'CALL {}({});'.format(stored_proc, ', '.join(_query_tuple).format(*input_args))
self.__connection.execute(_command)
if (output_arg_length > 0):
_output = []
_res_command = (('SELECT ' + ', '.join(_output_tuple)) + ';')
_results = self.__connection.execute(_res_command)
for _res in _results:
_output.append(_res)
self.__connection.close()
self.__connection = None
return _output | def stored_proc(self, stored_proc: str, input_args: list, output_arg_length: int):
'\n Call a stored procedure. Note that this does not support INOUT arguments.\n\n :param stored_proc: name of stored procedure\n :param input_args: args to pass into stored procedure\n :output_arg_length: number of arguments to return. can be 0.\n :returns: results of the stored procedure\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
_query_tuple = []
for elem in input_args:
if isinstance(elem, str):
_query_tuple.append("'{}'")
else:
_query_tuple.append('{}')
_output_tuple = []
for i in range(output_arg_length):
_output_tuple.append('@res{}'.format(i))
_query_tuple.extend(_output_tuple)
_command = 'CALL {}({});'.format(stored_proc, ', '.join(_query_tuple).format(*input_args))
self.__connection.execute(_command)
if (output_arg_length > 0):
_output = []
_res_command = (('SELECT ' + ', '.join(_output_tuple)) + ';')
_results = self.__connection.execute(_res_command)
for _res in _results:
_output.append(_res)
self.__connection.close()
self.__connection = None
return _output<|docstring|>Call a stored procedure. Note that this does not support INOUT arguments.
:param stored_proc: name of stored procedure
:param input_args: args to pass into stored procedure
:output_arg_length: number of arguments to return. can be 0.
:returns: results of the stored procedure<|endoftext|> |
3049a8250d25d2dd33f20d23289a91c54d34f653affe59f0f48417cd4a20e326 | def drop_rows(self, query: str):
'\n Drops rows from a table based on some conditions\n\n :param query: the delete command to execute\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
if ('DELETE' not in query):
raise ValueError('Not dropping anything')
if ('WHERE' not in query):
raise ValueError('Unsafe dropping without WHERE not permitted')
self.__connection = self.__engine.connect()
self.__connection.execute(query)
self.__connection.close()
self.__connection = None | Drops rows from a table based on some conditions
:param query: the delete command to execute | db/mysql_engine.py | drop_rows | nikwalia/schedule-generator | 1 | python | def drop_rows(self, query: str):
'\n Drops rows from a table based on some conditions\n\n :param query: the delete command to execute\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
if ('DELETE' not in query):
raise ValueError('Not dropping anything')
if ('WHERE' not in query):
raise ValueError('Unsafe dropping without WHERE not permitted')
self.__connection = self.__engine.connect()
self.__connection.execute(query)
self.__connection.close()
self.__connection = None | def drop_rows(self, query: str):
'\n Drops rows from a table based on some conditions\n\n :param query: the delete command to execute\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
if ('DELETE' not in query):
raise ValueError('Not dropping anything')
if ('WHERE' not in query):
raise ValueError('Unsafe dropping without WHERE not permitted')
self.__connection = self.__engine.connect()
self.__connection.execute(query)
self.__connection.close()
self.__connection = None<|docstring|>Drops rows from a table based on some conditions
:param query: the delete command to execute<|endoftext|> |
817093be2e190594e61716cd6cb9b5f81d5207037f926a490bedf79e37402897 | def insert_df(self, data: pd.DataFrame, table_name: str):
'\n Inserts data into an already-existing database table. Validates columns\n to ensure the table being inserted into matches the data types of the\n dataframe.\n \n :param data: pandas DataFrame containing data to insert\n :param table_name: which table to insert to\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
_table_headers = self.__get_header_types(table_name)
self.__connection = self.__engine.connect()
for (df_header, table_header) in zip(data.dtypes, _table_headers):
if ((df_header in ('float64', 'float')) and (table_header != 'float')):
raise TypeError(('Incompatible data types: %s and %s' % (df_header, table_header)))
elif ((df_header in ('int64', 'int')) and (table_header != 'int')):
raise TypeError(('Incompatible data types: %s and %s' % (df_header, table_header)))
elif ((df_header == 'object') and ('varchar' not in table_header) and (table_header != 'json')):
raise TypeError(('Incompatible data types: %s and %s' % (df_header, table_header)))
_name = ('student_info.%s' % table_name)
_command = ('INSERT INTO student_info.%s VALUES\n' % table_name)
_values = []
insert_tuple = []
for dt in data.dtypes:
if (dt == 'object'):
insert_tuple.append("'%s'")
elif ((dt == 'float64') or (dt == 'float')):
insert_tuple.append('%f')
elif ((dt == 'int64') or (dt == 'int')):
insert_tuple.append('%d')
insert_tuple = (('(' + ', '.join(insert_tuple)) + ')')
for row in data.to_numpy():
_values.append((insert_tuple % tuple(row)))
_command += ',\n'.join(_values)
self.__connection.execute(_command)
self.__connection.close()
self.__connection = None | Inserts data into an already-existing database table. Validates columns
to ensure the table being inserted into matches the data types of the
dataframe.
:param data: pandas DataFrame containing data to insert
:param table_name: which table to insert to | db/mysql_engine.py | insert_df | nikwalia/schedule-generator | 1 | python | def insert_df(self, data: pd.DataFrame, table_name: str):
'\n Inserts data into an already-existing database table. Validates columns\n to ensure the table being inserted into matches the data types of the\n dataframe.\n \n :param data: pandas DataFrame containing data to insert\n :param table_name: which table to insert to\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
_table_headers = self.__get_header_types(table_name)
self.__connection = self.__engine.connect()
for (df_header, table_header) in zip(data.dtypes, _table_headers):
if ((df_header in ('float64', 'float')) and (table_header != 'float')):
raise TypeError(('Incompatible data types: %s and %s' % (df_header, table_header)))
elif ((df_header in ('int64', 'int')) and (table_header != 'int')):
raise TypeError(('Incompatible data types: %s and %s' % (df_header, table_header)))
elif ((df_header == 'object') and ('varchar' not in table_header) and (table_header != 'json')):
raise TypeError(('Incompatible data types: %s and %s' % (df_header, table_header)))
_name = ('student_info.%s' % table_name)
_command = ('INSERT INTO student_info.%s VALUES\n' % table_name)
_values = []
insert_tuple = []
for dt in data.dtypes:
if (dt == 'object'):
insert_tuple.append("'%s'")
elif ((dt == 'float64') or (dt == 'float')):
insert_tuple.append('%f')
elif ((dt == 'int64') or (dt == 'int')):
insert_tuple.append('%d')
insert_tuple = (('(' + ', '.join(insert_tuple)) + ')')
for row in data.to_numpy():
_values.append((insert_tuple % tuple(row)))
_command += ',\n'.join(_values)
self.__connection.execute(_command)
self.__connection.close()
self.__connection = None | def insert_df(self, data: pd.DataFrame, table_name: str):
'\n Inserts data into an already-existing database table. Validates columns\n to ensure the table being inserted into matches the data types of the\n dataframe.\n \n :param data: pandas DataFrame containing data to insert\n :param table_name: which table to insert to\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
_table_headers = self.__get_header_types(table_name)
self.__connection = self.__engine.connect()
for (df_header, table_header) in zip(data.dtypes, _table_headers):
if ((df_header in ('float64', 'float')) and (table_header != 'float')):
raise TypeError(('Incompatible data types: %s and %s' % (df_header, table_header)))
elif ((df_header in ('int64', 'int')) and (table_header != 'int')):
raise TypeError(('Incompatible data types: %s and %s' % (df_header, table_header)))
elif ((df_header == 'object') and ('varchar' not in table_header) and (table_header != 'json')):
raise TypeError(('Incompatible data types: %s and %s' % (df_header, table_header)))
_name = ('student_info.%s' % table_name)
_command = ('INSERT INTO student_info.%s VALUES\n' % table_name)
_values = []
insert_tuple = []
for dt in data.dtypes:
if (dt == 'object'):
insert_tuple.append("'%s'")
elif ((dt == 'float64') or (dt == 'float')):
insert_tuple.append('%f')
elif ((dt == 'int64') or (dt == 'int')):
insert_tuple.append('%d')
insert_tuple = (('(' + ', '.join(insert_tuple)) + ')')
for row in data.to_numpy():
_values.append((insert_tuple % tuple(row)))
_command += ',\n'.join(_values)
self.__connection.execute(_command)
self.__connection.close()
self.__connection = None<|docstring|>Inserts data into an already-existing database table. Validates columns
to ensure the table being inserted into matches the data types of the
dataframe.
:param data: pandas DataFrame containing data to insert
:param table_name: which table to insert to<|endoftext|> |
5283b1633c26466aba8d11077db7f751f1cfc29c9758315bef3c05397e80c0f9 | def insert_tuple(self, data: tuple, table_name: str):
'\n Inserts data into an already-existing database table. Validates columns\n to ensure the table being inserted into matches the data types of the\n tuple\n \n :param data: tuple containing data to insert\n :param table_name: which table to insert to\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
_table_headers = self.__get_header_types(table_name)
tuple_types = tuple([type(val) for val in data])
for (tuple_dtype, table_header) in zip(tuple_types, _table_headers):
if ((tuple_dtype in ('float64', 'float')) and (table_header != 'float')):
raise TypeError(('Incompatible data types: %s and %s' % (tuple_dtype, table_header)))
elif ((tuple_dtype in ('int64', 'int')) and (table_header != 'int')):
raise TypeError(('Incompatible data types: %s and %s' % (tuple_dtype, table_header)))
elif ((tuple_dtype == 'object') and ('varchar' not in table_header) and (table_header != 'json')):
raise TypeError(('Incompatible data types: %s and %s' % (tuple_dtype, table_header)))
_name = ('student_info.%s' % table_name)
_command = ('INSERT INTO student_info.%s VALUES\n' % table_name)
insert_tuple = []
for dt in data.dtypes:
if (dt == 'object'):
insert_tuple.append("'%s'")
elif ((dt == 'float64') or (dt == 'float')):
insert_tuple.append('%f')
elif ((dt == 'int64') or (dt == 'int')):
insert_tuple.append('%d')
insert_tuple = (('(' + ', '.join(insert_tuple)) + ')')
_command += (insert_tuple % data)
self.__connection.execute(_command)
self.__connection.close()
self.__connection = None | Inserts data into an already-existing database table. Validates columns
to ensure the table being inserted into matches the data types of the
tuple
:param data: tuple containing data to insert
:param table_name: which table to insert to | db/mysql_engine.py | insert_tuple | nikwalia/schedule-generator | 1 | python | def insert_tuple(self, data: tuple, table_name: str):
'\n Inserts data into an already-existing database table. Validates columns\n to ensure the table being inserted into matches the data types of the\n tuple\n \n :param data: tuple containing data to insert\n :param table_name: which table to insert to\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
_table_headers = self.__get_header_types(table_name)
tuple_types = tuple([type(val) for val in data])
for (tuple_dtype, table_header) in zip(tuple_types, _table_headers):
if ((tuple_dtype in ('float64', 'float')) and (table_header != 'float')):
raise TypeError(('Incompatible data types: %s and %s' % (tuple_dtype, table_header)))
elif ((tuple_dtype in ('int64', 'int')) and (table_header != 'int')):
raise TypeError(('Incompatible data types: %s and %s' % (tuple_dtype, table_header)))
elif ((tuple_dtype == 'object') and ('varchar' not in table_header) and (table_header != 'json')):
raise TypeError(('Incompatible data types: %s and %s' % (tuple_dtype, table_header)))
_name = ('student_info.%s' % table_name)
_command = ('INSERT INTO student_info.%s VALUES\n' % table_name)
insert_tuple = []
for dt in data.dtypes:
if (dt == 'object'):
insert_tuple.append("'%s'")
elif ((dt == 'float64') or (dt == 'float')):
insert_tuple.append('%f')
elif ((dt == 'int64') or (dt == 'int')):
insert_tuple.append('%d')
insert_tuple = (('(' + ', '.join(insert_tuple)) + ')')
_command += (insert_tuple % data)
self.__connection.execute(_command)
self.__connection.close()
self.__connection = None | def insert_tuple(self, data: tuple, table_name: str):
'\n Inserts data into an already-existing database table. Validates columns\n to ensure the table being inserted into matches the data types of the\n tuple\n \n :param data: tuple containing data to insert\n :param table_name: which table to insert to\n '
if (self.__engine is None):
raise AttributeError('Engine is not initialized')
self.__connection = self.__engine.connect()
_table_headers = self.__get_header_types(table_name)
tuple_types = tuple([type(val) for val in data])
for (tuple_dtype, table_header) in zip(tuple_types, _table_headers):
if ((tuple_dtype in ('float64', 'float')) and (table_header != 'float')):
raise TypeError(('Incompatible data types: %s and %s' % (tuple_dtype, table_header)))
elif ((tuple_dtype in ('int64', 'int')) and (table_header != 'int')):
raise TypeError(('Incompatible data types: %s and %s' % (tuple_dtype, table_header)))
elif ((tuple_dtype == 'object') and ('varchar' not in table_header) and (table_header != 'json')):
raise TypeError(('Incompatible data types: %s and %s' % (tuple_dtype, table_header)))
_name = ('student_info.%s' % table_name)
_command = ('INSERT INTO student_info.%s VALUES\n' % table_name)
insert_tuple = []
for dt in data.dtypes:
if (dt == 'object'):
insert_tuple.append("'%s'")
elif ((dt == 'float64') or (dt == 'float')):
insert_tuple.append('%f')
elif ((dt == 'int64') or (dt == 'int')):
insert_tuple.append('%d')
insert_tuple = (('(' + ', '.join(insert_tuple)) + ')')
_command += (insert_tuple % data)
self.__connection.execute(_command)
self.__connection.close()
self.__connection = None<|docstring|>Inserts data into an already-existing database table. Validates columns
to ensure the table being inserted into matches the data types of the
tuple
:param data: tuple containing data to insert
:param table_name: which table to insert to<|endoftext|> |
e4986a4c29bc30791989dab29c67d412bc6a4bd43e181aa130f4fb1d05c05cd9 | def get_club_personas(club_id):
'Fetch personaname for a player. Fetch directly via http. Store in mongodb.'
url = (((('https://www.easports.com/iframe/nhl14proclubs/api/platforms/' + settings.PLATFORM) + '/clubs/') + club_id) + '/members')
personas = {}
response = urllib.urlopen(url)
try:
temp = json.loads(response.read())
except ValueError:
return personas
for player in temp['raw'][0]:
person = {'personaname': temp['raw'][0][player]['name'], '_id': player}
personas[player] = person
'try:\n db.personas.insert_one(person)\n except DuplicateKeyError:\n pass'
return personas | Fetch personaname for a player. Fetch directly via http. Store in mongodb. | repository/http.py | get_club_personas | glebb/eashl | 1 | python | def get_club_personas(club_id):
url = (((('https://www.easports.com/iframe/nhl14proclubs/api/platforms/' + settings.PLATFORM) + '/clubs/') + club_id) + '/members')
personas = {}
response = urllib.urlopen(url)
try:
temp = json.loads(response.read())
except ValueError:
return personas
for player in temp['raw'][0]:
person = {'personaname': temp['raw'][0][player]['name'], '_id': player}
personas[player] = person
'try:\n db.personas.insert_one(person)\n except DuplicateKeyError:\n pass'
return personas | def get_club_personas(club_id):
url = (((('https://www.easports.com/iframe/nhl14proclubs/api/platforms/' + settings.PLATFORM) + '/clubs/') + club_id) + '/members')
personas = {}
response = urllib.urlopen(url)
try:
temp = json.loads(response.read())
except ValueError:
return personas
for player in temp['raw'][0]:
person = {'personaname': temp['raw'][0][player]['name'], '_id': player}
personas[player] = person
'try:\n db.personas.insert_one(person)\n except DuplicateKeyError:\n pass'
return personas<|docstring|>Fetch personaname for a player. Fetch directly via http. Store in mongodb.<|endoftext|> |
bf2e71f6cc2cdfc703bf48593a2eb8b3cff3833f06e04f3fc31bd76aea6ea093 | @property
def stdout(self):
'\n Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT.\n Если есть любое значение в CROSSPM_STDOUT - оно понимается как True\n :return:\n '
stdout = self._args['--stdout']
if stdout:
return True
stdout_env = os.getenv('CROSSPM_STDOUT', None)
if (stdout_env is not None):
return True
return False | Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT.
Если есть любое значение в CROSSPM_STDOUT - оно понимается как True
:return: | crosspm/cpm.py | stdout | devopshq/crosspm2 | 3 | python | @property
def stdout(self):
'\n Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT.\n Если есть любое значение в CROSSPM_STDOUT - оно понимается как True\n :return:\n '
stdout = self._args['--stdout']
if stdout:
return True
stdout_env = os.getenv('CROSSPM_STDOUT', None)
if (stdout_env is not None):
return True
return False | @property
def stdout(self):
'\n Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT.\n Если есть любое значение в CROSSPM_STDOUT - оно понимается как True\n :return:\n '
stdout = self._args['--stdout']
if stdout:
return True
stdout_env = os.getenv('CROSSPM_STDOUT', None)
if (stdout_env is not None):
return True
return False<|docstring|>Флаг --stdout может быть взят из переменной окружения CROSSPM_STDOUT.
Если есть любое значение в CROSSPM_STDOUT - оно понимается как True
:return:<|endoftext|> |
8f7b97da808bf09c7261bde1e3e9c0ac1750c2453b0418c9b3a8b2bdd0433d03 | @staticmethod
def prepare_args(args, windows=None):
'\n Prepare args - add support for old interface, e.g:\n - --recursive was "flag" and for now it support True or False value\n :param args:\n :return:\n '
if (windows is None):
windows = ('win' in sys.platform)
if isinstance(args, str):
args = shlex.split(args, posix=(not windows))
elif isinstance(args, list):
pass
elif (args is None):
args = sys.argv[1:]
else:
raise Exception('Unknown args type: {}'.format(type(args)))
for (position, argument) in enumerate(args):
if (argument.lower() in ('--recursive=true', '--recursive=false')):
return args
elif (argument.lower() == '--recursive'):
if ((len(args) > (position + 1)) and (args[(position + 1)].lower() in ['true', 'false'])):
return args
else:
args[position] = '--recursive=True'
return args
return args | Prepare args - add support for old interface, e.g:
- --recursive was "flag" and for now it support True or False value
:param args:
:return: | crosspm/cpm.py | prepare_args | devopshq/crosspm2 | 3 | python | @staticmethod
def prepare_args(args, windows=None):
'\n Prepare args - add support for old interface, e.g:\n - --recursive was "flag" and for now it support True or False value\n :param args:\n :return:\n '
if (windows is None):
windows = ('win' in sys.platform)
if isinstance(args, str):
args = shlex.split(args, posix=(not windows))
elif isinstance(args, list):
pass
elif (args is None):
args = sys.argv[1:]
else:
raise Exception('Unknown args type: {}'.format(type(args)))
for (position, argument) in enumerate(args):
if (argument.lower() in ('--recursive=true', '--recursive=false')):
return args
elif (argument.lower() == '--recursive'):
if ((len(args) > (position + 1)) and (args[(position + 1)].lower() in ['true', 'false'])):
return args
else:
args[position] = '--recursive=True'
return args
return args | @staticmethod
def prepare_args(args, windows=None):
'\n Prepare args - add support for old interface, e.g:\n - --recursive was "flag" and for now it support True or False value\n :param args:\n :return:\n '
if (windows is None):
windows = ('win' in sys.platform)
if isinstance(args, str):
args = shlex.split(args, posix=(not windows))
elif isinstance(args, list):
pass
elif (args is None):
args = sys.argv[1:]
else:
raise Exception('Unknown args type: {}'.format(type(args)))
for (position, argument) in enumerate(args):
if (argument.lower() in ('--recursive=true', '--recursive=false')):
return args
elif (argument.lower() == '--recursive'):
if ((len(args) > (position + 1)) and (args[(position + 1)].lower() in ['true', 'false'])):
return args
else:
args[position] = '--recursive=True'
return args
return args<|docstring|>Prepare args - add support for old interface, e.g:
- --recursive was "flag" and for now it support True or False value
:param args:
:return:<|endoftext|> |
c8a3be1d99070ee5d140c5ae69a23add2dadbca1d432a8cc00d13c3e43e41d03 | def test_login_required(self):
'Test that login is required for retrieving tags'
res = self.client.get(TAGS_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | Test that login is required for retrieving tags | app/recipe/tests/test_tags_api.py | test_login_required | aamodpant15/recipe-app-api | 0 | python | def test_login_required(self):
res = self.client.get(TAGS_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | def test_login_required(self):
res = self.client.get(TAGS_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)<|docstring|>Test that login is required for retrieving tags<|endoftext|> |
7dec0d303d6c808bd6abbb3c61989a2aa79cf2e9eedf4df938467843e2f56b0c | def test_retrieve_tags(self):
'Test retrieving tags'
Tag.objects.create(user=self.user, name='Vegan')
Tag.objects.create(user=self.user, name='Dessert')
res = self.client.get(TAGS_URL)
tags = Tag.objects.all().order_by('-name')
serializer = TagSerializer(tags, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data) | Test retrieving tags | app/recipe/tests/test_tags_api.py | test_retrieve_tags | aamodpant15/recipe-app-api | 0 | python | def test_retrieve_tags(self):
Tag.objects.create(user=self.user, name='Vegan')
Tag.objects.create(user=self.user, name='Dessert')
res = self.client.get(TAGS_URL)
tags = Tag.objects.all().order_by('-name')
serializer = TagSerializer(tags, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data) | def test_retrieve_tags(self):
Tag.objects.create(user=self.user, name='Vegan')
Tag.objects.create(user=self.user, name='Dessert')
res = self.client.get(TAGS_URL)
tags = Tag.objects.all().order_by('-name')
serializer = TagSerializer(tags, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)<|docstring|>Test retrieving tags<|endoftext|> |
0ee8fc2ca391ce0e5741effbd406452206ec09794f6d91a623f82ba4bd354192 | def test_tags_limited_to_user(self):
'Test tjat tags returned are for the authenticated user'
user2 = get_user_model().objects.create_user('example@example.com', 'testpass')
Tag.objects.create(user=user2, name='Fruity')
tag = Tag.objects.create(user=self.user, name='Comfort User')
res = self.client.get(TAGS_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data[0]['name'], tag.name) | Test tjat tags returned are for the authenticated user | app/recipe/tests/test_tags_api.py | test_tags_limited_to_user | aamodpant15/recipe-app-api | 0 | python | def test_tags_limited_to_user(self):
user2 = get_user_model().objects.create_user('example@example.com', 'testpass')
Tag.objects.create(user=user2, name='Fruity')
tag = Tag.objects.create(user=self.user, name='Comfort User')
res = self.client.get(TAGS_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data[0]['name'], tag.name) | def test_tags_limited_to_user(self):
user2 = get_user_model().objects.create_user('example@example.com', 'testpass')
Tag.objects.create(user=user2, name='Fruity')
tag = Tag.objects.create(user=self.user, name='Comfort User')
res = self.client.get(TAGS_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data[0]['name'], tag.name)<|docstring|>Test tjat tags returned are for the authenticated user<|endoftext|> |
96edd790580860cc25341b7e4bae15b1806a3b095dfeb53bca484b140a9ee638 | def test_create_tab_sucessful(self):
'Test creating a new tab'
info = {'name': 'Test Tag'}
self.client.post(TAGS_URL, info)
exists = Tag.objects.filter(user=self.user, name=info['name']).exists()
self.assertTrue(exists) | Test creating a new tab | app/recipe/tests/test_tags_api.py | test_create_tab_sucessful | aamodpant15/recipe-app-api | 0 | python | def test_create_tab_sucessful(self):
info = {'name': 'Test Tag'}
self.client.post(TAGS_URL, info)
exists = Tag.objects.filter(user=self.user, name=info['name']).exists()
self.assertTrue(exists) | def test_create_tab_sucessful(self):
info = {'name': 'Test Tag'}
self.client.post(TAGS_URL, info)
exists = Tag.objects.filter(user=self.user, name=info['name']).exists()
self.assertTrue(exists)<|docstring|>Test creating a new tab<|endoftext|> |
497cd54eadb78aa71a0d981c9b765e58cb2f3e1d2db4d6f955cb133af0d99c60 | def test_create_invalid_tag(self):
'Test creating tag with invalid info'
info = {'name': ''}
res = self.client.post(TAGS_URL, info)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | Test creating tag with invalid info | app/recipe/tests/test_tags_api.py | test_create_invalid_tag | aamodpant15/recipe-app-api | 0 | python | def test_create_invalid_tag(self):
info = {'name': }
res = self.client.post(TAGS_URL, info)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) | def test_create_invalid_tag(self):
info = {'name': }
res = self.client.post(TAGS_URL, info)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)<|docstring|>Test creating tag with invalid info<|endoftext|> |
13a44b2505528c096c5b1d92f1a59b9e63f1fd5cb86ca2080b9f9631acc2d277 | def set_value(self, value):
'为变量赋值\n '
assert (isinstance(value, np.matrix) and (value.shape == self.dim))
self.reset_value(True)
self.value = value | 为变量赋值 | vectorflow/core/variable.py | set_value | dongrenguang/VectorFlow | 0 | python | def set_value(self, value):
'\n '
assert (isinstance(value, np.matrix) and (value.shape == self.dim))
self.reset_value(True)
self.value = value | def set_value(self, value):
'\n '
assert (isinstance(value, np.matrix) and (value.shape == self.dim))
self.reset_value(True)
self.value = value<|docstring|>为变量赋值<|endoftext|> |
2c76974a10e860ae84b2b91e5a29db1963723b53b05a13827dc7f5bf3134506b | def register_all_models():
'\n This function handles the registration of all the models inside of \n database.models.\n\n It returns True if succeeded and False otherwise\n '
all_database_models = get_all_models(module)
success = True
for model in all_database_models:
try:
admin.site.register(model)
except admin.sites.AlreadyRegistered:
success = False
return success | This function handles the registration of all the models inside of
database.models.
It returns True if succeeded and False otherwise | src/carbon_calculator/admin.py | register_all_models | jpeirce21/api | 2 | python | def register_all_models():
'\n This function handles the registration of all the models inside of \n database.models.\n\n It returns True if succeeded and False otherwise\n '
all_database_models = get_all_models(module)
success = True
for model in all_database_models:
try:
admin.site.register(model)
except admin.sites.AlreadyRegistered:
success = False
return success | def register_all_models():
'\n This function handles the registration of all the models inside of \n database.models.\n\n It returns True if succeeded and False otherwise\n '
all_database_models = get_all_models(module)
success = True
for model in all_database_models:
try:
admin.site.register(model)
except admin.sites.AlreadyRegistered:
success = False
return success<|docstring|>This function handles the registration of all the models inside of
database.models.
It returns True if succeeded and False otherwise<|endoftext|> |
e58a7ee20ad670c4029eb633db85c8d84a34183755c70a9bfef18461f8308a7b | def getString(prompt, default='', title='Input', echo='Normal'):
"\n Show a popup-window to ask the user some textual input.\n\n Makes use of QtWidgets.QInputDialog.getText; see\n https://srinikom.github.io/pyside-docs/PySide/QtGui/QInputDialog.html#PySide.QtGui.PySide.QtGui.QInputDialog.getText\n\n :param str prompt: The explanation that is visible just above the text input field.\n :param str default: The text that is already present in the editable input field.\n :param str title: The name of the pop-window (shown in its title bar).\n :param str echo: 'Normal' for normal text entry; 'Password' for password entry. See\n http://doc.qt.io/qt-4.8/qlineedit.html#EchoMode-enum\n "
echo_mode = getattr(QtWidgets.QLineEdit.EchoMode, echo)
return QtWidgets.QInputDialog.getText(None, title, prompt, echo=echo_mode, text=default)[0] | Show a popup-window to ask the user some textual input.
Makes use of QtWidgets.QInputDialog.getText; see
https://srinikom.github.io/pyside-docs/PySide/QtGui/QInputDialog.html#PySide.QtGui.PySide.QtGui.QInputDialog.getText
:param str prompt: The explanation that is visible just above the text input field.
:param str default: The text that is already present in the editable input field.
:param str title: The name of the pop-window (shown in its title bar).
:param str echo: 'Normal' for normal text entry; 'Password' for password entry. See
http://doc.qt.io/qt-4.8/qlineedit.html#EchoMode-enum | gdesk/dialogs/base.py | getString | thocoo/gamma-desk | 0 | python | def getString(prompt, default=, title='Input', echo='Normal'):
"\n Show a popup-window to ask the user some textual input.\n\n Makes use of QtWidgets.QInputDialog.getText; see\n https://srinikom.github.io/pyside-docs/PySide/QtGui/QInputDialog.html#PySide.QtGui.PySide.QtGui.QInputDialog.getText\n\n :param str prompt: The explanation that is visible just above the text input field.\n :param str default: The text that is already present in the editable input field.\n :param str title: The name of the pop-window (shown in its title bar).\n :param str echo: 'Normal' for normal text entry; 'Password' for password entry. See\n http://doc.qt.io/qt-4.8/qlineedit.html#EchoMode-enum\n "
echo_mode = getattr(QtWidgets.QLineEdit.EchoMode, echo)
return QtWidgets.QInputDialog.getText(None, title, prompt, echo=echo_mode, text=default)[0] | def getString(prompt, default=, title='Input', echo='Normal'):
"\n Show a popup-window to ask the user some textual input.\n\n Makes use of QtWidgets.QInputDialog.getText; see\n https://srinikom.github.io/pyside-docs/PySide/QtGui/QInputDialog.html#PySide.QtGui.PySide.QtGui.QInputDialog.getText\n\n :param str prompt: The explanation that is visible just above the text input field.\n :param str default: The text that is already present in the editable input field.\n :param str title: The name of the pop-window (shown in its title bar).\n :param str echo: 'Normal' for normal text entry; 'Password' for password entry. See\n http://doc.qt.io/qt-4.8/qlineedit.html#EchoMode-enum\n "
echo_mode = getattr(QtWidgets.QLineEdit.EchoMode, echo)
return QtWidgets.QInputDialog.getText(None, title, prompt, echo=echo_mode, text=default)[0]<|docstring|>Show a popup-window to ask the user some textual input.
Makes use of QtWidgets.QInputDialog.getText; see
https://srinikom.github.io/pyside-docs/PySide/QtGui/QInputDialog.html#PySide.QtGui.PySide.QtGui.QInputDialog.getText
:param str prompt: The explanation that is visible just above the text input field.
:param str default: The text that is already present in the editable input field.
:param str title: The name of the pop-window (shown in its title bar).
:param str echo: 'Normal' for normal text entry; 'Password' for password entry. See
http://doc.qt.io/qt-4.8/qlineedit.html#EchoMode-enum<|endoftext|> |
18e3c73505e4b200abcf7de7ceb578edb9f7faedf595cc815118581c19b0dab6 | def _resolve(self, **kwargs):
'Can be overridden to implement custom resolver'
return self | Can be overridden to implement custom resolver | tools/nntool/expressions/symbolic/symbol.py | _resolve | mfkiwl/gap_sdk | 0 | python | def _resolve(self, **kwargs):
return self | def _resolve(self, **kwargs):
return self<|docstring|>Can be overridden to implement custom resolver<|endoftext|> |
22675a5a830d9e43c24443e2f410da48ae0616c9381d06793cf9d4e546067110 | def _calculate(self, calculate_ranges=False, **kwargs):
'Can be overridden to implement custom calculator'
raise NotImplementedError() | Can be overridden to implement custom calculator | tools/nntool/expressions/symbolic/symbol.py | _calculate | mfkiwl/gap_sdk | 0 | python | def _calculate(self, calculate_ranges=False, **kwargs):
raise NotImplementedError() | def _calculate(self, calculate_ranges=False, **kwargs):
raise NotImplementedError()<|docstring|>Can be overridden to implement custom calculator<|endoftext|> |
b8a0e0b812724602bd87ab9a09b1cad7af1aa7b8c5c57966ef5e1a62217339cb | def resolve(self, **kwargs):
'Given a set of substitions for variable in kwargs resolve all variables'
return self._resolve(**kwargs) | Given a set of substitions for variable in kwargs resolve all variables | tools/nntool/expressions/symbolic/symbol.py | resolve | mfkiwl/gap_sdk | 0 | python | def resolve(self, **kwargs):
return self._resolve(**kwargs) | def resolve(self, **kwargs):
return self._resolve(**kwargs)<|docstring|>Given a set of substitions for variable in kwargs resolve all variables<|endoftext|> |
c458e6d15a75304a368055db40a3e021792ae0eb0134ae8772cb0cb15301d3b4 | def calculate(self, calculate_ranges=False, **kwargs):
'Given a set of substitions for variable in kwargs calculate a result'
return self._calculate(calculate_ranges=calculate_ranges, **kwargs) | Given a set of substitions for variable in kwargs calculate a result | tools/nntool/expressions/symbolic/symbol.py | calculate | mfkiwl/gap_sdk | 0 | python | def calculate(self, calculate_ranges=False, **kwargs):
return self._calculate(calculate_ranges=calculate_ranges, **kwargs) | def calculate(self, calculate_ranges=False, **kwargs):
return self._calculate(calculate_ranges=calculate_ranges, **kwargs)<|docstring|>Given a set of substitions for variable in kwargs calculate a result<|endoftext|> |
a8de8acc68954a15d2e99d37957d7b1e3c1e135f3838f608fc091bd8182629cc | def collect_globals(self) -> dict:
'Returns a dict of globals necessary to execute a lambda of this symbol. Globals\n can be attached to a subclass of symbol using the @environment decorator.'
return self._collect_globals() | Returns a dict of globals necessary to execute a lambda of this symbol. Globals
can be attached to a subclass of symbol using the @environment decorator. | tools/nntool/expressions/symbolic/symbol.py | collect_globals | mfkiwl/gap_sdk | 0 | python | def collect_globals(self) -> dict:
'Returns a dict of globals necessary to execute a lambda of this symbol. Globals\n can be attached to a subclass of symbol using the @environment decorator.'
return self._collect_globals() | def collect_globals(self) -> dict:
'Returns a dict of globals necessary to execute a lambda of this symbol. Globals\n can be attached to a subclass of symbol using the @environment decorator.'
return self._collect_globals()<|docstring|>Returns a dict of globals necessary to execute a lambda of this symbol. Globals
can be attached to a subclass of symbol using the @environment decorator.<|endoftext|> |
c96e30554fd287511a516563117a62322952f66859c52e3fabd51e4921990542 | def _resolve(self, **kwargs):
'Given a set of substitions for variable in kwargs resolve all variables'
if (self.name in kwargs):
return Constant(self._impl(**kwargs), shape=self.shape)
return self | Given a set of substitions for variable in kwargs resolve all variables | tools/nntool/expressions/symbolic/symbol.py | _resolve | mfkiwl/gap_sdk | 0 | python | def _resolve(self, **kwargs):
if (self.name in kwargs):
return Constant(self._impl(**kwargs), shape=self.shape)
return self | def _resolve(self, **kwargs):
if (self.name in kwargs):
return Constant(self._impl(**kwargs), shape=self.shape)
return self<|docstring|>Given a set of substitions for variable in kwargs resolve all variables<|endoftext|> |
946cbe86938cb96987aa551c79982d528c31d2dd86cda8200aab5fcd57cde3dc | def register_flag(self, flag: enum.Flag) -> typing.Callable:
'Decorator to easily associate methods to a flag'
def wrapper(func: typing.Callable) -> typing.Callable:
logger.debug('Flag %s registered to %s', flag, func)
self[flag] = func
return func
return wrapper | Decorator to easily associate methods to a flag | netdisc/snmp/mibhelp.py | register_flag | zohassadar/netdisc | 0 | python | def register_flag(self, flag: enum.Flag) -> typing.Callable:
def wrapper(func: typing.Callable) -> typing.Callable:
logger.debug('Flag %s registered to %s', flag, func)
self[flag] = func
return func
return wrapper | def register_flag(self, flag: enum.Flag) -> typing.Callable:
def wrapper(func: typing.Callable) -> typing.Callable:
logger.debug('Flag %s registered to %s', flag, func)
self[flag] = func
return func
return wrapper<|docstring|>Decorator to easily associate methods to a flag<|endoftext|> |
28ce76b5d82461efab43b0f40b3511acaadf5a2d46ac645d6a38ced625f10cdf | @click.group()
def main():
'la maREPOsa allows you to go through all the initiation process of new git/GitHub projects with just a single terminal command.'
pass | la maREPOsa allows you to go through all the initiation process of new git/GitHub projects with just a single terminal command. | mareposa/cli.py | main | RichStone/mareposa | 4 | python | @click.group()
def main():
pass | @click.group()
def main():
pass<|docstring|>la maREPOsa allows you to go through all the initiation process of new git/GitHub projects with just a single terminal command.<|endoftext|> |
8f9f073ce03f2a773ebc3db93cf06ba8d2ffc0762af295210de7763123343c86 | def bash_execute_curl(url, options='', append_command=''):
"\n # Popen together with curl cannot deal with chaining `>>` to curl commands, that's why shell=True is used for subprocess.Popen\n # check if shell=True is not to be used everywhere\n :param technology: technologies to ignore separated by come, e.g. eclipse,java etc. For full list of possible technologies refer to --ignore-list. '\n "
process = subprocess.Popen(((((('curl ' + options) + ' ') + url) + ' ') + append_command), shell=True)
process.wait()
process.terminate() | # Popen together with curl cannot deal with chaining `>>` to curl commands, that's why shell=True is used for subprocess.Popen
# check if shell=True is not to be used everywhere
:param technology: technologies to ignore separated by come, e.g. eclipse,java etc. For full list of possible technologies refer to --ignore-list. ' | mareposa/cli.py | bash_execute_curl | RichStone/mareposa | 4 | python | def bash_execute_curl(url, options=, append_command=):
"\n # Popen together with curl cannot deal with chaining `>>` to curl commands, that's why shell=True is used for subprocess.Popen\n # check if shell=True is not to be used everywhere\n :param technology: technologies to ignore separated by come, e.g. eclipse,java etc. For full list of possible technologies refer to --ignore-list. '\n "
process = subprocess.Popen(((((('curl ' + options) + ' ') + url) + ' ') + append_command), shell=True)
process.wait()
process.terminate() | def bash_execute_curl(url, options=, append_command=):
"\n # Popen together with curl cannot deal with chaining `>>` to curl commands, that's why shell=True is used for subprocess.Popen\n # check if shell=True is not to be used everywhere\n :param technology: technologies to ignore separated by come, e.g. eclipse,java etc. For full list of possible technologies refer to --ignore-list. '\n "
process = subprocess.Popen(((((('curl ' + options) + ' ') + url) + ' ') + append_command), shell=True)
process.wait()
process.terminate()<|docstring|># Popen together with curl cannot deal with chaining `>>` to curl commands, that's why shell=True is used for subprocess.Popen
# check if shell=True is not to be used everywhere
:param technology: technologies to ignore separated by come, e.g. eclipse,java etc. For full list of possible technologies refer to --ignore-list. '<|endoftext|> |
fd989893ca8966d6ddb087dc152d22352277ffba5becf2a4cebf23c41a4970b2 | def test(model, criterion, loaders, device, infer_fn):
'Evaluate the performance of a model\n\n Args:\n model: model to evaluate\n criterion: loss function\n loader: dictionary of data loaders for testing\n device: id of the device for torch to allocate objects\n infer_fn: BaseInference object: calculate additional metrics, saving predictions \n Return:\n test_loss: average loss over the test dataset\n test_score: score over the test dataset\n '
(eval_loss, eval_scr) = infer_fn(loaders=loaders, model=model, logger=logger, device=device, criterion=criterion)
return (eval_loss, eval_scr) | Evaluate the performance of a model
Args:
model: model to evaluate
criterion: loss function
loader: dictionary of data loaders for testing
device: id of the device for torch to allocate objects
infer_fn: BaseInference object: calculate additional metrics, saving predictions
Return:
test_loss: average loss over the test dataset
test_score: score over the test dataset | tester.py | test | hthieu166/selab-aic20-track-2 | 0 | python | def test(model, criterion, loaders, device, infer_fn):
'Evaluate the performance of a model\n\n Args:\n model: model to evaluate\n criterion: loss function\n loader: dictionary of data loaders for testing\n device: id of the device for torch to allocate objects\n infer_fn: BaseInference object: calculate additional metrics, saving predictions \n Return:\n test_loss: average loss over the test dataset\n test_score: score over the test dataset\n '
(eval_loss, eval_scr) = infer_fn(loaders=loaders, model=model, logger=logger, device=device, criterion=criterion)
return (eval_loss, eval_scr) | def test(model, criterion, loaders, device, infer_fn):
'Evaluate the performance of a model\n\n Args:\n model: model to evaluate\n criterion: loss function\n loader: dictionary of data loaders for testing\n device: id of the device for torch to allocate objects\n infer_fn: BaseInference object: calculate additional metrics, saving predictions \n Return:\n test_loss: average loss over the test dataset\n test_score: score over the test dataset\n '
(eval_loss, eval_scr) = infer_fn(loaders=loaders, model=model, logger=logger, device=device, criterion=criterion)
return (eval_loss, eval_scr)<|docstring|>Evaluate the performance of a model
Args:
model: model to evaluate
criterion: loss function
loader: dictionary of data loaders for testing
device: id of the device for torch to allocate objects
infer_fn: BaseInference object: calculate additional metrics, saving predictions
Return:
test_loss: average loss over the test dataset
test_score: score over the test dataset<|endoftext|> |
9d7eace8aa915ff837045e3a87c2c9043e93ef700f4ea37372e84d4b57b7c015 | def get_query_details(self, query_fqn, **kwargs):
'Retrieve detailed information for a query specification # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_query_details(query_fqn, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str query_fqn: Fully qualified name of the query (package name and query name separated with a dot) (required)\n :return: QuerySpecificationResponse\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_query_details_with_http_info(query_fqn, **kwargs)
else:
data = self.get_query_details_with_http_info(query_fqn, **kwargs)
return data | Retrieve detailed information for a query specification # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_query_details(query_fqn, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str query_fqn: Fully qualified name of the query (package name and query name separated with a dot) (required)
:return: QuerySpecificationResponse
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | get_query_details | thomas-bc/mms-autocref | 0 | python | def get_query_details(self, query_fqn, **kwargs):
'Retrieve detailed information for a query specification # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_query_details(query_fqn, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str query_fqn: Fully qualified name of the query (package name and query name separated with a dot) (required)\n :return: QuerySpecificationResponse\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_query_details_with_http_info(query_fqn, **kwargs)
else:
data = self.get_query_details_with_http_info(query_fqn, **kwargs)
return data | def get_query_details(self, query_fqn, **kwargs):
'Retrieve detailed information for a query specification # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_query_details(query_fqn, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str query_fqn: Fully qualified name of the query (package name and query name separated with a dot) (required)\n :return: QuerySpecificationResponse\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_query_details_with_http_info(query_fqn, **kwargs)
else:
data = self.get_query_details_with_http_info(query_fqn, **kwargs)
return data<|docstring|>Retrieve detailed information for a query specification # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_query_details(query_fqn, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str query_fqn: Fully qualified name of the query (package name and query name separated with a dot) (required)
:return: QuerySpecificationResponse
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
818b3149a133fe50d188a8707a3a4b6ddd3d761f7ac1acfc5f653c721dddfbcf | def get_query_details_with_http_info(self, query_fqn, **kwargs):
'Retrieve detailed information for a query specification # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_query_details_with_http_info(query_fqn, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str query_fqn: Fully qualified name of the query (package name and query name separated with a dot) (required)\n :return: QuerySpecificationResponse\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = ['query_fqn']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method get_query_details" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('query_fqn' not in local_var_params) or (local_var_params['query_fqn'] is None)):
raise ValueError('Missing the required parameter `query_fqn` when calling `get_query_details`')
collection_formats = {}
path_params = {}
query_params = []
if ('query_fqn' in local_var_params):
query_params.append(('queryFQN', local_var_params['query_fqn']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.details', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QuerySpecificationResponse', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | Retrieve detailed information for a query specification # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_query_details_with_http_info(query_fqn, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str query_fqn: Fully qualified name of the query (package name and query name separated with a dot) (required)
:return: QuerySpecificationResponse
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | get_query_details_with_http_info | thomas-bc/mms-autocref | 0 | python | def get_query_details_with_http_info(self, query_fqn, **kwargs):
'Retrieve detailed information for a query specification # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_query_details_with_http_info(query_fqn, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str query_fqn: Fully qualified name of the query (package name and query name separated with a dot) (required)\n :return: QuerySpecificationResponse\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = ['query_fqn']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method get_query_details" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('query_fqn' not in local_var_params) or (local_var_params['query_fqn'] is None)):
raise ValueError('Missing the required parameter `query_fqn` when calling `get_query_details`')
collection_formats = {}
path_params = {}
query_params = []
if ('query_fqn' in local_var_params):
query_params.append(('queryFQN', local_var_params['query_fqn']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.details', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QuerySpecificationResponse', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | def get_query_details_with_http_info(self, query_fqn, **kwargs):
'Retrieve detailed information for a query specification # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.get_query_details_with_http_info(query_fqn, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str query_fqn: Fully qualified name of the query (package name and query name separated with a dot) (required)\n :return: QuerySpecificationResponse\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = ['query_fqn']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method get_query_details" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('query_fqn' not in local_var_params) or (local_var_params['query_fqn'] is None)):
raise ValueError('Missing the required parameter `query_fqn` when calling `get_query_details`')
collection_formats = {}
path_params = {}
query_params = []
if ('query_fqn' in local_var_params):
query_params.append(('queryFQN', local_var_params['query_fqn']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.details', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QuerySpecificationResponse', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)<|docstring|>Retrieve detailed information for a query specification # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_query_details_with_http_info(query_fqn, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str query_fqn: Fully qualified name of the query (package name and query name separated with a dot) (required)
:return: QuerySpecificationResponse
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
dcce112c8e2b1f088c2c722af338a5717f8fe8e9768c69b6d417daf9b9d21888 | def list_queries(self, **kwargs):
'List registered query specifications # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.list_queries(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_queries_with_http_info(**kwargs)
else:
data = self.list_queries_with_http_info(**kwargs)
return data | List registered query specifications # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_queries(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: QueryListResponse
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | list_queries | thomas-bc/mms-autocref | 0 | python | def list_queries(self, **kwargs):
'List registered query specifications # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.list_queries(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_queries_with_http_info(**kwargs)
else:
data = self.list_queries_with_http_info(**kwargs)
return data | def list_queries(self, **kwargs):
'List registered query specifications # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.list_queries(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_queries_with_http_info(**kwargs)
else:
data = self.list_queries_with_http_info(**kwargs)
return data<|docstring|>List registered query specifications # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_queries(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: QueryListResponse
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
79ae044ae37fe40c143301f07b771ad73f910fef74b23b54b875cec2d6613831 | def list_queries_with_http_info(self, **kwargs):
'List registered query specifications # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.list_queries_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = []
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method list_queries" % key))
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.list', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryListResponse', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | List registered query specifications # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_queries_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: QueryListResponse
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | list_queries_with_http_info | thomas-bc/mms-autocref | 0 | python | def list_queries_with_http_info(self, **kwargs):
'List registered query specifications # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.list_queries_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = []
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method list_queries" % key))
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.list', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryListResponse', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | def list_queries_with_http_info(self, **kwargs):
'List registered query specifications # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.list_queries_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = []
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method list_queries" % key))
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.list', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryListResponse', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)<|docstring|>List registered query specifications # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_queries_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: QueryListResponse
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
842e1f7e308bd46ba1f1daf70895cab8d18c429a10945cd2a9e60636ddbc0cc0 | def register_queries(self, query_definition_request, **kwargs):
'Register query definitions # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries(query_definition_request, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param QueryDefinitionRequest query_definition_request: (required)\n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.register_queries_with_http_info(query_definition_request, **kwargs)
else:
data = self.register_queries_with_http_info(query_definition_request, **kwargs)
return data | Register query definitions # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries(query_definition_request, async_req=True)
>>> result = thread.get()
:param async_req bool
:param QueryDefinitionRequest query_definition_request: (required)
:return: QueryFQNList
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | register_queries | thomas-bc/mms-autocref | 0 | python | def register_queries(self, query_definition_request, **kwargs):
'Register query definitions # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries(query_definition_request, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param QueryDefinitionRequest query_definition_request: (required)\n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.register_queries_with_http_info(query_definition_request, **kwargs)
else:
data = self.register_queries_with_http_info(query_definition_request, **kwargs)
return data | def register_queries(self, query_definition_request, **kwargs):
'Register query definitions # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries(query_definition_request, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param QueryDefinitionRequest query_definition_request: (required)\n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.register_queries_with_http_info(query_definition_request, **kwargs)
else:
data = self.register_queries_with_http_info(query_definition_request, **kwargs)
return data<|docstring|>Register query definitions # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries(query_definition_request, async_req=True)
>>> result = thread.get()
:param async_req bool
:param QueryDefinitionRequest query_definition_request: (required)
:return: QueryFQNList
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
d0bcc9e9a021dc165a85d3cd457753aaf820957b757b3af5db863c7a964ebc12 | def register_queries_with_http_info(self, query_definition_request, **kwargs):
'Register query definitions # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_with_http_info(query_definition_request, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param QueryDefinitionRequest query_definition_request: (required)\n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = ['query_definition_request']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method register_queries" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('query_definition_request' not in local_var_params) or (local_var_params['query_definition_request'] is None)):
raise ValueError('Missing the required parameter `query_definition_request` when calling `register_queries`')
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if ('query_definition_request' in local_var_params):
body_params = local_var_params['query_definition_request']
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.register', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryFQNList', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | Register query definitions # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries_with_http_info(query_definition_request, async_req=True)
>>> result = thread.get()
:param async_req bool
:param QueryDefinitionRequest query_definition_request: (required)
:return: QueryFQNList
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | register_queries_with_http_info | thomas-bc/mms-autocref | 0 | python | def register_queries_with_http_info(self, query_definition_request, **kwargs):
'Register query definitions # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_with_http_info(query_definition_request, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param QueryDefinitionRequest query_definition_request: (required)\n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = ['query_definition_request']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method register_queries" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('query_definition_request' not in local_var_params) or (local_var_params['query_definition_request'] is None)):
raise ValueError('Missing the required parameter `query_definition_request` when calling `register_queries`')
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if ('query_definition_request' in local_var_params):
body_params = local_var_params['query_definition_request']
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.register', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryFQNList', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | def register_queries_with_http_info(self, query_definition_request, **kwargs):
'Register query definitions # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_with_http_info(query_definition_request, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param QueryDefinitionRequest query_definition_request: (required)\n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = ['query_definition_request']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method register_queries" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('query_definition_request' not in local_var_params) or (local_var_params['query_definition_request'] is None)):
raise ValueError('Missing the required parameter `query_definition_request` when calling `register_queries`')
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if ('query_definition_request' in local_var_params):
body_params = local_var_params['query_definition_request']
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.register', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryFQNList', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)<|docstring|>Register query definitions # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries_with_http_info(query_definition_request, async_req=True)
>>> result = thread.get()
:param async_req bool
:param QueryDefinitionRequest query_definition_request: (required)
:return: QueryFQNList
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
bf33bca3bd5714c2fc8b46a0387db0130d4e57d43d313613a4b3fa1550082ce9 | def register_queries_from_model_compartment(self, model_compartment, **kwargs):
'Registers query definitions contained in model compartments. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_from_model_compartment(model_compartment, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param ModelCompartment model_compartment: Model compartment descriptor. (required)\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.register_queries_from_model_compartment_with_http_info(model_compartment, **kwargs)
else:
data = self.register_queries_from_model_compartment_with_http_info(model_compartment, **kwargs)
return data | Registers query definitions contained in model compartments. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries_from_model_compartment(model_compartment, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ModelCompartment model_compartment: Model compartment descriptor. (required)
:return: QueryListResponse
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | register_queries_from_model_compartment | thomas-bc/mms-autocref | 0 | python | def register_queries_from_model_compartment(self, model_compartment, **kwargs):
'Registers query definitions contained in model compartments. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_from_model_compartment(model_compartment, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param ModelCompartment model_compartment: Model compartment descriptor. (required)\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.register_queries_from_model_compartment_with_http_info(model_compartment, **kwargs)
else:
data = self.register_queries_from_model_compartment_with_http_info(model_compartment, **kwargs)
return data | def register_queries_from_model_compartment(self, model_compartment, **kwargs):
'Registers query definitions contained in model compartments. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_from_model_compartment(model_compartment, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param ModelCompartment model_compartment: Model compartment descriptor. (required)\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.register_queries_from_model_compartment_with_http_info(model_compartment, **kwargs)
else:
data = self.register_queries_from_model_compartment_with_http_info(model_compartment, **kwargs)
return data<|docstring|>Registers query definitions contained in model compartments. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries_from_model_compartment(model_compartment, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ModelCompartment model_compartment: Model compartment descriptor. (required)
:return: QueryListResponse
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
6a7cd2df64a0464c71d902850d478ede98d0cb792a54c1d3ba066e5ced04c743 | def register_queries_from_model_compartment_with_http_info(self, model_compartment, **kwargs):
'Registers query definitions contained in model compartments. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_from_model_compartment_with_http_info(model_compartment, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param ModelCompartment model_compartment: Model compartment descriptor. (required)\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = ['model_compartment']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method register_queries_from_model_compartment" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('model_compartment' not in local_var_params) or (local_var_params['model_compartment'] is None)):
raise ValueError('Missing the required parameter `model_compartment` when calling `register_queries_from_model_compartment`')
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if ('model_compartment' in local_var_params):
body_params = local_var_params['model_compartment']
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.registerFromModelCompartment', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryListResponse', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | Registers query definitions contained in model compartments. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries_from_model_compartment_with_http_info(model_compartment, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ModelCompartment model_compartment: Model compartment descriptor. (required)
:return: QueryListResponse
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | register_queries_from_model_compartment_with_http_info | thomas-bc/mms-autocref | 0 | python | def register_queries_from_model_compartment_with_http_info(self, model_compartment, **kwargs):
'Registers query definitions contained in model compartments. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_from_model_compartment_with_http_info(model_compartment, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param ModelCompartment model_compartment: Model compartment descriptor. (required)\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = ['model_compartment']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method register_queries_from_model_compartment" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('model_compartment' not in local_var_params) or (local_var_params['model_compartment'] is None)):
raise ValueError('Missing the required parameter `model_compartment` when calling `register_queries_from_model_compartment`')
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if ('model_compartment' in local_var_params):
body_params = local_var_params['model_compartment']
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.registerFromModelCompartment', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryListResponse', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | def register_queries_from_model_compartment_with_http_info(self, model_compartment, **kwargs):
'Registers query definitions contained in model compartments. # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_from_model_compartment_with_http_info(model_compartment, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param ModelCompartment model_compartment: Model compartment descriptor. (required)\n :return: QueryListResponse\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = ['model_compartment']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method register_queries_from_model_compartment" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('model_compartment' not in local_var_params) or (local_var_params['model_compartment'] is None)):
raise ValueError('Missing the required parameter `model_compartment` when calling `register_queries_from_model_compartment`')
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if ('model_compartment' in local_var_params):
body_params = local_var_params['model_compartment']
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.registerFromModelCompartment', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryListResponse', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)<|docstring|>Registers query definitions contained in model compartments. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries_from_model_compartment_with_http_info(model_compartment, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ModelCompartment model_compartment: Model compartment descriptor. (required)
:return: QueryListResponse
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
e5809fc512367f9f5f3cdfe2dcc46a7e9a95337cace64a3fc80b179e46fadf9f | def register_queries_plain_text(self, body, **kwargs):
"Register query definitions in plain text format # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_plain_text(body, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str body: Query definition in plain text (required)\n :param str query_package: Optional query package for organizing queries and controlling visibility. The value must be a legal Java package name: * start with lowercase letter * contain only lowercase letters, digits and dots ('.') * cannot end with dot ('.') \n :param str query_language: Optional parameter for defining the query language. Default value is 'viatra'. Choose one of the followings: viatra, lucene \n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n "
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.register_queries_plain_text_with_http_info(body, **kwargs)
else:
data = self.register_queries_plain_text_with_http_info(body, **kwargs)
return data | Register query definitions in plain text format # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries_plain_text(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str body: Query definition in plain text (required)
:param str query_package: Optional query package for organizing queries and controlling visibility. The value must be a legal Java package name: * start with lowercase letter * contain only lowercase letters, digits and dots ('.') * cannot end with dot ('.')
:param str query_language: Optional parameter for defining the query language. Default value is 'viatra'. Choose one of the followings: viatra, lucene
:return: QueryFQNList
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | register_queries_plain_text | thomas-bc/mms-autocref | 0 | python | def register_queries_plain_text(self, body, **kwargs):
"Register query definitions in plain text format # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_plain_text(body, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str body: Query definition in plain text (required)\n :param str query_package: Optional query package for organizing queries and controlling visibility. The value must be a legal Java package name: * start with lowercase letter * contain only lowercase letters, digits and dots ('.') * cannot end with dot ('.') \n :param str query_language: Optional parameter for defining the query language. Default value is 'viatra'. Choose one of the followings: viatra, lucene \n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n "
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.register_queries_plain_text_with_http_info(body, **kwargs)
else:
data = self.register_queries_plain_text_with_http_info(body, **kwargs)
return data | def register_queries_plain_text(self, body, **kwargs):
"Register query definitions in plain text format # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_plain_text(body, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str body: Query definition in plain text (required)\n :param str query_package: Optional query package for organizing queries and controlling visibility. The value must be a legal Java package name: * start with lowercase letter * contain only lowercase letters, digits and dots ('.') * cannot end with dot ('.') \n :param str query_language: Optional parameter for defining the query language. Default value is 'viatra'. Choose one of the followings: viatra, lucene \n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n "
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.register_queries_plain_text_with_http_info(body, **kwargs)
else:
data = self.register_queries_plain_text_with_http_info(body, **kwargs)
return data<|docstring|>Register query definitions in plain text format # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries_plain_text(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str body: Query definition in plain text (required)
:param str query_package: Optional query package for organizing queries and controlling visibility. The value must be a legal Java package name: * start with lowercase letter * contain only lowercase letters, digits and dots ('.') * cannot end with dot ('.')
:param str query_language: Optional parameter for defining the query language. Default value is 'viatra'. Choose one of the followings: viatra, lucene
:return: QueryFQNList
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
457d938a169ab86783e3f63522aa8ce5bfa305942a9783cd7d4a5c0bcec2baeb | def register_queries_plain_text_with_http_info(self, body, **kwargs):
"Register query definitions in plain text format # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_plain_text_with_http_info(body, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str body: Query definition in plain text (required)\n :param str query_package: Optional query package for organizing queries and controlling visibility. The value must be a legal Java package name: * start with lowercase letter * contain only lowercase letters, digits and dots ('.') * cannot end with dot ('.') \n :param str query_language: Optional parameter for defining the query language. Default value is 'viatra'. Choose one of the followings: viatra, lucene \n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n "
local_var_params = locals()
all_params = ['body', 'query_package', 'query_language']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method register_queries_plain_text" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('body' not in local_var_params) or (local_var_params['body'] is None)):
raise ValueError('Missing the required parameter `body` when calling `register_queries_plain_text`')
collection_formats = {}
path_params = {}
query_params = []
if ('query_package' in local_var_params):
query_params.append(('queryPackage', local_var_params['query_package']))
if ('query_language' in local_var_params):
query_params.append(('queryLanguage', local_var_params['query_language']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if ('body' in local_var_params):
body_params = local_var_params['body']
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(['text/plain'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.registerPlainText', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryFQNList', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | Register query definitions in plain text format # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries_plain_text_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str body: Query definition in plain text (required)
:param str query_package: Optional query package for organizing queries and controlling visibility. The value must be a legal Java package name: * start with lowercase letter * contain only lowercase letters, digits and dots ('.') * cannot end with dot ('.')
:param str query_language: Optional parameter for defining the query language. Default value is 'viatra'. Choose one of the followings: viatra, lucene
:return: QueryFQNList
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | register_queries_plain_text_with_http_info | thomas-bc/mms-autocref | 0 | python | def register_queries_plain_text_with_http_info(self, body, **kwargs):
"Register query definitions in plain text format # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_plain_text_with_http_info(body, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str body: Query definition in plain text (required)\n :param str query_package: Optional query package for organizing queries and controlling visibility. The value must be a legal Java package name: * start with lowercase letter * contain only lowercase letters, digits and dots ('.') * cannot end with dot ('.') \n :param str query_language: Optional parameter for defining the query language. Default value is 'viatra'. Choose one of the followings: viatra, lucene \n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n "
local_var_params = locals()
all_params = ['body', 'query_package', 'query_language']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method register_queries_plain_text" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('body' not in local_var_params) or (local_var_params['body'] is None)):
raise ValueError('Missing the required parameter `body` when calling `register_queries_plain_text`')
collection_formats = {}
path_params = {}
query_params = []
if ('query_package' in local_var_params):
query_params.append(('queryPackage', local_var_params['query_package']))
if ('query_language' in local_var_params):
query_params.append(('queryLanguage', local_var_params['query_language']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if ('body' in local_var_params):
body_params = local_var_params['body']
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(['text/plain'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.registerPlainText', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryFQNList', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | def register_queries_plain_text_with_http_info(self, body, **kwargs):
"Register query definitions in plain text format # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.register_queries_plain_text_with_http_info(body, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str body: Query definition in plain text (required)\n :param str query_package: Optional query package for organizing queries and controlling visibility. The value must be a legal Java package name: * start with lowercase letter * contain only lowercase letters, digits and dots ('.') * cannot end with dot ('.') \n :param str query_language: Optional parameter for defining the query language. Default value is 'viatra'. Choose one of the followings: viatra, lucene \n :return: QueryFQNList\n If the method is called asynchronously,\n returns the request thread.\n "
local_var_params = locals()
all_params = ['body', 'query_package', 'query_language']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method register_queries_plain_text" % key))
local_var_params[key] = val
del local_var_params['kwargs']
if (('body' not in local_var_params) or (local_var_params['body'] is None)):
raise ValueError('Missing the required parameter `body` when calling `register_queries_plain_text`')
collection_formats = {}
path_params = {}
query_params = []
if ('query_package' in local_var_params):
query_params.append(('queryPackage', local_var_params['query_package']))
if ('query_language' in local_var_params):
query_params.append(('queryLanguage', local_var_params['query_language']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if ('body' in local_var_params):
body_params = local_var_params['body']
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
header_params['Content-Type'] = self.api_client.select_header_content_type(['text/plain'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.registerPlainText', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='QueryFQNList', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)<|docstring|>Register query definitions in plain text format # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.register_queries_plain_text_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str body: Query definition in plain text (required)
:param str query_package: Optional query package for organizing queries and controlling visibility. The value must be a legal Java package name: * start with lowercase letter * contain only lowercase letters, digits and dots ('.') * cannot end with dot ('.')
:param str query_language: Optional parameter for defining the query language. Default value is 'viatra'. Choose one of the followings: viatra, lucene
:return: QueryFQNList
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
92db4692bfb09a59d144f9d26d4e5764fec61f6adac3c0d9e6988d5c2c295bcd | def unregister_all_queries(self, **kwargs):
'Unregister all queries # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.unregister_all_queries(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: SimpleMessage\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.unregister_all_queries_with_http_info(**kwargs)
else:
data = self.unregister_all_queries_with_http_info(**kwargs)
return data | Unregister all queries # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.unregister_all_queries(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: SimpleMessage
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | unregister_all_queries | thomas-bc/mms-autocref | 0 | python | def unregister_all_queries(self, **kwargs):
'Unregister all queries # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.unregister_all_queries(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: SimpleMessage\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.unregister_all_queries_with_http_info(**kwargs)
else:
data = self.unregister_all_queries_with_http_info(**kwargs)
return data | def unregister_all_queries(self, **kwargs):
'Unregister all queries # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.unregister_all_queries(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: SimpleMessage\n If the method is called asynchronously,\n returns the request thread.\n '
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.unregister_all_queries_with_http_info(**kwargs)
else:
data = self.unregister_all_queries_with_http_info(**kwargs)
return data<|docstring|>Unregister all queries # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.unregister_all_queries(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: SimpleMessage
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
ad798a2b4fdb96d3f226d16b667294b92d618e305373603c02cb5eba4e90268d | def unregister_all_queries_with_http_info(self, **kwargs):
'Unregister all queries # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.unregister_all_queries_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: SimpleMessage\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = []
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method unregister_all_queries" % key))
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.unregisterAll', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SimpleMessage', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | Unregister all queries # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.unregister_all_queries_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: SimpleMessage
If the method is called asynchronously,
returns the request thread. | iqs_client/api/queries_api.py | unregister_all_queries_with_http_info | thomas-bc/mms-autocref | 0 | python | def unregister_all_queries_with_http_info(self, **kwargs):
'Unregister all queries # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.unregister_all_queries_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: SimpleMessage\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = []
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method unregister_all_queries" % key))
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.unregisterAll', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SimpleMessage', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | def unregister_all_queries_with_http_info(self, **kwargs):
'Unregister all queries # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.unregister_all_queries_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :return: SimpleMessage\n If the method is called asynchronously,\n returns the request thread.\n '
local_var_params = locals()
all_params = []
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for (key, val) in six.iteritems(local_var_params['kwargs']):
if (key not in all_params):
raise TypeError(("Got an unexpected keyword argument '%s' to method unregister_all_queries" % key))
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.select_header_accept(['application/json'])
auth_settings = ['basicAuth']
return self.api_client.call_api('/queries.unregisterAll', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SimpleMessage', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)<|docstring|>Unregister all queries # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.unregister_all_queries_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: SimpleMessage
If the method is called asynchronously,
returns the request thread.<|endoftext|> |
081a0dbc98723ba2a1f8b5015d9f43bd36ae86609a220c1a20ca6a1f092b09eb | def normalize(formatted_exception):
'Normalize exception output for reproducible test cases'
if (sys.platform == 'win32'):
formatted_exception = re.sub('File[^"]+"[^"]+\\.py[^"]*"', (lambda m: m.group().replace('\\', '/')), formatted_exception)
formatted_exception = re.sub('(\\r\\n|\\r|\\n)', '\n', formatted_exception)
formatted_exception = re.sub('\\b0x[0-9a-fA-F]+\\b', '0xDEADBEEF', formatted_exception)
return formatted_exception | Normalize exception output for reproducible test cases | tests/test_exceptions_formatting.py | normalize | needoptimism/loguru | 1 | python | def normalize(formatted_exception):
if (sys.platform == 'win32'):
formatted_exception = re.sub('File[^"]+"[^"]+\\.py[^"]*"', (lambda m: m.group().replace('\\', '/')), formatted_exception)
formatted_exception = re.sub('(\\r\\n|\\r|\\n)', '\n', formatted_exception)
formatted_exception = re.sub('\\b0x[0-9a-fA-F]+\\b', '0xDEADBEEF', formatted_exception)
return formatted_exception | def normalize(formatted_exception):
if (sys.platform == 'win32'):
formatted_exception = re.sub('File[^"]+"[^"]+\\.py[^"]*"', (lambda m: m.group().replace('\\', '/')), formatted_exception)
formatted_exception = re.sub('(\\r\\n|\\r|\\n)', '\n', formatted_exception)
formatted_exception = re.sub('\\b0x[0-9a-fA-F]+\\b', '0xDEADBEEF', formatted_exception)
return formatted_exception<|docstring|>Normalize exception output for reproducible test cases<|endoftext|> |
9792235ac57dbe1b9a414d1774d77a43ecab1df1f54d21da20c4d17a0da42830 | def generate(output, outpath):
'Generate new output file if exception formatting is updated'
with open(outpath, 'w') as file:
file.write(output) | Generate new output file if exception formatting is updated | tests/test_exceptions_formatting.py | generate | needoptimism/loguru | 1 | python | def generate(output, outpath):
with open(outpath, 'w') as file:
file.write(output) | def generate(output, outpath):
with open(outpath, 'w') as file:
file.write(output)<|docstring|>Generate new output file if exception formatting is updated<|endoftext|> |
5fce56ea252f0dd085f088380bda062633b954cfdea29a57b9c3e1024a381318 | def __init__(self, id, input_node, staging_table_definition, production_table_definition, pipeline_name, script_arguments=None, analyze_table=True, enforce_primary_key=True, non_transactional=False, log_to_s3=False, **kwargs):
'Constructor for the LoadReloadAndPrimaryKeyStep class\n\n Args:\n input_node: A S3 data node as input\n staging_table_definition(filepath):\n staging table schema to store the data\n production_table_definition(filepath):\n schema file for the table to be reloaded into\n **kwargs(optional): Keyword arguments directly passed to base class\n '
super(LoadReloadAndPrimaryKeyStep, self).__init__(id=id, **kwargs)
create_and_load_pipeline_object = self.create_and_load_redshift(table_definition=staging_table_definition, input_node=input_node, script_arguments=script_arguments)
reload_pipeline_object = self.reload(source=staging_table_definition, destination=production_table_definition, depends_on=[create_and_load_pipeline_object], analyze_table=analyze_table, non_transactional=non_transactional, enforce_primary_key=enforce_primary_key)
self.primary_key_check(table_definition=production_table_definition, pipeline_name=pipeline_name, depends_on=[reload_pipeline_object], log_to_s3=log_to_s3) | Constructor for the LoadReloadAndPrimaryKeyStep class
Args:
input_node: A S3 data node as input
staging_table_definition(filepath):
staging table schema to store the data
production_table_definition(filepath):
schema file for the table to be reloaded into
**kwargs(optional): Keyword arguments directly passed to base class | dataduct/steps/load_reload_pk.py | __init__ | recurly/dataduct | 3 | python | def __init__(self, id, input_node, staging_table_definition, production_table_definition, pipeline_name, script_arguments=None, analyze_table=True, enforce_primary_key=True, non_transactional=False, log_to_s3=False, **kwargs):
'Constructor for the LoadReloadAndPrimaryKeyStep class\n\n Args:\n input_node: A S3 data node as input\n staging_table_definition(filepath):\n staging table schema to store the data\n production_table_definition(filepath):\n schema file for the table to be reloaded into\n **kwargs(optional): Keyword arguments directly passed to base class\n '
super(LoadReloadAndPrimaryKeyStep, self).__init__(id=id, **kwargs)
create_and_load_pipeline_object = self.create_and_load_redshift(table_definition=staging_table_definition, input_node=input_node, script_arguments=script_arguments)
reload_pipeline_object = self.reload(source=staging_table_definition, destination=production_table_definition, depends_on=[create_and_load_pipeline_object], analyze_table=analyze_table, non_transactional=non_transactional, enforce_primary_key=enforce_primary_key)
self.primary_key_check(table_definition=production_table_definition, pipeline_name=pipeline_name, depends_on=[reload_pipeline_object], log_to_s3=log_to_s3) | def __init__(self, id, input_node, staging_table_definition, production_table_definition, pipeline_name, script_arguments=None, analyze_table=True, enforce_primary_key=True, non_transactional=False, log_to_s3=False, **kwargs):
'Constructor for the LoadReloadAndPrimaryKeyStep class\n\n Args:\n input_node: A S3 data node as input\n staging_table_definition(filepath):\n staging table schema to store the data\n production_table_definition(filepath):\n schema file for the table to be reloaded into\n **kwargs(optional): Keyword arguments directly passed to base class\n '
super(LoadReloadAndPrimaryKeyStep, self).__init__(id=id, **kwargs)
create_and_load_pipeline_object = self.create_and_load_redshift(table_definition=staging_table_definition, input_node=input_node, script_arguments=script_arguments)
reload_pipeline_object = self.reload(source=staging_table_definition, destination=production_table_definition, depends_on=[create_and_load_pipeline_object], analyze_table=analyze_table, non_transactional=non_transactional, enforce_primary_key=enforce_primary_key)
self.primary_key_check(table_definition=production_table_definition, pipeline_name=pipeline_name, depends_on=[reload_pipeline_object], log_to_s3=log_to_s3)<|docstring|>Constructor for the LoadReloadAndPrimaryKeyStep class
Args:
input_node: A S3 data node as input
staging_table_definition(filepath):
staging table schema to store the data
production_table_definition(filepath):
schema file for the table to be reloaded into
**kwargs(optional): Keyword arguments directly passed to base class<|endoftext|> |
fb7fea80a61ab7160465f2aa804fa737c7d52c49ce8521c509bb7e82bdda797a | @classmethod
def arguments_processor(cls, etl, input_args):
'Parse the step arguments according to the ETL pipeline\n\n Args:\n etl(ETLPipeline): Pipeline object containing resources and steps\n step_args(dict): Dictionary of the step arguments for the class\n '
step_args = cls.base_arguments_processor(etl, input_args)
step_args['pipeline_name'] = etl.name
return step_args | Parse the step arguments according to the ETL pipeline
Args:
etl(ETLPipeline): Pipeline object containing resources and steps
step_args(dict): Dictionary of the step arguments for the class | dataduct/steps/load_reload_pk.py | arguments_processor | recurly/dataduct | 3 | python | @classmethod
def arguments_processor(cls, etl, input_args):
'Parse the step arguments according to the ETL pipeline\n\n Args:\n etl(ETLPipeline): Pipeline object containing resources and steps\n step_args(dict): Dictionary of the step arguments for the class\n '
step_args = cls.base_arguments_processor(etl, input_args)
step_args['pipeline_name'] = etl.name
return step_args | @classmethod
def arguments_processor(cls, etl, input_args):
'Parse the step arguments according to the ETL pipeline\n\n Args:\n etl(ETLPipeline): Pipeline object containing resources and steps\n step_args(dict): Dictionary of the step arguments for the class\n '
step_args = cls.base_arguments_processor(etl, input_args)
step_args['pipeline_name'] = etl.name
return step_args<|docstring|>Parse the step arguments according to the ETL pipeline
Args:
etl(ETLPipeline): Pipeline object containing resources and steps
step_args(dict): Dictionary of the step arguments for the class<|endoftext|> |
9f692040b97e8136272580d3847ff50135a250bc4f8d7d1a23438c364eb475f3 | @contextmanager
def cd(path):
'\n A Fabric-inspired cd context that temporarily changes directory for\n performing some tasks, and returns to the original working directory\n afterwards. E.g.,\n\n with cd("/my/path/"):\n do_something()\n\n Args:\n path: Path to cd to.\n '
cwd = os.getcwd()
os.chdir(path)
try:
(yield)
finally:
os.chdir(cwd) | A Fabric-inspired cd context that temporarily changes directory for
performing some tasks, and returns to the original working directory
afterwards. E.g.,
with cd("/my/path/"):
do_something()
Args:
path: Path to cd to. | venv/Lib/site-packages/monty/os/__init__.py | cd | andrewsalij/pymatgen | 36 | python | @contextmanager
def cd(path):
'\n A Fabric-inspired cd context that temporarily changes directory for\n performing some tasks, and returns to the original working directory\n afterwards. E.g.,\n\n with cd("/my/path/"):\n do_something()\n\n Args:\n path: Path to cd to.\n '
cwd = os.getcwd()
os.chdir(path)
try:
(yield)
finally:
os.chdir(cwd) | @contextmanager
def cd(path):
'\n A Fabric-inspired cd context that temporarily changes directory for\n performing some tasks, and returns to the original working directory\n afterwards. E.g.,\n\n with cd("/my/path/"):\n do_something()\n\n Args:\n path: Path to cd to.\n '
cwd = os.getcwd()
os.chdir(path)
try:
(yield)
finally:
os.chdir(cwd)<|docstring|>A Fabric-inspired cd context that temporarily changes directory for
performing some tasks, and returns to the original working directory
afterwards. E.g.,
with cd("/my/path/"):
do_something()
Args:
path: Path to cd to.<|endoftext|> |
ea3b0501a145a2e29c659f1eba51023b9326132b68a3b034db96c3f0b05e936f | def makedirs_p(path, **kwargs):
'\n Wrapper for os.makedirs that does not raise an exception if the directory\n already exists, in the fashion of "mkdir -p" command. The check is\n performed in a thread-safe way\n\n Args:\n path: path of the directory to create\n kwargs: standard kwargs for os.makedirs\n '
try:
os.makedirs(path, **kwargs)
except OSError as exc:
if ((exc.errno == errno.EEXIST) and os.path.isdir(path)):
pass
else:
raise | Wrapper for os.makedirs that does not raise an exception if the directory
already exists, in the fashion of "mkdir -p" command. The check is
performed in a thread-safe way
Args:
path: path of the directory to create
kwargs: standard kwargs for os.makedirs | venv/Lib/site-packages/monty/os/__init__.py | makedirs_p | andrewsalij/pymatgen | 36 | python | def makedirs_p(path, **kwargs):
'\n Wrapper for os.makedirs that does not raise an exception if the directory\n already exists, in the fashion of "mkdir -p" command. The check is\n performed in a thread-safe way\n\n Args:\n path: path of the directory to create\n kwargs: standard kwargs for os.makedirs\n '
try:
os.makedirs(path, **kwargs)
except OSError as exc:
if ((exc.errno == errno.EEXIST) and os.path.isdir(path)):
pass
else:
raise | def makedirs_p(path, **kwargs):
'\n Wrapper for os.makedirs that does not raise an exception if the directory\n already exists, in the fashion of "mkdir -p" command. The check is\n performed in a thread-safe way\n\n Args:\n path: path of the directory to create\n kwargs: standard kwargs for os.makedirs\n '
try:
os.makedirs(path, **kwargs)
except OSError as exc:
if ((exc.errno == errno.EEXIST) and os.path.isdir(path)):
pass
else:
raise<|docstring|>Wrapper for os.makedirs that does not raise an exception if the directory
already exists, in the fashion of "mkdir -p" command. The check is
performed in a thread-safe way
Args:
path: path of the directory to create
kwargs: standard kwargs for os.makedirs<|endoftext|> |
c3691ed0a9a582ce45deb4eb4927b2499b51c8cc06ae31c7d9134300305ae1a0 | def __virtual__():
'\n Rename to ini\n '
return __virtualname__ | Rename to ini | salt/modules/ini_manage.py | __virtual__ | rawkode/salt | 1 | python | def __virtual__():
'\n \n '
return __virtualname__ | def __virtual__():
'\n \n '
return __virtualname__<|docstring|>Rename to ini<|endoftext|> |
91f405184c283a400561c42bd9d4d52f515a8051fd34552cb134c1c4a4951c84 | def set_option(file_name, sections=None, separator='='):
'\n Edit an ini file, replacing one or more sections. Returns a dictionary\n containing the changes made.\n\n file_name\n path of ini_file\n\n sections : None\n A dictionary representing the sections to be edited ini file\n The keys are the section names and the values are the dictionary\n containing the options\n If the ini file does not contain sections the keys and values represent\n the options\n\n separator : =\n A character used to separate keys and values. Standard ini files use\n the "=" character.\n\n .. versionadded:: 2016.11.0\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd(\'target\', \'ini.set_option\',\n [\'path_to_ini_file\', \'{"section_to_change": {"key": "value"}}\'])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt \'*\' ini.set_option /path/to/ini \'{section_foo: {key: value}}\'\n '
sections = (sections or {})
changes = {}
inifile = _Ini.get_ini_file(file_name, separator=separator)
changes = inifile.update(sections)
inifile.flush()
return changes | Edit an ini file, replacing one or more sections. Returns a dictionary
containing the changes made.
file_name
path of ini_file
sections : None
A dictionary representing the sections to be edited ini file
The keys are the section names and the values are the dictionary
containing the options
If the ini file does not contain sections the keys and values represent
the options
separator : =
A character used to separate keys and values. Standard ini files use
the "=" character.
.. versionadded:: 2016.11.0
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.set_option',
['path_to_ini_file', '{"section_to_change": {"key": "value"}}'])
CLI Example:
.. code-block:: bash
salt '*' ini.set_option /path/to/ini '{section_foo: {key: value}}' | salt/modules/ini_manage.py | set_option | rawkode/salt | 1 | python | def set_option(file_name, sections=None, separator='='):
'\n Edit an ini file, replacing one or more sections. Returns a dictionary\n containing the changes made.\n\n file_name\n path of ini_file\n\n sections : None\n A dictionary representing the sections to be edited ini file\n The keys are the section names and the values are the dictionary\n containing the options\n If the ini file does not contain sections the keys and values represent\n the options\n\n separator : =\n A character used to separate keys and values. Standard ini files use\n the "=" character.\n\n .. versionadded:: 2016.11.0\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd(\'target\', \'ini.set_option\',\n [\'path_to_ini_file\', \'{"section_to_change": {"key": "value"}}\'])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt \'*\' ini.set_option /path/to/ini \'{section_foo: {key: value}}\'\n '
sections = (sections or {})
changes = {}
inifile = _Ini.get_ini_file(file_name, separator=separator)
changes = inifile.update(sections)
inifile.flush()
return changes | def set_option(file_name, sections=None, separator='='):
'\n Edit an ini file, replacing one or more sections. Returns a dictionary\n containing the changes made.\n\n file_name\n path of ini_file\n\n sections : None\n A dictionary representing the sections to be edited ini file\n The keys are the section names and the values are the dictionary\n containing the options\n If the ini file does not contain sections the keys and values represent\n the options\n\n separator : =\n A character used to separate keys and values. Standard ini files use\n the "=" character.\n\n .. versionadded:: 2016.11.0\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd(\'target\', \'ini.set_option\',\n [\'path_to_ini_file\', \'{"section_to_change": {"key": "value"}}\'])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt \'*\' ini.set_option /path/to/ini \'{section_foo: {key: value}}\'\n '
sections = (sections or {})
changes = {}
inifile = _Ini.get_ini_file(file_name, separator=separator)
changes = inifile.update(sections)
inifile.flush()
return changes<|docstring|>Edit an ini file, replacing one or more sections. Returns a dictionary
containing the changes made.
file_name
path of ini_file
sections : None
A dictionary representing the sections to be edited ini file
The keys are the section names and the values are the dictionary
containing the options
If the ini file does not contain sections the keys and values represent
the options
separator : =
A character used to separate keys and values. Standard ini files use
the "=" character.
.. versionadded:: 2016.11.0
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.set_option',
['path_to_ini_file', '{"section_to_change": {"key": "value"}}'])
CLI Example:
.. code-block:: bash
salt '*' ini.set_option /path/to/ini '{section_foo: {key: value}}'<|endoftext|> |
af3de3abf4ad4527f0366a79df82978fc6e9ba158785a2ba58aad3b39980031b | def get_option(file_name, section, option, separator='='):
"\n Get value of a key from a section in an ini file. Returns ``None`` if\n no matching key was found.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.get_option',\n [path_to_ini_file, section_name, option])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.get_option /path/to/ini section_name option_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
return inifile.get(section, {}).get(option, None) | Get value of a key from a section in an ini file. Returns ``None`` if
no matching key was found.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_option',
[path_to_ini_file, section_name, option])
CLI Example:
.. code-block:: bash
salt '*' ini.get_option /path/to/ini section_name option_name | salt/modules/ini_manage.py | get_option | rawkode/salt | 1 | python | def get_option(file_name, section, option, separator='='):
"\n Get value of a key from a section in an ini file. Returns ``None`` if\n no matching key was found.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.get_option',\n [path_to_ini_file, section_name, option])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.get_option /path/to/ini section_name option_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
return inifile.get(section, {}).get(option, None) | def get_option(file_name, section, option, separator='='):
"\n Get value of a key from a section in an ini file. Returns ``None`` if\n no matching key was found.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.get_option',\n [path_to_ini_file, section_name, option])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.get_option /path/to/ini section_name option_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
return inifile.get(section, {}).get(option, None)<|docstring|>Get value of a key from a section in an ini file. Returns ``None`` if
no matching key was found.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_option',
[path_to_ini_file, section_name, option])
CLI Example:
.. code-block:: bash
salt '*' ini.get_option /path/to/ini section_name option_name<|endoftext|> |
22a12dc9be5763eae975bb58a68fc422bec0f6fc57e8d93bf92c02640b6d95d0 | def remove_option(file_name, section, option, separator='='):
"\n Remove a key/value pair from a section in an ini file. Returns the value of\n the removed key, or ``None`` if nothing was removed.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.remove_option',\n [path_to_ini_file, section_name, option])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.remove_option /path/to/ini section_name option_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
value = inifile.get(section, {}).pop(option, None)
inifile.flush()
return value | Remove a key/value pair from a section in an ini file. Returns the value of
the removed key, or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_option',
[path_to_ini_file, section_name, option])
CLI Example:
.. code-block:: bash
salt '*' ini.remove_option /path/to/ini section_name option_name | salt/modules/ini_manage.py | remove_option | rawkode/salt | 1 | python | def remove_option(file_name, section, option, separator='='):
"\n Remove a key/value pair from a section in an ini file. Returns the value of\n the removed key, or ``None`` if nothing was removed.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.remove_option',\n [path_to_ini_file, section_name, option])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.remove_option /path/to/ini section_name option_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
value = inifile.get(section, {}).pop(option, None)
inifile.flush()
return value | def remove_option(file_name, section, option, separator='='):
"\n Remove a key/value pair from a section in an ini file. Returns the value of\n the removed key, or ``None`` if nothing was removed.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.remove_option',\n [path_to_ini_file, section_name, option])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.remove_option /path/to/ini section_name option_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
value = inifile.get(section, {}).pop(option, None)
inifile.flush()
return value<|docstring|>Remove a key/value pair from a section in an ini file. Returns the value of
the removed key, or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_option',
[path_to_ini_file, section_name, option])
CLI Example:
.. code-block:: bash
salt '*' ini.remove_option /path/to/ini section_name option_name<|endoftext|> |
5bee1a47b6947bbcc4bdd7a65adb121901e84a2977e7531a3cf526611243376a | def get_section(file_name, section, separator='='):
"\n Retrieve a section from an ini file. Returns the section as dictionary. If\n the section is not found, an empty dictionary is returned.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.get_section',\n [path_to_ini_file, section_name])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.get_section /path/to/ini section_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
ret = {}
for (key, value) in six.iteritems(inifile.get(section, {})):
if (key[0] != '#'):
ret.update({key: value})
return ret | Retrieve a section from an ini file. Returns the section as dictionary. If
the section is not found, an empty dictionary is returned.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.get_section /path/to/ini section_name | salt/modules/ini_manage.py | get_section | rawkode/salt | 1 | python | def get_section(file_name, section, separator='='):
"\n Retrieve a section from an ini file. Returns the section as dictionary. If\n the section is not found, an empty dictionary is returned.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.get_section',\n [path_to_ini_file, section_name])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.get_section /path/to/ini section_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
ret = {}
for (key, value) in six.iteritems(inifile.get(section, {})):
if (key[0] != '#'):
ret.update({key: value})
return ret | def get_section(file_name, section, separator='='):
"\n Retrieve a section from an ini file. Returns the section as dictionary. If\n the section is not found, an empty dictionary is returned.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.get_section',\n [path_to_ini_file, section_name])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.get_section /path/to/ini section_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
ret = {}
for (key, value) in six.iteritems(inifile.get(section, {})):
if (key[0] != '#'):
ret.update({key: value})
return ret<|docstring|>Retrieve a section from an ini file. Returns the section as dictionary. If
the section is not found, an empty dictionary is returned.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.get_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.get_section /path/to/ini section_name<|endoftext|> |
4ddfc608802c6eac7f1ba0164372c0f62bd60c380599f941484dbf6efaf49cb4 | def remove_section(file_name, section, separator='='):
"\n Remove a section in an ini file. Returns the removed section as dictionary,\n or ``None`` if nothing was removed.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.remove_section',\n [path_to_ini_file, section_name])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.remove_section /path/to/ini section_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
section = inifile.pop(section, {})
inifile.flush()
ret = {}
for (key, value) in six.iteritems(section):
if (key[0] != '#'):
ret.update({key: value})
return ret | Remove a section in an ini file. Returns the removed section as dictionary,
or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.remove_section /path/to/ini section_name | salt/modules/ini_manage.py | remove_section | rawkode/salt | 1 | python | def remove_section(file_name, section, separator='='):
"\n Remove a section in an ini file. Returns the removed section as dictionary,\n or ``None`` if nothing was removed.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.remove_section',\n [path_to_ini_file, section_name])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.remove_section /path/to/ini section_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
section = inifile.pop(section, {})
inifile.flush()
ret = {}
for (key, value) in six.iteritems(section):
if (key[0] != '#'):
ret.update({key: value})
return ret | def remove_section(file_name, section, separator='='):
"\n Remove a section in an ini file. Returns the removed section as dictionary,\n or ``None`` if nothing was removed.\n\n API Example:\n\n .. code-block:: python\n\n import salt\n sc = salt.client.get_local_client()\n sc.cmd('target', 'ini.remove_section',\n [path_to_ini_file, section_name])\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' ini.remove_section /path/to/ini section_name\n "
inifile = _Ini.get_ini_file(file_name, separator=separator)
section = inifile.pop(section, {})
inifile.flush()
ret = {}
for (key, value) in six.iteritems(section):
if (key[0] != '#'):
ret.update({key: value})
return ret<|docstring|>Remove a section in an ini file. Returns the removed section as dictionary,
or ``None`` if nothing was removed.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
sc.cmd('target', 'ini.remove_section',
[path_to_ini_file, section_name])
CLI Example:
.. code-block:: bash
salt '*' ini.remove_section /path/to/ini section_name<|endoftext|> |
0d0268558f4196804902428969e956ca499c010e2783ad9b25898fb812cab2d6 | def raw(code_path, results):
'\n Compute raw metrics such as number of lines of code, documentation rate or complexity metrics\n\n :param code_path: Path to the source code\n :param results: Dictionary to which the results are appended.\n '
h = RawHarvester([code_path], Config(exclude=None, ignore=None, summary=True))
file_metrics = dict(h.results)
h = MIHarvester([code_path], Config(min='A', max='C', multi=True, exclude=None, ignore=None, show=False, json=False, sort=False))
mi_metrics = dict(h.results)
always_merger.merge(file_metrics, mi_metrics)
summary = dict()
summation_keys = ['loc', 'lloc', 'sloc', 'comments', 'multi', 'blank', 'single_comments']
for k in summation_keys:
summary[k] = sum([metrics[k] for metrics in file_metrics.values()])
averaging_keys = {'mi': 'sloc'}
for (key_index, weight_index) in averaging_keys.items():
if (summary[weight_index] == 0.0):
summary[weight_index] = 0.0
else:
summary[key_index] = (sum([(metrics[key_index] * metrics[weight_index]) for metrics in file_metrics.values()]) / summary[weight_index])
results[LINES_OF_CODE] = summary.get('lloc', 0)
results[COMMENT_RATE] = ((float(summary.get('comments', 0)) + float(summary.get('multi', 0))) / max(1, float(summary.get('loc', 1))))
results[MAINTAINABILITY_INDEX] = (summary.get('mi', 0.0) / 100.0) | Compute raw metrics such as number of lines of code, documentation rate or complexity metrics
:param code_path: Path to the source code
:param results: Dictionary to which the results are appended. | metrics/measures/raw.py | raw | sebMathieu/code_metrics | 0 | python | def raw(code_path, results):
'\n Compute raw metrics such as number of lines of code, documentation rate or complexity metrics\n\n :param code_path: Path to the source code\n :param results: Dictionary to which the results are appended.\n '
h = RawHarvester([code_path], Config(exclude=None, ignore=None, summary=True))
file_metrics = dict(h.results)
h = MIHarvester([code_path], Config(min='A', max='C', multi=True, exclude=None, ignore=None, show=False, json=False, sort=False))
mi_metrics = dict(h.results)
always_merger.merge(file_metrics, mi_metrics)
summary = dict()
summation_keys = ['loc', 'lloc', 'sloc', 'comments', 'multi', 'blank', 'single_comments']
for k in summation_keys:
summary[k] = sum([metrics[k] for metrics in file_metrics.values()])
averaging_keys = {'mi': 'sloc'}
for (key_index, weight_index) in averaging_keys.items():
if (summary[weight_index] == 0.0):
summary[weight_index] = 0.0
else:
summary[key_index] = (sum([(metrics[key_index] * metrics[weight_index]) for metrics in file_metrics.values()]) / summary[weight_index])
results[LINES_OF_CODE] = summary.get('lloc', 0)
results[COMMENT_RATE] = ((float(summary.get('comments', 0)) + float(summary.get('multi', 0))) / max(1, float(summary.get('loc', 1))))
results[MAINTAINABILITY_INDEX] = (summary.get('mi', 0.0) / 100.0) | def raw(code_path, results):
'\n Compute raw metrics such as number of lines of code, documentation rate or complexity metrics\n\n :param code_path: Path to the source code\n :param results: Dictionary to which the results are appended.\n '
h = RawHarvester([code_path], Config(exclude=None, ignore=None, summary=True))
file_metrics = dict(h.results)
h = MIHarvester([code_path], Config(min='A', max='C', multi=True, exclude=None, ignore=None, show=False, json=False, sort=False))
mi_metrics = dict(h.results)
always_merger.merge(file_metrics, mi_metrics)
summary = dict()
summation_keys = ['loc', 'lloc', 'sloc', 'comments', 'multi', 'blank', 'single_comments']
for k in summation_keys:
summary[k] = sum([metrics[k] for metrics in file_metrics.values()])
averaging_keys = {'mi': 'sloc'}
for (key_index, weight_index) in averaging_keys.items():
if (summary[weight_index] == 0.0):
summary[weight_index] = 0.0
else:
summary[key_index] = (sum([(metrics[key_index] * metrics[weight_index]) for metrics in file_metrics.values()]) / summary[weight_index])
results[LINES_OF_CODE] = summary.get('lloc', 0)
results[COMMENT_RATE] = ((float(summary.get('comments', 0)) + float(summary.get('multi', 0))) / max(1, float(summary.get('loc', 1))))
results[MAINTAINABILITY_INDEX] = (summary.get('mi', 0.0) / 100.0)<|docstring|>Compute raw metrics such as number of lines of code, documentation rate or complexity metrics
:param code_path: Path to the source code
:param results: Dictionary to which the results are appended.<|endoftext|> |
d584371ab9e380c50eb8f8201760437a81918185c5e138b75693c28bc3f068f4 | def has_add_permission(self, request):
'Permission to ADD a LogEntry'
return False | Permission to ADD a LogEntry | backend/core/admin.py | has_add_permission | ziibii88/ambassador | 1 | python | def has_add_permission(self, request):
return False | def has_add_permission(self, request):
return False<|docstring|>Permission to ADD a LogEntry<|endoftext|> |
57ec341081c3fc6aa27e491c5833cb5d29db2dc47ffe8120e9bf7ec416ba2b71 | def has_change_permission(self, request, obj=None):
'Permission to CHANGE a LogEntry'
return False | Permission to CHANGE a LogEntry | backend/core/admin.py | has_change_permission | ziibii88/ambassador | 1 | python | def has_change_permission(self, request, obj=None):
return False | def has_change_permission(self, request, obj=None):
return False<|docstring|>Permission to CHANGE a LogEntry<|endoftext|> |
9bf8c2b3953848c95ed88f9bf4878abfe972c1027336931a4fb927bacc38bbac | def has_delete_permission(self, request, obj=None):
'Permission to DELETE a LogEntry'
return request.user.is_superuser | Permission to DELETE a LogEntry | backend/core/admin.py | has_delete_permission | ziibii88/ambassador | 1 | python | def has_delete_permission(self, request, obj=None):
return request.user.is_superuser | def has_delete_permission(self, request, obj=None):
return request.user.is_superuser<|docstring|>Permission to DELETE a LogEntry<|endoftext|> |
949eaed3abf48cb1f5f8d486bb05eb6884cce38773f38bdf9b02da601e4d6f11 | def has_view_permission(self, request, obj=None):
'Permission to VIEW a LogEntry'
return request.user.is_superuser | Permission to VIEW a LogEntry | backend/core/admin.py | has_view_permission | ziibii88/ambassador | 1 | python | def has_view_permission(self, request, obj=None):
return request.user.is_superuser | def has_view_permission(self, request, obj=None):
return request.user.is_superuser<|docstring|>Permission to VIEW a LogEntry<|endoftext|> |
4ada9e37ac3fb1fdae3dafed434b2142ce92f12b7398b61a3d60c0d3cbaa78d2 | def user_link(self, obj):
'Show link to the User'
try:
url = reverse('admin:core_user_change', args=[obj.user_id])
link = f'<a href="{url}">{escape(obj.user)}</a>'
except Exception as e:
logger.debug(e)
link = escape(obj.user)
return mark_safe(link) | Show link to the User | backend/core/admin.py | user_link | ziibii88/ambassador | 1 | python | def user_link(self, obj):
try:
url = reverse('admin:core_user_change', args=[obj.user_id])
link = f'<a href="{url}">{escape(obj.user)}</a>'
except Exception as e:
logger.debug(e)
link = escape(obj.user)
return mark_safe(link) | def user_link(self, obj):
try:
url = reverse('admin:core_user_change', args=[obj.user_id])
link = f'<a href="{url}">{escape(obj.user)}</a>'
except Exception as e:
logger.debug(e)
link = escape(obj.user)
return mark_safe(link)<|docstring|>Show link to the User<|endoftext|> |
3001c66fcac4e68e89383b134b0c7b784edcfa543dfbe2bf30c4f408fc5edcd3 | def object_link(self, obj):
'Show link to the object'
if (obj.action_flag == DELETION):
link = escape(obj.object_repr)
else:
try:
ct = obj.content_type
url = reverse(f'admin:{ct.app_label}_{ct.model}_change', args=[obj.object_id])
link = f'<a href="{url}">{escape(obj.object_repr)}</a>'
except Exception as e:
logger.debug(e)
link = escape(obj.object_repr)
return mark_safe(link) | Show link to the object | backend/core/admin.py | object_link | ziibii88/ambassador | 1 | python | def object_link(self, obj):
if (obj.action_flag == DELETION):
link = escape(obj.object_repr)
else:
try:
ct = obj.content_type
url = reverse(f'admin:{ct.app_label}_{ct.model}_change', args=[obj.object_id])
link = f'<a href="{url}">{escape(obj.object_repr)}</a>'
except Exception as e:
logger.debug(e)
link = escape(obj.object_repr)
return mark_safe(link) | def object_link(self, obj):
if (obj.action_flag == DELETION):
link = escape(obj.object_repr)
else:
try:
ct = obj.content_type
url = reverse(f'admin:{ct.app_label}_{ct.model}_change', args=[obj.object_id])
link = f'<a href="{url}">{escape(obj.object_repr)}</a>'
except Exception as e:
logger.debug(e)
link = escape(obj.object_repr)
return mark_safe(link)<|docstring|>Show link to the object<|endoftext|> |
977661af295f5ac0fd8a293d27bd47bba18d0923e56bf87247b41c25c8b933df | def train(model, data_loader, optimizer=None):
'\n training function\n :param model:\n :param data_loader:\n :param optimizer:\n :return:\n '
mean_loss = 0
n_samples_precessed = 0
with torch.set_grad_enabled((optimizer is not None)):
for batch in data_loader:
k_model = model(batch.constraint_features, batch.edge_index, batch.edge_attr, batch.variable_features)
k_init = batch.k_init
loss = F.mse_loss(k_model.float(), k_init.float())
if (optimizer is not None):
optimizer.zero_grad()
loss.backward()
optimizer.step()
mean_loss += (loss.item() * batch.num_graphs)
n_samples_precessed += batch.num_graphs
mean_loss /= n_samples_precessed
return mean_loss | training function
:param model:
:param data_loader:
:param optimizer:
:return: | unit_test/test_train_kinit.py | train | pandat8/ML4LocalBranch_extend | 4 | python | def train(model, data_loader, optimizer=None):
'\n training function\n :param model:\n :param data_loader:\n :param optimizer:\n :return:\n '
mean_loss = 0
n_samples_precessed = 0
with torch.set_grad_enabled((optimizer is not None)):
for batch in data_loader:
k_model = model(batch.constraint_features, batch.edge_index, batch.edge_attr, batch.variable_features)
k_init = batch.k_init
loss = F.mse_loss(k_model.float(), k_init.float())
if (optimizer is not None):
optimizer.zero_grad()
loss.backward()
optimizer.step()
mean_loss += (loss.item() * batch.num_graphs)
n_samples_precessed += batch.num_graphs
mean_loss /= n_samples_precessed
return mean_loss | def train(model, data_loader, optimizer=None):
'\n training function\n :param model:\n :param data_loader:\n :param optimizer:\n :return:\n '
mean_loss = 0
n_samples_precessed = 0
with torch.set_grad_enabled((optimizer is not None)):
for batch in data_loader:
k_model = model(batch.constraint_features, batch.edge_index, batch.edge_attr, batch.variable_features)
k_init = batch.k_init
loss = F.mse_loss(k_model.float(), k_init.float())
if (optimizer is not None):
optimizer.zero_grad()
loss.backward()
optimizer.step()
mean_loss += (loss.item() * batch.num_graphs)
n_samples_precessed += batch.num_graphs
mean_loss /= n_samples_precessed
return mean_loss<|docstring|>training function
:param model:
:param data_loader:
:param optimizer:
:return:<|endoftext|> |
86fa661645f5b4c6b188dcedbf488251e7b6113881a5e8a319996eab9fd8d20e | def vader(text):
'Return score Vader'
analyzer = SentimentIntensityAnalyzer()
dict_vader = analyzer.polarity_scores(text)
return [dict_vader['neg'], dict_vader['neu'], dict_vader['pos']] | Return score Vader | representations.py | vader | claudiovaliense/compression_sparse | 0 | python | def vader(text):
analyzer = SentimentIntensityAnalyzer()
dict_vader = analyzer.polarity_scores(text)
return [dict_vader['neg'], dict_vader['neu'], dict_vader['pos']] | def vader(text):
analyzer = SentimentIntensityAnalyzer()
dict_vader = analyzer.polarity_scores(text)
return [dict_vader['neg'], dict_vader['neu'], dict_vader['pos']]<|docstring|>Return score Vader<|endoftext|> |
414632b1051f4d4f06195ee7ae6db7a8029931c7b946cd1e69d9145940f2d9f4 | def representation_bert(x, pooling=None):
'Create representation BERT'
import numpy
from transformers import BertModel, BertTokenizer
if ('16' in pooling):
limit_token = 16
elif ('32' in pooling):
limit_token = 32
elif ('64' in pooling):
limit_token = 64
elif ('128' in pooling):
limit_token = 128
elif ('256' in pooling):
limit_token = 256
elif ('512' in pooling):
limit_token = 512
limit_token = 512
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased', output_hidden_states=True)
model = model.to('cuda:0')
for index_doc in range(len(x)):
inputs = tokenizer(x[index_doc], return_tensors='pt', max_length=limit_token, truncation=True)
inputs = assign_GPU(inputs)
outputs = model(**inputs)
if (('bert_concat' in pooling) or ('bert_sum' in pooling) or ('bert_last_avg' in pooling) or ('bert_cls' in pooling)):
hidden_states = outputs[2]
token_embeddings = torch.stack(hidden_states, dim=0)
token_embeddings = torch.squeeze(token_embeddings, dim=1)
token_embeddings = token_embeddings.permute(1, 0, 2)
vets = []
for token in token_embeddings:
if ('bert_concat' == pooling):
vets.append(torch.cat((token[(- 1)], token[(- 2)], token[(- 3)], token[(- 4)]), dim=0).cpu().detach().numpy())
elif ('bert_sum' == pooling):
vets.append(torch.sum(token[(- 4):], dim=0).cpu().detach().numpy())
elif ('bert_last_avg' == pooling):
vets.append(torch.mean(token[(- 4):], dim=0).cpu().detach().numpy())
elif ('bert_cls' == pooling):
x[index_doc] = token[(- 1)].cpu().detach().numpy()
break
if ('bert_cls' != pooling):
x[index_doc] = numpy.mean(vets, axis=0)
else:
tokens = outputs[0].cpu().detach().numpy()[0]
if ('bert_avg' in pooling):
x[index_doc] = numpy.mean(tokens, axis=0)
elif ('bert_max' in pooling):
x[index_doc] = numpy.amax(tokens, axis=0)
return x | Create representation BERT | representations.py | representation_bert | claudiovaliense/compression_sparse | 0 | python | def representation_bert(x, pooling=None):
import numpy
from transformers import BertModel, BertTokenizer
if ('16' in pooling):
limit_token = 16
elif ('32' in pooling):
limit_token = 32
elif ('64' in pooling):
limit_token = 64
elif ('128' in pooling):
limit_token = 128
elif ('256' in pooling):
limit_token = 256
elif ('512' in pooling):
limit_token = 512
limit_token = 512
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased', output_hidden_states=True)
model = model.to('cuda:0')
for index_doc in range(len(x)):
inputs = tokenizer(x[index_doc], return_tensors='pt', max_length=limit_token, truncation=True)
inputs = assign_GPU(inputs)
outputs = model(**inputs)
if (('bert_concat' in pooling) or ('bert_sum' in pooling) or ('bert_last_avg' in pooling) or ('bert_cls' in pooling)):
hidden_states = outputs[2]
token_embeddings = torch.stack(hidden_states, dim=0)
token_embeddings = torch.squeeze(token_embeddings, dim=1)
token_embeddings = token_embeddings.permute(1, 0, 2)
vets = []
for token in token_embeddings:
if ('bert_concat' == pooling):
vets.append(torch.cat((token[(- 1)], token[(- 2)], token[(- 3)], token[(- 4)]), dim=0).cpu().detach().numpy())
elif ('bert_sum' == pooling):
vets.append(torch.sum(token[(- 4):], dim=0).cpu().detach().numpy())
elif ('bert_last_avg' == pooling):
vets.append(torch.mean(token[(- 4):], dim=0).cpu().detach().numpy())
elif ('bert_cls' == pooling):
x[index_doc] = token[(- 1)].cpu().detach().numpy()
break
if ('bert_cls' != pooling):
x[index_doc] = numpy.mean(vets, axis=0)
else:
tokens = outputs[0].cpu().detach().numpy()[0]
if ('bert_avg' in pooling):
x[index_doc] = numpy.mean(tokens, axis=0)
elif ('bert_max' in pooling):
x[index_doc] = numpy.amax(tokens, axis=0)
return x | def representation_bert(x, pooling=None):
import numpy
from transformers import BertModel, BertTokenizer
if ('16' in pooling):
limit_token = 16
elif ('32' in pooling):
limit_token = 32
elif ('64' in pooling):
limit_token = 64
elif ('128' in pooling):
limit_token = 128
elif ('256' in pooling):
limit_token = 256
elif ('512' in pooling):
limit_token = 512
limit_token = 512
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased', output_hidden_states=True)
model = model.to('cuda:0')
for index_doc in range(len(x)):
inputs = tokenizer(x[index_doc], return_tensors='pt', max_length=limit_token, truncation=True)
inputs = assign_GPU(inputs)
outputs = model(**inputs)
if (('bert_concat' in pooling) or ('bert_sum' in pooling) or ('bert_last_avg' in pooling) or ('bert_cls' in pooling)):
hidden_states = outputs[2]
token_embeddings = torch.stack(hidden_states, dim=0)
token_embeddings = torch.squeeze(token_embeddings, dim=1)
token_embeddings = token_embeddings.permute(1, 0, 2)
vets = []
for token in token_embeddings:
if ('bert_concat' == pooling):
vets.append(torch.cat((token[(- 1)], token[(- 2)], token[(- 3)], token[(- 4)]), dim=0).cpu().detach().numpy())
elif ('bert_sum' == pooling):
vets.append(torch.sum(token[(- 4):], dim=0).cpu().detach().numpy())
elif ('bert_last_avg' == pooling):
vets.append(torch.mean(token[(- 4):], dim=0).cpu().detach().numpy())
elif ('bert_cls' == pooling):
x[index_doc] = token[(- 1)].cpu().detach().numpy()
break
if ('bert_cls' != pooling):
x[index_doc] = numpy.mean(vets, axis=0)
else:
tokens = outputs[0].cpu().detach().numpy()[0]
if ('bert_avg' in pooling):
x[index_doc] = numpy.mean(tokens, axis=0)
elif ('bert_max' in pooling):
x[index_doc] = numpy.amax(tokens, axis=0)
return x<|docstring|>Create representation BERT<|endoftext|> |
e1607f68749a81c84523cc575eb1440761d7b90f1999a382dc73cfb7fc9bae4b | def __call__(self, request):
"\n Sets REMOTE_ADDR correctly to the client's ip, if REMOTE_ADDR is missing.\n It happens when django is run with a domain socket server (eg. gunicorn).\n ref: https://stackoverflow.com/a/34254843/1031191\n "
if ((not request.META('REMOTE_ADDR', '')) and ('HTTP_X_FORWARDED_FOR' in request.META)):
parts = request.META['HTTP_X_FORWARDED_FOR'].split(',', 1)
request.META['REMOTE_ADDR'] = parts[0]
return self.get_response(request) | Sets REMOTE_ADDR correctly to the client's ip, if REMOTE_ADDR is missing.
It happens when django is run with a domain socket server (eg. gunicorn).
ref: https://stackoverflow.com/a/34254843/1031191 | ratelimit/middleware.py | __call__ | BarnabasSzabolcs/django-ratelimit | 0 | python | def __call__(self, request):
"\n Sets REMOTE_ADDR correctly to the client's ip, if REMOTE_ADDR is missing.\n It happens when django is run with a domain socket server (eg. gunicorn).\n ref: https://stackoverflow.com/a/34254843/1031191\n "
if ((not request.META('REMOTE_ADDR', )) and ('HTTP_X_FORWARDED_FOR' in request.META)):
parts = request.META['HTTP_X_FORWARDED_FOR'].split(',', 1)
request.META['REMOTE_ADDR'] = parts[0]
return self.get_response(request) | def __call__(self, request):
"\n Sets REMOTE_ADDR correctly to the client's ip, if REMOTE_ADDR is missing.\n It happens when django is run with a domain socket server (eg. gunicorn).\n ref: https://stackoverflow.com/a/34254843/1031191\n "
if ((not request.META('REMOTE_ADDR', )) and ('HTTP_X_FORWARDED_FOR' in request.META)):
parts = request.META['HTTP_X_FORWARDED_FOR'].split(',', 1)
request.META['REMOTE_ADDR'] = parts[0]
return self.get_response(request)<|docstring|>Sets REMOTE_ADDR correctly to the client's ip, if REMOTE_ADDR is missing.
It happens when django is run with a domain socket server (eg. gunicorn).
ref: https://stackoverflow.com/a/34254843/1031191<|endoftext|> |
44d4aee7d894cc239f499ca6c5ad4b44c4600d900c63ab58ff4d8691fce374fa | def convert(subdir, hydrogen_per_atom):
'Converts united atom files to all atom format.'
with cd(subdir):
path = '../0_initial_structure'
for (subdir, dirs, files) in os.walk(path):
if (sum([('snapshot' in f) for f in files]) < 1):
print(os.getcwd())
raise RuntimeError('No snapshot.pdb file found.')
if (sum([('snapshot' in f) for f in files]) > 2):
print(os.getcwd())
raise RuntimeError('Multiple snapshot.pdb files found.')
smamp.convert_UA_to_AA.main(implicitHbondingPartners=hydrogen_per_atom) | Converts united atom files to all atom format. | bin/loop_convert_UA_to_AA.py | convert | lukaselflein/sarah_folderstructure | 0 | python | def convert(subdir, hydrogen_per_atom):
with cd(subdir):
path = '../0_initial_structure'
for (subdir, dirs, files) in os.walk(path):
if (sum([('snapshot' in f) for f in files]) < 1):
print(os.getcwd())
raise RuntimeError('No snapshot.pdb file found.')
if (sum([('snapshot' in f) for f in files]) > 2):
print(os.getcwd())
raise RuntimeError('Multiple snapshot.pdb files found.')
smamp.convert_UA_to_AA.main(implicitHbondingPartners=hydrogen_per_atom) | def convert(subdir, hydrogen_per_atom):
with cd(subdir):
path = '../0_initial_structure'
for (subdir, dirs, files) in os.walk(path):
if (sum([('snapshot' in f) for f in files]) < 1):
print(os.getcwd())
raise RuntimeError('No snapshot.pdb file found.')
if (sum([('snapshot' in f) for f in files]) > 2):
print(os.getcwd())
raise RuntimeError('Multiple snapshot.pdb files found.')
smamp.convert_UA_to_AA.main(implicitHbondingPartners=hydrogen_per_atom)<|docstring|>Converts united atom files to all atom format.<|endoftext|> |
e87379570f4e53c2d3b93486195e1ad2e7803b7a7392dd6b09c3076d5a40550a | def cmd_parser():
'Read Command line arguments.'
parser = argparse.ArgumentParser(prog='', description=__doc__.splitlines()[0])
args = parser.parse_args() | Read Command line arguments. | bin/loop_convert_UA_to_AA.py | cmd_parser | lukaselflein/sarah_folderstructure | 0 | python | def cmd_parser():
parser = argparse.ArgumentParser(prog=, description=__doc__.splitlines()[0])
args = parser.parse_args() | def cmd_parser():
parser = argparse.ArgumentParser(prog=, description=__doc__.splitlines()[0])
args = parser.parse_args()<|docstring|>Read Command line arguments.<|endoftext|> |
93d06ecad74cd4d706bd3554e84df4a2457865529da1cb6ca4916b598643c138 | def main():
' Execute everything.'
cmd_parser()
print('This is {}.'.format(__file__))
hydrogen_per_atom = read_atom_numbers()
print('Current working dir: {}'.format(os.getcwd()))
for (subdir, dirs, files) in sorted(os.walk('.')):
if (('template' in subdir) or ('exclude' in subdir)):
continue
if ('all_atom_structure' in subdir):
print('Moving to {}'.format(subdir))
convert(subdir, hydrogen_per_atom) | Execute everything. | bin/loop_convert_UA_to_AA.py | main | lukaselflein/sarah_folderstructure | 0 | python | def main():
' '
cmd_parser()
print('This is {}.'.format(__file__))
hydrogen_per_atom = read_atom_numbers()
print('Current working dir: {}'.format(os.getcwd()))
for (subdir, dirs, files) in sorted(os.walk('.')):
if (('template' in subdir) or ('exclude' in subdir)):
continue
if ('all_atom_structure' in subdir):
print('Moving to {}'.format(subdir))
convert(subdir, hydrogen_per_atom) | def main():
' '
cmd_parser()
print('This is {}.'.format(__file__))
hydrogen_per_atom = read_atom_numbers()
print('Current working dir: {}'.format(os.getcwd()))
for (subdir, dirs, files) in sorted(os.walk('.')):
if (('template' in subdir) or ('exclude' in subdir)):
continue
if ('all_atom_structure' in subdir):
print('Moving to {}'.format(subdir))
convert(subdir, hydrogen_per_atom)<|docstring|>Execute everything.<|endoftext|> |
010bdbfbc50d7303aa4af82519a460bdb6984030d15c5af4e9a54c92637c7069 | def main():
'Main program body.'
args = parse_args()
version = get_version()
if args.print_tag:
print(('v%s.%s.%s-pwsh' % (version.major, version.minor, version.patch)))
elif args.output_dir:
if os.path.exists(args.output_dir):
shutil.rmtree(args.output_dir)
os.makedirs(args.output_dir)
lib_path = os.path.join(OMI_REPO, 'PSWSMan', 'lib')
for distribution in os.listdir(lib_path):
artifact_dir = os.path.join(lib_path, distribution)
artifact_tar = (os.path.join(args.output_dir, distribution) + '.tar.gz')
if (distribution.startswith('.') or (not os.path.isdir(artifact_dir))):
continue
print(("Creating '%s'" % artifact_tar))
with tarfile.open(artifact_tar, 'w:gz') as tar:
for lib_name in os.listdir(artifact_dir):
if (lib_name == '.'):
continue
print(("\tAdding '%s' to tar" % lib_name))
tar.add(os.path.join(artifact_dir, lib_name), arcname=lib_name)
pwsh_command = ("$ErrorActionPreference = 'Stop'\n\n$outputDir = '%s'\n$repoParams = @{\n Name = 'PSWSManRepo'\n SourceLocation = $outputDir\n PublishLocation = $outputDir\n InstallationPolicy = 'Trusted'\n}\nif (Get-PSRepository -Name $repoParams.Name -ErrorAction SilentlyContinue) {\n Unregister-PSRepository -Name $repoParams.Name\n}\nRegister-PSRepository @repoParams\n\ntry {\n Publish-Module -Path ./PSWSMan -Repository $repoParams.Name\n} finally {\n Unregister-PSRepository -Name $repoParams.Name\n}\n" % args.output_dir)
with tempfile.NamedTemporaryFile(mode='w', suffix='.ps1') as temp_fd:
temp_fd.write(pwsh_command)
temp_fd.flush()
print('Creating PSWSMan nupkg')
subprocess.check_call(['pwsh', '-File', temp_fd.name], cwd=OMI_REPO)
nupkg_name = None
for name in os.listdir(args.output_dir):
if name.endswith('.nupkg'):
print(("Published PSWSMan to '%s'" % os.path.join(args.output_dir, name))) | Main program body. | release.py | main | TheBigBear/omi | 0 | python | def main():
args = parse_args()
version = get_version()
if args.print_tag:
print(('v%s.%s.%s-pwsh' % (version.major, version.minor, version.patch)))
elif args.output_dir:
if os.path.exists(args.output_dir):
shutil.rmtree(args.output_dir)
os.makedirs(args.output_dir)
lib_path = os.path.join(OMI_REPO, 'PSWSMan', 'lib')
for distribution in os.listdir(lib_path):
artifact_dir = os.path.join(lib_path, distribution)
artifact_tar = (os.path.join(args.output_dir, distribution) + '.tar.gz')
if (distribution.startswith('.') or (not os.path.isdir(artifact_dir))):
continue
print(("Creating '%s'" % artifact_tar))
with tarfile.open(artifact_tar, 'w:gz') as tar:
for lib_name in os.listdir(artifact_dir):
if (lib_name == '.'):
continue
print(("\tAdding '%s' to tar" % lib_name))
tar.add(os.path.join(artifact_dir, lib_name), arcname=lib_name)
pwsh_command = ("$ErrorActionPreference = 'Stop'\n\n$outputDir = '%s'\n$repoParams = @{\n Name = 'PSWSManRepo'\n SourceLocation = $outputDir\n PublishLocation = $outputDir\n InstallationPolicy = 'Trusted'\n}\nif (Get-PSRepository -Name $repoParams.Name -ErrorAction SilentlyContinue) {\n Unregister-PSRepository -Name $repoParams.Name\n}\nRegister-PSRepository @repoParams\n\ntry {\n Publish-Module -Path ./PSWSMan -Repository $repoParams.Name\n} finally {\n Unregister-PSRepository -Name $repoParams.Name\n}\n" % args.output_dir)
with tempfile.NamedTemporaryFile(mode='w', suffix='.ps1') as temp_fd:
temp_fd.write(pwsh_command)
temp_fd.flush()
print('Creating PSWSMan nupkg')
subprocess.check_call(['pwsh', '-File', temp_fd.name], cwd=OMI_REPO)
nupkg_name = None
for name in os.listdir(args.output_dir):
if name.endswith('.nupkg'):
print(("Published PSWSMan to '%s'" % os.path.join(args.output_dir, name))) | def main():
args = parse_args()
version = get_version()
if args.print_tag:
print(('v%s.%s.%s-pwsh' % (version.major, version.minor, version.patch)))
elif args.output_dir:
if os.path.exists(args.output_dir):
shutil.rmtree(args.output_dir)
os.makedirs(args.output_dir)
lib_path = os.path.join(OMI_REPO, 'PSWSMan', 'lib')
for distribution in os.listdir(lib_path):
artifact_dir = os.path.join(lib_path, distribution)
artifact_tar = (os.path.join(args.output_dir, distribution) + '.tar.gz')
if (distribution.startswith('.') or (not os.path.isdir(artifact_dir))):
continue
print(("Creating '%s'" % artifact_tar))
with tarfile.open(artifact_tar, 'w:gz') as tar:
for lib_name in os.listdir(artifact_dir):
if (lib_name == '.'):
continue
print(("\tAdding '%s' to tar" % lib_name))
tar.add(os.path.join(artifact_dir, lib_name), arcname=lib_name)
pwsh_command = ("$ErrorActionPreference = 'Stop'\n\n$outputDir = '%s'\n$repoParams = @{\n Name = 'PSWSManRepo'\n SourceLocation = $outputDir\n PublishLocation = $outputDir\n InstallationPolicy = 'Trusted'\n}\nif (Get-PSRepository -Name $repoParams.Name -ErrorAction SilentlyContinue) {\n Unregister-PSRepository -Name $repoParams.Name\n}\nRegister-PSRepository @repoParams\n\ntry {\n Publish-Module -Path ./PSWSMan -Repository $repoParams.Name\n} finally {\n Unregister-PSRepository -Name $repoParams.Name\n}\n" % args.output_dir)
with tempfile.NamedTemporaryFile(mode='w', suffix='.ps1') as temp_fd:
temp_fd.write(pwsh_command)
temp_fd.flush()
print('Creating PSWSMan nupkg')
subprocess.check_call(['pwsh', '-File', temp_fd.name], cwd=OMI_REPO)
nupkg_name = None
for name in os.listdir(args.output_dir):
if name.endswith('.nupkg'):
print(("Published PSWSMan to '%s'" % os.path.join(args.output_dir, name)))<|docstring|>Main program body.<|endoftext|> |
42145a923849def314e7a7d58b19929784b37fb5cc8196ed6a5dfb6cb6f6a9a7 | def parse_args():
'Parse and return args.'
parser = argparse.ArgumentParser(description='Release helpers for the OMI library in PowerShell.')
run_group = parser.add_mutually_exclusive_group()
run_group.add_argument('--print-tag', dest='print_tag', action='store_true', help='Print the tag number for the release.')
run_group.add_argument('--output-dir', dest='output_dir', action='store', help='The directory to create the release artifacts at.')
if argcomplete:
argcomplete.autocomplete(parser)
args = parser.parse_args()
if ((not args.print_tag) and (not args.output_dir)):
parser.error('argument --print-tag or --output-dir must be seet')
return args | Parse and return args. | release.py | parse_args | TheBigBear/omi | 0 | python | def parse_args():
parser = argparse.ArgumentParser(description='Release helpers for the OMI library in PowerShell.')
run_group = parser.add_mutually_exclusive_group()
run_group.add_argument('--print-tag', dest='print_tag', action='store_true', help='Print the tag number for the release.')
run_group.add_argument('--output-dir', dest='output_dir', action='store', help='The directory to create the release artifacts at.')
if argcomplete:
argcomplete.autocomplete(parser)
args = parser.parse_args()
if ((not args.print_tag) and (not args.output_dir)):
parser.error('argument --print-tag or --output-dir must be seet')
return args | def parse_args():
parser = argparse.ArgumentParser(description='Release helpers for the OMI library in PowerShell.')
run_group = parser.add_mutually_exclusive_group()
run_group.add_argument('--print-tag', dest='print_tag', action='store_true', help='Print the tag number for the release.')
run_group.add_argument('--output-dir', dest='output_dir', action='store', help='The directory to create the release artifacts at.')
if argcomplete:
argcomplete.autocomplete(parser)
args = parser.parse_args()
if ((not args.print_tag) and (not args.output_dir)):
parser.error('argument --print-tag or --output-dir must be seet')
return args<|docstring|>Parse and return args.<|endoftext|> |
121eec26ce090f4d7d7025d85f7dd6983bf3a7fcfe53d9e3cd08bb3ee0c7256e | def rivet_paths(file_name):
'Return all :py:mod:`rivet` paths found at file_name.'
from . import yodaplot
return yodaplot.data_object_names(file_name) | Return all :py:mod:`rivet` paths found at file_name. | heppyplotlib/plot.py | rivet_paths | ebothmann/heppyplotlib | 1 | python | def rivet_paths(file_name):
from . import yodaplot
return yodaplot.data_object_names(file_name) | def rivet_paths(file_name):
from . import yodaplot
return yodaplot.data_object_names(file_name)<|docstring|>Return all :py:mod:`rivet` paths found at file_name.<|endoftext|> |
2356454ad902a0246830e348342ae2ad7aa99dd2e6d0625d997855ec0438320b | def gridplot(file_name, uses_rivet_plot_info=True):
'Convenience function to plot all :py:mod:`yoda` data objects\n from a :py:mod:`yoda` file into a subplots grid.\n\n :param str file_name: The path to the :py:mod:`yoda` file.\n :return: fig, axes_list\n '
all_rivet_paths = rivet_paths(file_name)
if (len(all_rivet_paths) == 1):
(fig, axes_list) = plt.subplots()
else:
ncols = 2
nrows = (((len(all_rivet_paths) - 1) / ncols) + 1)
(fig, axes_list) = plt.subplots(nrows, ncols, squeeze=False)
for (rivet_path, axes) in zip(all_rivet_paths, np.ravel(axes_list)):
plt.sca(axes)
plot(file_name, rivet_path, uses_rivet_plot_info=uses_rivet_plot_info)
return (fig, axes_list) | Convenience function to plot all :py:mod:`yoda` data objects
from a :py:mod:`yoda` file into a subplots grid.
:param str file_name: The path to the :py:mod:`yoda` file.
:return: fig, axes_list | heppyplotlib/plot.py | gridplot | ebothmann/heppyplotlib | 1 | python | def gridplot(file_name, uses_rivet_plot_info=True):
'Convenience function to plot all :py:mod:`yoda` data objects\n from a :py:mod:`yoda` file into a subplots grid.\n\n :param str file_name: The path to the :py:mod:`yoda` file.\n :return: fig, axes_list\n '
all_rivet_paths = rivet_paths(file_name)
if (len(all_rivet_paths) == 1):
(fig, axes_list) = plt.subplots()
else:
ncols = 2
nrows = (((len(all_rivet_paths) - 1) / ncols) + 1)
(fig, axes_list) = plt.subplots(nrows, ncols, squeeze=False)
for (rivet_path, axes) in zip(all_rivet_paths, np.ravel(axes_list)):
plt.sca(axes)
plot(file_name, rivet_path, uses_rivet_plot_info=uses_rivet_plot_info)
return (fig, axes_list) | def gridplot(file_name, uses_rivet_plot_info=True):
'Convenience function to plot all :py:mod:`yoda` data objects\n from a :py:mod:`yoda` file into a subplots grid.\n\n :param str file_name: The path to the :py:mod:`yoda` file.\n :return: fig, axes_list\n '
all_rivet_paths = rivet_paths(file_name)
if (len(all_rivet_paths) == 1):
(fig, axes_list) = plt.subplots()
else:
ncols = 2
nrows = (((len(all_rivet_paths) - 1) / ncols) + 1)
(fig, axes_list) = plt.subplots(nrows, ncols, squeeze=False)
for (rivet_path, axes) in zip(all_rivet_paths, np.ravel(axes_list)):
plt.sca(axes)
plot(file_name, rivet_path, uses_rivet_plot_info=uses_rivet_plot_info)
return (fig, axes_list)<|docstring|>Convenience function to plot all :py:mod:`yoda` data objects
from a :py:mod:`yoda` file into a subplots grid.
:param str file_name: The path to the :py:mod:`yoda` file.
:return: fig, axes_list<|endoftext|> |
92b44483597b472c8435308a5201fa9b5bdbe5ac749280c150ba3611a4392647 | def plot(filename_or_data_object, rivet_path, uses_rivet_plot_info=True, errors_enabled=None, **kwargs):
'Plot a :py:mod:`yoda` data object, potentially from a :py:mod:`yoda` file.'
from . import yodaplot
print('Plotting', rivet_path, end='')
if isinstance(filename_or_data_object, str):
print(' from', filename_or_data_object, '...')
else:
print()
if (uses_rivet_plot_info and (errors_enabled is None)):
from . import rivetplot
errors_enabled = rivetplot.errors_enabled(rivet_path)
else:
errors_enabled = (True if (errors_enabled is None) else errors_enabled)
if ('rebin_count' in kwargs):
rebin_count = kwargs['rebin_count']
del kwargs['rebin_count']
elif uses_rivet_plot_info:
from . import rivetplot
rebin_count = rivetplot.rebin_count(rivet_path)
else:
rebin_count = 1
result = yodaplot.plot(filename_or_data_object, rivet_path, errors_enabled=errors_enabled, rebin_count=rebin_count, **kwargs)
if uses_rivet_plot_info:
from . import rivetplot
rivetplot.apply_plot_info(rivet_path)
return result | Plot a :py:mod:`yoda` data object, potentially from a :py:mod:`yoda` file. | heppyplotlib/plot.py | plot | ebothmann/heppyplotlib | 1 | python | def plot(filename_or_data_object, rivet_path, uses_rivet_plot_info=True, errors_enabled=None, **kwargs):
from . import yodaplot
print('Plotting', rivet_path, end=)
if isinstance(filename_or_data_object, str):
print(' from', filename_or_data_object, '...')
else:
print()
if (uses_rivet_plot_info and (errors_enabled is None)):
from . import rivetplot
errors_enabled = rivetplot.errors_enabled(rivet_path)
else:
errors_enabled = (True if (errors_enabled is None) else errors_enabled)
if ('rebin_count' in kwargs):
rebin_count = kwargs['rebin_count']
del kwargs['rebin_count']
elif uses_rivet_plot_info:
from . import rivetplot
rebin_count = rivetplot.rebin_count(rivet_path)
else:
rebin_count = 1
result = yodaplot.plot(filename_or_data_object, rivet_path, errors_enabled=errors_enabled, rebin_count=rebin_count, **kwargs)
if uses_rivet_plot_info:
from . import rivetplot
rivetplot.apply_plot_info(rivet_path)
return result | def plot(filename_or_data_object, rivet_path, uses_rivet_plot_info=True, errors_enabled=None, **kwargs):
from . import yodaplot
print('Plotting', rivet_path, end=)
if isinstance(filename_or_data_object, str):
print(' from', filename_or_data_object, '...')
else:
print()
if (uses_rivet_plot_info and (errors_enabled is None)):
from . import rivetplot
errors_enabled = rivetplot.errors_enabled(rivet_path)
else:
errors_enabled = (True if (errors_enabled is None) else errors_enabled)
if ('rebin_count' in kwargs):
rebin_count = kwargs['rebin_count']
del kwargs['rebin_count']
elif uses_rivet_plot_info:
from . import rivetplot
rebin_count = rivetplot.rebin_count(rivet_path)
else:
rebin_count = 1
result = yodaplot.plot(filename_or_data_object, rivet_path, errors_enabled=errors_enabled, rebin_count=rebin_count, **kwargs)
if uses_rivet_plot_info:
from . import rivetplot
rivetplot.apply_plot_info(rivet_path)
return result<|docstring|>Plot a :py:mod:`yoda` data object, potentially from a :py:mod:`yoda` file.<|endoftext|> |
bf8d278bb40e9a7636a4e8971f0eebd06b04611f1f38fd6986d0be6c475e31d8 | def predictions_vs_true_distribution_plots(y_pred: torch.Tensor, y_true: torch.Tensor, dep_var: str, bins: int=50):
'Plots the predicted and true distributions side by side plus the residuals distribution'
_y_p = y_pred.detach().numpy().ravel()
_y_t = y_true.detach().numpy().ravel()
(fig, axs) = plt.subplots(ncols=2, figsize=(14, 4))
ax = axs[0]
ax.hist(_y_p, bins=bins, alpha=0.5, label='pred')
ax.hist(_y_t, bins=bins, alpha=0.5, label='true')
ax.set_xlabel(f'{dep_var}')
ax.set_title(f"predicted vs true '{dep_var}'")
ax.legend()
ax = axs[1]
ax.hist((_y_p - _y_t), bins=bins)
ax.set_xlabel('Δ')
ax.set_title(f'Δ-distribution: mean = {(_y_p - _y_t).mean():.2f}, std = {np.std((_y_p - _y_t)):.2f}')
plt.show() | Plots the predicted and true distributions side by side plus the residuals distribution | kaggle_house_prices/modelling.py | predictions_vs_true_distribution_plots | eschmidt42/kaggle_house_prices | 0 | python | def predictions_vs_true_distribution_plots(y_pred: torch.Tensor, y_true: torch.Tensor, dep_var: str, bins: int=50):
_y_p = y_pred.detach().numpy().ravel()
_y_t = y_true.detach().numpy().ravel()
(fig, axs) = plt.subplots(ncols=2, figsize=(14, 4))
ax = axs[0]
ax.hist(_y_p, bins=bins, alpha=0.5, label='pred')
ax.hist(_y_t, bins=bins, alpha=0.5, label='true')
ax.set_xlabel(f'{dep_var}')
ax.set_title(f"predicted vs true '{dep_var}'")
ax.legend()
ax = axs[1]
ax.hist((_y_p - _y_t), bins=bins)
ax.set_xlabel('Δ')
ax.set_title(f'Δ-distribution: mean = {(_y_p - _y_t).mean():.2f}, std = {np.std((_y_p - _y_t)):.2f}')
plt.show() | def predictions_vs_true_distribution_plots(y_pred: torch.Tensor, y_true: torch.Tensor, dep_var: str, bins: int=50):
_y_p = y_pred.detach().numpy().ravel()
_y_t = y_true.detach().numpy().ravel()
(fig, axs) = plt.subplots(ncols=2, figsize=(14, 4))
ax = axs[0]
ax.hist(_y_p, bins=bins, alpha=0.5, label='pred')
ax.hist(_y_t, bins=bins, alpha=0.5, label='true')
ax.set_xlabel(f'{dep_var}')
ax.set_title(f"predicted vs true '{dep_var}'")
ax.legend()
ax = axs[1]
ax.hist((_y_p - _y_t), bins=bins)
ax.set_xlabel('Δ')
ax.set_title(f'Δ-distribution: mean = {(_y_p - _y_t).mean():.2f}, std = {np.std((_y_p - _y_t)):.2f}')
plt.show()<|docstring|>Plots the predicted and true distributions side by side plus the residuals distribution<|endoftext|> |
0dfe187f387b81c47655ee67d3bb59416df10a14fc6c7c9ad2a4ecef0ba509eb | def draw(self, replace=True):
'Draw uniformly between existing (non-empty) cells'
try:
idx = random.randint(0, (len(self._nonempty_cells) - 1))
except ValueError:
raise ValueError("can't draw from an empty meshgrid")
(e, md) = self._nonempty_cells[idx].draw(replace=replace)
if ((not replace) and (len(self._nonempty_cells[idx]) == 0)):
self._nonempty_cells.pop(idx)
return (e, md) | Draw uniformly between existing (non-empty) cells | toolbox/meshgrid.py | draw | afcarl/toolbox | 1 | python | def draw(self, replace=True):
try:
idx = random.randint(0, (len(self._nonempty_cells) - 1))
except ValueError:
raise ValueError("can't draw from an empty meshgrid")
(e, md) = self._nonempty_cells[idx].draw(replace=replace)
if ((not replace) and (len(self._nonempty_cells[idx]) == 0)):
self._nonempty_cells.pop(idx)
return (e, md) | def draw(self, replace=True):
try:
idx = random.randint(0, (len(self._nonempty_cells) - 1))
except ValueError:
raise ValueError("can't draw from an empty meshgrid")
(e, md) = self._nonempty_cells[idx].draw(replace=replace)
if ((not replace) and (len(self._nonempty_cells[idx]) == 0)):
self._nonempty_cells.pop(idx)
return (e, md)<|docstring|>Draw uniformly between existing (non-empty) cells<|endoftext|> |
93613def7b77bc8cfeadd571b19f3dbfec4cdae2e8159bdb8636b4cbb358af41 | def __request(self, api, **kwargs):
'\n Request to YouTube v3 API\n\n :param api: what to put after "googleapis.com/youtube/v3/"\n :param kwargs: request parameters, API-dependent\n :return: Content of the response, should be a JSON\n '
r = requests.get('https://www.googleapis.com/youtube/v3/{}'.format(api), {'key': YT_API_KEY, **kwargs}).json()
print(r)
return r | Request to YouTube v3 API
:param api: what to put after "googleapis.com/youtube/v3/"
:param kwargs: request parameters, API-dependent
:return: Content of the response, should be a JSON | hackathon_a11y/youtube_controller.py | __request | PaziewskiCezary/hackathon_a11y | 0 | python | def __request(self, api, **kwargs):
'\n Request to YouTube v3 API\n\n :param api: what to put after "googleapis.com/youtube/v3/"\n :param kwargs: request parameters, API-dependent\n :return: Content of the response, should be a JSON\n '
r = requests.get('https://www.googleapis.com/youtube/v3/{}'.format(api), {'key': YT_API_KEY, **kwargs}).json()
print(r)
return r | def __request(self, api, **kwargs):
'\n Request to YouTube v3 API\n\n :param api: what to put after "googleapis.com/youtube/v3/"\n :param kwargs: request parameters, API-dependent\n :return: Content of the response, should be a JSON\n '
r = requests.get('https://www.googleapis.com/youtube/v3/{}'.format(api), {'key': YT_API_KEY, **kwargs}).json()
print(r)
return r<|docstring|>Request to YouTube v3 API
:param api: what to put after "googleapis.com/youtube/v3/"
:param kwargs: request parameters, API-dependent
:return: Content of the response, should be a JSON<|endoftext|> |
e6b5c2758ee25e4bee123cbb91304310b8b6004a595a7c22481d5e3b13d1e816 | def search(self, phrase, max_results=5):
'\n Requests search results of `phrase`\n\n :param phrase: str\n :param max_results: optional, default: 25\n :return: Dictionary\n "items" key contains a list of dictionaries representing the results\n there "id"["videoId"] contains the video or playlist id\n '
return self.__request('search', part='snippet', q=phrase, type='video', max_results='{}'.format(max_results)) | Requests search results of `phrase`
:param phrase: str
:param max_results: optional, default: 25
:return: Dictionary
"items" key contains a list of dictionaries representing the results
there "id"["videoId"] contains the video or playlist id | hackathon_a11y/youtube_controller.py | search | PaziewskiCezary/hackathon_a11y | 0 | python | def search(self, phrase, max_results=5):
'\n Requests search results of `phrase`\n\n :param phrase: str\n :param max_results: optional, default: 25\n :return: Dictionary\n "items" key contains a list of dictionaries representing the results\n there "id"["videoId"] contains the video or playlist id\n '
return self.__request('search', part='snippet', q=phrase, type='video', max_results='{}'.format(max_results)) | def search(self, phrase, max_results=5):
'\n Requests search results of `phrase`\n\n :param phrase: str\n :param max_results: optional, default: 25\n :return: Dictionary\n "items" key contains a list of dictionaries representing the results\n there "id"["videoId"] contains the video or playlist id\n '
return self.__request('search', part='snippet', q=phrase, type='video', max_results='{}'.format(max_results))<|docstring|>Requests search results of `phrase`
:param phrase: str
:param max_results: optional, default: 25
:return: Dictionary
"items" key contains a list of dictionaries representing the results
there "id"["videoId"] contains the video or playlist id<|endoftext|> |
966ec51f3285349ce9c60c4bcad1eb8590a96121aed5108cb164a08b3976ce7b | @tf.function(input_signature=[tf.TensorSpec(shape=[None, DNN_PARAMS['in_img_width'], DNN_PARAMS['in_img_width'], 2], dtype=DNN_PARAMS['custom_dtype']._variable_dtype)])
def sobel_edges_tfpad(image):
'Returns a tensor holding Sobel edge maps.\n Note: image is CONSTANT(0) padded instead of REFLECT padded.\n Arguments:\n image: Image tensor with shape [batch_size, h, w, d] and type float32 or\n float64. The image(s) must be 2x2 or larger.\n Returns:\n Tensor holding edge maps for each channel. Returns a tensor with shape\n [batch_size, h, w, d, 2] where the last two dimensions hold [[dy[0], dx[0]],\n [dy[1], dx[1]], ..., [dy[d-1], dx[d-1]]] calculated using the Sobel filter.\n '
static_image_shape = image.get_shape()
image_shape = array_ops.shape(image)
num_kernels = 2
sobel_kn = tf.constant([[[(- 1), (- 2), (- 1)], [0, 0, 0], [1, 2, 1]], [[(- 1), 0, 1], [(- 2), 0, 2], [(- 1), 0, 1]]], dtype=tf.float32)
kernels_tf = tf.expand_dims(tf.transpose(sobel_kn, perm=(1, 2, 0)), axis=(- 2))
kernels_tf = array_ops.tile(kernels_tf, [1, 1, image_shape[(- 1)], 1], name='sobel_filters')
pad_sizes = tf.constant([[0, 0], [1, 1], [1, 1], [0, 0]], dtype=tf.int32)
padded = tf.pad(tensor=image, paddings=pad_sizes, mode='CONSTANT')
strides = [1, 1, 1, 1]
output = nn.depthwise_conv2d(padded, kernels_tf, strides, 'VALID')
shape = array_ops.concat([image_shape, [num_kernels]], 0)
output = array_ops.reshape(output, shape=shape)
output.set_shape(static_image_shape.concatenate([num_kernels]))
return output | Returns a tensor holding Sobel edge maps.
Note: image is CONSTANT(0) padded instead of REFLECT padded.
Arguments:
image: Image tensor with shape [batch_size, h, w, d] and type float32 or
float64. The image(s) must be 2x2 or larger.
Returns:
Tensor holding edge maps for each channel. Returns a tensor with shape
[batch_size, h, w, d, 2] where the last two dimensions hold [[dy[0], dx[0]],
[dy[1], dx[1]], ..., [dy[d-1], dx[d-1]]] calculated using the Sobel filter. | trainer/utils/tf_utility.py | sobel_edges_tfpad | maosi-chen/sapc2 | 1 | python | @tf.function(input_signature=[tf.TensorSpec(shape=[None, DNN_PARAMS['in_img_width'], DNN_PARAMS['in_img_width'], 2], dtype=DNN_PARAMS['custom_dtype']._variable_dtype)])
def sobel_edges_tfpad(image):
'Returns a tensor holding Sobel edge maps.\n Note: image is CONSTANT(0) padded instead of REFLECT padded.\n Arguments:\n image: Image tensor with shape [batch_size, h, w, d] and type float32 or\n float64. The image(s) must be 2x2 or larger.\n Returns:\n Tensor holding edge maps for each channel. Returns a tensor with shape\n [batch_size, h, w, d, 2] where the last two dimensions hold [[dy[0], dx[0]],\n [dy[1], dx[1]], ..., [dy[d-1], dx[d-1]]] calculated using the Sobel filter.\n '
static_image_shape = image.get_shape()
image_shape = array_ops.shape(image)
num_kernels = 2
sobel_kn = tf.constant([[[(- 1), (- 2), (- 1)], [0, 0, 0], [1, 2, 1]], [[(- 1), 0, 1], [(- 2), 0, 2], [(- 1), 0, 1]]], dtype=tf.float32)
kernels_tf = tf.expand_dims(tf.transpose(sobel_kn, perm=(1, 2, 0)), axis=(- 2))
kernels_tf = array_ops.tile(kernels_tf, [1, 1, image_shape[(- 1)], 1], name='sobel_filters')
pad_sizes = tf.constant([[0, 0], [1, 1], [1, 1], [0, 0]], dtype=tf.int32)
padded = tf.pad(tensor=image, paddings=pad_sizes, mode='CONSTANT')
strides = [1, 1, 1, 1]
output = nn.depthwise_conv2d(padded, kernels_tf, strides, 'VALID')
shape = array_ops.concat([image_shape, [num_kernels]], 0)
output = array_ops.reshape(output, shape=shape)
output.set_shape(static_image_shape.concatenate([num_kernels]))
return output | @tf.function(input_signature=[tf.TensorSpec(shape=[None, DNN_PARAMS['in_img_width'], DNN_PARAMS['in_img_width'], 2], dtype=DNN_PARAMS['custom_dtype']._variable_dtype)])
def sobel_edges_tfpad(image):
'Returns a tensor holding Sobel edge maps.\n Note: image is CONSTANT(0) padded instead of REFLECT padded.\n Arguments:\n image: Image tensor with shape [batch_size, h, w, d] and type float32 or\n float64. The image(s) must be 2x2 or larger.\n Returns:\n Tensor holding edge maps for each channel. Returns a tensor with shape\n [batch_size, h, w, d, 2] where the last two dimensions hold [[dy[0], dx[0]],\n [dy[1], dx[1]], ..., [dy[d-1], dx[d-1]]] calculated using the Sobel filter.\n '
static_image_shape = image.get_shape()
image_shape = array_ops.shape(image)
num_kernels = 2
sobel_kn = tf.constant([[[(- 1), (- 2), (- 1)], [0, 0, 0], [1, 2, 1]], [[(- 1), 0, 1], [(- 2), 0, 2], [(- 1), 0, 1]]], dtype=tf.float32)
kernels_tf = tf.expand_dims(tf.transpose(sobel_kn, perm=(1, 2, 0)), axis=(- 2))
kernels_tf = array_ops.tile(kernels_tf, [1, 1, image_shape[(- 1)], 1], name='sobel_filters')
pad_sizes = tf.constant([[0, 0], [1, 1], [1, 1], [0, 0]], dtype=tf.int32)
padded = tf.pad(tensor=image, paddings=pad_sizes, mode='CONSTANT')
strides = [1, 1, 1, 1]
output = nn.depthwise_conv2d(padded, kernels_tf, strides, 'VALID')
shape = array_ops.concat([image_shape, [num_kernels]], 0)
output = array_ops.reshape(output, shape=shape)
output.set_shape(static_image_shape.concatenate([num_kernels]))
return output<|docstring|>Returns a tensor holding Sobel edge maps.
Note: image is CONSTANT(0) padded instead of REFLECT padded.
Arguments:
image: Image tensor with shape [batch_size, h, w, d] and type float32 or
float64. The image(s) must be 2x2 or larger.
Returns:
Tensor holding edge maps for each channel. Returns a tensor with shape
[batch_size, h, w, d, 2] where the last two dimensions hold [[dy[0], dx[0]],
[dy[1], dx[1]], ..., [dy[d-1], dx[d-1]]] calculated using the Sobel filter.<|endoftext|> |
44e352bd53e42c92b19c8b6ada4b1cfbb389e0d668d00cea1eeb9cb5ac84769e | @pytest.fixture(autouse=True)
def helper_lock():
'Lock around anything using the helper module.'
with HELPER_LOCK:
(yield) | Lock around anything using the helper module. | tests/test_helpers.py | helper_lock | pganssle/pytz-deprecation-shim | 6 | python | @pytest.fixture(autouse=True)
def helper_lock():
with HELPER_LOCK:
(yield) | @pytest.fixture(autouse=True)
def helper_lock():
with HELPER_LOCK:
(yield)<|docstring|>Lock around anything using the helper module.<|endoftext|> |
e15a37c5402faae74b5d355e223959280115f579e81dc1f066c33f2d8b6a9b3b | @pytest.fixture
def no_pytz():
'Fixture to remove pytz from sys.modules for the duration of the test.'
with SYS_MODULES_LOCK:
pds._common._PYTZ_IMPORTED = False
base_classes = pds_helpers._PYTZ_BASE_CLASSES
pds_helpers._PYTZ_BASE_CLASSES = None
pytz_modules = {}
for modname in list(sys.modules):
if (modname.split('.', 1)[0] != 'pytz'):
continue
pytz_modules[modname] = sys.modules.pop(modname)
try:
(yield)
finally:
sys.modules.update(pytz_modules)
pds_helpers._PYTZ_BASE_CLASSES = base_classes | Fixture to remove pytz from sys.modules for the duration of the test. | tests/test_helpers.py | no_pytz | pganssle/pytz-deprecation-shim | 6 | python | @pytest.fixture
def no_pytz():
with SYS_MODULES_LOCK:
pds._common._PYTZ_IMPORTED = False
base_classes = pds_helpers._PYTZ_BASE_CLASSES
pds_helpers._PYTZ_BASE_CLASSES = None
pytz_modules = {}
for modname in list(sys.modules):
if (modname.split('.', 1)[0] != 'pytz'):
continue
pytz_modules[modname] = sys.modules.pop(modname)
try:
(yield)
finally:
sys.modules.update(pytz_modules)
pds_helpers._PYTZ_BASE_CLASSES = base_classes | @pytest.fixture
def no_pytz():
with SYS_MODULES_LOCK:
pds._common._PYTZ_IMPORTED = False
base_classes = pds_helpers._PYTZ_BASE_CLASSES
pds_helpers._PYTZ_BASE_CLASSES = None
pytz_modules = {}
for modname in list(sys.modules):
if (modname.split('.', 1)[0] != 'pytz'):
continue
pytz_modules[modname] = sys.modules.pop(modname)
try:
(yield)
finally:
sys.modules.update(pytz_modules)
pds_helpers._PYTZ_BASE_CLASSES = base_classes<|docstring|>Fixture to remove pytz from sys.modules for the duration of the test.<|endoftext|> |
25503055a6abbd7e68b7c56c22eaf3e97eef0f82aaa7ed549f94ce105349f5c8 | @pytest.mark.parametrize('tz', NON_PYTZ_ZONES)
def test_not_pytz_zones(tz):
'Tests is_pytz_zone for non-pytz zones.'
assert (not pds_helpers.is_pytz_zone(tz)) | Tests is_pytz_zone for non-pytz zones. | tests/test_helpers.py | test_not_pytz_zones | pganssle/pytz-deprecation-shim | 6 | python | @pytest.mark.parametrize('tz', NON_PYTZ_ZONES)
def test_not_pytz_zones(tz):
assert (not pds_helpers.is_pytz_zone(tz)) | @pytest.mark.parametrize('tz', NON_PYTZ_ZONES)
def test_not_pytz_zones(tz):
assert (not pds_helpers.is_pytz_zone(tz))<|docstring|>Tests is_pytz_zone for non-pytz zones.<|endoftext|> |
07ed856366dfc38f54ee7cd9d0cb91509b11d7e4377add9ac77ddbae1bbfa729 | @pytest.mark.parametrize('tz', NON_PYTZ_ZONES)
def test_not_pytz_no_pytz(tz, no_pytz):
'Tests is_pytz_zone when pytz has not been imported.'
assert (not pds_helpers.is_pytz_zone(tz))
assert ('pytz' not in sys.modules) | Tests is_pytz_zone when pytz has not been imported. | tests/test_helpers.py | test_not_pytz_no_pytz | pganssle/pytz-deprecation-shim | 6 | python | @pytest.mark.parametrize('tz', NON_PYTZ_ZONES)
def test_not_pytz_no_pytz(tz, no_pytz):
assert (not pds_helpers.is_pytz_zone(tz))
assert ('pytz' not in sys.modules) | @pytest.mark.parametrize('tz', NON_PYTZ_ZONES)
def test_not_pytz_no_pytz(tz, no_pytz):
assert (not pds_helpers.is_pytz_zone(tz))
assert ('pytz' not in sys.modules)<|docstring|>Tests is_pytz_zone when pytz has not been imported.<|endoftext|> |
e0ee4775bbee7baa3c3973206564bbd14227335ff4bd7297451691b54c6e14f8 | @pytest.mark.parametrize('key', (('UTC',) + ZONE_LIST))
def test_pytz_zones_before_after(key, no_pytz):
"Tests is_pytz_zone when pytz is imported after first use.\n\n We want to make sure that is_pytz_zone doesn't inappropriately cache the\n fact that pytz hasn't been imported, and just always return ``False``, even\n if pytz is imported after the first call to is_pytz_zone.\n "
non_pytz_zone = pds.timezone(key)
assert (not pds_helpers.is_pytz_zone(non_pytz_zone))
assert ('pytz' not in sys.modules)
import pytz
pytz_zone = pytz.timezone(key)
assert pds_helpers.is_pytz_zone(pytz_zone) | Tests is_pytz_zone when pytz is imported after first use.
We want to make sure that is_pytz_zone doesn't inappropriately cache the
fact that pytz hasn't been imported, and just always return ``False``, even
if pytz is imported after the first call to is_pytz_zone. | tests/test_helpers.py | test_pytz_zones_before_after | pganssle/pytz-deprecation-shim | 6 | python | @pytest.mark.parametrize('key', (('UTC',) + ZONE_LIST))
def test_pytz_zones_before_after(key, no_pytz):
"Tests is_pytz_zone when pytz is imported after first use.\n\n We want to make sure that is_pytz_zone doesn't inappropriately cache the\n fact that pytz hasn't been imported, and just always return ``False``, even\n if pytz is imported after the first call to is_pytz_zone.\n "
non_pytz_zone = pds.timezone(key)
assert (not pds_helpers.is_pytz_zone(non_pytz_zone))
assert ('pytz' not in sys.modules)
import pytz
pytz_zone = pytz.timezone(key)
assert pds_helpers.is_pytz_zone(pytz_zone) | @pytest.mark.parametrize('key', (('UTC',) + ZONE_LIST))
def test_pytz_zones_before_after(key, no_pytz):
"Tests is_pytz_zone when pytz is imported after first use.\n\n We want to make sure that is_pytz_zone doesn't inappropriately cache the\n fact that pytz hasn't been imported, and just always return ``False``, even\n if pytz is imported after the first call to is_pytz_zone.\n "
non_pytz_zone = pds.timezone(key)
assert (not pds_helpers.is_pytz_zone(non_pytz_zone))
assert ('pytz' not in sys.modules)
import pytz
pytz_zone = pytz.timezone(key)
assert pds_helpers.is_pytz_zone(pytz_zone)<|docstring|>Tests is_pytz_zone when pytz is imported after first use.
We want to make sure that is_pytz_zone doesn't inappropriately cache the
fact that pytz hasn't been imported, and just always return ``False``, even
if pytz is imported after the first call to is_pytz_zone.<|endoftext|> |
25a3194e9d2923666033bd707b3eb57e9a22e3c43020ff361350570275b0a1be | @pytest.mark.parametrize('utc', (pds.UTC, pytz.UTC))
def test_upgrade_utc(utc):
'Tests that upgrade_zone called on UTC objects returns _compat.UTC.\n\n This is relevant because tz.gettz("UTC") or zoneinfo.ZoneInfo("UTC") may\n each return a tzfile-based zone, not their respective UTC singletons.\n '
actual = pds_helpers.upgrade_tzinfo(utc)
assert (actual is UTC) | Tests that upgrade_zone called on UTC objects returns _compat.UTC.
This is relevant because tz.gettz("UTC") or zoneinfo.ZoneInfo("UTC") may
each return a tzfile-based zone, not their respective UTC singletons. | tests/test_helpers.py | test_upgrade_utc | pganssle/pytz-deprecation-shim | 6 | python | @pytest.mark.parametrize('utc', (pds.UTC, pytz.UTC))
def test_upgrade_utc(utc):
'Tests that upgrade_zone called on UTC objects returns _compat.UTC.\n\n This is relevant because tz.gettz("UTC") or zoneinfo.ZoneInfo("UTC") may\n each return a tzfile-based zone, not their respective UTC singletons.\n '
actual = pds_helpers.upgrade_tzinfo(utc)
assert (actual is UTC) | @pytest.mark.parametrize('utc', (pds.UTC, pytz.UTC))
def test_upgrade_utc(utc):
'Tests that upgrade_zone called on UTC objects returns _compat.UTC.\n\n This is relevant because tz.gettz("UTC") or zoneinfo.ZoneInfo("UTC") may\n each return a tzfile-based zone, not their respective UTC singletons.\n '
actual = pds_helpers.upgrade_tzinfo(utc)
assert (actual is UTC)<|docstring|>Tests that upgrade_zone called on UTC objects returns _compat.UTC.
This is relevant because tz.gettz("UTC") or zoneinfo.ZoneInfo("UTC") may
each return a tzfile-based zone, not their respective UTC singletons.<|endoftext|> |
07d1e9b101d097ba416a1030b222ccb99666f3863175bca4709532d11c1ee551 | @pytest.mark.parametrize('tz', (([UTC] + list(map(get_timezone, ZONE_LIST))) + list(map(get_fixed_timezone, OFFSET_MINUTES_LIST))))
def test_upgrade_tz_noop(tz):
'Tests that non-shim, non-pytz zones are unaffected by upgrade_tzinfo.'
actual = pds_helpers.upgrade_tzinfo(tz)
assert (actual is tz) | Tests that non-shim, non-pytz zones are unaffected by upgrade_tzinfo. | tests/test_helpers.py | test_upgrade_tz_noop | pganssle/pytz-deprecation-shim | 6 | python | @pytest.mark.parametrize('tz', (([UTC] + list(map(get_timezone, ZONE_LIST))) + list(map(get_fixed_timezone, OFFSET_MINUTES_LIST))))
def test_upgrade_tz_noop(tz):
actual = pds_helpers.upgrade_tzinfo(tz)
assert (actual is tz) | @pytest.mark.parametrize('tz', (([UTC] + list(map(get_timezone, ZONE_LIST))) + list(map(get_fixed_timezone, OFFSET_MINUTES_LIST))))
def test_upgrade_tz_noop(tz):
actual = pds_helpers.upgrade_tzinfo(tz)
assert (actual is tz)<|docstring|>Tests that non-shim, non-pytz zones are unaffected by upgrade_tzinfo.<|endoftext|> |
ac74eb6bea96e6c586b6d6085fe48b49e5bc507020a3d97b70aa840a8ab17565 | def assert_close(test_case, expected, actual, name):
'Raise an exception if expected does not equal actual.\n\n Equality is checked "approximately".\n\n Parameters\n ----------\n test_case : unittest.TestCase\n The test case to raise an assertion on.\n expected : list or ndarray\n The expected value.\n actual : ndarray\n The actual value.\n name : string\n The name of the value for use in the failure message.\n '
expected = np.array(expected)
if np.allclose(expected, actual):
return
msg = ('expected %s = %s, got %s' % (name, expected, actual))
raise test_case.failureException(msg) | Raise an exception if expected does not equal actual.
Equality is checked "approximately".
Parameters
----------
test_case : unittest.TestCase
The test case to raise an assertion on.
expected : list or ndarray
The expected value.
actual : ndarray
The actual value.
name : string
The name of the value for use in the failure message. | climbing_ratings/tests/assertions.py | assert_close | scottwedge/climbing_ratings | 0 | python | def assert_close(test_case, expected, actual, name):
'Raise an exception if expected does not equal actual.\n\n Equality is checked "approximately".\n\n Parameters\n ----------\n test_case : unittest.TestCase\n The test case to raise an assertion on.\n expected : list or ndarray\n The expected value.\n actual : ndarray\n The actual value.\n name : string\n The name of the value for use in the failure message.\n '
expected = np.array(expected)
if np.allclose(expected, actual):
return
msg = ('expected %s = %s, got %s' % (name, expected, actual))
raise test_case.failureException(msg) | def assert_close(test_case, expected, actual, name):
'Raise an exception if expected does not equal actual.\n\n Equality is checked "approximately".\n\n Parameters\n ----------\n test_case : unittest.TestCase\n The test case to raise an assertion on.\n expected : list or ndarray\n The expected value.\n actual : ndarray\n The actual value.\n name : string\n The name of the value for use in the failure message.\n '
expected = np.array(expected)
if np.allclose(expected, actual):
return
msg = ('expected %s = %s, got %s' % (name, expected, actual))
raise test_case.failureException(msg)<|docstring|>Raise an exception if expected does not equal actual.
Equality is checked "approximately".
Parameters
----------
test_case : unittest.TestCase
The test case to raise an assertion on.
expected : list or ndarray
The expected value.
actual : ndarray
The actual value.
name : string
The name of the value for use in the failure message.<|endoftext|> |
db1d6a7cce9cdb518f652e5e1f07b2d39dfb85e7eaa44fff3b305e77f52031a2 | def detail_url(aquarium_id):
'Return he aquarium detail URL\n - INPUT = Aquarium ID int\n '
return reverse('aquarium:aquarium-detail', args=(aquarium_id,)) | Return he aquarium detail URL
- INPUT = Aquarium ID int | aqua_track/aquarium/tests/test_aquarium_api.py | detail_url | nick-rc/aqua_track | 0 | python | def detail_url(aquarium_id):
'Return he aquarium detail URL\n - INPUT = Aquarium ID int\n '
return reverse('aquarium:aquarium-detail', args=(aquarium_id,)) | def detail_url(aquarium_id):
'Return he aquarium detail URL\n - INPUT = Aquarium ID int\n '
return reverse('aquarium:aquarium-detail', args=(aquarium_id,))<|docstring|>Return he aquarium detail URL
- INPUT = Aquarium ID int<|endoftext|> |
91f56d9d97cfc97f62e25d6ad5a0ff37e73c50ef47b4b261edfe6ba346148fdc | def sample_aquarium(user, **params):
'Create a sample aquarium for testing'
defaults = {'name': 'My 40gal Breeder', 'water_type': 'Fresh', 'volume_liter': 151}
defaults.update(params)
return Aquarium.objects.create(user=user, **defaults) | Create a sample aquarium for testing | aqua_track/aquarium/tests/test_aquarium_api.py | sample_aquarium | nick-rc/aqua_track | 0 | python | def sample_aquarium(user, **params):
defaults = {'name': 'My 40gal Breeder', 'water_type': 'Fresh', 'volume_liter': 151}
defaults.update(params)
return Aquarium.objects.create(user=user, **defaults) | def sample_aquarium(user, **params):
defaults = {'name': 'My 40gal Breeder', 'water_type': 'Fresh', 'volume_liter': 151}
defaults.update(params)
return Aquarium.objects.create(user=user, **defaults)<|docstring|>Create a sample aquarium for testing<|endoftext|> |
079ac61656374c601069ac2d2d6775c276ea27b220f7bf5b2ac30b5b30916bbc | def test_auth_required(self):
'Test to make sure authentication is required'
print('Test Auth Requred')
res = self.client.get(AQUARIUM_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | Test to make sure authentication is required | aqua_track/aquarium/tests/test_aquarium_api.py | test_auth_required | nick-rc/aqua_track | 0 | python | def test_auth_required(self):
print('Test Auth Requred')
res = self.client.get(AQUARIUM_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) | def test_auth_required(self):
print('Test Auth Requred')
res = self.client.get(AQUARIUM_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)<|docstring|>Test to make sure authentication is required<|endoftext|> |
8064d05938ee39534b9d04d437be67f70dc423cf7b46fe8577f3560b9e4870db | def test_retrieve_aquariums(self):
'Test getting a list of the aquariums available ot the user.'
sample_aquarium(user=self.user)
sample_aquarium(user=self.user)
res = self.client.get(AQUARIUM_URL)
aquariums = Aquarium.objects.all().order_by('-id')
serializer = AquariumSerializer(aquariums, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data) | Test getting a list of the aquariums available ot the user. | aqua_track/aquarium/tests/test_aquarium_api.py | test_retrieve_aquariums | nick-rc/aqua_track | 0 | python | def test_retrieve_aquariums(self):
sample_aquarium(user=self.user)
sample_aquarium(user=self.user)
res = self.client.get(AQUARIUM_URL)
aquariums = Aquarium.objects.all().order_by('-id')
serializer = AquariumSerializer(aquariums, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data) | def test_retrieve_aquariums(self):
sample_aquarium(user=self.user)
sample_aquarium(user=self.user)
res = self.client.get(AQUARIUM_URL)
aquariums = Aquarium.objects.all().order_by('-id')
serializer = AquariumSerializer(aquariums, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)<|docstring|>Test getting a list of the aquariums available ot the user.<|endoftext|> |
716a7e971c26d98b2c013e8733c5acc3b42472be743eda793b2e3cdd54bdf134 | def test_recipes_limited_to_user(self):
'Make sure user can only see their own recipes.'
user2 = get_user_model().objects.create_user('example@example.com', 'passsss')
sample_aquarium(user=user2)
sample_aquarium(user=self.user)
res = self.client.get(AQUARIUM_URL)
aquariums = Aquarium.objects.filter(user=self.user)
serializer = AquariumSerializer(aquariums, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data, serializer.data) | Make sure user can only see their own recipes. | aqua_track/aquarium/tests/test_aquarium_api.py | test_recipes_limited_to_user | nick-rc/aqua_track | 0 | python | def test_recipes_limited_to_user(self):
user2 = get_user_model().objects.create_user('example@example.com', 'passsss')
sample_aquarium(user=user2)
sample_aquarium(user=self.user)
res = self.client.get(AQUARIUM_URL)
aquariums = Aquarium.objects.filter(user=self.user)
serializer = AquariumSerializer(aquariums, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data, serializer.data) | def test_recipes_limited_to_user(self):
user2 = get_user_model().objects.create_user('example@example.com', 'passsss')
sample_aquarium(user=user2)
sample_aquarium(user=self.user)
res = self.client.get(AQUARIUM_URL)
aquariums = Aquarium.objects.filter(user=self.user)
serializer = AquariumSerializer(aquariums, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data, serializer.data)<|docstring|>Make sure user can only see their own recipes.<|endoftext|> |
dd32340435633daf4ffbe365110e9174058eb5e2dc3f361e9d917736c1c48ff6 | def test_view_aquarium_detail(self):
'Testing viewing the aquarium detail page.'
aquarium = sample_aquarium(user=self.user)
url = detail_url(aquarium.id)
res = self.client.get(url)
serializer = AquariumSerializer(aquarium)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data) | Testing viewing the aquarium detail page. | aqua_track/aquarium/tests/test_aquarium_api.py | test_view_aquarium_detail | nick-rc/aqua_track | 0 | python | def test_view_aquarium_detail(self):
aquarium = sample_aquarium(user=self.user)
url = detail_url(aquarium.id)
res = self.client.get(url)
serializer = AquariumSerializer(aquarium)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data) | def test_view_aquarium_detail(self):
aquarium = sample_aquarium(user=self.user)
url = detail_url(aquarium.id)
res = self.client.get(url)
serializer = AquariumSerializer(aquarium)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)<|docstring|>Testing viewing the aquarium detail page.<|endoftext|> |
3357fa39aa0ae2bde4bb997f5845adbef7c30a53c6849d9cc0f03c039235640e | def test_create_aquarium_basic(self):
'Test creating an aquarium with the basic details'
payload = {'name': 'My Sample Aq', 'water_type': 'Freshish', 'volume_liter': 50.0}
defaults_payload = {'length_cm': 0, 'width_cm': 0, 'height_cm': 0, 'description': 'My aquarium description.', 'is_planted': False}
payload.update(defaults_payload)
res = self.client.post(AQUARIUM_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
aquarium = Aquarium.objects.get(id=res.data['id'])
for key in payload.keys():
self.assertEqual(payload[key], getattr(aquarium, key)) | Test creating an aquarium with the basic details | aqua_track/aquarium/tests/test_aquarium_api.py | test_create_aquarium_basic | nick-rc/aqua_track | 0 | python | def test_create_aquarium_basic(self):
payload = {'name': 'My Sample Aq', 'water_type': 'Freshish', 'volume_liter': 50.0}
defaults_payload = {'length_cm': 0, 'width_cm': 0, 'height_cm': 0, 'description': 'My aquarium description.', 'is_planted': False}
payload.update(defaults_payload)
res = self.client.post(AQUARIUM_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
aquarium = Aquarium.objects.get(id=res.data['id'])
for key in payload.keys():
self.assertEqual(payload[key], getattr(aquarium, key)) | def test_create_aquarium_basic(self):
payload = {'name': 'My Sample Aq', 'water_type': 'Freshish', 'volume_liter': 50.0}
defaults_payload = {'length_cm': 0, 'width_cm': 0, 'height_cm': 0, 'description': 'My aquarium description.', 'is_planted': False}
payload.update(defaults_payload)
res = self.client.post(AQUARIUM_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
aquarium = Aquarium.objects.get(id=res.data['id'])
for key in payload.keys():
self.assertEqual(payload[key], getattr(aquarium, key))<|docstring|>Test creating an aquarium with the basic details<|endoftext|> |
22f23b8d79028f37213425f8e0597575479747516b5205550bda04d8dcf9d864 | def test_create_aquarium_detailed(self):
'Test creating an aquarium with the basic details'
payload = {'name': 'My Sample Aq', 'water_type': 'Freshish', 'volume_liter': 50.0, 'length_cm': 200, 'width_cm': 50, 'height_cm': 25, 'description': 'A luxurious aquatic experience.', 'is_planted': True}
res = self.client.post(AQUARIUM_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
aquarium = Aquarium.objects.get(id=res.data['id'])
for key in payload.keys():
self.assertEqual(payload[key], getattr(aquarium, key)) | Test creating an aquarium with the basic details | aqua_track/aquarium/tests/test_aquarium_api.py | test_create_aquarium_detailed | nick-rc/aqua_track | 0 | python | def test_create_aquarium_detailed(self):
payload = {'name': 'My Sample Aq', 'water_type': 'Freshish', 'volume_liter': 50.0, 'length_cm': 200, 'width_cm': 50, 'height_cm': 25, 'description': 'A luxurious aquatic experience.', 'is_planted': True}
res = self.client.post(AQUARIUM_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
aquarium = Aquarium.objects.get(id=res.data['id'])
for key in payload.keys():
self.assertEqual(payload[key], getattr(aquarium, key)) | def test_create_aquarium_detailed(self):
payload = {'name': 'My Sample Aq', 'water_type': 'Freshish', 'volume_liter': 50.0, 'length_cm': 200, 'width_cm': 50, 'height_cm': 25, 'description': 'A luxurious aquatic experience.', 'is_planted': True}
res = self.client.post(AQUARIUM_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
aquarium = Aquarium.objects.get(id=res.data['id'])
for key in payload.keys():
self.assertEqual(payload[key], getattr(aquarium, key))<|docstring|>Test creating an aquarium with the basic details<|endoftext|> |
2107410ee7fea0d3b282cec75a93193248d90b76f986a20005cf7dbeaa28d40b | def test_basic_aquarium_update(self):
'Test changing the values of aquarium data'
aquarium = sample_aquarium(user=self.user)
payload = {'name': 'New Aq Name', 'water_type': 'Salty', 'volume_liter': 1}
url = detail_url(aquarium.id)
self.client.put(url, payload)
aquarium.refresh_from_db()
self.assertEqual(aquarium.name, payload['name'])
self.assertEqual(aquarium.water_type, payload['water_type'])
self.assertEqual(aquarium.volume_liter, payload['volume_liter']) | Test changing the values of aquarium data | aqua_track/aquarium/tests/test_aquarium_api.py | test_basic_aquarium_update | nick-rc/aqua_track | 0 | python | def test_basic_aquarium_update(self):
aquarium = sample_aquarium(user=self.user)
payload = {'name': 'New Aq Name', 'water_type': 'Salty', 'volume_liter': 1}
url = detail_url(aquarium.id)
self.client.put(url, payload)
aquarium.refresh_from_db()
self.assertEqual(aquarium.name, payload['name'])
self.assertEqual(aquarium.water_type, payload['water_type'])
self.assertEqual(aquarium.volume_liter, payload['volume_liter']) | def test_basic_aquarium_update(self):
aquarium = sample_aquarium(user=self.user)
payload = {'name': 'New Aq Name', 'water_type': 'Salty', 'volume_liter': 1}
url = detail_url(aquarium.id)
self.client.put(url, payload)
aquarium.refresh_from_db()
self.assertEqual(aquarium.name, payload['name'])
self.assertEqual(aquarium.water_type, payload['water_type'])
self.assertEqual(aquarium.volume_liter, payload['volume_liter'])<|docstring|>Test changing the values of aquarium data<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.