nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
TwitchIO/TwitchIO
b5eb585b9b52d4966784f0d1ae947077a90ec0c7
twitchio/user.py
python
PartialUser.update_extensions
(self, token: str, extensions: "ExtensionBuilder")
return {typ: {int(n): ActiveExtension(d) for n, d in vals.items()} for typ, vals in data.items()}
|coro| Updates a users extensions. See the :class:`twitchio.ExtensionBuilder` Parameters ----------- token: :class:`str` An oauth token with user:edit:broadcast scope extensions: :class:`twitchio.ExtensionBuilder` A :class:`twitchio.ExtensionBuilder` to be given to the twitch api Returns -------- Dict[:class:`str`, Dict[:class:`int`, :class:`twitchio.ActiveExtension`]]
|coro|
[ "|coro|" ]
async def update_extensions(self, token: str, extensions: "ExtensionBuilder"): """|coro| Updates a users extensions. See the :class:`twitchio.ExtensionBuilder` Parameters ----------- token: :class:`str` An oauth token with user:edit:broadcast scope extensions: :class:`twitchio.ExtensionBuilder` A :class:`twitchio.ExtensionBuilder` to be given to the twitch api Returns -------- Dict[:class:`str`, Dict[:class:`int`, :class:`twitchio.ActiveExtension`]] """ from .models import ActiveExtension data = await self._http.put_user_extensions(token, extensions._to_dict()) return {typ: {int(n): ActiveExtension(d) for n, d in vals.items()} for typ, vals in data.items()}
[ "async", "def", "update_extensions", "(", "self", ",", "token", ":", "str", ",", "extensions", ":", "\"ExtensionBuilder\"", ")", ":", "from", ".", "models", "import", "ActiveExtension", "data", "=", "await", "self", ".", "_http", ".", "put_user_extensions", "(...
https://github.com/TwitchIO/TwitchIO/blob/b5eb585b9b52d4966784f0d1ae947077a90ec0c7/twitchio/user.py#L595-L614
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/lib/family.py
python
Family.get_handle_referents
(self)
return self.media_list + self.attribute_list + \ self.lds_ord_list + self.child_ref_list + self.event_ref_list
Return the list of child objects which may, directly or through their children, reference primary objects.. :returns: Returns the list of objects referencing primary objects. :rtype: list
Return the list of child objects which may, directly or through their children, reference primary objects..
[ "Return", "the", "list", "of", "child", "objects", "which", "may", "directly", "or", "through", "their", "children", "reference", "primary", "objects", ".." ]
def get_handle_referents(self): """ Return the list of child objects which may, directly or through their children, reference primary objects.. :returns: Returns the list of objects referencing primary objects. :rtype: list """ return self.media_list + self.attribute_list + \ self.lds_ord_list + self.child_ref_list + self.event_ref_list
[ "def", "get_handle_referents", "(", "self", ")", ":", "return", "self", ".", "media_list", "+", "self", ".", "attribute_list", "+", "self", ".", "lds_ord_list", "+", "self", ".", "child_ref_list", "+", "self", ".", "event_ref_list" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/lib/family.py#L383-L392
bookwyrm-social/bookwyrm
0c2537e27a2cdbc0136880dfbbf170d5fec72986
bookwyrm/models/activitypub_mixin.py
python
OrderedCollectionPageMixin.to_ordered_collection
( self, queryset, remote_id=None, page=False, collection_only=False, **kwargs )
return serializer(**activity)
an ordered collection of whatevers
an ordered collection of whatevers
[ "an", "ordered", "collection", "of", "whatevers" ]
def to_ordered_collection( self, queryset, remote_id=None, page=False, collection_only=False, **kwargs ): """an ordered collection of whatevers""" if not queryset.ordered: raise RuntimeError("queryset must be ordered") remote_id = remote_id or self.remote_id if page: if isinstance(page, list) and len(page) > 0: page = page[0] return to_ordered_collection_page(queryset, remote_id, page=page, **kwargs) if collection_only or not hasattr(self, "activity_serializer"): serializer = activitypub.OrderedCollection activity = {} else: serializer = self.activity_serializer # a dict from the model fields activity = generate_activity(self) if remote_id: activity["id"] = remote_id paginated = Paginator(queryset, PAGE_LENGTH) # add computed fields specific to orderd collections activity["totalItems"] = paginated.count activity["first"] = f"{remote_id}?page=1" activity["last"] = f"{remote_id}?page={paginated.num_pages}" return serializer(**activity)
[ "def", "to_ordered_collection", "(", "self", ",", "queryset", ",", "remote_id", "=", "None", ",", "page", "=", "False", ",", "collection_only", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "queryset", ".", "ordered", ":", "raise", "Runti...
https://github.com/bookwyrm-social/bookwyrm/blob/0c2537e27a2cdbc0136880dfbbf170d5fec72986/bookwyrm/models/activitypub_mixin.py#L316-L346
InsaneLife/dssm
1d32e137654e03994f7ba6cfde52e1d47601027c
util.py
python
_truncate_seq_pair
(tokens_a, tokens_b, max_length)
Truncates a sequence pair in place to the maximum length.
Truncates a sequence pair in place to the maximum length.
[ "Truncates", "a", "sequence", "pair", "in", "place", "to", "the", "maximum", "length", "." ]
def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_length: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop()
[ "def", "_truncate_seq_pair", "(", "tokens_a", ",", "tokens_b", ",", "max_length", ")", ":", "while", "True", ":", "total_length", "=", "len", "(", "tokens_a", ")", "+", "len", "(", "tokens_b", ")", "if", "total_length", "<=", "max_length", ":", "break", "i...
https://github.com/InsaneLife/dssm/blob/1d32e137654e03994f7ba6cfde52e1d47601027c/util.py#L47-L56
nil0x42/phpsploit
ee83c3260616a874877a904e732408b915ff272e
src/core/session/settings/REQ_ZLIB_TRY_LIMIT.py
python
default_value
()
return "20 MiB"
[]
def default_value(): return "20 MiB"
[ "def", "default_value", "(", ")", ":", "return", "\"20 MiB\"" ]
https://github.com/nil0x42/phpsploit/blob/ee83c3260616a874877a904e732408b915ff272e/src/core/session/settings/REQ_ZLIB_TRY_LIMIT.py#L31-L32
quantumlib/OpenFermion
6187085f2a7707012b68370b625acaeed547e62b
src/openfermion/chem/molecular_data.py
python
MolecularData.get_active_space_integrals
(self, occupied_indices=None, active_indices=None)
return reps.get_active_space_integrals(one_body_integrals, two_body_integrals, occupied_indices, active_indices)
Restricts a molecule at a spatial orbital level to an active space This active space may be defined by a list of active indices and doubly occupied indices. Note that one_body_integrals and two_body_integrals must be defined n an orthonormal basis set. Args: occupied_indices: A list of spatial orbital indices indicating which orbitals should be considered doubly occupied. active_indices: A list of spatial orbital indices indicating which orbitals should be considered active. Returns: tuple: Tuple with the following entries: **core_constant**: Adjustment to constant shift in Hamiltonian from integrating out core orbitals **one_body_integrals_new**: one-electron integrals over active space. **two_body_integrals_new**: two-electron integrals over active space.
Restricts a molecule at a spatial orbital level to an active space
[ "Restricts", "a", "molecule", "at", "a", "spatial", "orbital", "level", "to", "an", "active", "space" ]
def get_active_space_integrals(self, occupied_indices=None, active_indices=None): """Restricts a molecule at a spatial orbital level to an active space This active space may be defined by a list of active indices and doubly occupied indices. Note that one_body_integrals and two_body_integrals must be defined n an orthonormal basis set. Args: occupied_indices: A list of spatial orbital indices indicating which orbitals should be considered doubly occupied. active_indices: A list of spatial orbital indices indicating which orbitals should be considered active. Returns: tuple: Tuple with the following entries: **core_constant**: Adjustment to constant shift in Hamiltonian from integrating out core orbitals **one_body_integrals_new**: one-electron integrals over active space. **two_body_integrals_new**: two-electron integrals over active space. """ # Fix data type for a few edge cases occupied_indices = [] if occupied_indices is None else occupied_indices if (len(active_indices) < 1): raise ValueError('Some active indices required for reduction.') # Get integrals. one_body_integrals, two_body_integrals = self.get_integrals() return reps.get_active_space_integrals(one_body_integrals, two_body_integrals, occupied_indices, active_indices)
[ "def", "get_active_space_integrals", "(", "self", ",", "occupied_indices", "=", "None", ",", "active_indices", "=", "None", ")", ":", "# Fix data type for a few edge cases", "occupied_indices", "=", "[", "]", "if", "occupied_indices", "is", "None", "else", "occupied_i...
https://github.com/quantumlib/OpenFermion/blob/6187085f2a7707012b68370b625acaeed547e62b/src/openfermion/chem/molecular_data.py#L839-L876
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/ldap3/extend/microsoft/dirSync.py
python
DirSync.loop
(self)
[]
def loop(self): result = self.connection.search(search_base=self.base, search_filter=self.filter, search_scope=SUBTREE, attributes=self.attributes, dereference_aliases=DEREF_NEVER, controls=[dir_sync_control(criticality=True, object_security=self.object_security, ancestors_first=self.ancestors_first, public_data_only=self.public_data_only, incremental_values=self.incremental_values, max_length=self.max_length, cookie=self.cookie), extended_dn_control(criticality=False, hex_format=self.hex_guid), show_deleted_control(criticality=False)] ) if not self.connection.strategy.sync: response, result = self.connection.get_response(result) else: response = self.connection.response result = self.connection.result if result['description'] == 'success' and 'controls' in result and '1.2.840.113556.1.4.841' in result['controls']: self.more_results = result['controls']['1.2.840.113556.1.4.841']['value']['more_results'] self.cookie = result['controls']['1.2.840.113556.1.4.841']['value']['cookie'] return response elif 'controls' in result: raise LDAPExtensionError('Missing DirSync control in response from server') else: raise LDAPExtensionError('error %r in DirSync' % result)
[ "def", "loop", "(", "self", ")", ":", "result", "=", "self", ".", "connection", ".", "search", "(", "search_base", "=", "self", ".", "base", ",", "search_filter", "=", "self", ".", "filter", ",", "search_scope", "=", "SUBTREE", ",", "attributes", "=", ...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/ldap3/extend/microsoft/dirSync.py#L62-L90
morganstanley/treadmill
f18267c665baf6def4374d21170198f63ff1cde4
lib/python/treadmill/cli/app_dns.py
python
init
()
return appdns
Configures App DNS
Configures App DNS
[ "Configures", "App", "DNS" ]
def init(): """Configures App DNS """ # pylint: disable=too-many-statements formatter = cli.make_formatter('app-dns') @click.group(name='app-dns') def appdns(): """Manage Treadmill App DNS configuration. """ def configure_base(name, cell, pattern, endpoints, alias, scope, id_group): """Create, modify or get Treadmill App DNS entry""" restapi = context.GLOBAL.admin_api() url = _REST_PATH + name data = {} if cell: data['cells'] = cell if pattern is not None: data['pattern'] = pattern if endpoints is not None: data['endpoints'] = endpoints if alias is not None: data['alias'] = alias if scope is not None: data['scope'] = scope if id_group is not None: data['identity-group'] = id_group if data: try: _LOGGER.debug('Trying to create app-dns entry %s', name) restclient.post(restapi, url, data) except restclient.AlreadyExistsError: _LOGGER.debug('Updating app-dns entry %s', name) restclient.put(restapi, url, data) _LOGGER.debug('Retrieving App DNS entry %s', name) app_dns_entry = restclient.get(restapi, url).json() cli.out(formatter(app_dns_entry)) @appdns.command() @click.argument('name', nargs=1, required=True) @click.option('--cell', help='List of cells', type=cli.LIST) @click.option('--pattern', help='App pattern') @click.option('--endpoints', help='Endpoints to be included in SRV rec', type=cli.LIST) @click.option('--alias', help='App DNS alias') @click.option('--scope', help='DNS scope') @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def configure(name, cell, pattern, endpoints, alias, scope): """Create, modify or get DNS SRV entry""" configure_base(name, cell, pattern, endpoints, alias, scope, None) @appdns.group(name='cname') def cname(): """Manage DNS CNAME configuration. """ @cname.command(name='configure') @click.argument('name', nargs=1, required=True) @click.option('--cell', help='List of cells', type=cli.LIST) @click.option('--pattern', help='App pattern') @click.option('--alias', help='App DNS alias') @click.option('--scope', help='DNS scope') @click.option('--identity-group', 'id_group', help='Identity group to ' 'create alias(es) pointing to the instances\' hosts') @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def configure_cname(name, cell, pattern, alias, scope, id_group): """Create, modify or get DNS CNAME configuration""" configure_base(name, cell, pattern, None, alias, scope, id_group) @appdns.group(name='srv') def srv(): """Manage DNS SRV configuration. """ @srv.command(name='configure') @click.argument('name', nargs=1, required=True) @click.option('--cell', help='List of cells', type=cli.LIST) @click.option('--pattern', help='App pattern') @click.option('--endpoints', help='Endpoints to be included in SRV rec', type=cli.LIST) @click.option('--alias', help='App DNS alias') @click.option('--scope', help='DNS scope') @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def configure_srv(name, cell, pattern, endpoints, alias, scope): """Create, modify or get DNS SRV entry""" configure_base(name, cell, pattern, endpoints, alias, scope, None) @appdns.command() @click.argument('name', nargs=1, required=True) @click.option('--add', help='Cells to to add.', type=cli.LIST) @click.option('--remove', help='Cells to to remove.', type=cli.LIST) @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def cells(add, remove, name): """Add or remove cells from the app-dns.""" url = _REST_PATH + name restapi = context.GLOBAL.admin_api() existing = restclient.get(restapi, url).json() cells = set(existing['cells']) if add: cells.update(add) if remove: cells = cells - set(remove) if '_id' in existing: del existing['_id'] existing['cells'] = list(cells) restclient.put(restapi, url, existing) @appdns.command(name='list') @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def _list(): """List out App Group entries""" restapi = context.GLOBAL.admin_api() response = restclient.get(restapi, _REST_PATH) cli.out(formatter(response.json())) @appdns.command() @click.argument('name', nargs=1, required=True) @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def delete(name): """Delete Treadmill App Group entry""" restapi = context.GLOBAL.admin_api() url = _REST_PATH + name restclient.delete(restapi, url) del delete del cells del _list del configure del configure_cname del configure_srv del cname del srv return appdns
[ "def", "init", "(", ")", ":", "# pylint: disable=too-many-statements", "formatter", "=", "cli", ".", "make_formatter", "(", "'app-dns'", ")", "@", "click", ".", "group", "(", "name", "=", "'app-dns'", ")", "def", "appdns", "(", ")", ":", "\"\"\"Manage Treadmil...
https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/cli/app_dns.py#L22-L167
jupyterhub/jupyterhub
e58cf0670690d11631f9dc6e1ab702c60f7bfd13
jupyterhub/apihandlers/groups.py
python
GroupListAPIHandler.get
(self)
List groups
List groups
[ "List", "groups" ]
def get(self): """List groups""" query = full_query = self.db.query(orm.Group) sub_scope = self.parsed_scopes['list:groups'] if sub_scope != Scope.ALL: if not set(sub_scope).issubset({'group'}): # the only valid filter is group=... # don't expand invalid !server=x to all groups! self.log.warning( "Invalid filter on list:group for {self.current_user}: {sub_scope}" ) raise web.HTTPError(403) query = query.filter(orm.Group.name.in_(sub_scope['group'])) offset, limit = self.get_api_pagination() query = query.order_by(orm.Group.id.asc()).offset(offset).limit(limit) group_list = [self.group_model(g) for g in query] total_count = full_query.count() if self.accepts_pagination: data = self.paginated_model(group_list, offset, limit, total_count) else: query_count = query.count() if offset == 0 and total_count > query_count: self.log.warning( f"Truncated group list in request that does not expect pagination. Replying with {query_count} of {total_count} total groups." ) data = group_list self.write(json.dumps(data))
[ "def", "get", "(", "self", ")", ":", "query", "=", "full_query", "=", "self", ".", "db", ".", "query", "(", "orm", ".", "Group", ")", "sub_scope", "=", "self", ".", "parsed_scopes", "[", "'list:groups'", "]", "if", "sub_scope", "!=", "Scope", ".", "A...
https://github.com/jupyterhub/jupyterhub/blob/e58cf0670690d11631f9dc6e1ab702c60f7bfd13/jupyterhub/apihandlers/groups.py#L39-L66
python-telegram-bot/python-telegram-bot
ade1529986f5b6d394a65372d6a27045a70725b2
telegram/ext/filters.py
python
BaseFilter.__or__
(self, other: 'BaseFilter')
return MergedFilter(self, or_filter=other)
[]
def __or__(self, other: 'BaseFilter') -> 'BaseFilter': return MergedFilter(self, or_filter=other)
[ "def", "__or__", "(", "self", ",", "other", ":", "'BaseFilter'", ")", "->", "'BaseFilter'", ":", "return", "MergedFilter", "(", "self", ",", "or_filter", "=", "other", ")" ]
https://github.com/python-telegram-bot/python-telegram-bot/blob/ade1529986f5b6d394a65372d6a27045a70725b2/telegram/ext/filters.py#L135-L136
masthoon/pwintools
e62634e99bf33d6745d8c642d3c7f028699c1958
pwintools.py
python
Remote.recvline
(self, keepends = True, timeout = None)
return self.recvuntil(self.newline, not keepends, timeout)
recvline(keepends = True, timeout = None) reads one line on the socket before timeout
recvline(keepends = True, timeout = None) reads one line on the socket before timeout
[ "recvline", "(", "keepends", "=", "True", "timeout", "=", "None", ")", "reads", "one", "line", "on", "the", "socket", "before", "timeout" ]
def recvline(self, keepends = True, timeout = None): """recvline(keepends = True, timeout = None) reads one line on the socket before timeout""" return self.recvuntil(self.newline, not keepends, timeout)
[ "def", "recvline", "(", "self", ",", "keepends", "=", "True", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "recvuntil", "(", "self", ".", "newline", ",", "not", "keepends", ",", "timeout", ")" ]
https://github.com/masthoon/pwintools/blob/e62634e99bf33d6745d8c642d3c7f028699c1958/pwintools.py#L611-L613
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/decimal.py
python
Context.max_mag
(self, a, b)
return a.max_mag(b, context=self)
Compares the values numerically with their sign ignored. >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) Decimal('-10') >>> ExtendedContext.max_mag(1, -2) Decimal('-2') >>> ExtendedContext.max_mag(Decimal(1), -2) Decimal('-2') >>> ExtendedContext.max_mag(1, Decimal(-2)) Decimal('-2')
Compares the values numerically with their sign ignored.
[ "Compares", "the", "values", "numerically", "with", "their", "sign", "ignored", "." ]
def max_mag(self, a, b): """Compares the values numerically with their sign ignored. >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) Decimal('7') >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) Decimal('-10') >>> ExtendedContext.max_mag(1, -2) Decimal('-2') >>> ExtendedContext.max_mag(Decimal(1), -2) Decimal('-2') >>> ExtendedContext.max_mag(1, Decimal(-2)) Decimal('-2') """ a = _convert_other(a, raiseit=True) return a.max_mag(b, context=self)
[ "def", "max_mag", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "max_mag", "(", "b", ",", "context", "=", "self", ")" ]
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/decimal.py#L4870-L4885
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/hachoir_core/tools.py
python
alignValue
(value, align)
Align a value to next 'align' multiple. >>> alignValue(31, 4) 32 >>> alignValue(32, 4) 32 >>> alignValue(33, 4) 36 Note: alignValue(value, align) == (value + paddingSize(value, align))
Align a value to next 'align' multiple.
[ "Align", "a", "value", "to", "next", "align", "multiple", "." ]
def alignValue(value, align): """ Align a value to next 'align' multiple. >>> alignValue(31, 4) 32 >>> alignValue(32, 4) 32 >>> alignValue(33, 4) 36 Note: alignValue(value, align) == (value + paddingSize(value, align)) """ if value % align != 0: return value + align - (value % align) else: return value
[ "def", "alignValue", "(", "value", ",", "align", ")", ":", "if", "value", "%", "align", "!=", "0", ":", "return", "value", "+", "align", "-", "(", "value", "%", "align", ")", "else", ":", "return", "value" ]
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/hachoir_core/tools.py#L60-L77
davepeck/game-of-go
a75267f9ba0f47beda7a490824d99e0f5cf91f7b
www/go.py
python
GameBoard.is_dead
(self, x, y, color=CONST.Both_Colors)
return self.is_stone_of_color(x, y, color)
[]
def is_dead(self, x, y, color=CONST.Both_Colors): if self.get_owner(x, y) == CONST.No_Color: return False return self.is_stone_of_color(x, y, color)
[ "def", "is_dead", "(", "self", ",", "x", ",", "y", ",", "color", "=", "CONST", ".", "Both_Colors", ")", ":", "if", "self", ".", "get_owner", "(", "x", ",", "y", ")", "==", "CONST", ".", "No_Color", ":", "return", "False", "return", "self", ".", "...
https://github.com/davepeck/game-of-go/blob/a75267f9ba0f47beda7a490824d99e0f5cf91f7b/www/go.py#L386-L389
SCSSoftware/BlenderTools
96f323d3bdf2d8cb8ed7f882dcdf036277a802dd
addon/io_scs_tools/exp/pip/curve.py
python
Curve.set_length
(self, value)
Set curve length. :param value: curve length :type value: float
Set curve length.
[ "Set", "curve", "length", "." ]
def set_length(self, value): """Set curve length. :param value: curve length :type value: float """ self.__length = value
[ "def", "set_length", "(", "self", ",", "value", ")", ":", "self", ".", "__length", "=", "value" ]
https://github.com/SCSSoftware/BlenderTools/blob/96f323d3bdf2d8cb8ed7f882dcdf036277a802dd/addon/io_scs_tools/exp/pip/curve.py#L245-L251
mikgroup/sigpy
85739eee0a2db4c14074b670e63e36de0cc5a8f2
sigpy/mri/samp.py
python
poisson
(img_shape, accel, calib=(0, 0), dtype=np.complex, crop_corner=True, return_density=False, seed=0, max_attempts=30, tol=0.1)
return mask
Generate variable-density Poisson-disc sampling pattern. The function generates a variable density Poisson-disc sampling mask with density proportional to :math:`1 / (1 + s |r|)`, where :math:`r` represents the k-space radius, and :math:`s` represents the slope. A binary search is performed on the slope :math:`s` such that the resulting acceleration factor is close to the prescribed acceleration factor `accel`. The parameter `tol` determines how much they can deviate. Args: img_shape (tuple of ints): length-2 image shape. accel (float): Target acceleration factor. Must be greater than 1. calib (tuple of ints): length-2 calibration shape. dtype (Dtype): data type. crop_corner (bool): Toggle whether to crop sampling corners. seed (int): Random seed. max_attempts (float): maximum number of samples to reject in Poisson disc calculation. tol (float): Tolerance for how much the resulting acceleration can deviate form `accel`. Returns: array: Poisson-disc sampling mask. References: Bridson, Robert. "Fast Poisson disk sampling in arbitrary dimensions." SIGGRAPH sketches. 2007.
Generate variable-density Poisson-disc sampling pattern.
[ "Generate", "variable", "-", "density", "Poisson", "-", "disc", "sampling", "pattern", "." ]
def poisson(img_shape, accel, calib=(0, 0), dtype=np.complex, crop_corner=True, return_density=False, seed=0, max_attempts=30, tol=0.1): """Generate variable-density Poisson-disc sampling pattern. The function generates a variable density Poisson-disc sampling mask with density proportional to :math:`1 / (1 + s |r|)`, where :math:`r` represents the k-space radius, and :math:`s` represents the slope. A binary search is performed on the slope :math:`s` such that the resulting acceleration factor is close to the prescribed acceleration factor `accel`. The parameter `tol` determines how much they can deviate. Args: img_shape (tuple of ints): length-2 image shape. accel (float): Target acceleration factor. Must be greater than 1. calib (tuple of ints): length-2 calibration shape. dtype (Dtype): data type. crop_corner (bool): Toggle whether to crop sampling corners. seed (int): Random seed. max_attempts (float): maximum number of samples to reject in Poisson disc calculation. tol (float): Tolerance for how much the resulting acceleration can deviate form `accel`. Returns: array: Poisson-disc sampling mask. References: Bridson, Robert. "Fast Poisson disk sampling in arbitrary dimensions." SIGGRAPH sketches. 2007. """ if accel <= 1: raise ValueError(f'accel must be greater than 1, got {accel}') if seed is not None: rand_state = np.random.get_state() ny, nx = img_shape y, x = np.mgrid[:ny, :nx] x = np.maximum(abs(x - img_shape[-1] / 2) - calib[-1] / 2, 0) x /= x.max() y = np.maximum(abs(y - img_shape[-2] / 2) - calib[-2] / 2, 0) y /= y.max() r = np.sqrt(x**2 + y**2) slope_max = max(nx, ny) slope_min = 0 while slope_min < slope_max: slope = (slope_max + slope_min) / 2 radius_x = np.clip((1 + r * slope) * nx / max(nx, ny), 1, None) radius_y = np.clip((1 + r * slope) * ny / max(nx, ny), 1, None) mask = _poisson( img_shape[-1], img_shape[-2], max_attempts, radius_x, radius_y, calib, seed) if crop_corner: mask *= r < 1 actual_accel = img_shape[-1] * img_shape[-2] / np.sum(mask) if abs(actual_accel - accel) < tol: break if actual_accel < accel: slope_min = slope else: slope_max = slope if abs(actual_accel - accel) >= tol: raise ValueError(f'Cannot generate mask to satisfy accel={accel}.') mask = mask.reshape(img_shape).astype(dtype) if seed is not None: np.random.set_state(rand_state) return mask
[ "def", "poisson", "(", "img_shape", ",", "accel", ",", "calib", "=", "(", "0", ",", "0", ")", ",", "dtype", "=", "np", ".", "complex", ",", "crop_corner", "=", "True", ",", "return_density", "=", "False", ",", "seed", "=", "0", ",", "max_attempts", ...
https://github.com/mikgroup/sigpy/blob/85739eee0a2db4c14074b670e63e36de0cc5a8f2/sigpy/mri/samp.py#L11-L87
zhang-can/ECO-pytorch
355c3866b35cdaa5d451263c1f3291c150e22eeb
tf_model_zoo/models/im2txt/im2txt/show_and_tell_model.py
python
ShowAndTellModel.build_inputs
(self)
Input prefetching, preprocessing and batching. Outputs: self.images self.input_seqs self.target_seqs (training and eval only) self.input_mask (training and eval only)
Input prefetching, preprocessing and batching.
[ "Input", "prefetching", "preprocessing", "and", "batching", "." ]
def build_inputs(self): """Input prefetching, preprocessing and batching. Outputs: self.images self.input_seqs self.target_seqs (training and eval only) self.input_mask (training and eval only) """ if self.mode == "inference": # In inference mode, images and inputs are fed via placeholders. image_feed = tf.placeholder(dtype=tf.string, shape=[], name="image_feed") input_feed = tf.placeholder(dtype=tf.int64, shape=[None], # batch_size name="input_feed") # Process image and insert batch dimensions. images = tf.expand_dims(self.process_image(image_feed), 0) input_seqs = tf.expand_dims(input_feed, 1) # No target sequences or input mask in inference mode. target_seqs = None input_mask = None else: # Prefetch serialized SequenceExample protos. input_queue = input_ops.prefetch_input_data( self.reader, self.config.input_file_pattern, is_training=self.is_training(), batch_size=self.config.batch_size, values_per_shard=self.config.values_per_input_shard, input_queue_capacity_factor=self.config.input_queue_capacity_factor, num_reader_threads=self.config.num_input_reader_threads) # Image processing and random distortion. Split across multiple threads # with each thread applying a slightly different distortion. assert self.config.num_preprocess_threads % 2 == 0 images_and_captions = [] for thread_id in range(self.config.num_preprocess_threads): serialized_sequence_example = input_queue.dequeue() encoded_image, caption = input_ops.parse_sequence_example( serialized_sequence_example, image_feature=self.config.image_feature_name, caption_feature=self.config.caption_feature_name) image = self.process_image(encoded_image, thread_id=thread_id) images_and_captions.append([image, caption]) # Batch inputs. queue_capacity = (2 * self.config.num_preprocess_threads * self.config.batch_size) images, input_seqs, target_seqs, input_mask = ( input_ops.batch_with_dynamic_pad(images_and_captions, batch_size=self.config.batch_size, queue_capacity=queue_capacity)) self.images = images self.input_seqs = input_seqs self.target_seqs = target_seqs self.input_mask = input_mask
[ "def", "build_inputs", "(", "self", ")", ":", "if", "self", ".", "mode", "==", "\"inference\"", ":", "# In inference mode, images and inputs are fed via placeholders.", "image_feed", "=", "tf", ".", "placeholder", "(", "dtype", "=", "tf", ".", "string", ",", "shap...
https://github.com/zhang-can/ECO-pytorch/blob/355c3866b35cdaa5d451263c1f3291c150e22eeb/tf_model_zoo/models/im2txt/im2txt/show_and_tell_model.py#L121-L179
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/polys/rings.py
python
PolyElement.diff
(f, x)
return g
Computes partial derivative in ``x``. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring("x,y", ZZ) >>> p = x + x**2*y**3 >>> p.diff(x) 2*x*y**3 + 1
Computes partial derivative in ``x``.
[ "Computes", "partial", "derivative", "in", "x", "." ]
def diff(f, x): """Computes partial derivative in ``x``. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring("x,y", ZZ) >>> p = x + x**2*y**3 >>> p.diff(x) 2*x*y**3 + 1 """ ring = f.ring i = ring.index(x) m = ring.monomial_basis(i) g = ring.zero for expv, coeff in f.iterterms(): if expv[i]: e = ring.monomial_ldiv(expv, m) g[e] = ring.domain_new(coeff*expv[i]) return g
[ "def", "diff", "(", "f", ",", "x", ")", ":", "ring", "=", "f", ".", "ring", "i", "=", "ring", ".", "index", "(", "x", ")", "m", "=", "ring", ".", "monomial_basis", "(", "i", ")", "g", "=", "ring", ".", "zero", "for", "expv", ",", "coeff", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/polys/rings.py#L2252-L2275
researchmm/SiamDW
c82b0599920e1fbd67ada9271aa4a63405e2d316
lib/models/modules.py
python
ResNet._make_layer
(self, block, planes, blocks, last_relu, stride=1, stride2pool=False, dilation=1)
return nn.Sequential(*layers)
:param block: :param planes: :param blocks: :param stride: :param stride2pool: translate (3,2) conv to (3, 1)conv + (2, 2)pool :return:
:param block: :param planes: :param blocks: :param stride: :param stride2pool: translate (3,2) conv to (3, 1)conv + (2, 2)pool :return:
[ ":", "param", "block", ":", ":", "param", "planes", ":", ":", "param", "blocks", ":", ":", "param", "stride", ":", ":", "param", "stride2pool", ":", "translate", "(", "3", "2", ")", "conv", "to", "(", "3", "1", ")", "conv", "+", "(", "2", "2", ...
def _make_layer(self, block, planes, blocks, last_relu, stride=1, stride2pool=False, dilation=1): """ :param block: :param planes: :param blocks: :param stride: :param stride2pool: translate (3,2) conv to (3, 1)conv + (2, 2)pool :return: """ downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, last_relu=True, stride=stride, downsample=downsample, dilation=dilation)) if stride2pool: layers.append(self.maxpool) self.inplanes = planes * block.expansion for i in range(1, blocks): if i == blocks - 1: layers.append(block(self.inplanes, planes, last_relu=last_relu, dilation=dilation)) else: layers.append(block(self.inplanes, planes, last_relu=True, dilation=dilation)) return nn.Sequential(*layers)
[ "def", "_make_layer", "(", "self", ",", "block", ",", "planes", ",", "blocks", ",", "last_relu", ",", "stride", "=", "1", ",", "stride2pool", "=", "False", ",", "dilation", "=", "1", ")", ":", "downsample", "=", "None", "if", "stride", "!=", "1", "or...
https://github.com/researchmm/SiamDW/blob/c82b0599920e1fbd67ada9271aa4a63405e2d316/lib/models/modules.py#L193-L221
lunixbochs/ActualVim
1f555ce719e49d6584f0e35e9f0db2f216b98fa5
lib/neovim/msgpack_rpc/session.py
python
Session.threadsafe_call
(self, fn, *args, **kwargs)
Wrapper around `AsyncSession.threadsafe_call`.
Wrapper around `AsyncSession.threadsafe_call`.
[ "Wrapper", "around", "AsyncSession", ".", "threadsafe_call", "." ]
def threadsafe_call(self, fn, *args, **kwargs): """Wrapper around `AsyncSession.threadsafe_call`.""" def async_wrapper(): self.async_dispatch(fn, *args, **kwargs) self._async_session.threadsafe_call(async_wrapper)
[ "def", "threadsafe_call", "(", "self", ",", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "async_wrapper", "(", ")", ":", "self", ".", "async_dispatch", "(", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "...
https://github.com/lunixbochs/ActualVim/blob/1f555ce719e49d6584f0e35e9f0db2f216b98fa5/lib/neovim/msgpack_rpc/session.py#L44-L48
ranaroussi/quantstats
6aaa65c20bad4c364efa7623375901925c036b45
quantstats/stats.py
python
sortino
(returns, rf=0, periods=252, annualize=True, smart=False)
return res
Calculates the sortino ratio of access returns If rf is non-zero, you must specify periods. In this case, rf is assumed to be expressed in yearly (annualized) terms Calculation is based on this paper by Red Rock Capital http://www.redrockcapital.com/Sortino__A__Sharper__Ratio_Red_Rock_Capital.pdf
Calculates the sortino ratio of access returns
[ "Calculates", "the", "sortino", "ratio", "of", "access", "returns" ]
def sortino(returns, rf=0, periods=252, annualize=True, smart=False): """ Calculates the sortino ratio of access returns If rf is non-zero, you must specify periods. In this case, rf is assumed to be expressed in yearly (annualized) terms Calculation is based on this paper by Red Rock Capital http://www.redrockcapital.com/Sortino__A__Sharper__Ratio_Red_Rock_Capital.pdf """ if rf != 0 and periods is None: raise Exception('Must provide periods if rf != 0') returns = _utils._prepare_returns(returns, rf, periods) downside = _np.sqrt((returns[returns < 0] ** 2).sum() / len(returns)) if smart: # penalize sortino with auto correlation downside = downside * autocorr_penalty(returns) res = returns.mean() / downside if annualize: return res * _np.sqrt( 1 if periods is None else periods) return res
[ "def", "sortino", "(", "returns", ",", "rf", "=", "0", ",", "periods", "=", "252", ",", "annualize", "=", "True", ",", "smart", "=", "False", ")", ":", "if", "rf", "!=", "0", "and", "periods", "is", "None", ":", "raise", "Exception", "(", "'Must pr...
https://github.com/ranaroussi/quantstats/blob/6aaa65c20bad4c364efa7623375901925c036b45/quantstats/stats.py#L326-L353
ninthDevilHAUNSTER/ArknightsAutoHelper
a27a930502d6e432368d9f62595a1d69a992f4e6
vendor/penguin_client/penguin_client/models/exist_conditions.py
python
ExistConditions.to_str
(self)
return pprint.pformat(self.to_dict())
Returns the string representation of the model
Returns the string representation of the model
[ "Returns", "the", "string", "representation", "of", "the", "model" ]
def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict())
[ "def", "to_str", "(", "self", ")", ":", "return", "pprint", ".", "pformat", "(", "self", ".", "to_dict", "(", ")", ")" ]
https://github.com/ninthDevilHAUNSTER/ArknightsAutoHelper/blob/a27a930502d6e432368d9f62595a1d69a992f4e6/vendor/penguin_client/penguin_client/models/exist_conditions.py#L105-L107
tomoncle/Python-notes
ce675486290c3d1c7c2e4890b57e3d0c8a1228cc
skills/httpserver.py
python
simple_app
(environ, start_response)
return ['Hello world!\n']
[]
def simple_app(environ, start_response): status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) # print environ, start_response return ['Hello world!\n']
[ "def", "simple_app", "(", "environ", ",", "start_response", ")", ":", "status", "=", "'200 OK'", "response_headers", "=", "[", "(", "'Content-type'", ",", "'text/plain'", ")", "]", "start_response", "(", "status", ",", "response_headers", ")", "# print environ, st...
https://github.com/tomoncle/Python-notes/blob/ce675486290c3d1c7c2e4890b57e3d0c8a1228cc/skills/httpserver.py#L22-L27
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/compilers/c.py
python
GnuCCompiler.get_pch_use_args
(self, pch_dir: str, header: str)
return ['-fpch-preprocess', '-include', os.path.basename(header)]
[]
def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]: return ['-fpch-preprocess', '-include', os.path.basename(header)]
[ "def", "get_pch_use_args", "(", "self", ",", "pch_dir", ":", "str", ",", "header", ":", "str", ")", "->", "T", ".", "List", "[", "str", "]", ":", "return", "[", "'-fpch-preprocess'", ",", "'-include'", ",", "os", ".", "path", ".", "basename", "(", "h...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/compilers/c.py#L303-L304
mjwestcott/Goodrich
dc2516591bd28488516c0337a62e64248debe47c
ch14/graph_examples.py
python
graph_from_edgelist
(E, directed=False)
return g
Make a graph instance based on a sequence of edge tuples. Edges can be either of from (origin,destination) or (origin,destination,element). Vertex set is presume to be those incident to at least one edge. vertex labels are assumed to be hashable.
Make a graph instance based on a sequence of edge tuples.
[ "Make", "a", "graph", "instance", "based", "on", "a", "sequence", "of", "edge", "tuples", "." ]
def graph_from_edgelist(E, directed=False): """Make a graph instance based on a sequence of edge tuples. Edges can be either of from (origin,destination) or (origin,destination,element). Vertex set is presume to be those incident to at least one edge. vertex labels are assumed to be hashable. """ g = Graph(directed) V = set() for e in E: V.add(e[0]) V.add(e[1]) verts = {} # map from vertex label to Vertex instance for v in V: verts[v] = g.insert_vertex(v) for e in E: src = e[0] dest = e[1] element = e[2] if len(e) > 2 else None g.insert_edge(verts[src],verts[dest],element) return g
[ "def", "graph_from_edgelist", "(", "E", ",", "directed", "=", "False", ")", ":", "g", "=", "Graph", "(", "directed", ")", "V", "=", "set", "(", ")", "for", "e", "in", "E", ":", "V", ".", "add", "(", "e", "[", "0", "]", ")", "V", ".", "add", ...
https://github.com/mjwestcott/Goodrich/blob/dc2516591bd28488516c0337a62e64248debe47c/ch14/graph_examples.py#L24-L49
baidu/Senta
e5294c00a6ffc4b1284f38000f0fbf24d6554c22
senta/data/data_set_reader/roberta_pretrain_dataset_reader_en.py
python
RobertaPretrainDataReaderEnglish.create_reader
(self)
return py_reader
初始化paddle_py_reader,必须要初始化,否则会抛出异常 create reader 定义的这些 dtypes 要和 prepare_batch_data 一一对应 :return:
初始化paddle_py_reader,必须要初始化,否则会抛出异常 create reader 定义的这些 dtypes 要和 prepare_batch_data 一一对应 :return:
[ "初始化paddle_py_reader,必须要初始化,否则会抛出异常", "create", "reader", "定义的这些", "dtypes", "要和", "prepare_batch_data", "一一对应", ":", "return", ":" ]
def create_reader(self): """ 初始化paddle_py_reader,必须要初始化,否则会抛出异常 create reader 定义的这些 dtypes 要和 prepare_batch_data 一一对应 :return: """ py_reader = fluid.layers.py_reader( capacity=70, shapes=[f.shape for f in self.data_types.values()], dtypes=[f.dtype for f in self.data_types.values()], lod_levels=[f.lod_level for f in self.data_types.values()], name=self.pyreader_name, use_double_buffer=True) self.paddle_py_reader = py_reader self.fields_dict_ = collections.OrderedDict() input_placeholders = fluid.layers.read_file(py_reader) assert len(input_placeholders) == len(self.data_types) for op, (name, _) in zip(input_placeholders, self.data_types.items()): self.fields_dict_[name] = op return py_reader
[ "def", "create_reader", "(", "self", ")", ":", "py_reader", "=", "fluid", ".", "layers", ".", "py_reader", "(", "capacity", "=", "70", ",", "shapes", "=", "[", "f", ".", "shape", "for", "f", "in", "self", ".", "data_types", ".", "values", "(", ")", ...
https://github.com/baidu/Senta/blob/e5294c00a6ffc4b1284f38000f0fbf24d6554c22/senta/data/data_set_reader/roberta_pretrain_dataset_reader_en.py#L341-L363
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/nuomituangou/alp/request/bs4/element.py
python
Tag.decode
(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter="minimal")
return s
Returns a Unicode representation of this tag and its contents. :param eventual_encoding: The tag is destined to be encoded into this encoding. This method is _not_ responsible for performing that encoding. This information is passed in so that it can be substituted in if the document contains a <META> tag that mentions the document's encoding.
Returns a Unicode representation of this tag and its contents.
[ "Returns", "a", "Unicode", "representation", "of", "this", "tag", "and", "its", "contents", "." ]
def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter="minimal"): """Returns a Unicode representation of this tag and its contents. :param eventual_encoding: The tag is destined to be encoded into this encoding. This method is _not_ responsible for performing that encoding. This information is passed in so that it can be substituted in if the document contains a <META> tag that mentions the document's encoding. """ attrs = [] if self.attrs: for key, val in sorted(self.attrs.items()): if val is None: decoded = key else: if isinstance(val, list) or isinstance(val, tuple): val = ' '.join(val) elif not isinstance(val, basestring): val = unicode(val) elif ( isinstance(val, AttributeValueWithCharsetSubstitution) and eventual_encoding is not None): val = val.encode(eventual_encoding) text = self.format_string(val, formatter) decoded = ( unicode(key) + '=' + EntitySubstitution.quoted_attribute_value(text)) attrs.append(decoded) close = '' closeTag = '' prefix = '' if self.prefix: prefix = self.prefix + ":" if self.is_empty_element: close = '/' else: closeTag = '</%s%s>' % (prefix, self.name) pretty_print = (indent_level is not None) if pretty_print: space = (' ' * (indent_level - 1)) indent_contents = indent_level + 1 else: space = '' indent_contents = None contents = self.decode_contents( indent_contents, eventual_encoding, formatter) if self.hidden: # This is the 'document root' object. s = contents else: s = [] attribute_string = '' if attrs: attribute_string = ' ' + ' '.join(attrs) if pretty_print: s.append(space) s.append('<%s%s%s%s>' % ( prefix, self.name, attribute_string, close)) if pretty_print: s.append("\n") s.append(contents) if pretty_print and contents and contents[-1] != "\n": s.append("\n") if pretty_print and closeTag: s.append(space) s.append(closeTag) if pretty_print and closeTag and self.next_sibling: s.append("\n") s = ''.join(s) return s
[ "def", "decode", "(", "self", ",", "indent_level", "=", "None", ",", "eventual_encoding", "=", "DEFAULT_OUTPUT_ENCODING", ",", "formatter", "=", "\"minimal\"", ")", ":", "attrs", "=", "[", "]", "if", "self", ".", "attrs", ":", "for", "key", ",", "val", "...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/nuomituangou/alp/request/bs4/element.py#L969-L1046
log2timeline/plaso
fe2e316b8c76a0141760c0f2f181d84acb83abc2
plaso/filters/parser_filter.py
python
ParserFilterExpressionHelper._ExpandPresets
(self, presets_manager, preset_names, parsers_and_plugins)
Expands the presets in the parsers and plugins. This functions replaces the presets in parsers_and_plugins with the parser and plugin or preset names defined by the presets. Args: presets_manager (ParserPresetsManager): a parser preset manager, that is used to resolve which parsers and/or plugins are defined by presets. preset_names (set[str]): names of the presets defined by the presets manager. parsers_and_plugins (dict[str, set[str]]): parsers, plugins and presets.
Expands the presets in the parsers and plugins.
[ "Expands", "the", "presets", "in", "the", "parsers", "and", "plugins", "." ]
def _ExpandPresets(self, presets_manager, preset_names, parsers_and_plugins): """Expands the presets in the parsers and plugins. This functions replaces the presets in parsers_and_plugins with the parser and plugin or preset names defined by the presets. Args: presets_manager (ParserPresetsManager): a parser preset manager, that is used to resolve which parsers and/or plugins are defined by presets. preset_names (set[str]): names of the presets defined by the presets manager. parsers_and_plugins (dict[str, set[str]]): parsers, plugins and presets. """ for preset_name in preset_names: self._ExpandPreset(presets_manager, preset_name, parsers_and_plugins)
[ "def", "_ExpandPresets", "(", "self", ",", "presets_manager", ",", "preset_names", ",", "parsers_and_plugins", ")", ":", "for", "preset_name", "in", "preset_names", ":", "self", ".", "_ExpandPreset", "(", "presets_manager", ",", "preset_name", ",", "parsers_and_plug...
https://github.com/log2timeline/plaso/blob/fe2e316b8c76a0141760c0f2f181d84acb83abc2/plaso/filters/parser_filter.py#L133-L148
vrenkens/tfkaldi
30e8f7a32582a82a58cea66c2c52bcb66c06c326
neuralNetworks/trainer.py
python
Trainer.save_model
(self, filename)
Save the model Args: filename: path to the model file
Save the model
[ "Save", "the", "model" ]
def save_model(self, filename): ''' Save the model Args: filename: path to the model file ''' self.modelsaver.save(tf.get_default_session(), filename)
[ "def", "save_model", "(", "self", ",", "filename", ")", ":", "self", ".", "modelsaver", ".", "save", "(", "tf", ".", "get_default_session", "(", ")", ",", "filename", ")" ]
https://github.com/vrenkens/tfkaldi/blob/30e8f7a32582a82a58cea66c2c52bcb66c06c326/neuralNetworks/trainer.py#L448-L455
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/_vendor/urllib3/util/ssltransport.py
python
SSLTransport.recv_into
(self, buffer, nbytes=None, flags=0)
return self.read(nbytes, buffer)
[]
def recv_into(self, buffer, nbytes=None, flags=0): if flags != 0: raise ValueError("non-zero flags not allowed in calls to recv_into") if buffer and (nbytes is None): nbytes = len(buffer) elif nbytes is None: nbytes = 1024 return self.read(nbytes, buffer)
[ "def", "recv_into", "(", "self", ",", "buffer", ",", "nbytes", "=", "None", ",", "flags", "=", "0", ")", ":", "if", "flags", "!=", "0", ":", "raise", "ValueError", "(", "\"non-zero flags not allowed in calls to recv_into\"", ")", "if", "buffer", "and", "(", ...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/_vendor/urllib3/util/ssltransport.py#L85-L92
kedro-org/kedro
e78990c6b606a27830f0d502afa0f639c0830950
features/steps/cli_steps.py
python
commit_changes_to_git
(context)
Commit changes to git
Commit changes to git
[ "Commit", "changes", "to", "git" ]
def commit_changes_to_git(context): """Commit changes to git""" with util.chdir(context.root_project_dir): check_run(f"git commit -m 'Change {time()}'")
[ "def", "commit_changes_to_git", "(", "context", ")", ":", "with", "util", ".", "chdir", "(", "context", ".", "root_project_dir", ")", ":", "check_run", "(", "f\"git commit -m 'Change {time()}'\"", ")" ]
https://github.com/kedro-org/kedro/blob/e78990c6b606a27830f0d502afa0f639c0830950/features/steps/cli_steps.py#L318-L321
missionpinball/mpf
8e6b74cff4ba06d2fec9445742559c1068b88582
mpf/core/config_loader.py
python
ConfigLoader.load_mpf_config
(self)
Load and return a MPF config.
Load and return a MPF config.
[ "Load", "and", "return", "a", "MPF", "config", "." ]
def load_mpf_config(self) -> MpfConfig: """Load and return a MPF config."""
[ "def", "load_mpf_config", "(", "self", ")", "->", "MpfConfig", ":" ]
https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/core/config_loader.py#L124-L125
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/_vendor/distlib/util.py
python
is_string_sequence
(seq)
return result
[]
def is_string_sequence(seq): result = True i = None for i, s in enumerate(seq): if not isinstance(s, string_types): result = False break assert i is not None return result
[ "def", "is_string_sequence", "(", "seq", ")", ":", "result", "=", "True", "i", "=", "None", "for", "i", ",", "s", "in", "enumerate", "(", "seq", ")", ":", "if", "not", "isinstance", "(", "s", ",", "string_types", ")", ":", "result", "=", "False", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/distlib/util.py#L678-L686
OpenShot/openshot-qt
bbd2dd040a4e2a6120791e6c65ae0ddf212cb73d
src/classes/ui_util.py
python
get_icon
(theme_name)
return None
Get either the current theme icon or fallback to default theme (for custom icons). Returns None if none found or empty name.
Get either the current theme icon or fallback to default theme (for custom icons). Returns None if none found or empty name.
[ "Get", "either", "the", "current", "theme", "icon", "or", "fallback", "to", "default", "theme", "(", "for", "custom", "icons", ")", ".", "Returns", "None", "if", "none", "found", "or", "empty", "name", "." ]
def get_icon(theme_name): """Get either the current theme icon or fallback to default theme (for custom icons). Returns None if none found or empty name.""" if theme_name: has_icon = QIcon.hasThemeIcon(theme_name) fallback_icon, fallback_path = get_default_icon(theme_name) if has_icon or fallback_icon: return QIcon.fromTheme(theme_name, fallback_icon) return None
[ "def", "get_icon", "(", "theme_name", ")", ":", "if", "theme_name", ":", "has_icon", "=", "QIcon", ".", "hasThemeIcon", "(", "theme_name", ")", "fallback_icon", ",", "fallback_path", "=", "get_default_icon", "(", "theme_name", ")", "if", "has_icon", "or", "fal...
https://github.com/OpenShot/openshot-qt/blob/bbd2dd040a4e2a6120791e6c65ae0ddf212cb73d/src/classes/ui_util.py#L166-L175
tensorflow/datasets
2e496976d7d45550508395fb2f35cf958c8a3414
tensorflow_datasets/scripts/documentation/dataset_markdown_builder.py
python
Section.display
(self, builder: tfds.core.DatasetBuilder)
return content
Returns the section content.
Returns the section content.
[ "Returns", "the", "section", "content", "." ]
def display(self, builder: tfds.core.DatasetBuilder) -> str: """Returns the section content.""" content = self.content(builder) if content is _SKIP_SECTION: return '' header = f'* **{self.NAME}**{self.EXTRA_DOC}' is_block = isinstance(content, Block) if not isinstance(content, IntentedBlock): content = content.strip() # Note: `strip()` cast `Block` -> `str` if is_block: content = f'{header}:\n\n{content}\n\n' else: content = f'{header}: {content}\n\n' return content
[ "def", "display", "(", "self", ",", "builder", ":", "tfds", ".", "core", ".", "DatasetBuilder", ")", "->", "str", ":", "content", "=", "self", ".", "content", "(", "builder", ")", "if", "content", "is", "_SKIP_SECTION", ":", "return", "''", "header", "...
https://github.com/tensorflow/datasets/blob/2e496976d7d45550508395fb2f35cf958c8a3414/tensorflow_datasets/scripts/documentation/dataset_markdown_builder.py#L97-L110
oanda/v20-python
f28192f4a31bce038cf6dfa302f5878bec192fe5
src/v20/transaction.py
python
DelayedTradeClosureTransaction.__init__
(self, **kwargs)
Create a new DelayedTradeClosureTransaction instance
Create a new DelayedTradeClosureTransaction instance
[ "Create", "a", "new", "DelayedTradeClosureTransaction", "instance" ]
def __init__(self, **kwargs): """ Create a new DelayedTradeClosureTransaction instance """ super(DelayedTradeClosureTransaction, self).__init__() # # The Transaction's Identifier. # self.id = kwargs.get("id") # # The date/time when the Transaction was created. # self.time = kwargs.get("time") # # The ID of the user that initiated the creation of the Transaction. # self.userID = kwargs.get("userID") # # The ID of the Account the Transaction was created for. # self.accountID = kwargs.get("accountID") # # The ID of the "batch" that the Transaction belongs to. Transactions # in the same batch are applied to the Account simultaneously. # self.batchID = kwargs.get("batchID") # # The Request ID of the request which generated the transaction. # self.requestID = kwargs.get("requestID") # # The Type of the Transaction. Always set to "DELAYED_TRADE_CLOSURE" # for an DelayedTradeClosureTransaction. # self.type = kwargs.get("type", "DELAYED_TRADE_CLOSURE") # # The reason for the delayed trade closure # self.reason = kwargs.get("reason") # # List of Trade ID's identifying the open trades that will be closed # when their respective instruments become tradeable # self.tradeIDs = kwargs.get("tradeIDs")
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "super", "(", "DelayedTradeClosureTransaction", ",", "self", ")", ".", "__init__", "(", ")", "#", "# The Transaction's Identifier.", "#", "self", ".", "id", "=", "kwargs", ".", "get", "(", ...
https://github.com/oanda/v20-python/blob/f28192f4a31bce038cf6dfa302f5878bec192fe5/src/v20/transaction.py#L5157-L5209
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/PIL/TiffImagePlugin.py
python
AppendingTiffWriter.__enter__
(self)
return self
[]
def __enter__(self): return self
[ "def", "__enter__", "(", "self", ")", ":", "return", "self" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/PIL/TiffImagePlugin.py#L1732-L1733
pypa/pip
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
src/pip/_vendor/html5lib/_inputstream.py
python
EncodingBytes.skip
(self, chars=spaceCharactersBytes)
return None
Skip past a list of characters
Skip past a list of characters
[ "Skip", "past", "a", "list", "of", "characters" ]
def skip(self, chars=spaceCharactersBytes): """Skip past a list of characters""" p = self.position # use property for the error-checking while p < len(self): c = self[p:p + 1] if c not in chars: self._position = p return c p += 1 self._position = p return None
[ "def", "skip", "(", "self", ",", "chars", "=", "spaceCharactersBytes", ")", ":", "p", "=", "self", ".", "position", "# use property for the error-checking", "while", "p", "<", "len", "(", "self", ")", ":", "c", "=", "self", "[", "p", ":", "p", "+", "1"...
https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/html5lib/_inputstream.py#L634-L644
modin-project/modin
0d9d14e6669be3dd6bb3b72222dbe6a6dffe1bee
modin/core/dataframe/pandas/dataframe/dataframe.py
python
PandasDataframe.map
(self, func, dtypes=None)
return self.__constructor__( new_partitions, self.axes[0], self.axes[1], self._row_lengths_cache, self._column_widths_cache, dtypes=dtypes, )
Perform a function that maps across the entire dataset. Parameters ---------- func : callable The function to apply. dtypes : dtypes of the result, default: None The data types for the result. This is an optimization because there are functions that always result in a particular data type, and this allows us to avoid (re)computing it. Returns ------- PandasDataframe A new dataframe.
Perform a function that maps across the entire dataset.
[ "Perform", "a", "function", "that", "maps", "across", "the", "entire", "dataset", "." ]
def map(self, func, dtypes=None): """ Perform a function that maps across the entire dataset. Parameters ---------- func : callable The function to apply. dtypes : dtypes of the result, default: None The data types for the result. This is an optimization because there are functions that always result in a particular data type, and this allows us to avoid (re)computing it. Returns ------- PandasDataframe A new dataframe. """ new_partitions = self._partition_mgr_cls.map_partitions(self._partitions, func) if dtypes == "copy": dtypes = self._dtypes elif dtypes is not None: dtypes = pandas.Series( [np.dtype(dtypes)] * len(self.columns), index=self.columns ) return self.__constructor__( new_partitions, self.axes[0], self.axes[1], self._row_lengths_cache, self._column_widths_cache, dtypes=dtypes, )
[ "def", "map", "(", "self", ",", "func", ",", "dtypes", "=", "None", ")", ":", "new_partitions", "=", "self", ".", "_partition_mgr_cls", ".", "map_partitions", "(", "self", ".", "_partitions", ",", "func", ")", "if", "dtypes", "==", "\"copy\"", ":", "dtyp...
https://github.com/modin-project/modin/blob/0d9d14e6669be3dd6bb3b72222dbe6a6dffe1bee/modin/core/dataframe/pandas/dataframe/dataframe.py#L1287-L1319
qiucheng025/zao-
3a5edf3607b3a523f95746bc69b688090c76d89a
plugins/train/model/realface.py
python
Model.add_networks
(self)
Add the realface model weights
Add the realface model weights
[ "Add", "the", "realface", "model", "weights" ]
def add_networks(self): """ Add the realface model weights """ logger.debug("Adding networks") self.add_network("decoder", "a", self.decoder_a(), is_output=True) self.add_network("decoder", "b", self.decoder_b(), is_output=True) self.add_network("encoder", None, self.encoder()) logger.debug("Added networks")
[ "def", "add_networks", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Adding networks\"", ")", "self", ".", "add_network", "(", "\"decoder\"", ",", "\"a\"", ",", "self", ".", "decoder_a", "(", ")", ",", "is_output", "=", "True", ")", "self", ".",...
https://github.com/qiucheng025/zao-/blob/3a5edf3607b3a523f95746bc69b688090c76d89a/plugins/train/model/realface.py#L71-L77
cannatag/ldap3
040e09fe37cf06801960d494dfadf0a6ed94e38f
setup-binary.py
python
BuildWheels.initialize_options
(self)
Abstract method that is required to be overwritten
Abstract method that is required to be overwritten
[ "Abstract", "method", "that", "is", "required", "to", "be", "overwritten" ]
def initialize_options(self): ''' Abstract method that is required to be overwritten '''
[ "def", "initialize_options", "(", "self", ")", ":" ]
https://github.com/cannatag/ldap3/blob/040e09fe37cf06801960d494dfadf0a6ed94e38f/setup-binary.py#L155-L158
tosher/Mediawiker
81bf97cace59bedcb1668e7830b85c36e014428e
mwcommands/mw_category_list.py
python
MediawikerCategoryListCommand.get_category_current
(self)
return self.category_path[-1]
return current category name in format Category:CategoryName
return current category name in format Category:CategoryName
[ "return", "current", "category", "name", "in", "format", "Category", ":", "CategoryName" ]
def get_category_current(self): ''' return current category name in format Category:CategoryName''' return self.category_path[-1]
[ "def", "get_category_current", "(", "self", ")", ":", "return", "self", ".", "category_path", "[", "-", "1", "]" ]
https://github.com/tosher/Mediawiker/blob/81bf97cace59bedcb1668e7830b85c36e014428e/mwcommands/mw_category_list.py#L92-L94
sfepy/sfepy
02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25
sfepy/discrete/fem/fields_base.py
python
FEField.restore_substituted
(self, vec)
return vec.ravel()
Restore values of the unused DOFs using the transpose of the applied basis transformation.
Restore values of the unused DOFs using the transpose of the applied basis transformation.
[ "Restore", "values", "of", "the", "unused", "DOFs", "using", "the", "transpose", "of", "the", "applied", "basis", "transformation", "." ]
def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel()
[ "def", "restore_substituted", "(", "self", ",", "vec", ")", ":", "if", "(", "self", ".", "econn0", "is", "None", ")", "or", "(", "self", ".", "basis_transform", "is", "None", ")", ":", "raise", "ValueError", "(", "'no original DOF values to restore!!'", ")",...
https://github.com/sfepy/sfepy/blob/02ec7bb2ab39ee1dfe1eb4cd509f0ffb7dcc8b25/sfepy/discrete/fem/fields_base.py#L610-L623
windelbouwman/ppci
915c069e0667042c085ec42c78e9e3c9a5295324
ppci/format/hexfile.py
python
HexLine.to_line
(self)
return line
Create an ascii hex line
Create an ascii hex line
[ "Create", "an", "ascii", "hex", "line" ]
def to_line(self) -> str: """ Create an ascii hex line """ bytecount = len(self.data) nums = bytearray() nums.append(bytecount) nums.extend(struct.pack(">H", self.address)) nums.append(self.typ) nums.extend(self.data) crc = sum(nums) crc = ((~crc) + 1) & 0xFF nums.append(crc) line = ":" + binascii.hexlify(nums).decode("ascii") return line
[ "def", "to_line", "(", "self", ")", "->", "str", ":", "bytecount", "=", "len", "(", "self", ".", "data", ")", "nums", "=", "bytearray", "(", ")", "nums", ".", "append", "(", "bytecount", ")", "nums", ".", "extend", "(", "struct", ".", "pack", "(", ...
https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/format/hexfile.py#L52-L64
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/mpmath/math2.py
python
erf
(x)
return _erf_taylor(x)
erf of a real number.
erf of a real number.
[ "erf", "of", "a", "real", "number", "." ]
def erf(x): """ erf of a real number. """ x = float(x) if x != x: return x if x < 0.0: return -erf(-x) if x >= 1.0: if x >= 6.0: return 1.0 return 1.0 - _erfc_mid(x) return _erf_taylor(x)
[ "def", "erf", "(", "x", ")", ":", "x", "=", "float", "(", "x", ")", "if", "x", "!=", "x", ":", "return", "x", "if", "x", "<", "0.0", ":", "return", "-", "erf", "(", "-", "x", ")", "if", "x", ">=", "1.0", ":", "if", "x", ">=", "6.0", ":"...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/mpmath/math2.py#L425-L438
hacktoolspack/hack-tools
c2b1e324f4b24a2c5b4f111e7ef84e9c547159c2
BruteXSS/mechanize/_form.py
python
Control.pairs
(self)
return [(k, v) for (i, k, v) in self._totally_ordered_pairs()]
Return list of (key, value) pairs suitable for passing to urlencode.
Return list of (key, value) pairs suitable for passing to urlencode.
[ "Return", "list", "of", "(", "key", "value", ")", "pairs", "suitable", "for", "passing", "to", "urlencode", "." ]
def pairs(self): """Return list of (key, value) pairs suitable for passing to urlencode. """ return [(k, v) for (i, k, v) in self._totally_ordered_pairs()]
[ "def", "pairs", "(", "self", ")", ":", "return", "[", "(", "k", ",", "v", ")", "for", "(", "i", ",", "k", ",", "v", ")", "in", "self", ".", "_totally_ordered_pairs", "(", ")", "]" ]
https://github.com/hacktoolspack/hack-tools/blob/c2b1e324f4b24a2c5b4f111e7ef84e9c547159c2/BruteXSS/mechanize/_form.py#L1135-L1138
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/rendergui.py
python
RenderArgsPanelSmall.open_edit_window
(self)
[]
def open_edit_window(self): self.args_edit_window = RenderArgsEditWindow(self)
[ "def", "open_edit_window", "(", "self", ")", ":", "self", ".", "args_edit_window", "=", "RenderArgsEditWindow", "(", "self", ")" ]
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/rendergui.py#L1012-L1013
ckan/ckan
b3b01218ad88ed3fb914b51018abe8b07b07bff3
ckan/views/util.py
python
internal_redirect
()
u''' Redirect to the url parameter. Only internal URLs are allowed
u''' Redirect to the url parameter. Only internal URLs are allowed
[ "u", "Redirect", "to", "the", "url", "parameter", ".", "Only", "internal", "URLs", "are", "allowed" ]
def internal_redirect(): u''' Redirect to the url parameter. Only internal URLs are allowed''' url = request.form.get(u'url') or request.args.get(u'url') if not url: base.abort(400, _(u'Missing Value') + u': url') if h.url_is_local(url): return h.redirect_to(url) else: base.abort(403, _(u'Redirecting to external site is not allowed.'))
[ "def", "internal_redirect", "(", ")", ":", "url", "=", "request", ".", "form", ".", "get", "(", "u'url'", ")", "or", "request", ".", "args", ".", "get", "(", "u'url'", ")", "if", "not", "url", ":", "base", ".", "abort", "(", "400", ",", "_", "(",...
https://github.com/ckan/ckan/blob/b3b01218ad88ed3fb914b51018abe8b07b07bff3/ckan/views/util.py#L13-L24
home-assistant/supervisor
69c2517d5211b483fdfe968b0a2b36b672ee7ab2
supervisor/updater.py
python
Updater.version_multicast
(self)
return self._data.get(ATTR_MULTICAST)
Return latest version of Multicast.
Return latest version of Multicast.
[ "Return", "latest", "version", "of", "Multicast", "." ]
def version_multicast(self) -> Optional[AwesomeVersion]: """Return latest version of Multicast.""" return self._data.get(ATTR_MULTICAST)
[ "def", "version_multicast", "(", "self", ")", "->", "Optional", "[", "AwesomeVersion", "]", ":", "return", "self", ".", "_data", ".", "get", "(", "ATTR_MULTICAST", ")" ]
https://github.com/home-assistant/supervisor/blob/69c2517d5211b483fdfe968b0a2b36b672ee7ab2/supervisor/updater.py#L99-L101
viniciuschiele/flask-apscheduler
5f878c41417824a4f37b353cb4b22973a81746f2
flask_apscheduler/utils.py
python
pop_trigger
(data)
return trigger_name, trigger_args
Pops trigger and trigger args from a given dict.
Pops trigger and trigger args from a given dict.
[ "Pops", "trigger", "and", "trigger", "args", "from", "a", "given", "dict", "." ]
def pop_trigger(data): """Pops trigger and trigger args from a given dict.""" trigger_name = data.pop('trigger') trigger_args = {} if trigger_name == 'date': trigger_arg_names = ('run_date', 'timezone') elif trigger_name == 'interval': trigger_arg_names = ('weeks', 'days', 'hours', 'minutes', 'seconds', 'start_date', 'end_date', 'timezone') elif trigger_name == 'cron': trigger_arg_names = ('year', 'month', 'day', 'week', 'day_of_week', 'hour', 'minute', 'second', 'start_date', 'end_date', 'timezone') else: raise Exception('Trigger %s is not supported.' % trigger_name) for arg_name in trigger_arg_names: if arg_name in data: trigger_args[arg_name] = data.pop(arg_name) return trigger_name, trigger_args
[ "def", "pop_trigger", "(", "data", ")", ":", "trigger_name", "=", "data", ".", "pop", "(", "'trigger'", ")", "trigger_args", "=", "{", "}", "if", "trigger_name", "==", "'date'", ":", "trigger_arg_names", "=", "(", "'run_date'", ",", "'timezone'", ")", "eli...
https://github.com/viniciuschiele/flask-apscheduler/blob/5f878c41417824a4f37b353cb4b22973a81746f2/flask_apscheduler/utils.py#L46-L65
pytorch/benchmark
5c93a5389563a5b6ccfa17d265d60f4fe7272f31
torchbenchmark/models/pytorch_stargan/data_loader.py
python
CelebA.__init__
(self, image_dir, attr_path, selected_attrs, transform, mode)
Initialize and preprocess the CelebA dataset.
Initialize and preprocess the CelebA dataset.
[ "Initialize", "and", "preprocess", "the", "CelebA", "dataset", "." ]
def __init__(self, image_dir, attr_path, selected_attrs, transform, mode): """Initialize and preprocess the CelebA dataset.""" self.image_dir = image_dir self.attr_path = attr_path self.selected_attrs = selected_attrs self.transform = transform self.mode = mode self.train_dataset = [] self.test_dataset = [] self.attr2idx = {} self.idx2attr = {} self.preprocess() if mode == 'train': self.num_images = len(self.train_dataset) else: self.num_images = len(self.test_dataset)
[ "def", "__init__", "(", "self", ",", "image_dir", ",", "attr_path", ",", "selected_attrs", ",", "transform", ",", "mode", ")", ":", "self", ".", "image_dir", "=", "image_dir", "self", ".", "attr_path", "=", "attr_path", "self", ".", "selected_attrs", "=", ...
https://github.com/pytorch/benchmark/blob/5c93a5389563a5b6ccfa17d265d60f4fe7272f31/torchbenchmark/models/pytorch_stargan/data_loader.py#L13-L29
vaidik/sherlock
c56a87e987e561850d2fbe8534aa69d9dd397e24
sherlock/__init__.py
python
_Configuration.update
(self, **kwargs)
Update configuration. Provide keyword arguments where the keyword parameter is the configuration and its value (the argument) is the value you intend to set. :param backend: global choice of backend. This backend will be used for managing locks. :param client: global client object to use to connect with backend store. :param str namespace: optional global namespace to namespace lock keys for your application in order to avoid conflicts. :param float expire: set lock expiry time. If explicitly set to `None`, lock will not expire. :param float timeout: global timeout for acquiring a lock. :param float retry_interval: global timeout for retrying to acquire the lock if previous attempts failed.
Update configuration. Provide keyword arguments where the keyword parameter is the configuration and its value (the argument) is the value you intend to set.
[ "Update", "configuration", ".", "Provide", "keyword", "arguments", "where", "the", "keyword", "parameter", "is", "the", "configuration", "and", "its", "value", "(", "the", "argument", ")", "is", "the", "value", "you", "intend", "to", "set", "." ]
def update(self, **kwargs): ''' Update configuration. Provide keyword arguments where the keyword parameter is the configuration and its value (the argument) is the value you intend to set. :param backend: global choice of backend. This backend will be used for managing locks. :param client: global client object to use to connect with backend store. :param str namespace: optional global namespace to namespace lock keys for your application in order to avoid conflicts. :param float expire: set lock expiry time. If explicitly set to `None`, lock will not expire. :param float timeout: global timeout for acquiring a lock. :param float retry_interval: global timeout for retrying to acquire the lock if previous attempts failed. ''' for key, val in kwargs.items(): if key not in dir(self): raise AttributeError('Invalid configuration. No such ' 'configuration as %s.' % key) setattr(self, key, val)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "val", "in", "kwargs", ".", "items", "(", ")", ":", "if", "key", "not", "in", "dir", "(", "self", ")", ":", "raise", "AttributeError", "(", "'Invalid configuration. N...
https://github.com/vaidik/sherlock/blob/c56a87e987e561850d2fbe8534aa69d9dd397e24/sherlock/__init__.py#L468-L491
Blizzard/s2protocol
4bfe857bb832eee12cc6307dd699e3b74bd7e1b2
s2protocol/versions/protocol63454.py
python
decode_replay_tracker_events
(contents)
Decodes and yields each tracker event from the contents byte string.
Decodes and yields each tracker event from the contents byte string.
[ "Decodes", "and", "yields", "each", "tracker", "event", "from", "the", "contents", "byte", "string", "." ]
def decode_replay_tracker_events(contents): """Decodes and yields each tracker event from the contents byte string.""" decoder = VersionedDecoder(contents, typeinfos) for event in _decode_event_stream(decoder, tracker_eventid_typeid, tracker_event_types, decode_user_id=False): yield event
[ "def", "decode_replay_tracker_events", "(", "contents", ")", ":", "decoder", "=", "VersionedDecoder", "(", "contents", ",", "typeinfos", ")", "for", "event", "in", "_decode_event_stream", "(", "decoder", ",", "tracker_eventid_typeid", ",", "tracker_event_types", ",", ...
https://github.com/Blizzard/s2protocol/blob/4bfe857bb832eee12cc6307dd699e3b74bd7e1b2/s2protocol/versions/protocol63454.py#L456-L463
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/lxml-4.4.2-py3.7-macosx-10.9-x86_64.egg/lxml/html/__init__.py
python
Classes.remove
(self, value)
Remove a class; it must currently be present. If the class is not present, raise a KeyError.
Remove a class; it must currently be present.
[ "Remove", "a", "class", ";", "it", "must", "currently", "be", "present", "." ]
def remove(self, value): """ Remove a class; it must currently be present. If the class is not present, raise a KeyError. """ if not value or re.search(r'\s', value): raise ValueError("Invalid class name: %r" % value) super(Classes, self).remove(value)
[ "def", "remove", "(", "self", ",", "value", ")", ":", "if", "not", "value", "or", "re", ".", "search", "(", "r'\\s'", ",", "value", ")", ":", "raise", "ValueError", "(", "\"Invalid class name: %r\"", "%", "value", ")", "super", "(", "Classes", ",", "se...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/lxml-4.4.2-py3.7-macosx-10.9-x86_64.egg/lxml/html/__init__.py#L181-L189
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
pypy/module/cpyext/unicodeobject.py
python
PyUnicode_Replace
(space, w_str, w_substr, w_replstr, maxcount)
return space.call_method(w_str, "replace", w_substr, w_replstr, space.newint(maxcount))
Replace at most maxcount occurrences of substr in str with replstr and return the resulting Unicode object. maxcount == -1 means replace all occurrences.
Replace at most maxcount occurrences of substr in str with replstr and return the resulting Unicode object. maxcount == -1 means replace all occurrences.
[ "Replace", "at", "most", "maxcount", "occurrences", "of", "substr", "in", "str", "with", "replstr", "and", "return", "the", "resulting", "Unicode", "object", ".", "maxcount", "==", "-", "1", "means", "replace", "all", "occurrences", "." ]
def PyUnicode_Replace(space, w_str, w_substr, w_replstr, maxcount): """Replace at most maxcount occurrences of substr in str with replstr and return the resulting Unicode object. maxcount == -1 means replace all occurrences.""" return space.call_method(w_str, "replace", w_substr, w_replstr, space.newint(maxcount))
[ "def", "PyUnicode_Replace", "(", "space", ",", "w_str", ",", "w_substr", ",", "w_replstr", ",", "maxcount", ")", ":", "return", "space", ".", "call_method", "(", "w_str", ",", "\"replace\"", ",", "w_substr", ",", "w_replstr", ",", "space", ".", "newint", "...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/pypy/module/cpyext/unicodeobject.py#L715-L720
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/libs/liboozie/src/liboozie/oozie_api.py
python
OozieApi.submit_job
(self, properties=None)
return resp['id']
submit_job(properties=None, id=None) -> jobid Raise RestException on error.
submit_job(properties=None, id=None) -> jobid
[ "submit_job", "(", "properties", "=", "None", "id", "=", "None", ")", "-", ">", "jobid" ]
def submit_job(self, properties=None): """ submit_job(properties=None, id=None) -> jobid Raise RestException on error. """ defaults = { 'user.name': self.user, } if properties is not None: defaults.update(properties) properties = defaults params = self._get_params() resp = self._root.post('jobs', params, data=config_gen(properties), contenttype=_XML_CONTENT_TYPE) return resp['id']
[ "def", "submit_job", "(", "self", ",", "properties", "=", "None", ")", ":", "defaults", "=", "{", "'user.name'", ":", "self", ".", "user", ",", "}", "if", "properties", "is", "not", "None", ":", "defaults", ".", "update", "(", "properties", ")", "prope...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/libs/liboozie/src/liboozie/oozie_api.py#L273-L290
guildai/guildai
1665985a3d4d788efc1a3180ca51cc417f71ca78
guild/external/pip/_vendor/urllib3/util/ssl_.py
python
create_urllib3_context
(ssl_version=None, cert_reqs=None, options=None, ciphers=None)
return context
All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from pip._vendor.urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext
All arguments have the same meaning as ``ssl_wrap_socket``.
[ "All", "arguments", "have", "the", "same", "meaning", "as", "ssl_wrap_socket", "." ]
def create_urllib3_context(ssl_version=None, cert_reqs=None, options=None, ciphers=None): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from pip._vendor.urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23) # Setting the default here, as we may have no ssl module on import cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION context.options |= options if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6 context.set_ciphers(ciphers or DEFAULT_CIPHERS) context.verify_mode = cert_reqs if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False return context
[ "def", "create_urllib3_context", "(", "ssl_version", "=", "None", ",", "cert_reqs", "=", "None", ",", "options", "=", "None", ",", "ciphers", "=", "None", ")", ":", "context", "=", "SSLContext", "(", "ssl_version", "or", "ssl", ".", "PROTOCOL_SSLv23", ")", ...
https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/urllib3/util/ssl_.py#L242-L302
Azure/azure-linux-extensions
a42ef718c746abab2b3c6a21da87b29e76364558
Common/libpsutil/py2.6-glibc-2.12-pre/psutil/_psbsd.py
python
cpu_count_logical
()
return cext.cpu_count_logical()
Return the number of logical CPUs in the system.
Return the number of logical CPUs in the system.
[ "Return", "the", "number", "of", "logical", "CPUs", "in", "the", "system", "." ]
def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical()
[ "def", "cpu_count_logical", "(", ")", ":", "return", "cext", ".", "cpu_count_logical", "(", ")" ]
https://github.com/Azure/azure-linux-extensions/blob/a42ef718c746abab2b3c6a21da87b29e76364558/Common/libpsutil/py2.6-glibc-2.12-pre/psutil/_psbsd.py#L123-L125
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/bmeip/v20180625/models.py
python
EipAclRule.__init__
(self)
r""" :param Ip: 源 IP :type Ip: str :param Port: 目标端口 :type Port: str :param Protocol: 协议(TCP/UDP/ICMP/ANY) :type Protocol: str :param Action: 策略(accept/drop) :type Action: str :param Description: 备注 :type Description: str
r""" :param Ip: 源 IP :type Ip: str :param Port: 目标端口 :type Port: str :param Protocol: 协议(TCP/UDP/ICMP/ANY) :type Protocol: str :param Action: 策略(accept/drop) :type Action: str :param Description: 备注 :type Description: str
[ "r", ":", "param", "Ip", ":", "源", "IP", ":", "type", "Ip", ":", "str", ":", "param", "Port", ":", "目标端口", ":", "type", "Port", ":", "str", ":", "param", "Protocol", ":", "协议", "(", "TCP", "/", "UDP", "/", "ICMP", "/", "ANY", ")", ":", "type"...
def __init__(self): r""" :param Ip: 源 IP :type Ip: str :param Port: 目标端口 :type Port: str :param Protocol: 协议(TCP/UDP/ICMP/ANY) :type Protocol: str :param Action: 策略(accept/drop) :type Action: str :param Description: 备注 :type Description: str """ self.Ip = None self.Port = None self.Protocol = None self.Action = None self.Description = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Ip", "=", "None", "self", ".", "Port", "=", "None", "self", ".", "Protocol", "=", "None", "self", ".", "Action", "=", "None", "self", ".", "Description", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/bmeip/v20180625/models.py#L817-L834
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
futures/ctp/ApiStruct.py
python
ForQuote.__init__
(self, BrokerID='', InvestorID='', InstrumentID='', ForQuoteRef='', UserID='', ForQuoteLocalID='', ExchangeID='', ParticipantID='', ClientID='', ExchangeInstID='', TraderID='', InstallID=0, InsertDate='', InsertTime='', ForQuoteStatus=FQST_Submitted, FrontID=0, SessionID=0, StatusMsg='', ActiveUserID='', BrokerForQutoSeq=0)
[]
def __init__(self, BrokerID='', InvestorID='', InstrumentID='', ForQuoteRef='', UserID='', ForQuoteLocalID='', ExchangeID='', ParticipantID='', ClientID='', ExchangeInstID='', TraderID='', InstallID=0, InsertDate='', InsertTime='', ForQuoteStatus=FQST_Submitted, FrontID=0, SessionID=0, StatusMsg='', ActiveUserID='', BrokerForQutoSeq=0): self.BrokerID = '' #经纪公司代码, char[11] self.InvestorID = '' #投资者代码, char[13] self.InstrumentID = '' #合约代码, char[31] self.ForQuoteRef = 'OrderRef' #询价引用, char[13] self.UserID = '' #用户代码, char[16] self.ForQuoteLocalID = 'OrderLocalID' #本地询价编号, char[13] self.ExchangeID = '' #交易所代码, char[9] self.ParticipantID = '' #会员代码, char[11] self.ClientID = '' #客户代码, char[11] self.ExchangeInstID = '' #合约在交易所的代码, char[31] self.TraderID = '' #交易所交易员代码, char[21] self.InstallID = '' #安装编号, int self.InsertDate = 'Date' #报单日期, char[9] self.InsertTime = 'Time' #插入时间, char[9] self.ForQuoteStatus = '' #询价状态, char self.FrontID = '' #前置编号, int self.SessionID = '' #会话编号, int self.StatusMsg = 'ErrorMsg' #状态信息, char[81] self.ActiveUserID = 'UserID' #操作用户代码, char[16] self.BrokerForQutoSeq = 'SequenceNo'
[ "def", "__init__", "(", "self", ",", "BrokerID", "=", "''", ",", "InvestorID", "=", "''", ",", "InstrumentID", "=", "''", ",", "ForQuoteRef", "=", "''", ",", "UserID", "=", "''", ",", "ForQuoteLocalID", "=", "''", ",", "ExchangeID", "=", "''", ",", "...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/futures/ctp/ApiStruct.py#L3536-L3556
seppius-xbmc-repo/ru
d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2
plugin.audio.tracksflow/resources/lib/tracksflow/api.py
python
TracksFlow.getTopPlaylists
(self, pagenum = 0, pagesize = 25, days = 1)
return json.loads(data)
[]
def getTopPlaylists(self, pagenum = 0, pagesize = 25, days = 1): data = self.GET('top_playlists', { 'pagesize': pagesize, 'pagenum': pagenum, 'days': days }) return json.loads(data)
[ "def", "getTopPlaylists", "(", "self", ",", "pagenum", "=", "0", ",", "pagesize", "=", "25", ",", "days", "=", "1", ")", ":", "data", "=", "self", ".", "GET", "(", "'top_playlists'", ",", "{", "'pagesize'", ":", "pagesize", ",", "'pagenum'", ":", "pa...
https://github.com/seppius-xbmc-repo/ru/blob/d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2/plugin.audio.tracksflow/resources/lib/tracksflow/api.py#L42-L48
Anaconda-Platform/anaconda-project
df5ec33c12591e6512436d38d36c6132fa2e9618
anaconda_project/prepare.py
python
PrepareResult.__nonzero__
(self)
return self.__bool__()
True if we were successful.
True if we were successful.
[ "True", "if", "we", "were", "successful", "." ]
def __nonzero__(self): """True if we were successful.""" return self.__bool__()
[ "def", "__nonzero__", "(", "self", ")", ":", "return", "self", ".", "__bool__", "(", ")" ]
https://github.com/Anaconda-Platform/anaconda-project/blob/df5ec33c12591e6512436d38d36c6132fa2e9618/anaconda_project/prepare.py#L54-L56
okfn-brasil/serenata-de-amor
9e76e2e887802ff7e25f37000611af0bd1f6bd22
research/src/fetch_sex_places.py
python
fetch_place
(company, output, semaphore)
Gets a company (dict), finds the closest place nearby and write the result to a CSV file.
Gets a company (dict), finds the closest place nearby and write the result to a CSV file.
[ "Gets", "a", "company", "(", "dict", ")", "finds", "the", "closest", "place", "nearby", "and", "write", "the", "result", "to", "a", "CSV", "file", "." ]
async def fetch_place(company, output, semaphore): """ Gets a company (dict), finds the closest place nearby and write the result to a CSV file. """ with (await semaphore): places = SexPlacesNearBy(company) await places.get_closest() if places.closest: await write_to_csv(output, places.closest)
[ "async", "def", "fetch_place", "(", "company", ",", "output", ",", "semaphore", ")", ":", "with", "(", "await", "semaphore", ")", ":", "places", "=", "SexPlacesNearBy", "(", "company", ")", "await", "places", ".", "get_closest", "(", ")", "if", "places", ...
https://github.com/okfn-brasil/serenata-de-amor/blob/9e76e2e887802ff7e25f37000611af0bd1f6bd22/research/src/fetch_sex_places.py#L302-L311
airspeed-velocity/asv
9d5af5713357ccea00a518758fae6822cc69f539
asv/extern/asizeof.py
python
_len_bytearray
(obj)
return obj.__alloc__()
Bytearray size.
Bytearray size.
[ "Bytearray", "size", "." ]
def _len_bytearray(obj): '''Bytearray size. ''' return obj.__alloc__()
[ "def", "_len_bytearray", "(", "obj", ")", ":", "return", "obj", ".", "__alloc__", "(", ")" ]
https://github.com/airspeed-velocity/asv/blob/9d5af5713357ccea00a518758fae6822cc69f539/asv/extern/asizeof.py#L871-L874
sqall01/alertR
e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13
alertClientTemplate/lib/client/watchdog.py
python
ConnectionWatchdog.run
(self)
Connection watchdog loop that checks the communication channel to the server. :return:
Connection watchdog loop that checks the communication channel to the server. :return:
[ "Connection", "watchdog", "loop", "that", "checks", "the", "communication", "channel", "to", "the", "server", ".", ":", "return", ":" ]
def run(self): """ Connection watchdog loop that checks the communication channel to the server. :return: """ # check every 5 seconds if the client is still connected # and the time of the last received data # from the server lies too far in the past while True: # wait 5 seconds before checking time of last received data for i in range(5): if self._exit_flag: logging.info("[%s]: Exiting Connection Watchdog." % self._log_tag) return time.sleep(1) utc_timestamp = int(time.time()) # Connect to server if communication channel is not connected anymore. if not self._connection.is_connected: logging.error("[%s]: Connection to server has died. " % self._log_tag) # Reconnect to the server. while True: # Check if 5 unsuccessful attempts are made to connect # to the server and if smtp alert is activated # => send eMail alert if self._smtp_alert is not None and (self._connection_retries % 5) == 0: self._smtp_alert.sendCommunicationAlert(self._connection_retries) # try to connect to the server if self._connection.reconnect(): # if smtp alert is activated # => send email that communication problems are solved if self._smtp_alert is not None: self._smtp_alert.sendCommunicationAlertClear() logging.info("[%s] Reconnecting successful after %d attempts." % (self._log_tag, self._connection_retries)) self._connection_retries = 1 break self._connection_retries += 1 logging.error("[%s]: Reconnecting failed. Retrying in 5 seconds." % self._log_tag) time.sleep(5) # Check if the time of the data last received lies too far in the # past => send ping to check connection elif (utc_timestamp - self._connection.last_communication) > self._ping_interval: logging.debug("[%s]: Ping interval exceeded." % self._log_tag) # check if PING failed promise = self._connection.send_ping() # type: Promise # Wait for ping response to finish (in a non-blocking way since otherwise we could # get a deadlock in which we do not re-connect to the server anymore). is_finished = False for _ in range(self._ping_delay_warning): if promise.is_finished(blocking=False): is_finished = True break time.sleep(1) if is_finished: if not promise.was_successful(): logging.error("[%s]: Connection to server has died." % self._log_tag) else: logging.warning("[%s]: Stopped waiting for ping response after %d seconds." % (self._log_tag, self._ping_delay_warning))
[ "def", "run", "(", "self", ")", ":", "# check every 5 seconds if the client is still connected", "# and the time of the last received data", "# from the server lies too far in the past", "while", "True", ":", "# wait 5 seconds before checking time of last received data", "for", "i", "i...
https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/alertClientTemplate/lib/client/watchdog.py#L52-L127
nipy/nipype
cd4c34d935a43812d1756482fdc4034844e485b8
nipype/pipeline/engine/utils.py
python
_transpose_iterables
(fields, values)
return list( zip( fields, [ [v for v in list(transpose) if v is not None] for transpose in zip(*values) ], ) )
Converts the given fields and tuple values into a standardized iterables value. If the input values is a synchronize iterables dictionary, then the result is a (field, {key: values}) list. Otherwise, the result is a list of (field: value list) pairs.
Converts the given fields and tuple values into a standardized iterables value.
[ "Converts", "the", "given", "fields", "and", "tuple", "values", "into", "a", "standardized", "iterables", "value", "." ]
def _transpose_iterables(fields, values): """ Converts the given fields and tuple values into a standardized iterables value. If the input values is a synchronize iterables dictionary, then the result is a (field, {key: values}) list. Otherwise, the result is a list of (field: value list) pairs. """ if isinstance(values, dict): transposed = dict([(field, defaultdict(list)) for field in fields]) for key, tuples in list(values.items()): for kvals in tuples: for idx, val in enumerate(kvals): if val is not None: transposed[fields[idx]][key].append(val) return list(transposed.items()) return list( zip( fields, [ [v for v in list(transpose) if v is not None] for transpose in zip(*values) ], ) )
[ "def", "_transpose_iterables", "(", "fields", ",", "values", ")", ":", "if", "isinstance", "(", "values", ",", "dict", ")", ":", "transposed", "=", "dict", "(", "[", "(", "field", ",", "defaultdict", "(", "list", ")", ")", "for", "field", "in", "fields...
https://github.com/nipy/nipype/blob/cd4c34d935a43812d1756482fdc4034844e485b8/nipype/pipeline/engine/utils.py#L1299-L1326
rspeer/langcodes
49beea8e20ae26c2dead7bd77f41cfba0e0ab533
langcodes/tag_parser.py
python
_is_ascii
(s)
Determine whether a tag consists of ASCII characters.
Determine whether a tag consists of ASCII characters.
[ "Determine", "whether", "a", "tag", "consists", "of", "ASCII", "characters", "." ]
def _is_ascii(s): """ Determine whether a tag consists of ASCII characters. """ # When Python 3.6 support is dropped, we can replace this with str.isascii(). try: s.encode('ascii') return True except UnicodeEncodeError: return False
[ "def", "_is_ascii", "(", "s", ")", ":", "# When Python 3.6 support is dropped, we can replace this with str.isascii().", "try", ":", "s", ".", "encode", "(", "'ascii'", ")", "return", "True", "except", "UnicodeEncodeError", ":", "return", "False" ]
https://github.com/rspeer/langcodes/blob/49beea8e20ae26c2dead7bd77f41cfba0e0ab533/langcodes/tag_parser.py#L149-L158
mongodb-labs/edda
5acaf9918d9aae6a6acbbfe48741d8a20aae1f21
edda/filters/init_and_listen.py
python
starting_up
(msg, doc)
return doc
Generate a document for a server startup event.
Generate a document for a server startup event.
[ "Generate", "a", "document", "for", "a", "server", "startup", "event", "." ]
def starting_up(msg, doc): """Generate a document for a server startup event.""" doc["info"]["subtype"] = "startup" # what type of server is this? if ('MongoS' in msg) or ('mongos' in msg): doc["info"]["type"] = "mongos" # mongos startup does not provide an address doc["info"]["addr"] = "unknown" LOGGER.debug("Returning mongos startup doc") return doc elif msg.find("MongoDB") > -1: doc["info"]["type"] = "mongod" # isolate port number m = PORT_NUMBER.search(msg) if m is None: LOGGER.debug("malformed starting_up message: no port number found") return None port = m.group(0)[5:] host = msg[msg.find("host=") + 5:].split()[0] addr = host + ":" + port addr = addr.replace('\n', "") addr = addr.replace(" ", "") doc["info"]["addr"] = addr deb = "Returning new doc for a message of type: initandlisten: starting_up" LOGGER.debug(deb) return doc
[ "def", "starting_up", "(", "msg", ",", "doc", ")", ":", "doc", "[", "\"info\"", "]", "[", "\"subtype\"", "]", "=", "\"startup\"", "# what type of server is this?", "if", "(", "'MongoS'", "in", "msg", ")", "or", "(", "'mongos'", "in", "msg", ")", ":", "do...
https://github.com/mongodb-labs/edda/blob/5acaf9918d9aae6a6acbbfe48741d8a20aae1f21/edda/filters/init_and_listen.py#L134-L163
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/ipaddress.py
python
IPv4Address.is_private
(self)
return any(self in net for net in self._constants._private_networks)
Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry.
Test if this address is allocated for private networks.
[ "Test", "if", "this", "address", "is", "allocated", "for", "private", "networks", "." ]
def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry. """ return any(self in net for net in self._constants._private_networks)
[ "def", "is_private", "(", "self", ")", ":", "return", "any", "(", "self", "in", "net", "for", "net", "in", "self", ".", "_constants", ".", "_private_networks", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/ipaddress.py#L1428-L1436
Nitrate/Nitrate
7eacef697a15dcbb7ae90c8a1dbf769cba6d1bb1
src/tcms/xmlrpc/api/product.py
python
filter_categories
(request, query)
return TestCaseCategory.to_xmlrpc(query)
Performs a search and returns the resulting list of categories. :param dict query: a mapping containing following criteria. * id: (int) category ID. * name: (str) category name. * product: ForeignKey: :class:`Product`. * description: (str) category description. :return: a mapping representing found category. :rtype: dict Example:: # Get all of categories named like 'libvirt' Product.filter_categories({'name__icontains': 'regression'}) # Get all of categories named in product 'product name' Product.filter_categories({'product__name': 'product name'})
Performs a search and returns the resulting list of categories.
[ "Performs", "a", "search", "and", "returns", "the", "resulting", "list", "of", "categories", "." ]
def filter_categories(request, query): """Performs a search and returns the resulting list of categories. :param dict query: a mapping containing following criteria. * id: (int) category ID. * name: (str) category name. * product: ForeignKey: :class:`Product`. * description: (str) category description. :return: a mapping representing found category. :rtype: dict Example:: # Get all of categories named like 'libvirt' Product.filter_categories({'name__icontains': 'regression'}) # Get all of categories named in product 'product name' Product.filter_categories({'product__name': 'product name'}) """ from tcms.testcases.models import TestCaseCategory return TestCaseCategory.to_xmlrpc(query)
[ "def", "filter_categories", "(", "request", ",", "query", ")", ":", "from", "tcms", ".", "testcases", ".", "models", "import", "TestCaseCategory", "return", "TestCaseCategory", ".", "to_xmlrpc", "(", "query", ")" ]
https://github.com/Nitrate/Nitrate/blob/7eacef697a15dcbb7ae90c8a1dbf769cba6d1bb1/src/tcms/xmlrpc/api/product.py#L129-L151
pypa/setuptools
9f37366aab9cd8f6baa23e6a77cfdb8daf97757e
setuptools/_vendor/more_itertools/recipes.py
python
dotproduct
(vec1, vec2)
return sum(map(operator.mul, vec1, vec2))
Returns the dot product of the two iterables. >>> dotproduct([10, 10], [20, 20]) 400
Returns the dot product of the two iterables.
[ "Returns", "the", "dot", "product", "of", "the", "two", "iterables", "." ]
def dotproduct(vec1, vec2): """Returns the dot product of the two iterables. >>> dotproduct([10, 10], [20, 20]) 400 """ return sum(map(operator.mul, vec1, vec2))
[ "def", "dotproduct", "(", "vec1", ",", "vec2", ")", ":", "return", "sum", "(", "map", "(", "operator", ".", "mul", ",", "vec1", ",", "vec2", ")", ")" ]
https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_vendor/more_itertools/recipes.py#L209-L216
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
examples/pipeline/hetero_sbt/pipeline-hetero-sbt-regression-multi-host.py
python
main
(config="../../config.yaml", namespace="")
[]
def main(config="../../config.yaml", namespace=""): # obtain config if isinstance(config, str): config = load_job_config(config) parties = config.parties guest = parties.guest[0] hosts = parties.host # data sets guest_train_data = {"name": "motor_hetero_guest", "namespace": f"experiment{namespace}"} host_train_data_0 = {"name": "motor_hetero_host_1", "namespace": f"experiment{namespace}"} host_train_data_1 = {"name": "motor_hetero_host_2", "namespace": f"experiment{namespace}"} guest_validate_data = {"name": "motor_hetero_guest", "namespace": f"experiment{namespace}"} host_validate_data_0 = {"name": "motor_hetero_host_1", "namespace": f"experiment{namespace}"} host_validate_data_1 = {"name": "motor_hetero_host_2", "namespace": f"experiment{namespace}"} # init pipeline pipeline = PipeLine().set_initiator(role="guest", party_id=guest).set_roles(guest=guest, host=hosts,) # set data reader and data-io reader_0, reader_1 = Reader(name="reader_0"), Reader(name="reader_1") reader_0.get_party_instance(role="guest", party_id=guest).component_param(table=guest_train_data) reader_0.get_party_instance(role="host", party_id=hosts[0]).component_param(table=host_train_data_0) reader_0.get_party_instance(role="host", party_id=hosts[1]).component_param(table=host_train_data_1) reader_1.get_party_instance(role="guest", party_id=guest).component_param(table=guest_validate_data) reader_1.get_party_instance(role="host", party_id=hosts[0]).component_param(table=host_validate_data_0) reader_1.get_party_instance(role="host", party_id=hosts[1]).component_param(table=host_validate_data_1) data_transform_0, data_transform_1 = DataTransform(name="data_transform_0"), DataTransform(name="data_transform_1") data_transform_0.get_party_instance(role="guest", party_id=guest).component_param(with_label=True, output_format="dense", label_name='motor_speed', label_type="float") data_transform_0.get_party_instance(role="host", party_id=hosts[0]).component_param(with_label=False) data_transform_0.get_party_instance(role="host", party_id=hosts[1]).component_param(with_label=False) data_transform_1.get_party_instance(role="guest", party_id=guest).component_param(with_label=True, output_format="dense", label_name="motor_speed", label_type="float") data_transform_1.get_party_instance(role="host", party_id=hosts[0]).component_param(with_label=False) data_transform_1.get_party_instance(role="host", party_id=hosts[1]).component_param(with_label=False) # data intersect component intersect_0 = Intersection(name="intersection_0") intersect_1 = Intersection(name="intersection_1") # secure boost component hetero_secure_boost_0 = HeteroSecureBoost(name="hetero_secure_boost_0", num_trees=3, task_type="regression", objective_param={"objective": "lse"}, encrypt_param={"method": "iterativeAffine"}, tree_param={"max_depth": 3}, validation_freqs=1) # evaluation component evaluation_0 = Evaluation(name="evaluation_0", eval_type="regression") pipeline.add_component(reader_0) pipeline.add_component(reader_1) pipeline.add_component(data_transform_0, data=Data(data=reader_0.output.data)) pipeline.add_component(data_transform_1, data=Data(data=reader_1.output.data), model=Model(data_transform_0.output.model)) pipeline.add_component(intersect_0, data=Data(data=data_transform_0.output.data)) pipeline.add_component(intersect_1, data=Data(data=data_transform_1.output.data)) pipeline.add_component(hetero_secure_boost_0, data=Data(train_data=intersect_0.output.data, validate_data=intersect_1.output.data)) pipeline.add_component(evaluation_0, data=Data(data=hetero_secure_boost_0.output.data)) pipeline.compile() pipeline.fit() print("fitting hetero secureboost done, result:") print(pipeline.get_component("hetero_secure_boost_0").get_summary())
[ "def", "main", "(", "config", "=", "\"../../config.yaml\"", ",", "namespace", "=", "\"\"", ")", ":", "# obtain config", "if", "isinstance", "(", "config", ",", "str", ")", ":", "config", "=", "load_job_config", "(", "config", ")", "parties", "=", "config", ...
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/examples/pipeline/hetero_sbt/pipeline-hetero-sbt-regression-multi-host.py#L31-L105
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
13-protocol-abc/tombola_subhook.py
python
Tombola.__subclasshook__
(cls, other_cls)
return NotImplemented
[]
def __subclasshook__(cls, other_cls): if cls is Tombola: interface_names = function_names(cls) found_names = set() for a_cls in other_cls.__mro__: found_names |= function_names(a_cls) if found_names >= interface_names: return True return NotImplemented
[ "def", "__subclasshook__", "(", "cls", ",", "other_cls", ")", ":", "if", "cls", "is", "Tombola", ":", "interface_names", "=", "function_names", "(", "cls", ")", "found_names", "=", "set", "(", ")", "for", "a_cls", "in", "other_cls", ".", "__mro__", ":", ...
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/13-protocol-abc/tombola_subhook.py#L52-L60
aws-cloudformation/cfn-lint
16df5d0ca0d8ebcf9330ebea701e83d883b47217
src/cfnlint/rules/resources/iam/Permissions.py
python
Permissions.match_resource_properties
(self, properties, resourcetype, path, cfn)
return matches
Check CloudFormation Properties
Check CloudFormation Properties
[ "Check", "CloudFormation", "Properties" ]
def match_resource_properties(self, properties, resourcetype, path, cfn): """Check CloudFormation Properties""" matches = [] key = self.IAM_PERMISSION_RESOURCE_TYPES.get(resourcetype) for key, value in properties.items(): if key == 'Policies' and isinstance(value, list): for index, policy in enumerate(properties.get(key, [])): matches.extend( cfn.check_value( obj=policy, key='PolicyDocument', path=path[:] + ['Policies', index], check_value=self.check_policy_document, start_mark=key.start_mark, end_mark=key.end_mark, )) elif key in ['KeyPolicy', 'PolicyDocument', 'RepositoryPolicyText', 'AccessPolicies']: matches.extend( cfn.check_value( obj=properties, key=key, path=path[:], check_value=self.check_policy_document, start_mark=key.start_mark, end_mark=key.end_mark, )) return matches
[ "def", "match_resource_properties", "(", "self", ",", "properties", ",", "resourcetype", ",", "path", ",", "cfn", ")", ":", "matches", "=", "[", "]", "key", "=", "self", ".", "IAM_PERMISSION_RESOURCE_TYPES", ".", "get", "(", "resourcetype", ")", "for", "key"...
https://github.com/aws-cloudformation/cfn-lint/blob/16df5d0ca0d8ebcf9330ebea701e83d883b47217/src/cfnlint/rules/resources/iam/Permissions.py#L167-L191
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_12/paramiko/channel.py
python
Channel._log
(self, level, msg, *args)
[]
def _log(self, level, msg, *args): self.logger.log(level, "[chan " + self._name + "] " + msg, *args)
[ "def", "_log", "(", "self", ",", "level", ",", "msg", ",", "*", "args", ")", ":", "self", ".", "logger", ".", "log", "(", "level", ",", "\"[chan \"", "+", "self", ".", "_name", "+", "\"] \"", "+", "msg", ",", "*", "args", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_12/paramiko/channel.py#L1114-L1115
joelgrus/data-science-from-scratch
d5d0f117f41b3ccab3b07f1ee1fa21cfcf69afa1
scratch/machine_learning.py
python
accuracy
(tp: int, fp: int, fn: int, tn: int)
return correct / total
[]
def accuracy(tp: int, fp: int, fn: int, tn: int) -> float: correct = tp + tn total = tp + fp + fn + tn return correct / total
[ "def", "accuracy", "(", "tp", ":", "int", ",", "fp", ":", "int", ",", "fn", ":", "int", ",", "tn", ":", "int", ")", "->", "float", ":", "correct", "=", "tp", "+", "tn", "total", "=", "tp", "+", "fp", "+", "fn", "+", "tn", "return", "correct",...
https://github.com/joelgrus/data-science-from-scratch/blob/d5d0f117f41b3ccab3b07f1ee1fa21cfcf69afa1/scratch/machine_learning.py#L48-L51
nicolargo/glances
00c65933ae1d0ebd3e72dc30fc3c215a83dfaae2
glances/web_list.py
python
GlancesWebList.get_web_list
(self)
return self._web_list
Return the current server list (dict of dict).
Return the current server list (dict of dict).
[ "Return", "the", "current", "server", "list", "(", "dict", "of", "dict", ")", "." ]
def get_web_list(self): """Return the current server list (dict of dict).""" return self._web_list
[ "def", "get_web_list", "(", "self", ")", ":", "return", "self", ".", "_web_list" ]
https://github.com/nicolargo/glances/blob/00c65933ae1d0ebd3e72dc30fc3c215a83dfaae2/glances/web_list.py#L119-L121
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/datasets/last_fm.py
python
LastFM.processed_file_names
(self)
return 'data.pt'
[]
def processed_file_names(self) -> str: return 'data.pt'
[ "def", "processed_file_names", "(", "self", ")", "->", "str", ":", "return", "'data.pt'" ]
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/datasets/last_fm.py#L52-L53
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-modules/twisted/twisted/web/http.py
python
HTTPFactory.log
(self, request)
Log a request's result to the logfile, by default in combined log format.
Log a request's result to the logfile, by default in combined log format.
[ "Log", "a", "request", "s", "result", "to", "the", "logfile", "by", "default", "in", "combined", "log", "format", "." ]
def log(self, request): """ Log a request's result to the logfile, by default in combined log format. """ if hasattr(self, "logFile"): line = '%s - - %s "%s" %d %s "%s" "%s"\n' % ( request.getClientIP(), # request.getUser() or "-", # the remote user is almost never important _logDateTime, '%s %s %s' % (self._escape(request.method), self._escape(request.uri), self._escape(request.clientproto)), request.code, request.sentLength or "-", self._escape(request.getHeader("referer") or "-"), self._escape(request.getHeader("user-agent") or "-")) self.logFile.write(line)
[ "def", "log", "(", "self", ",", "request", ")", ":", "if", "hasattr", "(", "self", ",", "\"logFile\"", ")", ":", "line", "=", "'%s - - %s \"%s\" %d %s \"%s\" \"%s\"\\n'", "%", "(", "request", ".", "getClientIP", "(", ")", ",", "# request.getUser() or \"-\", # th...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/web/http.py#L1781-L1797
ni/nidaqmx-python
62fc6b48cbbb330fe1bcc9aedadc86610a1269b6
nidaqmx/_task_modules/triggering/start_trigger.py
python
StartTrigger.dig_edge_dig_fltr_timebase_src
(self)
[]
def dig_edge_dig_fltr_timebase_src(self): cfunc = (lib_importer.windll. DAQmxResetDigEdgeStartTrigDigFltrTimebaseSrc) if cfunc.argtypes is None: with cfunc.arglock: if cfunc.argtypes is None: cfunc.argtypes = [ lib_importer.task_handle] error_code = cfunc( self._handle) check_for_error(error_code)
[ "def", "dig_edge_dig_fltr_timebase_src", "(", "self", ")", ":", "cfunc", "=", "(", "lib_importer", ".", "windll", ".", "DAQmxResetDigEdgeStartTrigDigFltrTimebaseSrc", ")", "if", "cfunc", ".", "argtypes", "is", "None", ":", "with", "cfunc", ".", "arglock", ":", "...
https://github.com/ni/nidaqmx-python/blob/62fc6b48cbbb330fe1bcc9aedadc86610a1269b6/nidaqmx/_task_modules/triggering/start_trigger.py#L1374-L1385
sametmax/Django--an-app-at-a-time
99eddf12ead76e6dfbeb09ce0bae61e282e22f8a
ignore_this_directory/django/contrib/gis/geos/polygon.py
python
Polygon._get_ext_ring
(self)
return self[0]
Get the exterior ring of the Polygon.
Get the exterior ring of the Polygon.
[ "Get", "the", "exterior", "ring", "of", "the", "Polygon", "." ]
def _get_ext_ring(self): "Get the exterior ring of the Polygon." return self[0]
[ "def", "_get_ext_ring", "(", "self", ")", ":", "return", "self", "[", "0", "]" ]
https://github.com/sametmax/Django--an-app-at-a-time/blob/99eddf12ead76e6dfbeb09ce0bae61e282e22f8a/ignore_this_directory/django/contrib/gis/geos/polygon.py#L153-L155
JetBrains/python-skeletons
95ad24b666e475998e5d1cc02ed53a2188036167
numpy/core/__init__.py
python
generic.conjugate
(self, *args, **kwargs)
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest.
Not implemented (virtual attribute)
[ "Not", "implemented", "(", "virtual", "attribute", ")" ]
def conjugate(self, *args, **kwargs): # real signature unknown """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """ pass
[ "def", "conjugate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# real signature unknown", "pass" ]
https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/numpy/core/__init__.py#L162-L174
csparpa/pyowm
0474b61cc67fa3c95f9e572b96d3248031828fce
pyowm/commons/enums.py
python
ImageTypeEnum.items
(cls)
return [ cls.PNG, cls.GEOTIFF ]
All values for this enum :return: list of `pyowm.commons.enums.ImageType`
All values for this enum :return: list of `pyowm.commons.enums.ImageType`
[ "All", "values", "for", "this", "enum", ":", "return", ":", "list", "of", "pyowm", ".", "commons", ".", "enums", ".", "ImageType" ]
def items(cls): """ All values for this enum :return: list of `pyowm.commons.enums.ImageType` """ return [ cls.PNG, cls.GEOTIFF ]
[ "def", "items", "(", "cls", ")", ":", "return", "[", "cls", ".", "PNG", ",", "cls", ".", "GEOTIFF", "]" ]
https://github.com/csparpa/pyowm/blob/0474b61cc67fa3c95f9e572b96d3248031828fce/pyowm/commons/enums.py#L67-L76
machinalis/iepy
d7353e18d647d1657010d15fad09a4ea8d570089
iepy/extraction/features.py
python
total_number_of_entities
(datapoint)
return len(datapoint.all_eos)
Returns the number of entity in the text segment
Returns the number of entity in the text segment
[ "Returns", "the", "number", "of", "entity", "in", "the", "text", "segment" ]
def total_number_of_entities(datapoint): """ Returns the number of entity in the text segment """ return len(datapoint.all_eos)
[ "def", "total_number_of_entities", "(", "datapoint", ")", ":", "return", "len", "(", "datapoint", ".", "all_eos", ")" ]
https://github.com/machinalis/iepy/blob/d7353e18d647d1657010d15fad09a4ea8d570089/iepy/extraction/features.py#L182-L186
deepmind/rlax
58b3672b2f7ac1a400b3934ae9888c677f39b9e2
docs/conf.py
python
linkcode_resolve
(domain, info)
return 'https://github.com/deepmind/rlax/tree/master/rlax/%s#L%d#L%d' % ( os.path.relpath(filename, start=os.path.dirname( rlax.__file__)), lineno, lineno + len(source) - 1)
Resolve a GitHub URL corresponding to Python object.
Resolve a GitHub URL corresponding to Python object.
[ "Resolve", "a", "GitHub", "URL", "corresponding", "to", "Python", "object", "." ]
def linkcode_resolve(domain, info): """Resolve a GitHub URL corresponding to Python object.""" if domain != 'py': return None try: mod = sys.modules[info['module']] except ImportError: return None obj = mod try: for attr in info['fullname'].split('.'): obj = getattr(obj, attr) except AttributeError: return None else: obj = inspect.unwrap(obj) try: filename = inspect.getsourcefile(obj) except TypeError: return None try: source, lineno = inspect.getsourcelines(obj) except OSError: return None # TODO(slebedev): support tags after we release an initial version. return 'https://github.com/deepmind/rlax/tree/master/rlax/%s#L%d#L%d' % ( os.path.relpath(filename, start=os.path.dirname( rlax.__file__)), lineno, lineno + len(source) - 1)
[ "def", "linkcode_resolve", "(", "domain", ",", "info", ")", ":", "if", "domain", "!=", "'py'", ":", "return", "None", "try", ":", "mod", "=", "sys", ".", "modules", "[", "info", "[", "'module'", "]", "]", "except", "ImportError", ":", "return", "None",...
https://github.com/deepmind/rlax/blob/58b3672b2f7ac1a400b3934ae9888c677f39b9e2/docs/conf.py#L151-L183
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/os2emxpath.py
python
join
(a, *p)
return path
Join two or more pathname components, inserting sep as needed
Join two or more pathname components, inserting sep as needed
[ "Join", "two", "or", "more", "pathname", "components", "inserting", "sep", "as", "needed" ]
def join(a, *p): """Join two or more pathname components, inserting sep as needed""" path = a for b in p: if isabs(b): path = b elif path == '' or path[-1:] in '/\\:': path = path + b else: path = path + '/' + b return path
[ "def", "join", "(", "a", ",", "*", "p", ")", ":", "path", "=", "a", "for", "b", "in", "p", ":", "if", "isabs", "(", "b", ")", ":", "path", "=", "b", "elif", "path", "==", "''", "or", "path", "[", "-", "1", ":", "]", "in", "'/\\\\:'", ":",...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/os2emxpath.py#L44-L54
EmuKit/emukit
cdcb0d070d7f1c5585260266160722b636786859
emukit/model_wrappers/gpy_model_wrappers.py
python
GPyModelWrapper.predict_noiseless
(self, X: np.ndarray)
return self.model.predict(X, include_likelihood=False)
:param X: (n_points x n_dimensions) array containing locations at which to get predictions :return: (mean, variance) Arrays of size n_points x 1 of the predictive distribution at each input location
:param X: (n_points x n_dimensions) array containing locations at which to get predictions :return: (mean, variance) Arrays of size n_points x 1 of the predictive distribution at each input location
[ ":", "param", "X", ":", "(", "n_points", "x", "n_dimensions", ")", "array", "containing", "locations", "at", "which", "to", "get", "predictions", ":", "return", ":", "(", "mean", "variance", ")", "Arrays", "of", "size", "n_points", "x", "1", "of", "the",...
def predict_noiseless(self, X: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """ :param X: (n_points x n_dimensions) array containing locations at which to get predictions :return: (mean, variance) Arrays of size n_points x 1 of the predictive distribution at each input location """ return self.model.predict(X, include_likelihood=False)
[ "def", "predict_noiseless", "(", "self", ",", "X", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "np", ".", "ndarray", "]", ":", "return", "self", ".", "model", ".", "predict", "(", "X", ",", "include_likelihood", "="...
https://github.com/EmuKit/emukit/blob/cdcb0d070d7f1c5585260266160722b636786859/emukit/model_wrappers/gpy_model_wrappers.py#L36-L41
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-modules/twisted/twisted/python/log.py
python
_ignore
(*types)
PRIVATE. DEPRECATED. DON'T USE.
PRIVATE. DEPRECATED. DON'T USE.
[ "PRIVATE", ".", "DEPRECATED", ".", "DON", "T", "USE", "." ]
def _ignore(*types): """ PRIVATE. DEPRECATED. DON'T USE. """ for type in types: _ignoreErrors.append(type)
[ "def", "_ignore", "(", "*", "types", ")", ":", "for", "type", "in", "types", ":", "_ignoreErrors", ".", "append", "(", "type", ")" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/python/log.py#L153-L158
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/cinder/cinder/db/api.py
python
volume_type_get
(context, id)
return IMPL.volume_type_get(context, id)
Get volume type by id.
Get volume type by id.
[ "Get", "volume", "type", "by", "id", "." ]
def volume_type_get(context, id): """Get volume type by id.""" return IMPL.volume_type_get(context, id)
[ "def", "volume_type_get", "(", "context", ",", "id", ")", ":", "return", "IMPL", ".", "volume_type_get", "(", "context", ",", "id", ")" ]
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/cinder/cinder/db/api.py#L369-L371
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/ldap3/core/connection.py
python
Connection.abandon
(self, message_id, controls=None)
Abandon the operation indicated by message_id
Abandon the operation indicated by message_id
[ "Abandon", "the", "operation", "indicated", "by", "message_id" ]
def abandon(self, message_id, controls=None): """ Abandon the operation indicated by message_id """ if log_enabled(BASIC): log(BASIC, 'start ABANDON operation via <%s>', self) self.last_error = None with self.connection_lock: self._fire_deferred() return_value = False if self.strategy._outstanding or message_id == 0: # only current operation should be abandoned, abandon, bind and unbind cannot ever be abandoned, # messagiId 0 is invalid and should be used as a "ping" to keep alive the connection if (self.strategy._outstanding and message_id in self.strategy._outstanding and self.strategy._outstanding[message_id]['type'] not in ['abandonRequest', 'bindRequest', 'unbindRequest']) or message_id == 0: request = abandon_operation(message_id) if log_enabled(PROTOCOL): log(PROTOCOL, 'ABANDON request: <%s> sent via <%s>', abandon_request_to_dict(request), self) self.send('abandonRequest', request, controls) self.result = None self.response = None self._entries = [] return_value = True else: if log_enabled(ERROR): log(ERROR, 'cannot abandon a Bind, an Unbind or an Abandon operation or message ID %s not found via <%s>', str(message_id), self) if log_enabled(BASIC): log(BASIC, 'done ABANDON operation, result <%s>', return_value) return return_value
[ "def", "abandon", "(", "self", ",", "message_id", ",", "controls", "=", "None", ")", ":", "if", "log_enabled", "(", "BASIC", ")", ":", "log", "(", "BASIC", ",", "'start ABANDON operation via <%s>'", ",", "self", ")", "self", ".", "last_error", "=", "None",...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/ldap3/core/connection.py#L1138-L1169
mtivadar/qiew
87a3b96b43f1745a6b3f1fcfebce5164d2a40a14
plugins/unpack/basic.py
python
basic.getUI
(self)
return self.ui
[]
def getUI(self): return self.ui
[ "def", "getUI", "(", "self", ")", ":", "return", "self", ".", "ui" ]
https://github.com/mtivadar/qiew/blob/87a3b96b43f1745a6b3f1fcfebce5164d2a40a14/plugins/unpack/basic.py#L143-L144
cuthbertLab/music21
bd30d4663e52955ed922c10fdf541419d8c67671
music21/meter/base.py
python
TimeSignature.numerator
(self)
return self.beamSequence.numerator
Return the numerator of the TimeSignature as a number. Can set the numerator for a simple TimeSignature. To set the numerator of a complex TimeSignature, change beatCount. (for complex TimeSignatures, note that this comes from the .beamSequence of the TimeSignature) >>> ts = meter.TimeSignature('3/4') >>> ts.numerator 3 >>> ts.numerator = 5 >>> ts <music21.meter.TimeSignature 5/4> In this case, the TimeSignature is silently being converted to 9/8 to get a single digit numerator: >>> ts = meter.TimeSignature('2/4+5/8') >>> ts.numerator 9 Setting a summed time signature's numerator will change to a simple time signature >>> ts.numerator = 11 >>> ts <music21.meter.TimeSignature 11/8>
Return the numerator of the TimeSignature as a number.
[ "Return", "the", "numerator", "of", "the", "TimeSignature", "as", "a", "number", "." ]
def numerator(self): ''' Return the numerator of the TimeSignature as a number. Can set the numerator for a simple TimeSignature. To set the numerator of a complex TimeSignature, change beatCount. (for complex TimeSignatures, note that this comes from the .beamSequence of the TimeSignature) >>> ts = meter.TimeSignature('3/4') >>> ts.numerator 3 >>> ts.numerator = 5 >>> ts <music21.meter.TimeSignature 5/4> In this case, the TimeSignature is silently being converted to 9/8 to get a single digit numerator: >>> ts = meter.TimeSignature('2/4+5/8') >>> ts.numerator 9 Setting a summed time signature's numerator will change to a simple time signature >>> ts.numerator = 11 >>> ts <music21.meter.TimeSignature 11/8> ''' return self.beamSequence.numerator
[ "def", "numerator", "(", "self", ")", ":", "return", "self", ".", "beamSequence", ".", "numerator" ]
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/meter/base.py#L626-L659
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/categories/examples/sets_with_grading.py
python
NonNegativeIntegers._repr_
(self)
return "Non negative integers"
r""" TESTS:: sage: SetsWithGrading().example() # indirect example Non negative integers
r""" TESTS::
[ "r", "TESTS", "::" ]
def _repr_(self): r""" TESTS:: sage: SetsWithGrading().example() # indirect example Non negative integers """ return "Non negative integers"
[ "def", "_repr_", "(", "self", ")", ":", "return", "\"Non negative integers\"" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/categories/examples/sets_with_grading.py#L47-L54
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/client/grr_response_client/client_actions/osx/firmware.py
python
EficheckCollectHashes.Run
(self, args)
Use eficheck to extract hash files in plaintext. Args: args: EficheckConfig Returns: CollectEfiHashesResponse This action executes eficheck multiple times: * First to get the binary version, using --version. * Then with the --generate-hashes option. This will create one or more .ealf files. Each file contains a binary representation of the hashes extracted from a part of the flash image (e.g, EFI, SEC). * For each file generated, we use the --show-hashes option to get a plaintext representation of the hashes. This raw output is sent to the server which will perform further parsing.
Use eficheck to extract hash files in plaintext.
[ "Use", "eficheck", "to", "extract", "hash", "files", "in", "plaintext", "." ]
def Run(self, args): """Use eficheck to extract hash files in plaintext. Args: args: EficheckConfig Returns: CollectEfiHashesResponse This action executes eficheck multiple times: * First to get the binary version, using --version. * Then with the --generate-hashes option. This will create one or more .ealf files. Each file contains a binary representation of the hashes extracted from a part of the flash image (e.g, EFI, SEC). * For each file generated, we use the --show-hashes option to get a plaintext representation of the hashes. This raw output is sent to the server which will perform further parsing. """ eficheck_version = self._GetVersion(args) if not eficheck_version: return False with tempfiles.TemporaryDirectory() as tmp_dir: res = client_utils_common.Execute( args.cmd_path, ["--generate-hashes"], cwd=tmp_dir.path) stdout, stderr, exit_status, time_used = res # If something went wrong, forward the output directly. if exit_status: binary_response = rdf_client_action.ExecuteBinaryResponse( stdout=stdout, stderr=stderr, exit_status=exit_status, time_used=time_used) self.SendReply( rdf_apple_firmware.CollectEfiHashesResponse( response=binary_response)) return # Otherwise, convert all the files generated and forward the output. for filename in glob.glob(os.path.join(tmp_dir.path, "*.ealf")): cmd_args = ["--show-hashes", "-h", filename] # Get the boot rom version from the filename. basename = os.path.basename(filename) if not self._FILENAME_RE.match(basename): continue boot_rom_version, _ = os.path.splitext(basename) stdout, stderr, exit_status, time_used = client_utils_common.Execute( args.cmd_path, cmd_args, bypass_allowlist=True) binary_response = rdf_client_action.ExecuteBinaryResponse( stdout=stdout, stderr=stderr, exit_status=exit_status, time_used=time_used) self.SendReply( rdf_apple_firmware.CollectEfiHashesResponse( eficheck_version=eficheck_version, boot_rom_version=boot_rom_version, response=binary_response)) tempfiles.DeleteGRRTempFile(filename)
[ "def", "Run", "(", "self", ",", "args", ")", ":", "eficheck_version", "=", "self", ".", "_GetVersion", "(", "args", ")", "if", "not", "eficheck_version", ":", "return", "False", "with", "tempfiles", ".", "TemporaryDirectory", "(", ")", "as", "tmp_dir", ":"...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/client/grr_response_client/client_actions/osx/firmware.py#L50-L110
unknown-horizons/unknown-horizons
7397fb333006d26c3d9fe796c7bd9cb8c3b43a49
horizons/world/island.py
python
Island.__init__
(self, db, island_id, session, preview=False)
@param db: db instance with island table @param island_id: id of island in that table @param session: reference to Session instance @param preview: flag, map preview mode
[]
def __init__(self, db, island_id, session, preview=False): """ @param db: db instance with island table @param island_id: id of island in that table @param session: reference to Session instance @param preview: flag, map preview mode """ super().__init__(worldid=island_id) self.session = session self.terrain_cache = None self.available_land_cache = None self.__init(db, island_id, preview) if not preview: # Create building indexers. from horizons.world.units.animal import WildAnimal self.building_indexers = {} self.building_indexers[BUILDINGS.TREE] = BuildingIndexer(WildAnimal.walking_range, self, self.session.random) # Load settlements. for (settlement_id,) in db("SELECT rowid FROM settlement WHERE island = ?", island_id): settlement = Settlement.load(db, settlement_id, self.session, self) self.settlements.append(settlement) if preview: # Caches and buildings are not required for map preview. return self.terrain_cache = TerrainBuildabilityCache(self) flat_land_set = self.terrain_cache.cache[TerrainRequirement.LAND][(1, 1)] self.available_flat_land = len(flat_land_set) available_coords_set = set(self.terrain_cache.land_or_coast) for settlement in self.settlements: settlement.init_buildability_cache(self.terrain_cache) for coords in settlement.ground_map: available_coords_set.discard(coords) if coords in flat_land_set: self.available_flat_land -= 1 self.available_land_cache = FreeIslandBuildabilityCache(self) # Load buildings. from horizons.world import load_building buildings = db("SELECT rowid, type FROM building WHERE location = ?", island_id) for (building_worldid, building_typeid) in buildings: load_building(self.session, db, building_typeid, building_worldid)
[ "def", "__init__", "(", "self", ",", "db", ",", "island_id", ",", "session", ",", "preview", "=", "False", ")", ":", "super", "(", ")", ".", "__init__", "(", "worldid", "=", "island_id", ")", "self", ".", "session", "=", "session", "self", ".", "terr...
https://github.com/unknown-horizons/unknown-horizons/blob/7397fb333006d26c3d9fe796c7bd9cb8c3b43a49/horizons/world/island.py#L74-L122
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/_contour.py
python
Contour.autocontour
(self)
return self["autocontour"]
Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. The 'autocontour' property must be specified as a bool (either True, or False) Returns ------- bool
Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. The 'autocontour' property must be specified as a bool (either True, or False)
[ "Determines", "whether", "or", "not", "the", "contour", "level", "attributes", "are", "picked", "by", "an", "algorithm", ".", "If", "True", "the", "number", "of", "contour", "levels", "can", "be", "set", "in", "ncontours", ".", "If", "False", "set", "the",...
def autocontour(self): """ Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. The 'autocontour' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["autocontour"]
[ "def", "autocontour", "(", "self", ")", ":", "return", "self", "[", "\"autocontour\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/_contour.py#L113-L127
eggnogdb/eggnog-mapper
d6e6cdf0a829f2bd85480f3f3f16e38c213cd091
eggnogmapper/annotation/annotator.py
python
Annotator._annotate_ondisk
(self, hits_gen_func, annots_parser)
return
[]
def _annotate_ondisk(self, hits_gen_func, annots_parser): pool = multiprocessing.Pool(self.cpu) chunk_size = 1 # "my recommendation is targeting 10 ms chunk processing time" # https://stackoverflow.com/a/43817408/2361653 # As our tasks take no less than 0.1 secs, a large chunk_size makes no sense at all # Note that this makes q/s an approximation until all tasks have been finished try: for result in pool.imap(annotate_hit_line_ondisk, self.iter_hit_lines(hits_gen_func, annots_parser), chunk_size): yield result except EmapperException: raise except Exception as e: import traceback traceback.print_exc() raise EmapperException(f"Error: annotation failed. "+str(e)) finally: pool.close() pool.terminate() # it should remove the global eggnog_db variables also return
[ "def", "_annotate_ondisk", "(", "self", ",", "hits_gen_func", ",", "annots_parser", ")", ":", "pool", "=", "multiprocessing", ".", "Pool", "(", "self", ".", "cpu", ")", "chunk_size", "=", "1", "# \"my recommendation is targeting 10 ms chunk processing time\"", "# http...
https://github.com/eggnogdb/eggnog-mapper/blob/d6e6cdf0a829f2bd85480f3f3f16e38c213cd091/eggnogmapper/annotation/annotator.py#L240-L265
OpenMDAO/OpenMDAO
f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd
openmdao/vectors/vector.py
python
Vector.set_vals
(self, vals)
Set the data array of this vector using a value or iter of values, one for each variable. The values must be in the same order as the variables appear in this Vector. Parameters ---------- vals : ndarray, float, or iter of ndarrays and/or floats Values for each variable contained in this vector, in the proper order.
Set the data array of this vector using a value or iter of values, one for each variable.
[ "Set", "the", "data", "array", "of", "this", "vector", "using", "a", "value", "or", "iter", "of", "values", "one", "for", "each", "variable", "." ]
def set_vals(self, vals): """ Set the data array of this vector using a value or iter of values, one for each variable. The values must be in the same order as the variables appear in this Vector. Parameters ---------- vals : ndarray, float, or iter of ndarrays and/or floats Values for each variable contained in this vector, in the proper order. """ arr = self.asarray() if self.nvars() == 1: if isscalar(vals): arr[:] = vals else: arr[:] = vals.ravel() else: start = end = 0 for v in vals: if isscalar(v): end += 1 arr[start] = v else: end += v.size arr[start:end] = v.ravel() start = end
[ "def", "set_vals", "(", "self", ",", "vals", ")", ":", "arr", "=", "self", ".", "asarray", "(", ")", "if", "self", ".", "nvars", "(", ")", "==", "1", ":", "if", "isscalar", "(", "vals", ")", ":", "arr", "[", ":", "]", "=", "vals", "else", ":"...
https://github.com/OpenMDAO/OpenMDAO/blob/f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd/openmdao/vectors/vector.py#L558-L585
ChenRocks/fast_abs_rl
a3cd65016082ab842be4e42b0b26b7bc046f4ad5
metric.py
python
_lcs_dp
(a, b)
return dp
compute the len dp of lcs
compute the len dp of lcs
[ "compute", "the", "len", "dp", "of", "lcs" ]
def _lcs_dp(a, b): """ compute the len dp of lcs""" dp = [[0 for _ in range(0, len(b)+1)] for _ in range(0, len(a)+1)] # dp[i][j]: lcs_len(a[:i], b[:j]) for i in range(1, len(a)+1): for j in range(1, len(b)+1): if a[i-1] == b[j-1]: dp[i][j] = dp[i-1][j-1] + 1 else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) return dp
[ "def", "_lcs_dp", "(", "a", ",", "b", ")", ":", "dp", "=", "[", "[", "0", "for", "_", "in", "range", "(", "0", ",", "len", "(", "b", ")", "+", "1", ")", "]", "for", "_", "in", "range", "(", "0", ",", "len", "(", "a", ")", "+", "1", ")...
https://github.com/ChenRocks/fast_abs_rl/blob/a3cd65016082ab842be4e42b0b26b7bc046f4ad5/metric.py#L42-L53
aliyun/aliyun-oss-python-sdk
5f2afa0928a58c7c1cc6317ac147f3637481f6fd
oss2/resumable.py
python
_ResumableOperation.__init__
(self, bucket, key, filename, size, store, progress_callback=None, versionid=None)
[]
def __init__(self, bucket, key, filename, size, store, progress_callback=None, versionid=None): self.bucket = bucket self.key = to_string(key) self.filename = filename self.size = size self._abspath = os.path.abspath(filename) self.__store = store if versionid is None: self.__record_key = self.__store.make_store_key(bucket.bucket_name, self.key, self._abspath) else: self.__record_key = self.__store.make_store_key(bucket.bucket_name, self.key, self._abspath, versionid) logger.debug("Init _ResumableOperation, record_key: {0}".format(self.__record_key)) # protect self.__progress_callback self.__plock = threading.Lock() self.__progress_callback = progress_callback
[ "def", "__init__", "(", "self", ",", "bucket", ",", "key", ",", "filename", ",", "size", ",", "store", ",", "progress_callback", "=", "None", ",", "versionid", "=", "None", ")", ":", "self", ".", "bucket", "=", "bucket", "self", ".", "key", "=", "to_...
https://github.com/aliyun/aliyun-oss-python-sdk/blob/5f2afa0928a58c7c1cc6317ac147f3637481f6fd/oss2/resumable.py#L291-L311