hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
⌀
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
165a83b94a4ded18c8d30df32707f5df9a36823e
theLaborInVain/thelaborinvain_com
blog/app/routes.py
[ "MIT" ]
Python
update_asset
<not_specific>
def update_asset(asset_type, asset_oid): """ Pulls the asset, calls the update method. """ asset_object = models.get_asset(asset_type, ObjectId(asset_oid)) asset_object.update() return flask.Response( response=json.dumps(asset_object.serialize(), default=json_util.default), status=200, ...
Pulls the asset, calls the update method.
Pulls the asset, calls the update method.
[ "Pulls", "the", "asset", "calls", "the", "update", "method", "." ]
def update_asset(asset_type, asset_oid): asset_object = models.get_asset(asset_type, ObjectId(asset_oid)) asset_object.update() return flask.Response( response=json.dumps(asset_object.serialize(), default=json_util.default), status=200, mimetype='application/json', )
[ "def", "update_asset", "(", "asset_type", ",", "asset_oid", ")", ":", "asset_object", "=", "models", ".", "get_asset", "(", "asset_type", ",", "ObjectId", "(", "asset_oid", ")", ")", "asset_object", ".", "update", "(", ")", "return", "flask", ".", "Response"...
Pulls the asset, calls the update method.
[ "Pulls", "the", "asset", "calls", "the", "update", "method", "." ]
[ "\"\"\" Pulls the asset, calls the update method. \"\"\"" ]
[ { "param": "asset_type", "type": null }, { "param": "asset_oid", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "asset_type", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "asset_oid", "type": null, "docstring": null, "docstring...
165a83b94a4ded18c8d30df32707f5df9a36823e
theLaborInVain/thelaborinvain_com
blog/app/routes.py
[ "MIT" ]
Python
edit_post
<not_specific>
def edit_post(post_oid): """ Pulls a post for editing in the webapp. """ # first, make sure we can even get a post to edit post_object = posts.Post(_id=ObjectId(post_oid)) # the GET is for editing in the webapp; the POST # is for updating MDB if flask.request.method == 'GET': if not f...
Pulls a post for editing in the webapp.
Pulls a post for editing in the webapp.
[ "Pulls", "a", "post", "for", "editing", "in", "the", "webapp", "." ]
def edit_post(post_oid): post_object = posts.Post(_id=ObjectId(post_oid)) if flask.request.method == 'GET': if not flask_login.current_user.is_authenticated: return flask.redirect(flask.url_for('admin')) return flask.render_template( 'admin_edit.html', post=po...
[ "def", "edit_post", "(", "post_oid", ")", ":", "post_object", "=", "posts", ".", "Post", "(", "_id", "=", "ObjectId", "(", "post_oid", ")", ")", "if", "flask", ".", "request", ".", "method", "==", "'GET'", ":", "if", "not", "flask_login", ".", "current...
Pulls a post for editing in the webapp.
[ "Pulls", "a", "post", "for", "editing", "in", "the", "webapp", "." ]
[ "\"\"\" Pulls a post for editing in the webapp. \"\"\"", "# first, make sure we can even get a post to edit", "# the GET is for editing in the webapp; the POST ", "# is for updating MDB", "# if flesk.request.method == 'POST'" ]
[ { "param": "post_oid", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "post_oid", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
165a83b94a4ded18c8d30df32707f5df9a36823e
theLaborInVain/thelaborinvain_com
blog/app/routes.py
[ "MIT" ]
Python
upload_file
<not_specific>
def upload_file(): """ Accepts a post containing a file, parks it in uploads. """ # redirect to admin it NOT a post if flask.request.method == 'GET': return flask.redirect(flask.url_for('admin')) logger = util.get_logger(log_name='upload') def allowed_file(filename): """ private m...
Accepts a post containing a file, parks it in uploads.
Accepts a post containing a file, parks it in uploads.
[ "Accepts", "a", "post", "containing", "a", "file", "parks", "it", "in", "uploads", "." ]
def upload_file(): if flask.request.method == 'GET': return flask.redirect(flask.url_for('admin')) logger = util.get_logger(log_name='upload') def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() \ in app.config['ALLOWED_EXTENSIONS'] proce...
[ "def", "upload_file", "(", ")", ":", "if", "flask", ".", "request", ".", "method", "==", "'GET'", ":", "return", "flask", ".", "redirect", "(", "flask", ".", "url_for", "(", "'admin'", ")", ")", "logger", "=", "util", ".", "get_logger", "(", "log_name"...
Accepts a post containing a file, parks it in uploads.
[ "Accepts", "a", "post", "containing", "a", "file", "parks", "it", "in", "uploads", "." ]
[ "\"\"\" Accepts a post containing a file, parks it in uploads. \"\"\"", "# redirect to admin it NOT a post", "\"\"\" private method to check file names for ext. \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
165a83b94a4ded18c8d30df32707f5df9a36823e
theLaborInVain/thelaborinvain_com
blog/app/routes.py
[ "MIT" ]
Python
inject_template_scope
<not_specific>
def inject_template_scope(): """ Injects the consent cookie into scope. """ injections = dict() def cookies_check(): value = flask.request.cookies.get('cookie_consent') return value == 'true' injections.update(cookies_check=cookies_check) return injections
Injects the consent cookie into scope.
Injects the consent cookie into scope.
[ "Injects", "the", "consent", "cookie", "into", "scope", "." ]
def inject_template_scope(): injections = dict() def cookies_check(): value = flask.request.cookies.get('cookie_consent') return value == 'true' injections.update(cookies_check=cookies_check) return injections
[ "def", "inject_template_scope", "(", ")", ":", "injections", "=", "dict", "(", ")", "def", "cookies_check", "(", ")", ":", "value", "=", "flask", ".", "request", ".", "cookies", ".", "get", "(", "'cookie_consent'", ")", "return", "value", "==", "'true'", ...
Injects the consent cookie into scope.
[ "Injects", "the", "consent", "cookie", "into", "scope", "." ]
[ "\"\"\" Injects the consent cookie into scope. \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
9bcedc565394e86aad21858370ef3f20d82822b5
theLaborInVain/thelaborinvain_com
blog/app/models/__init__.py
[ "MIT" ]
Python
new
null
def new(self): """ Adds a new record to MDB. """ if not hasattr(self, 'required_attribs'): self.required_attribs = [] # sanity check for req_var in self.required_attribs: if req_var not in self.kwargs: err = "The '%s' kwarg is required when creat...
Adds a new record to MDB.
Adds a new record to MDB.
[ "Adds", "a", "new", "record", "to", "MDB", "." ]
def new(self): if not hasattr(self, 'required_attribs'): self.required_attribs = [] for req_var in self.required_attribs: if req_var not in self.kwargs: err = "The '%s' kwarg is required when creating new %s!" msg = err % (req_var, self.collection)...
[ "def", "new", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'required_attribs'", ")", ":", "self", ".", "required_attribs", "=", "[", "]", "for", "req_var", "in", "self", ".", "required_attribs", ":", "if", "req_var", "not", "in", "...
Adds a new record to MDB.
[ "Adds", "a", "new", "record", "to", "MDB", "." ]
[ "\"\"\" Adds a new record to MDB. \"\"\"", "# sanity check", "# do it" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9bcedc565394e86aad21858370ef3f20d82822b5
theLaborInVain/thelaborinvain_com
blog/app/models/__init__.py
[ "MIT" ]
Python
save
<not_specific>
def save(self, verbose=app.config['DEBUG']): """ Saves the object's self.data_model attribs to its self.collection in the MDB. """ # sanity check if not hasattr(self, '_id'): err = "'%s.%s' record requires '_id' attrib to save!" raise AttributeError( ...
Saves the object's self.data_model attribs to its self.collection in the MDB.
Saves the object's self.data_model attribs to its self.collection in the MDB.
[ "Saves", "the", "object", "'", "s", "self", ".", "data_model", "attribs", "to", "its", "self", ".", "collection", "in", "the", "MDB", "." ]
def save(self, verbose=app.config['DEBUG']): if not hasattr(self, '_id'): err = "'%s.%s' record requires '_id' attrib to save!" raise AttributeError( err % (app.config['MDB'].name, self.collection) ) record = {'_id': self._id} for key, value_ty...
[ "def", "save", "(", "self", ",", "verbose", "=", "app", ".", "config", "[", "'DEBUG'", "]", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_id'", ")", ":", "err", "=", "\"'%s.%s' record requires '_id' attrib to save!\"", "raise", "AttributeError", "("...
Saves the object's self.data_model attribs to its self.collection in the MDB.
[ "Saves", "the", "object", "'", "s", "self", ".", "data_model", "attribs", "to", "its", "self", ".", "collection", "in", "the", "MDB", "." ]
[ "\"\"\" Saves the object's self.data_model attribs to its self.collection\n in the MDB. \"\"\"", "# sanity check", "# make a record, enforce the data model", "# save and, if verbose, log about it", "# set self.update_on, created_by, because most models support it" ]
[ { "param": "self", "type": null }, { "param": "verbose", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "verbose", "type": null, "docstring": null, "docstring_tokens"...
9bcedc565394e86aad21858370ef3f20d82822b5
theLaborInVain/thelaborinvain_com
blog/app/models/__init__.py
[ "MIT" ]
Python
update
null
def update(self, verbose=True): """ Uses flask.request.json values to update an initialized object. Keys have to be in the self.data_model to be supported. """ params = flask.request.json for key, value in params.items(): if value == 'None': value = None ...
Uses flask.request.json values to update an initialized object. Keys have to be in the self.data_model to be supported.
Uses flask.request.json values to update an initialized object. Keys have to be in the self.data_model to be supported.
[ "Uses", "flask", ".", "request", ".", "json", "values", "to", "update", "an", "initialized", "object", ".", "Keys", "have", "to", "be", "in", "the", "self", ".", "data_model", "to", "be", "supported", "." ]
def update(self, verbose=True): params = flask.request.json for key, value in params.items(): if value == 'None': value = None if key == 'updated_on': value = datetime.now() if key in self.data_model.keys(): if self.data...
[ "def", "update", "(", "self", ",", "verbose", "=", "True", ")", ":", "params", "=", "flask", ".", "request", ".", "json", "for", "key", ",", "value", "in", "params", ".", "items", "(", ")", ":", "if", "value", "==", "'None'", ":", "value", "=", "...
Uses flask.request.json values to update an initialized object.
[ "Uses", "flask", ".", "request", ".", "json", "values", "to", "update", "an", "initialized", "object", "." ]
[ "\"\"\" Uses flask.request.json values to update an initialized object.\n Keys have to be in the self.data_model to be supported. \"\"\"", "# unfuck javascript-style date strings", "# set the self.attribute values" ]
[ { "param": "self", "type": null }, { "param": "verbose", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "verbose", "type": null, "docstring": null, "docstring_tokens"...
9bcedc565394e86aad21858370ef3f20d82822b5
theLaborInVain/thelaborinvain_com
blog/app/models/__init__.py
[ "MIT" ]
Python
update_password
null
def update_password(self, new_password=None): """ Hashes 'new_password' and saves it as the password. """ self.password = generate_password_hash(new_password) if self.save(verbose=False): self.logger.warn('Updated password! %s' % self) else: raise AttributeError...
Hashes 'new_password' and saves it as the password.
Hashes 'new_password' and saves it as the password.
[ "Hashes", "'", "new_password", "'", "and", "saves", "it", "as", "the", "password", "." ]
def update_password(self, new_password=None): self.password = generate_password_hash(new_password) if self.save(verbose=False): self.logger.warn('Updated password! %s' % self) else: raise AttributeError('Password update failed!')
[ "def", "update_password", "(", "self", ",", "new_password", "=", "None", ")", ":", "self", ".", "password", "=", "generate_password_hash", "(", "new_password", ")", "if", "self", ".", "save", "(", "verbose", "=", "False", ")", ":", "self", ".", "logger", ...
Hashes 'new_password' and saves it as the password.
[ "Hashes", "'", "new_password", "'", "and", "saves", "it", "as", "the", "password", "." ]
[ "\"\"\" Hashes 'new_password' and saves it as the password. \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "new_password", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "new_password", "type": null, "docstring": null, "docstring_to...
7242fb00c3dab3cd000a14913128b651b1a32873
theLaborInVain/thelaborinvain_com
blog/app/models/posts.py
[ "MIT" ]
Python
serialize
<not_specific>
def serialize(self): """ Expands the image_id onto a pseudo attrib called 'image'. """ output = copy(self.record) output['image'] = images.expand_image(output['image_id']) return output
Expands the image_id onto a pseudo attrib called 'image'.
Expands the image_id onto a pseudo attrib called 'image'.
[ "Expands", "the", "image_id", "onto", "a", "pseudo", "attrib", "called", "'", "image", "'", "." ]
def serialize(self): output = copy(self.record) output['image'] = images.expand_image(output['image_id']) return output
[ "def", "serialize", "(", "self", ")", ":", "output", "=", "copy", "(", "self", ".", "record", ")", "output", "[", "'image'", "]", "=", "images", ".", "expand_image", "(", "output", "[", "'image_id'", "]", ")", "return", "output" ]
Expands the image_id onto a pseudo attrib called 'image'.
[ "Expands", "the", "image_id", "onto", "a", "pseudo", "attrib", "called", "'", "image", "'", "." ]
[ "\"\"\" Expands the image_id onto a pseudo attrib called 'image'. \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7242fb00c3dab3cd000a14913128b651b1a32873
theLaborInVain/thelaborinvain_com
blog/app/models/posts.py
[ "MIT" ]
Python
serialize
<not_specific>
def serialize(self): """ Returns a fancy version of a post. """ # expand the hero image output = copy(self.record) try: output['hero_image'] = images.expand_image(output['hero_image']) except KeyError: output['hero_image'] = {'base_name': 'unknown_image.j...
Returns a fancy version of a post.
Returns a fancy version of a post.
[ "Returns", "a", "fancy", "version", "of", "a", "post", "." ]
def serialize(self): output = copy(self.record) try: output['hero_image'] = images.expand_image(output['hero_image']) except KeyError: output['hero_image'] = {'base_name': 'unknown_image.jpg'} output['html_hero_image'] = \ '<img class="webfeedsFeatured...
[ "def", "serialize", "(", "self", ")", ":", "output", "=", "copy", "(", "self", ".", "record", ")", "try", ":", "output", "[", "'hero_image'", "]", "=", "images", ".", "expand_image", "(", "output", "[", "'hero_image'", "]", ")", "except", "KeyError", "...
Returns a fancy version of a post.
[ "Returns", "a", "fancy", "version", "of", "a", "post", "." ]
[ "\"\"\" Returns a fancy version of a post. \"\"\"", "# expand the hero image", "# loop through attachment oids and expand", "# now, create some HTML from the plaintext" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7242fb00c3dab3cd000a14913128b651b1a32873
theLaborInVain/thelaborinvain_com
blog/app/models/posts.py
[ "MIT" ]
Python
update
null
def update(self): """ Calls the parent class update() method, then does some additional stuff required by the post object. """ was_published = getattr(self, 'published', False) # manage the attachments/tags/list (of OIDs) before update/save for attrib in ['attachments', 'tags',...
Calls the parent class update() method, then does some additional stuff required by the post object.
Calls the parent class update() method, then does some additional stuff required by the post object.
[ "Calls", "the", "parent", "class", "update", "()", "method", "then", "does", "some", "additional", "stuff", "required", "by", "the", "post", "object", "." ]
def update(self): was_published = getattr(self, 'published', False) for attrib in ['attachments', 'tags', 'paints']: if flask.request.json.get(attrib, None) is not None: setattr( self, attrib, list(set( ...
[ "def", "update", "(", "self", ")", ":", "was_published", "=", "getattr", "(", "self", ",", "'published'", ",", "False", ")", "for", "attrib", "in", "[", "'attachments'", ",", "'tags'", ",", "'paints'", "]", ":", "if", "flask", ".", "request", ".", "jso...
Calls the parent class update() method, then does some additional stuff required by the post object.
[ "Calls", "the", "parent", "class", "update", "()", "method", "then", "does", "some", "additional", "stuff", "required", "by", "the", "post", "object", "." ]
[ "\"\"\" Calls the parent class update() method, then does some additional\n stuff required by the post object. \"\"\"", "# manage the attachments/tags/list (of OIDs) before update/save", "# log tag and paint usage", "# a_object = Tag(_id=tag_dict['$oid'])" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7242fb00c3dab3cd000a14913128b651b1a32873
theLaborInVain/thelaborinvain_com
blog/app/models/posts.py
[ "MIT" ]
Python
save
<not_specific>
def save(self, verbose=True): """ Calls the base class method after creating the handle. """ date_str = self.created_on.strftime(util.YMDHMS) self.handle = util.string_to_handle(date_str + ' ' + self.title) return super().save(verbose)
Calls the base class method after creating the handle.
Calls the base class method after creating the handle.
[ "Calls", "the", "base", "class", "method", "after", "creating", "the", "handle", "." ]
def save(self, verbose=True): date_str = self.created_on.strftime(util.YMDHMS) self.handle = util.string_to_handle(date_str + ' ' + self.title) return super().save(verbose)
[ "def", "save", "(", "self", ",", "verbose", "=", "True", ")", ":", "date_str", "=", "self", ".", "created_on", ".", "strftime", "(", "util", ".", "YMDHMS", ")", "self", ".", "handle", "=", "util", ".", "string_to_handle", "(", "date_str", "+", "' '", ...
Calls the base class method after creating the handle.
[ "Calls", "the", "base", "class", "method", "after", "creating", "the", "handle", "." ]
[ "\"\"\" Calls the base class method after creating the handle. \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "verbose", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "verbose", "type": null, "docstring": null, "docstring_tokens"...
855f6d3cbaeb533612d9ef19272fa6a5bb9f3458
theLaborInVain/thelaborinvain_com
blog/app/admin/__main__.py
[ "MIT" ]
Python
create_user
<not_specific>
def create_user(): """ Gets new user stuff from CLI prompts. High tech shit! """ print('') name = input(" Name? ") email = input(" Email? ") password = getpass.getpass(prompt=' Password: ', stream=None) return name.strip(), email.lower().strip(), password
Gets new user stuff from CLI prompts. High tech shit!
Gets new user stuff from CLI prompts. High tech shit!
[ "Gets", "new", "user", "stuff", "from", "CLI", "prompts", ".", "High", "tech", "shit!" ]
def create_user(): print('') name = input(" Name? ") email = input(" Email? ") password = getpass.getpass(prompt=' Password: ', stream=None) return name.strip(), email.lower().strip(), password
[ "def", "create_user", "(", ")", ":", "print", "(", "''", ")", "name", "=", "input", "(", "\" Name? \"", ")", "email", "=", "input", "(", "\" Email? \"", ")", "password", "=", "getpass", ".", "getpass", "(", "prompt", "=", "' Password: '", ",", "stream...
Gets new user stuff from CLI prompts.
[ "Gets", "new", "user", "stuff", "from", "CLI", "prompts", "." ]
[ "\"\"\" Gets new user stuff from CLI prompts. High tech shit! \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
c941ffb3d60cf01b02c90af0cf87fbb950fb25a9
s25malho/PyTextWorldAdventure
TextWorldAdventure.py
[ "MIT" ]
Python
look
null
def look(self, noun): ''' returns none and accepts noun argument which the user wants to look at and prints the name and the description of the passed-in noun. Looks at the player or location if noun is "me" or "here" correspondingly. Effects: prints name and description of the ...
returns none and accepts noun argument which the user wants to look at and prints the name and the description of the passed-in noun. Looks at the player or location if noun is "me" or "here" correspondingly. Effects: prints name and description of the passed-in noun. ...
returns none and accepts noun argument which the user wants to look at and prints the name and the description of the passed-in noun. Looks at the player or location if noun is "me" or "here" correspondingly. Effects: prints name and description of the passed-in noun. World Str -> None
[ "returns", "none", "and", "accepts", "noun", "argument", "which", "the", "user", "wants", "to", "look", "at", "and", "prints", "the", "name", "and", "the", "description", "of", "the", "passed", "-", "in", "noun", ".", "Looks", "at", "the", "player", "or"...
def look(self, noun): if noun == "me": self.player.look() elif noun == "here": self.player.location.look() elif noun in list(map(lambda z: z.name ,self.player.inventory)): for item in self.player.inventory: if item.name == noun: ...
[ "def", "look", "(", "self", ",", "noun", ")", ":", "if", "noun", "==", "\"me\"", ":", "self", ".", "player", ".", "look", "(", ")", "elif", "noun", "==", "\"here\"", ":", "self", ".", "player", ".", "location", ".", "look", "(", ")", "elif", "nou...
returns none and accepts noun argument which the user wants to look at and prints the name and the description of the passed-in noun.
[ "returns", "none", "and", "accepts", "noun", "argument", "which", "the", "user", "wants", "to", "look", "at", "and", "prints", "the", "name", "and", "the", "description", "of", "the", "passed", "-", "in", "noun", "." ]
[ "'''\n returns none and accepts noun argument which the user wants to \n look at and prints the name and the description of the passed-in noun.\n Looks at the player or location if noun is \"me\" or \"here\" correspondingly.\n Effects: prints name and description of the passed-in noun. \...
[ { "param": "self", "type": null }, { "param": "noun", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "noun", "type": null, "docstring": null, "docstring_tokens": [...
c941ffb3d60cf01b02c90af0cf87fbb950fb25a9
s25malho/PyTextWorldAdventure
TextWorldAdventure.py
[ "MIT" ]
Python
save
null
def save(self, fname): ''' returns none and takes in fname(Str) other than self as an argument. Function writes the complete current state of the World in the textfile fname. Effects: current state of the World is written in the text file fname save: W...
returns none and takes in fname(Str) other than self as an argument. Function writes the complete current state of the World in the textfile fname. Effects: current state of the World is written in the text file fname save: World Str -> None
returns none and takes in fname(Str) other than self as an argument. Function writes the complete current state of the World in the textfile fname. Effects: current state of the World is written in the text file fname World Str -> None
[ "returns", "none", "and", "takes", "in", "fname", "(", "Str", ")", "other", "than", "self", "as", "an", "argument", ".", "Function", "writes", "the", "complete", "current", "state", "of", "the", "World", "in", "the", "textfile", "fname", ".", "Effects", ...
def save(self, fname): f = open(fname, "w") for items in self.player.inventory: f.write("thing #{0} {1}\n".format(items.id, items.name)) f.write("{0}\n".format(items.description)) for items in self.rooms: for t in items.contents: f.write("thing...
[ "def", "save", "(", "self", ",", "fname", ")", ":", "f", "=", "open", "(", "fname", ",", "\"w\"", ")", "for", "items", "in", "self", ".", "player", ".", "inventory", ":", "f", ".", "write", "(", "\"thing #{0} {1}\\n\"", ".", "format", "(", "items", ...
returns none and takes in fname(Str) other than self as an argument.
[ "returns", "none", "and", "takes", "in", "fname", "(", "Str", ")", "other", "than", "self", "as", "an", "argument", "." ]
[ "'''\n returns none and takes in fname(Str) other than self as an argument. \n Function writes the complete current state of the World in the textfile fname.\n Effects: current state of the World is written in the \n text file fname\n \n save: World Str -> None\n ...
[ { "param": "self", "type": null }, { "param": "fname", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fname", "type": null, "docstring": null, "docstring_tokens": ...
c941ffb3d60cf01b02c90af0cf87fbb950fb25a9
s25malho/PyTextWorldAdventure
TextWorldAdventure.py
[ "MIT" ]
Python
load
<not_specific>
def load(fname): ''' returns a complete new World after reading information from the textfile fname (Str). load: Str -> World ''' ww = open(fname, "r") next_line_str = ww.readline() ret = {} rooms_list = [] player = Player(id) while next_line_str != '': split_lis...
returns a complete new World after reading information from the textfile fname (Str). load: Str -> World
returns a complete new World after reading information from the textfile fname (Str). load: Str -> World
[ "returns", "a", "complete", "new", "World", "after", "reading", "information", "from", "the", "textfile", "fname", "(", "Str", ")", ".", "load", ":", "Str", "-", ">", "World" ]
def load(fname): ww = open(fname, "r") next_line_str = ww.readline() ret = {} rooms_list = [] player = Player(id) while next_line_str != '': split_list = next_line_str.split() if "thing" in split_list[0]: method = Thing(int(split_list[1][1:])) method.name ...
[ "def", "load", "(", "fname", ")", ":", "ww", "=", "open", "(", "fname", ",", "\"r\"", ")", "next_line_str", "=", "ww", ".", "readline", "(", ")", "ret", "=", "{", "}", "rooms_list", "=", "[", "]", "player", "=", "Player", "(", "id", ")", "while",...
returns a complete new World after reading information from the textfile fname (Str).
[ "returns", "a", "complete", "new", "World", "after", "reading", "information", "from", "the", "textfile", "fname", "(", "Str", ")", "." ]
[ "'''\n returns a complete new World after reading information from the textfile fname\n (Str).\n load: Str -> World\n \n '''" ]
[ { "param": "fname", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "fname", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
f1f47b998fdbd69d0f9c069bf792afd9efc83fc6
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
baseGraph.py
[ "MIT" ]
Python
add_legend_bottom
null
def add_legend_bottom(self, title, mean, model, color='wheat', multimodal=False): """ Generate a legend at the bottom of the graph args: title: type of measure (i.e:'coverage = ' or 'precision = ') mean: mean results for each discretization model (i.e: (0.7, 0.5) for a co...
Generate a legend at the bottom of the graph args: title: type of measure (i.e:'coverage = ' or 'precision = ') mean: mean results for each discretization model (i.e: (0.7, 0.5) for a coverage of 0.7 for MDLP and 0.5 for Decile) model: Different discretization model ...
Generate a legend at the bottom of the graph args: title: type of measure mean: mean results for each discretization model for a coverage of 0.7 for MDLP and 0.5 for Decile) model: Different discretization model that are measure
[ "Generate", "a", "legend", "at", "the", "bottom", "of", "the", "graph", "args", ":", "title", ":", "type", "of", "measure", "mean", ":", "mean", "results", "for", "each", "discretization", "model", "for", "a", "coverage", "of", "0", ".", "7", "for", "M...
def add_legend_bottom(self, title, mean, model, color='wheat', multimodal=False): ax = plt.subplot(111) if not multimodal: text = "Accuracy of the black box: " + str(self.accuracy) props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) ax.text(0.05, 0.95, text,...
[ "def", "add_legend_bottom", "(", "self", ",", "title", ",", "mean", ",", "model", ",", "color", "=", "'wheat'", ",", "multimodal", "=", "False", ")", ":", "ax", "=", "plt", ".", "subplot", "(", "111", ")", "if", "not", "multimodal", ":", "text", "=",...
Generate a legend at the bottom of the graph args: title: type of measure (i.e:'coverage = ' or 'precision = ') mean: mean results for each discretization model (i.e: (0.7, 0.5) for a coverage of 0.7 for MDLP and 0.5 for Decile) model: Different discretization model that are measure
[ "Generate", "a", "legend", "at", "the", "bottom", "of", "the", "graph", "args", ":", "title", ":", "type", "of", "measure", "(", "i", ".", "e", ":", "'", "coverage", "=", "'", "or", "'", "precision", "=", "'", ")", "mean", ":", "mean", "results", ...
[ "\"\"\"\n Generate a legend at the bottom of the graph\n args:\n title: type of measure (i.e:'coverage = ' or 'precision = ')\n mean: mean results for each discretization model (i.e: (0.7, 0.5) for a coverage of 0.7 for MDLP and 0.5 for Decile)\n model: Different discr...
[ { "param": "self", "type": null }, { "param": "title", "type": null }, { "param": "mean", "type": null }, { "param": "model", "type": null }, { "param": "color", "type": null }, { "param": "multimodal", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "title", "type": null, "docstring": null, "docstring_tokens": ...
2c05473a2e173a37ac49dfe1e2c1d19c63a3c01e
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingspheres.py
[ "MIT" ]
Python
find_counterfactual
<not_specific>
def find_counterfactual(self): """ Finds the decision border then perform projections to make the explanation sparse. """ ennemies_, radius = self.exploration() ennemies = sorted(ennemies_, key= lambda x: pairwise_distances(self.obs_to_interprete...
Finds the decision border then perform projections to make the explanation sparse.
Finds the decision border then perform projections to make the explanation sparse.
[ "Finds", "the", "decision", "border", "then", "perform", "projections", "to", "make", "the", "explanation", "sparse", "." ]
def find_counterfactual(self): ennemies_, radius = self.exploration() ennemies = sorted(ennemies_, key= lambda x: pairwise_distances(self.obs_to_interprete.reshape(1, -1), x.reshape(1, -1))) self.e_star = ennemies[0] if self.sparse == True: o...
[ "def", "find_counterfactual", "(", "self", ")", ":", "ennemies_", ",", "radius", "=", "self", ".", "exploration", "(", ")", "ennemies", "=", "sorted", "(", "ennemies_", ",", "key", "=", "lambda", "x", ":", "pairwise_distances", "(", "self", ".", "obs_to_in...
Finds the decision border then perform projections to make the explanation sparse.
[ "Finds", "the", "decision", "border", "then", "perform", "projections", "to", "make", "the", "explanation", "sparse", "." ]
[ "\"\"\"\n Finds the decision border then perform projections to make the explanation sparse.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2c05473a2e173a37ac49dfe1e2c1d19c63a3c01e
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingspheres.py
[ "MIT" ]
Python
exploration
<not_specific>
def exploration(self): """ Exploration of the feature space to find the decision boundary. Generation of instances in growing hyperspherical layers. """ n_ennemies_ = 999 radius_ = self.first_radius while n_ennemies_ > 0: first_layer_ = self.ennemies_...
Exploration of the feature space to find the decision boundary. Generation of instances in growing hyperspherical layers.
Exploration of the feature space to find the decision boundary. Generation of instances in growing hyperspherical layers.
[ "Exploration", "of", "the", "feature", "space", "to", "find", "the", "decision", "boundary", ".", "Generation", "of", "instances", "in", "growing", "hyperspherical", "layers", "." ]
def exploration(self): n_ennemies_ = 999 radius_ = self.first_radius while n_ennemies_ > 0: first_layer_ = self.ennemies_in_layer_((0, radius_), self.caps, self.n_in_layer) n_ennemies_ = first_layer_.shape[0] radius_ = radius_ / self.dicrease_radius ...
[ "def", "exploration", "(", "self", ")", ":", "n_ennemies_", "=", "999", "radius_", "=", "self", ".", "first_radius", "while", "n_ennemies_", ">", "0", ":", "first_layer_", "=", "self", ".", "ennemies_in_layer_", "(", "(", "0", ",", "radius_", ")", ",", "...
Exploration of the feature space to find the decision boundary.
[ "Exploration", "of", "the", "feature", "space", "to", "find", "the", "decision", "boundary", "." ]
[ "\"\"\"\n Exploration of the feature space to find the decision boundary. Generation of instances in growing hyperspherical layers.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2c05473a2e173a37ac49dfe1e2c1d19c63a3c01e
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingspheres.py
[ "MIT" ]
Python
ennemies_in_layer_
<not_specific>
def ennemies_in_layer_(self, segment, caps=None, n=1000): """ Basis for GS: generates a hypersphere layer, labels it with the blackbox and returns the instances that are predicted to belong to the target class. """ layer = self.generate_inside_spheres(self.obs_to_interprete, segment, n) ...
Basis for GS: generates a hypersphere layer, labels it with the blackbox and returns the instances that are predicted to belong to the target class.
Basis for GS: generates a hypersphere layer, labels it with the blackbox and returns the instances that are predicted to belong to the target class.
[ "Basis", "for", "GS", ":", "generates", "a", "hypersphere", "layer", "labels", "it", "with", "the", "blackbox", "and", "returns", "the", "instances", "that", "are", "predicted", "to", "belong", "to", "the", "target", "class", "." ]
def ennemies_in_layer_(self, segment, caps=None, n=1000): layer = self.generate_inside_spheres(self.obs_to_interprete, segment, n) if caps != None: cap_fn_ = lambda x: min(max(x, caps[0]), caps[1]) layer = np.vectorize(cap_fn_)(layer) preds_ = self.prediction_fn(layer) ...
[ "def", "ennemies_in_layer_", "(", "self", ",", "segment", ",", "caps", "=", "None", ",", "n", "=", "1000", ")", ":", "layer", "=", "self", ".", "generate_inside_spheres", "(", "self", ".", "obs_to_interprete", ",", "segment", ",", "n", ")", "if", "caps",...
Basis for GS: generates a hypersphere layer, labels it with the blackbox and returns the instances that are predicted to belong to the target class.
[ "Basis", "for", "GS", ":", "generates", "a", "hypersphere", "layer", "labels", "it", "with", "the", "blackbox", "and", "returns", "the", "instances", "that", "are", "predicted", "to", "belong", "to", "the", "target", "class", "." ]
[ "\"\"\"\n Basis for GS: generates a hypersphere layer, labels it with the blackbox and returns the instances that are predicted to belong to the target class.\n \"\"\"", "#cap here: not optimal" ]
[ { "param": "self", "type": null }, { "param": "segment", "type": null }, { "param": "caps", "type": null }, { "param": "n", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "segment", "type": null, "docstring": null, "docstring_tokens"...
2c05473a2e173a37ac49dfe1e2c1d19c63a3c01e
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingspheres.py
[ "MIT" ]
Python
feature_selection
<not_specific>
def feature_selection(self, counterfactual): """ Projection step of the GS algorithm. Make projections to make (e* - obs_to_interprete) sparse. Heuristic: sort the coordinates of np.abs(e* - obs_to_interprete) in ascending order and project as long as it does not change the predicted class ...
Projection step of the GS algorithm. Make projections to make (e* - obs_to_interprete) sparse. Heuristic: sort the coordinates of np.abs(e* - obs_to_interprete) in ascending order and project as long as it does not change the predicted class Inputs: counterfactual: e*
Projection step of the GS algorithm. Make projections to make (e* - obs_to_interprete) sparse. Heuristic: sort the coordinates of np.abs(e* - obs_to_interprete) in ascending order and project as long as it does not change the predicted class e
[ "Projection", "step", "of", "the", "GS", "algorithm", ".", "Make", "projections", "to", "make", "(", "e", "*", "-", "obs_to_interprete", ")", "sparse", ".", "Heuristic", ":", "sort", "the", "coordinates", "of", "np", ".", "abs", "(", "e", "*", "-", "ob...
def feature_selection(self, counterfactual): if self.verbose == True: print("Feature selection...") move_sorted = sorted(enumerate(abs(counterfactual - self.obs_to_interprete)), key=lambda x: x[1]) move_sorted = [x[0] for x in move_sorted if x[1] > 0.0] out = counterfactual.c...
[ "def", "feature_selection", "(", "self", ",", "counterfactual", ")", ":", "if", "self", ".", "verbose", "==", "True", ":", "print", "(", "\"Feature selection...\"", ")", "move_sorted", "=", "sorted", "(", "enumerate", "(", "abs", "(", "counterfactual", "-", ...
Projection step of the GS algorithm.
[ "Projection", "step", "of", "the", "GS", "algorithm", "." ]
[ "\"\"\"\n Projection step of the GS algorithm. Make projections to make (e* - obs_to_interprete) sparse. \n Heuristic: sort the coordinates of np.abs(e* - obs_to_interprete) in ascending order and project as long as it does not change the predicted class\n \n Inputs:\n counterfact...
[ { "param": "self", "type": null }, { "param": "counterfactual", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "counterfactual", "type": null, "docstring": null, "docstring_...
2c05473a2e173a37ac49dfe1e2c1d19c63a3c01e
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingspheres.py
[ "MIT" ]
Python
feature_selection_all
<not_specific>
def feature_selection_all(self, counterfactual): """ Try all possible combinations of projections to make the explanation as sparse as possible. Warning: really long! """ if self.verbose == True: print("Grid search for projections...") for k in range(self.obs...
Try all possible combinations of projections to make the explanation as sparse as possible. Warning: really long!
Try all possible combinations of projections to make the explanation as sparse as possible. Warning: really long!
[ "Try", "all", "possible", "combinations", "of", "projections", "to", "make", "the", "explanation", "as", "sparse", "as", "possible", ".", "Warning", ":", "really", "long!" ]
def feature_selection_all(self, counterfactual): if self.verbose == True: print("Grid search for projections...") for k in range(self.obs_to_interprete.size): print('==========', k, '==========') for combo in combinations(range(self.obs_to_interprete.size), k): ...
[ "def", "feature_selection_all", "(", "self", ",", "counterfactual", ")", ":", "if", "self", ".", "verbose", "==", "True", ":", "print", "(", "\"Grid search for projections...\"", ")", "for", "k", "in", "range", "(", "self", ".", "obs_to_interprete", ".", "size...
Try all possible combinations of projections to make the explanation as sparse as possible.
[ "Try", "all", "possible", "combinations", "of", "projections", "to", "make", "the", "explanation", "as", "sparse", "as", "possible", "." ]
[ "\"\"\"\n Try all possible combinations of projections to make the explanation as sparse as possible. \n Warning: really long!\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "counterfactual", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "counterfactual", "type": null, "docstring": null, "docstring_...
2c05473a2e173a37ac49dfe1e2c1d19c63a3c01e
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingspheres.py
[ "MIT" ]
Python
generate_inside_spheres
<not_specific>
def generate_inside_spheres(self, center, segment, n, feature_variance=None): """ Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_var...
Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Array of variance for each continuous feature
"center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Array of variance for each continuous feature
[ "\"", "center", "\"", "corresponds", "to", "the", "target", "instance", "to", "explain", "Segment", "corresponds", "to", "the", "size", "of", "the", "hypersphere", "n", "corresponds", "to", "the", "number", "of", "instances", "generated", "feature_variance", ":"...
def generate_inside_spheres(self, center, segment, n, feature_variance=None): def norm(v): v= np.linalg.norm(v, ord=2, axis=1) return v d = center.shape[0] z = np.random.normal(0, 1, (n, d)) u = np.random.uniform(segment[0]**d, segment[1]**d, n) r = u**(1/...
[ "def", "generate_inside_spheres", "(", "self", ",", "center", ",", "segment", ",", "n", ",", "feature_variance", "=", "None", ")", ":", "def", "norm", "(", "v", ")", ":", "v", "=", "np", ".", "linalg", ".", "norm", "(", "v", ",", "ord", "=", "2", ...
Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Array of variance for each continuous feature
[ "Args", ":", "\"", "center", "\"", "corresponds", "to", "the", "target", "instance", "to", "explain", "Segment", "corresponds", "to", "the", "size", "of", "the", "hypersphere", "n", "corresponds", "to", "the", "number", "of", "instances", "generated", "feature...
[ "\"\"\"\n Args:\n \"center\" corresponds to the target instance to explain\n Segment corresponds to the size of the hypersphere\n n corresponds to the number of instances generated\n feature_variance: Array of variance for each continuous feature\n \"\"\"", ...
[ { "param": "self", "type": null }, { "param": "center", "type": null }, { "param": "segment", "type": null }, { "param": "n", "type": null }, { "param": "feature_variance", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "center", "type": null, "docstring": null, "docstring_tokens":...
acb75881af18a8755c96f15ee240ad671152332b
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
tabular_user_experiments.py
[ "MIT" ]
Python
compute_score_interpretability_method
<not_specific>
def compute_score_interpretability_method(features_employed_by_explainer, features_employed_black_box): """ Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box """ precision = 0 recall = 0 for featur...
Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box
Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box
[ "Compute", "the", "score", "of", "the", "explanation", "method", "based", "on", "the", "features", "employed", "for", "the", "explanation", "compared", "to", "the", "features", "truely", "used", "by", "the", "black", "box" ]
def compute_score_interpretability_method(features_employed_by_explainer, features_employed_black_box): precision = 0 recall = 0 for feature_employe in features_employed_by_explainer: if feature_employe in features_employed_black_box: precision += 1 for feature_employe in features_em...
[ "def", "compute_score_interpretability_method", "(", "features_employed_by_explainer", ",", "features_employed_black_box", ")", ":", "precision", "=", "0", "recall", "=", "0", "for", "feature_employe", "in", "features_employed_by_explainer", ":", "if", "feature_employe", "i...
Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box
[ "Compute", "the", "score", "of", "the", "explanation", "method", "based", "on", "the", "features", "employed", "for", "the", "explanation", "compared", "to", "the", "features", "truely", "used", "by", "the", "black", "box" ]
[ "\"\"\"\n Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box\n \"\"\"" ]
[ { "param": "features_employed_by_explainer", "type": null }, { "param": "features_employed_black_box", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "features_employed_by_explainer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "features_employed_black_box", "type": null, ...
75ad78d9116960278d3f9d2893fd6dc6ddd2740a
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingfields.py
[ "MIT" ]
Python
find_counterfactual
<not_specific>
def find_counterfactual(self): """ Finds the decision border then perform projections to make the explanation sparse. """ ennemies_, radius = self.exploration() ennemies_ = sorted(ennemies_, key= lambda x: pairwise_distances(self.obs_to_interpret...
Finds the decision border then perform projections to make the explanation sparse.
Finds the decision border then perform projections to make the explanation sparse.
[ "Finds", "the", "decision", "border", "then", "perform", "projections", "to", "make", "the", "explanation", "sparse", "." ]
def find_counterfactual(self): ennemies_, radius = self.exploration() ennemies_ = sorted(ennemies_, key= lambda x: pairwise_distances(self.obs_to_interprete.reshape(1, -1), x.reshape(1, -1))) closest_ennemy_ = ennemies_[0] self.e_star = closest_ennemy_ ...
[ "def", "find_counterfactual", "(", "self", ")", ":", "ennemies_", ",", "radius", "=", "self", ".", "exploration", "(", ")", "ennemies_", "=", "sorted", "(", "ennemies_", ",", "key", "=", "lambda", "x", ":", "pairwise_distances", "(", "self", ".", "obs_to_i...
Finds the decision border then perform projections to make the explanation sparse.
[ "Finds", "the", "decision", "border", "then", "perform", "projections", "to", "make", "the", "explanation", "sparse", "." ]
[ "\"\"\"\n Finds the decision border then perform projections to make the explanation sparse.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
75ad78d9116960278d3f9d2893fd6dc6ddd2740a
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingfields.py
[ "MIT" ]
Python
exploration
<not_specific>
def exploration(self): """ Exploration of the feature space to find the decision boundary. Generation of instances in growing hyperspherical layers. """ n_ennemies_ = 999 radius_ = self.first_radius while n_ennemies_ > 0: first_layer_ = self.ennemies_...
Exploration of the feature space to find the decision boundary. Generation of instances in growing hyperspherical layers.
Exploration of the feature space to find the decision boundary. Generation of instances in growing hyperspherical layers.
[ "Exploration", "of", "the", "feature", "space", "to", "find", "the", "decision", "boundary", ".", "Generation", "of", "instances", "in", "growing", "hyperspherical", "layers", "." ]
def exploration(self): n_ennemies_ = 999 radius_ = self.first_radius while n_ennemies_ > 0: first_layer_ = self.ennemies_in_layer_((0, radius_), self.caps, self.n_in_layer, reducing_sphere=True) n_ennemies_ = first_layer_.shape[0] radius_ = radius_ / self.dicr...
[ "def", "exploration", "(", "self", ")", ":", "n_ennemies_", "=", "999", "radius_", "=", "self", ".", "first_radius", "while", "n_ennemies_", ">", "0", ":", "first_layer_", "=", "self", ".", "ennemies_in_layer_", "(", "(", "0", ",", "radius_", ")", ",", "...
Exploration of the feature space to find the decision boundary.
[ "Exploration", "of", "the", "feature", "space", "to", "find", "the", "decision", "boundary", "." ]
[ "\"\"\"\n Exploration of the feature space to find the decision boundary. Generation of instances in growing hyperspherical layers.\n \"\"\"", "#print(\"n ennemies\", n_ennemies_)", "#print(\"radius\", radius_)" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
75ad78d9116960278d3f9d2893fd6dc6ddd2740a
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingfields.py
[ "MIT" ]
Python
ennemies_in_layer_
<not_specific>
def ennemies_in_layer_(self, segment, caps=None, n=1000, reducing_sphere=False): """ Basis for GS: generates a hypersphere layer, labels it with the blackbox and returns the instances that are predicted to belong to the target class. """ if self.categorical_features != []: ...
Basis for GS: generates a hypersphere layer, labels it with the blackbox and returns the instances that are predicted to belong to the target class.
Basis for GS: generates a hypersphere layer, labels it with the blackbox and returns the instances that are predicted to belong to the target class.
[ "Basis", "for", "GS", ":", "generates", "a", "hypersphere", "layer", "labels", "it", "with", "the", "blackbox", "and", "returns", "the", "instances", "that", "are", "predicted", "to", "belong", "to", "the", "target", "class", "." ]
def ennemies_in_layer_(self, segment, caps=None, n=1000, reducing_sphere=False): if self.categorical_features != []: if self.farthest_distance_training_dataset is None: print("you must initialize a distance for the percentage distribution") else: percentag...
[ "def", "ennemies_in_layer_", "(", "self", ",", "segment", ",", "caps", "=", "None", ",", "n", "=", "1000", ",", "reducing_sphere", "=", "False", ")", ":", "if", "self", ".", "categorical_features", "!=", "[", "]", ":", "if", "self", ".", "farthest_distan...
Basis for GS: generates a hypersphere layer, labels it with the blackbox and returns the instances that are predicted to belong to the target class.
[ "Basis", "for", "GS", ":", "generates", "a", "hypersphere", "layer", "labels", "it", "with", "the", "blackbox", "and", "returns", "the", "instances", "that", "are", "predicted", "to", "belong", "to", "the", "target", "class", "." ]
[ "\"\"\"\n Basis for GS: generates a hypersphere layer, labels it with the blackbox \n and returns the instances that are predicted to belong to the target class.\n \"\"\"", "# If there are categorical features we must have a maximum distribution probability for changing the values of categori...
[ { "param": "self", "type": null }, { "param": "segment", "type": null }, { "param": "caps", "type": null }, { "param": "n", "type": null }, { "param": "reducing_sphere", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "segment", "type": null, "docstring": null, "docstring_tokens"...
75ad78d9116960278d3f9d2893fd6dc6ddd2740a
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingfields.py
[ "MIT" ]
Python
feature_selection
<not_specific>
def feature_selection(self, counterfactual): """ Projection step of the GS algorithm. Make projections to make (e* - obs_to_interprete) sparse. Heuristic: sort the coordinates of np.abs(e* - obs_to_interprete) in ascending order and project as long as it does not change the predicted class ...
Projection step of the GS algorithm. Make projections to make (e* - obs_to_interprete) sparse. Heuristic: sort the coordinates of np.abs(e* - obs_to_interprete) in ascending order and project as long as it does not change the predicted class Inputs: counterfactual: e*
Projection step of the GS algorithm. Make projections to make (e* - obs_to_interprete) sparse. Heuristic: sort the coordinates of np.abs(e* - obs_to_interprete) in ascending order and project as long as it does not change the predicted class Inputs: counterfactual: e
[ "Projection", "step", "of", "the", "GS", "algorithm", ".", "Make", "projections", "to", "make", "(", "e", "*", "-", "obs_to_interprete", ")", "sparse", ".", "Heuristic", ":", "sort", "the", "coordinates", "of", "np", ".", "abs", "(", "e", "*", "-", "ob...
def feature_selection(self, counterfactual): if self.verbose == True: print("Feature selection...") move_sorted = sorted(enumerate(abs(counterfactual - self.obs_to_interprete)), key=lambda x: x[1]) move_sorted = [x[0] for x in move_sorted if x[1] > 0.0] out = counterfactual.c...
[ "def", "feature_selection", "(", "self", ",", "counterfactual", ")", ":", "if", "self", ".", "verbose", "==", "True", ":", "print", "(", "\"Feature selection...\"", ")", "move_sorted", "=", "sorted", "(", "enumerate", "(", "abs", "(", "counterfactual", "-", ...
Projection step of the GS algorithm.
[ "Projection", "step", "of", "the", "GS", "algorithm", "." ]
[ "\"\"\"\n Projection step of the GS algorithm. Make projections to make (e* - obs_to_interprete) sparse. Heuristic: sort the coordinates of np.abs(e* - obs_to_interprete) in ascending order and project as long as it does not change the predicted class\n \n Inputs:\n counterfactual: e*\n ...
[ { "param": "self", "type": null }, { "param": "counterfactual", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "counterfactual", "type": null, "docstring": null, "docstring_...
75ad78d9116960278d3f9d2893fd6dc6ddd2740a
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/growingfields.py
[ "MIT" ]
Python
feature_selection_all
<not_specific>
def feature_selection_all(self, counterfactual): """ Try all possible combinations of projections to make the explanation as sparse as possible. Warning: really long! """ if self.verbose == True: print("Grid search for projections...") for k in range(self.obs...
Try all possible combinations of projections to make the explanation as sparse as possible. Warning: really long!
Try all possible combinations of projections to make the explanation as sparse as possible. Warning: really long!
[ "Try", "all", "possible", "combinations", "of", "projections", "to", "make", "the", "explanation", "as", "sparse", "as", "possible", ".", "Warning", ":", "really", "long!" ]
def feature_selection_all(self, counterfactual): if self.verbose == True: print("Grid search for projections...") for k in range(self.obs_to_interprete.size): print('==========', k, '==========') for combo in combinations(range(self.obs_to_interprete.size), k): ...
[ "def", "feature_selection_all", "(", "self", ",", "counterfactual", ")", ":", "if", "self", ".", "verbose", "==", "True", ":", "print", "(", "\"Grid search for projections...\"", ")", "for", "k", "in", "range", "(", "self", ".", "obs_to_interprete", ".", "size...
Try all possible combinations of projections to make the explanation as sparse as possible.
[ "Try", "all", "possible", "combinations", "of", "projections", "to", "make", "the", "explanation", "as", "sparse", "as", "possible", "." ]
[ "\"\"\"\n Try all possible combinations of projections to make the explanation as sparse as possible. \n Warning: really long!\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "counterfactual", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "counterfactual", "type": null, "docstring": null, "docstring_...
abe79dcd16996ddfa538ddc91b300c3db7436fd5
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
plot_functions.py
[ "MIT" ]
Python
pick_anchors_informations
<not_specific>
def pick_anchors_informations(anchors, x_min=-10, width=20, y_min=-10, height=20, compute=False): """ Function to store information about the anchors and return the position and size to draw the anchors Anchors is of the form : "2 < x <= 7, -5 > y" or any rule """ regex = re.compile(r"([+-]?\d+(?:\....
Function to store information about the anchors and return the position and size to draw the anchors Anchors is of the form : "2 < x <= 7, -5 > y" or any rule
Function to store information about the anchors and return the position and size to draw the anchors Anchors is of the form : "2 < x <= 7, -5 > y" or any rule
[ "Function", "to", "store", "information", "about", "the", "anchors", "and", "return", "the", "position", "and", "size", "to", "draw", "the", "anchors", "Anchors", "is", "of", "the", "form", ":", "\"", "2", "<", "x", "<", "=", "7", "-", "5", ">", "y",...
def pick_anchors_informations(anchors, x_min=-10, width=20, y_min=-10, height=20, compute=False): regex = re.compile(r"([+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)") if len(anchors) == 0: return x_min, y_min, width, height elif len(anchors) == 1: if "x" in anchors[0]: x_bounds = regex.f...
[ "def", "pick_anchors_informations", "(", "anchors", ",", "x_min", "=", "-", "10", ",", "width", "=", "20", ",", "y_min", "=", "-", "10", ",", "height", "=", "20", ",", "compute", "=", "False", ")", ":", "regex", "=", "re", ".", "compile", "(", "r\"...
Function to store information about the anchors and return the position and size to draw the anchors Anchors is of the form : "2 < x <= 7, -5 > y" or any rule
[ "Function", "to", "store", "information", "about", "the", "anchors", "and", "return", "the", "position", "and", "size", "to", "draw", "the", "anchors", "Anchors", "is", "of", "the", "form", ":", "\"", "2", "<", "x", "<", "=", "7", "-", "5", ">", "y",...
[ "\"\"\"\n Function to store information about the anchors and return the position and size to draw the anchors\n Anchors is of the form : \"2 < x <= 7, -5 > y\" or any rule\n \"\"\"" ]
[ { "param": "anchors", "type": null }, { "param": "x_min", "type": null }, { "param": "width", "type": null }, { "param": "y_min", "type": null }, { "param": "height", "type": null }, { "param": "compute", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "anchors", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "x_min", "type": null, "docstring": null, "docstring_tokens...
abe79dcd16996ddfa538ddc91b300c3db7436fd5
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
plot_functions.py
[ "MIT" ]
Python
draw_rectangle
null
def draw_rectangle(ax, x_min_anchors, y_min_anchors, width, height, cnt): """ Draw the rectangle upon the graphics """ if y_min_anchors != -10:#y_min-4: ax.plot([x_min_anchors, x_min_anchors + width], [y_min_anchors, y_min_anchors],'r-', color='grey', label='anchor border') if cnt == 1 else ax.p...
Draw the rectangle upon the graphics
Draw the rectangle upon the graphics
[ "Draw", "the", "rectangle", "upon", "the", "graphics" ]
def draw_rectangle(ax, x_min_anchors, y_min_anchors, width, height, cnt): if y_min_anchors != -10: ax.plot([x_min_anchors, x_min_anchors + width], [y_min_anchors, y_min_anchors],'r-', color='grey', label='anchor border') if cnt == 1 else ax.plot([x_min_anchors, x_min_anchors + width], [y_min_anchors, y_min_...
[ "def", "draw_rectangle", "(", "ax", ",", "x_min_anchors", ",", "y_min_anchors", ",", "width", ",", "height", ",", "cnt", ")", ":", "if", "y_min_anchors", "!=", "-", "10", ":", "ax", ".", "plot", "(", "[", "x_min_anchors", ",", "x_min_anchors", "+", "widt...
Draw the rectangle upon the graphics
[ "Draw", "the", "rectangle", "upon", "the", "graphics" ]
[ "\"\"\"\n Draw the rectangle upon the graphics\n \"\"\"", "#y_min-4:", "#x_min-4 :" ]
[ { "param": "ax", "type": null }, { "param": "x_min_anchors", "type": null }, { "param": "y_min_anchors", "type": null }, { "param": "width", "type": null }, { "param": "height", "type": null }, { "param": "cnt", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ax", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "x_min_anchors", "type": null, "docstring": null, "docstring_tok...
d05fdded23b578dbf8b09931be9132afd423b821
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
anchors/limes/lime_base.py
[ "MIT" ]
Python
forward_selection
<not_specific>
def forward_selection(self, data, labels, weights, num_features, model_regressor=None): """Iteratively adds features to the model""" if model_regressor is None: model_regressor = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state) clf = model_regressor used_fea...
Iteratively adds features to the model
Iteratively adds features to the model
[ "Iteratively", "adds", "features", "to", "the", "model" ]
def forward_selection(self, data, labels, weights, num_features, model_regressor=None): if model_regressor is None: model_regressor = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state) clf = model_regressor used_features = [] for _ in range(min(num_features, d...
[ "def", "forward_selection", "(", "self", ",", "data", ",", "labels", ",", "weights", ",", "num_features", ",", "model_regressor", "=", "None", ")", ":", "if", "model_regressor", "is", "None", ":", "model_regressor", "=", "Ridge", "(", "alpha", "=", "0", ",...
Iteratively adds features to the model
[ "Iteratively", "adds", "features", "to", "the", "model" ]
[ "\"\"\"Iteratively adds features to the model\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "data", "type": null }, { "param": "labels", "type": null }, { "param": "weights", "type": null }, { "param": "num_features", "type": null }, { "param": "model_regressor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data", "type": null, "docstring": null, "docstring_tokens": [...
d05fdded23b578dbf8b09931be9132afd423b821
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
anchors/limes/lime_base.py
[ "MIT" ]
Python
feature_selection
<not_specific>
def feature_selection(self, data, labels, weights, num_features, method, model_regressor=None): """Selects features for the model. see explain_instance_with_data to understand the parameters.""" if model_regressor is None: model_regressor = Ridge(alpha=0, fit_inte...
Selects features for the model. see explain_instance_with_data to understand the parameters.
Selects features for the model. see explain_instance_with_data to understand the parameters.
[ "Selects", "features", "for", "the", "model", ".", "see", "explain_instance_with_data", "to", "understand", "the", "parameters", "." ]
def feature_selection(self, data, labels, weights, num_features, method, model_regressor=None): if model_regressor is None: model_regressor = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state) if method == 'none': return np.array(range(data.shape[...
[ "def", "feature_selection", "(", "self", ",", "data", ",", "labels", ",", "weights", ",", "num_features", ",", "method", ",", "model_regressor", "=", "None", ")", ":", "if", "model_regressor", "is", "None", ":", "model_regressor", "=", "Ridge", "(", "alpha",...
Selects features for the model.
[ "Selects", "features", "for", "the", "model", "." ]
[ "\"\"\"Selects features for the model. see explain_instance_with_data to\n understand the parameters.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "data", "type": null }, { "param": "labels", "type": null }, { "param": "weights", "type": null }, { "param": "num_features", "type": null }, { "param": "method", "type": null }, { "param": "mod...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data", "type": null, "docstring": null, "docstring_tokens": [...
d05fdded23b578dbf8b09931be9132afd423b821
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
anchors/limes/lime_base.py
[ "MIT" ]
Python
explain_instance_with_data
<not_specific>
def explain_instance_with_data(self, neighborhood_data, neighborhood_labels, distances, label, num_features, f...
Takes perturbed data, labels and distances, returns explanation. Args: neighborhood_data: perturbed data, 2d array. first element is assumed to be the original data point. neighborhood_labels: corresponding perturbed labels. should have as ...
Takes perturbed data, labels and distances, returns explanation.
[ "Takes", "perturbed", "data", "labels", "and", "distances", "returns", "explanation", "." ]
def explain_instance_with_data(self, neighborhood_data, neighborhood_labels, distances, label, num_features, f...
[ "def", "explain_instance_with_data", "(", "self", ",", "neighborhood_data", ",", "neighborhood_labels", ",", "distances", ",", "label", ",", "num_features", ",", "feature_selection", "=", "'auto'", ",", "model_regressor", "=", "None", ",", "stability", "=", "False",...
Takes perturbed data, labels and distances, returns explanation.
[ "Takes", "perturbed", "data", "labels", "and", "distances", "returns", "explanation", "." ]
[ "\"\"\"Takes perturbed data, labels and distances, returns explanation.\n\n Args:\n neighborhood_data: perturbed data, 2d array. first element is\n assumed to be the original data point.\n neighborhood_labels: corresponding perturbed labels. should have as\...
[ { "param": "self", "type": null }, { "param": "neighborhood_data", "type": null }, { "param": "neighborhood_labels", "type": null }, { "param": "distances", "type": null }, { "param": "label", "type": null }, { "param": "num_features", "type": null...
{ "returns": [ { "docstring": "(intercept, exp, score):\nintercept is a float.\nexp is a sorted list of tuples, where each tuple (x,y) corresponds\nto the feature id (x) and the local weight (y). The list is sorted\nby decreasing absolute value of y.\nscore is the R^2 value of the returned explanation", ...
9dba10b89113c09c2c302bdbba12c8f4a8b28098
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
ape_tabular_experiments.py
[ "MIT" ]
Python
ape_center
<not_specific>
def ape_center(ape, instance, growing_method='GF', nb_features_employed=None): closest_counterfactual, growing_sphere, training_instances_in_sphere, train_labels_in_sphere, test_instances_in_sphere, \ test_labels_in_sphere, instances_in_sphere_libfolding, farthest_distance, \ ...
Generates or store instances in the area of the hyperfield and their corresponding labels
Generates or store instances in the area of the hyperfield and their corresponding labels
[ "Generates", "or", "store", "instances", "in", "the", "area", "of", "the", "hyperfield", "and", "their", "corresponding", "labels" ]
def ape_center(ape, instance, growing_method='GF', nb_features_employed=None): closest_counterfactual, growing_sphere, training_instances_in_sphere, train_labels_in_sphere, test_instances_in_sphere, \ test_labels_in_sphere, instances_in_sphere_libfolding, farthest_distance, \ ...
[ "def", "ape_center", "(", "ape", ",", "instance", ",", "growing_method", "=", "'GF'", ",", "nb_features_employed", "=", "None", ")", ":", "closest_counterfactual", ",", "growing_sphere", ",", "training_instances_in_sphere", ",", "train_labels_in_sphere", ",", "test_in...
Generates or store instances in the area of the hyperfield and their corresponding labels
[ "Generates", "or", "store", "instances", "in", "the", "area", "of", "the", "hyperfield", "and", "their", "corresponding", "labels" ]
[ "\"\"\" Generates or store instances in the area of the hyperfield and their corresponding labels \"\"\"", "# In case of categorical data, we transform categorical values into probability distribution (continuous values for libfolding)", "#print(\"start of unimodality test\")", "# While the libfolding test is...
[ { "param": "ape", "type": null }, { "param": "instance", "type": null }, { "param": "growing_method", "type": null }, { "param": "nb_features_employed", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ape", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "instance", "type": null, "docstring": null, "docstring_tokens"...
9dba10b89113c09c2c302bdbba12c8f4a8b28098
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
ape_tabular_experiments.py
[ "MIT" ]
Python
ape_illustrative_results
<not_specific>
def ape_illustrative_results(ape_tabular, instance, counterfactual_in_sphere): """ Function that print the explanation of ape depending on the distribution of counterfactual instances located in the hyper field Args: ape_tabular: ape tabular object used to explain the target instance instance: Tar...
Function that print the explanation of ape depending on the distribution of counterfactual instances located in the hyper field Args: ape_tabular: ape tabular object used to explain the target instance instance: Target instance to explain counterfactual_in_sphere: List of counterfactual ins...
Function that print the explanation of ape depending on the distribution of counterfactual instances located in the hyper field Args: ape_tabular: ape tabular object used to explain the target instance instance: Target instance to explain counterfactual_in_sphere: List of counterfactual instances located in the hyper f...
[ "Function", "that", "print", "the", "explanation", "of", "ape", "depending", "on", "the", "distribution", "of", "counterfactual", "instances", "located", "in", "the", "hyper", "field", "Args", ":", "ape_tabular", ":", "ape", "tabular", "object", "used", "to", ...
def ape_illustrative_results(ape_tabular, instance, counterfactual_in_sphere): multimodal = ape_tabular.multimodal_results if multimodal: anchor_exp = ape_tabular.anchor_explainer.explain_instance(instance, ape_tabular.black_box_predict, threshold=ape_tabular.threshold_precision, ...
[ "def", "ape_illustrative_results", "(", "ape_tabular", ",", "instance", ",", "counterfactual_in_sphere", ")", ":", "multimodal", "=", "ape_tabular", ".", "multimodal_results", "if", "multimodal", ":", "anchor_exp", "=", "ape_tabular", ".", "anchor_explainer", ".", "ex...
Function that print the explanation of ape depending on the distribution of counterfactual instances located in the hyper field Args: ape_tabular: ape tabular object used to explain the target instance instance: Target instance to explain counterfactual_in_sphere: List of counterfactual instances located in the hyper f...
[ "Function", "that", "print", "the", "explanation", "of", "ape", "depending", "on", "the", "distribution", "of", "counterfactual", "instances", "located", "in", "the", "hyper", "field", "Args", ":", "ape_tabular", ":", "ape", "tabular", "object", "used", "to", ...
[ "\"\"\"\n Function that print the explanation of ape depending on the distribution of counterfactual instances located in the hyper field\n Args: ape_tabular: ape tabular object used to explain the target instance\n instance: Target instance to explain\n counterfactual_in_sphere: List of cou...
[ { "param": "ape_tabular", "type": null }, { "param": "instance", "type": null }, { "param": "counterfactual_in_sphere", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ape_tabular", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "instance", "type": null, "docstring": null, "docstring...
9dba10b89113c09c2c302bdbba12c8f4a8b28098
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
ape_tabular_experiments.py
[ "MIT" ]
Python
decision_tree_function
<not_specific>
def decision_tree_function(clf, instance): """ Args: clf: Trained decision tree model instance: Target instance to explain Return: the set of features employed by the decision tree model """ feature = clf.tree_.feature node_indicator = clf.decision_path(instance) leaf_id = clf.appl...
Args: clf: Trained decision tree model instance: Target instance to explain Return: the set of features employed by the decision tree model
Trained decision tree model instance: Target instance to explain Return: the set of features employed by the decision tree model
[ "Trained", "decision", "tree", "model", "instance", ":", "Target", "instance", "to", "explain", "Return", ":", "the", "set", "of", "features", "employed", "by", "the", "decision", "tree", "model" ]
def decision_tree_function(clf, instance): feature = clf.tree_.feature node_indicator = clf.decision_path(instance) leaf_id = clf.apply(instance) sample_id = 0 node_index = node_indicator.indices[node_indicator.indptr[sample_id]: node_indicator.indptr[sample_i...
[ "def", "decision_tree_function", "(", "clf", ",", "instance", ")", ":", "feature", "=", "clf", ".", "tree_", ".", "feature", "node_indicator", "=", "clf", ".", "decision_path", "(", "instance", ")", "leaf_id", "=", "clf", ".", "apply", "(", "instance", ")"...
Args: clf: Trained decision tree model instance: Target instance to explain Return: the set of features employed by the decision tree model
[ "Args", ":", "clf", ":", "Trained", "decision", "tree", "model", "instance", ":", "Target", "instance", "to", "explain", "Return", ":", "the", "set", "of", "features", "employed", "by", "the", "decision", "tree", "model" ]
[ "\"\"\"\n Args: clf: Trained decision tree model\n instance: Target instance to explain\n Return: the set of features employed by the decision tree model\n \"\"\"", "#print('Rules used to predict sample {id}:\\n'.format(id=sample_id))", "# continue to the next node if it is a leaf node" ]
[ { "param": "clf", "type": null }, { "param": "instance", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "clf", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "instance", "type": null, "docstring": null, "docstring_tokens"...
1729acf51bd2ba88f52ea80246dbebeed91f945c
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
tabular_user_experiments_lime.py
[ "MIT" ]
Python
compute_score_interpretability_method
<not_specific>
def compute_score_interpretability_method(features_employed_by_explainer, features_employed_black_box): """ Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box """ score = 0 for feature_employe in featur...
Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box
Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box
[ "Compute", "the", "score", "of", "the", "explanation", "method", "based", "on", "the", "features", "employed", "for", "the", "explanation", "compared", "to", "the", "features", "truely", "used", "by", "the", "black", "box" ]
def compute_score_interpretability_method(features_employed_by_explainer, features_employed_black_box): score = 0 for feature_employe in features_employed_by_explainer: if feature_employe in features_employed_black_box: score += 1 return score/len(features_employed_by_explainer)
[ "def", "compute_score_interpretability_method", "(", "features_employed_by_explainer", ",", "features_employed_black_box", ")", ":", "score", "=", "0", "for", "feature_employe", "in", "features_employed_by_explainer", ":", "if", "feature_employe", "in", "features_employed_black...
Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box
[ "Compute", "the", "score", "of", "the", "explanation", "method", "based", "on", "the", "features", "employed", "for", "the", "explanation", "compared", "to", "the", "features", "truely", "used", "by", "the", "black", "box" ]
[ "\"\"\"\n Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box\n \"\"\"" ]
[ { "param": "features_employed_by_explainer", "type": null }, { "param": "features_employed_black_box", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "features_employed_by_explainer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "features_employed_black_box", "type": null, ...
751c53c30f7414b514591ce980c2cd43ce864b06
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
storeExperimentalInformations.py
[ "MIT" ]
Python
store_experiments_information
null
def store_experiments_information(self, nb_instance, nb_model, filename1, filename2=None, filename3=None, filename4=None, filename_multimodal=None, filename_all="", multimodal_filename="multimodal.csv"): """ Compute the mean coverage, precision and f2 per model Args: nb_instance: ...
Compute the mean coverage, precision and f2 per model Args: nb_instance: Number of instance for which we generate explanation for each model nb_model: Numerous of the black box model for which we generate explanation (first model employed = 0 , second model employed = 1, etc...) ...
Compute the mean coverage, precision and f2 per model Args: nb_instance: Number of instance for which we generate explanation for each model nb_model: Numerous of the black box model for which we generate explanation (first model employed = 0 , second model employed = 1, etc...)
[ "Compute", "the", "mean", "coverage", "precision", "and", "f2", "per", "model", "Args", ":", "nb_instance", ":", "Number", "of", "instance", "for", "which", "we", "generate", "explanation", "for", "each", "model", "nb_model", ":", "Numerous", "of", "the", "b...
def store_experiments_information(self, nb_instance, nb_model, filename1, filename2=None, filename3=None, filename4=None, filename_multimodal=None, filename_all="", multimodal_filename="multimodal.csv"): os.makedirs(os.path.dirname(self.filename), exist_ok=True) os.makedirs(os.path.dirname(...
[ "def", "store_experiments_information", "(", "self", ",", "nb_instance", ",", "nb_model", ",", "filename1", ",", "filename2", "=", "None", ",", "filename3", "=", "None", ",", "filename4", "=", "None", ",", "filename_multimodal", "=", "None", ",", "filename_all",...
Compute the mean coverage, precision and f2 per model Args: nb_instance: Number of instance for which we generate explanation for each model nb_model: Numerous of the black box model for which we generate explanation (first model employed = 0 , second model employed = 1, etc...)
[ "Compute", "the", "mean", "coverage", "precision", "and", "f2", "per", "model", "Args", ":", "nb_instance", ":", "Number", "of", "instance", "for", "which", "we", "generate", "explanation", "for", "each", "model", "nb_model", ":", "Numerous", "of", "the", "b...
[ "\"\"\" \n Compute the mean coverage, precision and f2 per model \n Args: nb_instance: Number of instance for which we generate explanation for each model\n nb_model: Numerous of the black box model for which we generate explanation (first model employed = 0 , second model employed = 1, e...
[ { "param": "self", "type": null }, { "param": "nb_instance", "type": null }, { "param": "nb_model", "type": null }, { "param": "filename1", "type": null }, { "param": "filename2", "type": null }, { "param": "filename3", "type": null }, { "p...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nb_instance", "type": null, "docstring": null, "docstring_tok...
d3c3b31f6228cb687dcbd053d0bcebf6d202d2f2
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/counterfactuals.py
[ "MIT" ]
Python
fit
null
def fit(self, caps=None, n_in_layer=2000, first_radius=0.1, dicrease_radius=10, sparse=True, verbose=False, feature_variance=None, farthest_distance_training_dataset=None, probability_categorical_feature=None, min_counterfactual_in_sphere=0): """ find the...
find the counterfactual with the specified method
find the counterfactual with the specified method
[ "find", "the", "counterfactual", "with", "the", "specified", "method" ]
def fit(self, caps=None, n_in_layer=2000, first_radius=0.1, dicrease_radius=10, sparse=True, verbose=False, feature_variance=None, farthest_distance_training_dataset=None, probability_categorical_feature=None, min_counterfactual_in_sphere=0): cf = self.methods_[s...
[ "def", "fit", "(", "self", ",", "caps", "=", "None", ",", "n_in_layer", "=", "2000", ",", "first_radius", "=", "0.1", ",", "dicrease_radius", "=", "10", ",", "sparse", "=", "True", ",", "verbose", "=", "False", ",", "feature_variance", "=", "None", ","...
find the counterfactual with the specified method
[ "find", "the", "counterfactual", "with", "the", "specified", "method" ]
[ "\"\"\"\n find the counterfactual with the specified method\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "caps", "type": null }, { "param": "n_in_layer", "type": null }, { "param": "first_radius", "type": null }, { "param": "dicrease_radius", "type": null }, { "param": "sparse", "type": null }, { "...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "caps", "type": null, "docstring": null, "docstring_tokens": [...
23e563dea3af6e2d80b7a90ece32409963f92743
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/utils/gs_utils.py
[ "MIT" ]
Python
generate_inside_ball
<not_specific>
def generate_inside_ball(center, segment, n): """ Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Array of variance for each continuous feature ...
Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Array of variance for each continuous feature
"center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Array of variance for each continuous feature
[ "\"", "center", "\"", "corresponds", "to", "the", "target", "instance", "to", "explain", "Segment", "corresponds", "to", "the", "size", "of", "the", "hypersphere", "n", "corresponds", "to", "the", "number", "of", "instances", "generated", "feature_variance", ":"...
def generate_inside_ball(center, segment, n): def norm(v): v = np.linalg.norm(v, ord=2, axis=1) return v d = center.shape[0] z = np.random.normal(0, 1, (n, d)) u = np.random.uniform(segment[0]**d, segment[1]**d, n) r = u**(1/float(d)) z = np.array([a * b / c for a, b, c in zip(z,...
[ "def", "generate_inside_ball", "(", "center", ",", "segment", ",", "n", ")", ":", "def", "norm", "(", "v", ")", ":", "v", "=", "np", ".", "linalg", ".", "norm", "(", "v", ",", "ord", "=", "2", ",", "axis", "=", "1", ")", "return", "v", "d", "...
Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Array of variance for each continuous feature
[ "Args", ":", "\"", "center", "\"", "corresponds", "to", "the", "target", "instance", "to", "explain", "Segment", "corresponds", "to", "the", "size", "of", "the", "hypersphere", "n", "corresponds", "to", "the", "number", "of", "instances", "generated", "feature...
[ "\"\"\"\n Args:\n \"center\" corresponds to the target instance to explain\n Segment corresponds to the size of the hypersphere\n n corresponds to the number of instances generated\n feature_variance: Array of variance for each continuous feature\n \"\"\"", "# For Thibault Laugel...
[ { "param": "center", "type": null }, { "param": "segment", "type": null }, { "param": "n", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "center", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "segment", "type": null, "docstring": null, "docstring_token...
23e563dea3af6e2d80b7a90ece32409963f92743
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/utils/gs_utils.py
[ "MIT" ]
Python
generate_inside_field
<not_specific>
def generate_inside_field(center, segment, n, max_features, min_features, feature_variance): """ Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Ar...
Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Array of variance for each continuous feature
"center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Array of variance for each continuous feature
[ "\"", "center", "\"", "corresponds", "to", "the", "target", "instance", "to", "explain", "Segment", "corresponds", "to", "the", "size", "of", "the", "hypersphere", "n", "corresponds", "to", "the", "number", "of", "instances", "generated", "feature_variance", ":"...
def generate_inside_field(center, segment, n, max_features, min_features, feature_variance): if segment[0] == 1 and max_features == []: print("IL Y A UN PROBLEME PUISQUE LE RAYON EST DE 1 et max features n'est pas initialisé", segment, center, feature_variance) generated_instances += 2 d = cente...
[ "def", "generate_inside_field", "(", "center", ",", "segment", ",", "n", ",", "max_features", ",", "min_features", ",", "feature_variance", ")", ":", "if", "segment", "[", "0", "]", "==", "1", "and", "max_features", "==", "[", "]", ":", "print", "(", "\"...
Args: "center" corresponds to the target instance to explain Segment corresponds to the size of the hypersphere n corresponds to the number of instances generated feature_variance: Array of variance for each continuous feature
[ "Args", ":", "\"", "center", "\"", "corresponds", "to", "the", "target", "instance", "to", "explain", "Segment", "corresponds", "to", "the", "size", "of", "the", "hypersphere", "n", "corresponds", "to", "the", "number", "of", "instances", "generated", "feature...
[ "\"\"\"\n Args:\n \"center\" corresponds to the target instance to explain\n Segment corresponds to the size of the hypersphere\n n corresponds to the number of instances generated\n feature_variance: Array of variance for each continuous feature\n \"\"\"", "#print(\"segment\", s...
[ { "param": "center", "type": null }, { "param": "segment", "type": null }, { "param": "n", "type": null }, { "param": "max_features", "type": null }, { "param": "min_features", "type": null }, { "param": "feature_variance", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "center", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "segment", "type": null, "docstring": null, "docstring_token...
23e563dea3af6e2d80b7a90ece32409963f92743
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
growingspheres/utils/gs_utils.py
[ "MIT" ]
Python
perturb_continuous_features
<not_specific>
def perturb_continuous_features(continuous_features, n, feature_variance, segment, center, matrix_perturb_instances): """ Perturb each continuous features of the n instances around center in the area of a sphere of radius equals to segment Return a matrix of n instances of d dimension perturbed ...
Perturb each continuous features of the n instances around center in the area of a sphere of radius equals to segment Return a matrix of n instances of d dimension perturbed based on the distribution of the dataset
Perturb each continuous features of the n instances around center in the area of a sphere of radius equals to segment Return a matrix of n instances of d dimension perturbed based on the distribution of the dataset
[ "Perturb", "each", "continuous", "features", "of", "the", "n", "instances", "around", "center", "in", "the", "area", "of", "a", "sphere", "of", "radius", "equals", "to", "segment", "Return", "a", "matrix", "of", "n", "instances", "of", "d", "dimension", "p...
def perturb_continuous_features(continuous_features, n, feature_variance, segment, center, matrix_perturb_instances): d = len(continuous_features) generated_instances = np.zeros((n,d)) for feature, (min_feature, max_feature) in enumerate(zip(min_features, max_features)): range_featur...
[ "def", "perturb_continuous_features", "(", "continuous_features", ",", "n", ",", "feature_variance", ",", "segment", ",", "center", ",", "matrix_perturb_instances", ")", ":", "d", "=", "len", "(", "continuous_features", ")", "generated_instances", "=", "np", ".", ...
Perturb each continuous features of the n instances around center in the area of a sphere of radius equals to segment Return a matrix of n instances of d dimension perturbed based on the distribution of the dataset
[ "Perturb", "each", "continuous", "features", "of", "the", "n", "instances", "around", "center", "in", "the", "area", "of", "a", "sphere", "of", "radius", "equals", "to", "segment", "Return", "a", "matrix", "of", "n", "instances", "of", "d", "dimension", "p...
[ "\"\"\"\n Perturb each continuous features of the n instances around center in the area of a sphere of radius equals to segment\n Return a matrix of n instances of d dimension perturbed based on the distribution of the dataset\n \"\"\"", "# Modify the generation of artificial instance dependi...
[ { "param": "continuous_features", "type": null }, { "param": "n", "type": null }, { "param": "feature_variance", "type": null }, { "param": "segment", "type": null }, { "param": "center", "type": null }, { "param": "matrix_perturb_instances", "type...
{ "returns": [], "raises": [], "params": [ { "identifier": "continuous_features", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "n", "type": null, "docstring": null, "docstrin...
abb4ee43412745b7f324968f67893f88cbab27e5
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
anchors/limes/lime_tabular.py
[ "MIT" ]
Python
explain_instance
<not_specific>
def explain_instance(self, data_row, predict_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='euclidean', ...
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_b...
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance . We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way .
[ "Generates", "explanations", "for", "a", "prediction", ".", "First", "we", "generate", "neighborhood", "data", "by", "randomly", "perturbing", "features", "from", "the", "instance", ".", "We", "then", "learn", "locally", "weighted", "linear", "models", "on", "th...
def explain_instance(self, data_row, predict_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='euclidean', ...
[ "def", "explain_instance", "(", "self", ",", "data_row", ",", "predict_fn", ",", "labels", "=", "(", "1", ",", ")", ",", "top_labels", "=", "None", ",", "num_features", "=", "10", ",", "num_samples", "=", "5000", ",", "distance_metric", "=", "'euclidean'",...
Generates explanations for a prediction.
[ "Generates", "explanations", "for", "a", "prediction", "." ]
[ "\"\"\"Generates explanations for a prediction.\n\n First, we generate neighborhood data by randomly perturbing features\n from the instance (see __data_inverse). We then learn locally weighted\n linear models on this neighborhood data to explain each of the classes\n in an interpretable...
[ { "param": "self", "type": null }, { "param": "data_row", "type": null }, { "param": "predict_fn", "type": null }, { "param": "labels", "type": null }, { "param": "top_labels", "type": null }, { "param": "num_features", "type": null }, { "p...
{ "returns": [ { "docstring": "An Explanation object with the corresponding\nexplanations.", "docstring_tokens": [ "An", "Explanation", "object", "with", "the", "corresponding", "explanations", "." ], "type": null } ], ...
abb4ee43412745b7f324968f67893f88cbab27e5
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
anchors/limes/lime_tabular.py
[ "MIT" ]
Python
explain_instance_training_dataset
<not_specific>
def explain_instance_training_dataset(self, data_row, predict_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metri...
Generates explanations for a prediction. First, we learn locally weighted linear models on the instances from "instances_in_sphere" to explain each of the classes in an interpretable way (see lime_base.py). Args: data_row: 1d numpy array, corresponding to a row ...
Generates explanations for a prediction. First, we learn locally weighted linear models on the instances from "instances_in_sphere" to explain each of the classes in an interpretable way .
[ "Generates", "explanations", "for", "a", "prediction", ".", "First", "we", "learn", "locally", "weighted", "linear", "models", "on", "the", "instances", "from", "\"", "instances_in_sphere", "\"", "to", "explain", "each", "of", "the", "classes", "in", "an", "in...
def explain_instance_training_dataset(self, data_row, predict_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metri...
[ "def", "explain_instance_training_dataset", "(", "self", ",", "data_row", ",", "predict_fn", ",", "labels", "=", "(", "1", ",", ")", ",", "top_labels", "=", "None", ",", "num_features", "=", "10", ",", "num_samples", "=", "5000", ",", "distance_metric", "=",...
Generates explanations for a prediction.
[ "Generates", "explanations", "for", "a", "prediction", "." ]
[ "\"\"\"Generates explanations for a prediction.\n\n First, we learn locally weighted linear models on \n the instances from \"instances_in_sphere\" to explain each of the classes\n in an interpretable way (see lime_base.py).\n\n Args:\n data_row: 1d numpy array, corresponding ...
[ { "param": "self", "type": null }, { "param": "data_row", "type": null }, { "param": "predict_fn", "type": null }, { "param": "labels", "type": null }, { "param": "top_labels", "type": null }, { "param": "num_features", "type": null }, { "p...
{ "returns": [ { "docstring": "An Explanation object with the corresponding\nexplanations.", "docstring_tokens": [ "An", "Explanation", "object", "with", "the", "corresponding", "explanations", "." ], "type": null } ], ...
abb4ee43412745b7f324968f67893f88cbab27e5
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
anchors/limes/lime_tabular.py
[ "MIT" ]
Python
__data_inverse
<not_specific>
def __data_inverse(self, data_row, num_samples): """Generates a neighborhood around a prediction. For numerical features, perturb them by sampling from a Normal(0,1) and doing the inverse operation of mean-centering and scaling, according to ...
Generates a neighborhood around a prediction. For numerical features, perturb them by sampling from a Normal(0,1) and doing the inverse operation of mean-centering and scaling, according to the means and stds in the training data. For categorical features, perturb by sampling according ...
Generates a neighborhood around a prediction. For numerical features, perturb them by sampling from a Normal(0,1) and doing the inverse operation of mean-centering and scaling, according to the means and stds in the training data. For categorical features, perturb by sampling according to the training distribution, and...
[ "Generates", "a", "neighborhood", "around", "a", "prediction", ".", "For", "numerical", "features", "perturb", "them", "by", "sampling", "from", "a", "Normal", "(", "0", "1", ")", "and", "doing", "the", "inverse", "operation", "of", "mean", "-", "centering",...
def __data_inverse(self, data_row, num_samples): data = np.zeros((num_samples, data_row.shape[0])) categorical_features = range(data_row.shape[0]) if self.discretizer is None: data = self.random_state.normal( 0, 1, num...
[ "def", "__data_inverse", "(", "self", ",", "data_row", ",", "num_samples", ")", ":", "data", "=", "np", ".", "zeros", "(", "(", "num_samples", ",", "data_row", ".", "shape", "[", "0", "]", ")", ")", "categorical_features", "=", "range", "(", "data_row", ...
Generates a neighborhood around a prediction.
[ "Generates", "a", "neighborhood", "around", "a", "prediction", "." ]
[ "\"\"\"Generates a neighborhood around a prediction.\n\n For numerical features, perturb them by sampling from a Normal(0,1) and\n doing the inverse operation of mean-centering and scaling, according to\n the means and stds in the training data. For categorical features,\n perturb by sam...
[ { "param": "self", "type": null }, { "param": "data_row", "type": null }, { "param": "num_samples", "type": null } ]
{ "returns": [ { "docstring": "A tuple (data, inverse), where:\ndata: dense num_samples * K matrix, where categorical features\nare encoded with either 0 (not equal to the corresponding value\nin data_row) or 1. The first row is the original instance.\ninverse: same as data, except the categorical features ...
abb4ee43412745b7f324968f67893f88cbab27e5
juliendelaunay35000/APE-Adapted_Post-Hoc_Explanations
anchors/limes/lime_tabular.py
[ "MIT" ]
Python
check_stability
<not_specific>
def check_stability(self, data_row, predict_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='euclidean', ...
Method to calculate stability indices for a trained LIME instance. The stability indices are relative to the particular data point we are explaining. The stability indices are described in the paper: "Statistical stability indices for LIME: obtaining reliable explanations for Machine Le...
Method to calculate stability indices for a trained LIME instance. The stability indices are relative to the particular data point we are explaining. The stability indices are described in the paper: "Statistical stability indices for LIME: obtaining reliable explanations for Machine Learning models".
[ "Method", "to", "calculate", "stability", "indices", "for", "a", "trained", "LIME", "instance", ".", "The", "stability", "indices", "are", "relative", "to", "the", "particular", "data", "point", "we", "are", "explaining", ".", "The", "stability", "indices", "a...
def check_stability(self, data_row, predict_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='euclidean', ...
[ "def", "check_stability", "(", "self", ",", "data_row", ",", "predict_fn", ",", "labels", "=", "(", "1", ",", ")", ",", "top_labels", "=", "None", ",", "num_features", "=", "10", ",", "num_samples", "=", "5000", ",", "distance_metric", "=", "'euclidean'", ...
Method to calculate stability indices for a trained LIME instance.
[ "Method", "to", "calculate", "stability", "indices", "for", "a", "trained", "LIME", "instance", "." ]
[ "\"\"\"\n Method to calculate stability indices for a trained LIME instance.\n The stability indices are relative to the particular data point we are explaining.\n The stability indices are described in the paper:\n \"Statistical stability indices for LIME: obtaining reliable explanation...
[ { "param": "self", "type": null }, { "param": "data_row", "type": null }, { "param": "predict_fn", "type": null }, { "param": "labels", "type": null }, { "param": "top_labels", "type": null }, { "param": "num_features", "type": null }, { "p...
{ "returns": [ { "docstring": "index to evaluate the stability of the coefficients of each variable across\ndifferent Lime explanations obtained from the repeated n_calls.\nRanges from 0 to 100.\nvsi: index to evaluate whether the variables retrieved in different Lime explanations\nare the same. Ranges from...
b6b19836b775fa4c679890e50e6f9af7146e715d
samuelbaruffi/aws-serverless-shopping-cart
backend/shopping-cart-service/checkout_cart.py
[ "MIT-0" ]
Python
lambda_handler
<not_specific>
def lambda_handler(event, context): """ Update cart table to use user identifier instead of anonymous cookie value as a key. This will be called when a user is logged in. """ cart_id, _ = get_cart_id(event["headers"]) try: # Because this method is authorized at API gateway layer, we don...
Update cart table to use user identifier instead of anonymous cookie value as a key. This will be called when a user is logged in.
Update cart table to use user identifier instead of anonymous cookie value as a key. This will be called when a user is logged in.
[ "Update", "cart", "table", "to", "use", "user", "identifier", "instead", "of", "anonymous", "cookie", "value", "as", "a", "key", ".", "This", "will", "be", "called", "when", "a", "user", "is", "logged", "in", "." ]
def lambda_handler(event, context): cart_id, _ = get_cart_id(event["headers"]) try: user_id = event["requestContext"]["authorizer"]["claims"]["sub"] except KeyError: return { "statusCode": 400, "headers": get_headers(cart_id), "body": json.dumps({"message"...
[ "def", "lambda_handler", "(", "event", ",", "context", ")", ":", "cart_id", ",", "_", "=", "get_cart_id", "(", "event", "[", "\"headers\"", "]", ")", "try", ":", "user_id", "=", "event", "[", "\"requestContext\"", "]", "[", "\"authorizer\"", "]", "[", "\...
Update cart table to use user identifier instead of anonymous cookie value as a key.
[ "Update", "cart", "table", "to", "use", "user", "identifier", "instead", "of", "anonymous", "cookie", "value", "as", "a", "key", "." ]
[ "\"\"\"\n Update cart table to use user identifier instead of anonymous cookie value as a key. This will be called when a user\n is logged in.\n \"\"\"", "# Because this method is authorized at API gateway layer, we don't need to validate the JWT claims here", "# Get all cart items belonging to the use...
[ { "param": "event", "type": null }, { "param": "context", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "event", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "context", "type": null, "docstring": null, "docstring_tokens...
298b1571d77ea453bd23c8994ce5583ded208088
takanotume24/flask_cognito
flask_cognito.py
[ "MIT" ]
Python
cognito_auth_required
<not_specific>
def cognito_auth_required(fn): """View decorator that requires a valid Cognito JWT token to be present in the request.""" @wraps(fn) def decorator(*args, **kwargs): _cognito_auth_required() return fn(*args, **kwargs) return decorator
View decorator that requires a valid Cognito JWT token to be present in the request.
View decorator that requires a valid Cognito JWT token to be present in the request.
[ "View", "decorator", "that", "requires", "a", "valid", "Cognito", "JWT", "token", "to", "be", "present", "in", "the", "request", "." ]
def cognito_auth_required(fn): @wraps(fn) def decorator(*args, **kwargs): _cognito_auth_required() return fn(*args, **kwargs) return decorator
[ "def", "cognito_auth_required", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "decorator", "(", "*", "args", ",", "**", "kwargs", ")", ":", "_cognito_auth_required", "(", ")", "return", "fn", "(", "*", "args", ",", "**", "kwargs", ")", "r...
View decorator that requires a valid Cognito JWT token to be present in the request.
[ "View", "decorator", "that", "requires", "a", "valid", "Cognito", "JWT", "token", "to", "be", "present", "in", "the", "request", "." ]
[ "\"\"\"View decorator that requires a valid Cognito JWT token to be present in the request.\"\"\"" ]
[ { "param": "fn", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "fn", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
298b1571d77ea453bd23c8994ce5583ded208088
takanotume24/flask_cognito
flask_cognito.py
[ "MIT" ]
Python
_cognito_check_groups
null
def _cognito_check_groups(groups: list): """ Does the actual work of verifying the user group to restrict access to some resources. :param groups a list with the name of the groups of Cognito Identity Pool :raise an exception if there is no group """ if 'cognito:groups' not in curre...
Does the actual work of verifying the user group to restrict access to some resources. :param groups a list with the name of the groups of Cognito Identity Pool :raise an exception if there is no group
Does the actual work of verifying the user group to restrict access to some resources. :param groups a list with the name of the groups of Cognito Identity Pool :raise an exception if there is no group
[ "Does", "the", "actual", "work", "of", "verifying", "the", "user", "group", "to", "restrict", "access", "to", "some", "resources", ".", ":", "param", "groups", "a", "list", "with", "the", "name", "of", "the", "groups", "of", "Cognito", "Identity", "Pool", ...
def _cognito_check_groups(groups: list): if 'cognito:groups' not in current_cognito_jwt or current_cognito_jwt['cognito:groups'] is None: raise CognitoAuthError('Not Authorized', 'User doesn\'t have access to this resource', status_code=403) if all...
[ "def", "_cognito_check_groups", "(", "groups", ":", "list", ")", ":", "if", "'cognito:groups'", "not", "in", "current_cognito_jwt", "or", "current_cognito_jwt", "[", "'cognito:groups'", "]", "is", "None", ":", "raise", "CognitoAuthError", "(", "'Not Authorized'", ",...
Does the actual work of verifying the user group to restrict access to some resources.
[ "Does", "the", "actual", "work", "of", "verifying", "the", "user", "group", "to", "restrict", "access", "to", "some", "resources", "." ]
[ "\"\"\"\n Does the actual work of verifying the user group to restrict access to some resources.\n :param groups a list with the name of the groups of Cognito Identity Pool\n :raise an exception if there is no group\n \"\"\"" ]
[ { "param": "groups", "type": "list" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "groups", "type": "list", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
298b1571d77ea453bd23c8994ce5583ded208088
takanotume24/flask_cognito
flask_cognito.py
[ "MIT" ]
Python
_cognito_auth_required
null
def _cognito_auth_required(): """Does the actual work of verifying the Cognito JWT data in the current request. This is done automatically for you by `cognito_jwt_required()` but you could call it manually. Doing so would be useful in the context of optional JWT access in your APIs. """ token = _cog...
Does the actual work of verifying the Cognito JWT data in the current request. This is done automatically for you by `cognito_jwt_required()` but you could call it manually. Doing so would be useful in the context of optional JWT access in your APIs.
Does the actual work of verifying the Cognito JWT data in the current request. This is done automatically for you by `cognito_jwt_required()` but you could call it manually. Doing so would be useful in the context of optional JWT access in your APIs.
[ "Does", "the", "actual", "work", "of", "verifying", "the", "Cognito", "JWT", "data", "in", "the", "current", "request", ".", "This", "is", "done", "automatically", "for", "you", "by", "`", "cognito_jwt_required", "()", "`", "but", "you", "could", "call", "...
def _cognito_auth_required(): token = _cog.get_token() if token is None: auth_header_name = _cog.jwt_header_name auth_header_prefix = _cog.jwt_header_prefix raise CognitoAuthError('Authorization Required', f'Request does not contain a well-formed access tok...
[ "def", "_cognito_auth_required", "(", ")", ":", "token", "=", "_cog", ".", "get_token", "(", ")", "if", "token", "is", "None", ":", "auth_header_name", "=", "_cog", ".", "jwt_header_name", "auth_header_prefix", "=", "_cog", ".", "jwt_header_prefix", "raise", "...
Does the actual work of verifying the Cognito JWT data in the current request.
[ "Does", "the", "actual", "work", "of", "verifying", "the", "Cognito", "JWT", "data", "in", "the", "current", "request", "." ]
[ "\"\"\"Does the actual work of verifying the Cognito JWT data in the current request.\n This is done automatically for you by `cognito_jwt_required()` but you could call it manually.\n Doing so would be useful in the context of optional JWT access in your APIs.\n \"\"\"", "# check if token is signed by u...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
f13d4772954fae5fa3f8f62daef738970d38f515
johnbenjaminlewis/me
me/app.py
[ "MIT" ]
Python
register_assets
null
def register_assets(app, debug=False): """We add the app's root path to assets search path. However, the output directory is relative to `app.static_folder`. """ assets = Environment(app) assets.debug = debug assets.auto_build = True assets.manifest = 'file' assets.append_path(app.root_p...
We add the app's root path to assets search path. However, the output directory is relative to `app.static_folder`.
We add the app's root path to assets search path. However, the output directory is relative to `app.static_folder`.
[ "We", "add", "the", "app", "'", "s", "root", "path", "to", "assets", "search", "path", ".", "However", "the", "output", "directory", "is", "relative", "to", "`", "app", ".", "static_folder", "`", "." ]
def register_assets(app, debug=False): assets = Environment(app) assets.debug = debug assets.auto_build = True assets.manifest = 'file' assets.append_path(app.root_path) site_js = Bundle( 'static/app.js', filters=('uglifyjs',), output='js/bundle.js' ) assets.regis...
[ "def", "register_assets", "(", "app", ",", "debug", "=", "False", ")", ":", "assets", "=", "Environment", "(", "app", ")", "assets", ".", "debug", "=", "debug", "assets", ".", "auto_build", "=", "True", "assets", ".", "manifest", "=", "'file'", "assets",...
We add the app's root path to assets search path.
[ "We", "add", "the", "app", "'", "s", "root", "path", "to", "assets", "search", "path", "." ]
[ "\"\"\"We add the app's root path to assets search path. However, the\n output directory is relative to `app.static_folder`.\n \"\"\"" ]
[ { "param": "app", "type": null }, { "param": "debug", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "app", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "debug", "type": null, "docstring": null, "docstring_tokens": [...
12f781d8f353ec05b8ef506fce514c0bf39f0944
johnbenjaminlewis/me
me/commands/__init__.py
[ "MIT" ]
Python
create_cli
<not_specific>
def create_cli(menu_groups): """Similar to create_app, creates a click instance and returns it. :param menu_groups: a list of package names to import """ @click.group(help=__doc__.format(this_file=__file__)) @click.option('--test-mode', default=False, is_flag=True, help='Use test ...
Similar to create_app, creates a click instance and returns it. :param menu_groups: a list of package names to import
Similar to create_app, creates a click instance and returns it.
[ "Similar", "to", "create_app", "creates", "a", "click", "instance", "and", "returns", "it", "." ]
def create_cli(menu_groups): @click.group(help=__doc__.format(this_file=__file__)) @click.option('--test-mode', default=False, is_flag=True, help='Use test config') @click.pass_context def cli_app(ctx, test_mode): if test_mode: click.secho('Using test mode', fg='gre...
[ "def", "create_cli", "(", "menu_groups", ")", ":", "@", "click", ".", "group", "(", "help", "=", "__doc__", ".", "format", "(", "this_file", "=", "__file__", ")", ")", "@", "click", ".", "option", "(", "'--test-mode'", ",", "default", "=", "False", ","...
Similar to create_app, creates a click instance and returns it.
[ "Similar", "to", "create_app", "creates", "a", "click", "instance", "and", "returns", "it", "." ]
[ "\"\"\"Similar to create_app, creates a click instance and returns it.\n\n :param menu_groups: a list of package names to import\n \"\"\"", "# Import menu groups", "# Register menu groups", "# Grab iterable of all objects defined in the module" ]
[ { "param": "menu_groups", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "menu_groups", "type": null, "docstring": "a list of package names to import", "docstring_tokens": [ "a", "list", "of", "package", "names", "to", "import" ], "...
5e1126d1cd4371d72190c29d80a2a37dc6cdff4c
johnbenjaminlewis/me
me/lib.py
[ "MIT" ]
Python
sorted_return
<not_specific>
def sorted_return(*a, **sorted_kwargs): """ Decorator with optional arguments that sorts output of decorated function. """ def _sorted_return(fn): @wraps(fn) def decorated(*args, **kwargs): res = fn(*args, **kwargs) return sorted(res, **sorted_kwargs) retu...
Decorator with optional arguments that sorts output of decorated function.
Decorator with optional arguments that sorts output of decorated function.
[ "Decorator", "with", "optional", "arguments", "that", "sorts", "output", "of", "decorated", "function", "." ]
def sorted_return(*a, **sorted_kwargs): def _sorted_return(fn): @wraps(fn) def decorated(*args, **kwargs): res = fn(*args, **kwargs) return sorted(res, **sorted_kwargs) return decorated if len(a) == 1 and callable(a[0]): return _sorted_return(a[0]) ret...
[ "def", "sorted_return", "(", "*", "a", ",", "**", "sorted_kwargs", ")", ":", "def", "_sorted_return", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "decorated", "(", "*", "args", ",", "**", "kwargs", ")", ":", "res", "=", "fn", "(", "...
Decorator with optional arguments that sorts output of decorated function.
[ "Decorator", "with", "optional", "arguments", "that", "sorts", "output", "of", "decorated", "function", "." ]
[ "\"\"\" Decorator with optional arguments that sorts output of\n decorated function.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
59045d237867e4046a798fa2c0b64634b3ff3afc
johnbenjaminlewis/me
fabfile.py
[ "MIT" ]
Python
virtualenv
null
def virtualenv(name): """Handy context manager to activate a virtualenv. """ with prefix('WORKON_HOME=$HOME/.virtualenvs'), \ prefix('source /usr/local/bin/virtualenvwrapper.sh'), \ prefix('workon {}'.format(name)): yield
Handy context manager to activate a virtualenv.
Handy context manager to activate a virtualenv.
[ "Handy", "context", "manager", "to", "activate", "a", "virtualenv", "." ]
def virtualenv(name): with prefix('WORKON_HOME=$HOME/.virtualenvs'), \ prefix('source /usr/local/bin/virtualenvwrapper.sh'), \ prefix('workon {}'.format(name)): yield
[ "def", "virtualenv", "(", "name", ")", ":", "with", "prefix", "(", "'WORKON_HOME=$HOME/.virtualenvs'", ")", ",", "prefix", "(", "'source /usr/local/bin/virtualenvwrapper.sh'", ")", ",", "prefix", "(", "'workon {}'", ".", "format", "(", "name", ")", ")", ":", "yi...
Handy context manager to activate a virtualenv.
[ "Handy", "context", "manager", "to", "activate", "a", "virtualenv", "." ]
[ "\"\"\"Handy context manager to activate a virtualenv.\n \"\"\"" ]
[ { "param": "name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "name", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
59045d237867e4046a798fa2c0b64634b3ff3afc
johnbenjaminlewis/me
fabfile.py
[ "MIT" ]
Python
git_pull
<not_specific>
def git_pull(): """Pull the latest version of the codebase. """ with cd('~/repos/me'): return run('git fetch origin && git reset --hard origin/master')
Pull the latest version of the codebase.
Pull the latest version of the codebase.
[ "Pull", "the", "latest", "version", "of", "the", "codebase", "." ]
def git_pull(): with cd('~/repos/me'): return run('git fetch origin && git reset --hard origin/master')
[ "def", "git_pull", "(", ")", ":", "with", "cd", "(", "'~/repos/me'", ")", ":", "return", "run", "(", "'git fetch origin && git reset --hard origin/master'", ")" ]
Pull the latest version of the codebase.
[ "Pull", "the", "latest", "version", "of", "the", "codebase", "." ]
[ "\"\"\"Pull the latest version of the codebase.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
f02bfa1800663ce1d8c3d202836c2c2a174e7f3b
johnbenjaminlewis/me
me/commands/shell.py
[ "MIT" ]
Python
_create_context
<not_specific>
def _create_context(): """Returns a dictionary with application objects defined and configured """ return { 'app': create_app() }
Returns a dictionary with application objects defined and configured
Returns a dictionary with application objects defined and configured
[ "Returns", "a", "dictionary", "with", "application", "objects", "defined", "and", "configured" ]
def _create_context(): return { 'app': create_app() }
[ "def", "_create_context", "(", ")", ":", "return", "{", "'app'", ":", "create_app", "(", ")", "}" ]
Returns a dictionary with application objects defined and configured
[ "Returns", "a", "dictionary", "with", "application", "objects", "defined", "and", "configured" ]
[ "\"\"\"Returns a dictionary with application objects defined and\n configured\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
5fae03eadd775733b0290f7e23769d115fda7ded
johnbenjaminlewis/me
me/commands/db.py
[ "MIT" ]
Python
grant
null
def grant(ctx): """ Grants permissions to read and write database users """ write('Granting permissions to database engines') updater = sql.DbUpdater(config.main_db, config.migrations_dir) updater.grant_all_users()
Grants permissions to read and write database users
Grants permissions to read and write database users
[ "Grants", "permissions", "to", "read", "and", "write", "database", "users" ]
def grant(ctx): write('Granting permissions to database engines') updater = sql.DbUpdater(config.main_db, config.migrations_dir) updater.grant_all_users()
[ "def", "grant", "(", "ctx", ")", ":", "write", "(", "'Granting permissions to database engines'", ")", "updater", "=", "sql", ".", "DbUpdater", "(", "config", ".", "main_db", ",", "config", ".", "migrations_dir", ")", "updater", ".", "grant_all_users", "(", ")...
Grants permissions to read and write database users
[ "Grants", "permissions", "to", "read", "and", "write", "database", "users" ]
[ "\"\"\" Grants permissions to read and write database users\n \"\"\"" ]
[ { "param": "ctx", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ctx", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
5fae03eadd775733b0290f7e23769d115fda7ded
johnbenjaminlewis/me
me/commands/db.py
[ "MIT" ]
Python
rebuild
<not_specific>
def rebuild(ctx): """ Completely rebuilds test db. Can only be used with --test-mode flag """ if not config.test_mode: return fail('rebuild may only be used in test mode! Aborting.') write('Rebuilding test database') updater = sql.DbUpdater(config.main_db, config.migrations_dir) engine =...
Completely rebuilds test db. Can only be used with --test-mode flag
Completely rebuilds test db. Can only be used with --test-mode flag
[ "Completely", "rebuilds", "test", "db", ".", "Can", "only", "be", "used", "with", "--", "test", "-", "mode", "flag" ]
def rebuild(ctx): if not config.test_mode: return fail('rebuild may only be used in test mode! Aborting.') write('Rebuilding test database') updater = sql.DbUpdater(config.main_db, config.migrations_dir) engine = updater.db.engines['migration'] user = engine.url.username database = engin...
[ "def", "rebuild", "(", "ctx", ")", ":", "if", "not", "config", ".", "test_mode", ":", "return", "fail", "(", "'rebuild may only be used in test mode! Aborting.'", ")", "write", "(", "'Rebuilding test database'", ")", "updater", "=", "sql", ".", "DbUpdater", "(", ...
Completely rebuilds test db.
[ "Completely", "rebuilds", "test", "db", "." ]
[ "\"\"\" Completely rebuilds test db. Can only be used with --test-mode flag\n \"\"\"", "# Begin calls" ]
[ { "param": "ctx", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ctx", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4b2eb7c159981e7076e1c3f26a8dfd2e82060050
johnbenjaminlewis/me
me/sql.py
[ "MIT" ]
Python
migrations
<not_specific>
def migrations(self): """Grab all versioned migrations from the migration directory, verify no duplicates and return list. """ files = os.listdir(self.migrations_dir) migrations = [] for _file in files: try: version = get_sql_version(_file) ...
Grab all versioned migrations from the migration directory, verify no duplicates and return list.
Grab all versioned migrations from the migration directory, verify no duplicates and return list.
[ "Grab", "all", "versioned", "migrations", "from", "the", "migration", "directory", "verify", "no", "duplicates", "and", "return", "list", "." ]
def migrations(self): files = os.listdir(self.migrations_dir) migrations = [] for _file in files: try: version = get_sql_version(_file) except ValueError: continue migrations.append(Migration(_file, version)) counts = co...
[ "def", "migrations", "(", "self", ")", ":", "files", "=", "os", ".", "listdir", "(", "self", ".", "migrations_dir", ")", "migrations", "=", "[", "]", "for", "_file", "in", "files", ":", "try", ":", "version", "=", "get_sql_version", "(", "_file", ")", ...
Grab all versioned migrations from the migration directory, verify no duplicates and return list.
[ "Grab", "all", "versioned", "migrations", "from", "the", "migration", "directory", "verify", "no", "duplicates", "and", "return", "list", "." ]
[ "\"\"\"Grab all versioned migrations from the migration directory, verify\n no duplicates and return list.\n \"\"\"", "# Skip invlaid sql migration version" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4b2eb7c159981e7076e1c3f26a8dfd2e82060050
johnbenjaminlewis/me
me/sql.py
[ "MIT" ]
Python
sequences
<not_specific>
def sequences(self): """ Returns list of postgres sequences. """ pg_table = sa.Table('sequences', self.meta, autoload=True, schema='information_schema') with self.db.session_manager() as s: return s.query(pg_table).all()
Returns list of postgres sequences.
Returns list of postgres sequences.
[ "Returns", "list", "of", "postgres", "sequences", "." ]
def sequences(self): pg_table = sa.Table('sequences', self.meta, autoload=True, schema='information_schema') with self.db.session_manager() as s: return s.query(pg_table).all()
[ "def", "sequences", "(", "self", ")", ":", "pg_table", "=", "sa", ".", "Table", "(", "'sequences'", ",", "self", ".", "meta", ",", "autoload", "=", "True", ",", "schema", "=", "'information_schema'", ")", "with", "self", ".", "db", ".", "session_manager"...
Returns list of postgres sequences.
[ "Returns", "list", "of", "postgres", "sequences", "." ]
[ "\"\"\" Returns list of postgres sequences.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4b2eb7c159981e7076e1c3f26a8dfd2e82060050
johnbenjaminlewis/me
me/sql.py
[ "MIT" ]
Python
schemata
<not_specific>
def schemata(self): """ Returns list of postgres schemata. """ pg_table = sa.Table('schemata', self.meta, autoload=True, schema='information_schema') with self.db.session_manager() as s: return s.query(pg_table)\ .filter(~pg_tab...
Returns list of postgres schemata.
Returns list of postgres schemata.
[ "Returns", "list", "of", "postgres", "schemata", "." ]
def schemata(self): pg_table = sa.Table('schemata', self.meta, autoload=True, schema='information_schema') with self.db.session_manager() as s: return s.query(pg_table)\ .filter(~pg_table.c.schema_name.match('pg_%'))\ .filte...
[ "def", "schemata", "(", "self", ")", ":", "pg_table", "=", "sa", ".", "Table", "(", "'schemata'", ",", "self", ".", "meta", ",", "autoload", "=", "True", ",", "schema", "=", "'information_schema'", ")", "with", "self", ".", "db", ".", "session_manager", ...
Returns list of postgres schemata.
[ "Returns", "list", "of", "postgres", "schemata", "." ]
[ "\"\"\" Returns list of postgres schemata.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4b2eb7c159981e7076e1c3f26a8dfd2e82060050
johnbenjaminlewis/me
me/sql.py
[ "MIT" ]
Python
users
<not_specific>
def users(self): """ Returns list of postgres users. """ pg_table = sa.Table('pg_user', self.meta, autoload=True, schema='pg_catalog') with self.db.session_manager() as s: return s.query(pg_table).all()
Returns list of postgres users.
Returns list of postgres users.
[ "Returns", "list", "of", "postgres", "users", "." ]
def users(self): pg_table = sa.Table('pg_user', self.meta, autoload=True, schema='pg_catalog') with self.db.session_manager() as s: return s.query(pg_table).all()
[ "def", "users", "(", "self", ")", ":", "pg_table", "=", "sa", ".", "Table", "(", "'pg_user'", ",", "self", ".", "meta", ",", "autoload", "=", "True", ",", "schema", "=", "'pg_catalog'", ")", "with", "self", ".", "db", ".", "session_manager", "(", ")"...
Returns list of postgres users.
[ "Returns", "list", "of", "postgres", "users", "." ]
[ "\"\"\" Returns list of postgres users.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3b72917d02502ac836cde91d77ff4183b97d90bd
robert-mcdermott/ec2reporter
ec2reporter.py
[ "Apache-2.0" ]
Python
removebadchars
<not_specific>
def removebadchars(token): """ Remove any undesirable characters that might gum up the works """ translate = {'$': '', '&': '', '#': '', '*': '', '(': '', ')': '', '[': '', ']': '', ' ': '', '?': '','^': '', '`': '', '~': '', '{': '', '}': '', ',': '', '|': '', ':': '', ';': '', "'": '',...
Remove any undesirable characters that might gum up the works
Remove any undesirable characters that might gum up the works
[ "Remove", "any", "undesirable", "characters", "that", "might", "gum", "up", "the", "works" ]
def removebadchars(token): translate = {'$': '', '&': '', '#': '', '*': '', '(': '', ')': '', '[': '', ']': '', ' ': '', '?': '','^': '', '`': '', '~': '', '{': '', '}': '', ',': '', '|': '', ':': '', ';': '', "'": '', '"': ''} for char in translate: token = token.replace(char, translate...
[ "def", "removebadchars", "(", "token", ")", ":", "translate", "=", "{", "'$'", ":", "''", ",", "'&'", ":", "''", ",", "'#'", ":", "''", ",", "'*'", ":", "''", ",", "'('", ":", "''", ",", "')'", ":", "''", ",", "'['", ":", "''", ",", "']'", ...
Remove any undesirable characters that might gum up the works
[ "Remove", "any", "undesirable", "characters", "that", "might", "gum", "up", "the", "works" ]
[ "\"\"\"\n Remove any undesirable characters that might gum up the works\n \"\"\"" ]
[ { "param": "token", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "token", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3b72917d02502ac836cde91d77ff4183b97d90bd
robert-mcdermott/ec2reporter
ec2reporter.py
[ "Apache-2.0" ]
Python
create_objects
<not_specific>
def create_objects(instances): """ Create and object for each of the instances in the provided list and return a list of instance objects populated with the corresponding AWS and custom tag metadata. """ objects = [] for instance in instances: i = Instance() i.AvailabilityZone =...
Create and object for each of the instances in the provided list and return a list of instance objects populated with the corresponding AWS and custom tag metadata.
Create and object for each of the instances in the provided list and return a list of instance objects populated with the corresponding AWS and custom tag metadata.
[ "Create", "and", "object", "for", "each", "of", "the", "instances", "in", "the", "provided", "list", "and", "return", "a", "list", "of", "instance", "objects", "populated", "with", "the", "corresponding", "AWS", "and", "custom", "tag", "metadata", "." ]
def create_objects(instances): objects = [] for instance in instances: i = Instance() i.AvailabilityZone = instance["Placement"]["AvailabilityZone"] i.InstanceId = instance["InstanceId"] i.InstanceType = instance["InstanceType"] i.State = instance["State"]["Name"] ...
[ "def", "create_objects", "(", "instances", ")", ":", "objects", "=", "[", "]", "for", "instance", "in", "instances", ":", "i", "=", "Instance", "(", ")", "i", ".", "AvailabilityZone", "=", "instance", "[", "\"Placement\"", "]", "[", "\"AvailabilityZone\"", ...
Create and object for each of the instances in the provided list and return a list of instance objects populated with the corresponding AWS and custom tag metadata.
[ "Create", "and", "object", "for", "each", "of", "the", "instances", "in", "the", "provided", "list", "and", "return", "a", "list", "of", "instance", "objects", "populated", "with", "the", "corresponding", "AWS", "and", "custom", "tag", "metadata", "." ]
[ "\"\"\"\n Create and object for each of the instances in the provided list and return a list of instance objects\n populated with the corresponding AWS and custom tag metadata.\n \"\"\"" ]
[ { "param": "instances", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "instances", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
1b57bc1b820270221f50b076c8f62002320be079
deepkashiwa20/CapitalTraffic
baseline/DCRNN.py
[ "MIT" ]
Python
forward
<not_specific>
def forward(self, G: torch.Tensor, x: torch.Tensor): ''' Batch-wise graph convolution operation on given n support adj matrices :param G: support adj matrices - torch.Tensor (K, n_nodes, n_nodes) :param x: graph feature/signal - torch.Tensor (batch_size, n_nodes, input_dim) :retu...
Batch-wise graph convolution operation on given n support adj matrices :param G: support adj matrices - torch.Tensor (K, n_nodes, n_nodes) :param x: graph feature/signal - torch.Tensor (batch_size, n_nodes, input_dim) :return: hidden representation - torch.Tensor (batch_size, n_nodes, h...
Batch-wise graph convolution operation on given n support adj matrices
[ "Batch", "-", "wise", "graph", "convolution", "operation", "on", "given", "n", "support", "adj", "matrices" ]
def forward(self, G: torch.Tensor, x: torch.Tensor): assert self.K == G.shape[0] support_list = list() for k in range(self.K): support = torch.einsum('ij,bjp->bip', [G[k, :, :], x]) support_list.append(support) support_cat = torch.cat(support_list, dim=-1) ...
[ "def", "forward", "(", "self", ",", "G", ":", "torch", ".", "Tensor", ",", "x", ":", "torch", ".", "Tensor", ")", ":", "assert", "self", ".", "K", "==", "G", ".", "shape", "[", "0", "]", "support_list", "=", "list", "(", ")", "for", "k", "in", ...
Batch-wise graph convolution operation on given n support adj matrices
[ "Batch", "-", "wise", "graph", "convolution", "operation", "on", "given", "n", "support", "adj", "matrices" ]
[ "'''\n Batch-wise graph convolution operation on given n support adj matrices\n :param G: support adj matrices - torch.Tensor (K, n_nodes, n_nodes)\n :param x: graph feature/signal - torch.Tensor (batch_size, n_nodes, input_dim)\n :return: hidden representation - torch.Tensor (batch_size...
[ { "param": "self", "type": null }, { "param": "G", "type": "torch.Tensor" }, { "param": "x", "type": "torch.Tensor" } ]
{ "returns": [ { "docstring": "hidden representation - torch.Tensor (batch_size, n_nodes, hidden_dim)", "docstring_tokens": [ "hidden", "representation", "-", "torch", ".", "Tensor", "(", "batch_size", "n_nodes", "hidden_d...
95cfc25477b59e0e94cd19d5a59192c54fe3f600
Dechrissen/PokeQuiz
pokequiz/Question.py
[ "MIT" ]
Python
checkPreevoGen
<not_specific>
def checkPreevoGen(preevo): """Returns the gen (str) of a preevo of a Pokemon object.""" conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() cur.execute('SELECT gen FROM pokemon WHERE name = ?;', (preevo,)) sel = list(cur.fetchone())[0] conn.close() return se...
Returns the gen (str) of a preevo of a Pokemon object.
Returns the gen (str) of a preevo of a Pokemon object.
[ "Returns", "the", "gen", "(", "str", ")", "of", "a", "preevo", "of", "a", "Pokemon", "object", "." ]
def checkPreevoGen(preevo): conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() cur.execute('SELECT gen FROM pokemon WHERE name = ?;', (preevo,)) sel = list(cur.fetchone())[0] conn.close() return sel
[ "def", "checkPreevoGen", "(", "preevo", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "db", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT gen F...
Returns the gen (str) of a preevo of a Pokemon object.
[ "Returns", "the", "gen", "(", "str", ")", "of", "a", "preevo", "of", "a", "Pokemon", "object", "." ]
[ "\"\"\"Returns the gen (str) of a preevo of a Pokemon object.\"\"\"" ]
[ { "param": "preevo", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "preevo", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
95cfc25477b59e0e94cd19d5a59192c54fe3f600
Dechrissen/PokeQuiz
pokequiz/Question.py
[ "MIT" ]
Python
randomPokemon
<not_specific>
def randomPokemon(): """Creates and returns a random Pokemon object.""" # Establish connection to SQLite database conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() # Get random Pokemon cur.execute('SELECT * FROM pokemon ORDER BY RANDOM() LIMIT 1;') sel = l...
Creates and returns a random Pokemon object.
Creates and returns a random Pokemon object.
[ "Creates", "and", "returns", "a", "random", "Pokemon", "object", "." ]
def randomPokemon(): conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() cur.execute('SELECT * FROM pokemon ORDER BY RANDOM() LIMIT 1;') sel = list(cur.fetchone()) sel[2] = json.loads(sel[2]) conn.close() return Pokemon(*sel)
[ "def", "randomPokemon", "(", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "db", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT * FROM pokemon ORD...
Creates and returns a random Pokemon object.
[ "Creates", "and", "returns", "a", "random", "Pokemon", "object", "." ]
[ "\"\"\"Creates and returns a random Pokemon object.\"\"\"", "# Establish connection to SQLite database", "# Get random Pokemon", "# Parse types list", "# Close connection" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
95cfc25477b59e0e94cd19d5a59192c54fe3f600
Dechrissen/PokeQuiz
pokequiz/Question.py
[ "MIT" ]
Python
randomLeader
<not_specific>
def randomLeader(): """Creates and returns a random Leader object.""" # Establish connection to SQLite database conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() # Get random Gym Leader cur.execute('SELECT * FROM leaders ORDER BY RANDOM() LIMIT 1;') sel = ...
Creates and returns a random Leader object.
Creates and returns a random Leader object.
[ "Creates", "and", "returns", "a", "random", "Leader", "object", "." ]
def randomLeader(): conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() cur.execute('SELECT * FROM leaders ORDER BY RANDOM() LIMIT 1;') sel = cur.fetchone() conn.close() return Leader(*sel)
[ "def", "randomLeader", "(", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "db", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT * FROM leaders ORDE...
Creates and returns a random Leader object.
[ "Creates", "and", "returns", "a", "random", "Leader", "object", "." ]
[ "\"\"\"Creates and returns a random Leader object.\"\"\"", "# Establish connection to SQLite database", "# Get random Gym Leader", "# Close connection" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
95cfc25477b59e0e94cd19d5a59192c54fe3f600
Dechrissen/PokeQuiz
pokequiz/Question.py
[ "MIT" ]
Python
randomTeam
<not_specific>
def randomTeam(): """Creates and returns a random Team object.""" # Establish connection to SQLite database conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() # Get random Team cur.execute('SELECT * FROM teams ORDER BY RANDOM() LIMIT 1;') sel = cur.fetchone...
Creates and returns a random Team object.
Creates and returns a random Team object.
[ "Creates", "and", "returns", "a", "random", "Team", "object", "." ]
def randomTeam(): conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() cur.execute('SELECT * FROM teams ORDER BY RANDOM() LIMIT 1;') sel = cur.fetchone() conn.close() return Team(*sel)
[ "def", "randomTeam", "(", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "db", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT * FROM teams ORDER BY...
Creates and returns a random Team object.
[ "Creates", "and", "returns", "a", "random", "Team", "object", "." ]
[ "\"\"\"Creates and returns a random Team object.\"\"\"", "# Establish connection to SQLite database", "# Get random Team", "# Close connection" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
95cfc25477b59e0e94cd19d5a59192c54fe3f600
Dechrissen/PokeQuiz
pokequiz/Question.py
[ "MIT" ]
Python
randomTown
<not_specific>
def randomTown(): """Creates and returns a random Town object.""" # Establish connection to SQLite database conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() # Get random Town cur.execute('SELECT * FROM towns ORDER BY RANDOM() LIMIT 1;') sel = list(cur.fet...
Creates and returns a random Town object.
Creates and returns a random Town object.
[ "Creates", "and", "returns", "a", "random", "Town", "object", "." ]
def randomTown(): conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() cur.execute('SELECT * FROM towns ORDER BY RANDOM() LIMIT 1;') sel = list(cur.fetchone()) sel[2] = json.loads(sel[2]) conn.close() return Town(*sel)
[ "def", "randomTown", "(", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "db", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT * FROM towns ORDER BY...
Creates and returns a random Town object.
[ "Creates", "and", "returns", "a", "random", "Town", "object", "." ]
[ "\"\"\"Creates and returns a random Town object.\"\"\"", "# Establish connection to SQLite database", "# Get random Town", "# Parse leaders list", "# Close connection" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
95cfc25477b59e0e94cd19d5a59192c54fe3f600
Dechrissen/PokeQuiz
pokequiz/Question.py
[ "MIT" ]
Python
randomRegion
<not_specific>
def randomRegion(): """Creates and returns a random Region object.""" # Establish connection to SQLite database conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() # Get random Region cur.execute('SELECT * FROM regions ORDER BY RANDOM() LIMIT 1;') sel = list...
Creates and returns a random Region object.
Creates and returns a random Region object.
[ "Creates", "and", "returns", "a", "random", "Region", "object", "." ]
def randomRegion(): conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() cur.execute('SELECT * FROM regions ORDER BY RANDOM() LIMIT 1;') sel = list(cur.fetchone()) sel[2] = json.loads(sel[2]) sel[3] = json.loads(sel[3]) conn.close() return Region(*sel)
[ "def", "randomRegion", "(", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "db", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT * FROM regions ORDE...
Creates and returns a random Region object.
[ "Creates", "and", "returns", "a", "random", "Region", "object", "." ]
[ "\"\"\"Creates and returns a random Region object.\"\"\"", "# Establish connection to SQLite database", "# Get random Region", "# Parse towns list", "# Parse landmarks list", "# Close connection" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
95cfc25477b59e0e94cd19d5a59192c54fe3f600
Dechrissen/PokeQuiz
pokequiz/Question.py
[ "MIT" ]
Python
randomGame
<not_specific>
def randomGame(): """Creates and returns a random Game object.""" # Establish connection to SQLite database conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() # Get random Game cur.execute('SELECT * FROM games ORDER BY RANDOM() LIMIT 1;') sel = list(cur.fet...
Creates and returns a random Game object.
Creates and returns a random Game object.
[ "Creates", "and", "returns", "a", "random", "Game", "object", "." ]
def randomGame(): conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) cur = conn.cursor() cur.execute('SELECT * FROM games ORDER BY RANDOM() LIMIT 1;') sel = list(cur.fetchone()) sel[3] = json.loads(sel[3]) conn.close() return Game(*sel)
[ "def", "randomGame", "(", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "db", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "cur", "=", "conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "'SELECT * FROM games ORDER BY...
Creates and returns a random Game object.
[ "Creates", "and", "returns", "a", "random", "Game", "object", "." ]
[ "\"\"\"Creates and returns a random Game object.\"\"\"", "# Establish connection to SQLite database", "# Get random Game", "# Parse rivals list", "# Close connection" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
95cfc25477b59e0e94cd19d5a59192c54fe3f600
Dechrissen/PokeQuiz
pokequiz/Question.py
[ "MIT" ]
Python
removeWords
<not_specific>
def removeWords(answer): """Removes specific words from input or answer, to allow for more leniency.""" words = [' town', ' city', ' island', ' badge', 'professor ', 'team '] answer = answer.lower() for word in words: answer = answer.replace(word, '') return answer
Removes specific words from input or answer, to allow for more leniency.
Removes specific words from input or answer, to allow for more leniency.
[ "Removes", "specific", "words", "from", "input", "or", "answer", "to", "allow", "for", "more", "leniency", "." ]
def removeWords(answer): words = [' town', ' city', ' island', ' badge', 'professor ', 'team '] answer = answer.lower() for word in words: answer = answer.replace(word, '') return answer
[ "def", "removeWords", "(", "answer", ")", ":", "words", "=", "[", "' town'", ",", "' city'", ",", "' island'", ",", "' badge'", ",", "'professor '", ",", "'team '", "]", "answer", "=", "answer", ".", "lower", "(", ")", "for", "word", "in", "words", ":"...
Removes specific words from input or answer, to allow for more leniency.
[ "Removes", "specific", "words", "from", "input", "or", "answer", "to", "allow", "for", "more", "leniency", "." ]
[ "\"\"\"Removes specific words from input or answer, to allow for more leniency.\"\"\"" ]
[ { "param": "answer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "answer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6b2847d0ef2aafced05fa68a40e983a929d467d0
as-suvorov/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/mnist.py
[ "Apache-2.0" ]
Python
configure
null
def configure(self): """ This method is responsible for obtaining the necessary parameters for converting from the command line or config. """ self.test_csv_file = self.get_value_from_config('annotation_file') self.converted_images_dir = self.get_value_from_config('conver...
This method is responsible for obtaining the necessary parameters for converting from the command line or config.
This method is responsible for obtaining the necessary parameters for converting from the command line or config.
[ "This", "method", "is", "responsible", "for", "obtaining", "the", "necessary", "parameters", "for", "converting", "from", "the", "command", "line", "or", "config", "." ]
def configure(self): self.test_csv_file = self.get_value_from_config('annotation_file') self.converted_images_dir = self.get_value_from_config('converted_images_dir') self.convert_images = self.get_value_from_config('convert_images') if self.convert_images and not self.converted_images_d...
[ "def", "configure", "(", "self", ")", ":", "self", ".", "test_csv_file", "=", "self", ".", "get_value_from_config", "(", "'annotation_file'", ")", "self", ".", "converted_images_dir", "=", "self", ".", "get_value_from_config", "(", "'converted_images_dir'", ")", "...
This method is responsible for obtaining the necessary parameters for converting from the command line or config.
[ "This", "method", "is", "responsible", "for", "obtaining", "the", "necessary", "parameters", "for", "converting", "from", "the", "command", "line", "or", "config", "." ]
[ "\"\"\"\n This method is responsible for obtaining the necessary parameters\n for converting from the command line or config.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6b2847d0ef2aafced05fa68a40e983a929d467d0
as-suvorov/open_model_zoo
tools/accuracy_checker/accuracy_checker/annotation_converters/mnist.py
[ "Apache-2.0" ]
Python
convert
<not_specific>
def convert(self, check_content=False, progress_callback=None, progress_interval=100, **kwargs): """ This method is executed automatically when convert.py is started. All arguments are automatically got from command line arguments or config file in method configure Returns: ...
This method is executed automatically when convert.py is started. All arguments are automatically got from command line arguments or config file in method configure Returns: annotations: list of annotation representation objects. meta: dictionary with additional dataset...
This method is executed automatically when convert.py is started. All arguments are automatically got from command line arguments or config file in method configure
[ "This", "method", "is", "executed", "automatically", "when", "convert", ".", "py", "is", "started", ".", "All", "arguments", "are", "automatically", "got", "from", "command", "line", "arguments", "or", "config", "file", "in", "method", "configure" ]
def convert(self, check_content=False, progress_callback=None, progress_interval=100, **kwargs): annotations = [] check_images = check_content and not self.convert_images meta = self.generate_meta() labels_to_id = meta['label_map'] content_errors = None if check_content: ...
[ "def", "convert", "(", "self", ",", "check_content", "=", "False", ",", "progress_callback", "=", "None", ",", "progress_interval", "=", "100", ",", "**", "kwargs", ")", ":", "annotations", "=", "[", "]", "check_images", "=", "check_content", "and", "not", ...
This method is executed automatically when convert.py is started.
[ "This", "method", "is", "executed", "automatically", "when", "convert", ".", "py", "is", "started", "." ]
[ "\"\"\"\n This method is executed automatically when convert.py is started.\n All arguments are automatically got from command line arguments or config file in method configure\n\n Returns:\n annotations: list of annotation representation objects.\n meta: dictionary with a...
[ { "param": "self", "type": null }, { "param": "check_content", "type": null }, { "param": "progress_callback", "type": null }, { "param": "progress_interval", "type": null } ]
{ "returns": [ { "docstring": "list of annotation representation objects.\nmeta: dictionary with additional dataset level metadata.", "docstring_tokens": [ "list", "of", "annotation", "representation", "objects", ".", "meta", ":", ...
b92f6bd235afde60271891420b1781b2a06e5b79
as-suvorov/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/machine_translation.py
[ "Apache-2.0" ]
Python
_get_ngrams
<not_specific>
def _get_ngrams(segment, max_order): """Extracts all n-grams upto a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter c...
Extracts all n-grams upto a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n-grams upto max_order in segm...
Extracts all n-grams upto a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n-grams upto max_order in segment with a count of how many times each ...
[ "Extracts", "all", "n", "-", "grams", "upto", "a", "given", "maximum", "order", "from", "an", "input", "segment", ".", "Args", ":", "segment", ":", "text", "segment", "from", "which", "n", "-", "grams", "will", "be", "extracted", ".", "max_order", ":", ...
def _get_ngrams(segment, max_order): ngram_counts = Counter() for order in range(1, max_order + 1): for i in range(0, len(segment) - order + 1): ngram = tuple(segment[i:i+order]) ngram_counts[ngram] += 1 return ngram_counts
[ "def", "_get_ngrams", "(", "segment", ",", "max_order", ")", ":", "ngram_counts", "=", "Counter", "(", ")", "for", "order", "in", "range", "(", "1", ",", "max_order", "+", "1", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "segmen...
Extracts all n-grams upto a given maximum order from an input segment.
[ "Extracts", "all", "n", "-", "grams", "upto", "a", "given", "maximum", "order", "from", "an", "input", "segment", "." ]
[ "\"\"\"Extracts all n-grams upto a given maximum order from an input segment.\n Args:\n segment: text segment from which n-grams will be extracted.\n max_order: maximum length in tokens of the n-grams returned by this\n methods.\n Returns:\n The Counter containing all n-grams upto ...
[ { "param": "segment", "type": null }, { "param": "max_order", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "segment", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "max_order", "type": null, "docstring": null, "docstring_to...
b92f6bd235afde60271891420b1781b2a06e5b79
as-suvorov/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/machine_translation.py
[ "Apache-2.0" ]
Python
_get_ngrams
<not_specific>
def _get_ngrams(segment, max_order): """Extracts all n-grams upto a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns:...
Extracts all n-grams upto a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: The Counter containing all n-grams up...
Extracts all n-grams upto a given maximum order from an input segment.
[ "Extracts", "all", "n", "-", "grams", "upto", "a", "given", "maximum", "order", "from", "an", "input", "segment", "." ]
def _get_ngrams(segment, max_order): ngram_counts = Counter() for order in range(1, max_order + 1): for i in range(0, len(segment) - order + 1): ngram = tuple(segment[i:i + order]) ngram_counts[ngram] += 1 return ngram_counts
[ "def", "_get_ngrams", "(", "segment", ",", "max_order", ")", ":", "ngram_counts", "=", "Counter", "(", ")", "for", "order", "in", "range", "(", "1", ",", "max_order", "+", "1", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "segmen...
Extracts all n-grams upto a given maximum order from an input segment.
[ "Extracts", "all", "n", "-", "grams", "upto", "a", "given", "maximum", "order", "from", "an", "input", "segment", "." ]
[ "\"\"\"Extracts all n-grams upto a given maximum order from an input segment.\n Args:\n segment: text segment from which n-grams will be extracted.\n max_order: maximum length in tokens of the n-grams returned by this\n methods.\n Returns:\n The Counter containi...
[ { "param": "segment", "type": null }, { "param": "max_order", "type": null } ]
{ "returns": [ { "docstring": "The Counter containing all n-grams upto max_order in segment\nwith a count of how many times each n-gram occurred.", "docstring_tokens": [ "The", "Counter", "containing", "all", "n", "-", "grams", "upto", ...
45464ce996bf04ea46d79f9b3d323e5030a8bc71
as-suvorov/open_model_zoo
tools/accuracy_checker/accuracy_checker/metrics/metric_executor.py
[ "Apache-2.0" ]
Python
update_metrics_on_batch
<not_specific>
def update_metrics_on_batch(self, batch_ids, annotation, prediction): """ Updates metric value corresponding given batch. Args: annotation: list of batch number of annotation objects. prediction: list of batch number of prediction objects. """ results = ...
Updates metric value corresponding given batch. Args: annotation: list of batch number of annotation objects. prediction: list of batch number of prediction objects.
Updates metric value corresponding given batch.
[ "Updates", "metric", "value", "corresponding", "given", "batch", "." ]
def update_metrics_on_batch(self, batch_ids, annotation, prediction): results = OrderedDict() for input_id, single_annotation, single_prediction in zip(batch_ids, annotation, prediction): results[input_id] = self.update_metrics_on_object(single_annotation, single_prediction) return r...
[ "def", "update_metrics_on_batch", "(", "self", ",", "batch_ids", ",", "annotation", ",", "prediction", ")", ":", "results", "=", "OrderedDict", "(", ")", "for", "input_id", ",", "single_annotation", ",", "single_prediction", "in", "zip", "(", "batch_ids", ",", ...
Updates metric value corresponding given batch.
[ "Updates", "metric", "value", "corresponding", "given", "batch", "." ]
[ "\"\"\"\n Updates metric value corresponding given batch.\n\n Args:\n annotation: list of batch number of annotation objects.\n prediction: list of batch number of prediction objects.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "batch_ids", "type": null }, { "param": "annotation", "type": null }, { "param": "prediction", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "batch_ids", "type": null, "docstring": null, "docstring_token...
5ec04f8cf98e18853f74b2cf718098d30c17d03d
chriszs/warn-transformer
warn_transformer/transformers/or.py
[ "Apache-2.0" ]
Python
check_if_temporary
typing.Optional[bool]
def check_if_temporary(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a temporary or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ return "temporary" in row["Layoff Type"].lower() or None
Determine whether a row is a temporary or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a temporary or not.
[ "Determine", "whether", "a", "row", "is", "a", "temporary", "or", "not", "." ]
def check_if_temporary(self, row: typing.Dict) -> typing.Optional[bool]: return "temporary" in row["Layoff Type"].lower() or None
[ "def", "check_if_temporary", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "return", "\"temporary\"", "in", "row", "[", "\"Layoff Type\"", "]", ".", "lower", "(", ")", "or", "None" ]
Determine whether a row is a temporary or not.
[ "Determine", "whether", "a", "row", "is", "a", "temporary", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a temporary or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
5ec04f8cf98e18853f74b2cf718098d30c17d03d
chriszs/warn-transformer
warn_transformer/transformers/or.py
[ "Apache-2.0" ]
Python
check_if_closure
typing.Optional[bool]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ return "closure" in row["Layoff Type"].lower() or None
Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: return "closure" in row["Layoff Type"].lower() or None
[ "def", "check_if_closure", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "return", "\"closure\"", "in", "row", "[", "\"Layoff Type\"", "]", ".", "lower", "(", ")", "or", "None" ]
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a closure or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
28be073cca378f6d13f640fc3cf6779f557e8277
chriszs/warn-transformer
warn_transformer/download.py
[ "Apache-2.0" ]
Python
run
null
def run( download_dir: Path = utils.WARN_TRANSFORMER_OUTPUT_DIR / "raw", source: typing.Optional[str] = None, ): """Download all the CSVs in the WARN Notice project on biglocalnews.org. Args: download_dir (Path): The directory where files will be downloaded. source (str): The postal cod...
Download all the CSVs in the WARN Notice project on biglocalnews.org. Args: download_dir (Path): The directory where files will be downloaded. source (str): The postal code of the source to download. Default is all sources.
Download all the CSVs in the WARN Notice project on biglocalnews.org.
[ "Download", "all", "the", "CSVs", "in", "the", "WARN", "Notice", "project", "on", "biglocalnews", ".", "org", "." ]
def run( download_dir: Path = utils.WARN_TRANSFORMER_OUTPUT_DIR / "raw", source: typing.Optional[str] = None, ): logging.basicConfig(level="DEBUG", format="%(asctime)s - %(name)s - %(message)s") c = Client(BLN_API_KEY) p = c.get_project_by_name("WARN Act Notices") file_list = [f["name"] for f in...
[ "def", "run", "(", "download_dir", ":", "Path", "=", "utils", ".", "WARN_TRANSFORMER_OUTPUT_DIR", "/", "\"raw\"", ",", "source", ":", "typing", ".", "Optional", "[", "str", "]", "=", "None", ",", ")", ":", "logging", ".", "basicConfig", "(", "level", "="...
Download all the CSVs in the WARN Notice project on biglocalnews.org.
[ "Download", "all", "the", "CSVs", "in", "the", "WARN", "Notice", "project", "on", "biglocalnews", ".", "org", "." ]
[ "\"\"\"Download all the CSVs in the WARN Notice project on biglocalnews.org.\n\n Args:\n download_dir (Path): The directory where files will be downloaded.\n source (str): The postal code of the source to download. Default is all sources.\n \"\"\"", "# Login to BLN.", "# Get the Warn Act Not...
[ { "param": "download_dir", "type": "Path" }, { "param": "source", "type": "typing.Optional[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "download_dir", "type": "Path", "docstring": "The directory where files will be downloaded.", "docstring_tokens": [ "The", "directory", "where", "files", "will", "be", "do...
3505ad163a3d405526c303da11d8a72f9ddccf1a
chriszs/warn-transformer
warn_transformer/transformers/ky.py
[ "Apache-2.0" ]
Python
transform_jobs
typing.Optional[int]
def transform_jobs(self, value: str) -> typing.Optional[int]: """Transform a raw jobs number into an integer. Args: value (str): A raw jobs number provided by the source Returns: An integer number ready for consolidation. Or, if the value is invalid, a None. """ val...
Transform a raw jobs number into an integer. Args: value (str): A raw jobs number provided by the source Returns: An integer number ready for consolidation. Or, if the value is invalid, a None.
Transform a raw jobs number into an integer.
[ "Transform", "a", "raw", "jobs", "number", "into", "an", "integer", "." ]
def transform_jobs(self, value: str) -> typing.Optional[int]: value = value.split("-")[0].strip() value = value.replace("+/-", "") value = value.replace("+/", "").strip() value = value.replace("+", "").strip() value = re.split(" {5,}", value)[0].strip() return super().tra...
[ "def", "transform_jobs", "(", "self", ",", "value", ":", "str", ")", "->", "typing", ".", "Optional", "[", "int", "]", ":", "value", "=", "value", ".", "split", "(", "\"-\"", ")", "[", "0", "]", ".", "strip", "(", ")", "value", "=", "value", ".",...
Transform a raw jobs number into an integer.
[ "Transform", "a", "raw", "jobs", "number", "into", "an", "integer", "." ]
[ "\"\"\"Transform a raw jobs number into an integer.\n\n Args:\n value (str): A raw jobs number provided by the source\n\n Returns: An integer number ready for consolidation. Or, if the value is invalid, a None.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "value", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": "str", "docstring": "A raw jobs number provided by ...
3505ad163a3d405526c303da11d8a72f9ddccf1a
chriszs/warn-transformer
warn_transformer/transformers/ky.py
[ "Apache-2.0" ]
Python
check_if_closure
typing.Optional[bool]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ if "closure" in row["Closure or Layoff?"].lower(): return True ...
Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: if "closure" in row["Closure or Layoff?"].lower(): return True elif "closure" in row["Closure/Layoff"].lower(): return True else: return None
[ "def", "check_if_closure", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "if", "\"closure\"", "in", "row", "[", "\"Closure or Layoff?\"", "]", ".", "lower", "(", ")", ":", "return", "T...
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a closure or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
c4f06d0987d504fa5a6d8de9970ab167d04d5f60
chriszs/warn-transformer
warn_transformer/transformers/ny.py
[ "Apache-2.0" ]
Python
check_if_temporary
typing.Optional[bool]
def check_if_temporary(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a temporary or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ value = row["Dislocation Type"].lower() if "possible" in value or...
Determine whether a row is a temporary or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a temporary or not.
[ "Determine", "whether", "a", "row", "is", "a", "temporary", "or", "not", "." ]
def check_if_temporary(self, row: typing.Dict) -> typing.Optional[bool]: value = row["Dislocation Type"].lower() if "possible" in value or "potential" in value: return None return "temp" in value or None
[ "def", "check_if_temporary", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "value", "=", "row", "[", "\"Dislocation Type\"", "]", ".", "lower", "(", ")", "if", "\"possible\"", "in", "v...
Determine whether a row is a temporary or not.
[ "Determine", "whether", "a", "row", "is", "a", "temporary", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a temporary or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
c4f06d0987d504fa5a6d8de9970ab167d04d5f60
chriszs/warn-transformer
warn_transformer/transformers/ny.py
[ "Apache-2.0" ]
Python
check_if_closure
typing.Optional[bool]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ value = row["Dislocation Type"].lower() if "possible" in value or "po...
Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: value = row["Dislocation Type"].lower() if "possible" in value or "potential" in value or "temp" in value: return None return "clos" in value or None
[ "def", "check_if_closure", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "value", "=", "row", "[", "\"Dislocation Type\"", "]", ".", "lower", "(", ")", "if", "\"possible\"", "in", "val...
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a closure or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
0d2192eb5f7ac81fa23f543d3cb646772588b182
chriszs/warn-transformer
warn_transformer/transformers/ia.py
[ "Apache-2.0" ]
Python
check_if_amendment
bool
def check_if_amendment(self, row: typing.Dict) -> bool: """Determine whether a row is an amendment or not. Args: row (dict): The raw row of data. Returns: A boolean """ return "amendment" in row["Notice Type"].lower().strip()
Determine whether a row is an amendment or not. Args: row (dict): The raw row of data. Returns: A boolean
Determine whether a row is an amendment or not.
[ "Determine", "whether", "a", "row", "is", "an", "amendment", "or", "not", "." ]
def check_if_amendment(self, row: typing.Dict) -> bool: return "amendment" in row["Notice Type"].lower().strip()
[ "def", "check_if_amendment", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "bool", ":", "return", "\"amendment\"", "in", "row", "[", "\"Notice Type\"", "]", ".", "lower", "(", ")", ".", "strip", "(", ")" ]
Determine whether a row is an amendment or not.
[ "Determine", "whether", "a", "row", "is", "an", "amendment", "or", "not", "." ]
[ "\"\"\"Determine whether a row is an amendment or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
0d2192eb5f7ac81fa23f543d3cb646772588b182
chriszs/warn-transformer
warn_transformer/transformers/ia.py
[ "Apache-2.0" ]
Python
check_if_closure
typing.Optional[bool]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ return "closing" in row["Notice Type"].lower() or None
Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: return "closing" in row["Notice Type"].lower() or None
[ "def", "check_if_closure", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "return", "\"closing\"", "in", "row", "[", "\"Notice Type\"", "]", ".", "lower", "(", ")", "or", "None" ]
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a closure or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
0d2192eb5f7ac81fa23f543d3cb646772588b182
chriszs/warn-transformer
warn_transformer/transformers/ia.py
[ "Apache-2.0" ]
Python
handle_amendments
typing.List[typing.Dict]
def handle_amendments( self, row_list: typing.List[typing.Dict] ) -> typing.List[typing.Dict]: """Remove amended filings from the provided list of records. Args: row_list (list): A list of clean rows of data. Returns: A list of cleaned data, minus amended records. ...
Remove amended filings from the provided list of records. Args: row_list (list): A list of clean rows of data. Returns: A list of cleaned data, minus amended records.
Remove amended filings from the provided list of records.
[ "Remove", "amended", "filings", "from", "the", "provided", "list", "of", "records", "." ]
def handle_amendments( self, row_list: typing.List[typing.Dict] ) -> typing.List[typing.Dict]: amendments_count = len([r for r in row_list if r["is_amendment"] is True]) logger.debug(f"{amendments_count} amendments in {self.postal_code}") logger.debug( "No action has been...
[ "def", "handle_amendments", "(", "self", ",", "row_list", ":", "typing", ".", "List", "[", "typing", ".", "Dict", "]", ")", "->", "typing", ".", "List", "[", "typing", ".", "Dict", "]", ":", "amendments_count", "=", "len", "(", "[", "r", "for", "r", ...
Remove amended filings from the provided list of records.
[ "Remove", "amended", "filings", "from", "the", "provided", "list", "of", "records", "." ]
[ "\"\"\"Remove amended filings from the provided list of records.\n\n Args:\n row_list (list): A list of clean rows of data.\n\n Returns: A list of cleaned data, minus amended records.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row_list", "type": "typing.List[typing.Dict]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row_list", "type": "typing.List[typing.Dict]", "docstring": "A list...
cd67f27bc7b1512472eda3ea5e0ea10369febe6c
chriszs/warn-transformer
warn_transformer/transformers/mo.py
[ "Apache-2.0" ]
Python
transform_date
typing.Optional[str]
def transform_date(self, value: str) -> typing.Optional[str]: """Transform a raw date string into a date object. Args: value (str): The raw date string provided by the source Returns: A date object ready for consolidation. Or, if the date string is invalid, a None. """ ...
Transform a raw date string into a date object. Args: value (str): The raw date string provided by the source Returns: A date object ready for consolidation. Or, if the date string is invalid, a None.
Transform a raw date string into a date object.
[ "Transform", "a", "raw", "date", "string", "into", "a", "date", "object", "." ]
def transform_date(self, value: str) -> typing.Optional[str]: try: return super().transform_date(value) except Exception: value = value.strip().split()[0].strip() value = value.strip().split("-")[0].strip() value = value.replace("–", "") value ...
[ "def", "transform_date", "(", "self", ",", "value", ":", "str", ")", "->", "typing", ".", "Optional", "[", "str", "]", ":", "try", ":", "return", "super", "(", ")", ".", "transform_date", "(", "value", ")", "except", "Exception", ":", "value", "=", "...
Transform a raw date string into a date object.
[ "Transform", "a", "raw", "date", "string", "into", "a", "date", "object", "." ]
[ "\"\"\"Transform a raw date string into a date object.\n\n Args:\n value (str): The raw date string provided by the source\n\n Returns: A date object ready for consolidation. Or, if the date string is invalid, a None.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "value", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": "str", "docstring": "The raw date string provided b...
cd67f27bc7b1512472eda3ea5e0ea10369febe6c
chriszs/warn-transformer
warn_transformer/transformers/mo.py
[ "Apache-2.0" ]
Python
check_if_closure
typing.Optional[bool]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ return "clos" in row["TYPE"].lower() or None
Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: return "clos" in row["TYPE"].lower() or None
[ "def", "check_if_closure", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "return", "\"clos\"", "in", "row", "[", "\"TYPE\"", "]", ".", "lower", "(", ")", "or", "None" ]
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a closure or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
6ab62335f150e612a5bf8ebcc5dfa6f76bba8aea
chriszs/warn-transformer
warn_transformer/transformers/wi.py
[ "Apache-2.0" ]
Python
transform_company
str
def transform_company(self, value: str) -> str: """Transform a raw company name. Args: value (str): The raw company string provided by the source Returns: A string object ready for consolidation. """ # Cut revision notices value = value.split("- Revision")[0...
Transform a raw company name. Args: value (str): The raw company string provided by the source Returns: A string object ready for consolidation.
Transform a raw company name.
[ "Transform", "a", "raw", "company", "name", "." ]
def transform_company(self, value: str) -> str: value = value.split("- Revision")[0] return super().transform_company(value)
[ "def", "transform_company", "(", "self", ",", "value", ":", "str", ")", "->", "str", ":", "value", "=", "value", ".", "split", "(", "\"- Revision\"", ")", "[", "0", "]", "return", "super", "(", ")", ".", "transform_company", "(", "value", ")" ]
Transform a raw company name.
[ "Transform", "a", "raw", "company", "name", "." ]
[ "\"\"\"Transform a raw company name.\n\n Args:\n value (str): The raw company string provided by the source\n\n Returns: A string object ready for consolidation.\n \"\"\"", "# Cut revision notices", "# Do the typical stuff" ]
[ { "param": "self", "type": null }, { "param": "value", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": "str", "docstring": "The raw company string provide...
6ab62335f150e612a5bf8ebcc5dfa6f76bba8aea
chriszs/warn-transformer
warn_transformer/transformers/wi.py
[ "Apache-2.0" ]
Python
check_if_amendment
bool
def check_if_amendment(self, row: typing.Dict) -> bool: """Determine whether a row is an amendment or not. Args: row (dict): The raw row of data. Returns: A boolean """ return "revision" in row["Company"].lower()
Determine whether a row is an amendment or not. Args: row (dict): The raw row of data. Returns: A boolean
Determine whether a row is an amendment or not.
[ "Determine", "whether", "a", "row", "is", "an", "amendment", "or", "not", "." ]
def check_if_amendment(self, row: typing.Dict) -> bool: return "revision" in row["Company"].lower()
[ "def", "check_if_amendment", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "bool", ":", "return", "\"revision\"", "in", "row", "[", "\"Company\"", "]", ".", "lower", "(", ")" ]
Determine whether a row is an amendment or not.
[ "Determine", "whether", "a", "row", "is", "an", "amendment", "or", "not", "." ]
[ "\"\"\"Determine whether a row is an amendment or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
6ab62335f150e612a5bf8ebcc5dfa6f76bba8aea
chriszs/warn-transformer
warn_transformer/transformers/wi.py
[ "Apache-2.0" ]
Python
handle_amendments
typing.List[typing.Dict]
def handle_amendments( self, row_list: typing.List[typing.Dict] ) -> typing.List[typing.Dict]: """Remove amended filings from the provided list of records. Args: row_list (list): A list of clean rows of data. Returns: A list of cleaned data, minus amended records. ...
Remove amended filings from the provided list of records. Args: row_list (list): A list of clean rows of data. Returns: A list of cleaned data, minus amended records.
Remove amended filings from the provided list of records.
[ "Remove", "amended", "filings", "from", "the", "provided", "list", "of", "records", "." ]
def handle_amendments( self, row_list: typing.List[typing.Dict] ) -> typing.List[typing.Dict]: amendments_count = len([r for r in row_list if r["is_amendment"] is True]) logger.debug(f"{amendments_count} amendments in {self.postal_code}") ancestor_list = [] for i, row in enum...
[ "def", "handle_amendments", "(", "self", ",", "row_list", ":", "typing", ".", "List", "[", "typing", ".", "Dict", "]", ")", "->", "typing", ".", "List", "[", "typing", ".", "Dict", "]", ":", "amendments_count", "=", "len", "(", "[", "r", "for", "r", ...
Remove amended filings from the provided list of records.
[ "Remove", "amended", "filings", "from", "the", "provided", "list", "of", "records", "." ]
[ "\"\"\"Remove amended filings from the provided list of records.\n\n Args:\n row_list (list): A list of clean rows of data.\n\n Returns: A list of cleaned data, minus amended records.\n \"\"\"", "# Loop through all the rows", "# If the current row is amended ...", "# Get the pr...
[ { "param": "self", "type": null }, { "param": "row_list", "type": "typing.List[typing.Dict]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row_list", "type": "typing.List[typing.Dict]", "docstring": "A list...
c4478362e710d32858983686e327a290501aa042
chriszs/warn-transformer
warn_transformer/transformers/oh.py
[ "Apache-2.0" ]
Python
transform_date
typing.Optional[str]
def transform_date(self, value: str) -> typing.Optional[str]: """Transform a raw date string into a date object. Args: value (str): The raw date string provided by the source Returns: A date object ready for consolidation. Or, if the date string is invalid, a None. """ ...
Transform a raw date string into a date object. Args: value (str): The raw date string provided by the source Returns: A date object ready for consolidation. Or, if the date string is invalid, a None.
Transform a raw date string into a date object.
[ "Transform", "a", "raw", "date", "string", "into", "a", "date", "object", "." ]
def transform_date(self, value: str) -> typing.Optional[str]: value = value.replace("Updated", "") value = value.replace("Revised", "") value = value.replace("-", "").strip() if len(value) == 20: value = value[:10] value = re.split(r"\s{2,}", value)[0].strip() ...
[ "def", "transform_date", "(", "self", ",", "value", ":", "str", ")", "->", "typing", ".", "Optional", "[", "str", "]", ":", "value", "=", "value", ".", "replace", "(", "\"Updated\"", ",", "\"\"", ")", "value", "=", "value", ".", "replace", "(", "\"Re...
Transform a raw date string into a date object.
[ "Transform", "a", "raw", "date", "string", "into", "a", "date", "object", "." ]
[ "\"\"\"Transform a raw date string into a date object.\n\n Args:\n value (str): The raw date string provided by the source\n\n Returns: A date object ready for consolidation. Or, if the date string is invalid, a None.\n \"\"\"", "# Cut out cruft", "# Split double dates" ]
[ { "param": "self", "type": null }, { "param": "value", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": "str", "docstring": "The raw date string provided b...
eb531e11a9127b1c39c25f2a36636d8fc5b11dd6
chriszs/warn-transformer
warn_transformer/transformers/ri.py
[ "Apache-2.0" ]
Python
transform_company
str
def transform_company(self, value: str) -> str: """Transform a raw company name. Args: value (str): The raw company string provided by the source Returns: A string object ready for consolidation. """ return value.strip().replace("*", "")
Transform a raw company name. Args: value (str): The raw company string provided by the source Returns: A string object ready for consolidation.
Transform a raw company name.
[ "Transform", "a", "raw", "company", "name", "." ]
def transform_company(self, value: str) -> str: return value.strip().replace("*", "")
[ "def", "transform_company", "(", "self", ",", "value", ":", "str", ")", "->", "str", ":", "return", "value", ".", "strip", "(", ")", ".", "replace", "(", "\"*\"", ",", "\"\"", ")" ]
Transform a raw company name.
[ "Transform", "a", "raw", "company", "name", "." ]
[ "\"\"\"Transform a raw company name.\n\n Args:\n value (str): The raw company string provided by the source\n\n Returns: A string object ready for consolidation.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "value", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": "str", "docstring": "The raw company string provide...
eb531e11a9127b1c39c25f2a36636d8fc5b11dd6
chriszs/warn-transformer
warn_transformer/transformers/ri.py
[ "Apache-2.0" ]
Python
check_if_closure
typing.Optional[bool]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ return "yes" in row["Closing Yes/No"].lower() or None
Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: return "yes" in row["Closing Yes/No"].lower() or None
[ "def", "check_if_closure", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "return", "\"yes\"", "in", "row", "[", "\"Closing Yes/No\"", "]", ".", "lower", "(", ")", "or", "None" ]
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a closure or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
d68fdfd5c03f0110201c3cfea945ad58633ccb63
chriszs/warn-transformer
warn_transformer/transformers/ca.py
[ "Apache-2.0" ]
Python
check_if_temporary
typing.Optional[bool]
def check_if_temporary(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a temporary or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ return "temporary" in row["layoff_or_closure"].lower() or None
Determine whether a row is a temporary or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a temporary or not.
[ "Determine", "whether", "a", "row", "is", "a", "temporary", "or", "not", "." ]
def check_if_temporary(self, row: typing.Dict) -> typing.Optional[bool]: return "temporary" in row["layoff_or_closure"].lower() or None
[ "def", "check_if_temporary", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "return", "\"temporary\"", "in", "row", "[", "\"layoff_or_closure\"", "]", ".", "lower", "(", ")", "or", "None"...
Determine whether a row is a temporary or not.
[ "Determine", "whether", "a", "row", "is", "a", "temporary", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a temporary or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
d68fdfd5c03f0110201c3cfea945ad58633ccb63
chriszs/warn-transformer
warn_transformer/transformers/ca.py
[ "Apache-2.0" ]
Python
check_if_closure
typing.Optional[bool]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ return row["layoff_or_closure"].lower().strip() == "closure permanent" or Non...
Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: return row["layoff_or_closure"].lower().strip() == "closure permanent" or None
[ "def", "check_if_closure", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "return", "row", "[", "\"layoff_or_closure\"", "]", ".", "lower", "(", ")", ".", "strip", "(", ")", "==", "\"...
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a closure or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...
c37d94ee3017642a91c57749089bf505c1cd7ef9
chriszs/warn-transformer
warn_transformer/transformers/il.py
[ "Apache-2.0" ]
Python
check_if_closure
typing.Optional[bool]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: """Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null """ return "closure" in row["Reason"].lower() or None
Determine whether a row is a closure or not. Args: row (dict): The raw row of data. Returns: A boolean or null
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
def check_if_closure(self, row: typing.Dict) -> typing.Optional[bool]: return "closure" in row["Reason"].lower() or None
[ "def", "check_if_closure", "(", "self", ",", "row", ":", "typing", ".", "Dict", ")", "->", "typing", ".", "Optional", "[", "bool", "]", ":", "return", "\"closure\"", "in", "row", "[", "\"Reason\"", "]", ".", "lower", "(", ")", "or", "None" ]
Determine whether a row is a closure or not.
[ "Determine", "whether", "a", "row", "is", "a", "closure", "or", "not", "." ]
[ "\"\"\"Determine whether a row is a closure or not.\n\n Args:\n row (dict): The raw row of data.\n\n Returns: A boolean or null\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "row", "type": "typing.Dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "row", "type": "typing.Dict", "docstring": "The raw row of data.", ...