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 |
|---|---|---|---|---|---|---|---|---|---|
918a7e4846129cb2bd207e93dbf1a7ac9ad298fd8c2257c861c2d39f3a36e86c | def _embed_thread(self, fsm, *args, **kwargs):
' extend a given thread FSM (for embed_thread func) '
frame = inspect.currentframe()
self.start_frame = frame.f_back.f_back
self._synthesize_start_fsm(args, kwargs, fsm)
return fsm | extend a given thread FSM (for embed_thread func) | venv/Lib/site-packages/veriloggen/thread/thread.py | _embed_thread | SweetSourPeter/violin | 232 | python | def _embed_thread(self, fsm, *args, **kwargs):
' '
frame = inspect.currentframe()
self.start_frame = frame.f_back.f_back
self._synthesize_start_fsm(args, kwargs, fsm)
return fsm | def _embed_thread(self, fsm, *args, **kwargs):
' '
frame = inspect.currentframe()
self.start_frame = frame.f_back.f_back
self._synthesize_start_fsm(args, kwargs, fsm)
return fsm<|docstring|>extend a given thread FSM (for embed_thread func)<|endoftext|> |
ebb48b7b6f2dffcd993f2612646cbc091b11f8f31934254b9f4000f99f052a1d | def run(self, fsm, *args, **kwargs):
' start as a child thread '
if ((not self.is_child) and (self.end_state is not None)):
raise ValueError('already started')
if (self.fsm is None):
self.fsm = FSM(self.m, self.name, self.clk, self.rst, as_module=self.fsm_as_module)
self.is_child = True
... | start as a child thread | venv/Lib/site-packages/veriloggen/thread/thread.py | run | SweetSourPeter/violin | 232 | python | def run(self, fsm, *args, **kwargs):
' '
if ((not self.is_child) and (self.end_state is not None)):
raise ValueError('already started')
if (self.fsm is None):
self.fsm = FSM(self.m, self.name, self.clk, self.rst, as_module=self.fsm_as_module)
self.is_child = True
if (self.start_stat... | def run(self, fsm, *args, **kwargs):
' '
if ((not self.is_child) and (self.end_state is not None)):
raise ValueError('already started')
if (self.fsm is None):
self.fsm = FSM(self.m, self.name, self.clk, self.rst, as_module=self.fsm_as_module)
self.is_child = True
if (self.start_stat... |
917277a4a5dea4fe18aa709ef2090ec013bccf5d34c5f34084411898304123eb | def join(self, fsm):
' wait for the completion '
if (self.end_state is None):
raise ValueError('not started')
end_flag = (self.fsm.state == self.end_state)
fsm.If(end_flag).goto_next()
return 0 | wait for the completion | venv/Lib/site-packages/veriloggen/thread/thread.py | join | SweetSourPeter/violin | 232 | python | def join(self, fsm):
' '
if (self.end_state is None):
raise ValueError('not started')
end_flag = (self.fsm.state == self.end_state)
fsm.If(end_flag).goto_next()
return 0 | def join(self, fsm):
' '
if (self.end_state is None):
raise ValueError('not started')
end_flag = (self.fsm.state == self.end_state)
fsm.If(end_flag).goto_next()
return 0<|docstring|>wait for the completion<|endoftext|> |
986ae98fc5e8e8db278218e163c07a45c0c1a82d68987614f39068eba06260f9 | def done(self, fsm):
' check whethe the thread is running '
if (self.end_state is None):
raise ValueError('not started')
end_flag = (self.fsm.state == self.end_state)
return end_flag | check whethe the thread is running | venv/Lib/site-packages/veriloggen/thread/thread.py | done | SweetSourPeter/violin | 232 | python | def done(self, fsm):
' '
if (self.end_state is None):
raise ValueError('not started')
end_flag = (self.fsm.state == self.end_state)
return end_flag | def done(self, fsm):
' '
if (self.end_state is None):
raise ValueError('not started')
end_flag = (self.fsm.state == self.end_state)
return end_flag<|docstring|>check whethe the thread is running<|endoftext|> |
b74a84cabc8c361df7a94b1eadb4fa0bac279943e3a1d31c81a58ded89d0b5f6 | def reset(self, fsm):
' reset the FSM counter to the initial state '
if (self.end_state is None):
raise ValueError('not started')
reset_flag = (fsm.state == fsm.current)
self.fsm._set_index(self.end_state)
if (self.called is not None):
self.fsm.If(reset_flag)(self.called(0))
self... | reset the FSM counter to the initial state | venv/Lib/site-packages/veriloggen/thread/thread.py | reset | SweetSourPeter/violin | 232 | python | def reset(self, fsm):
' '
if (self.end_state is None):
raise ValueError('not started')
reset_flag = (fsm.state == fsm.current)
self.fsm._set_index(self.end_state)
if (self.called is not None):
self.fsm.If(reset_flag)(self.called(0))
self.fsm.goto_from(self.end_state, self.start_... | def reset(self, fsm):
' '
if (self.end_state is None):
raise ValueError('not started')
reset_flag = (fsm.state == fsm.current)
self.fsm._set_index(self.end_state)
if (self.called is not None):
self.fsm.If(reset_flag)(self.called(0))
self.fsm.goto_from(self.end_state, self.start_... |
c40d35eb1e766bda03c3e3887495f55e8573bac0a64c327c4b4b98a32a57888e | def ret(self, fsm):
' return value '
return self.return_value | return value | venv/Lib/site-packages/veriloggen/thread/thread.py | ret | SweetSourPeter/violin | 232 | python | def ret(self, fsm):
' '
return self.return_value | def ret(self, fsm):
' '
return self.return_value<|docstring|>return value<|endoftext|> |
45574055dfda18fd1485d09f6d9fa9a3f77b302d79ab6c96e0b61afc70c2050c | def _thing_to_dict(self, thing):
"\n Converts a thing (a grakn object) to a dict for easy retrieval of the thing's\n attributes.\n "
entity = {'id': thing.id, 'type': thing.type().label()}
for each in thing.attributes():
entity[each.type().label()] = each.value()
return enti... | Converts a thing (a grakn object) to a dict for easy retrieval of the thing's
attributes. | graph_database.py | _thing_to_dict | psychedel/knowledgebase | 108 | python | def _thing_to_dict(self, thing):
"\n Converts a thing (a grakn object) to a dict for easy retrieval of the thing's\n attributes.\n "
entity = {'id': thing.id, 'type': thing.type().label()}
for each in thing.attributes():
entity[each.type().label()] = each.value()
return enti... | def _thing_to_dict(self, thing):
"\n Converts a thing (a grakn object) to a dict for easy retrieval of the thing's\n attributes.\n "
entity = {'id': thing.id, 'type': thing.type().label()}
for each in thing.attributes():
entity[each.type().label()] = each.value()
return enti... |
affd75c25e0c6cebfc231f0a1eb981605849c3aece33139242d69e38468f66de | def _execute_entity_query(self, query: Text) -> List[Dict[(Text, Any)]]:
'\n Executes a query that returns a list of entities with all their attributes.\n '
with GraknClient(uri=self.uri) as client:
with client.session(keyspace=self.keyspace) as session:
with session.transactio... | Executes a query that returns a list of entities with all their attributes. | graph_database.py | _execute_entity_query | psychedel/knowledgebase | 108 | python | def _execute_entity_query(self, query: Text) -> List[Dict[(Text, Any)]]:
'\n \n '
with GraknClient(uri=self.uri) as client:
with client.session(keyspace=self.keyspace) as session:
with session.transaction().read() as tx:
logger.debug(('Executing Graql Query: ' +... | def _execute_entity_query(self, query: Text) -> List[Dict[(Text, Any)]]:
'\n \n '
with GraknClient(uri=self.uri) as client:
with client.session(keyspace=self.keyspace) as session:
with session.transaction().read() as tx:
logger.debug(('Executing Graql Query: ' +... |
1dd28080e49fe4a3ab057a7c6afa324eb88bf109da70881667f1fb7f90ecc2d3 | def _execute_attribute_query(self, query: Text) -> List[Any]:
'\n Executes a query that returns the value(s) an entity has for a specific\n attribute.\n '
with GraknClient(uri=self.uri) as client:
with client.session(keyspace=self.keyspace) as session:
with session.trans... | Executes a query that returns the value(s) an entity has for a specific
attribute. | graph_database.py | _execute_attribute_query | psychedel/knowledgebase | 108 | python | def _execute_attribute_query(self, query: Text) -> List[Any]:
'\n Executes a query that returns the value(s) an entity has for a specific\n attribute.\n '
with GraknClient(uri=self.uri) as client:
with client.session(keyspace=self.keyspace) as session:
with session.trans... | def _execute_attribute_query(self, query: Text) -> List[Any]:
'\n Executes a query that returns the value(s) an entity has for a specific\n attribute.\n '
with GraknClient(uri=self.uri) as client:
with client.session(keyspace=self.keyspace) as session:
with session.trans... |
349e0f5f2b173f3054768c14fa9b737a1aea7dc0b90cdea6bcd4fb1c32e24a38 | def _execute_relation_query(self, query: Text, relation_name: Text) -> List[Dict[(Text, Any)]]:
'\n Execute a query that queries for a relation. All attributes of the relation and\n all entities participating in the relation are part of the result.\n '
with GraknClient(uri=self.uri) as clie... | Execute a query that queries for a relation. All attributes of the relation and
all entities participating in the relation are part of the result. | graph_database.py | _execute_relation_query | psychedel/knowledgebase | 108 | python | def _execute_relation_query(self, query: Text, relation_name: Text) -> List[Dict[(Text, Any)]]:
'\n Execute a query that queries for a relation. All attributes of the relation and\n all entities participating in the relation are part of the result.\n '
with GraknClient(uri=self.uri) as clie... | def _execute_relation_query(self, query: Text, relation_name: Text) -> List[Dict[(Text, Any)]]:
'\n Execute a query that queries for a relation. All attributes of the relation and\n all entities participating in the relation are part of the result.\n '
with GraknClient(uri=self.uri) as clie... |
3dad17a506cd92951993e41a73d8699d17f5d286de521098ead2631dab92d539 | def _get_me_clause(self, entity_type: Text) -> Text:
'\n Construct the me clause. Needed to only list, for example, accounts that are\n related to me.\n\n :param entity_type: entity type\n\n :return: me clause as string\n '
clause = ''
if (entity_type not in ['person', 'ba... | Construct the me clause. Needed to only list, for example, accounts that are
related to me.
:param entity_type: entity type
:return: me clause as string | graph_database.py | _get_me_clause | psychedel/knowledgebase | 108 | python | def _get_me_clause(self, entity_type: Text) -> Text:
'\n Construct the me clause. Needed to only list, for example, accounts that are\n related to me.\n\n :param entity_type: entity type\n\n :return: me clause as string\n '
clause =
if (entity_type not in ['person', 'bank... | def _get_me_clause(self, entity_type: Text) -> Text:
'\n Construct the me clause. Needed to only list, for example, accounts that are\n related to me.\n\n :param entity_type: entity type\n\n :return: me clause as string\n '
clause =
if (entity_type not in ['person', 'bank... |
aecb3299d13e32b9b1e68361d80272494a24595c57cb3a55dc96b7578a70bc6c | def _get_attribute_clause(self, attributes: Optional[List[Dict[(Text, Text)]]]=None) -> Text:
'\n Construct the attribute clause.\n\n :param attributes: attributes\n\n :return: attribute clause as string\n '
clause = ''
if attributes:
clause = ','.join([f"has {a['key']} '... | Construct the attribute clause.
:param attributes: attributes
:return: attribute clause as string | graph_database.py | _get_attribute_clause | psychedel/knowledgebase | 108 | python | def _get_attribute_clause(self, attributes: Optional[List[Dict[(Text, Text)]]]=None) -> Text:
'\n Construct the attribute clause.\n\n :param attributes: attributes\n\n :return: attribute clause as string\n '
clause =
if attributes:
clause = ','.join([f"has {a['key']} '{a... | def _get_attribute_clause(self, attributes: Optional[List[Dict[(Text, Text)]]]=None) -> Text:
'\n Construct the attribute clause.\n\n :param attributes: attributes\n\n :return: attribute clause as string\n '
clause =
if attributes:
clause = ','.join([f"has {a['key']} '{a... |
b0926b052b647aa8144d0ce57e2f1b12335f04f8dae6ede796ba3040b5887819 | def get_attribute_of(self, entity_type: Text, key_attribute: Text, entity: Text, attribute: Text) -> List[Any]:
'\n Get the value of the given attribute for the provided entity.\n\n :param entity_type: entity type\n :param key_attribute: key attribute of entity\n :param entity: name of t... | Get the value of the given attribute for the provided entity.
:param entity_type: entity type
:param key_attribute: key attribute of entity
:param entity: name of the entity
:param attribute: attribute of interest
:return: the value of the attribute | graph_database.py | get_attribute_of | psychedel/knowledgebase | 108 | python | def get_attribute_of(self, entity_type: Text, key_attribute: Text, entity: Text, attribute: Text) -> List[Any]:
'\n Get the value of the given attribute for the provided entity.\n\n :param entity_type: entity type\n :param key_attribute: key attribute of entity\n :param entity: name of t... | def get_attribute_of(self, entity_type: Text, key_attribute: Text, entity: Text, attribute: Text) -> List[Any]:
'\n Get the value of the given attribute for the provided entity.\n\n :param entity_type: entity type\n :param key_attribute: key attribute of entity\n :param entity: name of t... |
c981e698c19e73ba5ef375c8a5462e146221e04ae0da83a1b1a6c2a77e55692e | def _get_transaction_entities(self, attributes: Optional[List[Dict[(Text, Text)]]]=None) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for transactions. Restrict the transactions\n by the provided attributes, if any attributes are given.\n As transaction is a relation, query also the... | Query the graph database for transactions. Restrict the transactions
by the provided attributes, if any attributes are given.
As transaction is a relation, query also the related account entities.
:param attributes: list of attributes
:return: list of transactions | graph_database.py | _get_transaction_entities | psychedel/knowledgebase | 108 | python | def _get_transaction_entities(self, attributes: Optional[List[Dict[(Text, Text)]]]=None) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for transactions. Restrict the transactions\n by the provided attributes, if any attributes are given.\n As transaction is a relation, query also the... | def _get_transaction_entities(self, attributes: Optional[List[Dict[(Text, Text)]]]=None) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for transactions. Restrict the transactions\n by the provided attributes, if any attributes are given.\n As transaction is a relation, query also the... |
57d9282947d8a721a668ff7236cda338c5db09dd73fcf2dbd1b0084e8b2bea80 | def _get_card_entities(self, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=5) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for cards. Restrict the cards\n by the provided attributes, if any attributes are given.\n\n :param attributes: list of attributes\n :p... | Query the graph database for cards. Restrict the cards
by the provided attributes, if any attributes are given.
:param attributes: list of attributes
:param limit: maximum number of cards to return
:return: list of cards | graph_database.py | _get_card_entities | psychedel/knowledgebase | 108 | python | def _get_card_entities(self, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=5) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for cards. Restrict the cards\n by the provided attributes, if any attributes are given.\n\n :param attributes: list of attributes\n :p... | def _get_card_entities(self, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=5) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for cards. Restrict the cards\n by the provided attributes, if any attributes are given.\n\n :param attributes: list of attributes\n :p... |
bc385ecbe31fb182e29c2d8cc9ff2f175e797eee5549d99e15c071ca103f3863 | def _get_account_entities(self, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=5) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for accounts. Restrict the accounts\n by the provided attributes, if any attributes are given.\n Query the related relation contract, to ob... | Query the graph database for accounts. Restrict the accounts
by the provided attributes, if any attributes are given.
Query the related relation contract, to obtain additional information
about the bank and the person who owns the account.
:param attributes: list of attributes
:param limit: maximum number of accounts ... | graph_database.py | _get_account_entities | psychedel/knowledgebase | 108 | python | def _get_account_entities(self, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=5) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for accounts. Restrict the accounts\n by the provided attributes, if any attributes are given.\n Query the related relation contract, to ob... | def _get_account_entities(self, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=5) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for accounts. Restrict the accounts\n by the provided attributes, if any attributes are given.\n Query the related relation contract, to ob... |
b406702be5d3a80595269d747de73b1a4f11b1919b3c6d2c110db3d67bf7e620 | def get_entities(self, entity_type: Text, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=10) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for entities of the given type. Restrict the entities\n by the provided attributes, if any attributes are given.\n\n :param enti... | Query the graph database for entities of the given type. Restrict the entities
by the provided attributes, if any attributes are given.
:param entity_type: the entity type
:param attributes: list of attributes
:param limit: maximum number of entities to return
:return: list of entities | graph_database.py | get_entities | psychedel/knowledgebase | 108 | python | def get_entities(self, entity_type: Text, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=10) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for entities of the given type. Restrict the entities\n by the provided attributes, if any attributes are given.\n\n :param enti... | def get_entities(self, entity_type: Text, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=10) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for entities of the given type. Restrict the entities\n by the provided attributes, if any attributes are given.\n\n :param enti... |
365e2d83ee40a41b9b04f64d11c8db1193904673f19cdcc20f8907194b2b932e | def map(self, mapping_type: Text, mapping_key: Text) -> Text:
'\n Query the given mapping table for the provided key.\n\n :param mapping_type: the name of the mapping table\n :param mapping_key: the mapping key\n\n :return: the mapping value\n '
value = self._execute_attribute... | Query the given mapping table for the provided key.
:param mapping_type: the name of the mapping table
:param mapping_key: the mapping key
:return: the mapping value | graph_database.py | map | psychedel/knowledgebase | 108 | python | def map(self, mapping_type: Text, mapping_key: Text) -> Text:
'\n Query the given mapping table for the provided key.\n\n :param mapping_type: the name of the mapping table\n :param mapping_key: the mapping key\n\n :return: the mapping value\n '
value = self._execute_attribute... | def map(self, mapping_type: Text, mapping_key: Text) -> Text:
'\n Query the given mapping table for the provided key.\n\n :param mapping_type: the name of the mapping table\n :param mapping_key: the mapping key\n\n :return: the mapping value\n '
value = self._execute_attribute... |
0019d169bbd0a69eddea2a5cb183969d222823147e9d60f4bb2b26a7103317c9 | def validate_entity(self, entity_type, entity, key_attribute, attributes) -> Dict[(Text, Any)]:
'\n Validates if the given entity has all provided attribute values.\n\n :param entity_type: entity type\n :param entity: name of the entity\n :param key_attribute: key attribute of entity\n ... | Validates if the given entity has all provided attribute values.
:param entity_type: entity type
:param entity: name of the entity
:param key_attribute: key attribute of entity
:param attributes: attributes
:return: the found entity | graph_database.py | validate_entity | psychedel/knowledgebase | 108 | python | def validate_entity(self, entity_type, entity, key_attribute, attributes) -> Dict[(Text, Any)]:
'\n Validates if the given entity has all provided attribute values.\n\n :param entity_type: entity type\n :param entity: name of the entity\n :param key_attribute: key attribute of entity\n ... | def validate_entity(self, entity_type, entity, key_attribute, attributes) -> Dict[(Text, Any)]:
'\n Validates if the given entity has all provided attribute values.\n\n :param entity_type: entity type\n :param entity: name of the entity\n :param key_attribute: key attribute of entity\n ... |
94a3d8b5f17cc1581c096cb6a7b38093ad107141f1bbf930bf528b37c820d79d | def get_entities(self, entity_type: Text, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=5) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for entities of the given type. Restrict the entities\n by the provided attributes, if any attributes are given.\n\n :param entit... | Query the graph database for entities of the given type. Restrict the entities
by the provided attributes, if any attributes are given.
:param entity_type: the entity type
:param attributes: list of attributes
:param limit: maximum number of entities to return
:return: list of entities | graph_database.py | get_entities | psychedel/knowledgebase | 108 | python | def get_entities(self, entity_type: Text, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=5) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for entities of the given type. Restrict the entities\n by the provided attributes, if any attributes are given.\n\n :param entit... | def get_entities(self, entity_type: Text, attributes: Optional[List[Dict[(Text, Text)]]]=None, limit: int=5) -> List[Dict[(Text, Any)]]:
'\n Query the graph database for entities of the given type. Restrict the entities\n by the provided attributes, if any attributes are given.\n\n :param entit... |
4d7a4f82b2fa0e05a6a47bc9b0f44e0fd41f42d63f60bd40135b2f420ee3fd40 | def get_attribute_of(self, entity_type: Text, key_attribute: Text, entity: Text, attribute: Text) -> List[Any]:
'\n Get the value of the given attribute for the provided entity.\n\n :param entity_type: entity type\n :param key_attribute: key attribute of entity\n :param entity: name of t... | Get the value of the given attribute for the provided entity.
:param entity_type: entity type
:param key_attribute: key attribute of entity
:param entity: name of the entity
:param attribute: attribute of interest
:return: the value of the attribute | graph_database.py | get_attribute_of | psychedel/knowledgebase | 108 | python | def get_attribute_of(self, entity_type: Text, key_attribute: Text, entity: Text, attribute: Text) -> List[Any]:
'\n Get the value of the given attribute for the provided entity.\n\n :param entity_type: entity type\n :param key_attribute: key attribute of entity\n :param entity: name of t... | def get_attribute_of(self, entity_type: Text, key_attribute: Text, entity: Text, attribute: Text) -> List[Any]:
'\n Get the value of the given attribute for the provided entity.\n\n :param entity_type: entity type\n :param key_attribute: key attribute of entity\n :param entity: name of t... |
784d3fd4a58a02d0c819360820a64e8d6a01d32e072863ec56b7323c0f7645c3 | def validate_entity(self, entity_type, entity, key_attribute, attributes) -> Optional[Dict[(Text, Any)]]:
'\n Validates if the given entity has all provided attribute values.\n\n :param entity_type: entity type\n :param entity: name of the entity\n :param key_attribute: key attribute of ... | Validates if the given entity has all provided attribute values.
:param entity_type: entity type
:param entity: name of the entity
:param key_attribute: key attribute of entity
:param attributes: attributes
:return: the found entity | graph_database.py | validate_entity | psychedel/knowledgebase | 108 | python | def validate_entity(self, entity_type, entity, key_attribute, attributes) -> Optional[Dict[(Text, Any)]]:
'\n Validates if the given entity has all provided attribute values.\n\n :param entity_type: entity type\n :param entity: name of the entity\n :param key_attribute: key attribute of ... | def validate_entity(self, entity_type, entity, key_attribute, attributes) -> Optional[Dict[(Text, Any)]]:
'\n Validates if the given entity has all provided attribute values.\n\n :param entity_type: entity type\n :param entity: name of the entity\n :param key_attribute: key attribute of ... |
439f9e913530ac7d4b215bdb9b07b79fc757f91f66348ed3cdca1dc6c10e4a09 | def map(self, mapping_type: Text, mapping_key: Text) -> Text:
'\n Query the given mapping table for the provided key.\n\n :param mapping_type: the name of the mapping table\n :param mapping_key: the mapping key\n\n :return: the mapping value\n '
if ((mapping_type == 'attribute... | Query the given mapping table for the provided key.
:param mapping_type: the name of the mapping table
:param mapping_key: the mapping key
:return: the mapping value | graph_database.py | map | psychedel/knowledgebase | 108 | python | def map(self, mapping_type: Text, mapping_key: Text) -> Text:
'\n Query the given mapping table for the provided key.\n\n :param mapping_type: the name of the mapping table\n :param mapping_key: the mapping key\n\n :return: the mapping value\n '
if ((mapping_type == 'attribute... | def map(self, mapping_type: Text, mapping_key: Text) -> Text:
'\n Query the given mapping table for the provided key.\n\n :param mapping_type: the name of the mapping table\n :param mapping_key: the mapping key\n\n :return: the mapping value\n '
if ((mapping_type == 'attribute... |
9f854b759eff4728e9812961dbaee4419b0ee72e17b1c3477a435302340711c4 | @distributed_trace
def list_by_workspace(self, resource_group_name: str, workspace_name: str, **kwargs: Any) -> Iterable['_models.TablesListResult']:
'Gets all the tables for the specified Log Analytics workspace.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n... | Gets all the tables for the specified Log Analytics workspace.
:param resource_group_name: The name of the resource group. The name is case insensitive.
:type resource_group_name: str
:param workspace_name: The name of the workspace.
:type workspace_name: str
:keyword callable cls: A custom type or function that will ... | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/operations/_tables_operations.py | list_by_workspace | xolve/azure-sdk-for-python | 1 | python | @distributed_trace
def list_by_workspace(self, resource_group_name: str, workspace_name: str, **kwargs: Any) -> Iterable['_models.TablesListResult']:
'Gets all the tables for the specified Log Analytics workspace.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n... | @distributed_trace
def list_by_workspace(self, resource_group_name: str, workspace_name: str, **kwargs: Any) -> Iterable['_models.TablesListResult']:
'Gets all the tables for the specified Log Analytics workspace.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n... |
e4211caffff6069ffca2172a7304e8ffdb05783c7c9162d562b720cb63eb5c62 | @distributed_trace
def begin_create_or_update(self, resource_group_name: str, workspace_name: str, table_name: str, parameters: '_models.Table', **kwargs: Any) -> LROPoller['_models.Table']:
'Update or Create a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The... | Update or Create a Log Analytics workspace table.
:param resource_group_name: The name of the resource group. The name is case insensitive.
:type resource_group_name: str
:param workspace_name: The name of the workspace.
:type workspace_name: str
:param table_name: The name of the table.
:type table_name: str
:param p... | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/operations/_tables_operations.py | begin_create_or_update | xolve/azure-sdk-for-python | 1 | python | @distributed_trace
def begin_create_or_update(self, resource_group_name: str, workspace_name: str, table_name: str, parameters: '_models.Table', **kwargs: Any) -> LROPoller['_models.Table']:
'Update or Create a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The... | @distributed_trace
def begin_create_or_update(self, resource_group_name: str, workspace_name: str, table_name: str, parameters: '_models.Table', **kwargs: Any) -> LROPoller['_models.Table']:
'Update or Create a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The... |
1e76c20bf4c5aeb33fda106a775c9ed57a0ffb349d55bb452aa364fc0a6e1d5e | @distributed_trace
def begin_update(self, resource_group_name: str, workspace_name: str, table_name: str, parameters: '_models.Table', **kwargs: Any) -> LROPoller['_models.Table']:
'Update a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The name is case insens... | Update a Log Analytics workspace table.
:param resource_group_name: The name of the resource group. The name is case insensitive.
:type resource_group_name: str
:param workspace_name: The name of the workspace.
:type workspace_name: str
:param table_name: The name of the table.
:type table_name: str
:param parameters:... | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/operations/_tables_operations.py | begin_update | xolve/azure-sdk-for-python | 1 | python | @distributed_trace
def begin_update(self, resource_group_name: str, workspace_name: str, table_name: str, parameters: '_models.Table', **kwargs: Any) -> LROPoller['_models.Table']:
'Update a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The name is case insens... | @distributed_trace
def begin_update(self, resource_group_name: str, workspace_name: str, table_name: str, parameters: '_models.Table', **kwargs: Any) -> LROPoller['_models.Table']:
'Update a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The name is case insens... |
ff44130c8ccdd9b4b84e5fd76482e921dd297ff63a499419f90d4e37eb1e254e | @distributed_trace
def get(self, resource_group_name: str, workspace_name: str, table_name: str, **kwargs: Any) -> '_models.Table':
'Gets a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_group_name: str\n ... | Gets a Log Analytics workspace table.
:param resource_group_name: The name of the resource group. The name is case insensitive.
:type resource_group_name: str
:param workspace_name: The name of the workspace.
:type workspace_name: str
:param table_name: The name of the table.
:type table_name: str
:keyword callable cl... | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/operations/_tables_operations.py | get | xolve/azure-sdk-for-python | 1 | python | @distributed_trace
def get(self, resource_group_name: str, workspace_name: str, table_name: str, **kwargs: Any) -> '_models.Table':
'Gets a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_group_name: str\n ... | @distributed_trace
def get(self, resource_group_name: str, workspace_name: str, table_name: str, **kwargs: Any) -> '_models.Table':
'Gets a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_group_name: str\n ... |
cca5057b0b03dc8704a201a6fac6b6d844271011fab5799d5acada2f8745ca02 | @distributed_trace
def begin_delete(self, resource_group_name: str, workspace_name: str, table_name: str, **kwargs: Any) -> LROPoller[None]:
'Delete a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_group_nam... | Delete a Log Analytics workspace table.
:param resource_group_name: The name of the resource group. The name is case insensitive.
:type resource_group_name: str
:param workspace_name: The name of the workspace.
:type workspace_name: str
:param table_name: The name of the table.
:type table_name: str
:keyword callable ... | sdk/loganalytics/azure-mgmt-loganalytics/azure/mgmt/loganalytics/operations/_tables_operations.py | begin_delete | xolve/azure-sdk-for-python | 1 | python | @distributed_trace
def begin_delete(self, resource_group_name: str, workspace_name: str, table_name: str, **kwargs: Any) -> LROPoller[None]:
'Delete a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_group_nam... | @distributed_trace
def begin_delete(self, resource_group_name: str, workspace_name: str, table_name: str, **kwargs: Any) -> LROPoller[None]:
'Delete a Log Analytics workspace table.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_group_nam... |
31a7b08c9ac8a4a88e8d9376cd3916083cf400d748598173ef91f27b14af6b54 | @lru_cache()
def get() -> ApiSettings:
'Return the settings object.'
return ApiSettings(_env_file=os.environ['APP_ENV']) | Return the settings object. | api/settings/api_settings.py | get | quanttyo/GastroHelper | 0 | python | @lru_cache()
def get() -> ApiSettings:
return ApiSettings(_env_file=os.environ['APP_ENV']) | @lru_cache()
def get() -> ApiSettings:
return ApiSettings(_env_file=os.environ['APP_ENV'])<|docstring|>Return the settings object.<|endoftext|> |
b795d5fe236270384e82617fefc67400fe91ade5f77b8779d001a6d6f665010a | @property
def api_kwargs(self) -> dict[(str, Any)]:
'Return all settings for api.'
_kwargs: dict[(str, Any)] = {'debug': self.debug, 'docs_url': self.docs_url, 'redoc_url': self.redoc_url, 'openapi_prefix': self.openapi_prefix, 'openapi_url': self.openapi_url, 'title': self.title, 'version': self.version}
i... | Return all settings for api. | api/settings/api_settings.py | api_kwargs | quanttyo/GastroHelper | 0 | python | @property
def api_kwargs(self) -> dict[(str, Any)]:
_kwargs: dict[(str, Any)] = {'debug': self.debug, 'docs_url': self.docs_url, 'redoc_url': self.redoc_url, 'openapi_prefix': self.openapi_prefix, 'openapi_url': self.openapi_url, 'title': self.title, 'version': self.version}
if self.disable_docs:
_... | @property
def api_kwargs(self) -> dict[(str, Any)]:
_kwargs: dict[(str, Any)] = {'debug': self.debug, 'docs_url': self.docs_url, 'redoc_url': self.redoc_url, 'openapi_prefix': self.openapi_prefix, 'openapi_url': self.openapi_url, 'title': self.title, 'version': self.version}
if self.disable_docs:
_... |
cd9d45f49984860d614432af512c41687f1b6febb855b43949025a58bdefd966 | def _epoch(self, dataloader, epoch, mode='train'):
'\n Training logic for an epoch\n '
self.initepoch()
if (mode == 'train'):
self.model.train()
else:
self.model.eval()
nIters = len(dataloader)
bar = Bar('==>', max=nIters)
for (batch_idx, (data, ... | Training logic for an epoch | trainer.py | _epoch | Pandinosaurus/Pytorch-Human-Pose-Estimation | 423 | python | def _epoch(self, dataloader, epoch, mode='train'):
'\n \n '
self.initepoch()
if (mode == 'train'):
self.model.train()
else:
self.model.eval()
nIters = len(dataloader)
bar = Bar('==>', max=nIters)
for (batch_idx, (data, target, meta1, meta2)) in e... | def _epoch(self, dataloader, epoch, mode='train'):
'\n \n '
self.initepoch()
if (mode == 'train'):
self.model.train()
else:
self.model.eval()
nIters = len(dataloader)
bar = Bar('==>', max=nIters)
for (batch_idx, (data, target, meta1, meta2)) in e... |
691aeeb3ecf187bf516255ba8e23b4ac909bab0ba35d5102b737987bd9ebc822 | def __init__(self, x, y, w, h):
'\n Create a rectangle, not too fancy\n\n Normal case\n >>> r1 = Rect(10, 10, 10, 10)\n >>> (r1.x1, r1.y1, r1.x2, r1.y2)\n (10, 10, 20, 20)\n\n Weird rectangles\n >>> r2 = Rect(0, 0, 0, 0)\n >>> (r2.x1, r2.y1, r2.x2, r2.y2)\n ... | Create a rectangle, not too fancy
Normal case
>>> r1 = Rect(10, 10, 10, 10)
>>> (r1.x1, r1.y1, r1.x2, r1.y2)
(10, 10, 20, 20)
Weird rectangles
>>> r2 = Rect(0, 0, 0, 0)
>>> (r2.x1, r2.y1, r2.x2, r2.y2)
(0, 0, 0, 0)
>>> r3 = Rect(10, 10, -5, -5)
>>> (r3.x1, r3.y1, r3.x2, r3.y2)
(10, 10, 5, 5) | rect.py | __init__ | jorisslob/RoguelikeFantasyWorldSimulator | 0 | python | def __init__(self, x, y, w, h):
'\n Create a rectangle, not too fancy\n\n Normal case\n >>> r1 = Rect(10, 10, 10, 10)\n >>> (r1.x1, r1.y1, r1.x2, r1.y2)\n (10, 10, 20, 20)\n\n Weird rectangles\n >>> r2 = Rect(0, 0, 0, 0)\n >>> (r2.x1, r2.y1, r2.x2, r2.y2)\n ... | def __init__(self, x, y, w, h):
'\n Create a rectangle, not too fancy\n\n Normal case\n >>> r1 = Rect(10, 10, 10, 10)\n >>> (r1.x1, r1.y1, r1.x2, r1.y2)\n (10, 10, 20, 20)\n\n Weird rectangles\n >>> r2 = Rect(0, 0, 0, 0)\n >>> (r2.x1, r2.y1, r2.x2, r2.y2)\n ... |
867b4d7b4e7f7e0e8bd5c0794de0c13381b1addfe96b1c81486c05b0c745469b | def center(self):
'\n Calculates the center of a rectangle\n\n Happy path\n >>> r1 = Rect(10, 10, 2, 2)\n >>> r1.center()\n (11, 11)\n\n Rounded down\n >>> r2 = Rect(20, 10, 3, 5)\n >>> r2.center()\n (21, 12)\n '
center_x = ((self.x1 + self.x... | Calculates the center of a rectangle
Happy path
>>> r1 = Rect(10, 10, 2, 2)
>>> r1.center()
(11, 11)
Rounded down
>>> r2 = Rect(20, 10, 3, 5)
>>> r2.center()
(21, 12) | rect.py | center | jorisslob/RoguelikeFantasyWorldSimulator | 0 | python | def center(self):
'\n Calculates the center of a rectangle\n\n Happy path\n >>> r1 = Rect(10, 10, 2, 2)\n >>> r1.center()\n (11, 11)\n\n Rounded down\n >>> r2 = Rect(20, 10, 3, 5)\n >>> r2.center()\n (21, 12)\n '
center_x = ((self.x1 + self.x... | def center(self):
'\n Calculates the center of a rectangle\n\n Happy path\n >>> r1 = Rect(10, 10, 2, 2)\n >>> r1.center()\n (11, 11)\n\n Rounded down\n >>> r2 = Rect(20, 10, 3, 5)\n >>> r2.center()\n (21, 12)\n '
center_x = ((self.x1 + self.x... |
7699c0bccfbd2d44da824e9685573d70a9b116895374489ee21103f62b04080e | def intersect(self, other):
'\n returns true if this rectangle intersects with another one\n intersection also includes touching\n\n >>> r1 = Rect(10, 10, 10, 10)\n >>> r2 = Rect(15, 15, 10, 10)\n >>> r3 = Rect(25, 25, 10, 10)\n >>> r1.intersect(r2)\n True\n >... | returns true if this rectangle intersects with another one
intersection also includes touching
>>> r1 = Rect(10, 10, 10, 10)
>>> r2 = Rect(15, 15, 10, 10)
>>> r3 = Rect(25, 25, 10, 10)
>>> r1.intersect(r2)
True
>>> r1.intersect(r3)
False
>>> r2.intersect(r3)
True | rect.py | intersect | jorisslob/RoguelikeFantasyWorldSimulator | 0 | python | def intersect(self, other):
'\n returns true if this rectangle intersects with another one\n intersection also includes touching\n\n >>> r1 = Rect(10, 10, 10, 10)\n >>> r2 = Rect(15, 15, 10, 10)\n >>> r3 = Rect(25, 25, 10, 10)\n >>> r1.intersect(r2)\n True\n >... | def intersect(self, other):
'\n returns true if this rectangle intersects with another one\n intersection also includes touching\n\n >>> r1 = Rect(10, 10, 10, 10)\n >>> r2 = Rect(15, 15, 10, 10)\n >>> r3 = Rect(25, 25, 10, 10)\n >>> r1.intersect(r2)\n True\n >... |
41bd9d137fec0f3c4be1388b012eec128b7ea2e4502ee68b637cef3a1df87922 | def example_DMP():
'\n Creates a noisy trajectory, fits weights to it, and then adjusts the\n trajectory by moving its start position, goal position, or period\n '
t = np.arange(0, ((3 * np.pi) / 2), 0.01)
t1 = np.arange(((3 * np.pi) / 2), (2 * np.pi), 0.01)[:(- 1)]
t2 = np.arange(0, (np.pi / 2... | Creates a noisy trajectory, fits weights to it, and then adjusts the
trajectory by moving its start position, goal position, or period | PathPlanning/DynamicMovementPrimitives/dynamic_movement_primitives.py | example_DMP | SaintWarri0r/PythonRobotics | 15,431 | python | def example_DMP():
'\n Creates a noisy trajectory, fits weights to it, and then adjusts the\n trajectory by moving its start position, goal position, or period\n '
t = np.arange(0, ((3 * np.pi) / 2), 0.01)
t1 = np.arange(((3 * np.pi) / 2), (2 * np.pi), 0.01)[:(- 1)]
t2 = np.arange(0, (np.pi / 2... | def example_DMP():
'\n Creates a noisy trajectory, fits weights to it, and then adjusts the\n trajectory by moving its start position, goal position, or period\n '
t = np.arange(0, ((3 * np.pi) / 2), 0.01)
t1 = np.arange(((3 * np.pi) / 2), (2 * np.pi), 0.01)[:(- 1)]
t2 = np.arange(0, (np.pi / 2... |
49cf568edfd5f0a039c26741129cb0b9cd5f8170e28f0632bafb668ca6876fa4 | def __init__(self, training_data, data_period, K=156.25, B=25):
'\n Arguments:\n training_data - input data of form [N, dim]\n data_period - amount of time training data covers\n K and B - spring and damper constants to define\n DMP behavior... | Arguments:
training_data - input data of form [N, dim]
data_period - amount of time training data covers
K and B - spring and damper constants to define
DMP behavior | PathPlanning/DynamicMovementPrimitives/dynamic_movement_primitives.py | __init__ | SaintWarri0r/PythonRobotics | 15,431 | python | def __init__(self, training_data, data_period, K=156.25, B=25):
'\n Arguments:\n training_data - input data of form [N, dim]\n data_period - amount of time training data covers\n K and B - spring and damper constants to define\n DMP behavior... | def __init__(self, training_data, data_period, K=156.25, B=25):
'\n Arguments:\n training_data - input data of form [N, dim]\n data_period - amount of time training data covers\n K and B - spring and damper constants to define\n DMP behavior... |
33b413662e0383b634a1a28a04a31b539b4f28d2df8e7c664582162eb6e9905e | def find_basis_functions_weights(self, training_data, data_period, num_weights=10):
'\n Arguments:\n data [(steps x spacial dim) np array] - data to replicate with DMP\n data_period [float] - time duration of data\n '
if (not isinstance(training_data, np.ndarray)):
pr... | Arguments:
data [(steps x spacial dim) np array] - data to replicate with DMP
data_period [float] - time duration of data | PathPlanning/DynamicMovementPrimitives/dynamic_movement_primitives.py | find_basis_functions_weights | SaintWarri0r/PythonRobotics | 15,431 | python | def find_basis_functions_weights(self, training_data, data_period, num_weights=10):
'\n Arguments:\n data [(steps x spacial dim) np array] - data to replicate with DMP\n data_period [float] - time duration of data\n '
if (not isinstance(training_data, np.ndarray)):
pr... | def find_basis_functions_weights(self, training_data, data_period, num_weights=10):
'\n Arguments:\n data [(steps x spacial dim) np array] - data to replicate with DMP\n data_period [float] - time duration of data\n '
if (not isinstance(training_data, np.ndarray)):
pr... |
c7f152aad4d75a2dba1df8daeef3030e73c1dd87f61ba41a6330b69f5e2b26f6 | def recreate_trajectory(self, init_state, goal_state, T):
'\n init_state - initial state/position\n goal_state - goal state/position\n T - amount of time to travel q0 -> g\n '
nrBasis = len(self.weights[0])
C = np.linspace(0, 1, nrBasis)
H = (0.65 * ((1.0 / (nrBasis - 1)) **... | init_state - initial state/position
goal_state - goal state/position
T - amount of time to travel q0 -> g | PathPlanning/DynamicMovementPrimitives/dynamic_movement_primitives.py | recreate_trajectory | SaintWarri0r/PythonRobotics | 15,431 | python | def recreate_trajectory(self, init_state, goal_state, T):
'\n init_state - initial state/position\n goal_state - goal state/position\n T - amount of time to travel q0 -> g\n '
nrBasis = len(self.weights[0])
C = np.linspace(0, 1, nrBasis)
H = (0.65 * ((1.0 / (nrBasis - 1)) **... | def recreate_trajectory(self, init_state, goal_state, T):
'\n init_state - initial state/position\n goal_state - goal state/position\n T - amount of time to travel q0 -> g\n '
nrBasis = len(self.weights[0])
C = np.linspace(0, 1, nrBasis)
H = (0.65 * ((1.0 / (nrBasis - 1)) **... |
f0d2709dbaaa076ff35e55d135bc34ec11ead45625a563621b14835252ee6fd9 | def show_DMP_purpose(self):
'\n This function conveys the purpose of DMPs:\n to capture a trajectory and be able to stretch\n and squeeze it in terms of start and stop position\n or time\n '
q0_orig = self.training_data[0]
g_orig = self.training_data[(- 1)]
... | This function conveys the purpose of DMPs:
to capture a trajectory and be able to stretch
and squeeze it in terms of start and stop position
or time | PathPlanning/DynamicMovementPrimitives/dynamic_movement_primitives.py | show_DMP_purpose | SaintWarri0r/PythonRobotics | 15,431 | python | def show_DMP_purpose(self):
'\n This function conveys the purpose of DMPs:\n to capture a trajectory and be able to stretch\n and squeeze it in terms of start and stop position\n or time\n '
q0_orig = self.training_data[0]
g_orig = self.training_data[(- 1)]
... | def show_DMP_purpose(self):
'\n This function conveys the purpose of DMPs:\n to capture a trajectory and be able to stretch\n and squeeze it in terms of start and stop position\n or time\n '
q0_orig = self.training_data[0]
g_orig = self.training_data[(- 1)]
... |
39d89067bcc9eb00a9f33eb884aea1c18a6461cd7f322fda7defad0262b34324 | def evaluate_model(valid_dataloader, train_dataloader, nll_per_action, model):
' Calculates the model score, which is the UC-JSD. Also calculates the mean\n NLL per action of the validation, training, and generated sets. Writes the\n scores to `validation.csv`.\n\n Args:\n valid_dataloader (torch.util... | Calculates the model score, which is the UC-JSD. Also calculates the mean
NLL per action of the validation, training, and generated sets. Writes the
scores to `validation.csv`.
Args:
valid_dataloader (torch.utils.data.dataloader.DataLoader) : Validation set
data.
train_dataloader (torch.utils.data.dataloader.D... | fine-tuning/analyze.py | evaluate_model | olsson-group/RL-GraphINVENT | 18 | python | def evaluate_model(valid_dataloader, train_dataloader, nll_per_action, model):
' Calculates the model score, which is the UC-JSD. Also calculates the mean\n NLL per action of the validation, training, and generated sets. Writes the\n scores to `validation.csv`.\n\n Args:\n valid_dataloader (torch.util... | def evaluate_model(valid_dataloader, train_dataloader, nll_per_action, model):
' Calculates the model score, which is the UC-JSD. Also calculates the mean\n NLL per action of the validation, training, and generated sets. Writes the\n scores to `validation.csv`.\n\n Args:\n valid_dataloader (torch.util... |
42d1e973b9e0212ee9daf0fc0946969fe2955b6f642daaa427ad8b5c58b5c501 | def evaluate_generated_graphs(generated_graphs, termination, agent_lls, prior_lls, start_time, ts_properties, generation_batch_idx):
' Computes molecular properties for input set of generated graphs, saves\n results to CSV, and writes `generated_mols` to disk as a SMILES file.\n Properties are expensive to c... | Computes molecular properties for input set of generated graphs, saves
results to CSV, and writes `generated_mols` to disk as a SMILES file.
Properties are expensive to calculate, so only done when
`gen_batch_idx` == 0 (i.e. for the first batch of generated molecules).
Args:
generated_graphs (list) : Contains `Gene... | fine-tuning/analyze.py | evaluate_generated_graphs | olsson-group/RL-GraphINVENT | 18 | python | def evaluate_generated_graphs(generated_graphs, termination, agent_lls, prior_lls, start_time, ts_properties, generation_batch_idx):
' Computes molecular properties for input set of generated graphs, saves\n results to CSV, and writes `generated_mols` to disk as a SMILES file.\n Properties are expensive to c... | def evaluate_generated_graphs(generated_graphs, termination, agent_lls, prior_lls, start_time, ts_properties, generation_batch_idx):
' Computes molecular properties for input set of generated graphs, saves\n results to CSV, and writes `generated_mols` to disk as a SMILES file.\n Properties are expensive to c... |
6fc7674d6dfc7780d0428eb28043c71fd0c6b095bad6c04c3c345a056edd6ff8 | def evaluate_training_set(preprocessing_graphs):
' Computes molecular properties for structures in training set.\n\n Args:\n training_graphs (list) : Contains `PreprocessingGraph`s.\n\n Returns:\n ts_prop_dict (dict) : Dictionary of training set molecular properties.\n '
ts_prop_dict = get_mo... | Computes molecular properties for structures in training set.
Args:
training_graphs (list) : Contains `PreprocessingGraph`s.
Returns:
ts_prop_dict (dict) : Dictionary of training set molecular properties. | fine-tuning/analyze.py | evaluate_training_set | olsson-group/RL-GraphINVENT | 18 | python | def evaluate_training_set(preprocessing_graphs):
' Computes molecular properties for structures in training set.\n\n Args:\n training_graphs (list) : Contains `PreprocessingGraph`s.\n\n Returns:\n ts_prop_dict (dict) : Dictionary of training set molecular properties.\n '
ts_prop_dict = get_mo... | def evaluate_training_set(preprocessing_graphs):
' Computes molecular properties for structures in training set.\n\n Args:\n training_graphs (list) : Contains `PreprocessingGraph`s.\n\n Returns:\n ts_prop_dict (dict) : Dictionary of training set molecular properties.\n '
ts_prop_dict = get_mo... |
af524d6a4542c58a084dc2b0187088d774962826276e6bcedd544d1626ebf51a | def get_edge_feature_distribution(molecular_graphs):
' Returns a histogram of edge features present in the input `molecular_graphs`\n (`list` of `MolecularGraph`s). The histogram is a `torch.Tensor` where\n the first item corresponds to the count of the first edge type, etc.\n The edge types correspond to ... | Returns a histogram of edge features present in the input `molecular_graphs`
(`list` of `MolecularGraph`s). The histogram is a `torch.Tensor` where
the first item corresponds to the count of the first edge type, etc.
The edge types correspond to those defined in `BONDTYPE_TO_INT`. | fine-tuning/analyze.py | get_edge_feature_distribution | olsson-group/RL-GraphINVENT | 18 | python | def get_edge_feature_distribution(molecular_graphs):
' Returns a histogram of edge features present in the input `molecular_graphs`\n (`list` of `MolecularGraph`s). The histogram is a `torch.Tensor` where\n the first item corresponds to the count of the first edge type, etc.\n The edge types correspond to ... | def get_edge_feature_distribution(molecular_graphs):
' Returns a histogram of edge features present in the input `molecular_graphs`\n (`list` of `MolecularGraph`s). The histogram is a `torch.Tensor` where\n the first item corresponds to the count of the first edge type, etc.\n The edge types correspond to ... |
a7b0b44151e3f58b82dd219f27284261b47846dc9d73e42ff1a4b2517c09d8bc | def get_fraction_unique(molecular_graphs):
' Returns the fraction (`float`) of unique graphs in `molecular_graphs`\n (`list` of `MolecularGraph`s) by comparing their canonical SMILES strings.\n '
smiles_list = []
for molecular_graph in molecular_graphs:
smiles = molecular_graph.get_smiles()
... | Returns the fraction (`float`) of unique graphs in `molecular_graphs`
(`list` of `MolecularGraph`s) by comparing their canonical SMILES strings. | fine-tuning/analyze.py | get_fraction_unique | olsson-group/RL-GraphINVENT | 18 | python | def get_fraction_unique(molecular_graphs):
' Returns the fraction (`float`) of unique graphs in `molecular_graphs`\n (`list` of `MolecularGraph`s) by comparing their canonical SMILES strings.\n '
smiles_list = []
for molecular_graph in molecular_graphs:
smiles = molecular_graph.get_smiles()
... | def get_fraction_unique(molecular_graphs):
' Returns the fraction (`float`) of unique graphs in `molecular_graphs`\n (`list` of `MolecularGraph`s) by comparing their canonical SMILES strings.\n '
smiles_list = []
for molecular_graph in molecular_graphs:
smiles = molecular_graph.get_smiles()
... |
f1fa62f8f50a6ec8ec1df2deff2dffccce49f0c90c4e40be335dd7584c67c2dd | def get_fraction_valid(molecular_graphs, termination):
" Determines which graphs in `molecular_graphs` (`list` of `MolecularGraph`s)\n correspond to valid molecular structures. Uses RDKit which admittedly isn't\n perfect. `termination` is a `torch.Tensor` containing 0s or 1s corresponding\n to the validity... | Determines which graphs in `molecular_graphs` (`list` of `MolecularGraph`s)
correspond to valid molecular structures. Uses RDKit which admittedly isn't
perfect. `termination` is a `torch.Tensor` containing 0s or 1s corresponding
to the validity of the structures in `molecular_graphs`.
Returns:
fraction_valid (float)... | fine-tuning/analyze.py | get_fraction_valid | olsson-group/RL-GraphINVENT | 18 | python | def get_fraction_valid(molecular_graphs, termination):
" Determines which graphs in `molecular_graphs` (`list` of `MolecularGraph`s)\n correspond to valid molecular structures. Uses RDKit which admittedly isn't\n perfect. `termination` is a `torch.Tensor` containing 0s or 1s corresponding\n to the validity... | def get_fraction_valid(molecular_graphs, termination):
" Determines which graphs in `molecular_graphs` (`list` of `MolecularGraph`s)\n correspond to valid molecular structures. Uses RDKit which admittedly isn't\n perfect. `termination` is a `torch.Tensor` containing 0s or 1s corresponding\n to the validity... |
5751ffd3a3bff8310a30f50ccfbabdb15815fc56863a3a06d5be201521e39ad0 | def get_molecular_properties(molecules, epoch_key, termination=None):
' Calculates properties for input `molecules` (`list` of `MolecularGraph`s).\n Properties include the distribution in number of nodes per molecule, the\n distribution of atom types, the distribution of edge features (bond types),\n the d... | Calculates properties for input `molecules` (`list` of `MolecularGraph`s).
Properties include the distribution in number of nodes per molecule, the
distribution of atom types, the distribution of edge features (bond types),
the distribution of the chirality (if used), and the fraction of unique
molecules.
Args:
mole... | fine-tuning/analyze.py | get_molecular_properties | olsson-group/RL-GraphINVENT | 18 | python | def get_molecular_properties(molecules, epoch_key, termination=None):
' Calculates properties for input `molecules` (`list` of `MolecularGraph`s).\n Properties include the distribution in number of nodes per molecule, the\n distribution of atom types, the distribution of edge features (bond types),\n the d... | def get_molecular_properties(molecules, epoch_key, termination=None):
' Calculates properties for input `molecules` (`list` of `MolecularGraph`s).\n Properties include the distribution in number of nodes per molecule, the\n distribution of atom types, the distribution of edge features (bond types),\n the d... |
98a4bd61ebde3d467cde9c2b5fc223d467a678441b9c670004050a6f568f9339 | def combine_ts_properties(prev_properties, next_properties, weight_next):
' Averages the properties of `prev_properties` and `next_properties` (both\n `dict`s). This is used when calculating the properties of the training set\n in separate "groups", as is done in `create_h5py_file()`.\n\n Args:\n prev... | Averages the properties of `prev_properties` and `next_properties` (both
`dict`s). This is used when calculating the properties of the training set
in separate "groups", as is done in `create_h5py_file()`.
Args:
prev_properties (dict) : Dictionary of old training set properties.
next_properties (dict) : Dictionary... | fine-tuning/analyze.py | combine_ts_properties | olsson-group/RL-GraphINVENT | 18 | python | def combine_ts_properties(prev_properties, next_properties, weight_next):
' Averages the properties of `prev_properties` and `next_properties` (both\n `dict`s). This is used when calculating the properties of the training set\n in separate "groups", as is done in `create_h5py_file()`.\n\n Args:\n prev... | def combine_ts_properties(prev_properties, next_properties, weight_next):
' Averages the properties of `prev_properties` and `next_properties` (both\n `dict`s). This is used when calculating the properties of the training set\n in separate "groups", as is done in `create_h5py_file()`.\n\n Args:\n prev... |
7181a106bfeec7e4c9d1d1741811f685320c4dadb90cc602bcfffdc45731d21e | def weighted_average(b, key):
'Takes a weighted average of two training set property dictionaries.\n\n Args:\n b (tuple) : Bundle of the following four items:\n p (dict) : "Previous" dictionary.\n n (dict) : "Next" dictionary.\n wp (int) : Weight for `p`.\n wn (int) : Weight for ... | Takes a weighted average of two training set property dictionaries.
Args:
b (tuple) : Bundle of the following four items:
p (dict) : "Previous" dictionary.
n (dict) : "Next" dictionary.
wp (int) : Weight for `p`.
wn (int) : Weight for `n`.
key (str) : 2nd string in the tuple keys.
Returns:
weigh... | fine-tuning/analyze.py | weighted_average | olsson-group/RL-GraphINVENT | 18 | python | def weighted_average(b, key):
'Takes a weighted average of two training set property dictionaries.\n\n Args:\n b (tuple) : Bundle of the following four items:\n p (dict) : "Previous" dictionary.\n n (dict) : "Next" dictionary.\n wp (int) : Weight for `p`.\n wn (int) : Weight for ... | def weighted_average(b, key):
'Takes a weighted average of two training set property dictionaries.\n\n Args:\n b (tuple) : Bundle of the following four items:\n p (dict) : "Previous" dictionary.\n n (dict) : "Next" dictionary.\n wp (int) : Weight for `p`.\n wn (int) : Weight for ... |
32d06cdae4e324ad63c0e0f59ae8414991aaa5eaaabf7d4198f4cfb634acbb21 | def get_n_edges_distribution(molecular_graphs, n_edges_to_bin=10):
' Returns a histogram of the number of edges per node present in the\n `molecular_graphs` (`list` of `MolecularGraph`s). The histogram is a `list`\n where the first item corresponds to the count of the number of nodes with one\n edge, the s... | Returns a histogram of the number of edges per node present in the
`molecular_graphs` (`list` of `MolecularGraph`s). The histogram is a `list`
where the first item corresponds to the count of the number of nodes with one
edge, the second item to the count of the number of nodes with two edges,
etc, up until the count o... | fine-tuning/analyze.py | get_n_edges_distribution | olsson-group/RL-GraphINVENT | 18 | python | def get_n_edges_distribution(molecular_graphs, n_edges_to_bin=10):
' Returns a histogram of the number of edges per node present in the\n `molecular_graphs` (`list` of `MolecularGraph`s). The histogram is a `list`\n where the first item corresponds to the count of the number of nodes with one\n edge, the s... | def get_n_edges_distribution(molecular_graphs, n_edges_to_bin=10):
' Returns a histogram of the number of edges per node present in the\n `molecular_graphs` (`list` of `MolecularGraph`s). The histogram is a `list`\n where the first item corresponds to the count of the number of nodes with one\n edge, the s... |
a34723154a64f06aac4050bcf261751225dd7a0aeb18dd536900adee4f948736 | def get_n_nodes_distribution(molecular_graphs):
' Returns a histogram of the number of nodes per graph present in the\n `molecular_graphs` (`list` of `MolecularGraph`s). The histogram is a `list`\n where the first item corresponds to the count of the number of graphs with\n one node, the second item corres... | Returns a histogram of the number of nodes per graph present in the
`molecular_graphs` (`list` of `MolecularGraph`s). The histogram is a `list`
where the first item corresponds to the count of the number of graphs with
one node, the second item corresponds to the count of the number of graphs
with two nodes, etc, up un... | fine-tuning/analyze.py | get_n_nodes_distribution | olsson-group/RL-GraphINVENT | 18 | python | def get_n_nodes_distribution(molecular_graphs):
' Returns a histogram of the number of nodes per graph present in the\n `molecular_graphs` (`list` of `MolecularGraph`s). The histogram is a `list`\n where the first item corresponds to the count of the number of graphs with\n one node, the second item corres... | def get_n_nodes_distribution(molecular_graphs):
' Returns a histogram of the number of nodes per graph present in the\n `molecular_graphs` (`list` of `MolecularGraph`s). The histogram is a `list`\n where the first item corresponds to the count of the number of graphs with\n one node, the second item corres... |
0c33e14bb22c0c8769599c357e4b3968794f9ae22c1c5d781567818862b568dc | def get_node_feature_distribution(molecular_graphs):
' Returns a `tuple` of histograms (`torch.Tensor`s) for atom types, formal\n charges, number of implicit Hs, and chiral states that are present in the\n input `molecular_graphs` (`list` of `MolecularGraph`s). Each histogram is a\n `list` where the nth it... | Returns a `tuple` of histograms (`torch.Tensor`s) for atom types, formal
charges, number of implicit Hs, and chiral states that are present in the
input `molecular_graphs` (`list` of `MolecularGraph`s). Each histogram is a
`list` where the nth item corresponds to the count of the nth property in
`atom_types`, `formal_c... | fine-tuning/analyze.py | get_node_feature_distribution | olsson-group/RL-GraphINVENT | 18 | python | def get_node_feature_distribution(molecular_graphs):
' Returns a `tuple` of histograms (`torch.Tensor`s) for atom types, formal\n charges, number of implicit Hs, and chiral states that are present in the\n input `molecular_graphs` (`list` of `MolecularGraph`s). Each histogram is a\n `list` where the nth it... | def get_node_feature_distribution(molecular_graphs):
' Returns a `tuple` of histograms (`torch.Tensor`s) for atom types, formal\n charges, number of implicit Hs, and chiral states that are present in the\n input `molecular_graphs` (`list` of `MolecularGraph`s). Each histogram is a\n `list` where the nth it... |
96005f8a0f338e11bda2923f701e760cbe50730900b35cd0a450bf689d4d05ca | def get_validation_nll(dataloader, model):
' Computes validation NLL (e.g. the NLL for taking the "correct" action\n for a specific fragment/atom) for graphs in the validation and training sets\n (whichever is specified by the `dataloader`). The subsets are equal in size\n to the number of structures gener... | Computes validation NLL (e.g. the NLL for taking the "correct" action
for a specific fragment/atom) for graphs in the validation and training sets
(whichever is specified by the `dataloader`). The subsets are equal in size
to the number of structures generated per batch (`n_samples` below). Note:
do not use for generat... | fine-tuning/analyze.py | get_validation_nll | olsson-group/RL-GraphINVENT | 18 | python | def get_validation_nll(dataloader, model):
' Computes validation NLL (e.g. the NLL for taking the "correct" action\n for a specific fragment/atom) for graphs in the validation and training sets\n (whichever is specified by the `dataloader`). The subsets are equal in size\n to the number of structures gener... | def get_validation_nll(dataloader, model):
' Computes validation NLL (e.g. the NLL for taking the "correct" action\n for a specific fragment/atom) for graphs in the validation and training sets\n (whichever is specified by the `dataloader`). The subsets are equal in size\n to the number of structures gener... |
a9eecb569ad6c352682058c6d0c048c44c7a0a3028ec3557bf7894410bb13680 | def plot_molecular_properties(properties_dict, plot_filename):
' Plots a 3 by 3 grid of the histograms in `properties_dict` using\n separate colors for the training set and for each epoch.\n\n Args:\n properties_dict (dict) : Contains properties of generated and training\n set molecules. Only plot... | Plots a 3 by 3 grid of the histograms in `properties_dict` using
separate colors for the training set and for each epoch.
Args:
properties_dict (dict) : Contains properties of generated and training
set molecules. Only plots histogram properties, not averages.
plot_filename (str) : Full path/filename for savin... | fine-tuning/analyze.py | plot_molecular_properties | olsson-group/RL-GraphINVENT | 18 | python | def plot_molecular_properties(properties_dict, plot_filename):
' Plots a 3 by 3 grid of the histograms in `properties_dict` using\n separate colors for the training set and for each epoch.\n\n Args:\n properties_dict (dict) : Contains properties of generated and training\n set molecules. Only plot... | def plot_molecular_properties(properties_dict, plot_filename):
' Plots a 3 by 3 grid of the histograms in `properties_dict` using\n separate colors for the training set and for each epoch.\n\n Args:\n properties_dict (dict) : Contains properties of generated and training\n set molecules. Only plot... |
cbcfc73a75664fce8f4912fb237ba27630a6b2ba5f380b1f1cc62b15f1e7261c | def uc_jsd(nll_valid, nll_train, nll_sampled):
' Computes the UC-JSD (metric used for the benchmark of generative models\n in Arús-Pous, J. et al., J. Chem. Inf., 2019, 1-13).\n\n Args:\n nll_valid (torch.Tensor) : Contains NLLs for sampling the correct action\n of structures in the validation set... | Computes the UC-JSD (metric used for the benchmark of generative models
in Arús-Pous, J. et al., J. Chem. Inf., 2019, 1-13).
Args:
nll_valid (torch.Tensor) : Contains NLLs for sampling the correct action
of structures in the validation set.
nll_train (torch.Tensor) : Contains NLLs for sampling the correct acti... | fine-tuning/analyze.py | uc_jsd | olsson-group/RL-GraphINVENT | 18 | python | def uc_jsd(nll_valid, nll_train, nll_sampled):
' Computes the UC-JSD (metric used for the benchmark of generative models\n in Arús-Pous, J. et al., J. Chem. Inf., 2019, 1-13).\n\n Args:\n nll_valid (torch.Tensor) : Contains NLLs for sampling the correct action\n of structures in the validation set... | def uc_jsd(nll_valid, nll_train, nll_sampled):
' Computes the UC-JSD (metric used for the benchmark of generative models\n in Arús-Pous, J. et al., J. Chem. Inf., 2019, 1-13).\n\n Args:\n nll_valid (torch.Tensor) : Contains NLLs for sampling the correct action\n of structures in the validation set... |
04db5c4676c3bd5600b687192b2bdd48c7614f6b30e7f78d5f1aa889c98a3a56 | def __init__(self, configuration):
"Construct the pipeline.\n\n Parameters\n ----------\n configuration : dict-like\n Configuration for the lightcone simulation.\n\n Notes\n -----\n 'configuration' should contain an entry 'lightcone' which is a\n dictionar... | Construct the pipeline.
Parameters
----------
configuration : dict-like
Configuration for the lightcone simulation.
Notes
-----
'configuration' should contain an entry 'lightcone' which is a
dictionary defining 'z_min', 'z_max' and 'n_slice'. These are the
minimum and maximum redshift of the simulation and the nu... | skypy/pipeline/_lightcone.py | __init__ | ArthurTolley/skypy | 1 | python | def __init__(self, configuration):
"Construct the pipeline.\n\n Parameters\n ----------\n configuration : dict-like\n Configuration for the lightcone simulation.\n\n Notes\n -----\n 'configuration' should contain an entry 'lightcone' which is a\n dictionar... | def __init__(self, configuration):
"Construct the pipeline.\n\n Parameters\n ----------\n configuration : dict-like\n Configuration for the lightcone simulation.\n\n Notes\n -----\n 'configuration' should contain an entry 'lightcone' which is a\n dictionar... |
7822a975ed81089552f91361cfe16a011e6a1991dcc1e5fd03ef84a6b0c15c83 | def write(self, file_format=None, overwrite=False):
'Write pipeline results to disk.\n\n Parameters\n ----------\n file_format : str\n File format used to write tables. Files are written using the\n Astropy unified file read/write interface; see [1]_ for supported\n ... | Write pipeline results to disk.
Parameters
----------
file_format : str
File format used to write tables. Files are written using the
Astropy unified file read/write interface; see [1]_ for supported
file formats. If None (default) tables are not written to file.
overwrite : bool
Whether to overwrite a... | skypy/pipeline/_lightcone.py | write | ArthurTolley/skypy | 1 | python | def write(self, file_format=None, overwrite=False):
'Write pipeline results to disk.\n\n Parameters\n ----------\n file_format : str\n File format used to write tables. Files are written using the\n Astropy unified file read/write interface; see [1]_ for supported\n ... | def write(self, file_format=None, overwrite=False):
'Write pipeline results to disk.\n\n Parameters\n ----------\n file_format : str\n File format used to write tables. Files are written using the\n Astropy unified file read/write interface; see [1]_ for supported\n ... |
280c2e91601f55681ce94566e8147c3341a1d2cec0143e6f3e0dbebcd2da4f25 | def compute_kernel_bias(vecs, n_components):
'计算kernel和bias\n 最后的变换:y = (x + bias).dot(kernel)\n '
vecs = np.concatenate(vecs, axis=0)
mu = vecs.mean(axis=0, keepdims=True)
cov = np.cov(vecs.T)
(u, s, vh) = np.linalg.svd(cov)
W = np.dot(u, np.diag((s ** 0.5)))
W = np.linalg.inv(W.T)
... | 计算kernel和bias
最后的变换:y = (x + bias).dot(kernel) | bert_whitening.py | compute_kernel_bias | NTDXYG/CCGIR | 2 | python | def compute_kernel_bias(vecs, n_components):
'计算kernel和bias\n 最后的变换:y = (x + bias).dot(kernel)\n '
vecs = np.concatenate(vecs, axis=0)
mu = vecs.mean(axis=0, keepdims=True)
cov = np.cov(vecs.T)
(u, s, vh) = np.linalg.svd(cov)
W = np.dot(u, np.diag((s ** 0.5)))
W = np.linalg.inv(W.T)
... | def compute_kernel_bias(vecs, n_components):
'计算kernel和bias\n 最后的变换:y = (x + bias).dot(kernel)\n '
vecs = np.concatenate(vecs, axis=0)
mu = vecs.mean(axis=0, keepdims=True)
cov = np.cov(vecs.T)
(u, s, vh) = np.linalg.svd(cov)
W = np.dot(u, np.diag((s ** 0.5)))
W = np.linalg.inv(W.T)
... |
ed1aa151d784fd93da3d6bc490a2ceddf681b9c8b0231b44a74a8db49a3e0a6d | def transform_and_normalize(vecs, kernel, bias):
'应用变换,然后标准化\n '
if (not ((kernel is None) or (bias is None))):
vecs = (vecs + bias).dot(kernel)
return (vecs / ((vecs ** 2).sum(axis=1, keepdims=True) ** 0.5)) | 应用变换,然后标准化 | bert_whitening.py | transform_and_normalize | NTDXYG/CCGIR | 2 | python | def transform_and_normalize(vecs, kernel, bias):
'\n '
if (not ((kernel is None) or (bias is None))):
vecs = (vecs + bias).dot(kernel)
return (vecs / ((vecs ** 2).sum(axis=1, keepdims=True) ** 0.5)) | def transform_and_normalize(vecs, kernel, bias):
'\n '
if (not ((kernel is None) or (bias is None))):
vecs = (vecs + bias).dot(kernel)
return (vecs / ((vecs ** 2).sum(axis=1, keepdims=True) ** 0.5))<|docstring|>应用变换,然后标准化<|endoftext|> |
10629e95e3dd04ea46669dc23035757d4bafb258be0c7392e034850318022595 | def normalize(vecs):
'标准化\n '
return (vecs / ((vecs ** 2).sum(axis=1, keepdims=True) ** 0.5)) | 标准化 | bert_whitening.py | normalize | NTDXYG/CCGIR | 2 | python | def normalize(vecs):
'\n '
return (vecs / ((vecs ** 2).sum(axis=1, keepdims=True) ** 0.5)) | def normalize(vecs):
'\n '
return (vecs / ((vecs ** 2).sum(axis=1, keepdims=True) ** 0.5))<|docstring|>标准化<|endoftext|> |
8109c1d2e75cde6d57a6068a63b70a7c213b9be75c9d4794b5ead0ffe2db87e0 | def get_queryset(self, request):
'Prefetch profile data'
return super(UserAdmin, self).get_queryset(request).select_related('profile') | Prefetch profile data | src/users/admin.py | get_queryset | hutomadotAI/web-console | 6 | python | def get_queryset(self, request):
return super(UserAdmin, self).get_queryset(request).select_related('profile') | def get_queryset(self, request):
return super(UserAdmin, self).get_queryset(request).select_related('profile')<|docstring|>Prefetch profile data<|endoftext|> |
93d79dbe1359a1293e10f466e4fd811ecec4fa5d5789cc54dd069fdbe9982b72 | def __init__(self, ai_settings):
'Initialize statistics.'
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = True | Initialize statistics. | game_stats.py | __init__ | simonhoch/my_football_game | 0 | python | def __init__(self, ai_settings):
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = True | def __init__(self, ai_settings):
self.ai_settings = ai_settings
self.reset_stats()
self.game_active = True<|docstring|>Initialize statistics.<|endoftext|> |
d5952ff44d8c8ad710e29d4abb665c9de3c8a504f761dc45e1708a50c0d434b2 | def reset_stats(self):
'Initialize statistics that can change during the game.'
self.attackers_left = self.ai_settings.attackers_limit | Initialize statistics that can change during the game. | game_stats.py | reset_stats | simonhoch/my_football_game | 0 | python | def reset_stats(self):
self.attackers_left = self.ai_settings.attackers_limit | def reset_stats(self):
self.attackers_left = self.ai_settings.attackers_limit<|docstring|>Initialize statistics that can change during the game.<|endoftext|> |
747415f24406cc3cf45165f21b092c72268a9c8cf9cef767a462129bd87f85f1 | def _add_storage_to_ga_task(dag, bucket_uri, ga_tracking_id, bq_dataset, bq_table):
'Adds Google Cloud Storage(GCS) to Google Analytics data transfer task.\n\n Args:\n dag: The dag object which will include this task.\n bucket_uri: The uri of the GCS path containing the data.\n ga_tracking_id: The Google ... | Adds Google Cloud Storage(GCS) to Google Analytics data transfer task.
Args:
dag: The dag object which will include this task.
bucket_uri: The uri of the GCS path containing the data.
ga_tracking_id: The Google Analytics tracking id.
bq_dataset: BQ data set.
bq_table: BQ Table for monitoring purposes.
Retur... | src/dags/subdags/activate_ga_dag.py | _add_storage_to_ga_task | google/blockbuster | 4 | python | def _add_storage_to_ga_task(dag, bucket_uri, ga_tracking_id, bq_dataset, bq_table):
'Adds Google Cloud Storage(GCS) to Google Analytics data transfer task.\n\n Args:\n dag: The dag object which will include this task.\n bucket_uri: The uri of the GCS path containing the data.\n ga_tracking_id: The Google ... | def _add_storage_to_ga_task(dag, bucket_uri, ga_tracking_id, bq_dataset, bq_table):
'Adds Google Cloud Storage(GCS) to Google Analytics data transfer task.\n\n Args:\n dag: The dag object which will include this task.\n bucket_uri: The uri of the GCS path containing the data.\n ga_tracking_id: The Google ... |
38bc8c27e496798579121a5630d2d10c1e1cdab98ca21f0fbb446570973c1592 | def create_dag(args: Mapping[(str, Any)], parent_dag_name: Optional[str]=None) -> models.DAG:
'Generates a DAG that pushes data from Google Cloud Storage to GA.\n\n Args:\n args: Arguments to provide to the Airflow DAG object as defaults.\n parent_dag_name: If this is provided, this is a SubDAG.\n\n Returns... | Generates a DAG that pushes data from Google Cloud Storage to GA.
Args:
args: Arguments to provide to the Airflow DAG object as defaults.
parent_dag_name: If this is provided, this is a SubDAG.
Returns:
The DAG object. | src/dags/subdags/activate_ga_dag.py | create_dag | google/blockbuster | 4 | python | def create_dag(args: Mapping[(str, Any)], parent_dag_name: Optional[str]=None) -> models.DAG:
'Generates a DAG that pushes data from Google Cloud Storage to GA.\n\n Args:\n args: Arguments to provide to the Airflow DAG object as defaults.\n parent_dag_name: If this is provided, this is a SubDAG.\n\n Returns... | def create_dag(args: Mapping[(str, Any)], parent_dag_name: Optional[str]=None) -> models.DAG:
'Generates a DAG that pushes data from Google Cloud Storage to GA.\n\n Args:\n args: Arguments to provide to the Airflow DAG object as defaults.\n parent_dag_name: If this is provided, this is a SubDAG.\n\n Returns... |
6f99154938d0cafd5f6b2cf2020f9f0c7bb3eb2c8921cf0637f00fefa8228fba | @nottest
def dict_comparer(dict_a, dict_b):
'\n yield keywise tests for dict equality, making it easy to see what is going on\n '
if (not hasattr(dict_a, 'keys')):
raise AssertionError("left operand doesn't look like a dict")
if (not hasattr(dict_b, 'keys')):
raise AssertionError("righ... | yield keywise tests for dict equality, making it easy to see what is going on | mongosearch/tests/_util.py | dict_comparer | ixc/python-mongo-search | 0 | python | @nottest
def dict_comparer(dict_a, dict_b):
'\n \n '
if (not hasattr(dict_a, 'keys')):
raise AssertionError("left operand doesn't look like a dict")
if (not hasattr(dict_b, 'keys')):
raise AssertionError("right operand doesn't look like a dict")
for key in dict_a.keys():
(y... | @nottest
def dict_comparer(dict_a, dict_b):
'\n \n '
if (not hasattr(dict_a, 'keys')):
raise AssertionError("left operand doesn't look like a dict")
if (not hasattr(dict_b, 'keys')):
raise AssertionError("right operand doesn't look like a dict")
for key in dict_a.keys():
(y... |
bb02c70bbeba186760ea458cafc7d5838e13812ae2c3fc2c48ab2990e31aaf0a | def testExternalRepoCheckout(self):
'Test we detect external checkouts properly.'
tests = ['https://chromium.googlesource.com/chromiumos/manifest.git', 'example@example.com:39291/bla/manifest.git', 'example@example.com:39291/bla/manifest', 'example@example.com:39291/bla/Manifest-internal']
for test in tests... | Test we detect external checkouts properly. | third_party/chromite/cbuildbot/repository_unittest.py | testExternalRepoCheckout | zipated/src | 2,151 | python | def testExternalRepoCheckout(self):
tests = ['https://chromium.googlesource.com/chromiumos/manifest.git', 'example@example.com:39291/bla/manifest.git', 'example@example.com:39291/bla/manifest', 'example@example.com:39291/bla/Manifest-internal']
for test in tests:
self.rc.SetDefaultCmdResult(output=... | def testExternalRepoCheckout(self):
tests = ['https://chromium.googlesource.com/chromiumos/manifest.git', 'example@example.com:39291/bla/manifest.git', 'example@example.com:39291/bla/manifest', 'example@example.com:39291/bla/Manifest-internal']
for test in tests:
self.rc.SetDefaultCmdResult(output=... |
23b144dff9ed5bbe36cc1e7553839ea1965fc86be65e070eeff8dc9761863935 | def testInternalRepoCheckout(self):
'Test we detect internal checkouts properly.'
tests = ['https://chrome-internal.googlesource.com/chromeos/manifest-internal', 'example@example.com:39291/bla/manifest-internal.git']
for test in tests:
self.rc.SetDefaultCmdResult(output=test)
self.assertTrue... | Test we detect internal checkouts properly. | third_party/chromite/cbuildbot/repository_unittest.py | testInternalRepoCheckout | zipated/src | 2,151 | python | def testInternalRepoCheckout(self):
tests = ['https://chrome-internal.googlesource.com/chromeos/manifest-internal', 'example@example.com:39291/bla/manifest-internal.git']
for test in tests:
self.rc.SetDefaultCmdResult(output=test)
self.assertTrue(repository.IsInternalRepoCheckout('.')) | def testInternalRepoCheckout(self):
tests = ['https://chrome-internal.googlesource.com/chromeos/manifest-internal', 'example@example.com:39291/bla/manifest-internal.git']
for test in tests:
self.rc.SetDefaultCmdResult(output=test)
self.assertTrue(repository.IsInternalRepoCheckout('.'))<|doc... |
b5fed7012a40da869bacb8aa9e3d975360a87c2f52f4bbd4d16771aea7782319 | def testIsLocalPath(self):
'test IsLocalPath.'
self.assertTrue(repository._IsLocalPath('/tmp/chromiumos/'))
self.assertTrue(repository._IsLocalPath('file:///chromiumos/'))
self.assertFalse(repository._IsLocalPath('https://chromiumos/'))
self.assertFalse(repository._IsLocalPath('http://chromiumos/'))... | test IsLocalPath. | third_party/chromite/cbuildbot/repository_unittest.py | testIsLocalPath | zipated/src | 2,151 | python | def testIsLocalPath(self):
self.assertTrue(repository._IsLocalPath('/tmp/chromiumos/'))
self.assertTrue(repository._IsLocalPath('file:///chromiumos/'))
self.assertFalse(repository._IsLocalPath('https://chromiumos/'))
self.assertFalse(repository._IsLocalPath('http://chromiumos/'))
self.assertFal... | def testIsLocalPath(self):
self.assertTrue(repository._IsLocalPath('/tmp/chromiumos/'))
self.assertTrue(repository._IsLocalPath('file:///chromiumos/'))
self.assertFalse(repository._IsLocalPath('https://chromiumos/'))
self.assertFalse(repository._IsLocalPath('http://chromiumos/'))
self.assertFal... |
9b47b9b87323014cc4ba345190eb38ebf5daba80bd55139cd53dd3ad241a5f28 | @cros_test_lib.NetworkTest()
def testReInitialization(self):
'Test ability to switch between branches.'
self._Initialize('release-R19-2046.B')
self._Initialize('master')
self.assertRaises(Exception, self._Initialize, 'monkey')
self._Initialize('release-R20-2268.B') | Test ability to switch between branches. | third_party/chromite/cbuildbot/repository_unittest.py | testReInitialization | zipated/src | 2,151 | python | @cros_test_lib.NetworkTest()
def testReInitialization(self):
self._Initialize('release-R19-2046.B')
self._Initialize('master')
self.assertRaises(Exception, self._Initialize, 'monkey')
self._Initialize('release-R20-2268.B') | @cros_test_lib.NetworkTest()
def testReInitialization(self):
self._Initialize('release-R19-2046.B')
self._Initialize('master')
self.assertRaises(Exception, self._Initialize, 'monkey')
self._Initialize('release-R20-2268.B')<|docstring|>Test ability to switch between branches.<|endoftext|> |
ab2aa4c5919a1c8768bfa625e466e66c7d69531eafc48c73a598dec4763dcbbb | def testInitializationWithRepoInitRetry(self):
'Test Initialization with repo init retry.'
self.PatchObject(repository.RepoRepository, '_RepoSelfupdate')
mock_cleanup = self.PatchObject(repository.RepoRepository, '_CleanUpRepoManifest')
error_result = cros_build_lib.CommandResult(cmd=['cmd'], returncode... | Test Initialization with repo init retry. | third_party/chromite/cbuildbot/repository_unittest.py | testInitializationWithRepoInitRetry | zipated/src | 2,151 | python | def testInitializationWithRepoInitRetry(self):
self.PatchObject(repository.RepoRepository, '_RepoSelfupdate')
mock_cleanup = self.PatchObject(repository.RepoRepository, '_CleanUpRepoManifest')
error_result = cros_build_lib.CommandResult(cmd=['cmd'], returncode=1)
ex = cros_build_lib.RunCommandError... | def testInitializationWithRepoInitRetry(self):
self.PatchObject(repository.RepoRepository, '_RepoSelfupdate')
mock_cleanup = self.PatchObject(repository.RepoRepository, '_CleanUpRepoManifest')
error_result = cros_build_lib.CommandResult(cmd=['cmd'], returncode=1)
ex = cros_build_lib.RunCommandError... |
b71bf77ac610723f2e6e5fdb57def566208f08d9f405bc15a103f4eff21c6367 | def testInitializationWithoutRepoInitRetry(self):
'Test Initialization without repo init retry.'
self.PatchObject(repository.RepoRepository, '_RepoSelfupdate')
mock_cleanup = self.PatchObject(repository.RepoRepository, '_CleanUpRepoManifest')
mock_init = self.PatchObject(cros_build_lib, 'RunCommand')
... | Test Initialization without repo init retry. | third_party/chromite/cbuildbot/repository_unittest.py | testInitializationWithoutRepoInitRetry | zipated/src | 2,151 | python | def testInitializationWithoutRepoInitRetry(self):
self.PatchObject(repository.RepoRepository, '_RepoSelfupdate')
mock_cleanup = self.PatchObject(repository.RepoRepository, '_CleanUpRepoManifest')
mock_init = self.PatchObject(cros_build_lib, 'RunCommand')
self._Initialize()
self.assertEqual(mock... | def testInitializationWithoutRepoInitRetry(self):
self.PatchObject(repository.RepoRepository, '_RepoSelfupdate')
mock_cleanup = self.PatchObject(repository.RepoRepository, '_CleanUpRepoManifest')
mock_init = self.PatchObject(cros_build_lib, 'RunCommand')
self._Initialize()
self.assertEqual(mock... |
dcf66529102d0c247110cdc00a96b3cff020ecdd889e99afac68234736e43f09 | def testCreateManifestRepo(self):
'Test we can create a local git repository with a local manifest.'
CONTENTS = 'manifest contents'
src_manifest = os.path.join(self.tempdir, 'src_manifest')
git_repo = os.path.join(self.tempdir, 'git_repo')
dst_manifest = os.path.join(git_repo, 'default.xml')
osu... | Test we can create a local git repository with a local manifest. | third_party/chromite/cbuildbot/repository_unittest.py | testCreateManifestRepo | zipated/src | 2,151 | python | def testCreateManifestRepo(self):
CONTENTS = 'manifest contents'
src_manifest = os.path.join(self.tempdir, 'src_manifest')
git_repo = os.path.join(self.tempdir, 'git_repo')
dst_manifest = os.path.join(git_repo, 'default.xml')
osutils.WriteFile(src_manifest, CONTENTS)
repository.PrepManifest... | def testCreateManifestRepo(self):
CONTENTS = 'manifest contents'
src_manifest = os.path.join(self.tempdir, 'src_manifest')
git_repo = os.path.join(self.tempdir, 'git_repo')
dst_manifest = os.path.join(git_repo, 'default.xml')
osutils.WriteFile(src_manifest, CONTENTS)
repository.PrepManifest... |
9da738b5492b13d8ae630ccbf018a1ae02cb30f5b01c36d3de6b5d80cc34cc70 | def testUpdatingManifestRepo(self):
'Test we can update manifest in a local git repository.'
CONTENTS = 'manifest contents'
CONTENTS2 = 'manifest contents - PART 2'
src_manifest = os.path.join(self.tempdir, 'src_manifest')
git_repo = os.path.join(self.tempdir, 'git_repo')
dst_manifest = os.path.... | Test we can update manifest in a local git repository. | third_party/chromite/cbuildbot/repository_unittest.py | testUpdatingManifestRepo | zipated/src | 2,151 | python | def testUpdatingManifestRepo(self):
CONTENTS = 'manifest contents'
CONTENTS2 = 'manifest contents - PART 2'
src_manifest = os.path.join(self.tempdir, 'src_manifest')
git_repo = os.path.join(self.tempdir, 'git_repo')
dst_manifest = os.path.join(git_repo, 'default.xml')
osutils.WriteFile(src_... | def testUpdatingManifestRepo(self):
CONTENTS = 'manifest contents'
CONTENTS2 = 'manifest contents - PART 2'
src_manifest = os.path.join(self.tempdir, 'src_manifest')
git_repo = os.path.join(self.tempdir, 'git_repo')
dst_manifest = os.path.join(git_repo, 'default.xml')
osutils.WriteFile(src_... |
b5ed501915cb79f18654196f857f39fac4e7eb4499623ad0d55497a99bcad22d | def testSyncWithException(self):
'Test Sync retry on repo network sync failure'
self.PatchObject(repository.RepoRepository, '_ForceSyncSupported', return_value=True)
result = cros_build_lib.CommandResult(cmd=['cmd'], returncode=0, error='error')
ex = cros_build_lib.RunCommandError('msg', result)
run... | Test Sync retry on repo network sync failure | third_party/chromite/cbuildbot/repository_unittest.py | testSyncWithException | zipated/src | 2,151 | python | def testSyncWithException(self):
self.PatchObject(repository.RepoRepository, '_ForceSyncSupported', return_value=True)
result = cros_build_lib.CommandResult(cmd=['cmd'], returncode=0, error='error')
ex = cros_build_lib.RunCommandError('msg', result)
run_cmd_mock = self.PatchObject(cros_build_lib, '... | def testSyncWithException(self):
self.PatchObject(repository.RepoRepository, '_ForceSyncSupported', return_value=True)
result = cros_build_lib.CommandResult(cmd=['cmd'], returncode=0, error='error')
ex = cros_build_lib.RunCommandError('msg', result)
run_cmd_mock = self.PatchObject(cros_build_lib, '... |
74c576c360d4be5a817ccbf82fc74e6bc6d18e6bc6636313492042647dd9792c | def testSyncWithoutException(self):
'Test successful repo sync without exception and retry'
self.PatchObject(repository.RepoRepository, '_ForceSyncSupported', return_value=False)
run_cmd_mock = self.PatchObject(cros_build_lib, 'RunCommand')
self.repo.Sync(local_manifest='local_manifest', network_only=Tr... | Test successful repo sync without exception and retry | third_party/chromite/cbuildbot/repository_unittest.py | testSyncWithoutException | zipated/src | 2,151 | python | def testSyncWithoutException(self):
self.PatchObject(repository.RepoRepository, '_ForceSyncSupported', return_value=False)
run_cmd_mock = self.PatchObject(cros_build_lib, 'RunCommand')
self.repo.Sync(local_manifest='local_manifest', network_only=True)
self.assertEqual(run_cmd_mock.call_count, 1) | def testSyncWithoutException(self):
self.PatchObject(repository.RepoRepository, '_ForceSyncSupported', return_value=False)
run_cmd_mock = self.PatchObject(cros_build_lib, 'RunCommand')
self.repo.Sync(local_manifest='local_manifest', network_only=True)
self.assertEqual(run_cmd_mock.call_count, 1)<|d... |
d924c14c9a131f479c5fb2d528d808d6cc6bf46a5522f9ca96ffe85a90fa09af | def testForceSyncWorks(self):
'Test the --force-sync probe logic'
m = self.PatchObject(cros_build_lib, 'RunCommand')
m.return_value = cros_build_lib.CommandResult(output='Nope!')
self.assertFalse(self.repo._ForceSyncSupported())
help_fragment = '\n -f, --force-broken continue sync even if a proj... | Test the --force-sync probe logic | third_party/chromite/cbuildbot/repository_unittest.py | testForceSyncWorks | zipated/src | 2,151 | python | def testForceSyncWorks(self):
m = self.PatchObject(cros_build_lib, 'RunCommand')
m.return_value = cros_build_lib.CommandResult(output='Nope!')
self.assertFalse(self.repo._ForceSyncSupported())
help_fragment = '\n -f, --force-broken continue sync even if a project fails to sync\n --force-sync ... | def testForceSyncWorks(self):
m = self.PatchObject(cros_build_lib, 'RunCommand')
m.return_value = cros_build_lib.CommandResult(output='Nope!')
self.assertFalse(self.repo._ForceSyncSupported())
help_fragment = '\n -f, --force-broken continue sync even if a project fails to sync\n --force-sync ... |
feffd7584ea0cab499dae8dbbf3bda039be844ea305425f72824dd0ef4e66d8f | def test_RepoSelfupdateRaisesWarning(self):
'Test _RepoSelfupdate when repo version warning is raised.'
warnning_stderr = "\ninfo: A new version of repo is available\n\n...\n\ngpg: Can't check signature: public key not found\n\n...\n\nwarning: Skipped upgrade to unverified version\n"
mock_rm = self.PatchObj... | Test _RepoSelfupdate when repo version warning is raised. | third_party/chromite/cbuildbot/repository_unittest.py | test_RepoSelfupdateRaisesWarning | zipated/src | 2,151 | python | def test_RepoSelfupdateRaisesWarning(self):
warnning_stderr = "\ninfo: A new version of repo is available\n\n...\n\ngpg: Can't check signature: public key not found\n\n...\n\nwarning: Skipped upgrade to unverified version\n"
mock_rm = self.PatchObject(osutils, 'RmDir')
cmd_result = cros_build_lib.Comma... | def test_RepoSelfupdateRaisesWarning(self):
warnning_stderr = "\ninfo: A new version of repo is available\n\n...\n\ngpg: Can't check signature: public key not found\n\n...\n\nwarning: Skipped upgrade to unverified version\n"
mock_rm = self.PatchObject(osutils, 'RmDir')
cmd_result = cros_build_lib.Comma... |
d89009dc581c886d99f2a207a17e6db5f8e044067c941c45fd842d33973d075a | def test_RepoSelfupdateRaisesException(self):
'Test _RepoSelfupdate when exception is raised.'
mock_rm = self.PatchObject(osutils, 'RmDir')
ex = cros_build_lib.RunCommandError('msg', cros_build_lib.CommandResult())
self.PatchObject(cros_build_lib, 'RunCommand', side_effect=ex)
self.repo._RepoSelfupd... | Test _RepoSelfupdate when exception is raised. | third_party/chromite/cbuildbot/repository_unittest.py | test_RepoSelfupdateRaisesException | zipated/src | 2,151 | python | def test_RepoSelfupdateRaisesException(self):
mock_rm = self.PatchObject(osutils, 'RmDir')
ex = cros_build_lib.RunCommandError('msg', cros_build_lib.CommandResult())
self.PatchObject(cros_build_lib, 'RunCommand', side_effect=ex)
self.repo._RepoSelfupdate()
mock_rm.assert_called_once_with(mock.A... | def test_RepoSelfupdateRaisesException(self):
mock_rm = self.PatchObject(osutils, 'RmDir')
ex = cros_build_lib.RunCommandError('msg', cros_build_lib.CommandResult())
self.PatchObject(cros_build_lib, 'RunCommand', side_effect=ex)
self.repo._RepoSelfupdate()
mock_rm.assert_called_once_with(mock.A... |
f95a0639c0b4e981eb7489609e934d5e15d4534af10d41e8a39e36d4083b601a | def has_corner_crack(x: np.array, patch_size: int=64):
' As long as there are no non-black pixels in the center of the patch, continue\n If there are, this patch does not contain a corner crack.'
if (patch_size == 64):
corner_range = range(16, 48)
else:
corner_range = range(32, 96)
... | As long as there are no non-black pixels in the center of the patch, continue
If there are, this patch does not contain a corner crack. | src/utils/filter_patches.py | has_corner_crack | JAVersteeg/Deep-SAD-PyTorch | 0 | python | def has_corner_crack(x: np.array, patch_size: int=64):
' As long as there are no non-black pixels in the center of the patch, continue\n If there are, this patch does not contain a corner crack.'
if (patch_size == 64):
corner_range = range(16, 48)
else:
corner_range = range(32, 96)
... | def has_corner_crack(x: np.array, patch_size: int=64):
' As long as there are no non-black pixels in the center of the patch, continue\n If there are, this patch does not contain a corner crack.'
if (patch_size == 64):
corner_range = range(16, 48)
else:
corner_range = range(32, 96)
... |
229f0693158d5b0d93ccecd9be6f8228bf2c9b4edf9bc51776aa8c8d78609f25 | def compute_frozen_probs(mask_list):
'\n Compute the ratio of weight probabilities exceeding the freezing threshold.\n\n Args:\n mask_list (List[Tensor]): list of binary tensors determining if weight is frozen\n\n Returns:\n Scalar Tensor\n '
num_frozen = sum((torch.sum(m) for m in mas... | Compute the ratio of weight probabilities exceeding the freezing threshold.
Args:
mask_list (List[Tensor]): list of binary tensors determining if weight is frozen
Returns:
Scalar Tensor | lib/utils.py | compute_frozen_probs | smonsays/presynaptic-stochasticity | 1 | python | def compute_frozen_probs(mask_list):
'\n Compute the ratio of weight probabilities exceeding the freezing threshold.\n\n Args:\n mask_list (List[Tensor]): list of binary tensors determining if weight is frozen\n\n Returns:\n Scalar Tensor\n '
num_frozen = sum((torch.sum(m) for m in mas... | def compute_frozen_probs(mask_list):
'\n Compute the ratio of weight probabilities exceeding the freezing threshold.\n\n Args:\n mask_list (List[Tensor]): list of binary tensors determining if weight is frozen\n\n Returns:\n Scalar Tensor\n '
num_frozen = sum((torch.sum(m) for m in mas... |
be4594b0715e43c842f921e2e2ff72c207ff88a63b4585f47f8469226fc46e49 | def compute_mean_probs(probs_list):
'\n Compute the mean weight probabilities.\n\n Args:\n probs_list (List[Tensor]): list of tensors containing probabilities\n\n Returns:\n Scalar Tensor\n '
probs_cat = torch.cat([p.view((- 1)) for p in probs_list])
return torch.mean(probs_cat) | Compute the mean weight probabilities.
Args:
probs_list (List[Tensor]): list of tensors containing probabilities
Returns:
Scalar Tensor | lib/utils.py | compute_mean_probs | smonsays/presynaptic-stochasticity | 1 | python | def compute_mean_probs(probs_list):
'\n Compute the mean weight probabilities.\n\n Args:\n probs_list (List[Tensor]): list of tensors containing probabilities\n\n Returns:\n Scalar Tensor\n '
probs_cat = torch.cat([p.view((- 1)) for p in probs_list])
return torch.mean(probs_cat) | def compute_mean_probs(probs_list):
'\n Compute the mean weight probabilities.\n\n Args:\n probs_list (List[Tensor]): list of tensors containing probabilities\n\n Returns:\n Scalar Tensor\n '
probs_cat = torch.cat([p.view((- 1)) for p in probs_list])
return torch.mean(probs_cat)<|d... |
63a3262c9f6eef83380f0bf22f09eafc16f9bfc7018f693c04a4d9e632415de1 | def create_nonlinearity(name):
'\n Return nonlinearity function given its name.\n '
if (name == 'leaky_relu'):
return torch.nn.functional.leaky_relu
elif (name == 'relu'):
return torch.nn.functional.relu
elif (name == 'sigmoid'):
return torch.sigmoid
elif (name == 'tanh... | Return nonlinearity function given its name. | lib/utils.py | create_nonlinearity | smonsays/presynaptic-stochasticity | 1 | python | def create_nonlinearity(name):
'\n \n '
if (name == 'leaky_relu'):
return torch.nn.functional.leaky_relu
elif (name == 'relu'):
return torch.nn.functional.relu
elif (name == 'sigmoid'):
return torch.sigmoid
elif (name == 'tanh'):
return torch.nn.functional.tanh
... | def create_nonlinearity(name):
'\n \n '
if (name == 'leaky_relu'):
return torch.nn.functional.leaky_relu
elif (name == 'relu'):
return torch.nn.functional.relu
elif (name == 'sigmoid'):
return torch.sigmoid
elif (name == 'tanh'):
return torch.nn.functional.tanh
... |
faf1984470a1d276c4605919e7a40c0115ba76c79b2ee419d3a3a7fa85c6a1ea | def create_optimizer(name, model, **kwargs):
'\n Return optimizer for the given model.\n '
if (name == 'adagrad'):
return torch.optim.Adagrad(model.parameters(), **kwargs)
elif (name == 'adam'):
return torch.optim.Adam(model.parameters(), **kwargs)
elif (name == 'sgd'):
ret... | Return optimizer for the given model. | lib/utils.py | create_optimizer | smonsays/presynaptic-stochasticity | 1 | python | def create_optimizer(name, model, **kwargs):
'\n \n '
if (name == 'adagrad'):
return torch.optim.Adagrad(model.parameters(), **kwargs)
elif (name == 'adam'):
return torch.optim.Adam(model.parameters(), **kwargs)
elif (name == 'sgd'):
return torch.optim.SGD(model.parameters(... | def create_optimizer(name, model, **kwargs):
'\n \n '
if (name == 'adagrad'):
return torch.optim.Adagrad(model.parameters(), **kwargs)
elif (name == 'adam'):
return torch.optim.Adam(model.parameters(), **kwargs)
elif (name == 'sgd'):
return torch.optim.SGD(model.parameters(... |
e2f507151dec2f035fb4cae7193a167401ae90a69b88bb699388a0213e1dbfc8 | def list_to_csv(mylist, filepath):
'\n Save list as csv file.\n '
with open(filepath, 'w', newline='') as f:
wr = csv.writer(f)
wr.writerow(mylist) | Save list as csv file. | lib/utils.py | list_to_csv | smonsays/presynaptic-stochasticity | 1 | python | def list_to_csv(mylist, filepath):
'\n \n '
with open(filepath, 'w', newline=) as f:
wr = csv.writer(f)
wr.writerow(mylist) | def list_to_csv(mylist, filepath):
'\n \n '
with open(filepath, 'w', newline=) as f:
wr = csv.writer(f)
wr.writerow(mylist)<|docstring|>Save list as csv file.<|endoftext|> |
668ad2a000f47cea8a093a15475892d613fbdef89f04ce27179b7c3c5a5a2a65 | def save_dict_as_json(config, name, dir):
'\n Store a dictionary as a json text file.\n '
with open(os.path.join(dir, (name + '.json')), 'w') as file:
json.dump(config, file, sort_keys=True, indent=4) | Store a dictionary as a json text file. | lib/utils.py | save_dict_as_json | smonsays/presynaptic-stochasticity | 1 | python | def save_dict_as_json(config, name, dir):
'\n \n '
with open(os.path.join(dir, (name + '.json')), 'w') as file:
json.dump(config, file, sort_keys=True, indent=4) | def save_dict_as_json(config, name, dir):
'\n \n '
with open(os.path.join(dir, (name + '.json')), 'w') as file:
json.dump(config, file, sort_keys=True, indent=4)<|docstring|>Store a dictionary as a json text file.<|endoftext|> |
faa65fd725542741bc5ba8920b01bb62e05645fd7ee9137c152aa0df77ec1320 | def show_tensor(input):
'\n Transform tensor into PIL object and show in separate window.\n '
image = torchvision.transforms.functional.to_pil_image(input)
image.show() | Transform tensor into PIL object and show in separate window. | lib/utils.py | show_tensor | smonsays/presynaptic-stochasticity | 1 | python | def show_tensor(input):
'\n \n '
image = torchvision.transforms.functional.to_pil_image(input)
image.show() | def show_tensor(input):
'\n \n '
image = torchvision.transforms.functional.to_pil_image(input)
image.show()<|docstring|>Transform tensor into PIL object and show in separate window.<|endoftext|> |
c93ee6d7802cabe7f7ed996937ff3e92682356456e519557d11f5a9925232564 | def vector_angle(a, b):
'\n Compute the angle between two vectors.\n '
cos_theta = torch.nn.functional.cosine_similarity(a, b, dim=0)
angle_radians = torch.acos(cos_theta)
return (180 * (angle_radians / math.pi)) | Compute the angle between two vectors. | lib/utils.py | vector_angle | smonsays/presynaptic-stochasticity | 1 | python | def vector_angle(a, b):
'\n \n '
cos_theta = torch.nn.functional.cosine_similarity(a, b, dim=0)
angle_radians = torch.acos(cos_theta)
return (180 * (angle_radians / math.pi)) | def vector_angle(a, b):
'\n \n '
cos_theta = torch.nn.functional.cosine_similarity(a, b, dim=0)
angle_radians = torch.acos(cos_theta)
return (180 * (angle_radians / math.pi))<|docstring|>Compute the angle between two vectors.<|endoftext|> |
99c049562796dfc361b0708ba0c622ff051cd031cad64487af9938fef32470c0 | def main(config_file):
'Main entry function to the toolbox'
with open(config_file) as file:
config = json.load(file)
config = Config(RunConfig().load(config))
model = None
if config.model:
model_cls = get_class(config.model.classname)
model = model_cls(config.model.config)
... | Main entry function to the toolbox | aitlas/run.py | main | alex-hayhoe/aitlas-docker | 1 | python | def main(config_file):
with open(config_file) as file:
config = json.load(file)
config = Config(RunConfig().load(config))
model = None
if config.model:
model_cls = get_class(config.model.classname)
model = model_cls(config.model.config)
model.prepare()
task_cls =... | def main(config_file):
with open(config_file) as file:
config = json.load(file)
config = Config(RunConfig().load(config))
model = None
if config.model:
model_cls = get_class(config.model.classname)
model = model_cls(config.model.config)
model.prepare()
task_cls =... |
1797553260c32a48f4d85353ab441a21a8ae1d6147bc34ac4814513f7162228b | def restoreIpAddresses(self, s):
'\n :type s: str\n :rtype: List[str]\n '
(length, res) = (len(s), [])
self.recur(s, res, '', 0, 0, length)
return res | :type s: str
:rtype: List[str] | LeetCode/2018-12-26-93-Restore-IP-Addresses.py | restoreIpAddresses | HeRuivio/Algorithm | 5 | python | def restoreIpAddresses(self, s):
'\n :type s: str\n :rtype: List[str]\n '
(length, res) = (len(s), [])
self.recur(s, res, , 0, 0, length)
return res | def restoreIpAddresses(self, s):
'\n :type s: str\n :rtype: List[str]\n '
(length, res) = (len(s), [])
self.recur(s, res, , 0, 0, length)
return res<|docstring|>:type s: str
:rtype: List[str]<|endoftext|> |
a0adee2242a90d1487f6509d7bc395376dc423aeec4b33873f4f47cb8daeb344 | def maximumBeauty(self, flowers):
'\n :type flowers: List[int]\n :rtype: int\n '
lookup = {}
prefix = [0]
result = float('-inf')
for (i, f) in enumerate(flowers):
prefix.append(((prefix[(- 1)] + f) if (f > 0) else prefix[(- 1)]))
if (not (f in lookup)):
... | :type flowers: List[int]
:rtype: int | Python/maximize-the-beauty-of-the-garden.py | maximumBeauty | akashmathur-2212/LeetCode-Solutions | 3,269 | python | def maximumBeauty(self, flowers):
'\n :type flowers: List[int]\n :rtype: int\n '
lookup = {}
prefix = [0]
result = float('-inf')
for (i, f) in enumerate(flowers):
prefix.append(((prefix[(- 1)] + f) if (f > 0) else prefix[(- 1)]))
if (not (f in lookup)):
... | def maximumBeauty(self, flowers):
'\n :type flowers: List[int]\n :rtype: int\n '
lookup = {}
prefix = [0]
result = float('-inf')
for (i, f) in enumerate(flowers):
prefix.append(((prefix[(- 1)] + f) if (f > 0) else prefix[(- 1)]))
if (not (f in lookup)):
... |
ac79ed11efc5cc98ee6e5b3770cc4962899e349980ae02f06a141aae4a58e1c0 | @staticmethod
def get(name):
' Query a movie by last and first name '
return Movie.query.filter_by(name=name).one() | Query a movie by last and first name | server/src/repositories/movie.py | get | mounirchaabani/centrale | 0 | python | @staticmethod
def get(name):
' '
return Movie.query.filter_by(name=name).one() | @staticmethod
def get(name):
' '
return Movie.query.filter_by(name=name).one()<|docstring|>Query a movie by last and first name<|endoftext|> |
ce2d7e0e220fdffaeb28f2e429d8c7908054010a181bd797436fe5ea0350fc87 | def update(self, name, genre, year, affiche):
" Update a movie's age "
movie = self.get(name)
movie.year = year
movie.genre = genre
movie.affiche = affiche
return movie.save() | Update a movie's age | server/src/repositories/movie.py | update | mounirchaabani/centrale | 0 | python | def update(self, name, genre, year, affiche):
" "
movie = self.get(name)
movie.year = year
movie.genre = genre
movie.affiche = affiche
return movie.save() | def update(self, name, genre, year, affiche):
" "
movie = self.get(name)
movie.year = year
movie.genre = genre
movie.affiche = affiche
return movie.save()<|docstring|>Update a movie's age<|endoftext|> |
69735303bfc34cc20a3d4b6c7de8d84973a081054cd30a20dd4ab9f04964dbee | @staticmethod
def create(name, genre, year, affiche):
' Create a new movie '
movie = Movie(name=name, genre=genre, year=year, affiche=affiche)
return movie.save() | Create a new movie | server/src/repositories/movie.py | create | mounirchaabani/centrale | 0 | python | @staticmethod
def create(name, genre, year, affiche):
' '
movie = Movie(name=name, genre=genre, year=year, affiche=affiche)
return movie.save() | @staticmethod
def create(name, genre, year, affiche):
' '
movie = Movie(name=name, genre=genre, year=year, affiche=affiche)
return movie.save()<|docstring|>Create a new movie<|endoftext|> |
e524d28155222a5fe8374e9a564a0367b8bdff9c91e22c9c8df1e32c30117de7 | def run_game():
'\n Run hangman game\n '
loader = WordsLoader()
pic = pics()
your_name = input('Enter your name: ')
print(f'''{your_name}, welcome in the Magic Hangman game.
''')
loader.build_word_dict()
word = loader.get_word_from_list()
run = True
attempt = 0
hangengi... | Run hangman game | game.py | run_game | kymy86/hangman-cmd-game | 0 | python | def run_game():
'\n \n '
loader = WordsLoader()
pic = pics()
your_name = input('Enter your name: ')
print(f'{your_name}, welcome in the Magic Hangman game.
')
loader.build_word_dict()
word = loader.get_word_from_list()
run = True
attempt = 0
hangengine = HangEngine(word... | def run_game():
'\n \n '
loader = WordsLoader()
pic = pics()
your_name = input('Enter your name: ')
print(f'{your_name}, welcome in the Magic Hangman game.
')
loader.build_word_dict()
word = loader.get_word_from_list()
run = True
attempt = 0
hangengine = HangEngine(word... |
e730db4ce5d4d9877c9ee403de6cbc1f012c4dabb750ac025419b616892d4270 | def readLine(line):
' Reads out a line from the ephemeris file, returns time, position and position angle. \n\t\t\n\t\tArguments:\n\t\t\tline: [string] Ephemeris line.\n\n\t\tReturn:\n\t\t\tparam_tup: [tuple of 4 elements] Tuple containing the date [string], RA, Dec and PA [floats]. \n\t'
date_str = line[8:13]
... | Reads out a line from the ephemeris file, returns time, position and position angle.
Arguments:
line: [string] Ephemeris line.
Return:
param_tup: [tuple of 4 elements] Tuple containing the date [string], RA, Dec and PA [floats]. | planner/ReadQuery.py | readLine | astrohr/dagor-preprocessing | 0 | python | def readLine(line):
' Reads out a line from the ephemeris file, returns time, position and position angle. \n\t\t\n\t\tArguments:\n\t\t\tline: [string] Ephemeris line.\n\n\t\tReturn:\n\t\t\tparam_tup: [tuple of 4 elements] Tuple containing the date [string], RA, Dec and PA [floats]. \n\t'
date_str = line[8:13]
... | def readLine(line):
' Reads out a line from the ephemeris file, returns time, position and position angle. \n\t\t\n\t\tArguments:\n\t\t\tline: [string] Ephemeris line.\n\n\t\tReturn:\n\t\t\tparam_tup: [tuple of 4 elements] Tuple containing the date [string], RA, Dec and PA [floats]. \n\t'
date_str = line[8:13]
... |
71e53d6338e47c5d36fb91e08274c36832ca584555e7b8a7645d417e33fbaf8e | def readQuery(query_dir, query_name):
' Read a query, output a dict containing the data. \n\t\t\n\t\tArguments:\n\t\t\tquery_dir: [string] Where the query is located. \n\t\t\tquery_name: [string] Name of the query file (*.txt). \n\t\n\t\tReturn:\n\t\t\tquery_dict: [dictionary] Dictionary containing the data. \n\t\t... | Read a query, output a dict containing the data.
Arguments:
query_dir: [string] Where the query is located.
query_name: [string] Name of the query file (*.txt).
Return:
query_dict: [dictionary] Dictionary containing the data.
Shape: {object_string: [date_str_arr, ra_deg_arr... | planner/ReadQuery.py | readQuery | astrohr/dagor-preprocessing | 0 | python | def readQuery(query_dir, query_name):
' Read a query, output a dict containing the data. \n\t\t\n\t\tArguments:\n\t\t\tquery_dir: [string] Where the query is located. \n\t\t\tquery_name: [string] Name of the query file (*.txt). \n\t\n\t\tReturn:\n\t\t\tquery_dict: [dictionary] Dictionary containing the data. \n\t\t... | def readQuery(query_dir, query_name):
' Read a query, output a dict containing the data. \n\t\t\n\t\tArguments:\n\t\t\tquery_dir: [string] Where the query is located. \n\t\t\tquery_name: [string] Name of the query file (*.txt). \n\t\n\t\tReturn:\n\t\t\tquery_dict: [dictionary] Dictionary containing the data. \n\t\t... |
2520b58049d3c746b26522a395fb0ee061d5bb5e1307e6ecea20837427ae88f7 | def composition_iterator_fast(n):
"\n Iterator over compositions of ``n`` yielded as lists.\n\n TESTS::\n\n sage: from sage.combinat.composition import composition_iterator_fast\n sage: L = list(composition_iterator_fast(4)); L\n [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2,... | Iterator over compositions of ``n`` yielded as lists.
TESTS::
sage: from sage.combinat.composition import composition_iterator_fast
sage: L = list(composition_iterator_fast(4)); L
[[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]]
sage: type(L[0])
<class 'list'> | src/sage/combinat/composition.py | composition_iterator_fast | LaisRast/sage | 1,742 | python | def composition_iterator_fast(n):
"\n Iterator over compositions of ``n`` yielded as lists.\n\n TESTS::\n\n sage: from sage.combinat.composition import composition_iterator_fast\n sage: L = list(composition_iterator_fast(4)); L\n [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2,... | def composition_iterator_fast(n):
"\n Iterator over compositions of ``n`` yielded as lists.\n\n TESTS::\n\n sage: from sage.combinat.composition import composition_iterator_fast\n sage: L = list(composition_iterator_fast(4)); L\n [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2,... |
373c03932175b63ff4675d8625b78843a4e9eb4e8f40aa3ec30cc5c7b800ac64 | @staticmethod
def __classcall_private__(cls, co=None, descents=None, code=None, from_subset=None):
'\n This constructs a list from optional arguments and delegates the\n construction of a :class:`Composition` to the ``element_class()`` call\n of the appropriate parent.\n\n EXAMPLES::\n\n... | This constructs a list from optional arguments and delegates the
construction of a :class:`Composition` to the ``element_class()`` call
of the appropriate parent.
EXAMPLES::
sage: Composition([3,2,1])
[3, 2, 1]
sage: Composition(from_subset=({1, 2, 4}, 5))
[1, 1, 2, 1]
sage: Composition(descents=[... | src/sage/combinat/composition.py | __classcall_private__ | LaisRast/sage | 1,742 | python | @staticmethod
def __classcall_private__(cls, co=None, descents=None, code=None, from_subset=None):
'\n This constructs a list from optional arguments and delegates the\n construction of a :class:`Composition` to the ``element_class()`` call\n of the appropriate parent.\n\n EXAMPLES::\n\n... | @staticmethod
def __classcall_private__(cls, co=None, descents=None, code=None, from_subset=None):
'\n This constructs a list from optional arguments and delegates the\n construction of a :class:`Composition` to the ``element_class()`` call\n of the appropriate parent.\n\n EXAMPLES::\n\n... |
d22e9949788b49820781ebe0f457f3f77117e92fa1cca23db77652f7bfc66402 | def _ascii_art_(self):
'\n TESTS::\n\n sage: ascii_art(Compositions(4).list())\n [ * ]\n [ * ** * * ]\n [ * * ** *** * ** * ]\n [ *, * , * , * , **, ** , ***, **** ]\n ... | TESTS::
sage: ascii_art(Compositions(4).list())
[ * ]
[ * ** * * ]
[ * * ** *** * ** * ]
[ *, * , * , * , **, ** , ***, **** ]
sage: Partitions.options(diagram_str='#', convention="French")
sage: ascii_art(Composit... | src/sage/combinat/composition.py | _ascii_art_ | LaisRast/sage | 1,742 | python | def _ascii_art_(self):
'\n TESTS::\n\n sage: ascii_art(Compositions(4).list())\n [ * ]\n [ * ** * * ]\n [ * * ** *** * ** * ]\n [ *, * , * , * , **, ** , ***, **** ]\n ... | def _ascii_art_(self):
'\n TESTS::\n\n sage: ascii_art(Compositions(4).list())\n [ * ]\n [ * ** * * ]\n [ * * ** *** * ** * ]\n [ *, * , * , * , **, ** , ***, **** ]\n ... |
489236d7b78e6fa09c1dc6eb6ee6262efed7d08d016219e2f6fdbce19664cb45 | def _unicode_art_(self):
'\n TESTS::\n\n sage: unicode_art(Compositions(4).list())\n ⎡ ┌┐ ⎤\n ⎢ ├┤ ┌┬┐ ┌┐ ┌┐ ⎥\n ⎢ ├┤ ├┼┘ ┌┼┤ ┌┬┬┐ ├┤ ┌┬┐ ┌┐ ⎥\n ⎢ ├┤ ├┤ ├┼┘ ├┼┴┘ ... | TESTS::
sage: unicode_art(Compositions(4).list())
⎡ ┌┐ ⎤
⎢ ├┤ ┌┬┐ ┌┐ ┌┐ ⎥
⎢ ├┤ ├┼┘ ┌┼┤ ┌┬┬┐ ├┤ ┌┬┐ ┌┐ ⎥
⎢ ├┤ ├┤ ├┼┘ ├┼┴┘ ┌┼┤ ┌┼┼┘ ┌┬┼┤ ┌┬┬┬┐ ⎥
⎣ └┘, └┘ , └┘ , └┘ , └┴┘, └┴┘ , └┴┴┘, └┴┴┴┘ ⎦
sage: ... | src/sage/combinat/composition.py | _unicode_art_ | LaisRast/sage | 1,742 | python | def _unicode_art_(self):
'\n TESTS::\n\n sage: unicode_art(Compositions(4).list())\n ⎡ ┌┐ ⎤\n ⎢ ├┤ ┌┬┐ ┌┐ ┌┐ ⎥\n ⎢ ├┤ ├┼┘ ┌┼┤ ┌┬┬┐ ├┤ ┌┬┐ ┌┐ ⎥\n ⎢ ├┤ ├┤ ├┼┘ ├┼┴┘ ... | def _unicode_art_(self):
'\n TESTS::\n\n sage: unicode_art(Compositions(4).list())\n ⎡ ┌┐ ⎤\n ⎢ ├┤ ┌┬┐ ┌┐ ┌┐ ⎥\n ⎢ ├┤ ├┼┘ ┌┼┤ ┌┬┬┐ ├┤ ┌┬┐ ┌┐ ⎥\n ⎢ ├┤ ├┤ ├┼┘ ├┼┴┘ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.