body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
741c773abb9ffc58115a63a3b2411750dafd14edc5121cb9a5f3a2f7dad0cbc7 | @classmethod
def can_create_at(cls, parent):
'\n Checks if this page type can be created as a subpage under a parent\n page instance.\n '
return (cls.is_creatable and cls.can_exist_under(parent)) | Checks if this page type can be created as a subpage under a parent
page instance. | tuiuiu/tuiuiucore/models.py | can_create_at | caputomarcos/tuiuiu.io | 3 | python | @classmethod
def can_create_at(cls, parent):
'\n Checks if this page type can be created as a subpage under a parent\n page instance.\n '
return (cls.is_creatable and cls.can_exist_under(parent)) | @classmethod
def can_create_at(cls, parent):
'\n Checks if this page type can be created as a subpage under a parent\n page instance.\n '
return (cls.is_creatable and cls.can_exist_under(parent))<|docstring|>Checks if this page type can be created as a subpage under a parent
page instance.<... |
1ae89d720e1f948619c93d962363d6f7c65f29dec1a7534a37af71c983eba152 | def can_move_to(self, parent):
'\n Checks if this page instance can be moved to be a subpage of a parent\n page instance.\n '
return self.can_exist_under(parent) | Checks if this page instance can be moved to be a subpage of a parent
page instance. | tuiuiu/tuiuiucore/models.py | can_move_to | caputomarcos/tuiuiu.io | 3 | python | def can_move_to(self, parent):
'\n Checks if this page instance can be moved to be a subpage of a parent\n page instance.\n '
return self.can_exist_under(parent) | def can_move_to(self, parent):
'\n Checks if this page instance can be moved to be a subpage of a parent\n page instance.\n '
return self.can_exist_under(parent)<|docstring|>Checks if this page instance can be moved to be a subpage of a parent
page instance.<|endoftext|> |
33e766d25bd6189884f5cbad617c871dbb0b7e736ca2feb4ce5cf05825f9e250 | @classmethod
def get_verbose_name(cls):
'\n Returns the human-readable "verbose name" of this page model e.g "Blog page".\n '
return capfirst(cls._meta.verbose_name) | Returns the human-readable "verbose name" of this page model e.g "Blog page". | tuiuiu/tuiuiucore/models.py | get_verbose_name | caputomarcos/tuiuiu.io | 3 | python | @classmethod
def get_verbose_name(cls):
'\n \n '
return capfirst(cls._meta.verbose_name) | @classmethod
def get_verbose_name(cls):
'\n \n '
return capfirst(cls._meta.verbose_name)<|docstring|>Returns the human-readable "verbose name" of this page model e.g "Blog page".<|endoftext|> |
7e7bbca4931a51bf9e1bc29c9e081c6be54fd69ad699e9d2968e870669768732 | def has_unpublished_subtree(self):
'\n An awkwardly-defined flag used in determining whether unprivileged editors have\n permission to delete this article. Returns true if and only if this page is non-live,\n and it has no live children.\n '
return ((not self.live) and (not self.get_... | An awkwardly-defined flag used in determining whether unprivileged editors have
permission to delete this article. Returns true if and only if this page is non-live,
and it has no live children. | tuiuiu/tuiuiucore/models.py | has_unpublished_subtree | caputomarcos/tuiuiu.io | 3 | python | def has_unpublished_subtree(self):
'\n An awkwardly-defined flag used in determining whether unprivileged editors have\n permission to delete this article. Returns true if and only if this page is non-live,\n and it has no live children.\n '
return ((not self.live) and (not self.get_... | def has_unpublished_subtree(self):
'\n An awkwardly-defined flag used in determining whether unprivileged editors have\n permission to delete this article. Returns true if and only if this page is non-live,\n and it has no live children.\n '
return ((not self.live) and (not self.get_... |
d031d22b6f1aea6138bcdc1f2d996dd55dc9ed9a2ac2b32abf7c69fb6ea22296 | @transaction.atomic
def move(self, target, pos=None):
"\n Extension to the treebeard 'move' method to ensure that url_path is updated too.\n "
old_url_path = Page.objects.get(id=self.id).url_path
super(Page, self).move(target, pos=pos)
new_self = Page.objects.get(id=self.id)
new_url_pa... | Extension to the treebeard 'move' method to ensure that url_path is updated too. | tuiuiu/tuiuiucore/models.py | move | caputomarcos/tuiuiu.io | 3 | python | @transaction.atomic
def move(self, target, pos=None):
"\n \n "
old_url_path = Page.objects.get(id=self.id).url_path
super(Page, self).move(target, pos=pos)
new_self = Page.objects.get(id=self.id)
new_url_path = new_self.set_url_path(new_self.get_parent())
new_self.save()
new_se... | @transaction.atomic
def move(self, target, pos=None):
"\n \n "
old_url_path = Page.objects.get(id=self.id).url_path
super(Page, self).move(target, pos=pos)
new_self = Page.objects.get(id=self.id)
new_url_path = new_self.set_url_path(new_self.get_parent())
new_self.save()
new_se... |
96a948fdaac63e91c45ee8acf5e9504b68eea418e5c9d1ff7a35d897c930e9c0 | def permissions_for_user(self, user):
'\n Return a PagePermissionsTester object defining what actions the user can perform on this page\n '
user_perms = UserPagePermissionsProxy(user)
return user_perms.for_page(self) | Return a PagePermissionsTester object defining what actions the user can perform on this page | tuiuiu/tuiuiucore/models.py | permissions_for_user | caputomarcos/tuiuiu.io | 3 | python | def permissions_for_user(self, user):
'\n \n '
user_perms = UserPagePermissionsProxy(user)
return user_perms.for_page(self) | def permissions_for_user(self, user):
'\n \n '
user_perms = UserPagePermissionsProxy(user)
return user_perms.for_page(self)<|docstring|>Return a PagePermissionsTester object defining what actions the user can perform on this page<|endoftext|> |
e3a9aa6a4a325e43ecd1ca077de5f5c14448cf4c0338ef51ef48a23cc8e41c11 | def dummy_request(self, original_request=None, **meta):
'\n Construct a HttpRequest object that is, as far as possible, representative of ones that would\n receive this page as a response. Used for previewing / moderation and any other place where we\n want to display a view of this page in the... | Construct a HttpRequest object that is, as far as possible, representative of ones that would
receive this page as a response. Used for previewing / moderation and any other place where we
want to display a view of this page in the admin interface without going through the regular
page routing logic.
If you pass in a ... | tuiuiu/tuiuiucore/models.py | dummy_request | caputomarcos/tuiuiu.io | 3 | python | def dummy_request(self, original_request=None, **meta):
'\n Construct a HttpRequest object that is, as far as possible, representative of ones that would\n receive this page as a response. Used for previewing / moderation and any other place where we\n want to display a view of this page in the... | def dummy_request(self, original_request=None, **meta):
'\n Construct a HttpRequest object that is, as far as possible, representative of ones that would\n receive this page as a response. Used for previewing / moderation and any other place where we\n want to display a view of this page in the... |
4ef31bd37b580720d428ba909746c108fa3fcde336a0995e0399b161059310fc | @property
def preview_modes(self):
"\n A list of (internal_name, display_name) tuples for the modes in which\n this page can be displayed for preview/moderation purposes. Ordinarily a page\n will only have one display mode, but subclasses of Page can override this -\n for example, a page... | A list of (internal_name, display_name) tuples for the modes in which
this page can be displayed for preview/moderation purposes. Ordinarily a page
will only have one display mode, but subclasses of Page can override this -
for example, a page containing a form might have a default view of the form,
and a post-submissi... | tuiuiu/tuiuiucore/models.py | preview_modes | caputomarcos/tuiuiu.io | 3 | python | @property
def preview_modes(self):
"\n A list of (internal_name, display_name) tuples for the modes in which\n this page can be displayed for preview/moderation purposes. Ordinarily a page\n will only have one display mode, but subclasses of Page can override this -\n for example, a page... | @property
def preview_modes(self):
"\n A list of (internal_name, display_name) tuples for the modes in which\n this page can be displayed for preview/moderation purposes. Ordinarily a page\n will only have one display mode, but subclasses of Page can override this -\n for example, a page... |
35e8809e8df4034c3bef1ce4c12075de6d2343ea872e5fafcb08c30f3af44bca | def serve_preview(self, request, mode_name):
"\n Return an HTTP response for use in page previews. Normally this would be equivalent\n to self.serve(request), since we obviously want the preview to be indicative of how\n it looks on the live site. However, there are a couple of cases where this... | Return an HTTP response for use in page previews. Normally this would be equivalent
to self.serve(request), since we obviously want the preview to be indicative of how
it looks on the live site. However, there are a couple of cases where this is not
appropriate, and custom behaviour is required:
1) The page has custom... | tuiuiu/tuiuiucore/models.py | serve_preview | caputomarcos/tuiuiu.io | 3 | python | def serve_preview(self, request, mode_name):
"\n Return an HTTP response for use in page previews. Normally this would be equivalent\n to self.serve(request), since we obviously want the preview to be indicative of how\n it looks on the live site. However, there are a couple of cases where this... | def serve_preview(self, request, mode_name):
"\n Return an HTTP response for use in page previews. Normally this would be equivalent\n to self.serve(request), since we obviously want the preview to be indicative of how\n it looks on the live site. However, there are a couple of cases where this... |
db3e3f9a6b669363126c902a32829770236f54a2cae37706fee941f290e452f8 | def get_cached_paths(self):
'\n This returns a list of paths to invalidate in a frontend cache\n '
return ['/'] | This returns a list of paths to invalidate in a frontend cache | tuiuiu/tuiuiucore/models.py | get_cached_paths | caputomarcos/tuiuiu.io | 3 | python | def get_cached_paths(self):
'\n \n '
return ['/'] | def get_cached_paths(self):
'\n \n '
return ['/']<|docstring|>This returns a list of paths to invalidate in a frontend cache<|endoftext|> |
7e06f28b3b07cb7dececcb386c4ff06157c9be52a59ec911583540a4593b1a43 | def get_static_site_paths(self):
'\n This is a generator of URL paths to feed into a static site generator\n Override this if you would like to create static versions of subpages\n '
(yield '/')
for child in self.get_children().live():
for path in child.specific.get_static_site_... | This is a generator of URL paths to feed into a static site generator
Override this if you would like to create static versions of subpages | tuiuiu/tuiuiucore/models.py | get_static_site_paths | caputomarcos/tuiuiu.io | 3 | python | def get_static_site_paths(self):
'\n This is a generator of URL paths to feed into a static site generator\n Override this if you would like to create static versions of subpages\n '
(yield '/')
for child in self.get_children().live():
for path in child.specific.get_static_site_... | def get_static_site_paths(self):
'\n This is a generator of URL paths to feed into a static site generator\n Override this if you would like to create static versions of subpages\n '
(yield '/')
for child in self.get_children().live():
for path in child.specific.get_static_site_... |
ed11beebc64a3af470bcd79774b5801c300c343d2e73a8e41f92ba025e821f73 | def get_view_restrictions(self):
'Return a query set of all page view restrictions that apply to this page'
return PageViewRestriction.objects.filter(page__in=self.get_ancestors(inclusive=True)) | Return a query set of all page view restrictions that apply to this page | tuiuiu/tuiuiucore/models.py | get_view_restrictions | caputomarcos/tuiuiu.io | 3 | python | def get_view_restrictions(self):
return PageViewRestriction.objects.filter(page__in=self.get_ancestors(inclusive=True)) | def get_view_restrictions(self):
return PageViewRestriction.objects.filter(page__in=self.get_ancestors(inclusive=True))<|docstring|>Return a query set of all page view restrictions that apply to this page<|endoftext|> |
942c94e4ce2d10572efe85626a8e8796123ba27dc12436d1ecfbd53c0fcf69a8 | def serve_password_required_response(self, request, form, action_url):
'\n Serve a response indicating that the user has been denied access to view this page,\n and must supply a password.\n form = a Django form object containing the password input\n (and zero or more hidden fields t... | Serve a response indicating that the user has been denied access to view this page,
and must supply a password.
form = a Django form object containing the password input
(and zero or more hidden fields that also need to be output on the template)
action_url = URL that this form should be POSTed to | tuiuiu/tuiuiucore/models.py | serve_password_required_response | caputomarcos/tuiuiu.io | 3 | python | def serve_password_required_response(self, request, form, action_url):
'\n Serve a response indicating that the user has been denied access to view this page,\n and must supply a password.\n form = a Django form object containing the password input\n (and zero or more hidden fields t... | def serve_password_required_response(self, request, form, action_url):
'\n Serve a response indicating that the user has been denied access to view this page,\n and must supply a password.\n form = a Django form object containing the password input\n (and zero or more hidden fields t... |
9c33291298f482fd3d06e05ce5b14a00e0f372d15bca52a2a8742b35e24bf5af | def revisions_for_moderation(self):
'Return a queryset of page revisions awaiting moderation that this user has publish permission on'
if (not self.user.is_active):
return PageRevision.objects.none()
if self.user.is_superuser:
return PageRevision.submitted_revisions.all()
publishable_pag... | Return a queryset of page revisions awaiting moderation that this user has publish permission on | tuiuiu/tuiuiucore/models.py | revisions_for_moderation | caputomarcos/tuiuiu.io | 3 | python | def revisions_for_moderation(self):
if (not self.user.is_active):
return PageRevision.objects.none()
if self.user.is_superuser:
return PageRevision.submitted_revisions.all()
publishable_pages = [perm.page for perm in self.permissions if (perm.permission_type == 'publish')]
if (not p... | def revisions_for_moderation(self):
if (not self.user.is_active):
return PageRevision.objects.none()
if self.user.is_superuser:
return PageRevision.submitted_revisions.all()
publishable_pages = [perm.page for perm in self.permissions if (perm.permission_type == 'publish')]
if (not p... |
ae3f6e9c5c8371294297e5e72d7e41b2c7e7ef582259d73fdcb58b633fb77a68 | def for_page(self, page):
'Return a PagePermissionTester object that can be used to query whether this user has\n permission to perform specific tasks on the given page'
return PagePermissionTester(self, page) | Return a PagePermissionTester object that can be used to query whether this user has
permission to perform specific tasks on the given page | tuiuiu/tuiuiucore/models.py | for_page | caputomarcos/tuiuiu.io | 3 | python | def for_page(self, page):
'Return a PagePermissionTester object that can be used to query whether this user has\n permission to perform specific tasks on the given page'
return PagePermissionTester(self, page) | def for_page(self, page):
'Return a PagePermissionTester object that can be used to query whether this user has\n permission to perform specific tasks on the given page'
return PagePermissionTester(self, page)<|docstring|>Return a PagePermissionTester object that can be used to query whether this user ha... |
5fc09fc38f51e2fc3f2801eff3e4082f849a06fefb2ec46a5958aebae4e501b4 | def editable_pages(self):
'Return a queryset of the pages that this user has permission to edit'
if (not self.user.is_active):
return Page.objects.none()
if self.user.is_superuser:
return Page.objects.all()
editable_pages = Page.objects.none()
for perm in self.permissions.filter(perm... | Return a queryset of the pages that this user has permission to edit | tuiuiu/tuiuiucore/models.py | editable_pages | caputomarcos/tuiuiu.io | 3 | python | def editable_pages(self):
if (not self.user.is_active):
return Page.objects.none()
if self.user.is_superuser:
return Page.objects.all()
editable_pages = Page.objects.none()
for perm in self.permissions.filter(permission_type='add'):
editable_pages |= Page.objects.descendant_... | def editable_pages(self):
if (not self.user.is_active):
return Page.objects.none()
if self.user.is_superuser:
return Page.objects.all()
editable_pages = Page.objects.none()
for perm in self.permissions.filter(permission_type='add'):
editable_pages |= Page.objects.descendant_... |
dd7db3644bbbc2e59c4da9360dae293cdc980f497b213ef5aa7eb7e9cd317b1a | def can_edit_pages(self):
'Return True if the user has permission to edit any pages'
return self.editable_pages().exists() | Return True if the user has permission to edit any pages | tuiuiu/tuiuiucore/models.py | can_edit_pages | caputomarcos/tuiuiu.io | 3 | python | def can_edit_pages(self):
return self.editable_pages().exists() | def can_edit_pages(self):
return self.editable_pages().exists()<|docstring|>Return True if the user has permission to edit any pages<|endoftext|> |
db73caf180ee38cec797420b0662c82e0ff229826489f77c5d414d083ddbded4 | def publishable_pages(self):
'Return a queryset of the pages that this user has permission to publish'
if (not self.user.is_active):
return Page.objects.none()
if self.user.is_superuser:
return Page.objects.all()
publishable_pages = Page.objects.none()
for perm in self.permissions.fi... | Return a queryset of the pages that this user has permission to publish | tuiuiu/tuiuiucore/models.py | publishable_pages | caputomarcos/tuiuiu.io | 3 | python | def publishable_pages(self):
if (not self.user.is_active):
return Page.objects.none()
if self.user.is_superuser:
return Page.objects.all()
publishable_pages = Page.objects.none()
for perm in self.permissions.filter(permission_type='publish'):
publishable_pages |= Page.object... | def publishable_pages(self):
if (not self.user.is_active):
return Page.objects.none()
if self.user.is_superuser:
return Page.objects.all()
publishable_pages = Page.objects.none()
for perm in self.permissions.filter(permission_type='publish'):
publishable_pages |= Page.object... |
0923379df0196b9006c00f42ee8191c8ae168da272f568dc633ee483ff5fe438 | def can_publish_pages(self):
'Return True if the user has permission to publish any pages'
return self.publishable_pages().exists() | Return True if the user has permission to publish any pages | tuiuiu/tuiuiucore/models.py | can_publish_pages | caputomarcos/tuiuiu.io | 3 | python | def can_publish_pages(self):
return self.publishable_pages().exists() | def can_publish_pages(self):
return self.publishable_pages().exists()<|docstring|>Return True if the user has permission to publish any pages<|endoftext|> |
5a478196b19cb4cb1fc38e591d60eb473c898bdb29b15d5287a0abbd72fb49ed | def can_publish_subpage(self):
'\n Niggly special case for creating and publishing a page in one go.\n Differs from can_publish in that we want to be able to publish subpages of root, but not\n to be able to publish root itself. (Also, can_publish_subpage returns false if the page\n does... | Niggly special case for creating and publishing a page in one go.
Differs from can_publish in that we want to be able to publish subpages of root, but not
to be able to publish root itself. (Also, can_publish_subpage returns false if the page
does not allow subpages at all.) | tuiuiu/tuiuiucore/models.py | can_publish_subpage | caputomarcos/tuiuiu.io | 3 | python | def can_publish_subpage(self):
'\n Niggly special case for creating and publishing a page in one go.\n Differs from can_publish in that we want to be able to publish subpages of root, but not\n to be able to publish root itself. (Also, can_publish_subpage returns false if the page\n does... | def can_publish_subpage(self):
'\n Niggly special case for creating and publishing a page in one go.\n Differs from can_publish in that we want to be able to publish subpages of root, but not\n to be able to publish root itself. (Also, can_publish_subpage returns false if the page\n does... |
d3b218bdfc90e87688887296fe29c026bdb2497e32b566915068bd5dc74a110b | def can_reorder_children(self):
'\n Keep reorder permissions the same as publishing, since it immediately affects published pages\n (and the use-cases for a non-admin needing to do it are fairly obscure...)\n '
return self.can_publish_subpage() | Keep reorder permissions the same as publishing, since it immediately affects published pages
(and the use-cases for a non-admin needing to do it are fairly obscure...) | tuiuiu/tuiuiucore/models.py | can_reorder_children | caputomarcos/tuiuiu.io | 3 | python | def can_reorder_children(self):
'\n Keep reorder permissions the same as publishing, since it immediately affects published pages\n (and the use-cases for a non-admin needing to do it are fairly obscure...)\n '
return self.can_publish_subpage() | def can_reorder_children(self):
'\n Keep reorder permissions the same as publishing, since it immediately affects published pages\n (and the use-cases for a non-admin needing to do it are fairly obscure...)\n '
return self.can_publish_subpage()<|docstring|>Keep reorder permissions the same ... |
d8f4339188e701f10abccc51c5dc4333c73928df9c27d73f4f0491d84b38c350 | def can_move(self):
"\n Moving a page should be logically equivalent to deleting and re-adding it (and all its children).\n As such, the permission test for 'can this be moved at all?' should be the same as for deletion.\n (Further constraints will then apply on where it can be moved *to*.)\n ... | Moving a page should be logically equivalent to deleting and re-adding it (and all its children).
As such, the permission test for 'can this be moved at all?' should be the same as for deletion.
(Further constraints will then apply on where it can be moved *to*.) | tuiuiu/tuiuiucore/models.py | can_move | caputomarcos/tuiuiu.io | 3 | python | def can_move(self):
"\n Moving a page should be logically equivalent to deleting and re-adding it (and all its children).\n As such, the permission test for 'can this be moved at all?' should be the same as for deletion.\n (Further constraints will then apply on where it can be moved *to*.)\n ... | def can_move(self):
"\n Moving a page should be logically equivalent to deleting and re-adding it (and all its children).\n As such, the permission test for 'can this be moved at all?' should be the same as for deletion.\n (Further constraints will then apply on where it can be moved *to*.)\n ... |
4898fa91b5239be1cfcc9643a19050a9ba5455cb6fbb296cfbf762a921a76a29 | def mark_as_passed(self, request):
'\n Update the session data in the request to mark the user as having passed this\n view restriction\n '
has_existing_session = (settings.SESSION_COOKIE_NAME in request.COOKIES)
passed_restrictions = request.session.setdefault(self.passed_view_restrict... | Update the session data in the request to mark the user as having passed this
view restriction | tuiuiu/tuiuiucore/models.py | mark_as_passed | caputomarcos/tuiuiu.io | 3 | python | def mark_as_passed(self, request):
'\n Update the session data in the request to mark the user as having passed this\n view restriction\n '
has_existing_session = (settings.SESSION_COOKIE_NAME in request.COOKIES)
passed_restrictions = request.session.setdefault(self.passed_view_restrict... | def mark_as_passed(self, request):
'\n Update the session data in the request to mark the user as having passed this\n view restriction\n '
has_existing_session = (settings.SESSION_COOKIE_NAME in request.COOKIES)
passed_restrictions = request.session.setdefault(self.passed_view_restrict... |
4dbc6bb09e48a2cd7f653d2c69c66a8d18de2fcd7dfcd1cb07de759b70f4c3b2 | def get_view_restrictions(self):
'Return a query set of all collection view restrictions that apply to this collection'
return CollectionViewRestriction.objects.filter(collection__in=self.get_ancestors(inclusive=True)) | Return a query set of all collection view restrictions that apply to this collection | tuiuiu/tuiuiucore/models.py | get_view_restrictions | caputomarcos/tuiuiu.io | 3 | python | def get_view_restrictions(self):
return CollectionViewRestriction.objects.filter(collection__in=self.get_ancestors(inclusive=True)) | def get_view_restrictions(self):
return CollectionViewRestriction.objects.filter(collection__in=self.get_ancestors(inclusive=True))<|docstring|>Return a query set of all collection view restrictions that apply to this collection<|endoftext|> |
5af5cc319cd946815750cdd4da9d3e1919293cd597023e2d0399ae962ed65337 | def tktwine80kb(R=25):
'\n Evaluating the results of the following paper:\n Impossible Differential Cryptanalysis of Reduced-Round Tweakable TWINE [eprint-2020]\n ID attack on 25 rounds of T-TWIN-80 in which 22 subkey nibbles are involved. \n According to the authors\' claim, all of these 22 nibbles can... | Evaluating the results of the following paper:
Impossible Differential Cryptanalysis of Reduced-Round Tweakable TWINE [eprint-2020]
ID attack on 25 rounds of T-TWIN-80 in which 22 subkey nibbles are involved.
According to the authors' claim, all of these 22 nibbles can be deduced from 18 nibbles.
However using our to... | ciphers/T-TWINE/TWINE-80/tktwine80kb.py | tktwine80kb | letsdetermine/letsguess | 7 | python | def tktwine80kb(R=25):
'\n Evaluating the results of the following paper:\n Impossible Differential Cryptanalysis of Reduced-Round Tweakable TWINE [eprint-2020]\n ID attack on 25 rounds of T-TWIN-80 in which 22 subkey nibbles are involved. \n According to the authors\' claim, all of these 22 nibbles can... | def tktwine80kb(R=25):
'\n Evaluating the results of the following paper:\n Impossible Differential Cryptanalysis of Reduced-Round Tweakable TWINE [eprint-2020]\n ID attack on 25 rounds of T-TWIN-80 in which 22 subkey nibbles are involved. \n According to the authors\' claim, all of these 22 nibbles can... |
e118c17411430600df2e339449d570a27eb5b9432718b5d3287071c8e9866988 | def stan_hmc_warmup(kernel_factory, is_mass_matrix_diagonal: bool=True) -> Tuple[(Callable, Callable, Callable)]:
'Warmup scheme for sampling procedures based on euclidean manifold HMC.\n The schedule and algorithms used match Stan\'s [1]_ as closely as possible.\n\n Unlike several other libraries, we separat... | Warmup scheme for sampling procedures based on euclidean manifold HMC.
The schedule and algorithms used match Stan's [1]_ as closely as possible.
Unlike several other libraries, we separate the warmup and sampling phases
explicitly. This ensure a better modularity; a change in the warmup does
not affect the sampling. ... | mcx/inference/warmup/stan.py | stan_hmc_warmup | kancurochat/mcx | 1 | python | def stan_hmc_warmup(kernel_factory, is_mass_matrix_diagonal: bool=True) -> Tuple[(Callable, Callable, Callable)]:
'Warmup scheme for sampling procedures based on euclidean manifold HMC.\n The schedule and algorithms used match Stan\'s [1]_ as closely as possible.\n\n Unlike several other libraries, we separat... | def stan_hmc_warmup(kernel_factory, is_mass_matrix_diagonal: bool=True) -> Tuple[(Callable, Callable, Callable)]:
'Warmup scheme for sampling procedures based on euclidean manifold HMC.\n The schedule and algorithms used match Stan\'s [1]_ as closely as possible.\n\n Unlike several other libraries, we separat... |
faf59a303c7a832636302613033d5a741095672de24920e06a1df7b6d399f1c4 | def stan_first_stage() -> Tuple[(Callable, Callable)]:
"First stage of the Stan warmup. The step size is adapted using\n Nesterov's dual averaging algorithms while the mass matrix stays the same.\n\n Parameters\n ----------\n kernel_factory\n A function that takes the kernel's parameters as an in... | First stage of the Stan warmup. The step size is adapted using
Nesterov's dual averaging algorithms while the mass matrix stays the same.
Parameters
----------
kernel_factory
A function that takes the kernel's parameters as an input
and returns the corresponding transition kernel.
Returns
-------
A tuple of f... | mcx/inference/warmup/stan.py | stan_first_stage | kancurochat/mcx | 1 | python | def stan_first_stage() -> Tuple[(Callable, Callable)]:
"First stage of the Stan warmup. The step size is adapted using\n Nesterov's dual averaging algorithms while the mass matrix stays the same.\n\n Parameters\n ----------\n kernel_factory\n A function that takes the kernel's parameters as an in... | def stan_first_stage() -> Tuple[(Callable, Callable)]:
"First stage of the Stan warmup. The step size is adapted using\n Nesterov's dual averaging algorithms while the mass matrix stays the same.\n\n Parameters\n ----------\n kernel_factory\n A function that takes the kernel's parameters as an in... |
0759c0f7e1bed77a513717629a616c18d455a28191cad4570949b0445294a3c1 | def stan_second_stage(is_mass_matrix_diagonal: bool=True) -> Tuple[(Callable, Callable, Callable)]:
'Slow stage of the Stan warmup.\n\n In this stage we adapt the values of the mass matrix. The step size and the\n state of the mass matrix adaptation are re-initialized at the end of each\n window.\n\n Pa... | Slow stage of the Stan warmup.
In this stage we adapt the values of the mass matrix. The step size and the
state of the mass matrix adaptation are re-initialized at the end of each
window.
Parameters
----------
is_mass_matrix_diagonal
Whether we want a diagonal mass matrix. Passed to the mass matrix adapation
... | mcx/inference/warmup/stan.py | stan_second_stage | kancurochat/mcx | 1 | python | def stan_second_stage(is_mass_matrix_diagonal: bool=True) -> Tuple[(Callable, Callable, Callable)]:
'Slow stage of the Stan warmup.\n\n In this stage we adapt the values of the mass matrix. The step size and the\n state of the mass matrix adaptation are re-initialized at the end of each\n window.\n\n Pa... | def stan_second_stage(is_mass_matrix_diagonal: bool=True) -> Tuple[(Callable, Callable, Callable)]:
'Slow stage of the Stan warmup.\n\n In this stage we adapt the values of the mass matrix. The step size and the\n state of the mass matrix adaptation are re-initialized at the end of each\n window.\n\n Pa... |
80beeb1e33e8d18f076950b3fd44d758c636e5df79ca605b95a028ea91a1f7ce | def stan_warmup_schedule(num_steps: int, initial_buffer_size: int=75, final_buffer_size: int=50, first_window_size: int=25) -> List[Tuple[(int, bool)]]:
'Return the schedule for Stan\'s warmup.\n\n The schedule below is intended to be as close as possible to Stan\'s _[1].\n The warmup period is split into thr... | Return the schedule for Stan's warmup.
The schedule below is intended to be as close as possible to Stan's _[1].
The warmup period is split into three stages:
1. An initial fast interval to reach the typical set. Only the step size is
adapted in this window.
2. "Slow" parameters that require global information (typic... | mcx/inference/warmup/stan.py | stan_warmup_schedule | kancurochat/mcx | 1 | python | def stan_warmup_schedule(num_steps: int, initial_buffer_size: int=75, final_buffer_size: int=50, first_window_size: int=25) -> List[Tuple[(int, bool)]]:
'Return the schedule for Stan\'s warmup.\n\n The schedule below is intended to be as close as possible to Stan\'s _[1].\n The warmup period is split into thr... | def stan_warmup_schedule(num_steps: int, initial_buffer_size: int=75, final_buffer_size: int=50, first_window_size: int=25) -> List[Tuple[(int, bool)]]:
'Return the schedule for Stan\'s warmup.\n\n The schedule below is intended to be as close as possible to Stan\'s _[1].\n The warmup period is split into thr... |
f79f383e351da3b2c57a5bb3f30fe2a6f8ad3a90230b5a9c6ecac79f398c9ca3 | def init(rng_key: jax.random.PRNGKey, initial_state: HMCState, initial_step_size: int) -> StanWarmupState:
'Initialize the warmup.\n\n To initialize the Stan warmup we create an identity mass matrix and use\n the `find_reasonable_step_size` procedure to initialize the dual\n averaging algorithm... | Initialize the warmup.
To initialize the Stan warmup we create an identity mass matrix and use
the `find_reasonable_step_size` procedure to initialize the dual
averaging algorithm. | mcx/inference/warmup/stan.py | init | kancurochat/mcx | 1 | python | def init(rng_key: jax.random.PRNGKey, initial_state: HMCState, initial_step_size: int) -> StanWarmupState:
'Initialize the warmup.\n\n To initialize the Stan warmup we create an identity mass matrix and use\n the `find_reasonable_step_size` procedure to initialize the dual\n averaging algorithm... | def init(rng_key: jax.random.PRNGKey, initial_state: HMCState, initial_step_size: int) -> StanWarmupState:
'Initialize the warmup.\n\n To initialize the Stan warmup we create an identity mass matrix and use\n the `find_reasonable_step_size` procedure to initialize the dual\n averaging algorithm... |
1ccb39890e604eec02a6c4b39607ffbb76edc8500048aebab0d51c20434db034 | @jax.jit
def update(rng_key: jax.random.PRNGKey, stage: int, is_middle_window_end: bool, chain_state: HMCState, warmup_state: StanWarmupState) -> Tuple[(HMCState, StanWarmupState, HMCInfo)]:
"Move the warmup by one step.\n\n We first create a new kernel with the current values of the step size\n and m... | Move the warmup by one step.
We first create a new kernel with the current values of the step size
and mass matrix and move the chain one step. Then, depending on the
stage passed as an argument we execute either the fast or slow interval
update. Finally we execute the final update of the slow interval depending
on wh... | mcx/inference/warmup/stan.py | update | kancurochat/mcx | 1 | python | @jax.jit
def update(rng_key: jax.random.PRNGKey, stage: int, is_middle_window_end: bool, chain_state: HMCState, warmup_state: StanWarmupState) -> Tuple[(HMCState, StanWarmupState, HMCInfo)]:
"Move the warmup by one step.\n\n We first create a new kernel with the current values of the step size\n and m... | @jax.jit
def update(rng_key: jax.random.PRNGKey, stage: int, is_middle_window_end: bool, chain_state: HMCState, warmup_state: StanWarmupState) -> Tuple[(HMCState, StanWarmupState, HMCInfo)]:
"Move the warmup by one step.\n\n We first create a new kernel with the current values of the step size\n and m... |
164829f4ee94a80e4a4488e261c513c1a9d78ecebebe4085af4f76147d4b4237 | def final(warmup_state: StanWarmupState) -> Tuple[(float, np.DeviceArray)]:
'Return the step size and mass matrix.'
step_size = np.exp(warmup_state.da_state.log_step_size_avg)
inverse_mass_matrix = warmup_state.mm_state.inverse_mass_matrix
return (step_size, inverse_mass_matrix) | Return the step size and mass matrix. | mcx/inference/warmup/stan.py | final | kancurochat/mcx | 1 | python | def final(warmup_state: StanWarmupState) -> Tuple[(float, np.DeviceArray)]:
step_size = np.exp(warmup_state.da_state.log_step_size_avg)
inverse_mass_matrix = warmup_state.mm_state.inverse_mass_matrix
return (step_size, inverse_mass_matrix) | def final(warmup_state: StanWarmupState) -> Tuple[(float, np.DeviceArray)]:
step_size = np.exp(warmup_state.da_state.log_step_size_avg)
inverse_mass_matrix = warmup_state.mm_state.inverse_mass_matrix
return (step_size, inverse_mass_matrix)<|docstring|>Return the step size and mass matrix.<|endoftext|> |
fc16776f60529271bef9bc1a94d23611c675a70579df73b97c00515b18ca8a4f | def init(chain_state: HMCState) -> MassMatrixAdaptationState:
'Initialize the mass matrix adaptation algorithm.'
n_dims = np.shape(chain_state.position)[(- 1)]
mm_state = mm_init(n_dims)
return mm_state | Initialize the mass matrix adaptation algorithm. | mcx/inference/warmup/stan.py | init | kancurochat/mcx | 1 | python | def init(chain_state: HMCState) -> MassMatrixAdaptationState:
n_dims = np.shape(chain_state.position)[(- 1)]
mm_state = mm_init(n_dims)
return mm_state | def init(chain_state: HMCState) -> MassMatrixAdaptationState:
n_dims = np.shape(chain_state.position)[(- 1)]
mm_state = mm_init(n_dims)
return mm_state<|docstring|>Initialize the mass matrix adaptation algorithm.<|endoftext|> |
f474f965c92d4ca9720042529ca55e0a9fcd452ef7bb98c38bf88d0aae5a54b9 | @jax.jit
def update(state: Tuple[(jax.random.PRNGKey, HMCState, HMCInfo, StanWarmupState)]) -> StanWarmupState:
"Move the warmup by one state when in a slow adaptation interval.\n\n Mass matrix adaptation and dual averaging states are both\n adapted in slow adaptation intervals, as indicated in Stan's... | Move the warmup by one state when in a slow adaptation interval.
Mass matrix adaptation and dual averaging states are both
adapted in slow adaptation intervals, as indicated in Stan's
reference manual. | mcx/inference/warmup/stan.py | update | kancurochat/mcx | 1 | python | @jax.jit
def update(state: Tuple[(jax.random.PRNGKey, HMCState, HMCInfo, StanWarmupState)]) -> StanWarmupState:
"Move the warmup by one state when in a slow adaptation interval.\n\n Mass matrix adaptation and dual averaging states are both\n adapted in slow adaptation intervals, as indicated in Stan's... | @jax.jit
def update(state: Tuple[(jax.random.PRNGKey, HMCState, HMCInfo, StanWarmupState)]) -> StanWarmupState:
"Move the warmup by one state when in a slow adaptation interval.\n\n Mass matrix adaptation and dual averaging states are both\n adapted in slow adaptation intervals, as indicated in Stan's... |
7f1a03bc993f32eea980f7901c5d2f187b9fdb41f8ecf52b1ab4ef82a3362cc1 | @jax.jit
def final(warmup_state: StanWarmupState) -> StanWarmupState:
'Update the parameters at the end of a slow adaptation window.\n\n We compute the value of the mass matrix and reset the mass matrix\n adapation\'s internal state since middle windows are "memoryless".\n\n '
new_mm_state ... | Update the parameters at the end of a slow adaptation window.
We compute the value of the mass matrix and reset the mass matrix
adapation's internal state since middle windows are "memoryless". | mcx/inference/warmup/stan.py | final | kancurochat/mcx | 1 | python | @jax.jit
def final(warmup_state: StanWarmupState) -> StanWarmupState:
'Update the parameters at the end of a slow adaptation window.\n\n We compute the value of the mass matrix and reset the mass matrix\n adapation\'s internal state since middle windows are "memoryless".\n\n '
new_mm_state ... | @jax.jit
def final(warmup_state: StanWarmupState) -> StanWarmupState:
'Update the parameters at the end of a slow adaptation window.\n\n We compute the value of the mass matrix and reset the mass matrix\n adapation\'s internal state since middle windows are "memoryless".\n\n '
new_mm_state ... |
2c04350a92d75b7d0df6437733484dbc0bffd79d22939f7ca5206a0a7ba27ff8 | @run.run.command()
@click.argument('files', type=click.File(mode='rb'), nargs=(- 1), required=True)
@click.pass_context
def ios_ipa(ctx: click.core.Context, files: List[io.FileIO]) -> None:
'Run scan for .IPA package file.'
runtime = ctx.obj['runtime']
assets = []
for f in files:
assets.append(i... | Run scan for .IPA package file. | src/ostorlab/cli/scan/run/assets/ios_ipa.py | ios_ipa | bbhunter/ostorlab | 113 | python | @run.run.command()
@click.argument('files', type=click.File(mode='rb'), nargs=(- 1), required=True)
@click.pass_context
def ios_ipa(ctx: click.core.Context, files: List[io.FileIO]) -> None:
runtime = ctx.obj['runtime']
assets = []
for f in files:
assets.append(ios_ipa_asset.IOSIpa(content=f.rea... | @run.run.command()
@click.argument('files', type=click.File(mode='rb'), nargs=(- 1), required=True)
@click.pass_context
def ios_ipa(ctx: click.core.Context, files: List[io.FileIO]) -> None:
runtime = ctx.obj['runtime']
assets = []
for f in files:
assets.append(ios_ipa_asset.IOSIpa(content=f.rea... |
6cb7dd2c2a342fda9f64fedd8a4db96cd4ee8070a25b692f63a70c7b2ee53aba | def parse_port_pin(name_str):
'Parses a string and returns a (port-num, pin-num) tuple.'
if (len(name_str) < 4):
raise ValueError('Expecting pin name to be at least 5 charcters.')
if (name_str[0] != 'P'):
raise ValueError('Expecting pin name to start with P')
if (name_str[1] not in ('0',... | Parses a string and returns a (port-num, pin-num) tuple. | ports/nrf/boards/make-pins.py | parse_port_pin | DEVESHTARASIA/circuitpython | 1 | python | def parse_port_pin(name_str):
if (len(name_str) < 4):
raise ValueError('Expecting pin name to be at least 5 charcters.')
if (name_str[0] != 'P'):
raise ValueError('Expecting pin name to start with P')
if (name_str[1] not in ('0', '1')):
raise ValueError('Expecting pin port to be... | def parse_port_pin(name_str):
if (len(name_str) < 4):
raise ValueError('Expecting pin name to be at least 5 charcters.')
if (name_str[0] != 'P'):
raise ValueError('Expecting pin name to start with P')
if (name_str[1] not in ('0', '1')):
raise ValueError('Expecting pin port to be... |
cba1fc87cc5be80df0955ba07a52f9549ebf820b62f058947ee8dd46a2ab4ef9 | @staticmethod
def strempty(mstr: Optional[str]) -> bool:
'\n strempty\n\n Args:\n mstr (Optional[str]): str\n\n Returns:\n bool\n '
return ((mstr is None) or (mstr == '')) | strempty
Args:
mstr (Optional[str]): str
Returns:
bool | core/commons/utils.py | strempty | bopopescu/sdba | 2 | python | @staticmethod
def strempty(mstr: Optional[str]) -> bool:
'\n strempty\n\n Args:\n mstr (Optional[str]): str\n\n Returns:\n bool\n '
return ((mstr is None) or (mstr == )) | @staticmethod
def strempty(mstr: Optional[str]) -> bool:
'\n strempty\n\n Args:\n mstr (Optional[str]): str\n\n Returns:\n bool\n '
return ((mstr is None) or (mstr == ))<|docstring|>strempty
Args:
mstr (Optional[str]): str
Returns:
bool<|endoftext|> |
5f4599781f695a01feeeb91ea4b2db3fcdba2b049359cb8fb3a693edfe73164c | @staticmethod
def list_to_str_lit(elements: List[Any]) -> List[str]:
'\n list_to_str_lit\n\n Args:\n elements (List[Any]): -\n\n Returns:\n List[str]: list\n '
return list(map((lambda x: x.__str__()), elements)) | list_to_str_lit
Args:
elements (List[Any]): -
Returns:
List[str]: list | core/commons/utils.py | list_to_str_lit | bopopescu/sdba | 2 | python | @staticmethod
def list_to_str_lit(elements: List[Any]) -> List[str]:
'\n list_to_str_lit\n\n Args:\n elements (List[Any]): -\n\n Returns:\n List[str]: list\n '
return list(map((lambda x: x.__str__()), elements)) | @staticmethod
def list_to_str_lit(elements: List[Any]) -> List[str]:
'\n list_to_str_lit\n\n Args:\n elements (List[Any]): -\n\n Returns:\n List[str]: list\n '
return list(map((lambda x: x.__str__()), elements))<|docstring|>list_to_str_lit
Args:
elements (L... |
e62926a5b426cb98a094478274ad17469a2576256d45de8395ef26939fadf33b | @staticmethod
def dict_of_dicts_merge(x: Dict[(Any, Any)], y: Dict[(Any, Any)]) -> Dict[(Any, Any)]:
'\n dict_of_dicts_merge\n\n Args:\n x (Dict[Any, Any]): -\n y (Dict[Any, Any]): -\n\n Returns:\n Dict[Any, Any]: dict\n '
return {**x, **y} | dict_of_dicts_merge
Args:
x (Dict[Any, Any]): -
y (Dict[Any, Any]): -
Returns:
Dict[Any, Any]: dict | core/commons/utils.py | dict_of_dicts_merge | bopopescu/sdba | 2 | python | @staticmethod
def dict_of_dicts_merge(x: Dict[(Any, Any)], y: Dict[(Any, Any)]) -> Dict[(Any, Any)]:
'\n dict_of_dicts_merge\n\n Args:\n x (Dict[Any, Any]): -\n y (Dict[Any, Any]): -\n\n Returns:\n Dict[Any, Any]: dict\n '
return {**x, **y} | @staticmethod
def dict_of_dicts_merge(x: Dict[(Any, Any)], y: Dict[(Any, Any)]) -> Dict[(Any, Any)]:
'\n dict_of_dicts_merge\n\n Args:\n x (Dict[Any, Any]): -\n y (Dict[Any, Any]): -\n\n Returns:\n Dict[Any, Any]: dict\n '
return {**x, **y}<|docstring... |
e0904d0a14051213ccce7ba44a61e11125f8dbbe597bdf904d97c2ec9ced4f98 | @staticmethod
def filter_empty(elements: List[str]) -> List[str]:
'\n filter_empty\n\n Args:\n elements (List[str]): -\n\n Returns:\n List[str]: list\n '
return list(filter((lambda x: (x != '')), elements)) | filter_empty
Args:
elements (List[str]): -
Returns:
List[str]: list | core/commons/utils.py | filter_empty | bopopescu/sdba | 2 | python | @staticmethod
def filter_empty(elements: List[str]) -> List[str]:
'\n filter_empty\n\n Args:\n elements (List[str]): -\n\n Returns:\n List[str]: list\n '
return list(filter((lambda x: (x != )), elements)) | @staticmethod
def filter_empty(elements: List[str]) -> List[str]:
'\n filter_empty\n\n Args:\n elements (List[str]): -\n\n Returns:\n List[str]: list\n '
return list(filter((lambda x: (x != )), elements))<|docstring|>filter_empty
Args:
elements (List[str]):... |
85e1cf1f652ffa25beb2d8a1b9b6412b8abd858a1ef4776a7233be8196c364a1 | @staticmethod
def dict_to_json(dict_obj: Dict[(str, Any)]) -> str:
'\n dict_to_json\n\n Args:\n dict_obj (Dict[str, Any]): -\n\n Returns:\n str\n '
return json.dumps(dict_obj, default=str) | dict_to_json
Args:
dict_obj (Dict[str, Any]): -
Returns:
str | core/commons/utils.py | dict_to_json | bopopescu/sdba | 2 | python | @staticmethod
def dict_to_json(dict_obj: Dict[(str, Any)]) -> str:
'\n dict_to_json\n\n Args:\n dict_obj (Dict[str, Any]): -\n\n Returns:\n str\n '
return json.dumps(dict_obj, default=str) | @staticmethod
def dict_to_json(dict_obj: Dict[(str, Any)]) -> str:
'\n dict_to_json\n\n Args:\n dict_obj (Dict[str, Any]): -\n\n Returns:\n str\n '
return json.dumps(dict_obj, default=str)<|docstring|>dict_to_json
Args:
dict_obj (Dict[str, Any]): -
Returns... |
4efe8661b19fa64174c5e0a99c9a48cff90ad6ec4028dc6133ab625fd8dffbe4 | @staticmethod
def clear_breaks(mstr: Union[(str, List[str])], charlist: str='[\n\t\r]+') -> Union[(str, List[str])]:
'\n clear_breaks\n\n Args:\n mstr (Union[str, List[str]]): -\n charlist (str): -\n\n Returns:\n Union[str, List[str]]: list or str\n '
... | clear_breaks
Args:
mstr (Union[str, List[str]]): -
charlist (str): -
Returns:
Union[str, List[str]]: list or str | core/commons/utils.py | clear_breaks | bopopescu/sdba | 2 | python | @staticmethod
def clear_breaks(mstr: Union[(str, List[str])], charlist: str='[\n\t\r]+') -> Union[(str, List[str])]:
'\n clear_breaks\n\n Args:\n mstr (Union[str, List[str]]): -\n charlist (str): -\n\n Returns:\n Union[str, List[str]]: list or str\n '
... | @staticmethod
def clear_breaks(mstr: Union[(str, List[str])], charlist: str='[\n\t\r]+') -> Union[(str, List[str])]:
'\n clear_breaks\n\n Args:\n mstr (Union[str, List[str]]): -\n charlist (str): -\n\n Returns:\n Union[str, List[str]]: list or str\n '
... |
90d2eba007a69a391593c9e9c03c66ba5e300d44c367b1207ea19782205a77ba | def __test_float(self, bk, **ftc_opts):
' Test float index fetching for a given backend '
for arg in self.args['float']:
options = {**self.fetcher_opts, **ftc_opts}
f = ArgoIndexFetcher(src=bk, **options).float(arg)
assert isinstance(f.to_xarray(), xr.Dataset) | Test float index fetching for a given backend | argopy/tests/test_fetchers_facade_index.py | __test_float | ocefpaf/argopy | 0 | python | def __test_float(self, bk, **ftc_opts):
' '
for arg in self.args['float']:
options = {**self.fetcher_opts, **ftc_opts}
f = ArgoIndexFetcher(src=bk, **options).float(arg)
assert isinstance(f.to_xarray(), xr.Dataset) | def __test_float(self, bk, **ftc_opts):
' '
for arg in self.args['float']:
options = {**self.fetcher_opts, **ftc_opts}
f = ArgoIndexFetcher(src=bk, **options).float(arg)
assert isinstance(f.to_xarray(), xr.Dataset)<|docstring|>Test float index fetching for a given backend<|endoftext|> |
c2a09c57e956eb8f44652b2fcebfa666a6b6ee2f52be8c2023b2e018cd3a8adf | def __test_profile(self, bk, **ftc_opts):
' Test profile index fetching for a given backend '
for arg in self.args['profile']:
options = {**self.fetcher_opts, **ftc_opts}
f = ArgoIndexFetcher(src=bk, **options).profile(*arg)
assert isinstance(f.to_xarray(), xr.Dataset) | Test profile index fetching for a given backend | argopy/tests/test_fetchers_facade_index.py | __test_profile | ocefpaf/argopy | 0 | python | def __test_profile(self, bk, **ftc_opts):
' '
for arg in self.args['profile']:
options = {**self.fetcher_opts, **ftc_opts}
f = ArgoIndexFetcher(src=bk, **options).profile(*arg)
assert isinstance(f.to_xarray(), xr.Dataset) | def __test_profile(self, bk, **ftc_opts):
' '
for arg in self.args['profile']:
options = {**self.fetcher_opts, **ftc_opts}
f = ArgoIndexFetcher(src=bk, **options).profile(*arg)
assert isinstance(f.to_xarray(), xr.Dataset)<|docstring|>Test profile index fetching for a given backend<|endo... |
d1c37bab831374d5bd4f06fec6023b97c716a48d874aa804e89c32413201febd | def __test_region(self, bk, **ftc_opts):
' Test float index fetching for a given backend '
for arg in self.args['region']:
options = {**self.fetcher_opts, **ftc_opts}
f = ArgoIndexFetcher(src=bk, **options).region(arg)
assert isinstance(f.to_xarray(), xr.Dataset) | Test float index fetching for a given backend | argopy/tests/test_fetchers_facade_index.py | __test_region | ocefpaf/argopy | 0 | python | def __test_region(self, bk, **ftc_opts):
' '
for arg in self.args['region']:
options = {**self.fetcher_opts, **ftc_opts}
f = ArgoIndexFetcher(src=bk, **options).region(arg)
assert isinstance(f.to_xarray(), xr.Dataset) | def __test_region(self, bk, **ftc_opts):
' '
for arg in self.args['region']:
options = {**self.fetcher_opts, **ftc_opts}
f = ArgoIndexFetcher(src=bk, **options).region(arg)
assert isinstance(f.to_xarray(), xr.Dataset)<|docstring|>Test float index fetching for a given backend<|endoftext|... |
cfeb7f4ac3dd3c71891238163df3ebe67d3bc8fe3a7fdb9fcdfa87fa5d990e66 | def Instance(self):
' This function has been arbitrarily put into the stubs'
return TreeNodeMouseClickEventArgs() | This function has been arbitrarily put into the stubs | release/stubs.min/System/Windows/Forms/__init___parts/TreeNodeMouseClickEventArgs.py | Instance | tranconbv/ironpython-stubs | 0 | python | def Instance(self):
' '
return TreeNodeMouseClickEventArgs() | def Instance(self):
' '
return TreeNodeMouseClickEventArgs()<|docstring|>This function has been arbitrarily put into the stubs<|endoftext|> |
b38d34d1c88540c910763718c4e736604b07b6fd3af4407c7ecc720587fcfd7a | @staticmethod
def __new__(self, node, button, clicks, x, y):
' __new__(cls: type,node: TreeNode,button: MouseButtons,clicks: int,x: int,y: int) '
pass | __new__(cls: type,node: TreeNode,button: MouseButtons,clicks: int,x: int,y: int) | release/stubs.min/System/Windows/Forms/__init___parts/TreeNodeMouseClickEventArgs.py | __new__ | tranconbv/ironpython-stubs | 0 | python | @staticmethod
def __new__(self, node, button, clicks, x, y):
' '
pass | @staticmethod
def __new__(self, node, button, clicks, x, y):
' '
pass<|docstring|>__new__(cls: type,node: TreeNode,button: MouseButtons,clicks: int,x: int,y: int)<|endoftext|> |
dc5c0ee3251b412fcbe930c249a85f705f33687a26e1280d8f03c3ca2caa7d81 | def create_network(name, *args, **kwargs):
'\n Create tinybert network.\n '
if (name == 'ternarybert'):
if ('seq_length' in kwargs):
tinybert_student_net_cfg.seq_length = kwargs['seq_length']
is_training = kwargs.get('is_training', False)
return BertModel(tinybert_stude... | Create tinybert network. | model_zoo/research/nlp/ternarybert/mindspore_hub_conf.py | create_network | limberc/mindspore | 4 | python | def create_network(name, *args, **kwargs):
'\n \n '
if (name == 'ternarybert'):
if ('seq_length' in kwargs):
tinybert_student_net_cfg.seq_length = kwargs['seq_length']
is_training = kwargs.get('is_training', False)
return BertModel(tinybert_student_net_cfg, is_training,... | def create_network(name, *args, **kwargs):
'\n \n '
if (name == 'ternarybert'):
if ('seq_length' in kwargs):
tinybert_student_net_cfg.seq_length = kwargs['seq_length']
is_training = kwargs.get('is_training', False)
return BertModel(tinybert_student_net_cfg, is_training,... |
78fd81ea1485ad2074bad766f2453461b859927b16e800c39d05a48f19f26b8b | def create(self, req, body):
'Creates a new snapshot.'
context = req.environ['nova.context']
authorize(context, action='create')
if (not self.is_valid_body(body, 'snapshot')):
raise webob.exc.HTTPBadRequest()
try:
snapshot = body['snapshot']
create_info = snapshot['create_inf... | Creates a new snapshot. | nova/api/openstack/compute/contrib/assisted_volume_snapshots.py | create | Metaswitch/calico-nova | 7 | python | def create(self, req, body):
context = req.environ['nova.context']
authorize(context, action='create')
if (not self.is_valid_body(body, 'snapshot')):
raise webob.exc.HTTPBadRequest()
try:
snapshot = body['snapshot']
create_info = snapshot['create_info']
volume_id = s... | def create(self, req, body):
context = req.environ['nova.context']
authorize(context, action='create')
if (not self.is_valid_body(body, 'snapshot')):
raise webob.exc.HTTPBadRequest()
try:
snapshot = body['snapshot']
create_info = snapshot['create_info']
volume_id = s... |
0f92cdc51dc0427b8a105f59f34e0807a46fc66eb6a7906750b30ba6569f8014 | def delete(self, req, id):
'Delete a snapshot.'
context = req.environ['nova.context']
authorize(context, action='delete')
LOG.audit(_('Delete snapshot with id: %s'), id, context=context)
delete_metadata = {}
delete_metadata.update(req.GET)
try:
delete_info = jsonutils.loads(delete_me... | Delete a snapshot. | nova/api/openstack/compute/contrib/assisted_volume_snapshots.py | delete | Metaswitch/calico-nova | 7 | python | def delete(self, req, id):
context = req.environ['nova.context']
authorize(context, action='delete')
LOG.audit(_('Delete snapshot with id: %s'), id, context=context)
delete_metadata = {}
delete_metadata.update(req.GET)
try:
delete_info = jsonutils.loads(delete_metadata['delete_info'... | def delete(self, req, id):
context = req.environ['nova.context']
authorize(context, action='delete')
LOG.audit(_('Delete snapshot with id: %s'), id, context=context)
delete_metadata = {}
delete_metadata.update(req.GET)
try:
delete_info = jsonutils.loads(delete_metadata['delete_info'... |
1f331ce9424bba5b6745232578e9665ab8b0e5b5b455842a920c7690d82f70ee | def checkJobs(self):
'\n Query all running jobs\n '
if (time.time() < (self.checktime + int(self.conf.get(['jobs', 'checkmintime'])))):
self.log.debug('mininterval not reached')
return
self.checktime = time.time()
query = (((("condorstate in ('submitted', 'running', 'cancel... | Query all running jobs | src/act/condor/aCTStatus.py | checkJobs | bryngemark/aCT | 0 | python | def checkJobs(self):
'\n \n '
if (time.time() < (self.checktime + int(self.conf.get(['jobs', 'checkmintime'])))):
self.log.debug('mininterval not reached')
return
self.checktime = time.time()
query = (((("condorstate in ('submitted', 'running', 'cancelling', 'holding') and ... | def checkJobs(self):
'\n \n '
if (time.time() < (self.checktime + int(self.conf.get(['jobs', 'checkmintime'])))):
self.log.debug('mininterval not reached')
return
self.checktime = time.time()
query = (((("condorstate in ('submitted', 'running', 'cancelling', 'holding') and ... |
67ebbd51cc9669e68f31ebd135c938ecfd1b9e9abc28e9c45362fcce026b3795 | def checkLostJobs(self):
'\n Move jobs with a long time since status update to lost\n '
jobs = self.dbcondor.getCondorJobsInfo(((("condorstate in ('submitted', 'running', 'cancelling', 'finished') and cluster='" + self.cluster) + "' and ") + self.dbcondor.timeStampLessThan('tcondorstate', 172800))... | Move jobs with a long time since status update to lost | src/act/condor/aCTStatus.py | checkLostJobs | bryngemark/aCT | 0 | python | def checkLostJobs(self):
'\n \n '
jobs = self.dbcondor.getCondorJobsInfo(((("condorstate in ('submitted', 'running', 'cancelling', 'finished') and cluster='" + self.cluster) + "' and ") + self.dbcondor.timeStampLessThan('tcondorstate', 172800)), ['id', 'appjobid', 'ClusterId', 'condorstate'])
... | def checkLostJobs(self):
'\n \n '
jobs = self.dbcondor.getCondorJobsInfo(((("condorstate in ('submitted', 'running', 'cancelling', 'finished') and cluster='" + self.cluster) + "' and ") + self.dbcondor.timeStampLessThan('tcondorstate', 172800)), ['id', 'appjobid', 'ClusterId', 'condorstate'])
... |
44a883177511a24154e63d0e67c9a3d79340cf71d8b294138f75139d2b576c83 | def checkStuckJobs(self):
'\n check jobs with tstate too long ago and set them tocancel\n maxtimestate can be set in arc config file for any condor JobStatus,\n e.g. maxtimeidle, maxtimerunning\n '
for (jobstateid, jobstate) in self.condorjobstatemap.items():
maxtime = self.c... | check jobs with tstate too long ago and set them tocancel
maxtimestate can be set in arc config file for any condor JobStatus,
e.g. maxtimeidle, maxtimerunning | src/act/condor/aCTStatus.py | checkStuckJobs | bryngemark/aCT | 0 | python | def checkStuckJobs(self):
'\n check jobs with tstate too long ago and set them tocancel\n maxtimestate can be set in arc config file for any condor JobStatus,\n e.g. maxtimeidle, maxtimerunning\n '
for (jobstateid, jobstate) in self.condorjobstatemap.items():
maxtime = self.c... | def checkStuckJobs(self):
'\n check jobs with tstate too long ago and set them tocancel\n maxtimestate can be set in arc config file for any condor JobStatus,\n e.g. maxtimeidle, maxtimerunning\n '
for (jobstateid, jobstate) in self.condorjobstatemap.items():
maxtime = self.c... |
b7f8e67e721fea85013cfb1d3d4280078d577e7d502818398e9bf8199a6fd896 | @pytest.fixture(scope='module', autouse=True)
def simulated_multi(request):
'Starts the simulated serial port for the unit tests. Assumes that `socat`\n has been initialized already to setup the virtual COM ports.\n '
from liveserial.simulator import ComSimulatorThread
from os import name
if (name... | Starts the simulated serial port for the unit tests. Assumes that `socat`
has been initialized already to setup the virtual COM ports. | tests/test_multi.py | simulated_multi | rosenbrockc/live-serial | 11 | python | @pytest.fixture(scope='module', autouse=True)
def simulated_multi(request):
'Starts the simulated serial port for the unit tests. Assumes that `socat`\n has been initialized already to setup the virtual COM ports.\n '
from liveserial.simulator import ComSimulatorThread
from os import name
if (name... | @pytest.fixture(scope='module', autouse=True)
def simulated_multi(request):
'Starts the simulated serial port for the unit tests. Assumes that `socat`\n has been initialized already to setup the virtual COM ports.\n '
from liveserial.simulator import ComSimulatorThread
from os import name
if (name... |
78f7e4b61b8a3237b6fb8f08498fa08badc9a4fc36c530e7484abb47eca816d2 | def test_multi_listen(isnt):
"Tests the explicit monitor setup using the 'multiple.cfg' file in the\n current directory.\n "
from os import path
if isnt:
argv = ['py.test', 'COM2', 'COM4', '-virtual', '-listen', '-config', path.join('tests', 'ntmultiple.cfg')]
else:
strport = '/dev... | Tests the explicit monitor setup using the 'multiple.cfg' file in the
current directory. | tests/test_multi.py | test_multi_listen | rosenbrockc/live-serial | 11 | python | def test_multi_listen(isnt):
"Tests the explicit monitor setup using the 'multiple.cfg' file in the\n current directory.\n "
from os import path
if isnt:
argv = ['py.test', 'COM2', 'COM4', '-virtual', '-listen', '-config', path.join('tests', 'ntmultiple.cfg')]
else:
strport = '/dev... | def test_multi_listen(isnt):
"Tests the explicit monitor setup using the 'multiple.cfg' file in the\n current directory.\n "
from os import path
if isnt:
argv = ['py.test', 'COM2', 'COM4', '-virtual', '-listen', '-config', path.join('tests', 'ntmultiple.cfg')]
else:
strport = '/dev... |
82257051bd18ab7038cb747f6bbd9fa1a2d8a3c6a9f037c020d84ed90f5953dd | def test_multi_logplot(isnt, tmpdir):
'Tests the simultaneous logging and plotting from multiple ports with\n multiple sensors per port.\n '
from os import path
sub = tmpdir.mkdir('multilog')
if isnt:
argv = ['py.test', 'COM2', 'COM4', '-virtual', '-logdir', str(sub), '-config', path.join(... | Tests the simultaneous logging and plotting from multiple ports with
multiple sensors per port. | tests/test_multi.py | test_multi_logplot | rosenbrockc/live-serial | 11 | python | def test_multi_logplot(isnt, tmpdir):
'Tests the simultaneous logging and plotting from multiple ports with\n multiple sensors per port.\n '
from os import path
sub = tmpdir.mkdir('multilog')
if isnt:
argv = ['py.test', 'COM2', 'COM4', '-virtual', '-logdir', str(sub), '-config', path.join(... | def test_multi_logplot(isnt, tmpdir):
'Tests the simultaneous logging and plotting from multiple ports with\n multiple sensors per port.\n '
from os import path
sub = tmpdir.mkdir('multilog')
if isnt:
argv = ['py.test', 'COM2', 'COM4', '-virtual', '-logdir', str(sub), '-config', path.join(... |
5ad3e50fc87aa46c98a614a05d03c03e068ece3a99693b76465a0b43fe0cbba5 | def tube_locations():
'\n Return an (n, 2) array of selected London Tube locations in Ordnance\n Survey GB coordinates.\n\n Source: https://www.doogal.co.uk/london_stations.php\n\n '
return np.array([[531738.0, 180890.0], [532379.0, 179734.0], [531096.0, 181642.0], [530234.0, 180492.0], [531688.0, 1... | Return an (n, 2) array of selected London Tube locations in Ordnance
Survey GB coordinates.
Source: https://www.doogal.co.uk/london_stations.php | journal_venv/lib/python3.9/site-packages/cartopy/examples/tube_stations.py | tube_locations | ushham/JournalTool | 2 | python | def tube_locations():
'\n Return an (n, 2) array of selected London Tube locations in Ordnance\n Survey GB coordinates.\n\n Source: https://www.doogal.co.uk/london_stations.php\n\n '
return np.array([[531738.0, 180890.0], [532379.0, 179734.0], [531096.0, 181642.0], [530234.0, 180492.0], [531688.0, 1... | def tube_locations():
'\n Return an (n, 2) array of selected London Tube locations in Ordnance\n Survey GB coordinates.\n\n Source: https://www.doogal.co.uk/london_stations.php\n\n '
return np.array([[531738.0, 180890.0], [532379.0, 179734.0], [531096.0, 181642.0], [530234.0, 180492.0], [531688.0, 1... |
ed838d10b2662fce04bbd2537b73199a09d7ad22aa5dc57fc106544270bb5f74 | def get_freq(times, units='s'):
"\n Identify and return the frequency a dataset is sampled.\n\n Given an array with timestamps, the step between times is estimated, then\n a mean of its values is inverted to obtain the sampling frequency.\n\n Parameters\n ----------\n times : array\n 1-D ar... | Identify and return the frequency a dataset is sampled.
Given an array with timestamps, the step between times is estimated, then
a mean of its values is inverted to obtain the sampling frequency.
Parameters
----------
times : array
1-D array with the timestamps of the file.
units : str
Time units of the arra... | software/imu/ahrs/utils/io.py | get_freq | tucuongbrt/PIFer | 184 | python | def get_freq(times, units='s'):
"\n Identify and return the frequency a dataset is sampled.\n\n Given an array with timestamps, the step between times is estimated, then\n a mean of its values is inverted to obtain the sampling frequency.\n\n Parameters\n ----------\n times : array\n 1-D ar... | def get_freq(times, units='s'):
"\n Identify and return the frequency a dataset is sampled.\n\n Given an array with timestamps, the step between times is estimated, then\n a mean of its values is inverted to obtain the sampling frequency.\n\n Parameters\n ----------\n times : array\n 1-D ar... |
e9334c422198b59b2c463f689d0693fb5a76e1db3ca0622334b493ee52f7bd3d | def load(file_name, separator=';'):
"\n Load the contents of a file into a dictionary.\n\n Supported formats, so far, are MAT and CSV files. More to come.\n\n To Do:\n - Get a better way to find data from keys of dictionary. PLEASE.\n\n Parameters\n ----------\n file_name : str\n Name of... | Load the contents of a file into a dictionary.
Supported formats, so far, are MAT and CSV files. More to come.
To Do:
- Get a better way to find data from keys of dictionary. PLEASE.
Parameters
----------
file_name : str
Name of the file
separator : str, default: ';'
String used to split values. Normally usi... | software/imu/ahrs/utils/io.py | load | tucuongbrt/PIFer | 184 | python | def load(file_name, separator=';'):
"\n Load the contents of a file into a dictionary.\n\n Supported formats, so far, are MAT and CSV files. More to come.\n\n To Do:\n - Get a better way to find data from keys of dictionary. PLEASE.\n\n Parameters\n ----------\n file_name : str\n Name of... | def load(file_name, separator=';'):
"\n Load the contents of a file into a dictionary.\n\n Supported formats, so far, are MAT and CSV files. More to come.\n\n To Do:\n - Get a better way to find data from keys of dictionary. PLEASE.\n\n Parameters\n ----------\n file_name : str\n Name of... |
87d09930718b23fe54ffe2342a3bcaf781fc6e294b4a7522dbb24a718b4beacc | def load_ETH_EC(path):
"\n Loads data from a directory containing files of the Event-Camera Dataset\n from the ETH Zurich (http://rpg.ifi.uzh.ch/davis_data.html)\n\n The dataset includes 4 basic text files with recorded data, plus a file\n listing all images of the recording included in the subfolder 'i... | Loads data from a directory containing files of the Event-Camera Dataset
from the ETH Zurich (http://rpg.ifi.uzh.ch/davis_data.html)
The dataset includes 4 basic text files with recorded data, plus a file
listing all images of the recording included in the subfolder 'images.'
**events.txt**: One event per line (times... | software/imu/ahrs/utils/io.py | load_ETH_EC | tucuongbrt/PIFer | 184 | python | def load_ETH_EC(path):
"\n Loads data from a directory containing files of the Event-Camera Dataset\n from the ETH Zurich (http://rpg.ifi.uzh.ch/davis_data.html)\n\n The dataset includes 4 basic text files with recorded data, plus a file\n listing all images of the recording included in the subfolder 'i... | def load_ETH_EC(path):
"\n Loads data from a directory containing files of the Event-Camera Dataset\n from the ETH Zurich (http://rpg.ifi.uzh.ch/davis_data.html)\n\n The dataset includes 4 basic text files with recorded data, plus a file\n listing all images of the recording included in the subfolder 'i... |
66a7956f80b8ce985b036c38783bc14a7b9e8490de265c6db32156db0f8628cf | def load_ETH_EuRoC(path):
'\n Load data from the EuRoC MAV dataset of the ETH Zurich\n (https://projects.asl.ethz.ch/datasets/doku.php?id=kmavvisualinertialdatasets)\n\n Parameters\n ----------\n path : str\n Path to the folder containing the dataset.\n\n References\n ----------\n .. ... | Load data from the EuRoC MAV dataset of the ETH Zurich
(https://projects.asl.ethz.ch/datasets/doku.php?id=kmavvisualinertialdatasets)
Parameters
----------
path : str
Path to the folder containing the dataset.
References
----------
.. [ETH-EuRoC] M. Burri, J. Nikolic, P. Gohl, T. Schneider, J. Rehder, S.
Omar... | software/imu/ahrs/utils/io.py | load_ETH_EuRoC | tucuongbrt/PIFer | 184 | python | def load_ETH_EuRoC(path):
'\n Load data from the EuRoC MAV dataset of the ETH Zurich\n (https://projects.asl.ethz.ch/datasets/doku.php?id=kmavvisualinertialdatasets)\n\n Parameters\n ----------\n path : str\n Path to the folder containing the dataset.\n\n References\n ----------\n .. ... | def load_ETH_EuRoC(path):
'\n Load data from the EuRoC MAV dataset of the ETH Zurich\n (https://projects.asl.ethz.ch/datasets/doku.php?id=kmavvisualinertialdatasets)\n\n Parameters\n ----------\n path : str\n Path to the folder containing the dataset.\n\n References\n ----------\n .. ... |
5033232f0a07dcda1224b981f45fecd1b5c9b915ac14e62c787006d9019b9e50 | def load_OxIOD(path, sequence=1):
'\n Load data from the Oxford Inertial Odometry Dataset\n (http://deepio.cs.ox.ac.uk/)\n\n The OxIOD has several sequences stored in CSV, composed of sensors and\n vicon recordings, with the names and formats:\n\n imu:\n [0] Time\n [1] attitude_roll(rad... | Load data from the Oxford Inertial Odometry Dataset
(http://deepio.cs.ox.ac.uk/)
The OxIOD has several sequences stored in CSV, composed of sensors and
vicon recordings, with the names and formats:
imu:
[0] Time
[1] attitude_roll(radians)
[2] attitude_pitch(radians)
[3] attitude_yaw(radians)
[4] r... | software/imu/ahrs/utils/io.py | load_OxIOD | tucuongbrt/PIFer | 184 | python | def load_OxIOD(path, sequence=1):
'\n Load data from the Oxford Inertial Odometry Dataset\n (http://deepio.cs.ox.ac.uk/)\n\n The OxIOD has several sequences stored in CSV, composed of sensors and\n vicon recordings, with the names and formats:\n\n imu:\n [0] Time\n [1] attitude_roll(rad... | def load_OxIOD(path, sequence=1):
'\n Load data from the Oxford Inertial Odometry Dataset\n (http://deepio.cs.ox.ac.uk/)\n\n The OxIOD has several sequences stored in CSV, composed of sensors and\n vicon recordings, with the names and formats:\n\n imu:\n [0] Time\n [1] attitude_roll(rad... |
d1bef4ea4f7bf830547cf7ccd646901b6edbbf7874195e9d7c4b9fa6f9c55ded | def command_conversion(command, payload, command_list):
"\n Convert the command info (if known). See module_data['commands'] and module_data['exfil_types']\n Args:\n dest: a string containing either 'server' or 'client' to dictate which direction the packet is going.\n command: hex string of the... | Convert the command info (if known). See module_data['commands'] and module_data['exfil_types']
Args:
dest: a string containing either 'server' or 'client' to dictate which direction the packet is going.
command: hex string of the command byte
payload: hex string of the packet payload data | chopshop/modules/evilgrab.py | command_conversion | dgh2466/public_tools | 647 | python | def command_conversion(command, payload, command_list):
"\n Convert the command info (if known). See module_data['commands'] and module_data['exfil_types']\n Args:\n dest: a string containing either 'server' or 'client' to dictate which direction the packet is going.\n command: hex string of the... | def command_conversion(command, payload, command_list):
"\n Convert the command info (if known). See module_data['commands'] and module_data['exfil_types']\n Args:\n dest: a string containing either 'server' or 'client' to dictate which direction the packet is going.\n command: hex string of the... |
e79d78bc19e46f471af3f431dfea9ed3701475051584425300395183d48f2119 | def decode_command(dest, command, payload, command_list):
"\n Print out the command info response from command_conversion.\n Args:\n dest: a string containing either 'server' or 'client' to dictate which direction the packet is going.\n command: hex string of the command byte\n payload: h... | Print out the command info response from command_conversion.
Args:
dest: a string containing either 'server' or 'client' to dictate which direction the packet is going.
command: hex string of the command byte
payload: hex string of the packet payload data | chopshop/modules/evilgrab.py | decode_command | dgh2466/public_tools | 647 | python | def decode_command(dest, command, payload, command_list):
"\n Print out the command info response from command_conversion.\n Args:\n dest: a string containing either 'server' or 'client' to dictate which direction the packet is going.\n command: hex string of the command byte\n payload: h... | def decode_command(dest, command, payload, command_list):
"\n Print out the command info response from command_conversion.\n Args:\n dest: a string containing either 'server' or 'client' to dictate which direction the packet is going.\n command: hex string of the command byte\n payload: h... |
a865dd48c2f6630dfc850188451504282e7cfa8f639f357b914a8a1f1a7be69e | def find_similar_items(self, query, num_matches=5):
'Finds similar items to a given quey in the ANN index.\n\n Args:\n query: The query string\n num_matches: The number of similar items to retrieve.\n\n Returns:\n List of items.\n '
query_embedding = self.embed_fn([query])[0].numpy()
... | Finds similar items to a given quey in the ANN index.
Args:
query: The query string
num_matches: The number of similar items to retrieve.
Returns:
List of items. | tensorflow_hub/tools/make_nearest_neighbour_index/similarity_finder.py | find_similar_items | TylerBrabham/hub | 3,234 | python | def find_similar_items(self, query, num_matches=5):
'Finds similar items to a given quey in the ANN index.\n\n Args:\n query: The query string\n num_matches: The number of similar items to retrieve.\n\n Returns:\n List of items.\n '
query_embedding = self.embed_fn([query])[0].numpy()
... | def find_similar_items(self, query, num_matches=5):
'Finds similar items to a given quey in the ANN index.\n\n Args:\n query: The query string\n num_matches: The number of similar items to retrieve.\n\n Returns:\n List of items.\n '
query_embedding = self.embed_fn([query])[0].numpy()
... |
61ca817cccd4c429d830a4939588dec003e6896c910bbba4652818cd60bbfe3c | def topmovies():
'\n A web scraper to extract top movies information out of imdb website\n and create movie objects and return a list of movies\n '
imdburl = 'https://www.imdb.com'
url = 'https://www.imdb.com/list/ls068082370/'
page = requests.get(url)
soup = BeautifulSoup(page.cont... | A web scraper to extract top movies information out of imdb website
and create movie objects and return a list of movies | imdbexplorer/explorer.py | topmovies | Zahra-T/imdbexplorer | 1 | python | def topmovies():
'\n A web scraper to extract top movies information out of imdb website\n and create movie objects and return a list of movies\n '
imdburl = 'https://www.imdb.com'
url = 'https://www.imdb.com/list/ls068082370/'
page = requests.get(url)
soup = BeautifulSoup(page.cont... | def topmovies():
'\n A web scraper to extract top movies information out of imdb website\n and create movie objects and return a list of movies\n '
imdburl = 'https://www.imdb.com'
url = 'https://www.imdb.com/list/ls068082370/'
page = requests.get(url)
soup = BeautifulSoup(page.cont... |
3ee70baeaa8a1ce9f034cc83690ed52ac903e3600c9bfa89bdb9625ef1b3b050 | def filter(movies, filterattr, info):
'\n A method to filter a movie list by movie attributes\n\n Args:\n movies: a list of movie objects in type of Movie class\n\n filterattr: a string that defines movies have to be filtered by which of the attributes of movie object\n\n info: more info ... | A method to filter a movie list by movie attributes
Args:
movies: a list of movie objects in type of Movie class
filterattr: a string that defines movies have to be filtered by which of the attributes of movie object
info: more info for filter the movies list
for genre: a list of genres
... | imdbexplorer/explorer.py | filter | Zahra-T/imdbexplorer | 1 | python | def filter(movies, filterattr, info):
'\n A method to filter a movie list by movie attributes\n\n Args:\n movies: a list of movie objects in type of Movie class\n\n filterattr: a string that defines movies have to be filtered by which of the attributes of movie object\n\n info: more info ... | def filter(movies, filterattr, info):
'\n A method to filter a movie list by movie attributes\n\n Args:\n movies: a list of movie objects in type of Movie class\n\n filterattr: a string that defines movies have to be filtered by which of the attributes of movie object\n\n info: more info ... |
20c9f53b0f04309818b1a76eb8684a8a9d5866396bd06b77089ff1b3111629d8 | @lru_cache()
def _load_esm_model(model_name: str='esm1b_t33_650M_UR50S'):
'\n Loads pre-trained FAIR ESM model from torch hub.\n\n Sources:\n Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 Million Protein Sequences (2019)\n Rives, Alexander and Meier, Joshua and Sercu... | Loads pre-trained FAIR ESM model from torch hub.
Sources:
Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 Million Protein Sequences (2019)
Rives, Alexander and Meier, Joshua and Sercu, Tom and Goyal, Siddharth and Lin, Zeming and Liu, Jason and Guo,
Demi and Ott, Myle and Zitnick, C.... | graphein/protein/features/sequence/embeddings.py | _load_esm_model | rg314/graphein | 342 | python | @lru_cache()
def _load_esm_model(model_name: str='esm1b_t33_650M_UR50S'):
'\n Loads pre-trained FAIR ESM model from torch hub.\n\n Sources:\n Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 Million Protein Sequences (2019)\n Rives, Alexander and Meier, Joshua and Sercu... | @lru_cache()
def _load_esm_model(model_name: str='esm1b_t33_650M_UR50S'):
'\n Loads pre-trained FAIR ESM model from torch hub.\n\n Sources:\n Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 Million Protein Sequences (2019)\n Rives, Alexander and Meier, Joshua and Sercu... |
5660ecee7d4151fbc640b9cdd8ff0af5153471aff09cae777d9e4cb8c90fb4c5 | def compute_esm_embedding(sequence: str, representation: str, model_name: str='esm1b_t33_650M_UR50S', output_layer: int=33) -> np.ndarray:
'\n Computes sequence embedding using Pre-trained ESM model from FAIR\n\n Sources:\n Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 ... | Computes sequence embedding using Pre-trained ESM model from FAIR
Sources:
Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 Million Protein Sequences (2019)
Rives, Alexander and Meier, Joshua and Sercu, Tom and Goyal, Siddharth and Lin, Zeming and Liu, Jason and Guo,
Demi and Ott, Myl... | graphein/protein/features/sequence/embeddings.py | compute_esm_embedding | rg314/graphein | 342 | python | def compute_esm_embedding(sequence: str, representation: str, model_name: str='esm1b_t33_650M_UR50S', output_layer: int=33) -> np.ndarray:
'\n Computes sequence embedding using Pre-trained ESM model from FAIR\n\n Sources:\n Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 ... | def compute_esm_embedding(sequence: str, representation: str, model_name: str='esm1b_t33_650M_UR50S', output_layer: int=33) -> np.ndarray:
'\n Computes sequence embedding using Pre-trained ESM model from FAIR\n\n Sources:\n Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 ... |
9ef1bf59de258dad1fc18a474dd1931faeb397294239f1e2248b331759c014ef | def esm_residue_embedding(G: nx.Graph, model_name: str='esm1b_t33_650M_UR50S', output_layer: int=33) -> nx.Graph:
'\n Computes ESM residue embeddings from a protein sequence and adds the to the graph.\n\n Sources:\n Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 Million ... | Computes ESM residue embeddings from a protein sequence and adds the to the graph.
Sources:
Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 Million Protein Sequences (2019)
Rives, Alexander and Meier, Joshua and Sercu, Tom and Goyal, Siddharth and Lin, Zeming and Liu, Jason and Guo,
... | graphein/protein/features/sequence/embeddings.py | esm_residue_embedding | rg314/graphein | 342 | python | def esm_residue_embedding(G: nx.Graph, model_name: str='esm1b_t33_650M_UR50S', output_layer: int=33) -> nx.Graph:
'\n Computes ESM residue embeddings from a protein sequence and adds the to the graph.\n\n Sources:\n Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 Million ... | def esm_residue_embedding(G: nx.Graph, model_name: str='esm1b_t33_650M_UR50S', output_layer: int=33) -> nx.Graph:
'\n Computes ESM residue embeddings from a protein sequence and adds the to the graph.\n\n Sources:\n Biological Structure and Function Emerge from Scaling Unsupervised Learning to 250 Million ... |
9d67ee7593b9e6d535c36d6e702f182d35860cc8294a93613f35f9815e9f3ee1 | def esm_sequence_embedding(G: nx.Graph) -> nx.Graph:
'\n Computes ESM sequence embedding feature over chains in a graph\n\n :param G: nx.Graph protein structure graph\n :type G: nx.Graph\n :return: nx.Graphein protein structure graphein with esm embedding features added eg. G.graph["esm_embedding_A"]\n ... | Computes ESM sequence embedding feature over chains in a graph
:param G: nx.Graph protein structure graph
:type G: nx.Graph
:return: nx.Graphein protein structure graphein with esm embedding features added eg. G.graph["esm_embedding_A"]
:rtype: nx.Graph | graphein/protein/features/sequence/embeddings.py | esm_sequence_embedding | rg314/graphein | 342 | python | def esm_sequence_embedding(G: nx.Graph) -> nx.Graph:
'\n Computes ESM sequence embedding feature over chains in a graph\n\n :param G: nx.Graph protein structure graph\n :type G: nx.Graph\n :return: nx.Graphein protein structure graphein with esm embedding features added eg. G.graph["esm_embedding_A"]\n ... | def esm_sequence_embedding(G: nx.Graph) -> nx.Graph:
'\n Computes ESM sequence embedding feature over chains in a graph\n\n :param G: nx.Graph protein structure graph\n :type G: nx.Graph\n :return: nx.Graphein protein structure graphein with esm embedding features added eg. G.graph["esm_embedding_A"]\n ... |
246d67dc04514b525ffc0f54fd72a89f3626770b64a5e3995e90a983d13e8751 | @lru_cache()
def _load_biovec_model():
'Loads pretrained ProtVec Model\n\n Source: ProtVec: A Continuous Distributed Representation of Biological Sequences\n Paper: http://arxiv.org/pdf/1503.05140v1.pdf\n '
return biovec.models.load_protvec(os.fspath(((Path(__file__).parent.parent / 'pretrained_models'... | Loads pretrained ProtVec Model
Source: ProtVec: A Continuous Distributed Representation of Biological Sequences
Paper: http://arxiv.org/pdf/1503.05140v1.pdf | graphein/protein/features/sequence/embeddings.py | _load_biovec_model | rg314/graphein | 342 | python | @lru_cache()
def _load_biovec_model():
'Loads pretrained ProtVec Model\n\n Source: ProtVec: A Continuous Distributed Representation of Biological Sequences\n Paper: http://arxiv.org/pdf/1503.05140v1.pdf\n '
return biovec.models.load_protvec(os.fspath(((Path(__file__).parent.parent / 'pretrained_models'... | @lru_cache()
def _load_biovec_model():
'Loads pretrained ProtVec Model\n\n Source: ProtVec: A Continuous Distributed Representation of Biological Sequences\n Paper: http://arxiv.org/pdf/1503.05140v1.pdf\n '
return biovec.models.load_protvec(os.fspath(((Path(__file__).parent.parent / 'pretrained_models'... |
0e0e39b5630e40956d8e3d8e74b53bd013efaa7895d46a79a171e48f2c611c30 | def biovec_sequence_embedding(G: nx.Graph) -> nx.Graph:
'\n Adds BioVec sequence embedding feature to the graph. Computed over chains\n\n Source: ProtVec: A Continuous Distributed Representation of Biological Sequences\n Paper: http://arxiv.org/pdf/1503.05140v1.pdf\n\n :param G: nx.Graph protein structu... | Adds BioVec sequence embedding feature to the graph. Computed over chains
Source: ProtVec: A Continuous Distributed Representation of Biological Sequences
Paper: http://arxiv.org/pdf/1503.05140v1.pdf
:param G: nx.Graph protein structure graph
:type G: nx.Graph
:return: nx.Graph protein structure graph with biovec emb... | graphein/protein/features/sequence/embeddings.py | biovec_sequence_embedding | rg314/graphein | 342 | python | def biovec_sequence_embedding(G: nx.Graph) -> nx.Graph:
'\n Adds BioVec sequence embedding feature to the graph. Computed over chains\n\n Source: ProtVec: A Continuous Distributed Representation of Biological Sequences\n Paper: http://arxiv.org/pdf/1503.05140v1.pdf\n\n :param G: nx.Graph protein structu... | def biovec_sequence_embedding(G: nx.Graph) -> nx.Graph:
'\n Adds BioVec sequence embedding feature to the graph. Computed over chains\n\n Source: ProtVec: A Continuous Distributed Representation of Biological Sequences\n Paper: http://arxiv.org/pdf/1503.05140v1.pdf\n\n :param G: nx.Graph protein structu... |
289037531ed60dfcb30256d3b14d08175e42a1f664493f0e64d1c5c6cb397bd5 | def install_deps():
'Reads requirements.txt and preprocess it\n to be feed into setuptools.\n\n This is the only possible way (we found)\n how requirements.txt can be reused in setup.py\n using dependencies from private github repositories.\n\n Links must be appendend by `-{StringWithAtLeastOneNumber... | Reads requirements.txt and preprocess it
to be feed into setuptools.
This is the only possible way (we found)
how requirements.txt can be reused in setup.py
using dependencies from private github repositories.
Links must be appendend by `-{StringWithAtLeastOneNumber}`
or something like that, so e.g. `-9231` works as ... | setup.py | install_deps | Redferne/lwm2mclient | 0 | python | def install_deps():
'Reads requirements.txt and preprocess it\n to be feed into setuptools.\n\n This is the only possible way (we found)\n how requirements.txt can be reused in setup.py\n using dependencies from private github repositories.\n\n Links must be appendend by `-{StringWithAtLeastOneNumber... | def install_deps():
'Reads requirements.txt and preprocess it\n to be feed into setuptools.\n\n This is the only possible way (we found)\n how requirements.txt can be reused in setup.py\n using dependencies from private github repositories.\n\n Links must be appendend by `-{StringWithAtLeastOneNumber... |
e59c72f644310b9e34ac99d7f1f5e766c38f94456f00f32f13e1f9e789ef43b2 | def __init__(self, start_url: str, splash_address: str, allow_subdomains: bool=True, allow_queries: bool=False, depth_by_desc: Union[(int, None)]=None, concurrency: int=5, max_pause: float=10.0) -> None:
'__init__.\n\n Parameters\n ----------\n start_url : str\n Typically a website a... | __init__.
Parameters
----------
start_url : str
Typically a website address, like "https://google.com".
Must contain protocol prefix i.e. "http://" or "https://".
splash_address : str
Address of Splash renderer instance.
allow_subdomains : bool
Allow indexing subdomains like "https://mail.google.com"
a... | baby_crawler/crawler.py | __init__ | weiss-d/baby-crawler | 0 | python | def __init__(self, start_url: str, splash_address: str, allow_subdomains: bool=True, allow_queries: bool=False, depth_by_desc: Union[(int, None)]=None, concurrency: int=5, max_pause: float=10.0) -> None:
'__init__.\n\n Parameters\n ----------\n start_url : str\n Typically a website a... | def __init__(self, start_url: str, splash_address: str, allow_subdomains: bool=True, allow_queries: bool=False, depth_by_desc: Union[(int, None)]=None, concurrency: int=5, max_pause: float=10.0) -> None:
'__init__.\n\n Parameters\n ----------\n start_url : str\n Typically a website a... |
b384571483114daf3cd54b6f891dabb1e1eba089d050fbc9e1adc77c44c5e2f9 | def _has_root_url_only(self, url: str) -> bool:
'Check if the given link starts with root URL.\n\n Parameters\n ----------\n url : str\n URL to be checked.\n\n Returns\n -------\n bool\n True if the link starts only with root URL, no subdomain allowed.... | Check if the given link starts with root URL.
Parameters
----------
url : str
URL to be checked.
Returns
-------
bool
True if the link starts only with root URL, no subdomain allowed. | baby_crawler/crawler.py | _has_root_url_only | weiss-d/baby-crawler | 0 | python | def _has_root_url_only(self, url: str) -> bool:
'Check if the given link starts with root URL.\n\n Parameters\n ----------\n url : str\n URL to be checked.\n\n Returns\n -------\n bool\n True if the link starts only with root URL, no subdomain allowed.... | def _has_root_url_only(self, url: str) -> bool:
'Check if the given link starts with root URL.\n\n Parameters\n ----------\n url : str\n URL to be checked.\n\n Returns\n -------\n bool\n True if the link starts only with root URL, no subdomain allowed.... |
c7886a508569e229fba98134393717367a4ea2e885d9263601b5402e9e00de9a | def _has_root_url_or_subdomain(self, url: str) -> bool:
'Check if the given link starts with root URL or its subdomain.\n\n Parameters\n ----------\n url : str\n URL to be checked.\n\n Returns\n -------\n bool\n True if the links contains root URL.\n\n... | Check if the given link starts with root URL or its subdomain.
Parameters
----------
url : str
URL to be checked.
Returns
-------
bool
True if the links contains root URL. | baby_crawler/crawler.py | _has_root_url_or_subdomain | weiss-d/baby-crawler | 0 | python | def _has_root_url_or_subdomain(self, url: str) -> bool:
'Check if the given link starts with root URL or its subdomain.\n\n Parameters\n ----------\n url : str\n URL to be checked.\n\n Returns\n -------\n bool\n True if the links contains root URL.\n\n... | def _has_root_url_or_subdomain(self, url: str) -> bool:
'Check if the given link starts with root URL or its subdomain.\n\n Parameters\n ----------\n url : str\n URL to be checked.\n\n Returns\n -------\n bool\n True if the links contains root URL.\n\n... |
8f30b01c5c24e9952d0ee40d4f65a289887315908da0d0d72414e417b1656f10 | def _is_valid_link(self, link: str, parent_link: str) -> bool:
'Validates given URL against several rules to exclude unrelated links and some spider traps.\n\n Parameters\n ----------\n link : str\n URL for checking.\n parent_link : str\n URL of the page where given... | Validates given URL against several rules to exclude unrelated links and some spider traps.
Parameters
----------
link : str
URL for checking.
parent_link : str
URL of the page where given link was found.
Returns
-------
bool
True if all conditionsa are met. | baby_crawler/crawler.py | _is_valid_link | weiss-d/baby-crawler | 0 | python | def _is_valid_link(self, link: str, parent_link: str) -> bool:
'Validates given URL against several rules to exclude unrelated links and some spider traps.\n\n Parameters\n ----------\n link : str\n URL for checking.\n parent_link : str\n URL of the page where given... | def _is_valid_link(self, link: str, parent_link: str) -> bool:
'Validates given URL against several rules to exclude unrelated links and some spider traps.\n\n Parameters\n ----------\n link : str\n URL for checking.\n parent_link : str\n URL of the page where given... |
ac696226c710052bbbea0c27cd9c2795c5fe0970fcdf74e9e924bd94658e17f0 | def _remove_query(self, url: str) -> str:
'Removes query part of a URL (i.e. anythin after "?").\n\n Parameters\n ----------\n url : str\n URL with or without query part.\n\n Returns\n -------\n str\n Guaranteed clean URL.\n\n '
split = list... | Removes query part of a URL (i.e. anythin after "?").
Parameters
----------
url : str
URL with or without query part.
Returns
-------
str
Guaranteed clean URL. | baby_crawler/crawler.py | _remove_query | weiss-d/baby-crawler | 0 | python | def _remove_query(self, url: str) -> str:
'Removes query part of a URL (i.e. anythin after "?").\n\n Parameters\n ----------\n url : str\n URL with or without query part.\n\n Returns\n -------\n str\n Guaranteed clean URL.\n\n '
split = list... | def _remove_query(self, url: str) -> str:
'Removes query part of a URL (i.e. anythin after "?").\n\n Parameters\n ----------\n url : str\n URL with or without query part.\n\n Returns\n -------\n str\n Guaranteed clean URL.\n\n '
split = list... |
ec1288c83fa6a4898b42e4f8263fa57c62053f524b14dcc6960247cc909e736b | def _normalize_link(self, link: str, parent_link: str) -> str:
'Set relative link to absolute. Remove fragment if present. Remove trailing slash.\n\n Parameters\n ----------\n link : str\n URL for normalizing that passed _is_valid_link().\n parent_link : str\n URL o... | Set relative link to absolute. Remove fragment if present. Remove trailing slash.
Parameters
----------
link : str
URL for normalizing that passed _is_valid_link().
parent_link : str
URL of the page where given link was found.
Returns
-------
str
Clean absolute URL. | baby_crawler/crawler.py | _normalize_link | weiss-d/baby-crawler | 0 | python | def _normalize_link(self, link: str, parent_link: str) -> str:
'Set relative link to absolute. Remove fragment if present. Remove trailing slash.\n\n Parameters\n ----------\n link : str\n URL for normalizing that passed _is_valid_link().\n parent_link : str\n URL o... | def _normalize_link(self, link: str, parent_link: str) -> str:
'Set relative link to absolute. Remove fragment if present. Remove trailing slash.\n\n Parameters\n ----------\n link : str\n URL for normalizing that passed _is_valid_link().\n parent_link : str\n URL o... |
cc25770e771581437de5988af14c3c879c1688a046a50b365de5eb8787deda91 | def _filter_links(self, links: List[str], parent_link: str) -> Generator[(str, None, None)]:
'Filters out links that are invalid or not unique.\n\n Parameters\n ----------\n links : List[str]\n A list of links found on a page.\n\n Returns\n -------\n List[str]\n ... | Filters out links that are invalid or not unique.
Parameters
----------
links : List[str]
A list of links found on a page.
Returns
-------
List[str]
A list of links, that are valid and not yet been crawled. | baby_crawler/crawler.py | _filter_links | weiss-d/baby-crawler | 0 | python | def _filter_links(self, links: List[str], parent_link: str) -> Generator[(str, None, None)]:
'Filters out links that are invalid or not unique.\n\n Parameters\n ----------\n links : List[str]\n A list of links found on a page.\n\n Returns\n -------\n List[str]\n ... | def _filter_links(self, links: List[str], parent_link: str) -> Generator[(str, None, None)]:
'Filters out links that are invalid or not unique.\n\n Parameters\n ----------\n links : List[str]\n A list of links found on a page.\n\n Returns\n -------\n List[str]\n ... |
aa31eb67469d4cab8d4c78ad70c84fdb6407e251169b97fff303ddcca4301391 | def get_page_data(self, html: str) -> Tuple[(str, Set)]:
'get_page_data.\n\n Parameters\n ----------\n html : str\n String of page html.\n\n Returns\n -------\n Tuple[str, Set]\n Tuple containing page title (or "" if none) and a list of validated links... | get_page_data.
Parameters
----------
html : str
String of page html.
Returns
-------
Tuple[str, Set]
Tuple containing page title (or "" if none) and a list of validated links. | baby_crawler/crawler.py | get_page_data | weiss-d/baby-crawler | 0 | python | def get_page_data(self, html: str) -> Tuple[(str, Set)]:
'get_page_data.\n\n Parameters\n ----------\n html : str\n String of page html.\n\n Returns\n -------\n Tuple[str, Set]\n Tuple containing page title (or if none) and a list of validated links.\... | def get_page_data(self, html: str) -> Tuple[(str, Set)]:
'get_page_data.\n\n Parameters\n ----------\n html : str\n String of page html.\n\n Returns\n -------\n Tuple[str, Set]\n Tuple containing page title (or if none) and a list of validated links.\... |
2e4530c11ec26a5cfefeacca842d00e6213c782a9cf2835fcfa8bd0e3f2d3dd6 | def _add_graph_edge(self, node_id: int, parent_id: int, **kwargs) -> None:
'Add and edge to the site graph.\n\n Parameters\n ----------\n node_id : int\n Unique ID given by CrawlerQueue.\n parent_id : int\n Parent page ID, i.e. the page in which the node URL was fou... | Add and edge to the site graph.
Parameters
----------
node_id : int
Unique ID given by CrawlerQueue.
parent_id : int
Parent page ID, i.e. the page in which the node URL was found.
kwargs
Node attributes i.e. URL, Title etc.
Returns
-------
None | baby_crawler/crawler.py | _add_graph_edge | weiss-d/baby-crawler | 0 | python | def _add_graph_edge(self, node_id: int, parent_id: int, **kwargs) -> None:
'Add and edge to the site graph.\n\n Parameters\n ----------\n node_id : int\n Unique ID given by CrawlerQueue.\n parent_id : int\n Parent page ID, i.e. the page in which the node URL was fou... | def _add_graph_edge(self, node_id: int, parent_id: int, **kwargs) -> None:
'Add and edge to the site graph.\n\n Parameters\n ----------\n node_id : int\n Unique ID given by CrawlerQueue.\n parent_id : int\n Parent page ID, i.e. the page in which the node URL was fou... |
531a2c8495238cc6ffac7b05e0563460b54738bb371c63058a571d3d8ab22cc0 | async def fetch_page(self, url: str) -> str:
"Asyncronously fetch a page from given URL using aiohttp and Splash HTTP API.\n\n Parameters\n ----------\n url : str\n Absolute page URL.\n\n Returns\n -------\n str\n String of fetched page HTML.\n\n ... | Asyncronously fetch a page from given URL using aiohttp and Splash HTTP API.
Parameters
----------
url : str
Absolute page URL.
Returns
-------
str
String of fetched page HTML.
Raises
------
FetchError
Raised on every error associated with HTTP errors or exceeded timeouts.
Attribute 'error_type' cont... | baby_crawler/crawler.py | fetch_page | weiss-d/baby-crawler | 0 | python | async def fetch_page(self, url: str) -> str:
"Asyncronously fetch a page from given URL using aiohttp and Splash HTTP API.\n\n Parameters\n ----------\n url : str\n Absolute page URL.\n\n Returns\n -------\n str\n String of fetched page HTML.\n\n ... | async def fetch_page(self, url: str) -> str:
"Asyncronously fetch a page from given URL using aiohttp and Splash HTTP API.\n\n Parameters\n ----------\n url : str\n Absolute page URL.\n\n Returns\n -------\n str\n String of fetched page HTML.\n\n ... |
41763537cc19df95bad5f549074ddb449e0d88793cf3fff4371a8e6665a2f541 | async def _process_link(self, queue, page_id: int, page_link: str, parent_id: int, desc_level: int) -> None:
'Adds a page to site map graph and then processes all the links found on this page.\n Adds found links to the queue if they are not yet been crawled.\n\n Parameters\n ----------\n ... | Adds a page to site map graph and then processes all the links found on this page.
Adds found links to the queue if they are not yet been crawled.
Parameters
----------
queue : asyncio.Queue
CrawlerQueue to take items for processing from.
page_id : int
Unique page ID from queue.
page_link : str
Page URL.
p... | baby_crawler/crawler.py | _process_link | weiss-d/baby-crawler | 0 | python | async def _process_link(self, queue, page_id: int, page_link: str, parent_id: int, desc_level: int) -> None:
'Adds a page to site map graph and then processes all the links found on this page.\n Adds found links to the queue if they are not yet been crawled.\n\n Parameters\n ----------\n ... | async def _process_link(self, queue, page_id: int, page_link: str, parent_id: int, desc_level: int) -> None:
'Adds a page to site map graph and then processes all the links found on this page.\n Adds found links to the queue if they are not yet been crawled.\n\n Parameters\n ----------\n ... |
45ffc85604305a2a5b580c87ce53c28923201824750cbf2568568ff143efa8af | async def _link_worker(self, worker_number: int, queue: asyncio.Queue) -> None:
'Function from which concurrent workers for processing links are made.\n\n Parameters\n ----------\n worker_number : int\n Task number for logging.\n queue : asyncio.Queue\n CrawlerQueue... | Function from which concurrent workers for processing links are made.
Parameters
----------
worker_number : int
Task number for logging.
queue : asyncio.Queue
CrawlerQueue to take items for processing from.
Returns
-------
None | baby_crawler/crawler.py | _link_worker | weiss-d/baby-crawler | 0 | python | async def _link_worker(self, worker_number: int, queue: asyncio.Queue) -> None:
'Function from which concurrent workers for processing links are made.\n\n Parameters\n ----------\n worker_number : int\n Task number for logging.\n queue : asyncio.Queue\n CrawlerQueue... | async def _link_worker(self, worker_number: int, queue: asyncio.Queue) -> None:
'Function from which concurrent workers for processing links are made.\n\n Parameters\n ----------\n worker_number : int\n Task number for logging.\n queue : asyncio.Queue\n CrawlerQueue... |
ad48f246d8164de6d613cf7308224e7413838cf5df7d60e118cc16a5f2a5f584 | async def _run_crawler(self) -> None:
'Asyncronous function to initiate concurrent site crawling.\n\n Returns\n -------\n None\n\n '
queue = CrawlerQueue()
queue.put_nowait((self.start_url, 0, 0))
workers = [asyncio.create_task(self._link_worker(i, queue)) for i in range(self... | Asyncronous function to initiate concurrent site crawling.
Returns
-------
None | baby_crawler/crawler.py | _run_crawler | weiss-d/baby-crawler | 0 | python | async def _run_crawler(self) -> None:
'Asyncronous function to initiate concurrent site crawling.\n\n Returns\n -------\n None\n\n '
queue = CrawlerQueue()
queue.put_nowait((self.start_url, 0, 0))
workers = [asyncio.create_task(self._link_worker(i, queue)) for i in range(self... | async def _run_crawler(self) -> None:
'Asyncronous function to initiate concurrent site crawling.\n\n Returns\n -------\n None\n\n '
queue = CrawlerQueue()
queue.put_nowait((self.start_url, 0, 0))
workers = [asyncio.create_task(self._link_worker(i, queue)) for i in range(self... |
cf843fd8267421b1c9b688ec4e1566141222c76776505d98dbf0f109820da301 | def make_site_map(self) -> None:
'Sycncronous function to make the site map using async run_crawler().\n\n Returns\n -------\n None\n\n '
asyncio.run(self._run_crawler())
self.site_graph.remove_node(0)
networkx.freeze(self.site_graph)
self.logger.info('Site map building d... | Sycncronous function to make the site map using async run_crawler().
Returns
-------
None | baby_crawler/crawler.py | make_site_map | weiss-d/baby-crawler | 0 | python | def make_site_map(self) -> None:
'Sycncronous function to make the site map using async run_crawler().\n\n Returns\n -------\n None\n\n '
asyncio.run(self._run_crawler())
self.site_graph.remove_node(0)
networkx.freeze(self.site_graph)
self.logger.info('Site map building d... | def make_site_map(self) -> None:
'Sycncronous function to make the site map using async run_crawler().\n\n Returns\n -------\n None\n\n '
asyncio.run(self._run_crawler())
self.site_graph.remove_node(0)
networkx.freeze(self.site_graph)
self.logger.info('Site map building d... |
d9a01309a4db6c77a4b086ab9c883a85e68aaa7974345e33da11b43b7391405c | def crf_function(loaded_file, i):
'\n :param loaded_file: file output from operant box\n :param i: number of days analyzing\n :return: data frame of all analysis extracted from file (one animal)\n '
(timecode, eventcode) = extract_info_from_file(loaded_file, 500)
(dippers, dippers_retrieved, ret... | :param loaded_file: file output from operant box
:param i: number of days analyzing
:return: data frame of all analysis extracted from file (one animal) | operantanalysis/scripts/Switch.py | crf_function | mspring-dartmouth/OperantBehaviorAnalysis-Python | 0 | python | def crf_function(loaded_file, i):
'\n :param loaded_file: file output from operant box\n :param i: number of days analyzing\n :return: data frame of all analysis extracted from file (one animal)\n '
(timecode, eventcode) = extract_info_from_file(loaded_file, 500)
(dippers, dippers_retrieved, ret... | def crf_function(loaded_file, i):
'\n :param loaded_file: file output from operant box\n :param i: number of days analyzing\n :return: data frame of all analysis extracted from file (one animal)\n '
(timecode, eventcode) = extract_info_from_file(loaded_file, 500)
(dippers, dippers_retrieved, ret... |
c9c3f484546e964c71905ed3dbbbc036b8871e2d0c0b03d36cac136e6d3a41cf | def import_module_from_source(source, name, sanitize=False):
'Load a module from a Python source file.\n\n Parameters\n ----------\n source : str\n Path to the Python source file which will be loaded as a module.\n name : str\n Name to give to the module once loaded.\n sanitize: bool, d... | Load a module from a Python source file.
Parameters
----------
source : str
Path to the Python source file which will be loaded as a module.
name : str
Name to give to the module once loaded.
sanitize: bool, default=False
Check for blacklisted key words in code.
Returns
-------
module : Python module
... | rampwf/utils/importing.py | import_module_from_source | xuedong/ramp-workflow | 0 | python | def import_module_from_source(source, name, sanitize=False):
'Load a module from a Python source file.\n\n Parameters\n ----------\n source : str\n Path to the Python source file which will be loaded as a module.\n name : str\n Name to give to the module once loaded.\n sanitize: bool, d... | def import_module_from_source(source, name, sanitize=False):
'Load a module from a Python source file.\n\n Parameters\n ----------\n source : str\n Path to the Python source file which will be loaded as a module.\n name : str\n Name to give to the module once loaded.\n sanitize: bool, d... |
e9c44312ede091a6e1e5105ed4475d40cc05411b13e135bb3686845092233035 | def inform_changed_data(instances: Union[(Iterable[Model], Model)], information: List[str]=None, user_id: Optional[int]=None, disable_history: bool=False, no_delete_on_restriction: bool=False) -> None:
'\n Informs the autoupdate system and the caching system about the creation or\n update of an element.\n\n ... | Informs the autoupdate system and the caching system about the creation or
update of an element.
The argument instances can be one instance or an iterable over instances.
History creation is enabled. | openslides/utils/autoupdate.py | inform_changed_data | homer54/OpenSlides | 0 | python | def inform_changed_data(instances: Union[(Iterable[Model], Model)], information: List[str]=None, user_id: Optional[int]=None, disable_history: bool=False, no_delete_on_restriction: bool=False) -> None:
'\n Informs the autoupdate system and the caching system about the creation or\n update of an element.\n\n ... | def inform_changed_data(instances: Union[(Iterable[Model], Model)], information: List[str]=None, user_id: Optional[int]=None, disable_history: bool=False, no_delete_on_restriction: bool=False) -> None:
'\n Informs the autoupdate system and the caching system about the creation or\n update of an element.\n\n ... |
8e4f418b390e7e771f4ed88741f7090b3165c3da767ee376d53573666198a9c6 | def inform_deleted_data(deleted_elements: Iterable[Tuple[(str, int)]], information: List[str]=None, user_id: Optional[int]=None) -> None:
'\n Informs the autoupdate system and the caching system about the deletion of\n elements.\n\n History creation is enabled.\n '
if (information is None):
... | Informs the autoupdate system and the caching system about the deletion of
elements.
History creation is enabled. | openslides/utils/autoupdate.py | inform_deleted_data | homer54/OpenSlides | 0 | python | def inform_deleted_data(deleted_elements: Iterable[Tuple[(str, int)]], information: List[str]=None, user_id: Optional[int]=None) -> None:
'\n Informs the autoupdate system and the caching system about the deletion of\n elements.\n\n History creation is enabled.\n '
if (information is None):
... | def inform_deleted_data(deleted_elements: Iterable[Tuple[(str, int)]], information: List[str]=None, user_id: Optional[int]=None) -> None:
'\n Informs the autoupdate system and the caching system about the deletion of\n elements.\n\n History creation is enabled.\n '
if (information is None):
... |
9b7c5a1c96bfb4fe72d3926d9e7e219368ed97a3ce1962954e1359b04d500b54 | def inform_elements(elements: Iterable[AutoupdateElement]) -> None:
'\n Informs the autoupdate system about some elements. This is used just to send\n some data to all users.\n\n If you want to save history information, user id or disable history you\n have to put information or flag inside the elements... | Informs the autoupdate system about some elements. This is used just to send
some data to all users.
If you want to save history information, user id or disable history you
have to put information or flag inside the elements. | openslides/utils/autoupdate.py | inform_elements | homer54/OpenSlides | 0 | python | def inform_elements(elements: Iterable[AutoupdateElement]) -> None:
'\n Informs the autoupdate system about some elements. This is used just to send\n some data to all users.\n\n If you want to save history information, user id or disable history you\n have to put information or flag inside the elements... | def inform_elements(elements: Iterable[AutoupdateElement]) -> None:
'\n Informs the autoupdate system about some elements. This is used just to send\n some data to all users.\n\n If you want to save history information, user id or disable history you\n have to put information or flag inside the elements... |
8190645c0bcd155be75d9561a62237803dbe49f9b3e10a141405bc12deeb7911 | def save_history(elements: Iterable[AutoupdateElement]) -> Iterable:
'\n Thin wrapper around the call of history saving manager method.\n\n This is separated to patch it during tests.\n '
from ..core.models import History
return History.objects.add_elements(elements) | Thin wrapper around the call of history saving manager method.
This is separated to patch it during tests. | openslides/utils/autoupdate.py | save_history | homer54/OpenSlides | 0 | python | def save_history(elements: Iterable[AutoupdateElement]) -> Iterable:
'\n Thin wrapper around the call of history saving manager method.\n\n This is separated to patch it during tests.\n '
from ..core.models import History
return History.objects.add_elements(elements) | def save_history(elements: Iterable[AutoupdateElement]) -> Iterable:
'\n Thin wrapper around the call of history saving manager method.\n\n This is separated to patch it during tests.\n '
from ..core.models import History
return History.objects.add_elements(elements)<|docstring|>Thin wrapper around... |
0e44880ea091558f30de7981e2b25d7f346e038fb682dbaa4b6351e5c57e5b15 | def add(self, elements: Iterable[AutoupdateElement]) -> None:
' Adds the elements to the bundle '
for element in elements:
self.autoupdate_elements[element['collection_string']][element['id']] = element | Adds the elements to the bundle | openslides/utils/autoupdate.py | add | homer54/OpenSlides | 0 | python | def add(self, elements: Iterable[AutoupdateElement]) -> None:
' '
for element in elements:
self.autoupdate_elements[element['collection_string']][element['id']] = element | def add(self, elements: Iterable[AutoupdateElement]) -> None:
' '
for element in elements:
self.autoupdate_elements[element['collection_string']][element['id']] = element<|docstring|>Adds the elements to the bundle<|endoftext|> |
81e30fbab5633fe1e54368c609dd02a5427f94ec6f14dac9a7c6d47849c9a099 | def done(self) -> None:
'\n Finishes the bundle by resolving all missing data and passing it to\n the history and element cache.\n '
if (not self.autoupdate_elements):
return
for (collection, elements) in self.autoupdate_elements.items():
ids = [element['id'] for element... | Finishes the bundle by resolving all missing data and passing it to
the history and element cache. | openslides/utils/autoupdate.py | done | homer54/OpenSlides | 0 | python | def done(self) -> None:
'\n Finishes the bundle by resolving all missing data and passing it to\n the history and element cache.\n '
if (not self.autoupdate_elements):
return
for (collection, elements) in self.autoupdate_elements.items():
ids = [element['id'] for element... | def done(self) -> None:
'\n Finishes the bundle by resolving all missing data and passing it to\n the history and element cache.\n '
if (not self.autoupdate_elements):
return
for (collection, elements) in self.autoupdate_elements.items():
ids = [element['id'] for element... |
d70c7c9197bf4c91ec6868326a41b9f005aabc95adb98609ec499ed3ef5af42d | @property
def elements(self) -> Iterable[AutoupdateElement]:
' Iterator for all elements in this bundle '
for elements in self.autoupdate_elements.values():
(yield from elements.values()) | Iterator for all elements in this bundle | openslides/utils/autoupdate.py | elements | homer54/OpenSlides | 0 | python | @property
def elements(self) -> Iterable[AutoupdateElement]:
' '
for elements in self.autoupdate_elements.values():
(yield from elements.values()) | @property
def elements(self) -> Iterable[AutoupdateElement]:
' '
for elements in self.autoupdate_elements.values():
(yield from elements.values())<|docstring|>Iterator for all elements in this bundle<|endoftext|> |
b4d44d3ea647dcc44faf03d939835b444fcf055186e21d5d76e39fb120363619 | async def update_cache(self) -> int:
'\n Async helper function to update the cache.\n\n Returns the change_id\n '
cache_elements: Dict[(str, Optional[Dict[(str, Any)]])] = {}
for element in self.elements:
element_id = get_element_id(element['collection_string'], element['id'])
... | Async helper function to update the cache.
Returns the change_id | openslides/utils/autoupdate.py | update_cache | homer54/OpenSlides | 0 | python | async def update_cache(self) -> int:
'\n Async helper function to update the cache.\n\n Returns the change_id\n '
cache_elements: Dict[(str, Optional[Dict[(str, Any)]])] = {}
for element in self.elements:
element_id = get_element_id(element['collection_string'], element['id'])
... | async def update_cache(self) -> int:
'\n Async helper function to update the cache.\n\n Returns the change_id\n '
cache_elements: Dict[(str, Optional[Dict[(str, Any)]])] = {}
for element in self.elements:
element_id = get_element_id(element['collection_string'], element['id'])
... |
246769fac739850fb43515923d70a6376734c23defdb5ba3d01f2cce8881c12f | async def async_handle_collection_elements(self) -> None:
'\n Async helper function to update cache and send autoupdate.\n '
change_id = (await self.update_cache())
channel_layer = get_channel_layer()
(await channel_layer.group_send('autoupdate', {'type': 'send_data', 'change_id': change_i... | Async helper function to update cache and send autoupdate. | openslides/utils/autoupdate.py | async_handle_collection_elements | homer54/OpenSlides | 0 | python | async def async_handle_collection_elements(self) -> None:
'\n \n '
change_id = (await self.update_cache())
channel_layer = get_channel_layer()
(await channel_layer.group_send('autoupdate', {'type': 'send_data', 'change_id': change_id}))
projector_data = (await get_projector_data())
... | async def async_handle_collection_elements(self) -> None:
'\n \n '
change_id = (await self.update_cache())
channel_layer = get_channel_layer()
(await channel_layer.group_send('autoupdate', {'type': 'send_data', 'change_id': change_id}))
projector_data = (await get_projector_data())
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.