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
fd5f75c2df66d54ef236b00ab00284f1e5e01c2bcda74461480d435689fa153c
def __init__(self, state_reference, entity_type, interaction_id, learner_answer_info_list, accumulated_answer_info_json_size_bytes, learner_answer_info_schema_version=feconf.CURRENT_LEARNER_ANSWER_INFO_SCHEMA_VERSION): "Constructs a LearnerAnswerDetail domain object.\n\n Args:\n state_reference: s...
Constructs a LearnerAnswerDetail domain object. Args: state_reference: str. This field is used to refer to a state in an exploration or question. For an exploration the value will be equal to 'exp_id:state_name' & for question this will be equal to 'question_id' only. entity_type: str. ...
core/domain/stats_domain.py
__init__
yashdusing/oppia
3
python
def __init__(self, state_reference, entity_type, interaction_id, learner_answer_info_list, accumulated_answer_info_json_size_bytes, learner_answer_info_schema_version=feconf.CURRENT_LEARNER_ANSWER_INFO_SCHEMA_VERSION): "Constructs a LearnerAnswerDetail domain object.\n\n Args:\n state_reference: s...
def __init__(self, state_reference, entity_type, interaction_id, learner_answer_info_list, accumulated_answer_info_json_size_bytes, learner_answer_info_schema_version=feconf.CURRENT_LEARNER_ANSWER_INFO_SCHEMA_VERSION): "Constructs a LearnerAnswerDetail domain object.\n\n Args:\n state_reference: s...
a9408c9b8ef240e3cc2fe3ea3df8a537ad5f8e381b947cc04748b43813d51aa9
def to_dict(self): 'Returns a dict representing LearnerAnswerDetails domain object.\n\n Returns:\n dict. A dict, mapping all fields of LearnerAnswerDetails instance.\n ' return {'state_reference': self.state_reference, 'entity_type': self.entity_type, 'interaction_id': self.interaction_...
Returns a dict representing LearnerAnswerDetails domain object. Returns: dict. A dict, mapping all fields of LearnerAnswerDetails instance.
core/domain/stats_domain.py
to_dict
yashdusing/oppia
3
python
def to_dict(self): 'Returns a dict representing LearnerAnswerDetails domain object.\n\n Returns:\n dict. A dict, mapping all fields of LearnerAnswerDetails instance.\n ' return {'state_reference': self.state_reference, 'entity_type': self.entity_type, 'interaction_id': self.interaction_...
def to_dict(self): 'Returns a dict representing LearnerAnswerDetails domain object.\n\n Returns:\n dict. A dict, mapping all fields of LearnerAnswerDetails instance.\n ' return {'state_reference': self.state_reference, 'entity_type': self.entity_type, 'interaction_id': self.interaction_...
37d6b7fe59ef5ace067a388756d6c6ed197d4fe4f47f63b58b5c997a9a73784e
@classmethod def from_dict(cls, learner_answer_details_dict): 'Return a LearnerAnswerDetails domain object from a dict.\n\n Args:\n learner_answer_details_dict: dict. The dict representation of\n LearnerAnswerDetails object.\n\n Returns:\n LearnerAnswerDetails. The...
Return a LearnerAnswerDetails domain object from a dict. Args: learner_answer_details_dict: dict. The dict representation of LearnerAnswerDetails object. Returns: LearnerAnswerDetails. The corresponding LearnerAnswerDetails domain object.
core/domain/stats_domain.py
from_dict
yashdusing/oppia
3
python
@classmethod def from_dict(cls, learner_answer_details_dict): 'Return a LearnerAnswerDetails domain object from a dict.\n\n Args:\n learner_answer_details_dict: dict. The dict representation of\n LearnerAnswerDetails object.\n\n Returns:\n LearnerAnswerDetails. The...
@classmethod def from_dict(cls, learner_answer_details_dict): 'Return a LearnerAnswerDetails domain object from a dict.\n\n Args:\n learner_answer_details_dict: dict. The dict representation of\n LearnerAnswerDetails object.\n\n Returns:\n LearnerAnswerDetails. The...
54039963bbc67dcf66a369187aed4563daf54d8129312e7f3990ae082d728010
def validate(self): 'Validates LearnerAnswerDetails domain object.' if (not isinstance(self.state_reference, basestring)): raise utils.ValidationError(('Expected state_reference to be a string, received %s' % str(self.state_reference))) if (not isinstance(self.entity_type, basestring)): rais...
Validates LearnerAnswerDetails domain object.
core/domain/stats_domain.py
validate
yashdusing/oppia
3
python
def validate(self): if (not isinstance(self.state_reference, basestring)): raise utils.ValidationError(('Expected state_reference to be a string, received %s' % str(self.state_reference))) if (not isinstance(self.entity_type, basestring)): raise utils.ValidationError(('Expected entity_type ...
def validate(self): if (not isinstance(self.state_reference, basestring)): raise utils.ValidationError(('Expected state_reference to be a string, received %s' % str(self.state_reference))) if (not isinstance(self.entity_type, basestring)): raise utils.ValidationError(('Expected entity_type ...
52ceb9325b7f4713e88058f4e2cc4abe01cf19f1b1d039b09a3e0818bcbbaa9b
def add_learner_answer_info(self, learner_answer_info): 'Adds new learner answer info in the learner_answer_info_list.\n\n Args:\n learner_answer_info: LearnerAnswerInfo. The learner answer info\n object, which is created after the learner has submitted the\n details ...
Adds new learner answer info in the learner_answer_info_list. Args: learner_answer_info: LearnerAnswerInfo. The learner answer info object, which is created after the learner has submitted the details of the answer.
core/domain/stats_domain.py
add_learner_answer_info
yashdusing/oppia
3
python
def add_learner_answer_info(self, learner_answer_info): 'Adds new learner answer info in the learner_answer_info_list.\n\n Args:\n learner_answer_info: LearnerAnswerInfo. The learner answer info\n object, which is created after the learner has submitted the\n details ...
def add_learner_answer_info(self, learner_answer_info): 'Adds new learner answer info in the learner_answer_info_list.\n\n Args:\n learner_answer_info: LearnerAnswerInfo. The learner answer info\n object, which is created after the learner has submitted the\n details ...
2384a276c0fd08433e85e05100e79719c139ae81c9e8b4f76eb3f2d010aa39ca
def delete_learner_answer_info(self, learner_answer_info_id): 'Delete the learner answer info from the learner_answer_info_list.\n\n Args:\n learner_answer_info_id: str. The learner answer info\n id, which needs to be deleted from\n the learner_answer_info_list.\n\n ...
Delete the learner answer info from the learner_answer_info_list. Args: learner_answer_info_id: str. The learner answer info id, which needs to be deleted from the learner_answer_info_list. Raises: Exception: If the learner answer info with the given id is not found in the learner answ...
core/domain/stats_domain.py
delete_learner_answer_info
yashdusing/oppia
3
python
def delete_learner_answer_info(self, learner_answer_info_id): 'Delete the learner answer info from the learner_answer_info_list.\n\n Args:\n learner_answer_info_id: str. The learner answer info\n id, which needs to be deleted from\n the learner_answer_info_list.\n\n ...
def delete_learner_answer_info(self, learner_answer_info_id): 'Delete the learner answer info from the learner_answer_info_list.\n\n Args:\n learner_answer_info_id: str. The learner answer info\n id, which needs to be deleted from\n the learner_answer_info_list.\n\n ...
b2d8a7bd05adb01f389804dd08fc4cfd1b0e481bcae5369b94f037173a596583
def update_state_reference(self, new_state_reference): 'Updates the state_reference of the LearnerAnswerDetails object.\n\n Args:\n new_state_reference: str. The new state reference of the\n LearnerAnswerDetails.\n ' self.state_reference = new_state_reference
Updates the state_reference of the LearnerAnswerDetails object. Args: new_state_reference: str. The new state reference of the LearnerAnswerDetails.
core/domain/stats_domain.py
update_state_reference
yashdusing/oppia
3
python
def update_state_reference(self, new_state_reference): 'Updates the state_reference of the LearnerAnswerDetails object.\n\n Args:\n new_state_reference: str. The new state reference of the\n LearnerAnswerDetails.\n ' self.state_reference = new_state_reference
def update_state_reference(self, new_state_reference): 'Updates the state_reference of the LearnerAnswerDetails object.\n\n Args:\n new_state_reference: str. The new state reference of the\n LearnerAnswerDetails.\n ' self.state_reference = new_state_reference<|docstring|>...
c21bc690071b5262d616c9e0ce4cc06326409b658764127ffe0b3e96dc214a62
def __init__(self, learner_answer_info_id, answer, answer_details, created_on): "Constructs a LearnerAnswerInfo domain object.\n\n Args:\n learner_answer_info_id: str. The id of the LearnerAnswerInfo object.\n answer: dict or list or str or int or bool. The answer which is\n ...
Constructs a LearnerAnswerInfo domain object. Args: learner_answer_info_id: str. The id of the LearnerAnswerInfo object. answer: dict or list or str or int or bool. The answer which is submitted by the learner. Actually type of the answer is interaction dependent, like TextInput interactions ha...
core/domain/stats_domain.py
__init__
yashdusing/oppia
3
python
def __init__(self, learner_answer_info_id, answer, answer_details, created_on): "Constructs a LearnerAnswerInfo domain object.\n\n Args:\n learner_answer_info_id: str. The id of the LearnerAnswerInfo object.\n answer: dict or list or str or int or bool. The answer which is\n ...
def __init__(self, learner_answer_info_id, answer, answer_details, created_on): "Constructs a LearnerAnswerInfo domain object.\n\n Args:\n learner_answer_info_id: str. The id of the LearnerAnswerInfo object.\n answer: dict or list or str or int or bool. The answer which is\n ...
dc89e4ce0435660868c35690df1b327dcee089dd3b439c1f359e9c87cfabdd34
def to_dict(self): 'Returns the dict of learner answer info.\n\n Returns:\n dict. The learner_answer_info dict.\n ' learner_answer_info_dict = {'id': self.id, 'answer': self.answer, 'answer_details': self.answer_details, 'created_on': self.created_on.strftime('%Y-%m-%d %H:%M:%S.%f')} ...
Returns the dict of learner answer info. Returns: dict. The learner_answer_info dict.
core/domain/stats_domain.py
to_dict
yashdusing/oppia
3
python
def to_dict(self): 'Returns the dict of learner answer info.\n\n Returns:\n dict. The learner_answer_info dict.\n ' learner_answer_info_dict = {'id': self.id, 'answer': self.answer, 'answer_details': self.answer_details, 'created_on': self.created_on.strftime('%Y-%m-%d %H:%M:%S.%f')} ...
def to_dict(self): 'Returns the dict of learner answer info.\n\n Returns:\n dict. The learner_answer_info dict.\n ' learner_answer_info_dict = {'id': self.id, 'answer': self.answer, 'answer_details': self.answer_details, 'created_on': self.created_on.strftime('%Y-%m-%d %H:%M:%S.%f')} ...
62414922402a65ca11a641a8571f0d6aedd44e04534230335f673b65da5d334d
@classmethod def from_dict(cls, learner_answer_info_dict): 'Returns a dict representing LearnerAnswerInfo domain object.\n\n Returns:\n dict. A dict, mapping all fields of LearnerAnswerInfo instance.\n ' return cls(learner_answer_info_dict['id'], learner_answer_info_dict['answer'], lear...
Returns a dict representing LearnerAnswerInfo domain object. Returns: dict. A dict, mapping all fields of LearnerAnswerInfo instance.
core/domain/stats_domain.py
from_dict
yashdusing/oppia
3
python
@classmethod def from_dict(cls, learner_answer_info_dict): 'Returns a dict representing LearnerAnswerInfo domain object.\n\n Returns:\n dict. A dict, mapping all fields of LearnerAnswerInfo instance.\n ' return cls(learner_answer_info_dict['id'], learner_answer_info_dict['answer'], lear...
@classmethod def from_dict(cls, learner_answer_info_dict): 'Returns a dict representing LearnerAnswerInfo domain object.\n\n Returns:\n dict. A dict, mapping all fields of LearnerAnswerInfo instance.\n ' return cls(learner_answer_info_dict['id'], learner_answer_info_dict['answer'], lear...
93fc9fb0bc9983de660632400eaabbb85595e5e2009f4dbed85c1fd7d352267c
@classmethod def get_new_learner_answer_info_id(cls): 'Generates the learner answer info domain object id.\n\n Return:\n learner_answer_info_id: str. The id generated by the function.\n ' learner_answer_info_id = (utils.base64_from_int(utils.get_current_time_in_millisecs()) + utils.base...
Generates the learner answer info domain object id. Return: learner_answer_info_id: str. The id generated by the function.
core/domain/stats_domain.py
get_new_learner_answer_info_id
yashdusing/oppia
3
python
@classmethod def get_new_learner_answer_info_id(cls): 'Generates the learner answer info domain object id.\n\n Return:\n learner_answer_info_id: str. The id generated by the function.\n ' learner_answer_info_id = (utils.base64_from_int(utils.get_current_time_in_millisecs()) + utils.base...
@classmethod def get_new_learner_answer_info_id(cls): 'Generates the learner answer info domain object id.\n\n Return:\n learner_answer_info_id: str. The id generated by the function.\n ' learner_answer_info_id = (utils.base64_from_int(utils.get_current_time_in_millisecs()) + utils.base...
04b7a77da45e40a97da886c5fbed1a1f8bce9cab15cafaf152769d11b0cfdd54
def validate(self): 'Validates the LearnerAnswerInfo domain object.' if (not isinstance(self.id, basestring)): raise utils.ValidationError(('Expected id to be a string, received %s' % self.id)) if (self.answer is None): raise utils.ValidationError('The answer submitted by the learner cannot ...
Validates the LearnerAnswerInfo domain object.
core/domain/stats_domain.py
validate
yashdusing/oppia
3
python
def validate(self): if (not isinstance(self.id, basestring)): raise utils.ValidationError(('Expected id to be a string, received %s' % self.id)) if (self.answer is None): raise utils.ValidationError('The answer submitted by the learner cannot be empty') if isinstance(self.answer, dict):...
def validate(self): if (not isinstance(self.id, basestring)): raise utils.ValidationError(('Expected id to be a string, received %s' % self.id)) if (self.answer is None): raise utils.ValidationError('The answer submitted by the learner cannot be empty') if isinstance(self.answer, dict):...
b81e7b29e8b00a30fdb72aab304dcdb92c4a93b74753233fc9da1d4f8f124616
def get_learner_answer_info_dict_size(self): 'Returns a size overestimate (in bytes) of the given learner answer\n info dict.\n\n Returns:\n int. Size of the learner_answer_info_dict in bytes.\n ' learner_answer_info_dict = self.to_dict() return sys.getsizeof(json.dumps(learn...
Returns a size overestimate (in bytes) of the given learner answer info dict. Returns: int. Size of the learner_answer_info_dict in bytes.
core/domain/stats_domain.py
get_learner_answer_info_dict_size
yashdusing/oppia
3
python
def get_learner_answer_info_dict_size(self): 'Returns a size overestimate (in bytes) of the given learner answer\n info dict.\n\n Returns:\n int. Size of the learner_answer_info_dict in bytes.\n ' learner_answer_info_dict = self.to_dict() return sys.getsizeof(json.dumps(learn...
def get_learner_answer_info_dict_size(self): 'Returns a size overestimate (in bytes) of the given learner answer\n info dict.\n\n Returns:\n int. Size of the learner_answer_info_dict in bytes.\n ' learner_answer_info_dict = self.to_dict() return sys.getsizeof(json.dumps(learn...
886e9e2f53a1255c131e1ffb47afc04490c1ddf94a8238f8d01b5f839c8e96a8
def __init__(self, key): ' Construct object. Requires a valid SavedMacro\n entity key. Raises exception on failure.' self.entity = self.get_macro_entity(key) if (not self.entity): raise Exception(("Couldn't find macro for %s" % key))
Construct object. Requires a valid SavedMacro entity key. Raises exception on failure.
macro/data/appengine/savedmacro.py
__init__
cloudmattcloud/Macro-Explain-o-Matic
2
python
def __init__(self, key): ' Construct object. Requires a valid SavedMacro\n entity key. Raises exception on failure.' self.entity = self.get_macro_entity(key) if (not self.entity): raise Exception(("Couldn't find macro for %s" % key))
def __init__(self, key): ' Construct object. Requires a valid SavedMacro\n entity key. Raises exception on failure.' self.entity = self.get_macro_entity(key) if (not self.entity): raise Exception(("Couldn't find macro for %s" % key))<|docstring|>Construct object. Requires a valid SavedMacr...
6a38643207591203373fa6de8b60e354635aec9d680fc2cdc78b9f38f6804665
@classmethod def save_macro(self, macro, notes, title, name, classes, tags, version, server=''): ' Create a new macro entry in the datastore.\n This function assumes data has already been validated.\n \n Note that this function involves two writes to the datastore\n in order to have a se...
Create a new macro entry in the datastore. This function assumes data has already been validated. Note that this function involves two writes to the datastore in order to have a serialized count across all macro entites. This sucks donkey balls but ensures a) that we can page through macros in search results, and b) w...
macro/data/appengine/savedmacro.py
save_macro
cloudmattcloud/Macro-Explain-o-Matic
2
python
@classmethod def save_macro(self, macro, notes, title, name, classes, tags, version, server=): ' Create a new macro entry in the datastore.\n This function assumes data has already been validated.\n \n Note that this function involves two writes to the datastore\n in order to have a seri...
@classmethod def save_macro(self, macro, notes, title, name, classes, tags, version, server=): ' Create a new macro entry in the datastore.\n This function assumes data has already been validated.\n \n Note that this function involves two writes to the datastore\n in order to have a seri...
3a97cdcbafbec2328938ba8d1e1f77422190f302febd7bdb0d757eb0d1d905c6
@classmethod def get_macro_entity(self, key): ' Gets a macro from its macro_id from memcached or datastore,\n unquotes it, and places it in memcached before returning the\n object.\n\n Class method, can be called without object.\n ' saved_macro = memcache.get(cache_key(key)) if (...
Gets a macro from its macro_id from memcached or datastore, unquotes it, and places it in memcached before returning the object. Class method, can be called without object.
macro/data/appengine/savedmacro.py
get_macro_entity
cloudmattcloud/Macro-Explain-o-Matic
2
python
@classmethod def get_macro_entity(self, key): ' Gets a macro from its macro_id from memcached or datastore,\n unquotes it, and places it in memcached before returning the\n object.\n\n Class method, can be called without object.\n ' saved_macro = memcache.get(cache_key(key)) if (...
@classmethod def get_macro_entity(self, key): ' Gets a macro from its macro_id from memcached or datastore,\n unquotes it, and places it in memcached before returning the\n object.\n\n Class method, can be called without object.\n ' saved_macro = memcache.get(cache_key(key)) if (...
595639cc0548014fa8312b8edb6c57f30b0badeeb24f5b0293db56832d8d987b
@classmethod def get_rating_dict(self, rating): ' Given a float rating, translate it into a structure\n for rendering it on a page. ' int_rating = int(rating) rating_stars = [{'id': i, 'half': False, 'on': (i <= rating), 'off': (i > rating)} for i in range((MAX_RATING + 1))[1:]] if (int_rating !=...
Given a float rating, translate it into a structure for rendering it on a page.
macro/data/appengine/savedmacro.py
get_rating_dict
cloudmattcloud/Macro-Explain-o-Matic
2
python
@classmethod def get_rating_dict(self, rating): ' Given a float rating, translate it into a structure\n for rendering it on a page. ' int_rating = int(rating) rating_stars = [{'id': i, 'half': False, 'on': (i <= rating), 'off': (i > rating)} for i in range((MAX_RATING + 1))[1:]] if (int_rating !=...
@classmethod def get_rating_dict(self, rating): ' Given a float rating, translate it into a structure\n for rendering it on a page. ' int_rating = int(rating) rating_stars = [{'id': i, 'half': False, 'on': (i <= rating), 'off': (i > rating)} for i in range((MAX_RATING + 1))[1:]] if (int_rating !=...
89cf674ce97acbab57dce842f3783a20227e972a726404eeeef767859e71f6e7
@classmethod def get_rating_score(self, rating, num_rates, do_round=True): ' Calculate rating in float form. If specified,\n this function can round to the nearest half star.' if (num_rates == 0): return 0 stars = (float(rating) / float(num_rates)) if (not do_round): return stars...
Calculate rating in float form. If specified, this function can round to the nearest half star.
macro/data/appengine/savedmacro.py
get_rating_score
cloudmattcloud/Macro-Explain-o-Matic
2
python
@classmethod def get_rating_score(self, rating, num_rates, do_round=True): ' Calculate rating in float form. If specified,\n this function can round to the nearest half star.' if (num_rates == 0): return 0 stars = (float(rating) / float(num_rates)) if (not do_round): return stars...
@classmethod def get_rating_score(self, rating, num_rates, do_round=True): ' Calculate rating in float form. If specified,\n this function can round to the nearest half star.' if (num_rates == 0): return 0 stars = (float(rating) / float(num_rates)) if (not do_round): return stars...
8de0a0c5c8fba5b438518c06595f75a3db9c0f611278a7d241fe0897ef52cb6f
def get_rating(self, rating=None, num_rates=None, do_round=True): ' Calculate rating from counters for this entity,\n returning the rating in float form. If specified,\n this function can round to the nearest half star.' if ((rating is None) or (num_rates is None)): num_rates = get_count(...
Calculate rating from counters for this entity, returning the rating in float form. If specified, this function can round to the nearest half star.
macro/data/appengine/savedmacro.py
get_rating
cloudmattcloud/Macro-Explain-o-Matic
2
python
def get_rating(self, rating=None, num_rates=None, do_round=True): ' Calculate rating from counters for this entity,\n returning the rating in float form. If specified,\n this function can round to the nearest half star.' if ((rating is None) or (num_rates is None)): num_rates = get_count(...
def get_rating(self, rating=None, num_rates=None, do_round=True): ' Calculate rating from counters for this entity,\n returning the rating in float form. If specified,\n this function can round to the nearest half star.' if ((rating is None) or (num_rates is None)): num_rates = get_count(...
d91ba903d118daa8647d783665b60ac30723cc91333999d0dd61bc2707123402
def add_rating(self, rating=0): ' Add a rating for a SavedMacro. Returns the rating rounded\n to the largest half star.' if ((rating < 1) or (rating > MAX_RATING)): return self.get_rating() else: num_rates = incr_count(self.entity.link_id, 'num_rates', update_count, entity_val=self.en...
Add a rating for a SavedMacro. Returns the rating rounded to the largest half star.
macro/data/appengine/savedmacro.py
add_rating
cloudmattcloud/Macro-Explain-o-Matic
2
python
def add_rating(self, rating=0): ' Add a rating for a SavedMacro. Returns the rating rounded\n to the largest half star.' if ((rating < 1) or (rating > MAX_RATING)): return self.get_rating() else: num_rates = incr_count(self.entity.link_id, 'num_rates', update_count, entity_val=self.en...
def add_rating(self, rating=0): ' Add a rating for a SavedMacro. Returns the rating rounded\n to the largest half star.' if ((rating < 1) or (rating > MAX_RATING)): return self.get_rating() else: num_rates = incr_count(self.entity.link_id, 'num_rates', update_count, entity_val=self.en...
c40a59395e72da055d9ab15b5fc697c09a4eec634cd5373f4342d24fbf34e5fe
def add_to_send_count(self): ' Update send count for a SavedMacro.' try: init_val = self.entity.sends except: init_val = 0 ret = incr_count(self.entity.link_id, 'sends', update_count, entity_val=init_val) return ret
Update send count for a SavedMacro.
macro/data/appengine/savedmacro.py
add_to_send_count
cloudmattcloud/Macro-Explain-o-Matic
2
python
def add_to_send_count(self): ' ' try: init_val = self.entity.sends except: init_val = 0 ret = incr_count(self.entity.link_id, 'sends', update_count, entity_val=init_val) return ret
def add_to_send_count(self): ' ' try: init_val = self.entity.sends except: init_val = 0 ret = incr_count(self.entity.link_id, 'sends', update_count, entity_val=init_val) return ret<|docstring|>Update send count for a SavedMacro.<|endoftext|>
0d1ed96d533aa10360d155b53e2f3252d5644f928ed1508820d08e3589e40c2a
def add_to_view_count(self): ' Update view count for a SavedMacro.' try: init_val = self.entity.views except: init_val = 0 ret = incr_count(self.entity.link_id, 'views', update_count, entity_val=init_val) return ret
Update view count for a SavedMacro.
macro/data/appengine/savedmacro.py
add_to_view_count
cloudmattcloud/Macro-Explain-o-Matic
2
python
def add_to_view_count(self): ' ' try: init_val = self.entity.views except: init_val = 0 ret = incr_count(self.entity.link_id, 'views', update_count, entity_val=init_val) return ret
def add_to_view_count(self): ' ' try: init_val = self.entity.views except: init_val = 0 ret = incr_count(self.entity.link_id, 'views', update_count, entity_val=init_val) return ret<|docstring|>Update view count for a SavedMacro.<|endoftext|>
ef67f3c20cdbe1499677e503a14a0db0132925403bf9deae5479bbab7b80c9ff
@classmethod def search(self, tag, page=1, sort='-views', num=_NUM_RESULTS): ' Search macros for a given tag, return num results.\n Returns ([results], is_next_page), where is_next_page is\n True if there are more than this page of results, F otherwise.\n\n Each result in [results] is an object...
Search macros for a given tag, return num results. Returns ([results], is_next_page), where is_next_page is True if there are more than this page of results, F otherwise. Each result in [results] is an object in dict form for use in template output. Class method, can be called without object.
macro/data/appengine/savedmacro.py
search
cloudmattcloud/Macro-Explain-o-Matic
2
python
@classmethod def search(self, tag, page=1, sort='-views', num=_NUM_RESULTS): ' Search macros for a given tag, return num results.\n Returns ([results], is_next_page), where is_next_page is\n True if there are more than this page of results, F otherwise.\n\n Each result in [results] is an object...
@classmethod def search(self, tag, page=1, sort='-views', num=_NUM_RESULTS): ' Search macros for a given tag, return num results.\n Returns ([results], is_next_page), where is_next_page is\n True if there are more than this page of results, F otherwise.\n\n Each result in [results] is an object...
aa8ab0d5df389d190e9d3fe8ac65a66643739e54d88900f31ed6738859cd4a37
@staticmethod def dict_merge(self, dct, merge_dct): ' Recursive dict merge. Inspired by :meth:``dict.update()``, instead of\n updating only top-level keys, dict_merge recurses down into dicts nested\n to an arbitrary depth, updating keys. The ``merge_dct`` is merged into\n ``dct``.\n :pa...
Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is merged into ``dct``. :param dct: dict onto which the merge is executed :param merge_dct: dct merged into dct :return: ...
webdjango/Tools.py
dict_merge
myog-io/WebDjangular
1
python
@staticmethod def dict_merge(self, dct, merge_dct): ' Recursive dict merge. Inspired by :meth:``dict.update()``, instead of\n updating only top-level keys, dict_merge recurses down into dicts nested\n to an arbitrary depth, updating keys. The ``merge_dct`` is merged into\n ``dct``.\n :pa...
@staticmethod def dict_merge(self, dct, merge_dct): ' Recursive dict merge. Inspired by :meth:``dict.update()``, instead of\n updating only top-level keys, dict_merge recurses down into dicts nested\n to an arbitrary depth, updating keys. The ``merge_dct`` is merged into\n ``dct``.\n :pa...
59eca8d4c7adcb2951b7c4ba0662cbe412f844ab9008bcd99f46d8ed27efa092
@plot_gridworld_heatmap_ex.config def default_config(): 'Default configuration values.' normalize = False log_root = serialize.get_output_dir() discount = 0.99 reward_subset = None kind = 'npec' styles = ['paper', 'heatmap', 'heatmap-1col', 'heatmap-1col-fatlabels', 'tex'] save_kwargs = ...
Default configuration values.
src/evaluating_rewards/analysis/distances/plot_gridworld_heatmap.py
default_config
HumanCompatibleAI/evaluating_rewards
42
python
@plot_gridworld_heatmap_ex.config def default_config(): normalize = False log_root = serialize.get_output_dir() discount = 0.99 reward_subset = None kind = 'npec' styles = ['paper', 'heatmap', 'heatmap-1col', 'heatmap-1col-fatlabels', 'tex'] save_kwargs = {'fmt': 'pdf'} _ = locals()...
@plot_gridworld_heatmap_ex.config def default_config(): normalize = False log_root = serialize.get_output_dir() discount = 0.99 reward_subset = None kind = 'npec' styles = ['paper', 'heatmap', 'heatmap-1col', 'heatmap-1col-fatlabels', 'tex'] save_kwargs = {'fmt': 'pdf'} _ = locals()...
4166b122209315074907236bfba83dd3a71624e8fd82257c905677a4ae2f6388
@plot_gridworld_heatmap_ex.named_config def test(): 'Unit tests/debugging.' styles = ['paper', 'heatmap', 'heatmap-2col'] reward_subset = ['sparse_goal', 'dense_goal'] _ = locals() del _
Unit tests/debugging.
src/evaluating_rewards/analysis/distances/plot_gridworld_heatmap.py
test
HumanCompatibleAI/evaluating_rewards
42
python
@plot_gridworld_heatmap_ex.named_config def test(): styles = ['paper', 'heatmap', 'heatmap-2col'] reward_subset = ['sparse_goal', 'dense_goal'] _ = locals() del _
@plot_gridworld_heatmap_ex.named_config def test(): styles = ['paper', 'heatmap', 'heatmap-2col'] reward_subset = ['sparse_goal', 'dense_goal'] _ = locals() del _<|docstring|>Unit tests/debugging.<|endoftext|>
168bba919cd2f9447556ff7b4986c5343a38a5bcac2e595b41fd944ccdfd90fa
@plot_gridworld_heatmap_ex.named_config def paper(): 'Figure for paper appendix.' reward_subset = ['sparse_goal', 'transformed_goal', 'center_goal', 'sparse_penalty', 'dirt_path', 'cliff_walk'] heatmap_kwargs = {'cbar_kws': dict(fraction=0.05)} _ = locals() del _
Figure for paper appendix.
src/evaluating_rewards/analysis/distances/plot_gridworld_heatmap.py
paper
HumanCompatibleAI/evaluating_rewards
42
python
@plot_gridworld_heatmap_ex.named_config def paper(): reward_subset = ['sparse_goal', 'transformed_goal', 'center_goal', 'sparse_penalty', 'dirt_path', 'cliff_walk'] heatmap_kwargs = {'cbar_kws': dict(fraction=0.05)} _ = locals() del _
@plot_gridworld_heatmap_ex.named_config def paper(): reward_subset = ['sparse_goal', 'transformed_goal', 'center_goal', 'sparse_penalty', 'dirt_path', 'cliff_walk'] heatmap_kwargs = {'cbar_kws': dict(fraction=0.05)} _ = locals() del _<|docstring|>Figure for paper appendix.<|endoftext|>
797903316fde42d7d2943bf3255dea9308216d5e2d21ed0d8e6942b8a3c5ddff
def state_to_3d(reward: np.ndarray, ns: int, na: int) -> np.ndarray: "Convert state-only reward R[s] to 3D reward R[s,a,s'].\n\n Args:\n - reward: state only reward.\n - ns: number of states.\n - na: number of actions.\n\n Returns:\n State-action-next state reward from tiling `rewa...
Convert state-only reward R[s] to 3D reward R[s,a,s']. Args: - reward: state only reward. - ns: number of states. - na: number of actions. Returns: State-action-next state reward from tiling `reward`.
src/evaluating_rewards/analysis/distances/plot_gridworld_heatmap.py
state_to_3d
HumanCompatibleAI/evaluating_rewards
42
python
def state_to_3d(reward: np.ndarray, ns: int, na: int) -> np.ndarray: "Convert state-only reward R[s] to 3D reward R[s,a,s'].\n\n Args:\n - reward: state only reward.\n - ns: number of states.\n - na: number of actions.\n\n Returns:\n State-action-next state reward from tiling `rewa...
def state_to_3d(reward: np.ndarray, ns: int, na: int) -> np.ndarray: "Convert state-only reward R[s] to 3D reward R[s,a,s'].\n\n Args:\n - reward: state only reward.\n - ns: number of states.\n - na: number of actions.\n\n Returns:\n State-action-next state reward from tiling `rewa...
e07135012b30ce19738091250106bad679b0f3e78c4a41ff26e6b0726e17a6fb
def grid_to_3d(reward: np.ndarray) -> np.ndarray: "Convert gridworld state-only reward R[i,j] to 3D reward R[s,a,s']." assert (reward.ndim == 2) reward = reward.flatten() ns = reward.shape[0] return state_to_3d(reward, ns, 5)
Convert gridworld state-only reward R[i,j] to 3D reward R[s,a,s'].
src/evaluating_rewards/analysis/distances/plot_gridworld_heatmap.py
grid_to_3d
HumanCompatibleAI/evaluating_rewards
42
python
def grid_to_3d(reward: np.ndarray) -> np.ndarray: assert (reward.ndim == 2) reward = reward.flatten() ns = reward.shape[0] return state_to_3d(reward, ns, 5)
def grid_to_3d(reward: np.ndarray) -> np.ndarray: assert (reward.ndim == 2) reward = reward.flatten() ns = reward.shape[0] return state_to_3d(reward, ns, 5)<|docstring|>Convert gridworld state-only reward R[i,j] to 3D reward R[s,a,s'].<|endoftext|>
eb31e4746e4cca6171ecfee8c1501e8d394adadc6e3bafb8c33c6f54b47f5e54
def make_reward(cfg: Dict[(str, np.ndarray)], discount: float) -> np.ndarray: 'Create reward from state-only reward and potential.' state_reward = grid_to_3d(cfg['state_reward']) potential = cfg['potential'] assert (potential.ndim == 2) potential = potential.flatten() return tabular.shape(state_...
Create reward from state-only reward and potential.
src/evaluating_rewards/analysis/distances/plot_gridworld_heatmap.py
make_reward
HumanCompatibleAI/evaluating_rewards
42
python
def make_reward(cfg: Dict[(str, np.ndarray)], discount: float) -> np.ndarray: state_reward = grid_to_3d(cfg['state_reward']) potential = cfg['potential'] assert (potential.ndim == 2) potential = potential.flatten() return tabular.shape(state_reward, potential, discount)
def make_reward(cfg: Dict[(str, np.ndarray)], discount: float) -> np.ndarray: state_reward = grid_to_3d(cfg['state_reward']) potential = cfg['potential'] assert (potential.ndim == 2) potential = potential.flatten() return tabular.shape(state_reward, potential, discount)<|docstring|>Create rewar...
f9b6c6c3fb106f7d32c54c48b9b2f8b2dedf13feecdabc4afbd68af74f46dcb6
def build_dist(rew: np.ndarray, xlen: int, ylen: int) -> np.ndarray: 'Computes uniform visitation distribution compatible with gridworld dynamics.\n\n Args:\n rew: A three-dimensional reward (needed for dimensionality).\n xlen: width of gridworld.\n ylen: height of gridworld.\n\n Returns:...
Computes uniform visitation distribution compatible with gridworld dynamics. Args: rew: A three-dimensional reward (needed for dimensionality). xlen: width of gridworld. ylen: height of gridworld. Returns: A distribution
src/evaluating_rewards/analysis/distances/plot_gridworld_heatmap.py
build_dist
HumanCompatibleAI/evaluating_rewards
42
python
def build_dist(rew: np.ndarray, xlen: int, ylen: int) -> np.ndarray: 'Computes uniform visitation distribution compatible with gridworld dynamics.\n\n Args:\n rew: A three-dimensional reward (needed for dimensionality).\n xlen: width of gridworld.\n ylen: height of gridworld.\n\n Returns:...
def build_dist(rew: np.ndarray, xlen: int, ylen: int) -> np.ndarray: 'Computes uniform visitation distribution compatible with gridworld dynamics.\n\n Args:\n rew: A three-dimensional reward (needed for dimensionality).\n xlen: width of gridworld.\n ylen: height of gridworld.\n\n Returns:...
dfe6a0e1c952b12e93a57eea2e82573347d05fbc4c2194c63c1a861c237b2302
def compute_divergence(reward_cfg: Dict[(str, Any)], discount: float, kind: str) -> pd.Series: 'Compute divergence for each pair of rewards in `reward_cfg`.' rewards = {name: make_reward(cfg, discount) for (name, cfg) in reward_cfg.items()} divergence = collections.defaultdict(dict) for (src_name, src_r...
Compute divergence for each pair of rewards in `reward_cfg`.
src/evaluating_rewards/analysis/distances/plot_gridworld_heatmap.py
compute_divergence
HumanCompatibleAI/evaluating_rewards
42
python
def compute_divergence(reward_cfg: Dict[(str, Any)], discount: float, kind: str) -> pd.Series: rewards = {name: make_reward(cfg, discount) for (name, cfg) in reward_cfg.items()} divergence = collections.defaultdict(dict) for (src_name, src_reward) in rewards.items(): for (target_name, target_re...
def compute_divergence(reward_cfg: Dict[(str, Any)], discount: float, kind: str) -> pd.Series: rewards = {name: make_reward(cfg, discount) for (name, cfg) in reward_cfg.items()} divergence = collections.defaultdict(dict) for (src_name, src_reward) in rewards.items(): for (target_name, target_re...
07b2a9e1d4e1ea23a8cd5e61453864f8093c1ec0fe8ecdefe8a11c58bec0b5a0
def normalize_dissimilarity(s: pd.Series) -> pd.Series: 'Divides by distance from Zero reward, an upper bound on the distance.' df = s.unstack(level=['source_reward_type', 'source_reward_path']) zero_col_name = (serialize.ZERO_REWARD, 'dummy') zero_dissimilarity = df.pop(zero_col_name) df = df.apply...
Divides by distance from Zero reward, an upper bound on the distance.
src/evaluating_rewards/analysis/distances/plot_gridworld_heatmap.py
normalize_dissimilarity
HumanCompatibleAI/evaluating_rewards
42
python
def normalize_dissimilarity(s: pd.Series) -> pd.Series: df = s.unstack(level=['source_reward_type', 'source_reward_path']) zero_col_name = (serialize.ZERO_REWARD, 'dummy') zero_dissimilarity = df.pop(zero_col_name) df = df.apply((lambda x: (x / zero_dissimilarity))) return df.unstack(level=df.i...
def normalize_dissimilarity(s: pd.Series) -> pd.Series: df = s.unstack(level=['source_reward_type', 'source_reward_path']) zero_col_name = (serialize.ZERO_REWARD, 'dummy') zero_dissimilarity = df.pop(zero_col_name) df = df.apply((lambda x: (x / zero_dissimilarity))) return df.unstack(level=df.i...
f943f5d07aeb13f6413907db6a314fc677a2ae901b460e79c84db31423a1eb8e
@plot_gridworld_heatmap_ex.main def plot_gridworld_heatmap(normalize: bool, styles: Iterable[str], reward_subset: Optional[Iterable[str]], heatmap_kwargs: Dict[(str, Any)], kind: str, discount: float, log_dir: str, save_kwargs: Mapping[(str, Any)]) -> None: 'Entry-point into script to produce divergence heatmaps.\n...
Entry-point into script to produce divergence heatmaps. Args: normalize: whether to divide by distance from Zero. styles: styles to apply from `evaluating_rewards.analysis.stylesheets`. reward_subset: if specified, subset of keys to plot. discount: discount rate of MDP. log_dir: directory to write ...
src/evaluating_rewards/analysis/distances/plot_gridworld_heatmap.py
plot_gridworld_heatmap
HumanCompatibleAI/evaluating_rewards
42
python
@plot_gridworld_heatmap_ex.main def plot_gridworld_heatmap(normalize: bool, styles: Iterable[str], reward_subset: Optional[Iterable[str]], heatmap_kwargs: Dict[(str, Any)], kind: str, discount: float, log_dir: str, save_kwargs: Mapping[(str, Any)]) -> None: 'Entry-point into script to produce divergence heatmaps.\n...
@plot_gridworld_heatmap_ex.main def plot_gridworld_heatmap(normalize: bool, styles: Iterable[str], reward_subset: Optional[Iterable[str]], heatmap_kwargs: Dict[(str, Any)], kind: str, discount: float, log_dir: str, save_kwargs: Mapping[(str, Any)]) -> None: 'Entry-point into script to produce divergence heatmaps.\n...
86bbd6f3d90103ecefdb6ba35dbd06c92c73feca1cbc8108d3fdae35c267730e
@staticmethod def prepare(message): ' Assign unique hashes to messages ready for transport.\n Returns (new hashed message) -> str ' out = '' timestamp = str(datetime.datetime.utcnow()) out += timestamp out += message sig = sha3_224(out.encode()).hexdigest()[:16] out = '' out +...
Assign unique hashes to messages ready for transport. Returns (new hashed message) -> str
src/server/server.py
prepare
D3P-Dell-Part-Picker/Axonet
0
python
@staticmethod def prepare(message): ' Assign unique hashes to messages ready for transport.\n Returns (new hashed message) -> str ' out = timestamp = str(datetime.datetime.utcnow()) out += timestamp out += message sig = sha3_224(out.encode()).hexdigest()[:16] out = out += si...
@staticmethod def prepare(message): ' Assign unique hashes to messages ready for transport.\n Returns (new hashed message) -> str ' out = timestamp = str(datetime.datetime.utcnow()) out += timestamp out += message sig = sha3_224(out.encode()).hexdigest()[:16] out = out += si...
fdb23429db92b20a0fdbb0765e0a9f8578dea62932500eac033d054fb4f9abea
def permute_network_tuple(self): " Permute the network tuple. Repetitive permutation after each call\n of respond() functionally allows the network to inherit many of the anonymous\n aspects of a mixing network. Packets are sent sequentially in the order of the\n network tuple, whic...
Permute the network tuple. Repetitive permutation after each call of respond() functionally allows the network to inherit many of the anonymous aspects of a mixing network. Packets are sent sequentially in the order of the network tuple, which when permuted, thwarts many timing attacks. '' Doesn't return
src/server/server.py
permute_network_tuple
D3P-Dell-Part-Picker/Axonet
0
python
def permute_network_tuple(self): " Permute the network tuple. Repetitive permutation after each call\n of respond() functionally allows the network to inherit many of the anonymous\n aspects of a mixing network. Packets are sent sequentially in the order of the\n network tuple, whic...
def permute_network_tuple(self): " Permute the network tuple. Repetitive permutation after each call\n of respond() functionally allows the network to inherit many of the anonymous\n aspects of a mixing network. Packets are sent sequentially in the order of the\n network tuple, whic...
d31a3be5a74db18f8ec21759eaffc856db433dcf77dc116ffcd1ff938640a4e8
def lookup_socket(self, address): 'Do a brute force search for a specific socket.\n Maybe this can be optimized by caching the indexes of commonly-used connections?' net_tuple = self.read_nodestate(0) for item in net_tuple: discovered_address = item[1] if (address == discovered_add...
Do a brute force search for a specific socket. Maybe this can be optimized by caching the indexes of commonly-used connections?
src/server/server.py
lookup_socket
D3P-Dell-Part-Picker/Axonet
0
python
def lookup_socket(self, address): 'Do a brute force search for a specific socket.\n Maybe this can be optimized by caching the indexes of commonly-used connections?' net_tuple = self.read_nodestate(0) for item in net_tuple: discovered_address = item[1] if (address == discovered_add...
def lookup_socket(self, address): 'Do a brute force search for a specific socket.\n Maybe this can be optimized by caching the indexes of commonly-used connections?' net_tuple = self.read_nodestate(0) for item in net_tuple: discovered_address = item[1] if (address == discovered_add...
93887ce0b7bde1490992fc77bd4524fb08cac440dd04d1c6b76999897db049bc
def lookup_address(self, in_sock): 'Do a brute force search for a specific socket.\n Maybe this can be optimized by caching the indexes of commonly-used connections?' net_tuple = self.read_nodestate(0) for item in net_tuple: discovered_socket = item[0] if (in_sock == discovered_soc...
Do a brute force search for a specific socket. Maybe this can be optimized by caching the indexes of commonly-used connections?
src/server/server.py
lookup_address
D3P-Dell-Part-Picker/Axonet
0
python
def lookup_address(self, in_sock): 'Do a brute force search for a specific socket.\n Maybe this can be optimized by caching the indexes of commonly-used connections?' net_tuple = self.read_nodestate(0) for item in net_tuple: discovered_socket = item[0] if (in_sock == discovered_soc...
def lookup_address(self, in_sock): 'Do a brute force search for a specific socket.\n Maybe this can be optimized by caching the indexes of commonly-used connections?' net_tuple = self.read_nodestate(0) for item in net_tuple: discovered_socket = item[0] if (in_sock == discovered_soc...
eab7945b7f64a3c41b62144f2fbd9d332709e5231ead5189468932b8a7a613c2
def append(self, in_socket, address): " Add a connection to the network tuple. Doesn't return." net_tuple = self.read_nodestate(0) network_list = list(net_tuple) connection = (in_socket, address) network_list.append(connection) self.write_nodestate(nodeState, 0, tuple(network_list))
Add a connection to the network tuple. Doesn't return.
src/server/server.py
append
D3P-Dell-Part-Picker/Axonet
0
python
def append(self, in_socket, address): " " net_tuple = self.read_nodestate(0) network_list = list(net_tuple) connection = (in_socket, address) network_list.append(connection) self.write_nodestate(nodeState, 0, tuple(network_list))
def append(self, in_socket, address): " " net_tuple = self.read_nodestate(0) network_list = list(net_tuple) connection = (in_socket, address) network_list.append(connection) self.write_nodestate(nodeState, 0, tuple(network_list))<|docstring|>Add a connection to the network tuple. Doesn't return....
055f2ca9347d72782a0252c68000742c217d08ed1c835ebefe07b914eb3cae9a
def remove(self, connection): "Remove a connection from the network tuple. Doesn't return" net_tuple = self.read_nodestate(0) network_list = list(net_tuple) try: index = network_list.index(connection) network_list.pop(index) except ValueError: log_msg = str(('Not removing non...
Remove a connection from the network tuple. Doesn't return
src/server/server.py
remove
D3P-Dell-Part-Picker/Axonet
0
python
def remove(self, connection): net_tuple = self.read_nodestate(0) network_list = list(net_tuple) try: index = network_list.index(connection) network_list.pop(index) except ValueError: log_msg = str(('Not removing non-existent connection: ' + str(connection))) Primitiv...
def remove(self, connection): net_tuple = self.read_nodestate(0) network_list = list(net_tuple) try: index = network_list.index(connection) network_list.pop(index) except ValueError: log_msg = str(('Not removing non-existent connection: ' + str(connection))) Primitiv...
81440a707ed2b76ae626444ffaa3379c449857ceaf30a8f035a26499a667236b
def stop(self): ' Attempt to gracefully disconnect and terminate,\n but resort to brute force if needed. ' net_tuple = self.read_nodestate(0) try: localhost_socket = self.lookup_socket('127.0.0.1') localhost_connection = (localhost_socket, '127.0.0.1') self.send(localhost_conn...
Attempt to gracefully disconnect and terminate, but resort to brute force if needed.
src/server/server.py
stop
D3P-Dell-Part-Picker/Axonet
0
python
def stop(self): ' Attempt to gracefully disconnect and terminate,\n but resort to brute force if needed. ' net_tuple = self.read_nodestate(0) try: localhost_socket = self.lookup_socket('127.0.0.1') localhost_connection = (localhost_socket, '127.0.0.1') self.send(localhost_conn...
def stop(self): ' Attempt to gracefully disconnect and terminate,\n but resort to brute force if needed. ' net_tuple = self.read_nodestate(0) try: localhost_socket = self.lookup_socket('127.0.0.1') localhost_connection = (localhost_socket, '127.0.0.1') self.send(localhost_conn...
4d393a51abb24c39524529d37aa6c6ed7f65cd04b08ba6216f3d0f2dd26404a5
def disconnect(self, connection, disallow_local_disconnect=True): "Try to disconnect from a socket as cleanly as possible.\n Doesn't return anything. " sock = connection[0] address = connection[1] terminated = self.read_nodestate(2) try: if disallow_local_disconnect: Pr...
Try to disconnect from a socket as cleanly as possible. Doesn't return anything.
src/server/server.py
disconnect
D3P-Dell-Part-Picker/Axonet
0
python
def disconnect(self, connection, disallow_local_disconnect=True): "Try to disconnect from a socket as cleanly as possible.\n Doesn't return anything. " sock = connection[0] address = connection[1] terminated = self.read_nodestate(2) try: if disallow_local_disconnect: Pr...
def disconnect(self, connection, disallow_local_disconnect=True): "Try to disconnect from a socket as cleanly as possible.\n Doesn't return anything. " sock = connection[0] address = connection[1] terminated = self.read_nodestate(2) try: if disallow_local_disconnect: Pr...
1ef695b7ffda0da50503009c40479536b29a825fc21293ea15b5559a49d36149
def listen(self, connection): "Listen for incoming messages in one thread, manage the network injector in another.\n Doesn't return anything. " global receive_lock def listener(conn): _terminated = self.read_nodestate(2) listener_terminated = False while (not (_terminated or ...
Listen for incoming messages in one thread, manage the network injector in another. Doesn't return anything.
src/server/server.py
listen
D3P-Dell-Part-Picker/Axonet
0
python
def listen(self, connection): "Listen for incoming messages in one thread, manage the network injector in another.\n Doesn't return anything. " global receive_lock def listener(conn): _terminated = self.read_nodestate(2) listener_terminated = False while (not (_terminated or ...
def listen(self, connection): "Listen for incoming messages in one thread, manage the network injector in another.\n Doesn't return anything. " global receive_lock def listener(conn): _terminated = self.read_nodestate(2) listener_terminated = False while (not (_terminated or ...
68d6a4c4726c7e9f930644edde04bdd091638773141362151623a7684521c703
def accuracy(output, target, topk=(1,)): 'Computes the precision@k for the specified values of k\n Arguments\n ' maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expand_as(pred)) res = [] ...
Computes the precision@k for the specified values of k Arguments
workshops/sagemaker/pytorch_utils/trainers/train_utils.py
accuracy
MLDA-NTU/AWS-Workshop-2020
4
python
def accuracy(output, target, topk=(1,)): 'Computes the precision@k for the specified values of k\n Arguments\n ' maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expand_as(pred)) res = [] ...
def accuracy(output, target, topk=(1,)): 'Computes the precision@k for the specified values of k\n Arguments\n ' maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expand_as(pred)) res = [] ...
8ffefed52666e89dbadf052b7284159b2e5f52d6e26e54981b5442d9f994518b
def longestValidParentheses(self, s): '\n :type s: str\n :rtype: int\n ' dp = [0 for _ in xrange(0, len(s))] left = 0 ans = 0 for i in xrange(0, len(s)): if (s[i] == '('): left += 1 elif (left > 0): left -= 1 dp[i] = (dp[(i - 1...
:type s: str :rtype: int
LeetcodeAlgorithms/032. Longest Valid Parentheses/longest-valid-parentheses.py
longestValidParentheses
Fenghuapiao/PyLeetcode
3
python
def longestValidParentheses(self, s): '\n :type s: str\n :rtype: int\n ' dp = [0 for _ in xrange(0, len(s))] left = 0 ans = 0 for i in xrange(0, len(s)): if (s[i] == '('): left += 1 elif (left > 0): left -= 1 dp[i] = (dp[(i - 1...
def longestValidParentheses(self, s): '\n :type s: str\n :rtype: int\n ' dp = [0 for _ in xrange(0, len(s))] left = 0 ans = 0 for i in xrange(0, len(s)): if (s[i] == '('): left += 1 elif (left > 0): left -= 1 dp[i] = (dp[(i - 1...
4eff0f0e70543e837a975e2abe9a945314663d776102623eb7213d4781568ddd
@stateful_op_impl(op) def elementwise_op(types, args=(), kwargs=None, pg=None): '\n Handles ``__torch_function__`` dispatch for the elementwise op such\n as ``torch.nn.functional.gelu`` or ``torch.nn.functional.relu``.\n This method computes on either a normal tensor or a sharded tensor.\n ...
Handles ``__torch_function__`` dispatch for the elementwise op such as ``torch.nn.functional.gelu`` or ``torch.nn.functional.relu``. This method computes on either a normal tensor or a sharded tensor.
colossalai/gemini/tensor/_ops/element_wise.py
elementwise_op
weiplanet/ColossalAI
0
python
@stateful_op_impl(op) def elementwise_op(types, args=(), kwargs=None, pg=None): '\n Handles ``__torch_function__`` dispatch for the elementwise op such\n as ``torch.nn.functional.gelu`` or ``torch.nn.functional.relu``.\n This method computes on either a normal tensor or a sharded tensor.\n ...
@stateful_op_impl(op) def elementwise_op(types, args=(), kwargs=None, pg=None): '\n Handles ``__torch_function__`` dispatch for the elementwise op such\n as ``torch.nn.functional.gelu`` or ``torch.nn.functional.relu``.\n This method computes on either a normal tensor or a sharded tensor.\n ...
21a81b34594ab2443a62f450cb1d56d2fcc14eacf6ff0788761ae016701fc3e9
def ExampleModule(Layer): '\n An example outline module that implements all possible\n abtract functions.\n ' def __init__(self, name, **args): Layer.__init__(self, name, **args) def after_init(self): '\n Executed automatically after the constructor. This method\n e...
An example outline module that implements all possible abtract functions.
samples/outline-modules/example.py
ExampleModule
danielkrajnik/OpenCue
334
python
def ExampleModule(Layer): '\n An example outline module that implements all possible\n abtract functions.\n ' def __init__(self, name, **args): Layer.__init__(self, name, **args) def after_init(self): '\n Executed automatically after the constructor. This method\n e...
def ExampleModule(Layer): '\n An example outline module that implements all possible\n abtract functions.\n ' def __init__(self, name, **args): Layer.__init__(self, name, **args) def after_init(self): '\n Executed automatically after the constructor. This method\n e...
5821d83980e253113f2a32482c16eaf35acb6de710e9ec3527f28f902fcdc26e
def after_init(self): '\n Executed automatically after the constructor. This method\n exists because the parent outline is not known in the constructor.\n ' outline = self.get_outline()
Executed automatically after the constructor. This method exists because the parent outline is not known in the constructor.
samples/outline-modules/example.py
after_init
danielkrajnik/OpenCue
334
python
def after_init(self): '\n Executed automatically after the constructor. This method\n exists because the parent outline is not known in the constructor.\n ' outline = self.get_outline()
def after_init(self): '\n Executed automatically after the constructor. This method\n exists because the parent outline is not known in the constructor.\n ' outline = self.get_outline()<|docstring|>Executed automatically after the constructor. This method exists because the parent outline...
2f0a9344a7302376a8df54e8d4f51a0a75baf99be63364c6e52f3864621ba6c0
def after_parented(self): '\n Executed automatically after the layer has been parented\n to another layer. This only happens when building\n composite layers, or, layers that contain other layers.\n ' parent_layer = self.get_parent()
Executed automatically after the layer has been parented to another layer. This only happens when building composite layers, or, layers that contain other layers.
samples/outline-modules/example.py
after_parented
danielkrajnik/OpenCue
334
python
def after_parented(self): '\n Executed automatically after the layer has been parented\n to another layer. This only happens when building\n composite layers, or, layers that contain other layers.\n ' parent_layer = self.get_parent()
def after_parented(self): '\n Executed automatically after the layer has been parented\n to another layer. This only happens when building\n composite layers, or, layers that contain other layers.\n ' parent_layer = self.get_parent()<|docstring|>Executed automatically after the laye...
f2bf106f69c7262a44f37055fef5c659be97066a29a43de7f8274c809fe3f6ca
def _setup(self): '\n Should contain any operations that should be run before the job\n is launched. This is the first time the session becomes\n available, so its possible to write data into the cue_archive.\n ' pass
Should contain any operations that should be run before the job is launched. This is the first time the session becomes available, so its possible to write data into the cue_archive.
samples/outline-modules/example.py
_setup
danielkrajnik/OpenCue
334
python
def _setup(self): '\n Should contain any operations that should be run before the job\n is launched. This is the first time the session becomes\n available, so its possible to write data into the cue_archive.\n ' pass
def _setup(self): '\n Should contain any operations that should be run before the job\n is launched. This is the first time the session becomes\n available, so its possible to write data into the cue_archive.\n ' pass<|docstring|>Should contain any operations that should be run befo...
2d4321e0252e1208002b9f5429121b9671583e463852ae2aab55f39e46975399
def _before_execute(self): '\n Run before execute. Generally used to create objects that do\n not serialize to pickle properly for job launch.\n '
Run before execute. Generally used to create objects that do not serialize to pickle properly for job launch.
samples/outline-modules/example.py
_before_execute
danielkrajnik/OpenCue
334
python
def _before_execute(self): '\n Run before execute. Generally used to create objects that do\n not serialize to pickle properly for job launch.\n '
def _before_execute(self): '\n Run before execute. Generally used to create objects that do\n not serialize to pickle properly for job launch.\n '<|docstring|>Run before execute. Generally used to create objects that do not serialize to pickle properly for job launch.<|endoftext|>
d9160cbe839e9e63c8bd9dc9702ce815f7549eee1383dc4f3b54d48aeff2348b
def _execute(self, frames): '\n The core module behavior should be implemented here. The\n frames argument contains an array of frames that the current\n instance is responsible for.\n ' pass
The core module behavior should be implemented here. The frames argument contains an array of frames that the current instance is responsible for.
samples/outline-modules/example.py
_execute
danielkrajnik/OpenCue
334
python
def _execute(self, frames): '\n The core module behavior should be implemented here. The\n frames argument contains an array of frames that the current\n instance is responsible for.\n ' pass
def _execute(self, frames): '\n The core module behavior should be implemented here. The\n frames argument contains an array of frames that the current\n instance is responsible for.\n ' pass<|docstring|>The core module behavior should be implemented here. The frames argument conta...
e9b5ff409167f327b43200eb94fc4912bbdf5637e28e148924b2be9f5eff3502
def _after_execute(self): '\n Run after execute even if execute throws an exception. Used for\n cleanup and implementing extra output checks like checking for\n black frames or log parsing.\n ' pass
Run after execute even if execute throws an exception. Used for cleanup and implementing extra output checks like checking for black frames or log parsing.
samples/outline-modules/example.py
_after_execute
danielkrajnik/OpenCue
334
python
def _after_execute(self): '\n Run after execute even if execute throws an exception. Used for\n cleanup and implementing extra output checks like checking for\n black frames or log parsing.\n ' pass
def _after_execute(self): '\n Run after execute even if execute throws an exception. Used for\n cleanup and implementing extra output checks like checking for\n black frames or log parsing.\n ' pass<|docstring|>Run after execute even if execute throws an exception. Used for cleanup...
87b331b7b6727abc70e1c8362d65841f69fb5fdbaa9941b34d55b6f0fca310d0
@staticmethod def __watcher__(fd_out, fd_err): ' Static method that checks the stderr file descriptor looking\n for new lines added at the end.\n It is enabled to also look into the stdout file descriptor, but\n currently not being used.\n\n :param fd_out: Standard output file descriptor...
Static method that checks the stderr file descriptor looking for new lines added at the end. It is enabled to also look into the stdout file descriptor, but currently not being used. :param fd_out: Standard output file descriptor. :param fd_err: Standard error file descriptor. :return: Yields each line found in the fd...
compss/programming_model/bindings/python/src/pycompss/util/interactive/outwatcher.py
__watcher__
alexbarcelo/compss
31
python
@staticmethod def __watcher__(fd_out, fd_err): ' Static method that checks the stderr file descriptor looking\n for new lines added at the end.\n It is enabled to also look into the stdout file descriptor, but\n currently not being used.\n\n :param fd_out: Standard output file descriptor...
@staticmethod def __watcher__(fd_out, fd_err): ' Static method that checks the stderr file descriptor looking\n for new lines added at the end.\n It is enabled to also look into the stdout file descriptor, but\n currently not being used.\n\n :param fd_out: Standard output file descriptor...
3a69163d1f91e0bc62097be4d77abac04950dc07e1ad7b7fae816c7ee3bb2084
def __std_follower__(self, out_file_name, err_file_name): ' Opens the out and error files and looks inside them thanks to the\n __watcher__ generator. This function puts into the queue any line\n of the error file which starts with "[ERRMGR]".\n\n :param out_file_name: Output file name.\n ...
Opens the out and error files and looks inside them thanks to the __watcher__ generator. This function puts into the queue any line of the error file which starts with "[ERRMGR]". :param out_file_name: Output file name. :param err_file_name: Error file name. :return: None
compss/programming_model/bindings/python/src/pycompss/util/interactive/outwatcher.py
__std_follower__
alexbarcelo/compss
31
python
def __std_follower__(self, out_file_name, err_file_name): ' Opens the out and error files and looks inside them thanks to the\n __watcher__ generator. This function puts into the queue any line\n of the error file which starts with "[ERRMGR]".\n\n :param out_file_name: Output file name.\n ...
def __std_follower__(self, out_file_name, err_file_name): ' Opens the out and error files and looks inside them thanks to the\n __watcher__ generator. This function puts into the queue any line\n of the error file which starts with "[ERRMGR]".\n\n :param out_file_name: Output file name.\n ...
579e65979d2e3abfdb0b33f98cd9b641ebf161e8ca87e0779dd59a8937bb6097
def start_watching(self): ' Starts a new thread in charge of monitoring the stdout and stderr\n files provided by the redirector.\n\n :return: None\n ' if is_redirected(): self.running = True (out_file_name, err_file_name) = get_redirection_file_names() thread = thre...
Starts a new thread in charge of monitoring the stdout and stderr files provided by the redirector. :return: None
compss/programming_model/bindings/python/src/pycompss/util/interactive/outwatcher.py
start_watching
alexbarcelo/compss
31
python
def start_watching(self): ' Starts a new thread in charge of monitoring the stdout and stderr\n files provided by the redirector.\n\n :return: None\n ' if is_redirected(): self.running = True (out_file_name, err_file_name) = get_redirection_file_names() thread = thre...
def start_watching(self): ' Starts a new thread in charge of monitoring the stdout and stderr\n files provided by the redirector.\n\n :return: None\n ' if is_redirected(): self.running = True (out_file_name, err_file_name) = get_redirection_file_names() thread = thre...
7858f509a605f5eb126e1d3d21bd81a34c96951e87f1954cdd083ac17ef19b6e
def stop_watching(self, clean=True): ' Stops the monitoring thread and cleans the redirection files\n if clean is True.\n\n :param clean: Remove the redirection files.\n :return: None\n ' self.running = False if clean: (out_file_name, err_file_name) = get_redirection_file...
Stops the monitoring thread and cleans the redirection files if clean is True. :param clean: Remove the redirection files. :return: None
compss/programming_model/bindings/python/src/pycompss/util/interactive/outwatcher.py
stop_watching
alexbarcelo/compss
31
python
def stop_watching(self, clean=True): ' Stops the monitoring thread and cleans the redirection files\n if clean is True.\n\n :param clean: Remove the redirection files.\n :return: None\n ' self.running = False if clean: (out_file_name, err_file_name) = get_redirection_file...
def stop_watching(self, clean=True): ' Stops the monitoring thread and cleans the redirection files\n if clean is True.\n\n :param clean: Remove the redirection files.\n :return: None\n ' self.running = False if clean: (out_file_name, err_file_name) = get_redirection_file...
667ce74100e4bb3f44ff591cf18d7cd8a986001c018c92525cf4683a4a61667e
def get_messages(self): ' Retrieves the current messages stored in the queue as a list\n of strings (one per line reported by the stdout and stderr files).\n\n :return: A list with the reported messages.\n ' current_messages = [] while (not self.messages.empty()): current_messag...
Retrieves the current messages stored in the queue as a list of strings (one per line reported by the stdout and stderr files). :return: A list with the reported messages.
compss/programming_model/bindings/python/src/pycompss/util/interactive/outwatcher.py
get_messages
alexbarcelo/compss
31
python
def get_messages(self): ' Retrieves the current messages stored in the queue as a list\n of strings (one per line reported by the stdout and stderr files).\n\n :return: A list with the reported messages.\n ' current_messages = [] while (not self.messages.empty()): current_messag...
def get_messages(self): ' Retrieves the current messages stored in the queue as a list\n of strings (one per line reported by the stdout and stderr files).\n\n :return: A list with the reported messages.\n ' current_messages = [] while (not self.messages.empty()): current_messag...
e848765dd6740a09440856b4ece802fb8505692e00005a7b8257568c96e7a77d
def get_network_endpoint_group(name=None, self_link=None, zone=None, opts=None): '\n Use this data source to access information about an existing resource.\n \n ' __args__ = dict() __args__['name'] = name __args__['selfLink'] = self_link __args__['zone'] = zone if (opts is None): ...
Use this data source to access information about an existing resource.
sdk/python/pulumi_gcp/compute/get_network_endpoint_group.py
get_network_endpoint_group
23doors/pulumi-gcp
1
python
def get_network_endpoint_group(name=None, self_link=None, zone=None, opts=None): '\n \n \n ' __args__ = dict() __args__['name'] = name __args__['selfLink'] = self_link __args__['zone'] = zone if (opts is None): opts = pulumi.InvokeOptions() if (opts.version is None): ...
def get_network_endpoint_group(name=None, self_link=None, zone=None, opts=None): '\n \n \n ' __args__ = dict() __args__['name'] = name __args__['selfLink'] = self_link __args__['zone'] = zone if (opts is None): opts = pulumi.InvokeOptions() if (opts.version is None): ...
a46db432b847ac4ef5b9ed39cd42229e767ccba20ac95b205347cbf6b1681d20
def calc(self, request, **args): '\n\n :param request: StatsComputeOptions\n :param args: dict\n :return:\n ' start_time = datetime.now() (ds, bounding_polygon, start_seconds_from_epoch, end_seconds_from_epoch, apply_seasonal_cycle_filter, apply_low_pass_filter, nparts_requested,...
:param request: StatsComputeOptions :param args: dict :return:
analysis/webservice/algorithms_spark/TimeSeriesSpark.py
calc
kevinmarlis/incubator-sdap-nexus
17
python
def calc(self, request, **args): '\n\n :param request: StatsComputeOptions\n :param args: dict\n :return:\n ' start_time = datetime.now() (ds, bounding_polygon, start_seconds_from_epoch, end_seconds_from_epoch, apply_seasonal_cycle_filter, apply_low_pass_filter, nparts_requested,...
def calc(self, request, **args): '\n\n :param request: StatsComputeOptions\n :param args: dict\n :return:\n ' start_time = datetime.now() (ds, bounding_polygon, start_seconds_from_epoch, end_seconds_from_epoch, apply_seasonal_cycle_filter, apply_low_pass_filter, nparts_requested,...
de5d5c0000027eff2cd91997189ffd6e65b020fdd87554076c60614b382b9434
def describe(source, *, source_type=None, **options): 'Describe the data source\n\n API | Usage\n -------- | --------\n Public | `from frictionless import describe`\n\n Parameters:\n source (any): data source\n source_type (str): source type - `schema`, `resource` or `package`\n ...
Describe the data source API | Usage -------- | -------- Public | `from frictionless import describe` Parameters: source (any): data source source_type (str): source type - `schema`, `resource` or `package` **options (dict): options for the underlaying describe function Returns: Package|Resour...
frictionless/describe/main.py
describe
kant/frictionless-py
0
python
def describe(source, *, source_type=None, **options): 'Describe the data source\n\n API | Usage\n -------- | --------\n Public | `from frictionless import describe`\n\n Parameters:\n source (any): data source\n source_type (str): source type - `schema`, `resource` or `package`\n ...
def describe(source, *, source_type=None, **options): 'Describe the data source\n\n API | Usage\n -------- | --------\n Public | `from frictionless import describe`\n\n Parameters:\n source (any): data source\n source_type (str): source type - `schema`, `resource` or `package`\n ...
9c90461c01f4e15e4a8c8b3c7fc728916eb5a99dc06fc1cbff437ce1b7bf8ff7
@abstractmethod def run(self, event: EventMessage) -> EventMessage: 'Runs the function when it is called directly\n :param event: Event which function wants running on, for which, this should be true:\n (is_prefixed is not false and command_args is not None)\n ' raise NotImplementedError
Runs the function when it is called directly :param event: Event which function wants running on, for which, this should be true: (is_prefixed is not false and command_args is not None)
hallo/function.py
run
joshcoales/Hallo
1
python
@abstractmethod def run(self, event: EventMessage) -> EventMessage: 'Runs the function when it is called directly\n :param event: Event which function wants running on, for which, this should be true:\n (is_prefixed is not false and command_args is not None)\n ' raise NotImplementedError
@abstractmethod def run(self, event: EventMessage) -> EventMessage: 'Runs the function when it is called directly\n :param event: Event which function wants running on, for which, this should be true:\n (is_prefixed is not false and command_args is not None)\n ' raise NotImplementedError<|d...
b94a5f33989c7d1c5589f4d6eb0b4ba514327c00ad53aa215941027a18f576e2
@staticmethod def is_persistent() -> bool: 'Returns boolean representing whether this function is supposed to be persistent or not' return False
Returns boolean representing whether this function is supposed to be persistent or not
hallo/function.py
is_persistent
joshcoales/Hallo
1
python
@staticmethod def is_persistent() -> bool: return False
@staticmethod def is_persistent() -> bool: return False<|docstring|>Returns boolean representing whether this function is supposed to be persistent or not<|endoftext|>
a64f36f7d92b21b4bdff7ab33df2f73b205154ad455516ffc249d5fd0e11100c
@staticmethod def load_function() -> 'Function': 'Loads the function, persistent functions only.' return Function()
Loads the function, persistent functions only.
hallo/function.py
load_function
joshcoales/Hallo
1
python
@staticmethod def load_function() -> 'Function': return Function()
@staticmethod def load_function() -> 'Function': return Function()<|docstring|>Loads the function, persistent functions only.<|endoftext|>
43b7be5eeb7de78e97b9ac48070f44f0bad9b79be668692772e72bb3707cf8d3
def save_function(self) -> None: 'Saves the function, persistent functions only.' return None
Saves the function, persistent functions only.
hallo/function.py
save_function
joshcoales/Hallo
1
python
def save_function(self) -> None: return None
def save_function(self) -> None: return None<|docstring|>Saves the function, persistent functions only.<|endoftext|>
2a08ebe7a8e4bbfe32593c61111ec62771669c6962fb6e49fd8bb6ee3dbbc81c
def get_passive_events(self) -> Set[Type[Event]]: 'Returns a list of events which this function may want to respond to in a passive way' return set()
Returns a list of events which this function may want to respond to in a passive way
hallo/function.py
get_passive_events
joshcoales/Hallo
1
python
def get_passive_events(self) -> Set[Type[Event]]: return set()
def get_passive_events(self) -> Set[Type[Event]]: return set()<|docstring|>Returns a list of events which this function may want to respond to in a passive way<|endoftext|>
bace9d17aefe562f6de091fbc52f6ccc33de08368002071f106b434df5126e6f
def passive_run(self, event: Event, hallo_obj) -> Optional[ServerEvent]: 'Replies to an event not directly addressed to the bot.\n :param event: Event which has called the function\n :param hallo_obj: Hallo object which fired the event.\n ' pass
Replies to an event not directly addressed to the bot. :param event: Event which has called the function :param hallo_obj: Hallo object which fired the event.
hallo/function.py
passive_run
joshcoales/Hallo
1
python
def passive_run(self, event: Event, hallo_obj) -> Optional[ServerEvent]: 'Replies to an event not directly addressed to the bot.\n :param event: Event which has called the function\n :param hallo_obj: Hallo object which fired the event.\n ' pass
def passive_run(self, event: Event, hallo_obj) -> Optional[ServerEvent]: 'Replies to an event not directly addressed to the bot.\n :param event: Event which has called the function\n :param hallo_obj: Hallo object which fired the event.\n ' pass<|docstring|>Replies to an event not directly ...
c830bb914bf1c985427eb861f9a527b1fd871fbc8c7568794b146a71d1ce222b
def get_help_name(self) -> str: 'Returns the name to be printed for help documentation' if (self.help_name is None): raise NotImplementedError return self.help_name
Returns the name to be printed for help documentation
hallo/function.py
get_help_name
joshcoales/Hallo
1
python
def get_help_name(self) -> str: if (self.help_name is None): raise NotImplementedError return self.help_name
def get_help_name(self) -> str: if (self.help_name is None): raise NotImplementedError return self.help_name<|docstring|>Returns the name to be printed for help documentation<|endoftext|>
2e6bfb8e59540150fe75b71777d54585c351610d442e21ca9ea39d99b0fa8bb9
def get_help_docs(self) -> str: '\n Returns the help documentation, specific to given arguments, if supplied\n ' if (self.help_docs is None): raise NotImplementedError return self.help_docs
Returns the help documentation, specific to given arguments, if supplied
hallo/function.py
get_help_docs
joshcoales/Hallo
1
python
def get_help_docs(self) -> str: '\n \n ' if (self.help_docs is None): raise NotImplementedError return self.help_docs
def get_help_docs(self) -> str: '\n \n ' if (self.help_docs is None): raise NotImplementedError return self.help_docs<|docstring|>Returns the help documentation, specific to given arguments, if supplied<|endoftext|>
b0c669b0e6f51366bec3424e7808d3dc0d55b61fc8a5650a16fd7330dc4dd63e
def get_names(self) -> Set[str]: 'Returns the list of names for directly addressing the function' self.names.add(self.help_name) return self.names
Returns the list of names for directly addressing the function
hallo/function.py
get_names
joshcoales/Hallo
1
python
def get_names(self) -> Set[str]: self.names.add(self.help_name) return self.names
def get_names(self) -> Set[str]: self.names.add(self.help_name) return self.names<|docstring|>Returns the list of names for directly addressing the function<|endoftext|>
533732a788b776d4d611ff86574a5b1e0bb1c208ebc3d92b6f271e485a84fdf8
def fill_insn(self, insn: Insn, model: Model) -> Optional[ProgInsn]: "Try to fill out an instruction\n\n This might fail if, for example, the model doesn't have enough\n registers with architectural values. In that case, return None.\n\n " if (insn.lsu is None): op_vals = [] ...
Try to fill out an instruction This might fail if, for example, the model doesn't have enough registers with architectural values. In that case, return None.
hw/ip/otbn/util/rig/gens/straight_line_insn.py
fill_insn
vanwinkeljan/opentitan
0
python
def fill_insn(self, insn: Insn, model: Model) -> Optional[ProgInsn]: "Try to fill out an instruction\n\n This might fail if, for example, the model doesn't have enough\n registers with architectural values. In that case, return None.\n\n " if (insn.lsu is None): op_vals = [] ...
def fill_insn(self, insn: Insn, model: Model) -> Optional[ProgInsn]: "Try to fill out an instruction\n\n This might fail if, for example, the model doesn't have enough\n registers with architectural values. In that case, return None.\n\n " if (insn.lsu is None): op_vals = [] ...
e8126722ac44199184bdd1a60d25b0d42b491bf59cc48d4735ce27def17a4cfa
@click.group() @click.pass_context def config(context): 'create config files required for running the pipeline.' pass
create config files required for running the pipeline.
BALSAMIC/commands/config/base.py
config
Clinical-Genomics/BALSAMIC
39
python
@click.group() @click.pass_context def config(context): pass
@click.group() @click.pass_context def config(context): pass<|docstring|>create config files required for running the pipeline.<|endoftext|>
8a94c49d7c2faee4e8c146081461acb9e07b2ec2fbff67664fc169300bedfaa2
def Score(self, result, score_aggregator=aggregators.Multiplier(), reasons_aggregator=aggregators.IdentityAggregator(), changed_files_aggregator=aggregators.ChangedFilesAggregator()): 'Aggregates score, reasons and changed_files from all the scorers.\n\n Note: This method sets confidence, reasons and changed_fil...
Aggregates score, reasons and changed_files from all the scorers. Note: This method sets confidence, reasons and changed_files of results.
appengine/findit/crash/scorers/aggregated_scorer.py
Score
mithro/chromium-infra
0
python
def Score(self, result, score_aggregator=aggregators.Multiplier(), reasons_aggregator=aggregators.IdentityAggregator(), changed_files_aggregator=aggregators.ChangedFilesAggregator()): 'Aggregates score, reasons and changed_files from all the scorers.\n\n Note: This method sets confidence, reasons and changed_fil...
def Score(self, result, score_aggregator=aggregators.Multiplier(), reasons_aggregator=aggregators.IdentityAggregator(), changed_files_aggregator=aggregators.ChangedFilesAggregator()): 'Aggregates score, reasons and changed_files from all the scorers.\n\n Note: This method sets confidence, reasons and changed_fil...
780a48e42bf18d934bc46056cde00621d2a2118984bb89a7bba1161536079982
def elemsens(teffs=[3500, 4500, 5500], loggs=[1.0, 3.0, 5.0], mhs=[0.0], delta=0.1, suffix='', complement=False): ' create sample with small delta of each element at grid of [teff,logg,mh] to see sensitivities\n ' els = np.array(['O', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'K', 'Ca', 'Ti', 'V', 'Cr', 'Mn', 'Co', ...
create sample with small delta of each element at grid of [teff,logg,mh] to see sensitivities
python/apogee/speclib/sample.py
elemsens
sdss/apogee
5
python
def elemsens(teffs=[3500, 4500, 5500], loggs=[1.0, 3.0, 5.0], mhs=[0.0], delta=0.1, suffix=, complement=False): ' \n ' els = np.array(['O', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'K', 'Ca', 'Ti', 'V', 'Cr', 'Mn', 'Co', 'Fe', 'Ni', 'Cu', 'Ge', 'Rb', 'Ce', 'Nd']) els_alpha = els[np.where(((((((els == 'O') | (el...
def elemsens(teffs=[3500, 4500, 5500], loggs=[1.0, 3.0, 5.0], mhs=[0.0], delta=0.1, suffix=, complement=False): ' \n ' els = np.array(['O', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'K', 'Ca', 'Ti', 'V', 'Cr', 'Mn', 'Co', 'Fe', 'Ni', 'Cu', 'Ge', 'Rb', 'Ce', 'Nd']) els_alpha = els[np.where(((((((els == 'O') | (el...
f08fc2aa5de80be086ea7c13695cb0fa299c075c9a022aec97ae9467c6bce02e
def sample(name='test', gridclass=None, eps=0.01, tefflim=[3000, 8000], dtlo=100.0, logglim=[(- 0.5), 5.5], mhlim=[(- 2.5), 0.75], nmlim=[(- 0.5), 2.0], cmlim=[(- 1.5), 1.0], emlim=[(- 0.5), 1.0], vmicrolim=[0.3, 4.8], amlim=[(- 0.5), 1.0], vrotlim=[1.5, 96.0], rot=True, nsamp=1, niso=None, elems='all', fact=1.0, offgr...
Generate a test sample of parameters and abundances from isochrones
python/apogee/speclib/sample.py
sample
sdss/apogee
5
python
def sample(name='test', gridclass=None, eps=0.01, tefflim=[3000, 8000], dtlo=100.0, logglim=[(- 0.5), 5.5], mhlim=[(- 2.5), 0.75], nmlim=[(- 0.5), 2.0], cmlim=[(- 1.5), 1.0], emlim=[(- 0.5), 1.0], vmicrolim=[0.3, 4.8], amlim=[(- 0.5), 1.0], vrotlim=[1.5, 96.0], rot=True, nsamp=1, niso=None, elems='all', fact=1.0, offgr...
def sample(name='test', gridclass=None, eps=0.01, tefflim=[3000, 8000], dtlo=100.0, logglim=[(- 0.5), 5.5], mhlim=[(- 2.5), 0.75], nmlim=[(- 0.5), 2.0], cmlim=[(- 1.5), 1.0], emlim=[(- 0.5), 1.0], vmicrolim=[0.3, 4.8], amlim=[(- 0.5), 1.0], vrotlim=[1.5, 96.0], rot=True, nsamp=1, niso=None, elems='all', fact=1.0, offgr...
3689fabfe43bbb694ec4e3cb31572f166ce0d14ed59fdc462b95bebb424969d9
def comp(file, true=None, truespec=None, hard=False, plot=False, minchi2=0.0, testid=None, rot=False): ' Compare input parameters with output results\n ' if (true is None): true = (file + '.ipf') if rot: names = ['id', 'vmicro', 'cm', 'nm', 'am', 'vrot', 'mh', 'logg', 'teff'] name...
Compare input parameters with output results
python/apogee/speclib/sample.py
comp
sdss/apogee
5
python
def comp(file, true=None, truespec=None, hard=False, plot=False, minchi2=0.0, testid=None, rot=False): ' \n ' if (true is None): true = (file + '.ipf') if rot: names = ['id', 'vmicro', 'cm', 'nm', 'am', 'vrot', 'mh', 'logg', 'teff'] names_spm = ['id', 'vmicro', 'cm', 'nm', 'am', '...
def comp(file, true=None, truespec=None, hard=False, plot=False, minchi2=0.0, testid=None, rot=False): ' \n ' if (true is None): true = (file + '.ipf') if rot: names = ['id', 'vmicro', 'cm', 'nm', 'am', 'vrot', 'mh', 'logg', 'teff'] names_spm = ['id', 'vmicro', 'cm', 'nm', 'am', '...
01847c495c20dee0e8206b946a5cae573dbe8c57231b2e7b3c3051492bfaca11
def clip(x, lim, eps=None): ' Utility routine to clip values within limits, and move slightly off edges if requested\n ' if np.isclose(x, 0.0): x = 0.0 tmp = np.max([lim[0], np.min([lim[1], x])]) if (eps is not None): if np.isclose(tmp, lim[0]): tmp += eps if np.is...
Utility routine to clip values within limits, and move slightly off edges if requested
python/apogee/speclib/sample.py
clip
sdss/apogee
5
python
def clip(x, lim, eps=None): ' \n ' if np.isclose(x, 0.0): x = 0.0 tmp = np.max([lim[0], np.min([lim[1], x])]) if (eps is not None): if np.isclose(tmp, lim[0]): tmp += eps if np.isclose(tmp, lim[1]): tmp -= eps return tmp
def clip(x, lim, eps=None): ' \n ' if np.isclose(x, 0.0): x = 0.0 tmp = np.max([lim[0], np.min([lim[1], x])]) if (eps is not None): if np.isclose(tmp, lim[0]): tmp += eps if np.isclose(tmp, lim[1]): tmp -= eps return tmp<|docstring|>Utility routine ...
47aaa5af025a50f1453b3242ea118ade9c7a1deeb1aa227480d0f26e4476c363
def upgrade(): 'Add ProposedTags.' op.create_table('proposed_tags', sa.Column('id', sa.Integer(), nullable=False), sa.Column('tags', sa.String(), nullable=True), sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column(...
Add ProposedTags.
migrations/versions/2019_05_13_a80fa524a2ba_add_proposed_tags.py
upgrade
fan-tom/sticker-finder
82
python
def upgrade(): op.create_table('proposed_tags', sa.Column('id', sa.Integer(), nullable=False), sa.Column('tags', sa.String(), nullable=True), sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('sticker_file_id', ...
def upgrade(): op.create_table('proposed_tags', sa.Column('id', sa.Integer(), nullable=False), sa.Column('tags', sa.String(), nullable=True), sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=False), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('sticker_file_id', ...
d34dcb8439f3d4d9415bd95ef2bf9fec12dc4b13cab697a2426f26847c082d2a
def downgrade(): 'Remove ProposedTags.' op.drop_index(op.f('ix_proposed_tags_user_id'), table_name='proposed_tags') op.drop_index(op.f('ix_proposed_tags_sticker_file_id'), table_name='proposed_tags') op.drop_index(op.f('ix_proposed_tags_chat_id'), table_name='proposed_tags') op.drop_table('proposed_...
Remove ProposedTags.
migrations/versions/2019_05_13_a80fa524a2ba_add_proposed_tags.py
downgrade
fan-tom/sticker-finder
82
python
def downgrade(): op.drop_index(op.f('ix_proposed_tags_user_id'), table_name='proposed_tags') op.drop_index(op.f('ix_proposed_tags_sticker_file_id'), table_name='proposed_tags') op.drop_index(op.f('ix_proposed_tags_chat_id'), table_name='proposed_tags') op.drop_table('proposed_tags')
def downgrade(): op.drop_index(op.f('ix_proposed_tags_user_id'), table_name='proposed_tags') op.drop_index(op.f('ix_proposed_tags_sticker_file_id'), table_name='proposed_tags') op.drop_index(op.f('ix_proposed_tags_chat_id'), table_name='proposed_tags') op.drop_table('proposed_tags')<|docstring|>Rem...
858c7d58b0de3540a7fc08982be9112042af7fee6582c7a0987b31e1d7656bf2
def get_native_encoding_type(): "Returns the encoding type that matches Python's native strings." if (sys.maxunicode == 65535): return 'UTF16' else: return 'UTF32'
Returns the encoding type that matches Python's native strings.
ml/language/python/mlapi.py
get_native_encoding_type
obulpathi/cloud
4
python
def get_native_encoding_type(): if (sys.maxunicode == 65535): return 'UTF16' else: return 'UTF32'
def get_native_encoding_type(): if (sys.maxunicode == 65535): return 'UTF16' else: return 'UTF32'<|docstring|>Returns the encoding type that matches Python's native strings.<|endoftext|>
2a770e5e29395293c979158098606286e32eaa34bc097a2538bf67ea6876305f
def read(fileToInput, outputPath=None, badFrameStrikes=BAD_FRAME_STRIKES, assembleHold=False, blockHeightOverride=False, blockWidthOverride=False, encryptionKey=None, scryptN=SCRYPT_N_DEFAULT, scryptR=SCRYPT_R_DEFAULT, scryptP=SCRYPT_P_DEFAULT, loggingLevel='info', loggingScreenOutput=True, loggingSaveOutput=False): ...
This is the high level function that decodes BitGlitter encoded images and video back into the files/folders contained within them. This along with write() are the two primary functions of this library.
bitglitter/read/read.py
read
Drunpy/BitGlitter
0
python
def read(fileToInput, outputPath=None, badFrameStrikes=BAD_FRAME_STRIKES, assembleHold=False, blockHeightOverride=False, blockWidthOverride=False, encryptionKey=None, scryptN=SCRYPT_N_DEFAULT, scryptR=SCRYPT_R_DEFAULT, scryptP=SCRYPT_P_DEFAULT, loggingLevel='info', loggingScreenOutput=True, loggingSaveOutput=False): ...
def read(fileToInput, outputPath=None, badFrameStrikes=BAD_FRAME_STRIKES, assembleHold=False, blockHeightOverride=False, blockWidthOverride=False, encryptionKey=None, scryptN=SCRYPT_N_DEFAULT, scryptR=SCRYPT_R_DEFAULT, scryptP=SCRYPT_P_DEFAULT, loggingLevel='info', loggingScreenOutput=True, loggingSaveOutput=False): ...
34c990759e041df56361a47e05ffe5d22a586c19ccb9fe105ce3435fef9f17bd
def sim_busy_all_clusters(trace): '\n Returns DataFrame of simultaneously busy cores irrespectively of cluster.\n ' data = {num_cores: trace.cpu.simultaneously_busy_time(num_cores, interval=None) for num_cores in xrange((len(ALL_CPUS) + 1))} total_duration = (trace.duration if (not INTERVAL) else INTE...
Returns DataFrame of simultaneously busy cores irrespectively of cluster.
examples/power_perf_tool.py
sim_busy_all_clusters
steven-eckhoff/ftrace
62
python
def sim_busy_all_clusters(trace): '\n \n ' data = {num_cores: trace.cpu.simultaneously_busy_time(num_cores, interval=None) for num_cores in xrange((len(ALL_CPUS) + 1))} total_duration = (trace.duration if (not INTERVAL) else INTERVAL.duration) return (Series(data=data.values(), index=data.keys(), ...
def sim_busy_all_clusters(trace): '\n \n ' data = {num_cores: trace.cpu.simultaneously_busy_time(num_cores, interval=None) for num_cores in xrange((len(ALL_CPUS) + 1))} total_duration = (trace.duration if (not INTERVAL) else INTERVAL.duration) return (Series(data=data.values(), index=data.keys(), ...
5cd808588ebada934b414ceba472d00a362ed2a6d362da80fe411469ded316bf
def sim_busy_by_clusters(trace, cpus): '\n Returns Series of simultaneously busy cores per `cpus` in cluster.\n ' data = {num_cores: trace.cpu.simultaneously_busy_time(num_cores, cpus=list(cpus), interval=None) for num_cores in xrange((len(cpus) + 1))} total_duration = (trace.duration if (not INTERVAL...
Returns Series of simultaneously busy cores per `cpus` in cluster.
examples/power_perf_tool.py
sim_busy_by_clusters
steven-eckhoff/ftrace
62
python
def sim_busy_by_clusters(trace, cpus): '\n \n ' data = {num_cores: trace.cpu.simultaneously_busy_time(num_cores, cpus=list(cpus), interval=None) for num_cores in xrange((len(cpus) + 1))} total_duration = (trace.duration if (not INTERVAL) else INTERVAL.duration) return (Series(data=data.values(), i...
def sim_busy_by_clusters(trace, cpus): '\n \n ' data = {num_cores: trace.cpu.simultaneously_busy_time(num_cores, cpus=list(cpus), interval=None) for num_cores in xrange((len(cpus) + 1))} total_duration = (trace.duration if (not INTERVAL) else INTERVAL.duration) return (Series(data=data.values(), i...
3b3d71001f38286f83646ecd1f68d32536ca950becb1bd5673df50fe0a577263
def __init__(self): '\n transform: 4x4 matrix to transform from local system to world system\n vertices_L: point locations expressed in local coordinate system in centimeters. vertices matrix will have shape\n 4xN\n vertices_W: point locations expressed in world coordinate system...
transform: 4x4 matrix to transform from local system to world system vertices_L: point locations expressed in local coordinate system in centimeters. vertices matrix will have shape 4xN vertices_W: point locations expressed in world coordinate system
simulator/util/LaneMarking.py
__init__
Iftimie/ChauffeurNet
99
python
def __init__(self): '\n transform: 4x4 matrix to transform from local system to world system\n vertices_L: point locations expressed in local coordinate system in centimeters. vertices matrix will have shape\n 4xN\n vertices_W: point locations expressed in world coordinate system...
def __init__(self): '\n transform: 4x4 matrix to transform from local system to world system\n vertices_L: point locations expressed in local coordinate system in centimeters. vertices matrix will have shape\n 4xN\n vertices_W: point locations expressed in world coordinate system...
8840dc0c180fe0fef40ea7f077885d4f1448be44c8d6d9dc5f061a26ebce8bab
def render(self, image, C): '\n :param image: image on which this actor will be renderd on\n :param C: camera matrix\n :return: image with this object renderd\n ' if (self.vertices_W.shape[1] > 1): (x, y) = C.project(self.vertices_W) pts = np.array([x, y]).T ...
:param image: image on which this actor will be renderd on :param C: camera matrix :return: image with this object renderd
simulator/util/LaneMarking.py
render
Iftimie/ChauffeurNet
99
python
def render(self, image, C): '\n :param image: image on which this actor will be renderd on\n :param C: camera matrix\n :return: image with this object renderd\n ' if (self.vertices_W.shape[1] > 1): (x, y) = C.project(self.vertices_W) pts = np.array([x, y]).T ...
def render(self, image, C): '\n :param image: image on which this actor will be renderd on\n :param C: camera matrix\n :return: image with this object renderd\n ' if (self.vertices_W.shape[1] > 1): (x, y) = C.project(self.vertices_W) pts = np.array([x, y]).T ...
01e8b9692e65a936364e2ccafb1843b0ea6369637d5c5db81e42f9abd0eb9fa8
@property def n_words(self): ' The dictionary size. ' if (not hasattr(self, 'word2idx')): raise Exception('Dictionary not built yet!') return len(self.word2idx)
The dictionary size.
data_utils/dataset_msrvtt.py
n_words
ahjeongseo/MASN---Attend-What-You-Need-Motion-Appearance-Synergistic-Networks-for-Video-Question-Answering
18
python
@property def n_words(self): ' ' if (not hasattr(self, 'word2idx')): raise Exception('Dictionary not built yet!') return len(self.word2idx)
@property def n_words(self): ' ' if (not hasattr(self, 'word2idx')): raise Exception('Dictionary not built yet!') return len(self.word2idx)<|docstring|>The dictionary size.<|endoftext|>
182dc42f9d670c653b3da584838b5fbf4e10117bc3815297cdac72dd9c8d57cf
def split_sentence_into_words(self, sentence, eos=True): '\n Split the given sentence (str) and enumerate the words as strs.\n Each word is normalized, i.e. lower-cased, non-alphabet characters\n like period (.) or comma (,) are stripped.\n When tokenizing, I use ``data_util.clean_str``\...
Split the given sentence (str) and enumerate the words as strs. Each word is normalized, i.e. lower-cased, non-alphabet characters like period (.) or comma (,) are stripped. When tokenizing, I use ``data_util.clean_str``
data_utils/dataset_msrvtt.py
split_sentence_into_words
ahjeongseo/MASN---Attend-What-You-Need-Motion-Appearance-Synergistic-Networks-for-Video-Question-Answering
18
python
def split_sentence_into_words(self, sentence, eos=True): '\n Split the given sentence (str) and enumerate the words as strs.\n Each word is normalized, i.e. lower-cased, non-alphabet characters\n like period (.) or comma (,) are stripped.\n When tokenizing, I use ``data_util.clean_str``\...
def split_sentence_into_words(self, sentence, eos=True): '\n Split the given sentence (str) and enumerate the words as strs.\n Each word is normalized, i.e. lower-cased, non-alphabet characters\n like period (.) or comma (,) are stripped.\n When tokenizing, I use ``data_util.clean_str``\...
91ba23e5685790be31435cab1d5dc44cc51e2ec15d0f2aaeaf57cdd72dec0c84
def create_answerset(self, ans_df): 'Generate 1000 answer set from train_qa.json.\n Args:\n trainqa_path: path to train_qa.json.\n answerset_path: generate answer set of mc_qa\n ' ans_num = 4000 answer_freq = ans_df['answer'].value_counts() answer_freq = list(answer_f...
Generate 1000 answer set from train_qa.json. Args: trainqa_path: path to train_qa.json. answerset_path: generate answer set of mc_qa
data_utils/dataset_msrvtt.py
create_answerset
ahjeongseo/MASN---Attend-What-You-Need-Motion-Appearance-Synergistic-Networks-for-Video-Question-Answering
18
python
def create_answerset(self, ans_df): 'Generate 1000 answer set from train_qa.json.\n Args:\n trainqa_path: path to train_qa.json.\n answerset_path: generate answer set of mc_qa\n ' ans_num = 4000 answer_freq = ans_df['answer'].value_counts() answer_freq = list(answer_f...
def create_answerset(self, ans_df): 'Generate 1000 answer set from train_qa.json.\n Args:\n trainqa_path: path to train_qa.json.\n answerset_path: generate answer set of mc_qa\n ' ans_num = 4000 answer_freq = ans_df['answer'].value_counts() answer_freq = list(answer_f...
bc8fff6663a19e8267a8c71d01b590974d5c48e030a08c4b840e253356e76c54
def build_word_vocabulary(self, all_sen=None, ans_df=None, word_count_threshold=0): "\n borrowed this implementation from @karpathy's neuraltalk.\n " log.infov('Building word vocabulary (%s) ...', self.dataset_name) if ((all_sen is None) or (ans_df is None)): (all_sen, ans_df) = self.g...
borrowed this implementation from @karpathy's neuraltalk.
data_utils/dataset_msrvtt.py
build_word_vocabulary
ahjeongseo/MASN---Attend-What-You-Need-Motion-Appearance-Synergistic-Networks-for-Video-Question-Answering
18
python
def build_word_vocabulary(self, all_sen=None, ans_df=None, word_count_threshold=0): "\n \n " log.infov('Building word vocabulary (%s) ...', self.dataset_name) if ((all_sen is None) or (ans_df is None)): (all_sen, ans_df) = self.get_all_captions() all_captions_source = all_sen w...
def build_word_vocabulary(self, all_sen=None, ans_df=None, word_count_threshold=0): "\n \n " log.infov('Building word vocabulary (%s) ...', self.dataset_name) if ((all_sen is None) or (ans_df is None)): (all_sen, ans_df) = self.get_all_captions() all_captions_source = all_sen w...
1ff68f36a84c05b1f76231b1d3c0fc1cf1ce29047a5a5b2403882511cdc5567b
def get_all_captions(self): '\n Iterate caption strings associated in the vid/gifs.\n ' data_path = ('%s/train_qa.json' % self.csv_dir) with open(data_path, 'r') as f: data_df = pd.read_json(f) all_sents = list(data_df['question']) return (all_sents, data_df)
Iterate caption strings associated in the vid/gifs.
data_utils/dataset_msrvtt.py
get_all_captions
ahjeongseo/MASN---Attend-What-You-Need-Motion-Appearance-Synergistic-Networks-for-Video-Question-Answering
18
python
def get_all_captions(self): '\n \n ' data_path = ('%s/train_qa.json' % self.csv_dir) with open(data_path, 'r') as f: data_df = pd.read_json(f) all_sents = list(data_df['question']) return (all_sents, data_df)
def get_all_captions(self): '\n \n ' data_path = ('%s/train_qa.json' % self.csv_dir) with open(data_path, 'r') as f: data_df = pd.read_json(f) all_sents = list(data_df['question']) return (all_sents, data_df)<|docstring|>Iterate caption strings associated in the vid/gifs.<|endo...
c5b40a2d11eaf69c7e17b9d401b3f7932dd076ff62234bbd0a99f996cf354eb4
def convert_sentence_to_matrix(self, sentence, eos=True): '\n Convert the given sentence into word indices and masks.\n WARNING: Unknown words (not in vocabulary) are revmoed.\n\n Args:\n sentence: A str for unnormalized sentence, containing T words\n\n Returns:\n s...
Convert the given sentence into word indices and masks. WARNING: Unknown words (not in vocabulary) are revmoed. Args: sentence: A str for unnormalized sentence, containing T words Returns: sentence_word_indices : list of (at most) length T, each being a word index
data_utils/dataset_msrvtt.py
convert_sentence_to_matrix
ahjeongseo/MASN---Attend-What-You-Need-Motion-Appearance-Synergistic-Networks-for-Video-Question-Answering
18
python
def convert_sentence_to_matrix(self, sentence, eos=True): '\n Convert the given sentence into word indices and masks.\n WARNING: Unknown words (not in vocabulary) are revmoed.\n\n Args:\n sentence: A str for unnormalized sentence, containing T words\n\n Returns:\n s...
def convert_sentence_to_matrix(self, sentence, eos=True): '\n Convert the given sentence into word indices and masks.\n WARNING: Unknown words (not in vocabulary) are revmoed.\n\n Args:\n sentence: A str for unnormalized sentence, containing T words\n\n Returns:\n s...
c574caa08e1df0afa449b657f8a57a13e85b79bcdb625f02bd939112310a0d7f
def get_question(self, key): '\n Return question index for given key.\n ' question = self.data_df.loc[(key, ['question'])].values question = question[0] question = self.split_sentence_into_words(question, eos=False) q_refine = [] for w in question: q_refine.append(w) q_...
Return question index for given key.
data_utils/dataset_msrvtt.py
get_question
ahjeongseo/MASN---Attend-What-You-Need-Motion-Appearance-Synergistic-Networks-for-Video-Question-Answering
18
python
def get_question(self, key): '\n \n ' question = self.data_df.loc[(key, ['question'])].values question = question[0] question = self.split_sentence_into_words(question, eos=False) q_refine = [] for w in question: q_refine.append(w) q_refine = self.convert_sentence_to_ma...
def get_question(self, key): '\n \n ' question = self.data_df.loc[(key, ['question'])].values question = question[0] question = self.split_sentence_into_words(question, eos=False) q_refine = [] for w in question: q_refine.append(w) q_refine = self.convert_sentence_to_ma...
09b0a57baf3dbe6456e6b414bf63628df9fabf2144023ab50755230a040d5230
def tag_to_wn(self, tag): ' Convert between a Penn Treebank tag to a simplified Wordnet tag ' if tag.startswith('N'): return 'n' if tag.startswith('V'): return 'v' if tag.startswith('J'): return 'a' if tag.startswith('R'): return 'r' return None
Convert between a Penn Treebank tag to a simplified Wordnet tag
text_similarity/wordnet.py
tag_to_wn
sorindragan/ChatBot_Th
0
python
def tag_to_wn(self, tag): ' ' if tag.startswith('N'): return 'n' if tag.startswith('V'): return 'v' if tag.startswith('J'): return 'a' if tag.startswith('R'): return 'r' return None
def tag_to_wn(self, tag): ' ' if tag.startswith('N'): return 'n' if tag.startswith('V'): return 'v' if tag.startswith('J'): return 'a' if tag.startswith('R'): return 'r' return None<|docstring|>Convert between a Penn Treebank tag to a simplified Wordnet tag<|endo...
260a56c475c86ba09b486087048c90f6dab7e8f393bedf444ea18efbbaadd140
def tagged_to_synset(self, word, tag): ' Returns the first synset of the word given as parameter' wn_tag = self.tag_to_wn(tag) if (wn_tag is None): return None try: return wn.synsets(word, wn_tag)[0] except: return None
Returns the first synset of the word given as parameter
text_similarity/wordnet.py
tagged_to_synset
sorindragan/ChatBot_Th
0
python
def tagged_to_synset(self, word, tag): ' ' wn_tag = self.tag_to_wn(tag) if (wn_tag is None): return None try: return wn.synsets(word, wn_tag)[0] except: return None
def tagged_to_synset(self, word, tag): ' ' wn_tag = self.tag_to_wn(tag) if (wn_tag is None): return None try: return wn.synsets(word, wn_tag)[0] except: return None<|docstring|>Returns the first synset of the word given as parameter<|endoftext|>
2a418c1841f0d3052ed3bf7a14e24fcd8120d0e73fee86d41a57e7724c0c4446
def sentence_similarity(self, sentence1, sentence2): ' compute the sentence similarity using Wordnet ' if (sentence1.lower() == sentence2.lower()): return 2 sentence1 = pos_tag(word_tokenize(sentence1.lower())) sentence2 = pos_tag(word_tokenize(sentence2.lower())) synsets1 = reduce((lambda a...
compute the sentence similarity using Wordnet
text_similarity/wordnet.py
sentence_similarity
sorindragan/ChatBot_Th
0
python
def sentence_similarity(self, sentence1, sentence2): ' ' if (sentence1.lower() == sentence2.lower()): return 2 sentence1 = pos_tag(word_tokenize(sentence1.lower())) sentence2 = pos_tag(word_tokenize(sentence2.lower())) synsets1 = reduce((lambda acc, w: (acc if (self.tagged_to_synset(*w) is ...
def sentence_similarity(self, sentence1, sentence2): ' ' if (sentence1.lower() == sentence2.lower()): return 2 sentence1 = pos_tag(word_tokenize(sentence1.lower())) sentence2 = pos_tag(word_tokenize(sentence2.lower())) synsets1 = reduce((lambda acc, w: (acc if (self.tagged_to_synset(*w) is ...
5afe441d6cd5584d2d5acd37681a6dcbc720d7bcfb84808fd2f7df60230a84ea
def GetMessages(): 'Import and return the appropriate projects messages module.' return apis.GetMessagesModule('projects', 'v1beta1')
Import and return the appropriate projects messages module.
lib/googlecloudsdk/api_lib/projects/util.py
GetMessages
eyalev/gcloud
0
python
def GetMessages(): return apis.GetMessagesModule('projects', 'v1beta1')
def GetMessages(): return apis.GetMessagesModule('projects', 'v1beta1')<|docstring|>Import and return the appropriate projects messages module.<|endoftext|>
4ecc8cda2cf55a7fd1b64e72f6f15fa81e88340e46e0ff6fb0470bd85de28423
def GetClient(): 'Import and return the appropriate projects client.\n\n Returns:\n Cloud Resource Manager client for the appropriate release track.\n ' return apis.GetClientInstance('projects', 'v1beta1')
Import and return the appropriate projects client. Returns: Cloud Resource Manager client for the appropriate release track.
lib/googlecloudsdk/api_lib/projects/util.py
GetClient
eyalev/gcloud
0
python
def GetClient(): 'Import and return the appropriate projects client.\n\n Returns:\n Cloud Resource Manager client for the appropriate release track.\n ' return apis.GetClientInstance('projects', 'v1beta1')
def GetClient(): 'Import and return the appropriate projects client.\n\n Returns:\n Cloud Resource Manager client for the appropriate release track.\n ' return apis.GetClientInstance('projects', 'v1beta1')<|docstring|>Import and return the appropriate projects client. Returns: Cloud Resource Manager cli...
b7b2a4efc6e650318c1722740d34e40b688ee94d8132ef7cf80e67cd73f03c16
def IsActive(project): "Returns true if the project's lifecycle state is 'active'.\n\n Args:\n project: A Project\n Returns:\n True if the Project's lifecycle state is 'active,' else False.\n " lifecycle_enum = GetMessages().Project.LifecycleStateValueValuesEnum return (project.lifecycleState == li...
Returns true if the project's lifecycle state is 'active'. Args: project: A Project Returns: True if the Project's lifecycle state is 'active,' else False.
lib/googlecloudsdk/api_lib/projects/util.py
IsActive
eyalev/gcloud
0
python
def IsActive(project): "Returns true if the project's lifecycle state is 'active'.\n\n Args:\n project: A Project\n Returns:\n True if the Project's lifecycle state is 'active,' else False.\n " lifecycle_enum = GetMessages().Project.LifecycleStateValueValuesEnum return (project.lifecycleState == li...
def IsActive(project): "Returns true if the project's lifecycle state is 'active'.\n\n Args:\n project: A Project\n Returns:\n True if the Project's lifecycle state is 'active,' else False.\n " lifecycle_enum = GetMessages().Project.LifecycleStateValueValuesEnum return (project.lifecycleState == li...
0a8be7ecaf6622a484da1597e212338ae538c27a0c236fa12fe4100b25e29990
def GetError(error): "Returns a more specific Projects error from an HttpError.\n\n Args:\n error: HttpError resulting from unsuccessful call to API.\n\n Returns:\n Specific error based on error reason in HttpError.\n\n First line will parse project ID out of error url.\n Example:\n URL = .../v1beta1/pr...
Returns a more specific Projects error from an HttpError. Args: error: HttpError resulting from unsuccessful call to API. Returns: Specific error based on error reason in HttpError. First line will parse project ID out of error url. Example: URL = .../v1beta1/projects/BAD_ID?prettyPrint=True&alt=json project_i...
lib/googlecloudsdk/api_lib/projects/util.py
GetError
eyalev/gcloud
0
python
def GetError(error): "Returns a more specific Projects error from an HttpError.\n\n Args:\n error: HttpError resulting from unsuccessful call to API.\n\n Returns:\n Specific error based on error reason in HttpError.\n\n First line will parse project ID out of error url.\n Example:\n URL = .../v1beta1/pr...
def GetError(error): "Returns a more specific Projects error from an HttpError.\n\n Args:\n error: HttpError resulting from unsuccessful call to API.\n\n Returns:\n Specific error based on error reason in HttpError.\n\n First line will parse project ID out of error url.\n Example:\n URL = .../v1beta1/pr...
efc24e5ee0c9ca76506bb2fbcee8b2e647c22828b0d7206d737f7236d8c17623
def HandleKnownHttpErrors(func): 'Decorator that catches HttpError and raises corresponding error.' @functools.wraps(func) def CatchHTTPErrorRaiseProjectError(*args, **kwargs): try: return func(*args, **kwargs) except exceptions.HttpError as error: processed_error = ...
Decorator that catches HttpError and raises corresponding error.
lib/googlecloudsdk/api_lib/projects/util.py
HandleKnownHttpErrors
eyalev/gcloud
0
python
def HandleKnownHttpErrors(func): @functools.wraps(func) def CatchHTTPErrorRaiseProjectError(*args, **kwargs): try: return func(*args, **kwargs) except exceptions.HttpError as error: processed_error = GetError(error) if (not processed_error): ...
def HandleKnownHttpErrors(func): @functools.wraps(func) def CatchHTTPErrorRaiseProjectError(*args, **kwargs): try: return func(*args, **kwargs) except exceptions.HttpError as error: processed_error = GetError(error) if (not processed_error): ...