repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
IdentityPython/oidcendpoint
src/oidcendpoint/oidc/authorization.py
Authorization.authz_part2
def authz_part2(self, user, authn_event, request, **kwargs): """ After the authentication this is where you should end up :param user: :param request: The Authorization Request :param sid: Session key :param kwargs: possible other parameters :return: A redirect t...
python
def authz_part2(self, user, authn_event, request, **kwargs): """ After the authentication this is where you should end up :param user: :param request: The Authorization Request :param sid: Session key :param kwargs: possible other parameters :return: A redirect t...
[ "def", "authz_part2", "(", "self", ",", "user", ",", "authn_event", ",", "request", ",", "*", "*", "kwargs", ")", ":", "sid", "=", "setup_session", "(", "self", ".", "endpoint_context", ",", "request", ",", "user", ",", "authn_event", "=", "authn_event", ...
After the authentication this is where you should end up :param user: :param request: The Authorization Request :param sid: Session key :param kwargs: possible other parameters :return: A redirect to the redirect_uri of the client
[ "After", "the", "authentication", "this", "is", "where", "you", "should", "end", "up" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/oidc/authorization.py#L642-L693
IdentityPython/oidcendpoint
src/oidcendpoint/oidc/authorization.py
Authorization.process_request
def process_request(self, request_info=None, **kwargs): """ The AuthorizationRequest endpoint :param request_info: The authorization request as a dictionary :return: dictionary """ if isinstance(request_info, AuthorizationErrorResponse): return request_info ...
python
def process_request(self, request_info=None, **kwargs): """ The AuthorizationRequest endpoint :param request_info: The authorization request as a dictionary :return: dictionary """ if isinstance(request_info, AuthorizationErrorResponse): return request_info ...
[ "def", "process_request", "(", "self", ",", "request_info", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "request_info", ",", "AuthorizationErrorResponse", ")", ":", "return", "request_info", "_cid", "=", "request_info", "[", "\"cli...
The AuthorizationRequest endpoint :param request_info: The authorization request as a dictionary :return: dictionary
[ "The", "AuthorizationRequest", "endpoint" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/oidc/authorization.py#L695-L751
IdentityPython/oidcendpoint
src/oidcendpoint/session.py
setup_session
def setup_session(endpoint_context, areq, uid, client_id='', acr='', salt='salt', authn_event=None): """ Setting up a user session :param endpoint_context: :param areq: :param uid: :param acr: :param client_id: :param salt: :param authn_event: A already made AuthnE...
python
def setup_session(endpoint_context, areq, uid, client_id='', acr='', salt='salt', authn_event=None): """ Setting up a user session :param endpoint_context: :param areq: :param uid: :param acr: :param client_id: :param salt: :param authn_event: A already made AuthnE...
[ "def", "setup_session", "(", "endpoint_context", ",", "areq", ",", "uid", ",", "client_id", "=", "''", ",", "acr", "=", "''", ",", "salt", "=", "'salt'", ",", "authn_event", "=", "None", ")", ":", "if", "authn_event", "is", "None", "and", "acr", ":", ...
Setting up a user session :param endpoint_context: :param areq: :param uid: :param acr: :param client_id: :param salt: :param authn_event: A already made AuthnEvent :return:
[ "Setting", "up", "a", "user", "session" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L44-L69
IdentityPython/oidcendpoint
src/oidcendpoint/session.py
dict_match
def dict_match(a, b): """ Check if all attribute/value pairs in a also appears in b :param a: A dictionary :param b: A dictionary :return: True/False """ res = [] for k, v in a.items(): try: res.append(b[k] == v) except KeyError: pass return a...
python
def dict_match(a, b): """ Check if all attribute/value pairs in a also appears in b :param a: A dictionary :param b: A dictionary :return: True/False """ res = [] for k, v in a.items(): try: res.append(b[k] == v) except KeyError: pass return a...
[ "def", "dict_match", "(", "a", ",", "b", ")", ":", "res", "=", "[", "]", "for", "k", ",", "v", "in", "a", ".", "items", "(", ")", ":", "try", ":", "res", ".", "append", "(", "b", "[", "k", "]", "==", "v", ")", "except", "KeyError", ":", "...
Check if all attribute/value pairs in a also appears in b :param a: A dictionary :param b: A dictionary :return: True/False
[ "Check", "if", "all", "attribute", "/", "value", "pairs", "in", "a", "also", "appears", "in", "b" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L92-L106
IdentityPython/oidcendpoint
src/oidcendpoint/session.py
mint_sub
def mint_sub(client_salt, sector_id="", subject_type="public", uid='', user_salt=''): """ Mint a new sub (subject identifier) :param authn_event: Authentication event information :param client_salt: client specific salt - used in pairwise :param sector_id: Possible sector identifier ...
python
def mint_sub(client_salt, sector_id="", subject_type="public", uid='', user_salt=''): """ Mint a new sub (subject identifier) :param authn_event: Authentication event information :param client_salt: client specific salt - used in pairwise :param sector_id: Possible sector identifier ...
[ "def", "mint_sub", "(", "client_salt", ",", "sector_id", "=", "\"\"", ",", "subject_type", "=", "\"public\"", ",", "uid", "=", "''", ",", "user_salt", "=", "''", ")", ":", "if", "subject_type", "==", "\"public\"", ":", "sub", "=", "hashlib", ".", "sha256...
Mint a new sub (subject identifier) :param authn_event: Authentication event information :param client_salt: client specific salt - used in pairwise :param sector_id: Possible sector identifier :param subject_type: 'public'/'pairwise' :return: Subject identifier
[ "Mint", "a", "new", "sub", "(", "subject", "identifier", ")" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L109-L127
IdentityPython/oidcendpoint
src/oidcendpoint/session.py
SessionDB.update
def update(self, sid, **kwargs): """ Add attribute value assertion to a special session :param sid: Session ID :param kwargs: """ item = self[sid] for attribute, value in kwargs.items(): item[attribute] = value self[sid] = item
python
def update(self, sid, **kwargs): """ Add attribute value assertion to a special session :param sid: Session ID :param kwargs: """ item = self[sid] for attribute, value in kwargs.items(): item[attribute] = value self[sid] = item
[ "def", "update", "(", "self", ",", "sid", ",", "*", "*", "kwargs", ")", ":", "item", "=", "self", "[", "sid", "]", "for", "attribute", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "item", "[", "attribute", "]", "=", "value", "self",...
Add attribute value assertion to a special session :param sid: Session ID :param kwargs:
[ "Add", "attribute", "value", "assertion", "to", "a", "special", "session" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L204-L214
IdentityPython/oidcendpoint
src/oidcendpoint/session.py
SessionDB.update_by_token
def update_by_token(self, token, **kwargs): """ Updated the session info. Any type of known token can be used :param token: code/access token/refresh token/... :param kwargs: Key word arguements """ _sid = self.handler.sid(token) return self.update(_sid, **kwargs...
python
def update_by_token(self, token, **kwargs): """ Updated the session info. Any type of known token can be used :param token: code/access token/refresh token/... :param kwargs: Key word arguements """ _sid = self.handler.sid(token) return self.update(_sid, **kwargs...
[ "def", "update_by_token", "(", "self", ",", "token", ",", "*", "*", "kwargs", ")", ":", "_sid", "=", "self", ".", "handler", ".", "sid", "(", "token", ")", "return", "self", ".", "update", "(", "_sid", ",", "*", "*", "kwargs", ")" ]
Updated the session info. Any type of known token can be used :param token: code/access token/refresh token/... :param kwargs: Key word arguements
[ "Updated", "the", "session", "info", ".", "Any", "type", "of", "known", "token", "can", "be", "used" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L216-L224
IdentityPython/oidcendpoint
src/oidcendpoint/session.py
SessionDB.replace_token
def replace_token(self, sid, sinfo, token_type): """ Replace an old refresh_token with a new one :param sid: session ID :param sinfo: session info :param token_type: What type of tokens should be replaced :return: Updated session info """ try: ...
python
def replace_token(self, sid, sinfo, token_type): """ Replace an old refresh_token with a new one :param sid: session ID :param sinfo: session info :param token_type: What type of tokens should be replaced :return: Updated session info """ try: ...
[ "def", "replace_token", "(", "self", ",", "sid", ",", "sinfo", ",", "token_type", ")", ":", "try", ":", "# Mint a new one", "refresh_token", "=", "self", ".", "handler", "[", "token_type", "]", "(", "sid", ",", "sinfo", "=", "sinfo", ")", "except", "KeyE...
Replace an old refresh_token with a new one :param sid: session ID :param sinfo: session info :param token_type: What type of tokens should be replaced :return: Updated session info
[ "Replace", "an", "old", "refresh_token", "with", "a", "new", "one" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L268-L291
IdentityPython/oidcendpoint
src/oidcendpoint/session.py
SessionDB.refresh_token
def refresh_token(self, token, new_refresh=False): """ Issue a new access token using a valid refresh token :param token: Refresh token :param new_refresh: Whether a new refresh token should be minted or not :return: Dictionary with session info :raises: ExpiredToken for...
python
def refresh_token(self, token, new_refresh=False): """ Issue a new access token using a valid refresh token :param token: Refresh token :param new_refresh: Whether a new refresh token should be minted or not :return: Dictionary with session info :raises: ExpiredToken for...
[ "def", "refresh_token", "(", "self", ",", "token", ",", "new_refresh", "=", "False", ")", ":", "try", ":", "_tinfo", "=", "self", ".", "handler", "[", "'refresh_token'", "]", ".", "info", "(", "token", ")", "except", "KeyError", ":", "return", "False", ...
Issue a new access token using a valid refresh token :param token: Refresh token :param new_refresh: Whether a new refresh token should be minted or not :return: Dictionary with session info :raises: ExpiredToken for invalid refresh token WrongTokenType for wrong token ...
[ "Issue", "a", "new", "access", "token", "using", "a", "valid", "refresh", "token" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L356-L387
IdentityPython/oidcendpoint
src/oidcendpoint/session.py
SessionDB.is_token_valid
def is_token_valid(self, token): """ Checks validity of a given token :param token: Access or refresh token """ try: _tinfo = self.handler.info(token) except KeyError: return False if is_expired(int(_tinfo['exp'])) or _tinfo['black_liste...
python
def is_token_valid(self, token): """ Checks validity of a given token :param token: Access or refresh token """ try: _tinfo = self.handler.info(token) except KeyError: return False if is_expired(int(_tinfo['exp'])) or _tinfo['black_liste...
[ "def", "is_token_valid", "(", "self", ",", "token", ")", ":", "try", ":", "_tinfo", "=", "self", ".", "handler", ".", "info", "(", "token", ")", "except", "KeyError", ":", "return", "False", "if", "is_expired", "(", "int", "(", "_tinfo", "[", "'exp'", ...
Checks validity of a given token :param token: Access or refresh token
[ "Checks", "validity", "of", "a", "given", "token" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L389-L414
IdentityPython/oidcendpoint
src/oidcendpoint/session.py
SessionDB.revoke_token
def revoke_token(self, token, token_type=''): """ Revokes access token :param token: access token """ if token_type: self.handler[token_type].black_list(token) else: self.handler.black_list(token)
python
def revoke_token(self, token, token_type=''): """ Revokes access token :param token: access token """ if token_type: self.handler[token_type].black_list(token) else: self.handler.black_list(token)
[ "def", "revoke_token", "(", "self", ",", "token", ",", "token_type", "=", "''", ")", ":", "if", "token_type", ":", "self", ".", "handler", "[", "token_type", "]", ".", "black_list", "(", "token", ")", "else", ":", "self", ".", "handler", ".", "black_li...
Revokes access token :param token: access token
[ "Revokes", "access", "token" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L416-L425
IdentityPython/oidcendpoint
src/oidcendpoint/session.py
SessionDB.revoke_session
def revoke_session(self, sid='', token=''): """ Mark session as revoked but also explicitly revoke all issued tokens :param token: any token connected to the session :param sid: Session identifier """ if not sid: if token: sid = self.handler.s...
python
def revoke_session(self, sid='', token=''): """ Mark session as revoked but also explicitly revoke all issued tokens :param token: any token connected to the session :param sid: Session identifier """ if not sid: if token: sid = self.handler.s...
[ "def", "revoke_session", "(", "self", ",", "sid", "=", "''", ",", "token", "=", "''", ")", ":", "if", "not", "sid", ":", "if", "token", ":", "sid", "=", "self", ".", "handler", ".", "sid", "(", "token", ")", "else", ":", "raise", "ValueError", "(...
Mark session as revoked but also explicitly revoke all issued tokens :param token: any token connected to the session :param sid: Session identifier
[ "Mark", "session", "as", "revoked", "but", "also", "explicitly", "revoke", "all", "issued", "tokens" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/session.py#L435-L454
guaix-ucm/pyemir
emirdrp/processing/wavecal/rectwv_coeff_add_longslit_model.py
rectwv_coeff_add_longslit_model
def rectwv_coeff_add_longslit_model(rectwv_coeff, geometry, debugplot=0): """Compute longslit_model coefficients for RectWaveCoeff object. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for a particular CSU configuration...
python
def rectwv_coeff_add_longslit_model(rectwv_coeff, geometry, debugplot=0): """Compute longslit_model coefficients for RectWaveCoeff object. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for a particular CSU configuration...
[ "def", "rectwv_coeff_add_longslit_model", "(", "rectwv_coeff", ",", "geometry", ",", "debugplot", "=", "0", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "# check grism and filter", "grism_name", "=", "rectwv_coeff", ".", "tags", "[",...
Compute longslit_model coefficients for RectWaveCoeff object. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for a particular CSU configuration corresponding to a longslit observation. geometry : TBD debugplo...
[ "Compute", "longslit_model", "coefficients", "for", "RectWaveCoeff", "object", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/rectwv_coeff_add_longslit_model.py#L44-L266
IdentityPython/oidcendpoint
src/oidcendpoint/user_authn/authn_context.py
pick_auth
def pick_auth(endpoint_context, areq, all=False): """ Pick authentication method :param areq: AuthorizationRequest instance :return: A dictionary with the authentication method and its authn class ref """ acrs = [] try: if len(endpoint_context.authn_broker) == 1: return...
python
def pick_auth(endpoint_context, areq, all=False): """ Pick authentication method :param areq: AuthorizationRequest instance :return: A dictionary with the authentication method and its authn class ref """ acrs = [] try: if len(endpoint_context.authn_broker) == 1: return...
[ "def", "pick_auth", "(", "endpoint_context", ",", "areq", ",", "all", "=", "False", ")", ":", "acrs", "=", "[", "]", "try", ":", "if", "len", "(", "endpoint_context", ".", "authn_broker", ")", "==", "1", ":", "return", "endpoint_context", ".", "authn_bro...
Pick authentication method :param areq: AuthorizationRequest instance :return: A dictionary with the authentication method and its authn class ref
[ "Pick", "authentication", "method" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/user_authn/authn_context.py#L117-L172
IdentityPython/oidcendpoint
src/oidcendpoint/user_authn/authn_context.py
AuthnBroker.get_method
def get_method(self, cls_name): """ Generator that returns all registered authenticators based on a specific authentication class. :param acr: Authentication Class :return: generator """ for id, spec in self.db.items(): if spec["method"].__class__.__n...
python
def get_method(self, cls_name): """ Generator that returns all registered authenticators based on a specific authentication class. :param acr: Authentication Class :return: generator """ for id, spec in self.db.items(): if spec["method"].__class__.__n...
[ "def", "get_method", "(", "self", ",", "cls_name", ")", ":", "for", "id", ",", "spec", "in", "self", ".", "db", ".", "items", "(", ")", ":", "if", "spec", "[", "\"method\"", "]", ".", "__class__", ".", "__name__", "==", "cls_name", ":", "yield", "s...
Generator that returns all registered authenticators based on a specific authentication class. :param acr: Authentication Class :return: generator
[ "Generator", "that", "returns", "all", "registered", "authenticators", "based", "on", "a", "specific", "authentication", "class", "." ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/user_authn/authn_context.py#L63-L73
IdentityPython/oidcendpoint
src/oidcendpoint/user_authn/authn_context.py
AuthnBroker.pick
def pick(self, acr=None): """ Given the authentication context find zero or more authn methods that could be used. :param acr: The authentication class reference requested :return: An URL """ if acr is None: # Anything else doesn't make sense ...
python
def pick(self, acr=None): """ Given the authentication context find zero or more authn methods that could be used. :param acr: The authentication class reference requested :return: An URL """ if acr is None: # Anything else doesn't make sense ...
[ "def", "pick", "(", "self", ",", "acr", "=", "None", ")", ":", "if", "acr", "is", "None", ":", "# Anything else doesn't make sense", "return", "self", ".", "db", ".", "values", "(", ")", "else", ":", "return", "self", ".", "_pick_by_class_ref", "(", "acr...
Given the authentication context find zero or more authn methods that could be used. :param acr: The authentication class reference requested :return: An URL
[ "Given", "the", "authentication", "context", "find", "zero", "or", "more", "authn", "methods", "that", "could", "be", "used", "." ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/user_authn/authn_context.py#L78-L91
guaix-ucm/pyemir
emirdrp/util/sextractor.py
SExtractor.setup
def setup(self, path=None): """ Look for SExtractor program ('sextractor', or 'sex'). If a full path is provided, only this path is checked. Raise a SExtractorException if it failed. Return program and version if it succeed. """ # -- Finding sextractor program an...
python
def setup(self, path=None): """ Look for SExtractor program ('sextractor', or 'sex'). If a full path is provided, only this path is checked. Raise a SExtractorException if it failed. Return program and version if it succeed. """ # -- Finding sextractor program an...
[ "def", "setup", "(", "self", ",", "path", "=", "None", ")", ":", "# -- Finding sextractor program and its version", "# first look for 'sextractor', then 'sex'", "candidates", "=", "[", "'sextractor'", ",", "'sex'", "]", "if", "(", "path", ")", ":", "candidates", "="...
Look for SExtractor program ('sextractor', or 'sex'). If a full path is provided, only this path is checked. Raise a SExtractorException if it failed. Return program and version if it succeed.
[ "Look", "for", "SExtractor", "program", "(", "sextractor", "or", "sex", ")", ".", "If", "a", "full", "path", "is", "provided", "only", "this", "path", "is", "checked", ".", "Raise", "a", "SExtractorException", "if", "it", "failed", ".", "Return", "program"...
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/util/sextractor.py#L419-L476
guaix-ucm/pyemir
emirdrp/util/sextractor.py
SExtractor.update_config
def update_config(self): """ Update the configuration files according to the current in-memory SExtractor configuration. """ # -- Write filter configuration file # First check the filter itself filter = self.config['FILTER_MASK'] rows = len(filter) ...
python
def update_config(self): """ Update the configuration files according to the current in-memory SExtractor configuration. """ # -- Write filter configuration file # First check the filter itself filter = self.config['FILTER_MASK'] rows = len(filter) ...
[ "def", "update_config", "(", "self", ")", ":", "# -- Write filter configuration file", "# First check the filter itself", "filter", "=", "self", ".", "config", "[", "'FILTER_MASK'", "]", "rows", "=", "len", "(", "filter", ")", "cols", "=", "len", "(", "filter", ...
Update the configuration files according to the current in-memory SExtractor configuration.
[ "Update", "the", "configuration", "files", "according", "to", "the", "current", "in", "-", "memory", "SExtractor", "configuration", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/util/sextractor.py#L478-L531
guaix-ucm/pyemir
emirdrp/util/sextractor.py
SExtractor.run
def run(self, file, updateconfig=True, clean=False, path=None): """ Run SExtractor. If updateconfig is True (default), the configuration files will be updated before running SExtractor. If clean is True (default: False), configuration files (if any) will be deleted afte...
python
def run(self, file, updateconfig=True, clean=False, path=None): """ Run SExtractor. If updateconfig is True (default), the configuration files will be updated before running SExtractor. If clean is True (default: False), configuration files (if any) will be deleted afte...
[ "def", "run", "(", "self", ",", "file", ",", "updateconfig", "=", "True", ",", "clean", "=", "False", ",", "path", "=", "None", ")", ":", "if", "updateconfig", ":", "self", ".", "update_config", "(", ")", "# Try to find SExtractor program", "# This will rais...
Run SExtractor. If updateconfig is True (default), the configuration files will be updated before running SExtractor. If clean is True (default: False), configuration files (if any) will be deleted after SExtractor terminates.
[ "Run", "SExtractor", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/util/sextractor.py#L533-L565
guaix-ucm/pyemir
emirdrp/util/sextractor.py
SExtractor.catalog
def catalog(self): """ Read the output catalog produced by the last SExtractor run. Output is a list of dictionaries, with a dictionary for each star: {'param1': value, 'param2': value, ...}. """ output_f = SExtractorfile(self.config['CATALOG_NAME'], 'r') c = out...
python
def catalog(self): """ Read the output catalog produced by the last SExtractor run. Output is a list of dictionaries, with a dictionary for each star: {'param1': value, 'param2': value, ...}. """ output_f = SExtractorfile(self.config['CATALOG_NAME'], 'r') c = out...
[ "def", "catalog", "(", "self", ")", ":", "output_f", "=", "SExtractorfile", "(", "self", ".", "config", "[", "'CATALOG_NAME'", "]", ",", "'r'", ")", "c", "=", "output_f", ".", "read", "(", ")", "output_f", ".", "close", "(", ")", "return", "c" ]
Read the output catalog produced by the last SExtractor run. Output is a list of dictionaries, with a dictionary for each star: {'param1': value, 'param2': value, ...}.
[ "Read", "the", "output", "catalog", "produced", "by", "the", "last", "SExtractor", "run", ".", "Output", "is", "a", "list", "of", "dictionaries", "with", "a", "dictionary", "for", "each", "star", ":", "{", "param1", ":", "value", "param2", ":", "value", ...
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/util/sextractor.py#L567-L578
guaix-ucm/pyemir
emirdrp/util/sextractor.py
SExtractor.clean
def clean(self, config=True, catalog=False, check=False): """ Remove the generated SExtractor files (if any). If config is True, remove generated configuration files. If catalog is True, remove the output catalog. If check is True, remove output check image. """ ...
python
def clean(self, config=True, catalog=False, check=False): """ Remove the generated SExtractor files (if any). If config is True, remove generated configuration files. If catalog is True, remove the output catalog. If check is True, remove output check image. """ ...
[ "def", "clean", "(", "self", ",", "config", "=", "True", ",", "catalog", "=", "False", ",", "check", "=", "False", ")", ":", "try", ":", "if", "(", "config", ")", ":", "os", ".", "unlink", "(", "self", ".", "config", "[", "'FILTER_NAME'", "]", ")...
Remove the generated SExtractor files (if any). If config is True, remove generated configuration files. If catalog is True, remove the output catalog. If check is True, remove output check image.
[ "Remove", "the", "generated", "SExtractor", "files", "(", "if", "any", ")", ".", "If", "config", "is", "True", "remove", "generated", "configuration", "files", ".", "If", "catalog", "is", "True", "remove", "the", "output", "catalog", ".", "If", "check", "i...
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/util/sextractor.py#L580-L600
guaix-ucm/pyemir
emirdrp/processing/wavecal/refine_rectwv_coeff.py
refine_rectwv_coeff
def refine_rectwv_coeff(input_image, rectwv_coeff, refine_wavecalib_mode, minimum_slitlet_width_mm, maximum_slitlet_width_mm, save_intermediate_results=False, debugplot=0): """Refine RectWaveCoeff...
python
def refine_rectwv_coeff(input_image, rectwv_coeff, refine_wavecalib_mode, minimum_slitlet_width_mm, maximum_slitlet_width_mm, save_intermediate_results=False, debugplot=0): """Refine RectWaveCoeff...
[ "def", "refine_rectwv_coeff", "(", "input_image", ",", "rectwv_coeff", ",", "refine_wavecalib_mode", ",", "minimum_slitlet_width_mm", ",", "maximum_slitlet_width_mm", ",", "save_intermediate_results", "=", "False", ",", "debugplot", "=", "0", ")", ":", "logger", "=", ...
Refine RectWaveCoeff object using a catalogue of lines One and only one among refine_with_oh_lines_mode and refine_with_arc_lines must be different from zero. Parameters ---------- input_image : HDUList object Input 2D image. rectwv_coeff : RectWaveCoeff instance Rectification ...
[ "Refine", "RectWaveCoeff", "object", "using", "a", "catalogue", "of", "lines" ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/refine_rectwv_coeff.py#L49-L381
guaix-ucm/pyemir
emirdrp/tools/select_unrectified_slitlets.py
select_unrectified_slitlet
def select_unrectified_slitlet(image2d, islitlet, csu_bar_slit_center, params, parmodel, maskonly): """Returns image with the indicated slitlet (zero anywhere else). Parameters ---------- image2d : numpy array Initial image from which the slitlet data will be extr...
python
def select_unrectified_slitlet(image2d, islitlet, csu_bar_slit_center, params, parmodel, maskonly): """Returns image with the indicated slitlet (zero anywhere else). Parameters ---------- image2d : numpy array Initial image from which the slitlet data will be extr...
[ "def", "select_unrectified_slitlet", "(", "image2d", ",", "islitlet", ",", "csu_bar_slit_center", ",", "params", ",", "parmodel", ",", "maskonly", ")", ":", "# protection", "if", "image2d", ".", "shape", "!=", "(", "EMIR_NAXIS2", ",", "EMIR_NAXIS1", ")", ":", ...
Returns image with the indicated slitlet (zero anywhere else). Parameters ---------- image2d : numpy array Initial image from which the slitlet data will be extracted. islitlet : int Slitlet number. csu_bar_slit_center : float CSU bar slit center. params : :class:`~lmfit...
[ "Returns", "image", "with", "the", "indicated", "slitlet", "(", "zero", "anywhere", "else", ")", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/tools/select_unrectified_slitlets.py#L47-L108
guaix-ucm/pyemir
emirdrp/processing/wavecal/rectwv_coeff_from_arc_image.py
rectwv_coeff_from_arc_image
def rectwv_coeff_from_arc_image(reduced_image, bound_param, lines_catalog, args_nbrightlines=None, args_ymargin_bb=2, args_remove_sp_background=True, ...
python
def rectwv_coeff_from_arc_image(reduced_image, bound_param, lines_catalog, args_nbrightlines=None, args_ymargin_bb=2, args_remove_sp_background=True, ...
[ "def", "rectwv_coeff_from_arc_image", "(", "reduced_image", ",", "bound_param", ",", "lines_catalog", ",", "args_nbrightlines", "=", "None", ",", "args_ymargin_bb", "=", "2", ",", "args_remove_sp_background", "=", "True", ",", "args_times_sigma_threshold", "=", "10", ...
Evaluate rect.+wavecal. coefficients from arc image Parameters ---------- reduced_image : HDUList object Image with preliminary basic reduction: bpm, bias, dark and flatfield. bound_param : RefinedBoundaryModelParam instance Refined boundary model. lines_catalog : Numpy arra...
[ "Evaluate", "rect", ".", "+", "wavecal", ".", "coefficients", "from", "arc", "image" ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/rectwv_coeff_from_arc_image.py#L60-L625
guaix-ucm/pyemir
emirdrp/processing/wcs.py
offsets_from_wcs
def offsets_from_wcs(frames, pixref): '''Compute offsets between frames using WCS information. :parameter frames: sequence of FITS filenames or file descriptors :parameter pixref: numpy array used as reference pixel The sky world coordinates are computed on *pixref* using the WCS of the first fram...
python
def offsets_from_wcs(frames, pixref): '''Compute offsets between frames using WCS information. :parameter frames: sequence of FITS filenames or file descriptors :parameter pixref: numpy array used as reference pixel The sky world coordinates are computed on *pixref* using the WCS of the first fram...
[ "def", "offsets_from_wcs", "(", "frames", ",", "pixref", ")", ":", "result", "=", "numpy", ".", "zeros", "(", "(", "len", "(", "frames", ")", ",", "pixref", ".", "shape", "[", "1", "]", ")", ")", "with", "frames", "[", "0", "]", ".", "open", "(",...
Compute offsets between frames using WCS information. :parameter frames: sequence of FITS filenames or file descriptors :parameter pixref: numpy array used as reference pixel The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel coordi...
[ "Compute", "offsets", "between", "frames", "using", "WCS", "information", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wcs.py#L24-L54
guaix-ucm/pyemir
emirdrp/processing/wcs.py
reference_pix_from_wcs
def reference_pix_from_wcs(frames, pixref, origin=1): """Compute reference pixels between frames using WCS information. The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel coordinates of the reference sky world-coordinates are compute...
python
def reference_pix_from_wcs(frames, pixref, origin=1): """Compute reference pixels between frames using WCS information. The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel coordinates of the reference sky world-coordinates are compute...
[ "def", "reference_pix_from_wcs", "(", "frames", ",", "pixref", ",", "origin", "=", "1", ")", ":", "result", "=", "[", "]", "with", "frames", "[", "0", "]", ".", "open", "(", ")", "as", "hdulist", ":", "wcsh", "=", "wcs", ".", "WCS", "(", "hdulist",...
Compute reference pixels between frames using WCS information. The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel coordinates of the reference sky world-coordinates are computed for the rest of the frames. The results is a list with...
[ "Compute", "reference", "pixels", "between", "frames", "using", "WCS", "information", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wcs.py#L73-L99
guaix-ucm/pyemir
emirdrp/processing/wcs.py
reference_pix_from_wcs_imgs
def reference_pix_from_wcs_imgs(imgs, pixref, origin=1): """Compute reference pixels between frames using WCS information. The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel coordinates of the reference sky world-coordinates are comp...
python
def reference_pix_from_wcs_imgs(imgs, pixref, origin=1): """Compute reference pixels between frames using WCS information. The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel coordinates of the reference sky world-coordinates are comp...
[ "def", "reference_pix_from_wcs_imgs", "(", "imgs", ",", "pixref", ",", "origin", "=", "1", ")", ":", "result", "=", "[", "]", "refimg", "=", "imgs", "[", "0", "]", "wcsh", "=", "wcs", ".", "WCS", "(", "refimg", "[", "0", "]", ".", "header", ")", ...
Compute reference pixels between frames using WCS information. The sky world coordinates are computed on *pixref* using the WCS of the first frame in the sequence. Then, the pixel coordinates of the reference sky world-coordinates are computed for the rest of the frames. The results is a list with...
[ "Compute", "reference", "pixels", "between", "frames", "using", "WCS", "information", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wcs.py#L102-L128
IdentityPython/oidcendpoint
src/oidcendpoint/oidc/session.py
Session.process_request
def process_request(self, request=None, cookie=None, **kwargs): """ Perform user logout :param request: :param cookie: :param kwargs: :return: """ _cntx = self.endpoint_context _sdb = _cntx.sdb if 'post_logout_redirect_uri' in request: ...
python
def process_request(self, request=None, cookie=None, **kwargs): """ Perform user logout :param request: :param cookie: :param kwargs: :return: """ _cntx = self.endpoint_context _sdb = _cntx.sdb if 'post_logout_redirect_uri' in request: ...
[ "def", "process_request", "(", "self", ",", "request", "=", "None", ",", "cookie", "=", "None", ",", "*", "*", "kwargs", ")", ":", "_cntx", "=", "self", ".", "endpoint_context", "_sdb", "=", "_cntx", ".", "sdb", "if", "'post_logout_redirect_uri'", "in", ...
Perform user logout :param request: :param cookie: :param kwargs: :return:
[ "Perform", "user", "logout" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/oidc/session.py#L193-L314
guaix-ucm/pyemir
emirdrp/processing/wavecal/rectwv_coeff_from_mos_library.py
rectwv_coeff_from_mos_library
def rectwv_coeff_from_mos_library(reduced_image, master_rectwv, ignore_dtu_configuration=True, debugplot=0): """Evaluate rect.+wavecal. coefficients from MOS library Parameters ---------- reduced_image...
python
def rectwv_coeff_from_mos_library(reduced_image, master_rectwv, ignore_dtu_configuration=True, debugplot=0): """Evaluate rect.+wavecal. coefficients from MOS library Parameters ---------- reduced_image...
[ "def", "rectwv_coeff_from_mos_library", "(", "reduced_image", ",", "master_rectwv", ",", "ignore_dtu_configuration", "=", "True", ",", "debugplot", "=", "0", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", ...
Evaluate rect.+wavecal. coefficients from MOS library Parameters ---------- reduced_image : HDUList object Image with preliminary basic reduction: bpm, bias, dark and flatfield. master_rectwv : MasterRectWave instance Rectification and Wavelength Calibrartion Library product. ...
[ "Evaluate", "rect", ".", "+", "wavecal", ".", "coefficients", "from", "MOS", "library" ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/rectwv_coeff_from_mos_library.py#L55-L410
guaix-ucm/pyemir
emirdrp/processing/wavecal/median_slitlets_rectified.py
median_slitlets_rectified
def median_slitlets_rectified( input_image, mode=0, minimum_slitlet_width_mm=EMIR_MINIMUM_SLITLET_WIDTH_MM, maximum_slitlet_width_mm=EMIR_MAXIMUM_SLITLET_WIDTH_MM, debugplot=0 ): """Compute median spectrum for each slitlet. Parameters ---------- input_image :...
python
def median_slitlets_rectified( input_image, mode=0, minimum_slitlet_width_mm=EMIR_MINIMUM_SLITLET_WIDTH_MM, maximum_slitlet_width_mm=EMIR_MAXIMUM_SLITLET_WIDTH_MM, debugplot=0 ): """Compute median spectrum for each slitlet. Parameters ---------- input_image :...
[ "def", "median_slitlets_rectified", "(", "input_image", ",", "mode", "=", "0", ",", "minimum_slitlet_width_mm", "=", "EMIR_MINIMUM_SLITLET_WIDTH_MM", ",", "maximum_slitlet_width_mm", "=", "EMIR_MAXIMUM_SLITLET_WIDTH_MM", ",", "debugplot", "=", "0", ")", ":", "image_header...
Compute median spectrum for each slitlet. Parameters ---------- input_image : HDUList object Input 2D image. mode : int Indicate desired result: 0 : image with the same size as the input image, with the median spectrum of each slitlet spanning all the spectra ...
[ "Compute", "median", "spectrum", "for", "each", "slitlet", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/median_slitlets_rectified.py#L42-L167
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/api.py
_check_deployed_nodes
def _check_deployed_nodes(nodes): """This is borrowed from execo.""" deployed = [] undeployed = [] cmd = "! (mount | grep -E '^/dev/[[:alpha:]]+2 on / ')" deployed_check = get_execo_remote( cmd, nodes, DEFAULT_CONN_PARAMS) for p in deployed_check.processes: p.no...
python
def _check_deployed_nodes(nodes): """This is borrowed from execo.""" deployed = [] undeployed = [] cmd = "! (mount | grep -E '^/dev/[[:alpha:]]+2 on / ')" deployed_check = get_execo_remote( cmd, nodes, DEFAULT_CONN_PARAMS) for p in deployed_check.processes: p.no...
[ "def", "_check_deployed_nodes", "(", "nodes", ")", ":", "deployed", "=", "[", "]", "undeployed", "=", "[", "]", "cmd", "=", "\"! (mount | grep -E '^/dev/[[:alpha:]]+2 on / ')\"", "deployed_check", "=", "get_execo_remote", "(", "cmd", ",", "nodes", ",", "DEFAULT_CONN...
This is borrowed from execo.
[ "This", "is", "borrowed", "from", "execo", "." ]
train
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/api.py#L30-L54
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/api.py
Resources.get_networks
def get_networks(self): """Get the networks assoiated with the resource description. Returns list of tuple roles, network """ networks = self.c_resources["networks"] result = [] for net in networks: _c_network = net.get("_c_network") i...
python
def get_networks(self): """Get the networks assoiated with the resource description. Returns list of tuple roles, network """ networks = self.c_resources["networks"] result = [] for net in networks: _c_network = net.get("_c_network") i...
[ "def", "get_networks", "(", "self", ")", ":", "networks", "=", "self", ".", "c_resources", "[", "\"networks\"", "]", "result", "=", "[", "]", "for", "net", "in", "networks", ":", "_c_network", "=", "net", ".", "get", "(", "\"_c_network\"", ")", "if", "...
Get the networks assoiated with the resource description. Returns list of tuple roles, network
[ "Get", "the", "networks", "assoiated", "with", "the", "resource", "description", "." ]
train
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/api.py#L167-L181
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/api.py
Resources.get_roles
def get_roles(self): """Get the roles associated with the hosts. Returns dict of role -> [host] """ machines = self.c_resources["machines"] result = {} for desc in machines: roles = utils.get_roles_as_list(desc) hosts = self._denormal...
python
def get_roles(self): """Get the roles associated with the hosts. Returns dict of role -> [host] """ machines = self.c_resources["machines"] result = {} for desc in machines: roles = utils.get_roles_as_list(desc) hosts = self._denormal...
[ "def", "get_roles", "(", "self", ")", ":", "machines", "=", "self", ".", "c_resources", "[", "\"machines\"", "]", "result", "=", "{", "}", "for", "desc", "in", "machines", ":", "roles", "=", "utils", ".", "get_roles_as_list", "(", "desc", ")", "hosts", ...
Get the roles associated with the hosts. Returns dict of role -> [host]
[ "Get", "the", "roles", "associated", "with", "the", "hosts", "." ]
train
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/api.py#L183-L198
Fuyukai/asyncwebsockets
asyncwebsockets/websocket.py
Websocket.start_client
async def start_client(self, sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[List] = None, subprotocols: Optional[List[str]] = None): """Start a client WS conne...
python
async def start_client(self, sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[List] = None, subprotocols: Optional[List[str]] = None): """Start a client WS conne...
[ "async", "def", "start_client", "(", "self", ",", "sock", ":", "anyio", ".", "abc", ".", "SocketStream", ",", "addr", ",", "path", ":", "str", ",", "headers", ":", "Optional", "[", "List", "]", "=", "None", ",", "subprotocols", ":", "Optional", "[", ...
Start a client WS connection on this socket. Returns: the AcceptConnection message.
[ "Start", "a", "client", "WS", "connection", "on", "this", "socket", "." ]
train
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/websocket.py#L42-L75
Fuyukai/asyncwebsockets
asyncwebsockets/websocket.py
Websocket.start_server
async def start_server(self, sock: anyio.abc.SocketStream, filter=None): # pylint: disable=W0622 """Start a server WS connection on this socket. Filter: an async callable that gets passed the initial Request. It may return an AcceptConnection message, a bool, or a string (the subprotoc...
python
async def start_server(self, sock: anyio.abc.SocketStream, filter=None): # pylint: disable=W0622 """Start a server WS connection on this socket. Filter: an async callable that gets passed the initial Request. It may return an AcceptConnection message, a bool, or a string (the subprotoc...
[ "async", "def", "start_server", "(", "self", ",", "sock", ":", "anyio", ".", "abc", ".", "SocketStream", ",", "filter", "=", "None", ")", ":", "# pylint: disable=W0622", "assert", "self", ".", "_scope", "is", "None", "self", ".", "_scope", "=", "True", "...
Start a server WS connection on this socket. Filter: an async callable that gets passed the initial Request. It may return an AcceptConnection message, a bool, or a string (the subprotocol to use). Returns: the Request message.
[ "Start", "a", "server", "WS", "connection", "on", "this", "socket", "." ]
train
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/websocket.py#L77-L111
Fuyukai/asyncwebsockets
asyncwebsockets/websocket.py
Websocket._next_event
async def _next_event(self): """ Gets the next event. """ while True: for event in self._connection.events(): if isinstance(event, Message): # check if we need to buffer if event.message_finished: ...
python
async def _next_event(self): """ Gets the next event. """ while True: for event in self._connection.events(): if isinstance(event, Message): # check if we need to buffer if event.message_finished: ...
[ "async", "def", "_next_event", "(", "self", ")", ":", "while", "True", ":", "for", "event", "in", "self", ".", "_connection", ".", "events", "(", ")", ":", "if", "isinstance", "(", "event", ",", "Message", ")", ":", "# check if we need to buffer", "if", ...
Gets the next event.
[ "Gets", "the", "next", "event", "." ]
train
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/websocket.py#L113-L131
Fuyukai/asyncwebsockets
asyncwebsockets/websocket.py
Websocket.close
async def close(self, code: int = 1006, reason: str = "Connection closed"): """ Closes the websocket. """ if self._closed: return self._closed = True if self._scope is not None: await self._scope.cancel() # cancel any outstanding list...
python
async def close(self, code: int = 1006, reason: str = "Connection closed"): """ Closes the websocket. """ if self._closed: return self._closed = True if self._scope is not None: await self._scope.cancel() # cancel any outstanding list...
[ "async", "def", "close", "(", "self", ",", "code", ":", "int", "=", "1006", ",", "reason", ":", "str", "=", "\"Connection closed\"", ")", ":", "if", "self", ".", "_closed", ":", "return", "self", ".", "_closed", "=", "True", "if", "self", ".", "_scop...
Closes the websocket.
[ "Closes", "the", "websocket", "." ]
train
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/websocket.py#L133-L150
Fuyukai/asyncwebsockets
asyncwebsockets/websocket.py
Websocket.send
async def send(self, data: Union[bytes, str], final: bool = True): """ Sends some data down the connection. """ MsgType = TextMessage if isinstance(data, str) else BytesMessage data = MsgType(data=data, message_finished=final) data = self._connection.send(event=data) ...
python
async def send(self, data: Union[bytes, str], final: bool = True): """ Sends some data down the connection. """ MsgType = TextMessage if isinstance(data, str) else BytesMessage data = MsgType(data=data, message_finished=final) data = self._connection.send(event=data) ...
[ "async", "def", "send", "(", "self", ",", "data", ":", "Union", "[", "bytes", ",", "str", "]", ",", "final", ":", "bool", "=", "True", ")", ":", "MsgType", "=", "TextMessage", "if", "isinstance", "(", "data", ",", "str", ")", "else", "BytesMessage", ...
Sends some data down the connection.
[ "Sends", "some", "data", "down", "the", "connection", "." ]
train
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/websocket.py#L152-L159
Fuyukai/asyncwebsockets
asyncwebsockets/websocket.py
Websocket._buffer
def _buffer(self, event: Message): """ Buffers an event, if applicable. """ if isinstance(event, BytesMessage): self._byte_buffer.write(event.data) elif isinstance(event, TextMessage): self._string_buffer.write(event.data)
python
def _buffer(self, event: Message): """ Buffers an event, if applicable. """ if isinstance(event, BytesMessage): self._byte_buffer.write(event.data) elif isinstance(event, TextMessage): self._string_buffer.write(event.data)
[ "def", "_buffer", "(", "self", ",", "event", ":", "Message", ")", ":", "if", "isinstance", "(", "event", ",", "BytesMessage", ")", ":", "self", ".", "_byte_buffer", ".", "write", "(", "event", ".", "data", ")", "elif", "isinstance", "(", "event", ",", ...
Buffers an event, if applicable.
[ "Buffers", "an", "event", "if", "applicable", "." ]
train
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/websocket.py#L161-L168
Fuyukai/asyncwebsockets
asyncwebsockets/websocket.py
Websocket._gather_buffers
def _gather_buffers(self, event: Message): """ Gathers all the data from a buffer. """ if isinstance(event, BytesMessage): buf = self._byte_buffer else: buf = self._string_buffer # yay for code shortening buf.write(event.data) buf....
python
def _gather_buffers(self, event: Message): """ Gathers all the data from a buffer. """ if isinstance(event, BytesMessage): buf = self._byte_buffer else: buf = self._string_buffer # yay for code shortening buf.write(event.data) buf....
[ "def", "_gather_buffers", "(", "self", ",", "event", ":", "Message", ")", ":", "if", "isinstance", "(", "event", ",", "BytesMessage", ")", ":", "buf", "=", "self", ".", "_byte_buffer", "else", ":", "buf", "=", "self", ".", "_string_buffer", "# yay for code...
Gathers all the data from a buffer.
[ "Gathers", "all", "the", "data", "from", "a", "buffer", "." ]
train
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/websocket.py#L170-L185
Fuyukai/asyncwebsockets
asyncwebsockets/websocket.py
Websocket._wrap_data
def _wrap_data(data: Union[str, bytes]): """ Wraps data into the right event. """ MsgType = TextMessage if isinstance(data, str) else BytesMessage return MsgType(data=data, frame_finished=True, message_finished=True)
python
def _wrap_data(data: Union[str, bytes]): """ Wraps data into the right event. """ MsgType = TextMessage if isinstance(data, str) else BytesMessage return MsgType(data=data, frame_finished=True, message_finished=True)
[ "def", "_wrap_data", "(", "data", ":", "Union", "[", "str", ",", "bytes", "]", ")", ":", "MsgType", "=", "TextMessage", "if", "isinstance", "(", "data", ",", "str", ")", "else", "BytesMessage", "return", "MsgType", "(", "data", "=", "data", ",", "frame...
Wraps data into the right event.
[ "Wraps", "data", "into", "the", "right", "event", "." ]
train
https://github.com/Fuyukai/asyncwebsockets/blob/e33e75fd51ce5ae0feac244e8407d2672c5b4745/asyncwebsockets/websocket.py#L188-L193
Jaymon/prom
prom/interface/sqlite.py
SQLite.get_field_SQL
def get_field_SQL(self, field_name, field): """ returns the SQL for a given field with full type information http://www.sqlite.org/datatype3.html field_name -- string -- the field's name field -- Field() -- the set options for the field return -- string -- the field ty...
python
def get_field_SQL(self, field_name, field): """ returns the SQL for a given field with full type information http://www.sqlite.org/datatype3.html field_name -- string -- the field's name field -- Field() -- the set options for the field return -- string -- the field ty...
[ "def", "get_field_SQL", "(", "self", ",", "field_name", ",", "field", ")", ":", "field_type", "=", "\"\"", "is_pk", "=", "field", ".", "options", ".", "get", "(", "'pk'", ",", "False", ")", "if", "issubclass", "(", "field", ".", "type", ",", "bool", ...
returns the SQL for a given field with full type information http://www.sqlite.org/datatype3.html field_name -- string -- the field's name field -- Field() -- the set options for the field return -- string -- the field type (eg, foo BOOL NOT NULL)
[ "returns", "the", "SQL", "for", "a", "given", "field", "with", "full", "type", "information" ]
train
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/sqlite.py#L266-L362
Jaymon/prom
prom/interface/sqlite.py
SQLite._set_table
def _set_table(self, schema, **kwargs): """ http://sqlite.org/lang_createtable.html """ query_str = [] query_str.append("CREATE TABLE {} (".format(self._normalize_table_name(schema))) query_fields = [] for field_name, field in schema.fields.items(): q...
python
def _set_table(self, schema, **kwargs): """ http://sqlite.org/lang_createtable.html """ query_str = [] query_str.append("CREATE TABLE {} (".format(self._normalize_table_name(schema))) query_fields = [] for field_name, field in schema.fields.items(): q...
[ "def", "_set_table", "(", "self", ",", "schema", ",", "*", "*", "kwargs", ")", ":", "query_str", "=", "[", "]", "query_str", ".", "append", "(", "\"CREATE TABLE {} (\"", ".", "format", "(", "self", ".", "_normalize_table_name", "(", "schema", ")", ")", "...
http://sqlite.org/lang_createtable.html
[ "http", ":", "//", "sqlite", ".", "org", "/", "lang_createtable", ".", "html" ]
train
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/sqlite.py#L364-L378
Jaymon/prom
prom/interface/sqlite.py
SQLite._set_index
def _set_index(self, schema, name, fields, **index_options): """ https://www.sqlite.org/lang_createindex.html """ query_str = "CREATE {}INDEX IF NOT EXISTS '{}_{}' ON {} ({})".format( 'UNIQUE ' if index_options.get('unique', False) else '', schema, nam...
python
def _set_index(self, schema, name, fields, **index_options): """ https://www.sqlite.org/lang_createindex.html """ query_str = "CREATE {}INDEX IF NOT EXISTS '{}_{}' ON {} ({})".format( 'UNIQUE ' if index_options.get('unique', False) else '', schema, nam...
[ "def", "_set_index", "(", "self", ",", "schema", ",", "name", ",", "fields", ",", "*", "*", "index_options", ")", ":", "query_str", "=", "\"CREATE {}INDEX IF NOT EXISTS '{}_{}' ON {} ({})\"", ".", "format", "(", "'UNIQUE '", "if", "index_options", ".", "get", "(...
https://www.sqlite.org/lang_createindex.html
[ "https", ":", "//", "www", ".", "sqlite", ".", "org", "/", "lang_createindex", ".", "html" ]
train
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/sqlite.py#L380-L392
Jaymon/prom
prom/interface/sqlite.py
SQLite._get_indexes
def _get_indexes(self, schema, **kwargs): """return all the indexes for the given schema""" # http://www.sqlite.org/pragma.html#schema # http://www.mail-archive.com/sqlite-users@sqlite.org/msg22055.html # http://stackoverflow.com/questions/604939/ ret = {} rs = self._quer...
python
def _get_indexes(self, schema, **kwargs): """return all the indexes for the given schema""" # http://www.sqlite.org/pragma.html#schema # http://www.mail-archive.com/sqlite-users@sqlite.org/msg22055.html # http://stackoverflow.com/questions/604939/ ret = {} rs = self._quer...
[ "def", "_get_indexes", "(", "self", ",", "schema", ",", "*", "*", "kwargs", ")", ":", "# http://www.sqlite.org/pragma.html#schema", "# http://www.mail-archive.com/sqlite-users@sqlite.org/msg22055.html", "# http://stackoverflow.com/questions/604939/", "ret", "=", "{", "}", "rs",...
return all the indexes for the given schema
[ "return", "all", "the", "indexes", "for", "the", "given", "schema" ]
train
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/sqlite.py#L394-L409
Jaymon/prom
prom/interface/sqlite.py
SQLite._get_fields
def _get_fields(self, table_name, **kwargs): """return all the fields for the given table""" ret = {} query_str = 'PRAGMA table_info({})'.format(self._normalize_table_name(table_name)) fields = self._query(query_str, **kwargs) #pout.v([dict(d) for d in fields]) query_str...
python
def _get_fields(self, table_name, **kwargs): """return all the fields for the given table""" ret = {} query_str = 'PRAGMA table_info({})'.format(self._normalize_table_name(table_name)) fields = self._query(query_str, **kwargs) #pout.v([dict(d) for d in fields]) query_str...
[ "def", "_get_fields", "(", "self", ",", "table_name", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "query_str", "=", "'PRAGMA table_info({})'", ".", "format", "(", "self", ".", "_normalize_table_name", "(", "table_name", ")", ")", "fields", "="...
return all the fields for the given table
[ "return", "all", "the", "fields", "for", "the", "given", "table" ]
train
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/sqlite.py#L473-L527
Jaymon/prom
prom/interface/sqlite.py
SQLite._normalize_date_SQL
def _normalize_date_SQL(self, field_name, field_kwargs, symbol): """ allow extracting information from date http://www.sqlite.org/lang_datefunc.html """ fstrs = [] k_opts = { 'day': "CAST(strftime('%d', {}) AS integer)", 'hour': "CAST(strftime('%H...
python
def _normalize_date_SQL(self, field_name, field_kwargs, symbol): """ allow extracting information from date http://www.sqlite.org/lang_datefunc.html """ fstrs = [] k_opts = { 'day': "CAST(strftime('%d', {}) AS integer)", 'hour': "CAST(strftime('%H...
[ "def", "_normalize_date_SQL", "(", "self", ",", "field_name", ",", "field_kwargs", ",", "symbol", ")", ":", "fstrs", "=", "[", "]", "k_opts", "=", "{", "'day'", ":", "\"CAST(strftime('%d', {}) AS integer)\"", ",", "'hour'", ":", "\"CAST(strftime('%H', {}) AS integer...
allow extracting information from date http://www.sqlite.org/lang_datefunc.html
[ "allow", "extracting", "information", "from", "date" ]
train
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/sqlite.py#L529-L551
Jaymon/prom
prom/interface/sqlite.py
SQLite._normalize_sort_SQL
def _normalize_sort_SQL(self, field_name, field_vals, sort_dir_str): """ allow sorting by a set of values http://stackoverflow.com/questions/3303851/sqlite-and-custom-order-by """ fvi = None if sort_dir_str == 'ASC': fvi = (t for t in enumerate(field_vals)) ...
python
def _normalize_sort_SQL(self, field_name, field_vals, sort_dir_str): """ allow sorting by a set of values http://stackoverflow.com/questions/3303851/sqlite-and-custom-order-by """ fvi = None if sort_dir_str == 'ASC': fvi = (t for t in enumerate(field_vals)) ...
[ "def", "_normalize_sort_SQL", "(", "self", ",", "field_name", ",", "field_vals", ",", "sort_dir_str", ")", ":", "fvi", "=", "None", "if", "sort_dir_str", "==", "'ASC'", ":", "fvi", "=", "(", "t", "for", "t", "in", "enumerate", "(", "field_vals", ")", ")"...
allow sorting by a set of values http://stackoverflow.com/questions/3303851/sqlite-and-custom-order-by
[ "allow", "sorting", "by", "a", "set", "of", "values" ]
train
https://github.com/Jaymon/prom/blob/b7ad2c259eca198da03e1e4bc7d95014c168c361/prom/interface/sqlite.py#L553-L574
BreakingBytes/simkit
simkit/core/calculations.py
CalcRegistry.register
def register(self, new_calc, *args, **kwargs): """ Register calculations and meta data. * ``dependencies`` - list of prerequisite calculations * ``always_calc`` - ``True`` if calculation ignores thresholds * ``frequency`` - frequency of calculation in intervals or units of time ...
python
def register(self, new_calc, *args, **kwargs): """ Register calculations and meta data. * ``dependencies`` - list of prerequisite calculations * ``always_calc`` - ``True`` if calculation ignores thresholds * ``frequency`` - frequency of calculation in intervals or units of time ...
[ "def", "register", "(", "self", ",", "new_calc", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "zip", "(", "self", ".", "meta_names", ",", "args", ")", ")", "# dependencies should be a list of other calculations", "if", ...
Register calculations and meta data. * ``dependencies`` - list of prerequisite calculations * ``always_calc`` - ``True`` if calculation ignores thresholds * ``frequency`` - frequency of calculation in intervals or units of time :param new_calc: register new calculation
[ "Register", "calculations", "and", "meta", "data", "." ]
train
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/calculations.py#L41-L56
guaix-ucm/pyemir
emirdrp/processing/bars.py
slits_to_ds9_reg
def slits_to_ds9_reg(ds9reg, slits): """Transform fiber traces to ds9-region format. Parameters ---------- ds9reg : BinaryIO Handle to output file name in ds9-region format. """ # open output file and insert header ds9reg.write('# Region file format: DS9 version 4.1\n') ds9reg...
python
def slits_to_ds9_reg(ds9reg, slits): """Transform fiber traces to ds9-region format. Parameters ---------- ds9reg : BinaryIO Handle to output file name in ds9-region format. """ # open output file and insert header ds9reg.write('# Region file format: DS9 version 4.1\n') ds9reg...
[ "def", "slits_to_ds9_reg", "(", "ds9reg", ",", "slits", ")", ":", "# open output file and insert header", "ds9reg", ".", "write", "(", "'# Region file format: DS9 version 4.1\\n'", ")", "ds9reg", ".", "write", "(", "'global color=green dashlist=8 3 width=1 font=\"helvetica 10 '...
Transform fiber traces to ds9-region format. Parameters ---------- ds9reg : BinaryIO Handle to output file name in ds9-region format.
[ "Transform", "fiber", "traces", "to", "ds9", "-", "region", "format", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/bars.py#L192-L218
BreakingBytes/simkit
simkit/core/simulations.py
id_maker
def id_maker(obj): """ Makes an ID from the object's class name and the datetime now in ISO format. :param obj: the class from which to make the ID :return: ID """ dtfmt = '%Y%m%d-%H%M%S' return '%s-%s' % (obj.__class__.__name__, datetime.now().strftime(dtfmt))
python
def id_maker(obj): """ Makes an ID from the object's class name and the datetime now in ISO format. :param obj: the class from which to make the ID :return: ID """ dtfmt = '%Y%m%d-%H%M%S' return '%s-%s' % (obj.__class__.__name__, datetime.now().strftime(dtfmt))
[ "def", "id_maker", "(", "obj", ")", ":", "dtfmt", "=", "'%Y%m%d-%H%M%S'", "return", "'%s-%s'", "%", "(", "obj", ".", "__class__", ".", "__name__", ",", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "dtfmt", ")", ")" ]
Makes an ID from the object's class name and the datetime now in ISO format. :param obj: the class from which to make the ID :return: ID
[ "Makes", "an", "ID", "from", "the", "object", "s", "class", "name", "and", "the", "datetime", "now", "in", "ISO", "format", "." ]
train
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/simulations.py#L38-L46
BreakingBytes/simkit
simkit/core/simulations.py
topological_sort
def topological_sort(dag): """ topological sort :param dag: directed acyclic graph :type dag: dict .. seealso:: `Topographical Sorting <http://en.wikipedia.org/wiki/Topological_sorting>`_, `Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`...
python
def topological_sort(dag): """ topological sort :param dag: directed acyclic graph :type dag: dict .. seealso:: `Topographical Sorting <http://en.wikipedia.org/wiki/Topological_sorting>`_, `Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`...
[ "def", "topological_sort", "(", "dag", ")", ":", "# find all edges of dag", "topsort", "=", "[", "node", "for", "node", ",", "edge", "in", "dag", ".", "iteritems", "(", ")", "if", "not", "edge", "]", "# loop through nodes until topologically sorted", "while", "l...
topological sort :param dag: directed acyclic graph :type dag: dict .. seealso:: `Topographical Sorting <http://en.wikipedia.org/wiki/Topological_sorting>`_, `Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`_
[ "topological", "sort" ]
train
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/simulations.py#L69-L95
BreakingBytes/simkit
simkit/core/simulations.py
SimRegistry.register
def register(self, sim, *args, **kwargs): """ register simulation and metadata. * ``commands`` - list of methods to callable from model :param sim: new simulation """ kwargs.update(zip(self.meta_names, args)) # call super method, now meta can be passed as args o...
python
def register(self, sim, *args, **kwargs): """ register simulation and metadata. * ``commands`` - list of methods to callable from model :param sim: new simulation """ kwargs.update(zip(self.meta_names, args)) # call super method, now meta can be passed as args o...
[ "def", "register", "(", "self", ",", "sim", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "zip", "(", "self", ".", "meta_names", ",", "args", ")", ")", "# call super method, now meta can be passed as args or kwargs.", "su...
register simulation and metadata. * ``commands`` - list of methods to callable from model :param sim: new simulation
[ "register", "simulation", "and", "metadata", "." ]
train
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/simulations.py#L111-L121
BreakingBytes/simkit
simkit/core/simulations.py
Simulation.check_data
def check_data(self, data): """ Check if data loaded for all sources in data layer. :param data: data layer from model :type data: :class:`~simkit.core.layer.Data` :return: dictionary of data sources and objects or `None` if not loaded """ data_objs = { ...
python
def check_data(self, data): """ Check if data loaded for all sources in data layer. :param data: data layer from model :type data: :class:`~simkit.core.layer.Data` :return: dictionary of data sources and objects or `None` if not loaded """ data_objs = { ...
[ "def", "check_data", "(", "self", ",", "data", ")", ":", "data_objs", "=", "{", "data_src", ":", "data", ".", "objects", ".", "get", "(", "data_src", ")", "for", "data_src", "in", "data", ".", "layer", "}", "self", ".", "_is_data_loaded", "=", "all", ...
Check if data loaded for all sources in data layer. :param data: data layer from model :type data: :class:`~simkit.core.layer.Data` :return: dictionary of data sources and objects or `None` if not loaded
[ "Check", "if", "data", "loaded", "for", "all", "sources", "in", "data", "layer", "." ]
train
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/simulations.py#L303-L315
BreakingBytes/simkit
simkit/core/simulations.py
Simulation.initialize
def initialize(self, calc_reg): """ Initialize the simulation. Organize calculations by dependency. :param calc_reg: Calculation registry. :type calc_reg: :class:`~simkit.core.calculation.CalcRegistry` """ self._isinitialized = True # TODO: if calcula...
python
def initialize(self, calc_reg): """ Initialize the simulation. Organize calculations by dependency. :param calc_reg: Calculation registry. :type calc_reg: :class:`~simkit.core.calculation.CalcRegistry` """ self._isinitialized = True # TODO: if calcula...
[ "def", "initialize", "(", "self", ",", "calc_reg", ")", ":", "self", ".", "_isinitialized", "=", "True", "# TODO: if calculations are edited, loaded, added, etc. then reset", "self", ".", "calc_order", "=", "topological_sort", "(", "calc_reg", ".", "dependencies", ")" ]
Initialize the simulation. Organize calculations by dependency. :param calc_reg: Calculation registry. :type calc_reg: :class:`~simkit.core.calculation.CalcRegistry`
[ "Initialize", "the", "simulation", ".", "Organize", "calculations", "by", "dependency", "." ]
train
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/simulations.py#L317-L327
BreakingBytes/simkit
simkit/core/simulations.py
Simulation.index_iterator
def index_iterator(self): """ Generator that resumes from same index, or restarts from sent index. """ idx = 0 # index while idx < self.number_intervals: new_idx = yield idx idx += 1 if new_idx: idx = new_idx - 1
python
def index_iterator(self): """ Generator that resumes from same index, or restarts from sent index. """ idx = 0 # index while idx < self.number_intervals: new_idx = yield idx idx += 1 if new_idx: idx = new_idx - 1
[ "def", "index_iterator", "(", "self", ")", ":", "idx", "=", "0", "# index", "while", "idx", "<", "self", ".", "number_intervals", ":", "new_idx", "=", "yield", "idx", "idx", "+=", "1", "if", "new_idx", ":", "idx", "=", "new_idx", "-", "1" ]
Generator that resumes from same index, or restarts from sent index.
[ "Generator", "that", "resumes", "from", "same", "index", "or", "restarts", "from", "sent", "index", "." ]
train
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/simulations.py#L329-L338
BreakingBytes/simkit
simkit/core/simulations.py
Simulation.start
def start(self, model, progress_hook=None): """ Start the simulation from time zero. :param model: Model with layers and registries containing parameters :type: :class:`~simkit.core.models.Model` :param progress_hook: A function that receives either a string or a lis...
python
def start(self, model, progress_hook=None): """ Start the simulation from time zero. :param model: Model with layers and registries containing parameters :type: :class:`~simkit.core.models.Model` :param progress_hook: A function that receives either a string or a lis...
[ "def", "start", "(", "self", ",", "model", ",", "progress_hook", "=", "None", ")", ":", "# check if data loaded", "data_objs", "=", "self", ".", "check_data", "(", "model", ".", "data", ")", "if", "not", "self", ".", "is_data_loaded", ":", "raise", "Missin...
Start the simulation from time zero. :param model: Model with layers and registries containing parameters :type: :class:`~simkit.core.models.Model` :param progress_hook: A function that receives either a string or a list containing the index followed by tuples of the data or outputs...
[ "Start", "the", "simulation", "from", "time", "zero", "." ]
train
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/simulations.py#L342-L503
BreakingBytes/simkit
simkit/core/simulations.py
Simulation.pause
def pause(self, progress_hook=None): """ Pause the simulation. How is this different from stopping it? Maintain info sufficient to restart simulation. Sets ``is_paused`` to True. Will this state allow analysis? changing parameters? What can you do with a paused simulation? ...
python
def pause(self, progress_hook=None): """ Pause the simulation. How is this different from stopping it? Maintain info sufficient to restart simulation. Sets ``is_paused`` to True. Will this state allow analysis? changing parameters? What can you do with a paused simulation? ...
[ "def", "pause", "(", "self", ",", "progress_hook", "=", "None", ")", ":", "# default progress hook", "if", "progress_hook", "is", "None", ":", "progress_hook", "=", "sim_progress_hook", "progress_hook", "(", "'simulation paused'", ")", "self", ".", "cmd_queue", "....
Pause the simulation. How is this different from stopping it? Maintain info sufficient to restart simulation. Sets ``is_paused`` to True. Will this state allow analysis? changing parameters? What can you do with a paused simulation? Should be capable of saving paused simulation for loadi...
[ "Pause", "the", "simulation", ".", "How", "is", "this", "different", "from", "stopping", "it?", "Maintain", "info", "sufficient", "to", "restart", "simulation", ".", "Sets", "is_paused", "to", "True", ".", "Will", "this", "state", "allow", "analysis?", "changi...
train
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/simulations.py#L519-L535
guaix-ucm/pyemir
emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py
save_ds9
def save_ds9(output, filename): """Save ds9 region output info filename. Parameters ---------- output : str String containing the full output to be exported as a ds9 region file. filename : str Output file name. """ ds9_file = open(filename, 'wt') ds9_file.writ...
python
def save_ds9(output, filename): """Save ds9 region output info filename. Parameters ---------- output : str String containing the full output to be exported as a ds9 region file. filename : str Output file name. """ ds9_file = open(filename, 'wt') ds9_file.writ...
[ "def", "save_ds9", "(", "output", ",", "filename", ")", ":", "ds9_file", "=", "open", "(", "filename", ",", "'wt'", ")", "ds9_file", ".", "write", "(", "output", ")", "ds9_file", ".", "close", "(", ")" ]
Save ds9 region output info filename. Parameters ---------- output : str String containing the full output to be exported as a ds9 region file. filename : str Output file name.
[ "Save", "ds9", "region", "output", "info", "filename", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py#L41-L56
guaix-ucm/pyemir
emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py
save_four_ds9
def save_four_ds9(rectwv_coeff, debugplot=0): """Save the 4 possible ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugplot : int Debugging level ...
python
def save_four_ds9(rectwv_coeff, debugplot=0): """Save the 4 possible ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugplot : int Debugging level ...
[ "def", "save_four_ds9", "(", "rectwv_coeff", ",", "debugplot", "=", "0", ")", ":", "for", "limits", ",", "rectified", ",", "suffix", "in", "zip", "(", "[", "'frontiers'", ",", "'frontiers'", ",", "'boundaries'", ",", "'boundaries'", "]", ",", "[", "False",...
Save the 4 possible ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugplot : int Debugging level for messages and plots. For details see '...
[ "Save", "the", "4", "possible", "ds9", "region", "files", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py#L59-L84
guaix-ucm/pyemir
emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py
rectwv_coeff_to_ds9
def rectwv_coeff_to_ds9(rectwv_coeff, limits=None, rectified=False, numpix=100): """Generate ds9 region output with requested slitlet limits Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wave...
python
def rectwv_coeff_to_ds9(rectwv_coeff, limits=None, rectified=False, numpix=100): """Generate ds9 region output with requested slitlet limits Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wave...
[ "def", "rectwv_coeff_to_ds9", "(", "rectwv_coeff", ",", "limits", "=", "None", ",", "rectified", "=", "False", ",", "numpix", "=", "100", ")", ":", "# protections", "if", "limits", "not", "in", "[", "'boundaries'", ",", "'frontiers'", "]", ":", "raise", "V...
Generate ds9 region output with requested slitlet limits Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. limits : str Region to be saved: the only two possibilities are 'bound...
[ "Generate", "ds9", "region", "output", "with", "requested", "slitlet", "limits" ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py#L87-L236
guaix-ucm/pyemir
emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py
save_spectral_lines_ds9
def save_spectral_lines_ds9(rectwv_coeff, debugplot=0): """Save expected location of arc and OH airglow to ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugp...
python
def save_spectral_lines_ds9(rectwv_coeff, debugplot=0): """Save expected location of arc and OH airglow to ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugp...
[ "def", "save_spectral_lines_ds9", "(", "rectwv_coeff", ",", "debugplot", "=", "0", ")", ":", "for", "spectral_lines", ",", "rectified", ",", "suffix", "in", "zip", "(", "[", "'arc'", ",", "'arc'", ",", "'oh'", ",", "'oh'", "]", ",", "[", "False", ",", ...
Save expected location of arc and OH airglow to ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugplot : int Debugging level for messages and plots. F...
[ "Save", "expected", "location", "of", "arc", "and", "OH", "airglow", "to", "ds9", "region", "files", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py#L239-L264
guaix-ucm/pyemir
emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py
spectral_lines_to_ds9
def spectral_lines_to_ds9(rectwv_coeff, spectral_lines=None, rectified=False): """Generate ds9 region output with requested spectral lines Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients fo...
python
def spectral_lines_to_ds9(rectwv_coeff, spectral_lines=None, rectified=False): """Generate ds9 region output with requested spectral lines Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients fo...
[ "def", "spectral_lines_to_ds9", "(", "rectwv_coeff", ",", "spectral_lines", "=", "None", ",", "rectified", "=", "False", ")", ":", "# protections", "if", "spectral_lines", "not", "in", "[", "'arc'", ",", "'oh'", "]", ":", "raise", "ValueError", "(", "'Unexpect...
Generate ds9 region output with requested spectral lines Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. spectral_lines : str Spectral lines to be saved: the only two possibil...
[ "Generate", "ds9", "region", "output", "with", "requested", "spectral", "lines" ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/processing/wavecal/rectwv_coeff_to_ds9.py#L267-L456
IdentityPython/oidcendpoint
src/oidcendpoint/endpoint_context.py
EndpointContext.create_providerinfo
def create_providerinfo(self, capabilities): """ Dynamically create the provider info response :param capabilities: :return: """ _pinfo = self.package_capabilities() not_supported = {} for key, val in capabilities.items(): try: ...
python
def create_providerinfo(self, capabilities): """ Dynamically create the provider info response :param capabilities: :return: """ _pinfo = self.package_capabilities() not_supported = {} for key, val in capabilities.items(): try: ...
[ "def", "create_providerinfo", "(", "self", ",", "capabilities", ")", ":", "_pinfo", "=", "self", ".", "package_capabilities", "(", ")", "not_supported", "=", "{", "}", "for", "key", ",", "val", "in", "capabilities", ".", "items", "(", ")", ":", "try", ":...
Dynamically create the provider info response :param capabilities: :return:
[ "Dynamically", "create", "the", "provider", "info", "response" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/endpoint_context.py#L324-L390
TkTech/PyNBT
pynbt/nbt.py
BaseTag._write_utf8
def _write_utf8(write, value): """Writes a length-prefixed UTF-8 string.""" write('h', len(value)) write.io.write(value.encode('utf-8'))
python
def _write_utf8(write, value): """Writes a length-prefixed UTF-8 string.""" write('h', len(value)) write.io.write(value.encode('utf-8'))
[ "def", "_write_utf8", "(", "write", ",", "value", ")", ":", "write", "(", "'h'", ",", "len", "(", "value", ")", ")", "write", ".", "io", ".", "write", "(", "value", ".", "encode", "(", "'utf-8'", ")", ")" ]
Writes a length-prefixed UTF-8 string.
[ "Writes", "a", "length", "-", "prefixed", "UTF", "-", "8", "string", "." ]
train
https://github.com/TkTech/PyNBT/blob/060fb0a2b58fc464a637fc108f05bd7274da8e5f/pynbt/nbt.py#L29-L32
TkTech/PyNBT
pynbt/nbt.py
BaseTag.read
def read(cls, read, has_name=True): """ Read the tag in using the reader `rd`. If `has_name` is `False`, skip reading the tag name. """ name = cls._read_utf8(read) if has_name else None if cls is TAG_Compound: # A TAG_Compound is almost identical to Python's ...
python
def read(cls, read, has_name=True): """ Read the tag in using the reader `rd`. If `has_name` is `False`, skip reading the tag name. """ name = cls._read_utf8(read) if has_name else None if cls is TAG_Compound: # A TAG_Compound is almost identical to Python's ...
[ "def", "read", "(", "cls", ",", "read", ",", "has_name", "=", "True", ")", ":", "name", "=", "cls", ".", "_read_utf8", "(", "read", ")", "if", "has_name", "else", "None", "if", "cls", "is", "TAG_Compound", ":", "# A TAG_Compound is almost identical to Python...
Read the tag in using the reader `rd`. If `has_name` is `False`, skip reading the tag name.
[ "Read", "the", "tag", "in", "using", "the", "reader", "rd", ".", "If", "has_name", "is", "False", "skip", "reading", "the", "tag", "name", "." ]
train
https://github.com/TkTech/PyNBT/blob/060fb0a2b58fc464a637fc108f05bd7274da8e5f/pynbt/nbt.py#L35-L105
TkTech/PyNBT
pynbt/nbt.py
BaseTag.pretty
def pretty(self, indent=0, indent_str=' '): """ Pretty-print a tag in the same general style as Markus's example output. """ return '{0}{1}({2!r}): {3!r}'.format( indent_str * indent, self.__class__.__name__, self.name, self.value ...
python
def pretty(self, indent=0, indent_str=' '): """ Pretty-print a tag in the same general style as Markus's example output. """ return '{0}{1}({2!r}): {3!r}'.format( indent_str * indent, self.__class__.__name__, self.name, self.value ...
[ "def", "pretty", "(", "self", ",", "indent", "=", "0", ",", "indent_str", "=", "' '", ")", ":", "return", "'{0}{1}({2!r}): {3!r}'", ".", "format", "(", "indent_str", "*", "indent", ",", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "name"...
Pretty-print a tag in the same general style as Markus's example output.
[ "Pretty", "-", "print", "a", "tag", "in", "the", "same", "general", "style", "as", "Markus", "s", "example", "output", "." ]
train
https://github.com/TkTech/PyNBT/blob/060fb0a2b58fc464a637fc108f05bd7274da8e5f/pynbt/nbt.py#L153-L163
TkTech/PyNBT
pynbt/nbt.py
TAG_Compound.update
def update(self, *args, **kwargs): """See `__setitem__`.""" super(TAG_Compound, self).update(*args, **kwargs) for key, item in self.items(): if item.name is None: item.name = key
python
def update(self, *args, **kwargs): """See `__setitem__`.""" super(TAG_Compound, self).update(*args, **kwargs) for key, item in self.items(): if item.name is None: item.name = key
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "TAG_Compound", ",", "self", ")", ".", "update", "(", "*", "args", ",", "*", "*", "kwargs", ")", "for", "key", ",", "item", "in", "self", ".", "ite...
See `__setitem__`.
[ "See", "__setitem__", "." ]
train
https://github.com/TkTech/PyNBT/blob/060fb0a2b58fc464a637fc108f05bd7274da8e5f/pynbt/nbt.py#L272-L277
TkTech/PyNBT
pynbt/nbt.py
NBTFile.save
def save(self, io, little_endian=False): """ Saves the `NBTFile()` to `io`, which can be any file-like object providing `write()`. """ if little_endian: write = lambda fmt, *args: io.write(pack('<' + fmt, *args)) else: write = lambda fmt, *args: io...
python
def save(self, io, little_endian=False): """ Saves the `NBTFile()` to `io`, which can be any file-like object providing `write()`. """ if little_endian: write = lambda fmt, *args: io.write(pack('<' + fmt, *args)) else: write = lambda fmt, *args: io...
[ "def", "save", "(", "self", ",", "io", ",", "little_endian", "=", "False", ")", ":", "if", "little_endian", ":", "write", "=", "lambda", "fmt", ",", "*", "args", ":", "io", ".", "write", "(", "pack", "(", "'<'", "+", "fmt", ",", "*", "args", ")",...
Saves the `NBTFile()` to `io`, which can be any file-like object providing `write()`.
[ "Saves", "the", "NBTFile", "()", "to", "io", "which", "can", "be", "any", "file", "-", "like", "object", "providing", "write", "()", "." ]
train
https://github.com/TkTech/PyNBT/blob/060fb0a2b58fc464a637fc108f05bd7274da8e5f/pynbt/nbt.py#L345-L356
IdentityPython/oidcendpoint
src/oidcendpoint/token_handler.py
factory
def factory(ec, code=None, token=None, refresh=None, **kwargs): """ Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance """ TTYPE = {'code': 'A', 'token': 'T', 'refresh': 'R'} args = {} if code: args['code_handler'] = init_...
python
def factory(ec, code=None, token=None, refresh=None, **kwargs): """ Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance """ TTYPE = {'code': 'A', 'token': 'T', 'refresh': 'R'} args = {} if code: args['code_handler'] = init_...
[ "def", "factory", "(", "ec", ",", "code", "=", "None", ",", "token", "=", "None", ",", "refresh", "=", "None", ",", "*", "*", "kwargs", ")", ":", "TTYPE", "=", "{", "'code'", ":", "'A'", ",", "'token'", ":", "'T'", ",", "'refresh'", ":", "'R'", ...
Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance
[ "Create", "a", "token", "handler" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/token_handler.py#L279-L300
IdentityPython/oidcendpoint
src/oidcendpoint/token_handler.py
DefaultToken.key
def key(self, user="", areq=None): """ Return a key (the session id) :param user: User id :param areq: The authorization request :return: An ID """ csum = hashlib.new('sha224') csum.update(rndstr(32).encode('utf-8')) return csum.hexdigest()
python
def key(self, user="", areq=None): """ Return a key (the session id) :param user: User id :param areq: The authorization request :return: An ID """ csum = hashlib.new('sha224') csum.update(rndstr(32).encode('utf-8')) return csum.hexdigest()
[ "def", "key", "(", "self", ",", "user", "=", "\"\"", ",", "areq", "=", "None", ")", ":", "csum", "=", "hashlib", ".", "new", "(", "'sha224'", ")", "csum", ".", "update", "(", "rndstr", "(", "32", ")", ".", "encode", "(", "'utf-8'", ")", ")", "r...
Return a key (the session id) :param user: User id :param areq: The authorization request :return: An ID
[ "Return", "a", "key", "(", "the", "session", "id", ")" ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/token_handler.py#L150-L160
IdentityPython/oidcendpoint
src/oidcendpoint/token_handler.py
DefaultToken.info
def info(self, token): """ Return token information. :param token: A token :return: dictionary with info about the token """ _res = dict(zip(['_id', 'type', 'sid', 'exp'], self.split_token(token))) if _res['type'] != self.type: ...
python
def info(self, token): """ Return token information. :param token: A token :return: dictionary with info about the token """ _res = dict(zip(['_id', 'type', 'sid', 'exp'], self.split_token(token))) if _res['type'] != self.type: ...
[ "def", "info", "(", "self", ",", "token", ")", ":", "_res", "=", "dict", "(", "zip", "(", "[", "'_id'", ",", "'type'", ",", "'sid'", ",", "'exp'", "]", ",", "self", ".", "split_token", "(", "token", ")", ")", ")", "if", "_res", "[", "'type'", "...
Return token information. :param token: A token :return: dictionary with info about the token
[ "Return", "token", "information", "." ]
train
https://github.com/IdentityPython/oidcendpoint/blob/6c1d729d51bfb6332816117fe476073df7a1d823/src/oidcendpoint/token_handler.py#L170-L184
openmicroanalysis/pyxray
pyxray/composition.py
process_wildcard
def process_wildcard(fractions): """ Processes element with a wildcard ``?`` weight fraction and returns composition balanced to 1.0. """ wildcard_zs = set() total_fraction = 0.0 for z, fraction in fractions.items(): if fraction == '?': wildcard_zs.add(z) else: ...
python
def process_wildcard(fractions): """ Processes element with a wildcard ``?`` weight fraction and returns composition balanced to 1.0. """ wildcard_zs = set() total_fraction = 0.0 for z, fraction in fractions.items(): if fraction == '?': wildcard_zs.add(z) else: ...
[ "def", "process_wildcard", "(", "fractions", ")", ":", "wildcard_zs", "=", "set", "(", ")", "total_fraction", "=", "0.0", "for", "z", ",", "fraction", "in", "fractions", ".", "items", "(", ")", ":", "if", "fraction", "==", "'?'", ":", "wildcard_zs", ".",...
Processes element with a wildcard ``?`` weight fraction and returns composition balanced to 1.0.
[ "Processes", "element", "with", "a", "wildcard", "?", "weight", "fraction", "and", "returns", "composition", "balanced", "to", "1", ".", "0", "." ]
train
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/composition.py#L20-L40
openmicroanalysis/pyxray
pyxray/composition.py
convert_mass_to_atomic_fractions
def convert_mass_to_atomic_fractions(mass_fractions): """ Converts a mass fraction :class:`dict` to an atomic fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the v...
python
def convert_mass_to_atomic_fractions(mass_fractions): """ Converts a mass fraction :class:`dict` to an atomic fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the v...
[ "def", "convert_mass_to_atomic_fractions", "(", "mass_fractions", ")", ":", "atomic_fractions", "=", "{", "}", "for", "z", ",", "mass_fraction", "in", "mass_fractions", ".", "items", "(", ")", ":", "atomic_fractions", "[", "z", "]", "=", "mass_fraction", "/", ...
Converts a mass fraction :class:`dict` to an atomic fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the values weight fractions. No wildcard are accepted.
[ "Converts", "a", "mass", "fraction", ":", "class", ":", "dict", "to", "an", "atomic", "fraction", ":", "class", ":", "dict", "." ]
train
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/composition.py#L42-L65
openmicroanalysis/pyxray
pyxray/composition.py
convert_atomic_to_mass_fractions
def convert_atomic_to_mass_fractions(atomic_fractions): """ Converts an atomic fraction :class:`dict` to a mass fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and...
python
def convert_atomic_to_mass_fractions(atomic_fractions): """ Converts an atomic fraction :class:`dict` to a mass fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and...
[ "def", "convert_atomic_to_mass_fractions", "(", "atomic_fractions", ")", ":", "# Calculate total atomic mass", "atomic_masses", "=", "{", "}", "total_atomic_mass", "=", "0.0", "for", "z", ",", "atomic_fraction", "in", "atomic_fractions", ".", "items", "(", ")", ":", ...
Converts an atomic fraction :class:`dict` to a mass fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the values atomic fractions. No wildcard are accepted.
[ "Converts", "an", "atomic", "fraction", ":", "class", ":", "dict", "to", "a", "mass", "fraction", ":", "class", ":", "dict", "." ]
train
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/composition.py#L67-L90
openmicroanalysis/pyxray
pyxray/composition.py
convert_formula_to_atomic_fractions
def convert_formula_to_atomic_fractions(formula): """ Converts a chemical formula to an atomic fraction :class:`dict`. Args: formula (str): chemical formula, like Al2O3. No wildcard are accepted. """ mole_fractions = {} total_mole_fraction = 0.0 for match in CHEMICAL_FORMULA_PATTER...
python
def convert_formula_to_atomic_fractions(formula): """ Converts a chemical formula to an atomic fraction :class:`dict`. Args: formula (str): chemical formula, like Al2O3. No wildcard are accepted. """ mole_fractions = {} total_mole_fraction = 0.0 for match in CHEMICAL_FORMULA_PATTER...
[ "def", "convert_formula_to_atomic_fractions", "(", "formula", ")", ":", "mole_fractions", "=", "{", "}", "total_mole_fraction", "=", "0.0", "for", "match", "in", "CHEMICAL_FORMULA_PATTERN", ".", "finditer", "(", "formula", ")", ":", "symbol", ",", "mole_fraction", ...
Converts a chemical formula to an atomic fraction :class:`dict`. Args: formula (str): chemical formula, like Al2O3. No wildcard are accepted.
[ "Converts", "a", "chemical", "formula", "to", "an", "atomic", "fraction", ":", "class", ":", "dict", "." ]
train
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/composition.py#L92-L120
openmicroanalysis/pyxray
pyxray/composition.py
generate_name
def generate_name(atomic_fractions): """ Generates a name from the composition. The name is generated on the basis of a classical chemical formula. """ if not atomic_fractions: return '' if len(atomic_fractions) == 1: z = list(atomic_fractions.keys())[0] return pyxray.el...
python
def generate_name(atomic_fractions): """ Generates a name from the composition. The name is generated on the basis of a classical chemical formula. """ if not atomic_fractions: return '' if len(atomic_fractions) == 1: z = list(atomic_fractions.keys())[0] return pyxray.el...
[ "def", "generate_name", "(", "atomic_fractions", ")", ":", "if", "not", "atomic_fractions", ":", "return", "''", "if", "len", "(", "atomic_fractions", ")", "==", "1", ":", "z", "=", "list", "(", "atomic_fractions", ".", "keys", "(", ")", ")", "[", "0", ...
Generates a name from the composition. The name is generated on the basis of a classical chemical formula.
[ "Generates", "a", "name", "from", "the", "composition", ".", "The", "name", "is", "generated", "on", "the", "basis", "of", "a", "classical", "chemical", "formula", "." ]
train
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/composition.py#L122-L157
openmicroanalysis/pyxray
pyxray/composition.py
Composition.from_pure
def from_pure(cls, z): """ Creates a pure composition. Args: z (int): atomic number """ return cls(cls._key, {z: 1.0}, {z: 1.0}, pyxray.element_symbol(z))
python
def from_pure(cls, z): """ Creates a pure composition. Args: z (int): atomic number """ return cls(cls._key, {z: 1.0}, {z: 1.0}, pyxray.element_symbol(z))
[ "def", "from_pure", "(", "cls", ",", "z", ")", ":", "return", "cls", "(", "cls", ".", "_key", ",", "{", "z", ":", "1.0", "}", ",", "{", "z", ":", "1.0", "}", ",", "pyxray", ".", "element_symbol", "(", "z", ")", ")" ]
Creates a pure composition. Args: z (int): atomic number
[ "Creates", "a", "pure", "composition", "." ]
train
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/composition.py#L199-L206
openmicroanalysis/pyxray
pyxray/composition.py
Composition.from_mass_fractions
def from_mass_fractions(cls, mass_fractions, formula=None): """ Creates a composition from a mass fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The keys are atomic numbers and the values weight fractions. Wildcard a...
python
def from_mass_fractions(cls, mass_fractions, formula=None): """ Creates a composition from a mass fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The keys are atomic numbers and the values weight fractions. Wildcard a...
[ "def", "from_mass_fractions", "(", "cls", ",", "mass_fractions", ",", "formula", "=", "None", ")", ":", "mass_fractions", "=", "process_wildcard", "(", "mass_fractions", ")", "atomic_fractions", "=", "convert_mass_to_atomic_fractions", "(", "mass_fractions", ")", "if"...
Creates a composition from a mass fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The keys are atomic numbers and the values weight fractions. Wildcard are accepted, e.g. ``{5: '?', 25: 0.4}`` where boron will get a m...
[ "Creates", "a", "composition", "from", "a", "mass", "fraction", ":", "class", ":", "dict", "." ]
train
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/composition.py#L220-L236
openmicroanalysis/pyxray
pyxray/composition.py
Composition.from_atomic_fractions
def from_atomic_fractions(cls, atomic_fractions, formula=None): """ Creates a composition from an atomic fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The keys are atomic numbers and the values atomic fractions. ...
python
def from_atomic_fractions(cls, atomic_fractions, formula=None): """ Creates a composition from an atomic fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The keys are atomic numbers and the values atomic fractions. ...
[ "def", "from_atomic_fractions", "(", "cls", ",", "atomic_fractions", ",", "formula", "=", "None", ")", ":", "atomic_fractions", "=", "process_wildcard", "(", "atomic_fractions", ")", "mass_fractions", "=", "convert_atomic_to_mass_fractions", "(", "atomic_fractions", ")"...
Creates a composition from an atomic fraction :class:`dict`. Args: atomic_fractions (dict): atomic fraction :class:`dict`. The keys are atomic numbers and the values atomic fractions. Wildcard are accepted, e.g. ``{5: '?', 25: 0.4}`` where boron will ...
[ "Creates", "a", "composition", "from", "an", "atomic", "fraction", ":", "class", ":", "dict", "." ]
train
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/composition.py#L239-L255
delvelabs/hammertime
hammertime/rules/status.py
DetectSoft404._collect_sample
async def _collect_sample(self, url, url_pattern): """ Sample collection is meant to be very tolerant to generic failures as failing to obtain the sample has important consequences on the results. - Multiple retries with longer delays - Larger than usual timeout """ ...
python
async def _collect_sample(self, url, url_pattern): """ Sample collection is meant to be very tolerant to generic failures as failing to obtain the sample has important consequences on the results. - Multiple retries with longer delays - Larger than usual timeout """ ...
[ "async", "def", "_collect_sample", "(", "self", ",", "url", ",", "url_pattern", ")", ":", "samples", "=", "[", "]", "urls", "=", "[", "self", ".", "path_generator", ".", "generate_url", "(", "url", ",", "url_pattern", ")", "for", "_", "in", "range", "(...
Sample collection is meant to be very tolerant to generic failures as failing to obtain the sample has important consequences on the results. - Multiple retries with longer delays - Larger than usual timeout
[ "Sample", "collection", "is", "meant", "to", "be", "very", "tolerant", "to", "generic", "failures", "as", "failing", "to", "obtain", "the", "sample", "has", "important", "consequences", "on", "the", "results", "." ]
train
https://github.com/delvelabs/hammertime/blob/0b371499869881c7d12ed71f66e0d6ac9f9a3307/hammertime/rules/status.py#L182-L206
delvelabs/hammertime
hammertime/rules/status.py
SimilarPathGenerator.get_pattern
def get_pattern(self, url): """Return the path part of the URL with the last element replaced with its pattern in a regex-like format: \l -> lowercase letters, same as [a-z]+ \L -> uppercase letters, same as [A-Z]+ \i -> letters ignoring case, same as [a-zA-Z]+ \d -> digits, same...
python
def get_pattern(self, url): """Return the path part of the URL with the last element replaced with its pattern in a regex-like format: \l -> lowercase letters, same as [a-z]+ \L -> uppercase letters, same as [A-Z]+ \i -> letters ignoring case, same as [a-zA-Z]+ \d -> digits, same...
[ "def", "get_pattern", "(", "self", ",", "url", ")", ":", "path", "=", "urlparse", "(", "url", ")", ".", "path", "directories", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "len", "(", "filename", ")", ">", "0", "...
Return the path part of the URL with the last element replaced with its pattern in a regex-like format: \l -> lowercase letters, same as [a-z]+ \L -> uppercase letters, same as [A-Z]+ \i -> letters ignoring case, same as [a-zA-Z]+ \d -> digits, same as \d+ \w -> word characters (...
[ "Return", "the", "path", "part", "of", "the", "URL", "with", "the", "last", "element", "replaced", "with", "its", "pattern", "in", "a", "regex", "-", "like", "format", ":", "\\", "l", "-", ">", "lowercase", "letters", "same", "as", "[", "a", "-", "z"...
train
https://github.com/delvelabs/hammertime/blob/0b371499869881c7d12ed71f66e0d6ac9f9a3307/hammertime/rules/status.py#L241-L258
guaix-ucm/pyemir
emirdrp/tools/overplot_bounddict.py
get_boundaries
def get_boundaries(bounddict_file, slitlet_number): """Read the bounddict json file and return the polynomial boundaries. Parameters ---------- bounddict_file : file handler File containing the bounddict JSON data. slitlet_number : int Number of slitlet. Returns ------- ...
python
def get_boundaries(bounddict_file, slitlet_number): """Read the bounddict json file and return the polynomial boundaries. Parameters ---------- bounddict_file : file handler File containing the bounddict JSON data. slitlet_number : int Number of slitlet. Returns ------- ...
[ "def", "get_boundaries", "(", "bounddict_file", ",", "slitlet_number", ")", ":", "bounddict", "=", "json", ".", "loads", "(", "open", "(", "bounddict_file", ".", "name", ")", ".", "read", "(", ")", ")", "# return values in case the requested slitlet number is not de...
Read the bounddict json file and return the polynomial boundaries. Parameters ---------- bounddict_file : file handler File containing the bounddict JSON data. slitlet_number : int Number of slitlet. Returns ------- pol_lower_boundary : numpy polynomial Polynomial d...
[ "Read", "the", "bounddict", "json", "file", "and", "return", "the", "polynomial", "boundaries", "." ]
train
https://github.com/guaix-ucm/pyemir/blob/fef6bbabcb13f80123cafd1800a0f508a3c21702/emirdrp/tools/overplot_bounddict.py#L38-L104
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/provider.py
_to_enos_roles
def _to_enos_roles(roles): """Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init` """ def to_host(h): extra = {} # create extra_vars for the nics # network_role = ethX ...
python
def _to_enos_roles(roles): """Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init` """ def to_host(h): extra = {} # create extra_vars for the nics # network_role = ethX ...
[ "def", "_to_enos_roles", "(", "roles", ")", ":", "def", "to_host", "(", "h", ")", ":", "extra", "=", "{", "}", "# create extra_vars for the nics", "# network_role = ethX", "for", "nic", ",", "roles", "in", "h", "[", "\"nics\"", "]", ":", "for", "role", "in...
Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init`
[ "Transform", "the", "roles", "to", "use", "enoslib", ".", "host", ".", "Host", "hosts", "." ]
train
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/provider.py#L12-L34
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/provider.py
_to_enos_networks
def _to_enos_networks(networks): """Transform the networks returned by deploy5k. Args: networks (dict): networks returned by :py:func:`enoslib.infra.provider.Provider.init` """ nets = [] for roles, network in networks: nets.append(network.to_enos(roles)) logger.debug...
python
def _to_enos_networks(networks): """Transform the networks returned by deploy5k. Args: networks (dict): networks returned by :py:func:`enoslib.infra.provider.Provider.init` """ nets = [] for roles, network in networks: nets.append(network.to_enos(roles)) logger.debug...
[ "def", "_to_enos_networks", "(", "networks", ")", ":", "nets", "=", "[", "]", "for", "roles", ",", "network", "in", "networks", ":", "nets", ".", "append", "(", "network", ".", "to_enos", "(", "roles", ")", ")", "logger", ".", "debug", "(", "nets", "...
Transform the networks returned by deploy5k. Args: networks (dict): networks returned by :py:func:`enoslib.infra.provider.Provider.init`
[ "Transform", "the", "networks", "returned", "by", "deploy5k", "." ]
train
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/provider.py#L37-L48
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/provider.py
G5k.init
def init(self, force_deploy=False, client=None): """Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be red...
python
def init(self, force_deploy=False, client=None): """Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be red...
[ "def", "init", "(", "self", ",", "force_deploy", "=", "False", ",", "client", "=", "None", ")", ":", "_force_deploy", "=", "self", ".", "provider_conf", ".", "force_deploy", "self", ".", "provider_conf", ".", "force_deploy", "=", "_force_deploy", "or", "forc...
Reserve and deploys the nodes according to the resources section In comparison to the vagrant provider, networks must be characterized as in the networks key. Args: force_deploy (bool): True iff the environment must be redeployed Raises: MissingNetworkError: If ...
[ "Reserve", "and", "deploys", "the", "nodes", "according", "to", "the", "resources", "section" ]
train
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/provider.py#L54-L77
BeyondTheClouds/enoslib
enoslib/infra/enos_g5k/provider.py
G5k.destroy
def destroy(self): """Destroys the jobs.""" r = api.Resources(self.provider_conf.to_dict()) # insert force_deploy r.destroy()
python
def destroy(self): """Destroys the jobs.""" r = api.Resources(self.provider_conf.to_dict()) # insert force_deploy r.destroy()
[ "def", "destroy", "(", "self", ")", ":", "r", "=", "api", ".", "Resources", "(", "self", ".", "provider_conf", ".", "to_dict", "(", ")", ")", "# insert force_deploy", "r", ".", "destroy", "(", ")" ]
Destroys the jobs.
[ "Destroys", "the", "jobs", "." ]
train
https://github.com/BeyondTheClouds/enoslib/blob/fb00be58e56a7848cfe482187d659744919fe2f7/enoslib/infra/enos_g5k/provider.py#L79-L83
openmicroanalysis/pyxray
pyxray/parser/wikipedia.py
WikipediaElementNameParser._find_wikipedia_names
def _find_wikipedia_names(self, name_en): """ Finds all Wikipedia pages referring to the specified name in English and returns a dictionary where the keys are the language code and the values are the titles of the corresponding pages. """ url = 'https://en.wikipedia.org/w...
python
def _find_wikipedia_names(self, name_en): """ Finds all Wikipedia pages referring to the specified name in English and returns a dictionary where the keys are the language code and the values are the titles of the corresponding pages. """ url = 'https://en.wikipedia.org/w...
[ "def", "_find_wikipedia_names", "(", "self", ",", "name_en", ")", ":", "url", "=", "'https://en.wikipedia.org/w/api.php'", "params", "=", "{", "'action'", ":", "'query'", ",", "'titles'", ":", "name_en", ",", "'prop'", ":", "'langlinks'", ",", "'lllimit'", ":", ...
Finds all Wikipedia pages referring to the specified name in English and returns a dictionary where the keys are the language code and the values are the titles of the corresponding pages.
[ "Finds", "all", "Wikipedia", "pages", "referring", "to", "the", "specified", "name", "in", "English", "and", "returns", "a", "dictionary", "where", "the", "keys", "are", "the", "language", "code", "and", "the", "values", "are", "the", "titles", "of", "the", ...
train
https://github.com/openmicroanalysis/pyxray/blob/cae89677f00ebcc0952f94d1ab70e6b35e1a51e9/pyxray/parser/wikipedia.py#L73-L96
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPResponse.append_response
def append_response(self, response): """Append the response to the stack of responses. :param tornado.httpclient.HTTPResponse response: The HTTP response """ self._responses.append(response) if 'Warning' in response.headers: LOGGER.warning( 'HTTP %s ...
python
def append_response(self, response): """Append the response to the stack of responses. :param tornado.httpclient.HTTPResponse response: The HTTP response """ self._responses.append(response) if 'Warning' in response.headers: LOGGER.warning( 'HTTP %s ...
[ "def", "append_response", "(", "self", ",", "response", ")", ":", "self", ".", "_responses", ".", "append", "(", "response", ")", "if", "'Warning'", "in", "response", ".", "headers", ":", "LOGGER", ".", "warning", "(", "'HTTP %s %s Warning (%s): %s (attempt %s)'...
Append the response to the stack of responses. :param tornado.httpclient.HTTPResponse response: The HTTP response
[ "Append", "the", "response", "to", "the", "stack", "of", "responses", "." ]
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L64-L76
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPResponse.body
def body(self): """Returns the HTTP response body, deserialized if possible. :rtype: mixed """ if not self._responses: return None if self._responses[-1].code >= 400: return self._error_message() return self._deserialize()
python
def body(self): """Returns the HTTP response body, deserialized if possible. :rtype: mixed """ if not self._responses: return None if self._responses[-1].code >= 400: return self._error_message() return self._deserialize()
[ "def", "body", "(", "self", ")", ":", "if", "not", "self", ".", "_responses", ":", "return", "None", "if", "self", ".", "_responses", "[", "-", "1", "]", ".", "code", ">=", "400", ":", "return", "self", ".", "_error_message", "(", ")", "return", "s...
Returns the HTTP response body, deserialized if possible. :rtype: mixed
[ "Returns", "the", "HTTP", "response", "body", "deserialized", "if", "possible", "." ]
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L94-L104
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPResponse.links
def links(self): """Return the parsed link header if it was set, returning a list of the links as a dict. :rtype: list(dict()) or None """ if not self._responses: return None if 'Link' in self._responses[-1].headers: links = [] for l ...
python
def links(self): """Return the parsed link header if it was set, returning a list of the links as a dict. :rtype: list(dict()) or None """ if not self._responses: return None if 'Link' in self._responses[-1].headers: links = [] for l ...
[ "def", "links", "(", "self", ")", ":", "if", "not", "self", ".", "_responses", ":", "return", "None", "if", "'Link'", "in", "self", ".", "_responses", "[", "-", "1", "]", ".", "headers", ":", "links", "=", "[", "]", "for", "l", "in", "headers", "...
Return the parsed link header if it was set, returning a list of the links as a dict. :rtype: list(dict()) or None
[ "Return", "the", "parsed", "link", "header", "if", "it", "was", "set", "returning", "a", "list", "of", "the", "links", "as", "a", "dict", "." ]
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L155-L170
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPResponse._decode
def _decode(self, value): """Decode bytes to UTF-8 strings as a singe value, list, or dict. :param mixed value: The value to decode :rtype: mixed """ if isinstance(value, list): return [self._decode(v) for v in value] elif isinstance(value, dict): ...
python
def _decode(self, value): """Decode bytes to UTF-8 strings as a singe value, list, or dict. :param mixed value: The value to decode :rtype: mixed """ if isinstance(value, list): return [self._decode(v) for v in value] elif isinstance(value, dict): ...
[ "def", "_decode", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "[", "self", ".", "_decode", "(", "v", ")", "for", "v", "in", "value", "]", "elif", "isinstance", "(", "value", ",", "dict", ...
Decode bytes to UTF-8 strings as a singe value, list, or dict. :param mixed value: The value to decode :rtype: mixed
[ "Decode", "bytes", "to", "UTF", "-", "8", "strings", "as", "a", "singe", "value", "list", "or", "dict", "." ]
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L196-L210
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPResponse._deserialize
def _deserialize(self): """Try and deserialize a response body based upon the specified content type. :rtype: mixed """ if not self._responses or not self._responses[-1].body: return None if 'Content-Type' not in self._responses[-1].headers: retu...
python
def _deserialize(self): """Try and deserialize a response body based upon the specified content type. :rtype: mixed """ if not self._responses or not self._responses[-1].body: return None if 'Content-Type' not in self._responses[-1].headers: retu...
[ "def", "_deserialize", "(", "self", ")", ":", "if", "not", "self", ".", "_responses", "or", "not", "self", ".", "_responses", "[", "-", "1", "]", ".", "body", ":", "return", "None", "if", "'Content-Type'", "not", "in", "self", ".", "_responses", "[", ...
Try and deserialize a response body based upon the specified content type. :rtype: mixed
[ "Try", "and", "deserialize", "a", "response", "body", "based", "upon", "the", "specified", "content", "type", "." ]
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L212-L236
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPResponse._error_message
def _error_message(self): """Try and extract the error message from a HTTP error response. :rtype: str """ body = self._deserialize() return body.get('message', body) if isinstance(body, dict) else body
python
def _error_message(self): """Try and extract the error message from a HTTP error response. :rtype: str """ body = self._deserialize() return body.get('message', body) if isinstance(body, dict) else body
[ "def", "_error_message", "(", "self", ")", ":", "body", "=", "self", ".", "_deserialize", "(", ")", "return", "body", ".", "get", "(", "'message'", ",", "body", ")", "if", "isinstance", "(", "body", ",", "dict", ")", "else", "body" ]
Try and extract the error message from a HTTP error response. :rtype: str
[ "Try", "and", "extract", "the", "error", "message", "from", "a", "HTTP", "error", "response", "." ]
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L238-L245
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPClientMixin.http_fetch
async def http_fetch(self, url, method='GET', request_headers=None, body=None, content_type=CONTENT_TYPE_MSGPACK, follow_redirects=False, max_redirects=MAX_REDIRECTS, ...
python
async def http_fetch(self, url, method='GET', request_headers=None, body=None, content_type=CONTENT_TYPE_MSGPACK, follow_redirects=False, max_redirects=MAX_REDIRECTS, ...
[ "async", "def", "http_fetch", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "request_headers", "=", "None", ",", "body", "=", "None", ",", "content_type", "=", "CONTENT_TYPE_MSGPACK", ",", "follow_redirects", "=", "False", ",", "max_redirects", ...
Perform a HTTP request Will retry up to ``self.MAX_HTTP_RETRIES`` times. :param str url: The URL for the request :param str method: The HTTP request method, defaults to ``GET`` :param dict request_headers: Headers to include in the HTTP request :param mixed body: The HTTP reque...
[ "Perform", "a", "HTTP", "request" ]
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L265-L392
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPClientMixin._http_req_apply_default_headers
def _http_req_apply_default_headers(self, request_headers, content_type, body): """Set default values for common HTTP request headers :param dict request_headers: The HTTP request headers :param content_type: The mime-type used in the request/response ...
python
def _http_req_apply_default_headers(self, request_headers, content_type, body): """Set default values for common HTTP request headers :param dict request_headers: The HTTP request headers :param content_type: The mime-type used in the request/response ...
[ "def", "_http_req_apply_default_headers", "(", "self", ",", "request_headers", ",", "content_type", ",", "body", ")", ":", "if", "not", "request_headers", ":", "request_headers", "=", "{", "}", "request_headers", ".", "setdefault", "(", "'Accept'", ",", "', '", ...
Set default values for common HTTP request headers :param dict request_headers: The HTTP request headers :param content_type: The mime-type used in the request/response :type content_type: :py:class:`ietfparse.datastructures.ContentType` or str :param mixed body: The request...
[ "Set", "default", "values", "for", "common", "HTTP", "request", "headers" ]
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L394-L420
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPClientMixin._http_req_body_serialize
def _http_req_body_serialize(self, body, content_type): """Conditionally serialize the request body value if mime_type is set and it's serializable. :param mixed body: The request body :param str content_type: The content type for the request body :raises: ValueError ""...
python
def _http_req_body_serialize(self, body, content_type): """Conditionally serialize the request body value if mime_type is set and it's serializable. :param mixed body: The request body :param str content_type: The content type for the request body :raises: ValueError ""...
[ "def", "_http_req_body_serialize", "(", "self", ",", "body", ",", "content_type", ")", ":", "if", "not", "body", "or", "not", "isinstance", "(", "body", ",", "(", "dict", ",", "list", ")", ")", ":", "return", "body", "content_type", "=", "headers", ".", ...
Conditionally serialize the request body value if mime_type is set and it's serializable. :param mixed body: The request body :param str content_type: The content type for the request body :raises: ValueError
[ "Conditionally", "serialize", "the", "request", "body", "value", "if", "mime_type", "is", "set", "and", "it", "s", "serializable", "." ]
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L422-L438
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPClientMixin._http_req_user_agent
def _http_req_user_agent(self): """Return the User-Agent value to specify in HTTP requests, defaulting to ``service/version`` if configured in the application settings, or if used in a consumer, it will attempt to obtain a user-agent from the consumer's process. If it can not auto-set th...
python
def _http_req_user_agent(self): """Return the User-Agent value to specify in HTTP requests, defaulting to ``service/version`` if configured in the application settings, or if used in a consumer, it will attempt to obtain a user-agent from the consumer's process. If it can not auto-set th...
[ "def", "_http_req_user_agent", "(", "self", ")", ":", "# Tornado Request Handler", "try", ":", "return", "'{}/{}'", ".", "format", "(", "self", ".", "settings", "[", "'service'", "]", ",", "self", ".", "settings", "[", "'version'", "]", ")", "except", "(", ...
Return the User-Agent value to specify in HTTP requests, defaulting to ``service/version`` if configured in the application settings, or if used in a consumer, it will attempt to obtain a user-agent from the consumer's process. If it can not auto-set the User-Agent, it defaults to ``spro...
[ "Return", "the", "User", "-", "Agent", "value", "to", "specify", "in", "HTTP", "requests", "defaulting", "to", "service", "/", "version", "if", "configured", "in", "the", "application", "settings", "or", "if", "used", "in", "a", "consumer", "it", "will", "...
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L440-L465
sprockets/sprockets.mixins.http
sprockets/mixins/http/__init__.py
HTTPClientMixin._http_resp_rate_limited
def _http_resp_rate_limited(response): """Extract the ``Retry-After`` header value if the request was rate limited and return a future to sleep for the specified duration. :param tornado.httpclient.HTTPResponse response: The response :rtype: tornado.concurrent.Future """ ...
python
def _http_resp_rate_limited(response): """Extract the ``Retry-After`` header value if the request was rate limited and return a future to sleep for the specified duration. :param tornado.httpclient.HTTPResponse response: The response :rtype: tornado.concurrent.Future """ ...
[ "def", "_http_resp_rate_limited", "(", "response", ")", ":", "parsed", "=", "parse", ".", "urlparse", "(", "response", ".", "request", ".", "url", ")", "duration", "=", "int", "(", "response", ".", "headers", ".", "get", "(", "'Retry-After'", ",", "3", "...
Extract the ``Retry-After`` header value if the request was rate limited and return a future to sleep for the specified duration. :param tornado.httpclient.HTTPResponse response: The response :rtype: tornado.concurrent.Future
[ "Extract", "the", "Retry", "-", "After", "header", "value", "if", "the", "request", "was", "rate", "limited", "and", "return", "a", "future", "to", "sleep", "for", "the", "specified", "duration", "." ]
train
https://github.com/sprockets/sprockets.mixins.http/blob/982219a10be979668726f573f324415fcf2020c8/sprockets/mixins/http/__init__.py#L468-L480
thorgate/tg-utils
tg_utils/lock.py
acquires_lock
def acquires_lock(expires, should_fail=True, should_wait=False, resource=None, prefix=DEFAULT_PREFIX): """ Decorator to ensure function only runs when it is unique holder of the resource. Any invocations of the functions before the first is done will raise RuntimeError. Locks are stored in redis w...
python
def acquires_lock(expires, should_fail=True, should_wait=False, resource=None, prefix=DEFAULT_PREFIX): """ Decorator to ensure function only runs when it is unique holder of the resource. Any invocations of the functions before the first is done will raise RuntimeError. Locks are stored in redis w...
[ "def", "acquires_lock", "(", "expires", ",", "should_fail", "=", "True", ",", "should_wait", "=", "False", ",", "resource", "=", "None", ",", "prefix", "=", "DEFAULT_PREFIX", ")", ":", "# Seconds from now on", "if", "isinstance", "(", "expires", ",", "timedelt...
Decorator to ensure function only runs when it is unique holder of the resource. Any invocations of the functions before the first is done will raise RuntimeError. Locks are stored in redis with prefix: `lock:acquires_lock` Arguments: expires(timedelta|int): Expiry time of lock, way more than...
[ "Decorator", "to", "ensure", "function", "only", "runs", "when", "it", "is", "unique", "holder", "of", "the", "resource", "." ]
train
https://github.com/thorgate/tg-utils/blob/81e404e837334b241686d9159cc3eb44de509a88/tg_utils/lock.py#L36-L124