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
twisted/txacme
src/txacme/client.py
Client._parse_authorization
def _parse_authorization(cls, response, uri=None): """ Parse an authorization resource. """ links = _parse_header_links(response) try: new_cert_uri = links[u'next'][u'url'] except KeyError: raise errors.ClientError('"next" link missing') re...
python
def _parse_authorization(cls, response, uri=None): """ Parse an authorization resource. """ links = _parse_header_links(response) try: new_cert_uri = links[u'next'][u'url'] except KeyError: raise errors.ClientError('"next" link missing') re...
[ "def", "_parse_authorization", "(", "cls", ",", "response", ",", "uri", "=", "None", ")", ":", "links", "=", "_parse_header_links", "(", "response", ")", "try", ":", "new_cert_uri", "=", "links", "[", "u'next'", "]", "[", "u'url'", "]", "except", "KeyError...
Parse an authorization resource.
[ "Parse", "an", "authorization", "resource", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L303-L319
twisted/txacme
src/txacme/client.py
Client._check_authorization
def _check_authorization(cls, authzr, identifier): """ Check that the authorization we got is the one we expected. """ if authzr.body.identifier != identifier: raise errors.UnexpectedUpdate(authzr) return authzr
python
def _check_authorization(cls, authzr, identifier): """ Check that the authorization we got is the one we expected. """ if authzr.body.identifier != identifier: raise errors.UnexpectedUpdate(authzr) return authzr
[ "def", "_check_authorization", "(", "cls", ",", "authzr", ",", "identifier", ")", ":", "if", "authzr", ".", "body", ".", "identifier", "!=", "identifier", ":", "raise", "errors", ".", "UnexpectedUpdate", "(", "authzr", ")", "return", "authzr" ]
Check that the authorization we got is the one we expected.
[ "Check", "that", "the", "authorization", "we", "got", "is", "the", "one", "we", "expected", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L322-L328
twisted/txacme
src/txacme/client.py
Client.answer_challenge
def answer_challenge(self, challenge_body, response): """ Respond to an authorization challenge. :param ~acme.messages.ChallengeBody challenge_body: The challenge being responded to. :param ~acme.challenges.ChallengeResponse response: The response to the challeng...
python
def answer_challenge(self, challenge_body, response): """ Respond to an authorization challenge. :param ~acme.messages.ChallengeBody challenge_body: The challenge being responded to. :param ~acme.challenges.ChallengeResponse response: The response to the challeng...
[ "def", "answer_challenge", "(", "self", ",", "challenge_body", ",", "response", ")", ":", "action", "=", "LOG_ACME_ANSWER_CHALLENGE", "(", "challenge_body", "=", "challenge_body", ",", "response", "=", "response", ")", "with", "action", ".", "context", "(", ")",...
Respond to an authorization challenge. :param ~acme.messages.ChallengeBody challenge_body: The challenge being responded to. :param ~acme.challenges.ChallengeResponse response: The response to the challenge. :return: The updated challenge resource. :rtype: Defer...
[ "Respond", "to", "an", "authorization", "challenge", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L330-L353
twisted/txacme
src/txacme/client.py
Client._parse_challenge
def _parse_challenge(cls, response): """ Parse a challenge resource. """ links = _parse_header_links(response) try: authzr_uri = links['up']['url'] except KeyError: raise errors.ClientError('"up" link missing') return ( response...
python
def _parse_challenge(cls, response): """ Parse a challenge resource. """ links = _parse_header_links(response) try: authzr_uri = links['up']['url'] except KeyError: raise errors.ClientError('"up" link missing') return ( response...
[ "def", "_parse_challenge", "(", "cls", ",", "response", ")", ":", "links", "=", "_parse_header_links", "(", "response", ")", "try", ":", "authzr_uri", "=", "links", "[", "'up'", "]", "[", "'url'", "]", "except", "KeyError", ":", "raise", "errors", ".", "...
Parse a challenge resource.
[ "Parse", "a", "challenge", "resource", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L356-L371
twisted/txacme
src/txacme/client.py
Client._check_challenge
def _check_challenge(cls, challenge, challenge_body): """ Check that the challenge resource we got is the one we expected. """ if challenge.uri != challenge_body.uri: raise errors.UnexpectedUpdate(challenge.uri) return challenge
python
def _check_challenge(cls, challenge, challenge_body): """ Check that the challenge resource we got is the one we expected. """ if challenge.uri != challenge_body.uri: raise errors.UnexpectedUpdate(challenge.uri) return challenge
[ "def", "_check_challenge", "(", "cls", ",", "challenge", ",", "challenge_body", ")", ":", "if", "challenge", ".", "uri", "!=", "challenge_body", ".", "uri", ":", "raise", "errors", ".", "UnexpectedUpdate", "(", "challenge", ".", "uri", ")", "return", "challe...
Check that the challenge resource we got is the one we expected.
[ "Check", "that", "the", "challenge", "resource", "we", "got", "is", "the", "one", "we", "expected", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L374-L380
twisted/txacme
src/txacme/client.py
Client.poll
def poll(self, authzr): """ Update an authorization from the server (usually to check its status). """ action = LOG_ACME_POLL_AUTHORIZATION(authorization=authzr) with action.context(): return ( DeferredContext(self._client.get(authzr.uri)) ...
python
def poll(self, authzr): """ Update an authorization from the server (usually to check its status). """ action = LOG_ACME_POLL_AUTHORIZATION(authorization=authzr) with action.context(): return ( DeferredContext(self._client.get(authzr.uri)) ...
[ "def", "poll", "(", "self", ",", "authzr", ")", ":", "action", "=", "LOG_ACME_POLL_AUTHORIZATION", "(", "authorization", "=", "authzr", ")", "with", "action", ".", "context", "(", ")", ":", "return", "(", "DeferredContext", "(", "self", ".", "_client", "."...
Update an authorization from the server (usually to check its status).
[ "Update", "an", "authorization", "from", "the", "server", "(", "usually", "to", "check", "its", "status", ")", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L382-L406
twisted/txacme
src/txacme/client.py
Client.retry_after
def retry_after(cls, response, default=5, _now=time.time): """ Parse the Retry-After value from a response. """ val = response.headers.getRawHeaders(b'retry-after', [default])[0] try: return int(val) except ValueError: return http.stringToDatetime(...
python
def retry_after(cls, response, default=5, _now=time.time): """ Parse the Retry-After value from a response. """ val = response.headers.getRawHeaders(b'retry-after', [default])[0] try: return int(val) except ValueError: return http.stringToDatetime(...
[ "def", "retry_after", "(", "cls", ",", "response", ",", "default", "=", "5", ",", "_now", "=", "time", ".", "time", ")", ":", "val", "=", "response", ".", "headers", ".", "getRawHeaders", "(", "b'retry-after'", ",", "[", "default", "]", ")", "[", "0"...
Parse the Retry-After value from a response.
[ "Parse", "the", "Retry", "-", "After", "value", "from", "a", "response", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L409-L417
twisted/txacme
src/txacme/client.py
Client.request_issuance
def request_issuance(self, csr): """ Request a certificate. Authorizations should have already been completed for all of the names requested in the CSR. Note that unlike `acme.client.Client.request_issuance`, the certificate resource will have the body data as raw bytes...
python
def request_issuance(self, csr): """ Request a certificate. Authorizations should have already been completed for all of the names requested in the CSR. Note that unlike `acme.client.Client.request_issuance`, the certificate resource will have the body data as raw bytes...
[ "def", "request_issuance", "(", "self", ",", "csr", ")", ":", "action", "=", "LOG_ACME_REQUEST_CERTIFICATE", "(", ")", "with", "action", ".", "context", "(", ")", ":", "return", "(", "DeferredContext", "(", "self", ".", "_client", ".", "post", "(", "self",...
Request a certificate. Authorizations should have already been completed for all of the names requested in the CSR. Note that unlike `acme.client.Client.request_issuance`, the certificate resource will have the body data as raw bytes. .. seealso:: `txacme.util.csr_for_names` ...
[ "Request", "a", "certificate", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L419-L451
twisted/txacme
src/txacme/client.py
Client._parse_certificate
def _parse_certificate(cls, response): """ Parse a response containing a certificate resource. """ links = _parse_header_links(response) try: cert_chain_uri = links[u'up'][u'url'] except KeyError: cert_chain_uri = None return ( ...
python
def _parse_certificate(cls, response): """ Parse a response containing a certificate resource. """ links = _parse_header_links(response) try: cert_chain_uri = links[u'up'][u'url'] except KeyError: cert_chain_uri = None return ( ...
[ "def", "_parse_certificate", "(", "cls", ",", "response", ")", ":", "links", "=", "_parse_header_links", "(", "response", ")", "try", ":", "cert_chain_uri", "=", "links", "[", "u'up'", "]", "[", "u'url'", "]", "except", "KeyError", ":", "cert_chain_uri", "="...
Parse a response containing a certificate resource.
[ "Parse", "a", "response", "containing", "a", "certificate", "resource", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L454-L470
twisted/txacme
src/txacme/client.py
Client.fetch_chain
def fetch_chain(self, certr, max_length=10): """ Fetch the intermediary chain for a certificate. :param acme.messages.CertificateResource certr: The certificate to fetch the chain for. :param int max_length: The maximum length of the chain that will be fetched. ...
python
def fetch_chain(self, certr, max_length=10): """ Fetch the intermediary chain for a certificate. :param acme.messages.CertificateResource certr: The certificate to fetch the chain for. :param int max_length: The maximum length of the chain that will be fetched. ...
[ "def", "fetch_chain", "(", "self", ",", "certr", ",", "max_length", "=", "10", ")", ":", "action", "=", "LOG_ACME_FETCH_CHAIN", "(", ")", "with", "action", ".", "context", "(", ")", ":", "if", "certr", ".", "cert_chain_uri", "is", "None", ":", "return", ...
Fetch the intermediary chain for a certificate. :param acme.messages.CertificateResource certr: The certificate to fetch the chain for. :param int max_length: The maximum length of the chain that will be fetched. :rtype: Deferred[List[`acme.messages.CertificateResource`...
[ "Fetch", "the", "intermediary", "chain", "for", "a", "certificate", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L472-L502
twisted/txacme
src/txacme/client.py
JWSClient._wrap_in_jws
def _wrap_in_jws(self, nonce, obj): """ Wrap ``JSONDeSerializable`` object in JWS. .. todo:: Implement ``acmePath``. :param ~josepy.interfaces.JSONDeSerializable obj: :param bytes nonce: :rtype: `bytes` :return: JSON-encoded data """ with LOG_J...
python
def _wrap_in_jws(self, nonce, obj): """ Wrap ``JSONDeSerializable`` object in JWS. .. todo:: Implement ``acmePath``. :param ~josepy.interfaces.JSONDeSerializable obj: :param bytes nonce: :rtype: `bytes` :return: JSON-encoded data """ with LOG_J...
[ "def", "_wrap_in_jws", "(", "self", ",", "nonce", ",", "obj", ")", ":", "with", "LOG_JWS_SIGN", "(", "key_type", "=", "self", ".", "_key", ".", "typ", ",", "alg", "=", "self", ".", "_alg", ".", "name", ",", "nonce", "=", "nonce", ")", ":", "jobj", ...
Wrap ``JSONDeSerializable`` object in JWS. .. todo:: Implement ``acmePath``. :param ~josepy.interfaces.JSONDeSerializable obj: :param bytes nonce: :rtype: `bytes` :return: JSON-encoded data
[ "Wrap", "JSONDeSerializable", "object", "in", "JWS", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L678-L697
twisted/txacme
src/txacme/client.py
JWSClient._check_response
def _check_response(cls, response, content_type=JSON_CONTENT_TYPE): """ Check response content and its type. .. note:: Unlike :mod:`acme.client`, checking is strict. :param bytes content_type: Expected Content-Type response header. If the response Content-Typ...
python
def _check_response(cls, response, content_type=JSON_CONTENT_TYPE): """ Check response content and its type. .. note:: Unlike :mod:`acme.client`, checking is strict. :param bytes content_type: Expected Content-Type response header. If the response Content-Typ...
[ "def", "_check_response", "(", "cls", ",", "response", ",", "content_type", "=", "JSON_CONTENT_TYPE", ")", ":", "def", "_got_failure", "(", "f", ")", ":", "f", ".", "trap", "(", "ValueError", ")", "return", "None", "def", "_got_json", "(", "jobj", ")", "...
Check response content and its type. .. note:: Unlike :mod:`acme.client`, checking is strict. :param bytes content_type: Expected Content-Type response header. If the response Content-Type does not match, :exc:`ClientError` is raised. :raises .ServerErro...
[ "Check", "response", "content", "and", "its", "type", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L700-L748
twisted/txacme
src/txacme/client.py
JWSClient._send_request
def _send_request(self, method, url, *args, **kwargs): """ Send HTTP request. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :return: Deferred firing with the HTTP response. """ action = LOG_JWS_REQUEST(url=url) ...
python
def _send_request(self, method, url, *args, **kwargs): """ Send HTTP request. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :return: Deferred firing with the HTTP response. """ action = LOG_JWS_REQUEST(url=url) ...
[ "def", "_send_request", "(", "self", ",", "method", ",", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "action", "=", "LOG_JWS_REQUEST", "(", "url", "=", "url", ")", "with", "action", ".", "context", "(", ")", ":", "headers", "=", "kw...
Send HTTP request. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :return: Deferred firing with the HTTP response.
[ "Send", "HTTP", "request", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L750-L772
twisted/txacme
src/txacme/client.py
JWSClient.head
def head(self, url, *args, **kwargs): """ Send HEAD request without checking the response. Note that ``_check_response`` is not called, as there will be no response body to check. :param str url: The URL to make the request to. """ with LOG_JWS_HEAD().context():...
python
def head(self, url, *args, **kwargs): """ Send HEAD request without checking the response. Note that ``_check_response`` is not called, as there will be no response body to check. :param str url: The URL to make the request to. """ with LOG_JWS_HEAD().context():...
[ "def", "head", "(", "self", ",", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "LOG_JWS_HEAD", "(", ")", ".", "context", "(", ")", ":", "return", "DeferredContext", "(", "self", ".", "_send_request", "(", "u'HEAD'", ",", "url", ...
Send HEAD request without checking the response. Note that ``_check_response`` is not called, as there will be no response body to check. :param str url: The URL to make the request to.
[ "Send", "HEAD", "request", "without", "checking", "the", "response", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L774-L786
twisted/txacme
src/txacme/client.py
JWSClient.get
def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs): """ Send GET request and check response. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :raises txacme.client.ServerError: If server response body carries HTTP ...
python
def get(self, url, content_type=JSON_CONTENT_TYPE, **kwargs): """ Send GET request and check response. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :raises txacme.client.ServerError: If server response body carries HTTP ...
[ "def", "get", "(", "self", ",", "url", ",", "content_type", "=", "JSON_CONTENT_TYPE", ",", "*", "*", "kwargs", ")", ":", "with", "LOG_JWS_GET", "(", ")", ".", "context", "(", ")", ":", "return", "(", "DeferredContext", "(", "self", ".", "_send_request", ...
Send GET request and check response. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :raises txacme.client.ServerError: If server response body carries HTTP Problem (draft-ietf-appsawg-http-problem-00). :raises acme.errors.ClientEr...
[ "Send", "GET", "request", "and", "check", "response", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L788-L805
twisted/txacme
src/txacme/client.py
JWSClient._add_nonce
def _add_nonce(self, response): """ Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified. """ nonce = response.headers.getRawHeaders( REPLAY_NONCE_HEADER, [None])[0] ...
python
def _add_nonce(self, response): """ Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified. """ nonce = response.headers.getRawHeaders( REPLAY_NONCE_HEADER, [None])[0] ...
[ "def", "_add_nonce", "(", "self", ",", "response", ")", ":", "nonce", "=", "response", ".", "headers", ".", "getRawHeaders", "(", "REPLAY_NONCE_HEADER", ",", "[", "None", "]", ")", "[", "0", "]", "with", "LOG_JWS_ADD_NONCE", "(", "raw_nonce", "=", "nonce",...
Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified.
[ "Store", "a", "nonce", "from", "a", "response", "we", "received", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L807-L829
twisted/txacme
src/txacme/client.py
JWSClient._get_nonce
def _get_nonce(self, url): """ Get a nonce to use in a request, removing it from the nonces on hand. """ action = LOG_JWS_GET_NONCE() if len(self._nonces) > 0: with action: nonce = self._nonces.pop() action.add_success_fields(nonce=nonc...
python
def _get_nonce(self, url): """ Get a nonce to use in a request, removing it from the nonces on hand. """ action = LOG_JWS_GET_NONCE() if len(self._nonces) > 0: with action: nonce = self._nonces.pop() action.add_success_fields(nonce=nonc...
[ "def", "_get_nonce", "(", "self", ",", "url", ")", ":", "action", "=", "LOG_JWS_GET_NONCE", "(", ")", "if", "len", "(", "self", ".", "_nonces", ")", ">", "0", ":", "with", "action", ":", "nonce", "=", "self", ".", "_nonces", ".", "pop", "(", ")", ...
Get a nonce to use in a request, removing it from the nonces on hand.
[ "Get", "a", "nonce", "to", "use", "in", "a", "request", "removing", "it", "from", "the", "nonces", "on", "hand", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L831-L849
twisted/txacme
src/txacme/client.py
JWSClient._post
def _post(self, url, obj, content_type, **kwargs): """ POST an object and check the response. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected conten...
python
def _post(self, url, obj, content_type, **kwargs): """ POST an object and check the response. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected conten...
[ "def", "_post", "(", "self", ",", "url", ",", "obj", ",", "content_type", ",", "*", "*", "kwargs", ")", ":", "with", "LOG_JWS_POST", "(", ")", ".", "context", "(", ")", ":", "headers", "=", "kwargs", ".", "setdefault", "(", "'headers'", ",", "Headers...
POST an object and check the response. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected content type of the response. :raises txacme.client.ServerError: If ...
[ "POST", "an", "object", "and", "check", "the", "response", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L851-L875
twisted/txacme
src/txacme/client.py
JWSClient.post
def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): """ POST an object and check the response. Retry once if a badNonce error is received. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload o...
python
def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): """ POST an object and check the response. Retry once if a badNonce error is received. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload o...
[ "def", "post", "(", "self", ",", "url", ",", "obj", ",", "content_type", "=", "JSON_CONTENT_TYPE", ",", "*", "*", "kwargs", ")", ":", "def", "retry_bad_nonce", "(", "f", ")", ":", "f", ".", "trap", "(", "ServerError", ")", "# The current RFC draft defines ...
POST an object and check the response. Retry once if a badNonce error is received. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected content type of the respo...
[ "POST", "an", "object", "and", "check", "the", "response", ".", "Retry", "once", "if", "a", "badNonce", "error", "is", "received", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L877-L907
twisted/txacme
src/txacme/challenges/_libcloud.py
_daemon_thread
def _daemon_thread(*a, **kw): """ Create a `threading.Thread`, but always set ``daemon``. """ thread = Thread(*a, **kw) thread.daemon = True return thread
python
def _daemon_thread(*a, **kw): """ Create a `threading.Thread`, but always set ``daemon``. """ thread = Thread(*a, **kw) thread.daemon = True return thread
[ "def", "_daemon_thread", "(", "*", "a", ",", "*", "*", "kw", ")", ":", "thread", "=", "Thread", "(", "*", "a", ",", "*", "*", "kw", ")", "thread", ".", "daemon", "=", "True", "return", "thread" ]
Create a `threading.Thread`, but always set ``daemon``.
[ "Create", "a", "threading", ".", "Thread", "but", "always", "set", "daemon", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/challenges/_libcloud.py#L18-L24
twisted/txacme
src/txacme/challenges/_libcloud.py
_defer_to_worker
def _defer_to_worker(deliver, worker, work, *args, **kwargs): """ Run a task in a worker, delivering the result as a ``Deferred`` in the reactor thread. """ deferred = Deferred() def wrapped_work(): try: result = work(*args, **kwargs) except BaseException: ...
python
def _defer_to_worker(deliver, worker, work, *args, **kwargs): """ Run a task in a worker, delivering the result as a ``Deferred`` in the reactor thread. """ deferred = Deferred() def wrapped_work(): try: result = work(*args, **kwargs) except BaseException: ...
[ "def", "_defer_to_worker", "(", "deliver", ",", "worker", ",", "work", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "deferred", "=", "Deferred", "(", ")", "def", "wrapped_work", "(", ")", ":", "try", ":", "result", "=", "work", "(", "*", "a...
Run a task in a worker, delivering the result as a ``Deferred`` in the reactor thread.
[ "Run", "a", "task", "in", "a", "worker", "delivering", "the", "result", "as", "a", "Deferred", "in", "the", "reactor", "thread", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/challenges/_libcloud.py#L27-L43
twisted/txacme
src/txacme/challenges/_libcloud.py
_split_zone
def _split_zone(server_name, zone_name): """ Split the zone portion off from a DNS label. :param str server_name: The full DNS label. :param str zone_name: The zone name suffix. """ server_name = server_name.rstrip(u'.') zone_name = zone_name.rstrip(u'.') if not (server_name == zone_nam...
python
def _split_zone(server_name, zone_name): """ Split the zone portion off from a DNS label. :param str server_name: The full DNS label. :param str zone_name: The zone name suffix. """ server_name = server_name.rstrip(u'.') zone_name = zone_name.rstrip(u'.') if not (server_name == zone_nam...
[ "def", "_split_zone", "(", "server_name", ",", "zone_name", ")", ":", "server_name", "=", "server_name", ".", "rstrip", "(", "u'.'", ")", "zone_name", "=", "zone_name", ".", "rstrip", "(", "u'.'", ")", "if", "not", "(", "server_name", "==", "zone_name", "o...
Split the zone portion off from a DNS label. :param str server_name: The full DNS label. :param str zone_name: The zone name suffix.
[ "Split", "the", "zone", "portion", "off", "from", "a", "DNS", "label", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/challenges/_libcloud.py#L46-L58
twisted/txacme
src/txacme/challenges/_libcloud.py
_get_existing
def _get_existing(driver, zone_name, server_name, validation): """ Get existing validation records. """ if zone_name is None: zones = sorted( (z for z in driver.list_zones() if server_name.rstrip(u'.') .endswith(u'.' + z.domain.rstrip(u'.')))...
python
def _get_existing(driver, zone_name, server_name, validation): """ Get existing validation records. """ if zone_name is None: zones = sorted( (z for z in driver.list_zones() if server_name.rstrip(u'.') .endswith(u'.' + z.domain.rstrip(u'.')))...
[ "def", "_get_existing", "(", "driver", ",", "zone_name", ",", "server_name", ",", "validation", ")", ":", "if", "zone_name", "is", "None", ":", "zones", "=", "sorted", "(", "(", "z", "for", "z", "in", "driver", ".", "list_zones", "(", ")", "if", "serve...
Get existing validation records.
[ "Get", "existing", "validation", "records", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/challenges/_libcloud.py#L61-L90
twisted/txacme
src/txacme/challenges/_libcloud.py
_validation
def _validation(response): """ Get the validation value for a challenge response. """ h = hashlib.sha256(response.key_authorization.encode("utf-8")) return b64encode(h.digest()).decode()
python
def _validation(response): """ Get the validation value for a challenge response. """ h = hashlib.sha256(response.key_authorization.encode("utf-8")) return b64encode(h.digest()).decode()
[ "def", "_validation", "(", "response", ")", ":", "h", "=", "hashlib", ".", "sha256", "(", "response", ".", "key_authorization", ".", "encode", "(", "\"utf-8\"", ")", ")", "return", "b64encode", "(", "h", ".", "digest", "(", ")", ")", ".", "decode", "("...
Get the validation value for a challenge response.
[ "Get", "the", "validation", "value", "for", "a", "challenge", "response", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/challenges/_libcloud.py#L93-L98
twisted/txacme
src/txacme/endpoint.py
load_or_create_client_key
def load_or_create_client_key(pem_path): """ Load the client key from a directory, creating it if it does not exist. .. note:: The client key that will be created will be a 2048-bit RSA key. :type pem_path: ``twisted.python.filepath.FilePath`` :param pem_path: The certificate directory to ...
python
def load_or_create_client_key(pem_path): """ Load the client key from a directory, creating it if it does not exist. .. note:: The client key that will be created will be a 2048-bit RSA key. :type pem_path: ``twisted.python.filepath.FilePath`` :param pem_path: The certificate directory to ...
[ "def", "load_or_create_client_key", "(", "pem_path", ")", ":", "acme_key_file", "=", "pem_path", ".", "asTextMode", "(", ")", ".", "child", "(", "u'client.key'", ")", "if", "acme_key_file", ".", "exists", "(", ")", ":", "key", "=", "serialization", ".", "loa...
Load the client key from a directory, creating it if it does not exist. .. note:: The client key that will be created will be a 2048-bit RSA key. :type pem_path: ``twisted.python.filepath.FilePath`` :param pem_path: The certificate directory to use, as with the endpoint.
[ "Load", "the", "client", "key", "from", "a", "directory", "creating", "it", "if", "it", "does", "not", "exist", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/endpoint.py#L131-L154
twisted/txacme
src/txacme/endpoint.py
_parse
def _parse(reactor, directory, pemdir, *args, **kwargs): """ Parse a txacme endpoint description. :param reactor: The Twisted reactor. :param directory: ``twisted.python.url.URL`` for the ACME directory to use for issuing certs. :param str pemdir: The path to the certificate directory to us...
python
def _parse(reactor, directory, pemdir, *args, **kwargs): """ Parse a txacme endpoint description. :param reactor: The Twisted reactor. :param directory: ``twisted.python.url.URL`` for the ACME directory to use for issuing certs. :param str pemdir: The path to the certificate directory to us...
[ "def", "_parse", "(", "reactor", ",", "directory", ",", "pemdir", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "colon_join", "(", "items", ")", ":", "return", "':'", ".", "join", "(", "[", "item", ".", "replace", "(", "':'", ",", "...
Parse a txacme endpoint description. :param reactor: The Twisted reactor. :param directory: ``twisted.python.url.URL`` for the ACME directory to use for issuing certs. :param str pemdir: The path to the certificate directory to use.
[ "Parse", "a", "txacme", "endpoint", "description", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/endpoint.py#L157-L177
alexwlchan/lazyreader
lazyreader.py
lazyread
def lazyread(f, delimiter): """ Generator which continually reads ``f`` to the next instance of ``delimiter``. This allows you to do batch processing on the contents of ``f`` without loading the entire file into memory. :param f: Any file-like object which has a ``.read()`` method. :param ...
python
def lazyread(f, delimiter): """ Generator which continually reads ``f`` to the next instance of ``delimiter``. This allows you to do batch processing on the contents of ``f`` without loading the entire file into memory. :param f: Any file-like object which has a ``.read()`` method. :param ...
[ "def", "lazyread", "(", "f", ",", "delimiter", ")", ":", "# Get an empty string to start with. We need to make sure that if the", "# file is opened in binary mode, we're using byte strings, and similar", "# for Unicode. Otherwise trying to update the running string will", "# hit a TypeError....
Generator which continually reads ``f`` to the next instance of ``delimiter``. This allows you to do batch processing on the contents of ``f`` without loading the entire file into memory. :param f: Any file-like object which has a ``.read()`` method. :param delimiter: Delimiter on which to split u...
[ "Generator", "which", "continually", "reads", "f", "to", "the", "next", "instance", "of", "delimiter", "." ]
train
https://github.com/alexwlchan/lazyreader/blob/918c408efba015efc1d67b05d1e4b373ac9d1192/lazyreader.py#L3-L44
twisted/txacme
src/txacme/util.py
generate_private_key
def generate_private_key(key_type): """ Generate a random private key using sensible parameters. :param str key_type: The type of key to generate. One of: ``rsa``. """ if key_type == u'rsa': return rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_b...
python
def generate_private_key(key_type): """ Generate a random private key using sensible parameters. :param str key_type: The type of key to generate. One of: ``rsa``. """ if key_type == u'rsa': return rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_b...
[ "def", "generate_private_key", "(", "key_type", ")", ":", "if", "key_type", "==", "u'rsa'", ":", "return", "rsa", ".", "generate_private_key", "(", "public_exponent", "=", "65537", ",", "key_size", "=", "2048", ",", "backend", "=", "default_backend", "(", ")",...
Generate a random private key using sensible parameters. :param str key_type: The type of key to generate. One of: ``rsa``.
[ "Generate", "a", "random", "private", "key", "using", "sensible", "parameters", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/util.py#L20-L29
twisted/txacme
src/txacme/util.py
generate_tls_sni_01_cert
def generate_tls_sni_01_cert(server_name, key_type=u'rsa', _generate_private_key=None): """ Generate a certificate/key pair for responding to a tls-sni-01 challenge. :param str server_name: The SAN the certificate should have. :param str key_type: The type of key to generat...
python
def generate_tls_sni_01_cert(server_name, key_type=u'rsa', _generate_private_key=None): """ Generate a certificate/key pair for responding to a tls-sni-01 challenge. :param str server_name: The SAN the certificate should have. :param str key_type: The type of key to generat...
[ "def", "generate_tls_sni_01_cert", "(", "server_name", ",", "key_type", "=", "u'rsa'", ",", "_generate_private_key", "=", "None", ")", ":", "key", "=", "(", "_generate_private_key", "or", "generate_private_key", ")", "(", "key_type", ")", "name", "=", "x509", "....
Generate a certificate/key pair for responding to a tls-sni-01 challenge. :param str server_name: The SAN the certificate should have. :param str key_type: The type of key to generate; usually not necessary. :rtype: ``Tuple[`~cryptography.x509.Certificate`, PrivateKey]`` :return: A tuple of the certif...
[ "Generate", "a", "certificate", "/", "key", "pair", "for", "responding", "to", "a", "tls", "-", "sni", "-", "01", "challenge", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/util.py#L32-L62
twisted/txacme
src/txacme/util.py
tap
def tap(f): """ "Tap" a Deferred callback chain with a function whose return value is ignored. """ @wraps(f) def _cb(res, *a, **kw): d = maybeDeferred(f, res, *a, **kw) d.addCallback(lambda ignored: res) return d return _cb
python
def tap(f): """ "Tap" a Deferred callback chain with a function whose return value is ignored. """ @wraps(f) def _cb(res, *a, **kw): d = maybeDeferred(f, res, *a, **kw) d.addCallback(lambda ignored: res) return d return _cb
[ "def", "tap", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "_cb", "(", "res", ",", "*", "a", ",", "*", "*", "kw", ")", ":", "d", "=", "maybeDeferred", "(", "f", ",", "res", ",", "*", "a", ",", "*", "*", "kw", ")", "d", ".", ...
"Tap" a Deferred callback chain with a function whose return value is ignored.
[ "Tap", "a", "Deferred", "callback", "chain", "with", "a", "function", "whose", "return", "value", "is", "ignored", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/util.py#L65-L75
twisted/txacme
src/txacme/util.py
decode_csr
def decode_csr(b64der): """ Decode JOSE Base-64 DER-encoded CSR. :param str b64der: The encoded CSR. :rtype: `cryptography.x509.CertificateSigningRequest` :return: The decoded CSR. """ try: return x509.load_der_x509_csr( decode_b64jose(b64der), default_backend()) ex...
python
def decode_csr(b64der): """ Decode JOSE Base-64 DER-encoded CSR. :param str b64der: The encoded CSR. :rtype: `cryptography.x509.CertificateSigningRequest` :return: The decoded CSR. """ try: return x509.load_der_x509_csr( decode_b64jose(b64der), default_backend()) ex...
[ "def", "decode_csr", "(", "b64der", ")", ":", "try", ":", "return", "x509", ".", "load_der_x509_csr", "(", "decode_b64jose", "(", "b64der", ")", ",", "default_backend", "(", ")", ")", "except", "ValueError", "as", "error", ":", "raise", "DeserializationError",...
Decode JOSE Base-64 DER-encoded CSR. :param str b64der: The encoded CSR. :rtype: `cryptography.x509.CertificateSigningRequest` :return: The decoded CSR.
[ "Decode", "JOSE", "Base", "-", "64", "DER", "-", "encoded", "CSR", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/util.py#L89-L102
twisted/txacme
src/txacme/util.py
csr_for_names
def csr_for_names(names, key): """ Generate a certificate signing request for the given names and private key. .. seealso:: `acme.client.Client.request_issuance` .. seealso:: `generate_private_key` :param ``List[str]``: One or more names (subjectAltName) for which to request a certifica...
python
def csr_for_names(names, key): """ Generate a certificate signing request for the given names and private key. .. seealso:: `acme.client.Client.request_issuance` .. seealso:: `generate_private_key` :param ``List[str]``: One or more names (subjectAltName) for which to request a certifica...
[ "def", "csr_for_names", "(", "names", ",", "key", ")", ":", "if", "len", "(", "names", ")", "==", "0", ":", "raise", "ValueError", "(", "'Must have at least one name'", ")", "if", "len", "(", "names", "[", "0", "]", ")", ">", "64", ":", "common_name", ...
Generate a certificate signing request for the given names and private key. .. seealso:: `acme.client.Client.request_issuance` .. seealso:: `generate_private_key` :param ``List[str]``: One or more names (subjectAltName) for which to request a certificate. :param key: A Cryptography private ...
[ "Generate", "a", "certificate", "signing", "request", "for", "the", "given", "names", "and", "private", "key", "." ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/util.py#L105-L133
samuelcolvin/python-devtools
devtools/debug.py
Debug._wrap_parse
def _wrap_parse(code, filename): """ async wrapper is required to avoid await calls raising a SyntaxError """ code = 'async def wrapper():\n' + indent(code, ' ') return ast.parse(code, filename=filename).body[0].body[0].value
python
def _wrap_parse(code, filename): """ async wrapper is required to avoid await calls raising a SyntaxError """ code = 'async def wrapper():\n' + indent(code, ' ') return ast.parse(code, filename=filename).body[0].body[0].value
[ "def", "_wrap_parse", "(", "code", ",", "filename", ")", ":", "code", "=", "'async def wrapper():\\n'", "+", "indent", "(", "code", ",", "' '", ")", "return", "ast", ".", "parse", "(", "code", ",", "filename", "=", "filename", ")", ".", "body", "[", "0...
async wrapper is required to avoid await calls raising a SyntaxError
[ "async", "wrapper", "is", "required", "to", "avoid", "await", "calls", "raising", "a", "SyntaxError" ]
train
https://github.com/samuelcolvin/python-devtools/blob/fb0021b3e6815348a28c1d2bf11b50b8f0bd511a/devtools/debug.py#L274-L279
twisted/txacme
docs/conf.py
linkcode_resolve
def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part ...
python
def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part ...
[ "def", "linkcode_resolve", "(", "domain", ",", "info", ")", ":", "if", "domain", "!=", "'py'", ":", "return", "None", "modname", "=", "info", "[", "'module'", "]", "fullname", "=", "info", "[", "'fullname'", "]", "submod", "=", "sys", ".", "modules", "...
Determine the URL corresponding to Python object
[ "Determine", "the", "URL", "corresponding", "to", "Python", "object" ]
train
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/docs/conf.py#L326-L359
cga-harvard/Hypermap-Registry
hypermap/aggregator/solr.py
SolrHypermap.layers_to_solr
def layers_to_solr(self, layers): """ Sync n layers in Solr. """ layers_dict_list = [] layers_success_ids = [] layers_errors_ids = [] for layer in layers: layer_dict, message = layer2dict(layer) if not layer_dict: layers_e...
python
def layers_to_solr(self, layers): """ Sync n layers in Solr. """ layers_dict_list = [] layers_success_ids = [] layers_errors_ids = [] for layer in layers: layer_dict, message = layer2dict(layer) if not layer_dict: layers_e...
[ "def", "layers_to_solr", "(", "self", ",", "layers", ")", ":", "layers_dict_list", "=", "[", "]", "layers_success_ids", "=", "[", "]", "layers_errors_ids", "=", "[", "]", "for", "layer", "in", "layers", ":", "layer_dict", ",", "message", "=", "layer2dict", ...
Sync n layers in Solr.
[ "Sync", "n", "layers", "in", "Solr", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/solr.py#L19-L50
cga-harvard/Hypermap-Registry
hypermap/aggregator/solr.py
SolrHypermap.layer_to_solr
def layer_to_solr(self, layer): """ Sync a layer in Solr. """ success = True message = 'Synced layer id %s to Solr' % layer.id layer_dict, message = layer2dict(layer) if not layer_dict: success = False else: layer_json = json.dumps...
python
def layer_to_solr(self, layer): """ Sync a layer in Solr. """ success = True message = 'Synced layer id %s to Solr' % layer.id layer_dict, message = layer2dict(layer) if not layer_dict: success = False else: layer_json = json.dumps...
[ "def", "layer_to_solr", "(", "self", ",", "layer", ")", ":", "success", "=", "True", "message", "=", "'Synced layer id %s to Solr'", "%", "layer", ".", "id", "layer_dict", ",", "message", "=", "layer2dict", "(", "layer", ")", "if", "not", "layer_dict", ":", ...
Sync a layer in Solr.
[ "Sync", "a", "layer", "in", "Solr", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/solr.py#L52-L81
cga-harvard/Hypermap-Registry
hypermap/aggregator/solr.py
SolrHypermap.clear_solr
def clear_solr(self, catalog="hypermap"): """Clear all indexes in the solr core""" solr_url = "{0}/solr/{1}".format(SEARCH_URL, catalog) solr = pysolr.Solr(solr_url, timeout=60) solr.delete(q='*:*') LOGGER.debug('Solr core cleared')
python
def clear_solr(self, catalog="hypermap"): """Clear all indexes in the solr core""" solr_url = "{0}/solr/{1}".format(SEARCH_URL, catalog) solr = pysolr.Solr(solr_url, timeout=60) solr.delete(q='*:*') LOGGER.debug('Solr core cleared')
[ "def", "clear_solr", "(", "self", ",", "catalog", "=", "\"hypermap\"", ")", ":", "solr_url", "=", "\"{0}/solr/{1}\"", ".", "format", "(", "SEARCH_URL", ",", "catalog", ")", "solr", "=", "pysolr", ".", "Solr", "(", "solr_url", ",", "timeout", "=", "60", "...
Clear all indexes in the solr core
[ "Clear", "all", "indexes", "in", "the", "solr", "core" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/solr.py#L83-L88
cga-harvard/Hypermap-Registry
hypermap/aggregator/solr.py
SolrHypermap.update_schema
def update_schema(self, catalog="hypermap"): """ set the mapping in solr. :param catalog: core :return: """ schema_url = "{0}/solr/{1}/schema".format(SEARCH_URL, catalog) print schema_url # create a special type to draw better heatmaps. location_r...
python
def update_schema(self, catalog="hypermap"): """ set the mapping in solr. :param catalog: core :return: """ schema_url = "{0}/solr/{1}/schema".format(SEARCH_URL, catalog) print schema_url # create a special type to draw better heatmaps. location_r...
[ "def", "update_schema", "(", "self", ",", "catalog", "=", "\"hypermap\"", ")", ":", "schema_url", "=", "\"{0}/solr/{1}/schema\"", ".", "format", "(", "SEARCH_URL", ",", "catalog", ")", "print", "schema_url", "# create a special type to draw better heatmaps.", "location_...
set the mapping in solr. :param catalog: core :return:
[ "set", "the", "mapping", "in", "solr", ".", ":", "param", "catalog", ":", "core", ":", "return", ":" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/solr.py#L99-L221
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
create_layer_from_metadata_xml
def create_layer_from_metadata_xml(resourcetype, xml, monitor=False, service=None, catalog=None): """ Create a layer / keyword list from a metadata record if it does not already exist. """ from models import gen_anytext, Layer if resourcetype == 'http://www.opengis.net/cat/csw/2.0.2': # Dublin cor...
python
def create_layer_from_metadata_xml(resourcetype, xml, monitor=False, service=None, catalog=None): """ Create a layer / keyword list from a metadata record if it does not already exist. """ from models import gen_anytext, Layer if resourcetype == 'http://www.opengis.net/cat/csw/2.0.2': # Dublin cor...
[ "def", "create_layer_from_metadata_xml", "(", "resourcetype", ",", "xml", ",", "monitor", "=", "False", ",", "service", "=", "None", ",", "catalog", "=", "None", ")", ":", "from", "models", "import", "gen_anytext", ",", "Layer", "if", "resourcetype", "==", "...
Create a layer / keyword list from a metadata record if it does not already exist.
[ "Create", "a", "layer", "/", "keyword", "list", "from", "a", "metadata", "record", "if", "it", "does", "not", "already", "exist", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L28-L59
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
create_service_from_endpoint
def create_service_from_endpoint(endpoint, service_type, title=None, abstract=None, catalog=None): """ Create a service from an endpoint if it does not already exists. """ from models import Service if Service.objects.filter(url=endpoint, catalog=catalog).count() == 0: # check if endpoint is...
python
def create_service_from_endpoint(endpoint, service_type, title=None, abstract=None, catalog=None): """ Create a service from an endpoint if it does not already exists. """ from models import Service if Service.objects.filter(url=endpoint, catalog=catalog).count() == 0: # check if endpoint is...
[ "def", "create_service_from_endpoint", "(", "endpoint", ",", "service_type", ",", "title", "=", "None", ",", "abstract", "=", "None", ",", "catalog", "=", "None", ")", ":", "from", "models", "import", "Service", "if", "Service", ".", "objects", ".", "filter"...
Create a service from an endpoint if it does not already exists.
[ "Create", "a", "service", "from", "an", "endpoint", "if", "it", "does", "not", "already", "exists", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L62-L82
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
create_services_from_endpoint
def create_services_from_endpoint(url, catalog, greedy_opt=True): """ Generate service/services from an endpoint. WMS, WMTS, TMS endpoints correspond to a single service. ESRI, CSW endpoints corrispond to many services. :return: imported, message """ # this variable will collect any excepti...
python
def create_services_from_endpoint(url, catalog, greedy_opt=True): """ Generate service/services from an endpoint. WMS, WMTS, TMS endpoints correspond to a single service. ESRI, CSW endpoints corrispond to many services. :return: imported, message """ # this variable will collect any excepti...
[ "def", "create_services_from_endpoint", "(", "url", ",", "catalog", ",", "greedy_opt", "=", "True", ")", ":", "# this variable will collect any exception message during the routine.", "# will be used in the last step to send a message if \"detected\" var is False.", "messages", "=", ...
Generate service/services from an endpoint. WMS, WMTS, TMS endpoints correspond to a single service. ESRI, CSW endpoints corrispond to many services. :return: imported, message
[ "Generate", "service", "/", "services", "from", "an", "endpoint", ".", "WMS", "WMTS", "TMS", "endpoints", "correspond", "to", "a", "single", "service", ".", "ESRI", "CSW", "endpoints", "corrispond", "to", "many", "services", ".", ":", "return", ":", "importe...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L85-L332
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
service_url_parse
def service_url_parse(url): """ Function that parses from url the service and folder of services. """ endpoint = get_sanitized_endpoint(url) url_split_list = url.split(endpoint + '/') if len(url_split_list) != 0: url_split_list = url_split_list[1].split('/') else: raise Excep...
python
def service_url_parse(url): """ Function that parses from url the service and folder of services. """ endpoint = get_sanitized_endpoint(url) url_split_list = url.split(endpoint + '/') if len(url_split_list) != 0: url_split_list = url_split_list[1].split('/') else: raise Excep...
[ "def", "service_url_parse", "(", "url", ")", ":", "endpoint", "=", "get_sanitized_endpoint", "(", "url", ")", "url_split_list", "=", "url", ".", "split", "(", "endpoint", "+", "'/'", ")", "if", "len", "(", "url_split_list", ")", "!=", "0", ":", "url_split_...
Function that parses from url the service and folder of services.
[ "Function", "that", "parses", "from", "url", "the", "service", "and", "folder", "of", "services", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L335-L349
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
inverse_mercator
def inverse_mercator(xy): """ Given coordinates in spherical mercator, return a lon,lat tuple. """ lon = (xy[0] / 20037508.34) * 180 lat = (xy[1] / 20037508.34) * 180 lat = 180 / math.pi * \ (2 * math.atan(math.exp(lat * math.pi / 180)) - math.pi / 2) return (lon, lat)
python
def inverse_mercator(xy): """ Given coordinates in spherical mercator, return a lon,lat tuple. """ lon = (xy[0] / 20037508.34) * 180 lat = (xy[1] / 20037508.34) * 180 lat = 180 / math.pi * \ (2 * math.atan(math.exp(lat * math.pi / 180)) - math.pi / 2) return (lon, lat)
[ "def", "inverse_mercator", "(", "xy", ")", ":", "lon", "=", "(", "xy", "[", "0", "]", "/", "20037508.34", ")", "*", "180", "lat", "=", "(", "xy", "[", "1", "]", "/", "20037508.34", ")", "*", "180", "lat", "=", "180", "/", "math", ".", "pi", "...
Given coordinates in spherical mercator, return a lon,lat tuple.
[ "Given", "coordinates", "in", "spherical", "mercator", "return", "a", "lon", "lat", "tuple", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L404-L412
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
get_wms_version_negotiate
def get_wms_version_negotiate(url, timeout=10): """ OWSLib wrapper function to perform version negotiation against owslib.wms.WebMapService """ try: LOGGER.debug('Trying a WMS 1.3.0 GetCapabilities request') return WebMapService(url, version='1.3.0', timeout=timeout) except Exceptio...
python
def get_wms_version_negotiate(url, timeout=10): """ OWSLib wrapper function to perform version negotiation against owslib.wms.WebMapService """ try: LOGGER.debug('Trying a WMS 1.3.0 GetCapabilities request') return WebMapService(url, version='1.3.0', timeout=timeout) except Exceptio...
[ "def", "get_wms_version_negotiate", "(", "url", ",", "timeout", "=", "10", ")", ":", "try", ":", "LOGGER", ".", "debug", "(", "'Trying a WMS 1.3.0 GetCapabilities request'", ")", "return", "WebMapService", "(", "url", ",", "version", "=", "'1.3.0'", ",", "timeou...
OWSLib wrapper function to perform version negotiation against owslib.wms.WebMapService
[ "OWSLib", "wrapper", "function", "to", "perform", "version", "negotiation", "against", "owslib", ".", "wms", ".", "WebMapService" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L415-L426
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
get_sanitized_endpoint
def get_sanitized_endpoint(url): """ Sanitize an endpoint, as removing unneeded parameters """ # sanitize esri sanitized_url = url.rstrip() esri_string = '/rest/services' if esri_string in url: match = re.search(esri_string, sanitized_url) sanitized_url = url[0:(match.start(0...
python
def get_sanitized_endpoint(url): """ Sanitize an endpoint, as removing unneeded parameters """ # sanitize esri sanitized_url = url.rstrip() esri_string = '/rest/services' if esri_string in url: match = re.search(esri_string, sanitized_url) sanitized_url = url[0:(match.start(0...
[ "def", "get_sanitized_endpoint", "(", "url", ")", ":", "# sanitize esri", "sanitized_url", "=", "url", ".", "rstrip", "(", ")", "esri_string", "=", "'/rest/services'", "if", "esri_string", "in", "url", ":", "match", "=", "re", ".", "search", "(", "esri_string"...
Sanitize an endpoint, as removing unneeded parameters
[ "Sanitize", "an", "endpoint", "as", "removing", "unneeded", "parameters" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L435-L445
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
get_esri_service_name
def get_esri_service_name(url): """ A method to get a service name from an esri endpoint. For example: http://example.com/arcgis/rest/services/myservice/mylayer/MapServer/?f=json Will return: myservice/mylayer """ result = re.search('rest/services/(.*)/[MapServer|ImageServer]', url) if resul...
python
def get_esri_service_name(url): """ A method to get a service name from an esri endpoint. For example: http://example.com/arcgis/rest/services/myservice/mylayer/MapServer/?f=json Will return: myservice/mylayer """ result = re.search('rest/services/(.*)/[MapServer|ImageServer]', url) if resul...
[ "def", "get_esri_service_name", "(", "url", ")", ":", "result", "=", "re", ".", "search", "(", "'rest/services/(.*)/[MapServer|ImageServer]'", ",", "url", ")", "if", "result", "is", "None", ":", "return", "url", "else", ":", "return", "result", ".", "group", ...
A method to get a service name from an esri endpoint. For example: http://example.com/arcgis/rest/services/myservice/mylayer/MapServer/?f=json Will return: myservice/mylayer
[ "A", "method", "to", "get", "a", "service", "name", "from", "an", "esri", "endpoint", ".", "For", "example", ":", "http", ":", "//", "example", ".", "com", "/", "arcgis", "/", "rest", "/", "services", "/", "myservice", "/", "mylayer", "/", "MapServer",...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L448-L458
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
get_esri_extent
def get_esri_extent(esriobj): """ Get the extent of an ESRI resource """ extent = None srs = None if 'fullExtent' in esriobj._json_struct: extent = esriobj._json_struct['fullExtent'] if 'extent' in esriobj._json_struct: extent = esriobj._json_struct['extent'] try: ...
python
def get_esri_extent(esriobj): """ Get the extent of an ESRI resource """ extent = None srs = None if 'fullExtent' in esriobj._json_struct: extent = esriobj._json_struct['fullExtent'] if 'extent' in esriobj._json_struct: extent = esriobj._json_struct['extent'] try: ...
[ "def", "get_esri_extent", "(", "esriobj", ")", ":", "extent", "=", "None", "srs", "=", "None", "if", "'fullExtent'", "in", "esriobj", ".", "_json_struct", ":", "extent", "=", "esriobj", ".", "_json_struct", "[", "'fullExtent'", "]", "if", "'extent'", "in", ...
Get the extent of an ESRI resource
[ "Get", "the", "extent", "of", "an", "ESRI", "resource" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L461-L479
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
bbox2wktpolygon
def bbox2wktpolygon(bbox): """ Return OGC WKT Polygon of a simple bbox list of strings """ minx = float(bbox[0]) miny = float(bbox[1]) maxx = float(bbox[2]) maxy = float(bbox[3]) return 'POLYGON((%.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f))' \ % (minx, miny, minx, max...
python
def bbox2wktpolygon(bbox): """ Return OGC WKT Polygon of a simple bbox list of strings """ minx = float(bbox[0]) miny = float(bbox[1]) maxx = float(bbox[2]) maxy = float(bbox[3]) return 'POLYGON((%.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f))' \ % (minx, miny, minx, max...
[ "def", "bbox2wktpolygon", "(", "bbox", ")", ":", "minx", "=", "float", "(", "bbox", "[", "0", "]", ")", "miny", "=", "float", "(", "bbox", "[", "1", "]", ")", "maxx", "=", "float", "(", "bbox", "[", "2", "]", ")", "maxy", "=", "float", "(", "...
Return OGC WKT Polygon of a simple bbox list of strings
[ "Return", "OGC", "WKT", "Polygon", "of", "a", "simple", "bbox", "list", "of", "strings" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L503-L513
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
get_solr_date
def get_solr_date(pydate, is_negative): """ Returns a date in a valid Solr format from a string. """ # check if date is valid and then set it to solr format YYYY-MM-DDThh:mm:ssZ try: if isinstance(pydate, datetime.datetime): solr_date = '%sZ' % pydate.isoformat()[0:19] ...
python
def get_solr_date(pydate, is_negative): """ Returns a date in a valid Solr format from a string. """ # check if date is valid and then set it to solr format YYYY-MM-DDThh:mm:ssZ try: if isinstance(pydate, datetime.datetime): solr_date = '%sZ' % pydate.isoformat()[0:19] ...
[ "def", "get_solr_date", "(", "pydate", ",", "is_negative", ")", ":", "# check if date is valid and then set it to solr format YYYY-MM-DDThh:mm:ssZ", "try", ":", "if", "isinstance", "(", "pydate", ",", "datetime", ".", "datetime", ")", ":", "solr_date", "=", "'%sZ'", "...
Returns a date in a valid Solr format from a string.
[ "Returns", "a", "date", "in", "a", "valid", "Solr", "format", "from", "a", "string", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L516-L532
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
get_date
def get_date(layer): """ Returns a custom date representation. A date can be detected or from metadata. It can be a range or a simple date in isoformat. """ date = None sign = '+' date_type = 1 layer_dates = layer.get_layer_dates() # we index the first date! if layer_dates: ...
python
def get_date(layer): """ Returns a custom date representation. A date can be detected or from metadata. It can be a range or a simple date in isoformat. """ date = None sign = '+' date_type = 1 layer_dates = layer.get_layer_dates() # we index the first date! if layer_dates: ...
[ "def", "get_date", "(", "layer", ")", ":", "date", "=", "None", "sign", "=", "'+'", "date_type", "=", "1", "layer_dates", "=", "layer", ".", "get_layer_dates", "(", ")", "# we index the first date!", "if", "layer_dates", ":", "sign", "=", "layer_dates", "[",...
Returns a custom date representation. A date can be detected or from metadata. It can be a range or a simple date in isoformat.
[ "Returns", "a", "custom", "date", "representation", ".", "A", "date", "can", "be", "detected", "or", "from", "metadata", ".", "It", "can", "be", "a", "range", "or", "a", "simple", "date", "in", "isoformat", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L535-L559
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
layer2dict
def layer2dict(layer): """ Return a json representation for a layer. """ category = None username = None # bbox must be valid before proceeding if not layer.has_valid_bbox(): message = 'Layer id: %s has a not valid bbox' % layer.id return None, message # we can proceed...
python
def layer2dict(layer): """ Return a json representation for a layer. """ category = None username = None # bbox must be valid before proceeding if not layer.has_valid_bbox(): message = 'Layer id: %s has a not valid bbox' % layer.id return None, message # we can proceed...
[ "def", "layer2dict", "(", "layer", ")", ":", "category", "=", "None", "username", "=", "None", "# bbox must be valid before proceeding", "if", "not", "layer", ".", "has_valid_bbox", "(", ")", ":", "message", "=", "'Layer id: %s has a not valid bbox'", "%", "layer", ...
Return a json representation for a layer.
[ "Return", "a", "json", "representation", "for", "a", "layer", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L570-L661
cga-harvard/Hypermap-Registry
hypermap/aggregator/utils.py
detect_metadata_url_scheme
def detect_metadata_url_scheme(url): """detect whether a url is a Service type that HHypermap supports""" scheme = None url_lower = url.lower() if any(x in url_lower for x in ['wms', 'service=wms']): scheme = 'OGC:WMS' if any(x in url_lower for x in ['wmts', 'service=wmts']): schem...
python
def detect_metadata_url_scheme(url): """detect whether a url is a Service type that HHypermap supports""" scheme = None url_lower = url.lower() if any(x in url_lower for x in ['wms', 'service=wms']): scheme = 'OGC:WMS' if any(x in url_lower for x in ['wmts', 'service=wmts']): schem...
[ "def", "detect_metadata_url_scheme", "(", "url", ")", ":", "scheme", "=", "None", "url_lower", "=", "url", ".", "lower", "(", ")", "if", "any", "(", "x", "in", "url_lower", "for", "x", "in", "[", "'wms'", ",", "'service=wms'", "]", ")", ":", "scheme", ...
detect whether a url is a Service type that HHypermap supports
[ "detect", "whether", "a", "url", "is", "a", "Service", "type", "that", "HHypermap", "supports" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/utils.py#L664-L679
cga-harvard/Hypermap-Registry
hypermap/aggregator/views.py
serialize_checks
def serialize_checks(check_set): """ Serialize a check_set for raphael """ check_set_list = [] for check in check_set.all()[:25]: check_set_list.append( { 'datetime': check.checked_datetime.isoformat(), 'value': check.response_time, ...
python
def serialize_checks(check_set): """ Serialize a check_set for raphael """ check_set_list = [] for check in check_set.all()[:25]: check_set_list.append( { 'datetime': check.checked_datetime.isoformat(), 'value': check.response_time, ...
[ "def", "serialize_checks", "(", "check_set", ")", ":", "check_set_list", "=", "[", "]", "for", "check", "in", "check_set", ".", "all", "(", ")", "[", ":", "25", "]", ":", "check_set_list", ".", "append", "(", "{", "'datetime'", ":", "check", ".", "chec...
Serialize a check_set for raphael
[ "Serialize", "a", "check_set", "for", "raphael" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/views.py#L45-L58
cga-harvard/Hypermap-Registry
hypermap/aggregator/views.py
domains
def domains(request): """ A page with number of services and layers faceted on domains. """ url = '' query = '*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0' if settings.SEARCH_TYPE == 'elasticsearch': url = '%s/select?q=%s' % (settings.SEARCH...
python
def domains(request): """ A page with number of services and layers faceted on domains. """ url = '' query = '*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0' if settings.SEARCH_TYPE == 'elasticsearch': url = '%s/select?q=%s' % (settings.SEARCH...
[ "def", "domains", "(", "request", ")", ":", "url", "=", "''", "query", "=", "'*:*&facet=true&facet.limit=-1&facet.pivot=domain_name,service_id&wt=json&indent=true&rows=0'", "if", "settings", ".", "SEARCH_TYPE", "==", "'elasticsearch'", ":", "url", "=", "'%s/select?q=%s'", ...
A page with number of services and layers faceted on domains.
[ "A", "page", "with", "number", "of", "services", "and", "layers", "faceted", "on", "domains", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/views.py#L62-L84
cga-harvard/Hypermap-Registry
hypermap/aggregator/views.py
tasks_runner
def tasks_runner(request): """ A page that let the admin to run global tasks. """ # server info cached_layers_number = 0 cached_layers = cache.get('layers') if cached_layers: cached_layers_number = len(cached_layers) cached_deleted_layers_number = 0 cached_deleted_layers = ...
python
def tasks_runner(request): """ A page that let the admin to run global tasks. """ # server info cached_layers_number = 0 cached_layers = cache.get('layers') if cached_layers: cached_layers_number = len(cached_layers) cached_deleted_layers_number = 0 cached_deleted_layers = ...
[ "def", "tasks_runner", "(", "request", ")", ":", "# server info", "cached_layers_number", "=", "0", "cached_layers", "=", "cache", ".", "get", "(", "'layers'", ")", "if", "cached_layers", ":", "cached_layers_number", "=", "len", "(", "cached_layers", ")", "cache...
A page that let the admin to run global tasks.
[ "A", "page", "that", "let", "the", "admin", "to", "run", "global", "tasks", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/views.py#L254-L307
cga-harvard/Hypermap-Registry
hypermap/aggregator/views.py
layer_mapproxy
def layer_mapproxy(request, catalog_slug, layer_uuid, path_info): """ Get Layer with matching catalog and uuid """ layer = get_object_or_404(Layer, uuid=layer_uuid, catalog__slug=catalog_slug) # for WorldMap layers we need to use the url o...
python
def layer_mapproxy(request, catalog_slug, layer_uuid, path_info): """ Get Layer with matching catalog and uuid """ layer = get_object_or_404(Layer, uuid=layer_uuid, catalog__slug=catalog_slug) # for WorldMap layers we need to use the url o...
[ "def", "layer_mapproxy", "(", "request", ",", "catalog_slug", ",", "layer_uuid", ",", "path_info", ")", ":", "layer", "=", "get_object_or_404", "(", "Layer", ",", "uuid", "=", "layer_uuid", ",", "catalog__slug", "=", "catalog_slug", ")", "# for WorldMap layers we ...
Get Layer with matching catalog and uuid
[ "Get", "Layer", "with", "matching", "catalog", "and", "uuid" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/aggregator/views.py#L310-L350
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
parse_datetime
def parse_datetime(date_str): """ Parses a date string to date object. for BCE dates, only supports the year part. """ is_common_era = True date_str_parts = date_str.split("-") if date_str_parts and date_str_parts[0] == '': is_common_era = False # for now, only support BCE ye...
python
def parse_datetime(date_str): """ Parses a date string to date object. for BCE dates, only supports the year part. """ is_common_era = True date_str_parts = date_str.split("-") if date_str_parts and date_str_parts[0] == '': is_common_era = False # for now, only support BCE ye...
[ "def", "parse_datetime", "(", "date_str", ")", ":", "is_common_era", "=", "True", "date_str_parts", "=", "date_str", ".", "split", "(", "\"-\"", ")", "if", "date_str_parts", "and", "date_str_parts", "[", "0", "]", "==", "''", ":", "is_common_era", "=", "Fals...
Parses a date string to date object. for BCE dates, only supports the year part.
[ "Parses", "a", "date", "string", "to", "date", "object", ".", "for", "BCE", "dates", "only", "supports", "the", "year", "part", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L24-L57
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
parse_solr_time_range_as_pair
def parse_solr_time_range_as_pair(time_filter): """ :param time_filter: [2013-03-01 TO 2013-05-01T00:00:00] :return: (2013-03-01, 2013-05-01T00:00:00) """ pattern = "\\[(.*) TO (.*)\\]" matcher = re.search(pattern, time_filter) if matcher: return matcher.group(1), matcher.group(2) ...
python
def parse_solr_time_range_as_pair(time_filter): """ :param time_filter: [2013-03-01 TO 2013-05-01T00:00:00] :return: (2013-03-01, 2013-05-01T00:00:00) """ pattern = "\\[(.*) TO (.*)\\]" matcher = re.search(pattern, time_filter) if matcher: return matcher.group(1), matcher.group(2) ...
[ "def", "parse_solr_time_range_as_pair", "(", "time_filter", ")", ":", "pattern", "=", "\"\\\\[(.*) TO (.*)\\\\]\"", "matcher", "=", "re", ".", "search", "(", "pattern", ",", "time_filter", ")", "if", "matcher", ":", "return", "matcher", ".", "group", "(", "1", ...
:param time_filter: [2013-03-01 TO 2013-05-01T00:00:00] :return: (2013-03-01, 2013-05-01T00:00:00)
[ ":", "param", "time_filter", ":", "[", "2013", "-", "03", "-", "01", "TO", "2013", "-", "05", "-", "01T00", ":", "00", ":", "00", "]", ":", "return", ":", "(", "2013", "-", "03", "-", "01", "2013", "-", "05", "-", "01T00", ":", "00", ":", "...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L60-L70
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
parse_datetime_range
def parse_datetime_range(time_filter): """ Parse the url param to python objects. From what time range to divide by a.time.gap into intervals. Defaults to q.time and otherwise 90 days. Validate in API: re.search("\\[(.*) TO (.*)\\]", value) :param time_filter: [2013-03-01 TO 2013-05-01T00:00:00]...
python
def parse_datetime_range(time_filter): """ Parse the url param to python objects. From what time range to divide by a.time.gap into intervals. Defaults to q.time and otherwise 90 days. Validate in API: re.search("\\[(.*) TO (.*)\\]", value) :param time_filter: [2013-03-01 TO 2013-05-01T00:00:00]...
[ "def", "parse_datetime_range", "(", "time_filter", ")", ":", "if", "not", "time_filter", ":", "time_filter", "=", "\"[* TO *]\"", "start", ",", "end", "=", "parse_solr_time_range_as_pair", "(", "time_filter", ")", "start", ",", "end", "=", "parse_datetime", "(", ...
Parse the url param to python objects. From what time range to divide by a.time.gap into intervals. Defaults to q.time and otherwise 90 days. Validate in API: re.search("\\[(.*) TO (.*)\\]", value) :param time_filter: [2013-03-01 TO 2013-05-01T00:00:00] :return: datetime.datetime(2013, 3, 1, 0, 0), ...
[ "Parse", "the", "url", "param", "to", "python", "objects", ".", "From", "what", "time", "range", "to", "divide", "by", "a", ".", "time", ".", "gap", "into", "intervals", ".", "Defaults", "to", "q", ".", "time", "and", "otherwise", "90", "days", ".", ...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L73-L88
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
parse_ISO8601
def parse_ISO8601(time_gap): """ P1D to (1, ("DAYS", isodate.Duration(days=1)). P1Y to (1, ("YEARS", isodate.Duration(years=1)). :param time_gap: ISO8601 string. :return: tuple with quantity and unit of time. """ matcher = None if time_gap.count("T"): units = { "H": ...
python
def parse_ISO8601(time_gap): """ P1D to (1, ("DAYS", isodate.Duration(days=1)). P1Y to (1, ("YEARS", isodate.Duration(years=1)). :param time_gap: ISO8601 string. :return: tuple with quantity and unit of time. """ matcher = None if time_gap.count("T"): units = { "H": ...
[ "def", "parse_ISO8601", "(", "time_gap", ")", ":", "matcher", "=", "None", "if", "time_gap", ".", "count", "(", "\"T\"", ")", ":", "units", "=", "{", "\"H\"", ":", "(", "\"HOURS\"", ",", "isodate", ".", "Duration", "(", "hours", "=", "1", ")", ")", ...
P1D to (1, ("DAYS", isodate.Duration(days=1)). P1Y to (1, ("YEARS", isodate.Duration(years=1)). :param time_gap: ISO8601 string. :return: tuple with quantity and unit of time.
[ "P1D", "to", "(", "1", "(", "DAYS", "isodate", ".", "Duration", "(", "days", "=", "1", "))", ".", "P1Y", "to", "(", "1", "(", "YEARS", "isodate", ".", "Duration", "(", "years", "=", "1", "))", ".", ":", "param", "time_gap", ":", "ISO8601", "strin...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L109-L145
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
compute_gap
def compute_gap(start, end, time_limit): """ Compute a gap that seems reasonable, considering natural time units and limit. # TODO: make it to be reasonable. # TODO: make it to be small unit of time sensitive. :param start: datetime :param end: datetime :param time_limit: gaps count :ret...
python
def compute_gap(start, end, time_limit): """ Compute a gap that seems reasonable, considering natural time units and limit. # TODO: make it to be reasonable. # TODO: make it to be small unit of time sensitive. :param start: datetime :param end: datetime :param time_limit: gaps count :ret...
[ "def", "compute_gap", "(", "start", ",", "end", ",", "time_limit", ")", ":", "if", "is_range_common_era", "(", "start", ",", "end", ")", ":", "duration", "=", "end", ".", "get", "(", "\"parsed_datetime\"", ")", "-", "start", ".", "get", "(", "\"parsed_da...
Compute a gap that seems reasonable, considering natural time units and limit. # TODO: make it to be reasonable. # TODO: make it to be small unit of time sensitive. :param start: datetime :param end: datetime :param time_limit: gaps count :return: solr's format duration.
[ "Compute", "a", "gap", "that", "seems", "reasonable", "considering", "natural", "time", "units", "and", "limit", ".", "#", "TODO", ":", "make", "it", "to", "be", "reasonable", ".", "#", "TODO", ":", "make", "it", "to", "be", "small", "unit", "of", "tim...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L148-L166
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
gap_to_sorl
def gap_to_sorl(time_gap): """ P1D to +1DAY :param time_gap: :return: solr's format duration. """ quantity, unit = parse_ISO8601(time_gap) if unit[0] == "WEEKS": return "+{0}DAYS".format(quantity * 7) else: return "+{0}{1}".format(quantity, unit[0])
python
def gap_to_sorl(time_gap): """ P1D to +1DAY :param time_gap: :return: solr's format duration. """ quantity, unit = parse_ISO8601(time_gap) if unit[0] == "WEEKS": return "+{0}DAYS".format(quantity * 7) else: return "+{0}{1}".format(quantity, unit[0])
[ "def", "gap_to_sorl", "(", "time_gap", ")", ":", "quantity", ",", "unit", "=", "parse_ISO8601", "(", "time_gap", ")", "if", "unit", "[", "0", "]", "==", "\"WEEKS\"", ":", "return", "\"+{0}DAYS\"", ".", "format", "(", "quantity", "*", "7", ")", "else", ...
P1D to +1DAY :param time_gap: :return: solr's format duration.
[ "P1D", "to", "+", "1DAY", ":", "param", "time_gap", ":", ":", "return", ":", "solr", "s", "format", "duration", "." ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L185-L195
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
request_time_facet
def request_time_facet(field, time_filter, time_gap, time_limit=100): """ time facet query builder :param field: map the query to this field. :param time_limit: Non-0 triggers time/date range faceting. This value is the maximum number of time ranges to return when a.time.gap is unspecified. This is ...
python
def request_time_facet(field, time_filter, time_gap, time_limit=100): """ time facet query builder :param field: map the query to this field. :param time_limit: Non-0 triggers time/date range faceting. This value is the maximum number of time ranges to return when a.time.gap is unspecified. This is ...
[ "def", "request_time_facet", "(", "field", ",", "time_filter", ",", "time_gap", ",", "time_limit", "=", "100", ")", ":", "start", ",", "end", "=", "parse_datetime_range", "(", "time_filter", ")", "key_range_start", "=", "\"f.{0}.facet.range.start\"", ".", "format"...
time facet query builder :param field: map the query to this field. :param time_limit: Non-0 triggers time/date range faceting. This value is the maximum number of time ranges to return when a.time.gap is unspecified. This is a soft maximum; less will usually be returned. A suggested value is 100. N...
[ "time", "facet", "query", "builder", ":", "param", "field", ":", "map", "the", "query", "to", "this", "field", ".", ":", "param", "time_limit", ":", "Non", "-", "0", "triggers", "time", "/", "date", "range", "faceting", ".", "This", "value", "is", "the...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L198-L244
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
parse_solr_geo_range_as_pair
def parse_solr_geo_range_as_pair(geo_box_str): """ :param geo_box_str: [-90,-180 TO 90,180] :return: ("-90,-180", "90,180") """ pattern = "\\[(.*) TO (.*)\\]" matcher = re.search(pattern, geo_box_str) if matcher: return matcher.group(1), matcher.group(2) else: raise Excep...
python
def parse_solr_geo_range_as_pair(geo_box_str): """ :param geo_box_str: [-90,-180 TO 90,180] :return: ("-90,-180", "90,180") """ pattern = "\\[(.*) TO (.*)\\]" matcher = re.search(pattern, geo_box_str) if matcher: return matcher.group(1), matcher.group(2) else: raise Excep...
[ "def", "parse_solr_geo_range_as_pair", "(", "geo_box_str", ")", ":", "pattern", "=", "\"\\\\[(.*) TO (.*)\\\\]\"", "matcher", "=", "re", ".", "search", "(", "pattern", ",", "geo_box_str", ")", "if", "matcher", ":", "return", "matcher", ".", "group", "(", "1", ...
:param geo_box_str: [-90,-180 TO 90,180] :return: ("-90,-180", "90,180")
[ ":", "param", "geo_box_str", ":", "[", "-", "90", "-", "180", "TO", "90", "180", "]", ":", "return", ":", "(", "-", "90", "-", "180", "90", "180", ")" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L247-L257
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
parse_geo_box
def parse_geo_box(geo_box_str): """ parses [-90,-180 TO 90,180] to a shapely.geometry.box :param geo_box_str: :return: """ from_point_str, to_point_str = parse_solr_geo_range_as_pair(geo_box_str) from_point = parse_lat_lon(from_point_str) to_point = parse_lat_lon(to_point_str) recta...
python
def parse_geo_box(geo_box_str): """ parses [-90,-180 TO 90,180] to a shapely.geometry.box :param geo_box_str: :return: """ from_point_str, to_point_str = parse_solr_geo_range_as_pair(geo_box_str) from_point = parse_lat_lon(from_point_str) to_point = parse_lat_lon(to_point_str) recta...
[ "def", "parse_geo_box", "(", "geo_box_str", ")", ":", "from_point_str", ",", "to_point_str", "=", "parse_solr_geo_range_as_pair", "(", "geo_box_str", ")", "from_point", "=", "parse_lat_lon", "(", "from_point_str", ")", "to_point", "=", "parse_lat_lon", "(", "to_point_...
parses [-90,-180 TO 90,180] to a shapely.geometry.box :param geo_box_str: :return:
[ "parses", "[", "-", "90", "-", "180", "TO", "90", "180", "]", "to", "a", "shapely", ".", "geometry", ".", "box", ":", "param", "geo_box_str", ":", ":", "return", ":" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L265-L276
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
request_heatmap_facet
def request_heatmap_facet(field, hm_filter, hm_grid_level, hm_limit): """ heatmap facet query builder :param field: map the query to this field. :param hm_filter: From what region to plot the heatmap. Defaults to q.geo or otherwise the world. :param hm_grid_level: To explicitly specify the grid leve...
python
def request_heatmap_facet(field, hm_filter, hm_grid_level, hm_limit): """ heatmap facet query builder :param field: map the query to this field. :param hm_filter: From what region to plot the heatmap. Defaults to q.geo or otherwise the world. :param hm_grid_level: To explicitly specify the grid leve...
[ "def", "request_heatmap_facet", "(", "field", ",", "hm_filter", ",", "hm_grid_level", ",", "hm_limit", ")", ":", "if", "not", "hm_filter", ":", "hm_filter", "=", "'[-90,-180 TO 90,180]'", "params", "=", "{", "'facet'", ":", "'on'", ",", "'facet.heatmap'", ":", ...
heatmap facet query builder :param field: map the query to this field. :param hm_filter: From what region to plot the heatmap. Defaults to q.geo or otherwise the world. :param hm_grid_level: To explicitly specify the grid level, e.g. to let a user ask for greater or courser resolution than the most rece...
[ "heatmap", "facet", "query", "builder", ":", "param", "field", ":", "map", "the", "query", "to", "this", "field", ".", ":", "param", "hm_filter", ":", "From", "what", "region", "to", "plot", "the", "heatmap", ".", "Defaults", "to", "q", ".", "geo", "or...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L279-L315
cga-harvard/Hypermap-Registry
hypermap/search_api/utils.py
asterisk_to_min_max
def asterisk_to_min_max(field, time_filter, search_engine_endpoint, actual_params=None): """ traduce [* TO *] to something like [MIN-INDEXED-DATE TO MAX-INDEXED-DATE] :param field: map the stats to this field. :param time_filter: this is the value to be translated. think in "[* TO 2000]" :param sear...
python
def asterisk_to_min_max(field, time_filter, search_engine_endpoint, actual_params=None): """ traduce [* TO *] to something like [MIN-INDEXED-DATE TO MAX-INDEXED-DATE] :param field: map the stats to this field. :param time_filter: this is the value to be translated. think in "[* TO 2000]" :param sear...
[ "def", "asterisk_to_min_max", "(", "field", ",", "time_filter", ",", "search_engine_endpoint", ",", "actual_params", "=", "None", ")", ":", "if", "actual_params", ":", "raise", "NotImplemented", "(", "\"actual_params\"", ")", "start", ",", "end", "=", "parse_solr_...
traduce [* TO *] to something like [MIN-INDEXED-DATE TO MAX-INDEXED-DATE] :param field: map the stats to this field. :param time_filter: this is the value to be translated. think in "[* TO 2000]" :param search_engine_endpoint: solr core :param actual_params: (not implemented) to merge with other params....
[ "traduce", "[", "*", "TO", "*", "]", "to", "something", "like", "[", "MIN", "-", "INDEXED", "-", "DATE", "TO", "MAX", "-", "INDEXED", "-", "DATE", "]", ":", "param", "field", ":", "map", "the", "stats", "to", "this", "field", ".", ":", "param", "...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/utils.py#L322-L359
cga-harvard/Hypermap-Registry
hypermap/search/pycsw_plugin.py
get_service
def get_service(raw_xml): """ Set a service object based on the XML metadata <dct:references scheme="OGC:WMS">http://ngamaps.geointapps.org/arcgis /services/RIO/Rio_Foundation_Transportation/MapServer/WMSServer </dct:references> :param instance: :return: Layer """ from pycsw...
python
def get_service(raw_xml): """ Set a service object based on the XML metadata <dct:references scheme="OGC:WMS">http://ngamaps.geointapps.org/arcgis /services/RIO/Rio_Foundation_Transportation/MapServer/WMSServer </dct:references> :param instance: :return: Layer """ from pycsw...
[ "def", "get_service", "(", "raw_xml", ")", ":", "from", "pycsw", ".", "core", ".", "etree", "import", "etree", "parsed", "=", "etree", ".", "fromstring", "(", "raw_xml", ",", "etree", ".", "XMLParser", "(", "resolve_entities", "=", "False", ")", ")", "# ...
Set a service object based on the XML metadata <dct:references scheme="OGC:WMS">http://ngamaps.geointapps.org/arcgis /services/RIO/Rio_Foundation_Transportation/MapServer/WMSServer </dct:references> :param instance: :return: Layer
[ "Set", "a", "service", "object", "based", "on", "the", "XML", "metadata", "<dct", ":", "references", "scheme", "=", "OGC", ":", "WMS", ">", "http", ":", "//", "ngamaps", ".", "geointapps", ".", "org", "/", "arcgis", "/", "services", "/", "RIO", "/", ...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/pycsw_plugin.py#L56-L95
cga-harvard/Hypermap-Registry
hypermap/search/pycsw_plugin.py
HHypermapRepository.query_ids
def query_ids(self, ids): """ Query by list of identifiers """ results = self._get_repo_filter(Layer.objects).filter(uuid__in=ids).all() if len(results) == 0: # try services results = self._get_repo_filter(Service.objects).filter(uuid__in=ids).all() return...
python
def query_ids(self, ids): """ Query by list of identifiers """ results = self._get_repo_filter(Layer.objects).filter(uuid__in=ids).all() if len(results) == 0: # try services results = self._get_repo_filter(Service.objects).filter(uuid__in=ids).all() return...
[ "def", "query_ids", "(", "self", ",", "ids", ")", ":", "results", "=", "self", ".", "_get_repo_filter", "(", "Layer", ".", "objects", ")", ".", "filter", "(", "uuid__in", "=", "ids", ")", ".", "all", "(", ")", "if", "len", "(", "results", ")", "=="...
Query by list of identifiers
[ "Query", "by", "list", "of", "identifiers" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/pycsw_plugin.py#L152-L162
cga-harvard/Hypermap-Registry
hypermap/search/pycsw_plugin.py
HHypermapRepository.query_domain
def query_domain(self, domain, typenames, domainquerytype='list', count=False): """ Query by property domain values """ objects = self._get_repo_filter(Layer.objects) if domainquerytype == 'range': return [tuple(objects.aggregate(Min(domain), Max(domain)).values())]...
python
def query_domain(self, domain, typenames, domainquerytype='list', count=False): """ Query by property domain values """ objects = self._get_repo_filter(Layer.objects) if domainquerytype == 'range': return [tuple(objects.aggregate(Min(domain), Max(domain)).values())]...
[ "def", "query_domain", "(", "self", ",", "domain", ",", "typenames", ",", "domainquerytype", "=", "'list'", ",", "count", "=", "False", ")", ":", "objects", "=", "self", ".", "_get_repo_filter", "(", "Layer", ".", "objects", ")", "if", "domainquerytype", "...
Query by property domain values
[ "Query", "by", "property", "domain", "values" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/pycsw_plugin.py#L164-L178
cga-harvard/Hypermap-Registry
hypermap/search/pycsw_plugin.py
HHypermapRepository.query_insert
def query_insert(self, direction='max'): """ Query to get latest (default) or earliest update to repository """ if direction == 'min': return Layer.objects.aggregate( Min('last_updated'))['last_updated__min'].strftime('%Y-%m-%dT%H:%M:%SZ') return self....
python
def query_insert(self, direction='max'): """ Query to get latest (default) or earliest update to repository """ if direction == 'min': return Layer.objects.aggregate( Min('last_updated'))['last_updated__min'].strftime('%Y-%m-%dT%H:%M:%SZ') return self....
[ "def", "query_insert", "(", "self", ",", "direction", "=", "'max'", ")", ":", "if", "direction", "==", "'min'", ":", "return", "Layer", ".", "objects", ".", "aggregate", "(", "Min", "(", "'last_updated'", ")", ")", "[", "'last_updated__min'", "]", ".", "...
Query to get latest (default) or earliest update to repository
[ "Query", "to", "get", "latest", "(", "default", ")", "or", "earliest", "update", "to", "repository" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/pycsw_plugin.py#L180-L188
cga-harvard/Hypermap-Registry
hypermap/search/pycsw_plugin.py
HHypermapRepository.query_source
def query_source(self, source): """ Query by source """ return self._get_repo_filter(Layer.objects).filter(url=source)
python
def query_source(self, source): """ Query by source """ return self._get_repo_filter(Layer.objects).filter(url=source)
[ "def", "query_source", "(", "self", ",", "source", ")", ":", "return", "self", ".", "_get_repo_filter", "(", "Layer", ".", "objects", ")", ".", "filter", "(", "url", "=", "source", ")" ]
Query by source
[ "Query", "by", "source" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/pycsw_plugin.py#L190-L194
cga-harvard/Hypermap-Registry
hypermap/search/pycsw_plugin.py
HHypermapRepository.query
def query(self, constraint, sortby=None, typenames=None, maxrecords=10, startposition=0): """ Query records from underlying repository """ # run the raw query and get total # we want to exclude layers which are not valid, as it is done in the search engine if 'where' in ...
python
def query(self, constraint, sortby=None, typenames=None, maxrecords=10, startposition=0): """ Query records from underlying repository """ # run the raw query and get total # we want to exclude layers which are not valid, as it is done in the search engine if 'where' in ...
[ "def", "query", "(", "self", ",", "constraint", ",", "sortby", "=", "None", ",", "typenames", "=", "None", ",", "maxrecords", "=", "10", ",", "startposition", "=", "0", ")", ":", "# run the raw query and get total", "# we want to exclude layers which are not valid, ...
Query records from underlying repository
[ "Query", "records", "from", "underlying", "repository" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/pycsw_plugin.py#L196-L231
cga-harvard/Hypermap-Registry
hypermap/search/pycsw_plugin.py
HHypermapRepository.insert
def insert(self, resourcetype, source, insert_date=None): """ Insert a record into the repository """ caller = inspect.stack()[1][3] if caller == 'transaction': # insert of Layer hhclass = 'Layer' source = resourcetype resourcetype = resourc...
python
def insert(self, resourcetype, source, insert_date=None): """ Insert a record into the repository """ caller = inspect.stack()[1][3] if caller == 'transaction': # insert of Layer hhclass = 'Layer' source = resourcetype resourcetype = resourc...
[ "def", "insert", "(", "self", ",", "resourcetype", ",", "source", ",", "insert_date", "=", "None", ")", ":", "caller", "=", "inspect", ".", "stack", "(", ")", "[", "1", "]", "[", "3", "]", "if", "caller", "==", "'transaction'", ":", "# insert of Layer"...
Insert a record into the repository
[ "Insert", "a", "record", "into", "the", "repository" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/pycsw_plugin.py#L233-L249
cga-harvard/Hypermap-Registry
hypermap/search/pycsw_plugin.py
HHypermapRepository._insert_or_update
def _insert_or_update(self, resourcetype, source, mode='insert', hhclass='Service'): """ Insert or update a record in the repository """ keywords = [] if self.filter is not None: catalog = Catalog.objects.get(id=int(self.filter.split()[-1])) try: ...
python
def _insert_or_update(self, resourcetype, source, mode='insert', hhclass='Service'): """ Insert or update a record in the repository """ keywords = [] if self.filter is not None: catalog = Catalog.objects.get(id=int(self.filter.split()[-1])) try: ...
[ "def", "_insert_or_update", "(", "self", ",", "resourcetype", ",", "source", ",", "mode", "=", "'insert'", ",", "hhclass", "=", "'Service'", ")", ":", "keywords", "=", "[", "]", "if", "self", ".", "filter", "is", "not", "None", ":", "catalog", "=", "Ca...
Insert or update a record in the repository
[ "Insert", "or", "update", "a", "record", "in", "the", "repository" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/pycsw_plugin.py#L251-L321
cga-harvard/Hypermap-Registry
hypermap/search/pycsw_plugin.py
HHypermapRepository.delete
def delete(self, constraint): """ Delete a record from the repository """ results = self._get_repo_filter(Service.objects).extra(where=[constraint['where']], params=constraint['values']).all() deleted = len(results) ...
python
def delete(self, constraint): """ Delete a record from the repository """ results = self._get_repo_filter(Service.objects).extra(where=[constraint['where']], params=constraint['values']).all() deleted = len(results) ...
[ "def", "delete", "(", "self", ",", "constraint", ")", ":", "results", "=", "self", ".", "_get_repo_filter", "(", "Service", ".", "objects", ")", ".", "extra", "(", "where", "=", "[", "constraint", "[", "'where'", "]", "]", ",", "params", "=", "constrai...
Delete a record from the repository
[ "Delete", "a", "record", "from", "the", "repository" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/pycsw_plugin.py#L323-L332
cga-harvard/Hypermap-Registry
hypermap/search/pycsw_plugin.py
HHypermapRepository._get_repo_filter
def _get_repo_filter(self, query): """ Apply repository wide side filter / mask query """ if self.filter is not None: return query.extra(where=[self.filter]) return query
python
def _get_repo_filter(self, query): """ Apply repository wide side filter / mask query """ if self.filter is not None: return query.extra(where=[self.filter]) return query
[ "def", "_get_repo_filter", "(", "self", ",", "query", ")", ":", "if", "self", ".", "filter", "is", "not", "None", ":", "return", "query", ".", "extra", "(", "where", "=", "[", "self", ".", "filter", "]", ")", "return", "query" ]
Apply repository wide side filter / mask query
[ "Apply", "repository", "wide", "side", "filter", "/", "mask", "query" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search/pycsw_plugin.py#L334-L340
hni14/jismesh
jismesh/utils.py
to_meshcode
def to_meshcode(lat, lon, level): """緯度経度から指定次の地域メッシュコードを算出する。 Args: lat: 世界測地系の緯度(度単位) lon: 世界測地系の経度(度単位) level: 地域メッシュコードの次数 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 ...
python
def to_meshcode(lat, lon, level): """緯度経度から指定次の地域メッシュコードを算出する。 Args: lat: 世界測地系の緯度(度単位) lon: 世界測地系の経度(度単位) level: 地域メッシュコードの次数 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 ...
[ "def", "to_meshcode", "(", "lat", ",", "lon", ",", "level", ")", ":", "if", "not", "0", "<=", "lat", "<", "66.66", ":", "raise", "ValueError", "(", "'the latitude is out of bound.'", ")", "if", "not", "100", "<=", "lon", "<", "180", ":", "raise", "Valu...
緯度経度から指定次の地域メッシュコードを算出する。 Args: lat: 世界測地系の緯度(度単位) lon: 世界測地系の経度(度単位) level: 地域メッシュコードの次数 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 ...
[ "緯度経度から指定次の地域メッシュコードを算出する。" ]
train
https://github.com/hni14/jismesh/blob/bda486ac7828d0adaea2a128154d0a554be7ef37/jismesh/utils.py#L64-L238
hni14/jismesh
jismesh/utils.py
to_meshlevel
def to_meshlevel(meshcode): """メッシュコードから次数を算出する。 Args: meshcode: メッシュコード Return: 地域メッシュコードの次数 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 ...
python
def to_meshlevel(meshcode): """メッシュコードから次数を算出する。 Args: meshcode: メッシュコード Return: 地域メッシュコードの次数 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 ...
[ "def", "to_meshlevel", "(", "meshcode", ")", ":", "length", "=", "len", "(", "str", "(", "meshcode", ")", ")", "if", "length", "==", "4", ":", "return", "1", "if", "length", "==", "5", ":", "return", "40000", "if", "length", "==", "6", ":", "return...
メッシュコードから次数を算出する。 Args: meshcode: メッシュコード Return: 地域メッシュコードの次数 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 5倍(5km四方):5000 ...
[ "メッシュコードから次数を算出する。" ]
train
https://github.com/hni14/jismesh/blob/bda486ac7828d0adaea2a128154d0a554be7ef37/jismesh/utils.py#L240-L310
hni14/jismesh
jismesh/utils.py
to_meshpoint
def to_meshpoint(meshcode, lat_multiplier, lon_multiplier): """地域メッシュコードから緯度経度を算出する。 下記のメッシュに対応している。 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 ...
python
def to_meshpoint(meshcode, lat_multiplier, lon_multiplier): """地域メッシュコードから緯度経度を算出する。 下記のメッシュに対応している。 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 ...
[ "def", "to_meshpoint", "(", "meshcode", ",", "lat_multiplier", ",", "lon_multiplier", ")", ":", "def", "mesh_cord", "(", "func_higher_cord", ",", "func_unit_cord", ",", "func_multiplier", ")", ":", "return", "func_higher_cord", "(", ")", "+", "func_unit_cord", "("...
地域メッシュコードから緯度経度を算出する。 下記のメッシュに対応している。 1次(80km四方):1 40倍(40km四方):40000 20倍(20km四方):20000 16倍(16km四方):16000 2次(10km四方):2 8倍(8km四方):8000 5倍(5km四方):5000 4倍(4km四方):4000 2.5倍(...
[ "地域メッシュコードから緯度経度を算出する。", "下記のメッシュに対応している。", "1次", "(", "80km四方", ")", ":", "1", "40倍", "(", "40km四方", ")", ":", "40000", "20倍", "(", "20km四方", ")", ":", "20000", "16倍", "(", "16km四方", ")", ":", "16000", "2次", "(", "10km四方", ")", ":", "2", "8倍", "(", ...
train
https://github.com/hni14/jismesh/blob/bda486ac7828d0adaea2a128154d0a554be7ef37/jismesh/utils.py#L312-L811
caffeinehit/django-follow
follow/views.py
check
def check(func): """ Check the permissions, http method and login state. """ def iCheck(request, *args, **kwargs): if not request.method == "POST": return HttpResponseBadRequest("Must be POST request.") follow = func(request, *args, **kwargs) if request.is_ajax(): ...
python
def check(func): """ Check the permissions, http method and login state. """ def iCheck(request, *args, **kwargs): if not request.method == "POST": return HttpResponseBadRequest("Must be POST request.") follow = func(request, *args, **kwargs) if request.is_ajax(): ...
[ "def", "check", "(", "func", ")", ":", "def", "iCheck", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "request", ".", "method", "==", "\"POST\"", ":", "return", "HttpResponseBadRequest", "(", "\"Must be POST request.\"",...
Check the permissions, http method and login state.
[ "Check", "the", "permissions", "http", "method", "and", "login", "state", "." ]
train
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/views.py#L7-L30
caffeinehit/django-follow
follow/utils.py
register
def register(model, field_name=None, related_name=None, lookup_method_name='get_follows'): """ This registers any model class to be follow-able. """ if model in registry: return registry.append(model) if not field_name: field_name = 'target_%s' % model._meta.module_nam...
python
def register(model, field_name=None, related_name=None, lookup_method_name='get_follows'): """ This registers any model class to be follow-able. """ if model in registry: return registry.append(model) if not field_name: field_name = 'target_%s' % model._meta.module_nam...
[ "def", "register", "(", "model", ",", "field_name", "=", "None", ",", "related_name", "=", "None", ",", "lookup_method_name", "=", "'get_follows'", ")", ":", "if", "model", "in", "registry", ":", "return", "registry", ".", "append", "(", "model", ")", "if"...
This registers any model class to be follow-able.
[ "This", "registers", "any", "model", "class", "to", "be", "follow", "-", "able", "." ]
train
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/utils.py#L9-L30
caffeinehit/django-follow
follow/utils.py
follow
def follow(user, obj): """ Make a user follow an object """ follow, created = Follow.objects.get_or_create(user, obj) return follow
python
def follow(user, obj): """ Make a user follow an object """ follow, created = Follow.objects.get_or_create(user, obj) return follow
[ "def", "follow", "(", "user", ",", "obj", ")", ":", "follow", ",", "created", "=", "Follow", ".", "objects", ".", "get_or_create", "(", "user", ",", "obj", ")", "return", "follow" ]
Make a user follow an object
[ "Make", "a", "user", "follow", "an", "object" ]
train
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/utils.py#L32-L35
caffeinehit/django-follow
follow/utils.py
unfollow
def unfollow(user, obj): """ Make a user unfollow an object """ try: follow = Follow.objects.get_follows(obj).get(user=user) follow.delete() return follow except Follow.DoesNotExist: pass
python
def unfollow(user, obj): """ Make a user unfollow an object """ try: follow = Follow.objects.get_follows(obj).get(user=user) follow.delete() return follow except Follow.DoesNotExist: pass
[ "def", "unfollow", "(", "user", ",", "obj", ")", ":", "try", ":", "follow", "=", "Follow", ".", "objects", ".", "get_follows", "(", "obj", ")", ".", "get", "(", "user", "=", "user", ")", "follow", ".", "delete", "(", ")", "return", "follow", "excep...
Make a user unfollow an object
[ "Make", "a", "user", "unfollow", "an", "object" ]
train
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/utils.py#L37-L44
caffeinehit/django-follow
follow/utils.py
toggle
def toggle(user, obj): """ Toggles a follow status. Useful function if you don't want to perform follow checks but just toggle it on / off. """ if Follow.objects.is_following(user, obj): return unfollow(user, obj) return follow(user, obj)
python
def toggle(user, obj): """ Toggles a follow status. Useful function if you don't want to perform follow checks but just toggle it on / off. """ if Follow.objects.is_following(user, obj): return unfollow(user, obj) return follow(user, obj)
[ "def", "toggle", "(", "user", ",", "obj", ")", ":", "if", "Follow", ".", "objects", ".", "is_following", "(", "user", ",", "obj", ")", ":", "return", "unfollow", "(", "user", ",", "obj", ")", "return", "follow", "(", "user", ",", "obj", ")" ]
Toggles a follow status. Useful function if you don't want to perform follow checks but just toggle it on / off.
[ "Toggles", "a", "follow", "status", ".", "Useful", "function", "if", "you", "don", "t", "want", "to", "perform", "follow", "checks", "but", "just", "toggle", "it", "on", "/", "off", "." ]
train
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/utils.py#L46-L51
cga-harvard/Hypermap-Registry
hypermap/search_api/serializers.py
SearchSerializer.validate_q_time
def validate_q_time(self, value): """ Would be for example: [2013-03-01 TO 2013-04-01T00:00:00] and/or [* TO *] Returns a valid sorl value. [2013-03-01T00:00:00Z TO 2013-04-01T00:00:00Z] and/or [* TO *] """ if value: try: range = utils.parse_datetime_r...
python
def validate_q_time(self, value): """ Would be for example: [2013-03-01 TO 2013-04-01T00:00:00] and/or [* TO *] Returns a valid sorl value. [2013-03-01T00:00:00Z TO 2013-04-01T00:00:00Z] and/or [* TO *] """ if value: try: range = utils.parse_datetime_r...
[ "def", "validate_q_time", "(", "self", ",", "value", ")", ":", "if", "value", ":", "try", ":", "range", "=", "utils", ".", "parse_datetime_range_to_solr", "(", "value", ")", "return", "range", "except", "Exception", "as", "e", ":", "raise", "serializers", ...
Would be for example: [2013-03-01 TO 2013-04-01T00:00:00] and/or [* TO *] Returns a valid sorl value. [2013-03-01T00:00:00Z TO 2013-04-01T00:00:00Z] and/or [* TO *]
[ "Would", "be", "for", "example", ":", "[", "2013", "-", "03", "-", "01", "TO", "2013", "-", "04", "-", "01T00", ":", "00", ":", "00", "]", "and", "/", "or", "[", "*", "TO", "*", "]", "Returns", "a", "valid", "sorl", "value", ".", "[", "2013",...
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/serializers.py#L114-L126
cga-harvard/Hypermap-Registry
hypermap/search_api/serializers.py
SearchSerializer.validate_q_geo
def validate_q_geo(self, value): """ Would be for example: [-90,-180 TO 90,180] """ if value: try: rectangle = utils.parse_geo_box(value) return "[{0},{1} TO {2},{3}]".format( rectangle.bounds[0], rectang...
python
def validate_q_geo(self, value): """ Would be for example: [-90,-180 TO 90,180] """ if value: try: rectangle = utils.parse_geo_box(value) return "[{0},{1} TO {2},{3}]".format( rectangle.bounds[0], rectang...
[ "def", "validate_q_geo", "(", "self", ",", "value", ")", ":", "if", "value", ":", "try", ":", "rectangle", "=", "utils", ".", "parse_geo_box", "(", "value", ")", "return", "\"[{0},{1} TO {2},{3}]\"", ".", "format", "(", "rectangle", ".", "bounds", "[", "0"...
Would be for example: [-90,-180 TO 90,180]
[ "Would", "be", "for", "example", ":", "[", "-", "90", "-", "180", "TO", "90", "180", "]" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/serializers.py#L128-L144
cga-harvard/Hypermap-Registry
hypermap/search_api/serializers.py
SearchSerializer.validate_a_time_filter
def validate_a_time_filter(self, value): """ Would be for example: [2013-03-01 TO 2013-04-01:00:00:00] and/or [* TO *] """ if value: try: utils.parse_datetime_range(value) except Exception as e: raise serializers.ValidationError(e.m...
python
def validate_a_time_filter(self, value): """ Would be for example: [2013-03-01 TO 2013-04-01:00:00:00] and/or [* TO *] """ if value: try: utils.parse_datetime_range(value) except Exception as e: raise serializers.ValidationError(e.m...
[ "def", "validate_a_time_filter", "(", "self", ",", "value", ")", ":", "if", "value", ":", "try", ":", "utils", ".", "parse_datetime_range", "(", "value", ")", "except", "Exception", "as", "e", ":", "raise", "serializers", ".", "ValidationError", "(", "e", ...
Would be for example: [2013-03-01 TO 2013-04-01:00:00:00] and/or [* TO *]
[ "Would", "be", "for", "example", ":", "[", "2013", "-", "03", "-", "01", "TO", "2013", "-", "04", "-", "01", ":", "00", ":", "00", ":", "00", "]", "and", "/", "or", "[", "*", "TO", "*", "]" ]
train
https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/serializers.py#L146-L156
caffeinehit/django-follow
follow/models.py
FollowManager.fname
def fname(self, model_or_obj_or_qs): """ Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``. """ if isinstance(model_or_obj_or_qs, QuerySet): _, fname = model_map[model_or_obj_or_qs.model] else: cls = model_or_obj_or_qs if inspe...
python
def fname(self, model_or_obj_or_qs): """ Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``. """ if isinstance(model_or_obj_or_qs, QuerySet): _, fname = model_map[model_or_obj_or_qs.model] else: cls = model_or_obj_or_qs if inspe...
[ "def", "fname", "(", "self", ",", "model_or_obj_or_qs", ")", ":", "if", "isinstance", "(", "model_or_obj_or_qs", ",", "QuerySet", ")", ":", "_", ",", "fname", "=", "model_map", "[", "model_or_obj_or_qs", ".", "model", "]", "else", ":", "cls", "=", "model_o...
Return the field name on the :class:`Follow` model for ``model_or_obj_or_qs``.
[ "Return", "the", "field", "name", "on", "the", ":", "class", ":", "Follow", "model", "for", "model_or_obj_or_qs", "." ]
train
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/models.py#L10-L19
caffeinehit/django-follow
follow/models.py
FollowManager.create
def create(self, user, obj, **kwargs): """ Create a new follow link between a user and an object of a registered model type. """ follow = Follow(user=user) follow.target = obj follow.save() return follow
python
def create(self, user, obj, **kwargs): """ Create a new follow link between a user and an object of a registered model type. """ follow = Follow(user=user) follow.target = obj follow.save() return follow
[ "def", "create", "(", "self", ",", "user", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "follow", "=", "Follow", "(", "user", "=", "user", ")", "follow", ".", "target", "=", "obj", "follow", ".", "save", "(", ")", "return", "follow" ]
Create a new follow link between a user and an object of a registered model type.
[ "Create", "a", "new", "follow", "link", "between", "a", "user", "and", "an", "object", "of", "a", "registered", "model", "type", "." ]
train
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/models.py#L21-L30
caffeinehit/django-follow
follow/models.py
FollowManager.get_or_create
def get_or_create(self, user, obj, **kwargs): """ Almost the same as `FollowManager.objects.create` - behaves the same as the normal `get_or_create` methods in django though. Returns a tuple with the `Follow` and either `True` or `False` """ if not self.is_following(...
python
def get_or_create(self, user, obj, **kwargs): """ Almost the same as `FollowManager.objects.create` - behaves the same as the normal `get_or_create` methods in django though. Returns a tuple with the `Follow` and either `True` or `False` """ if not self.is_following(...
[ "def", "get_or_create", "(", "self", ",", "user", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "is_following", "(", "user", ",", "obj", ")", ":", "return", "self", ".", "create", "(", "user", ",", "obj", ",", "*", "*",...
Almost the same as `FollowManager.objects.create` - behaves the same as the normal `get_or_create` methods in django though. Returns a tuple with the `Follow` and either `True` or `False`
[ "Almost", "the", "same", "as", "FollowManager", ".", "objects", ".", "create", "-", "behaves", "the", "same", "as", "the", "normal", "get_or_create", "methods", "in", "django", "though", "." ]
train
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/models.py#L32-L42
caffeinehit/django-follow
follow/models.py
FollowManager.is_following
def is_following(self, user, obj): """ Returns `True` or `False` """ if isinstance(user, AnonymousUser): return False return 0 < self.get_follows(obj).filter(user=user).count()
python
def is_following(self, user, obj): """ Returns `True` or `False` """ if isinstance(user, AnonymousUser): return False return 0 < self.get_follows(obj).filter(user=user).count()
[ "def", "is_following", "(", "self", ",", "user", ",", "obj", ")", ":", "if", "isinstance", "(", "user", ",", "AnonymousUser", ")", ":", "return", "False", "return", "0", "<", "self", ".", "get_follows", "(", "obj", ")", ".", "filter", "(", "user", "=...
Returns `True` or `False`
[ "Returns", "True", "or", "False" ]
train
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/models.py#L44-L48
caffeinehit/django-follow
follow/models.py
FollowManager.get_follows
def get_follows(self, model_or_obj_or_qs): """ Returns all the followers of a model, an object or a queryset. """ fname = self.fname(model_or_obj_or_qs) if isinstance(model_or_obj_or_qs, QuerySet): return self.filter(**{'%s__in' % fname: model_or_obj_or_qs}) ...
python
def get_follows(self, model_or_obj_or_qs): """ Returns all the followers of a model, an object or a queryset. """ fname = self.fname(model_or_obj_or_qs) if isinstance(model_or_obj_or_qs, QuerySet): return self.filter(**{'%s__in' % fname: model_or_obj_or_qs}) ...
[ "def", "get_follows", "(", "self", ",", "model_or_obj_or_qs", ")", ":", "fname", "=", "self", ".", "fname", "(", "model_or_obj_or_qs", ")", "if", "isinstance", "(", "model_or_obj_or_qs", ",", "QuerySet", ")", ":", "return", "self", ".", "filter", "(", "*", ...
Returns all the followers of a model, an object or a queryset.
[ "Returns", "all", "the", "followers", "of", "a", "model", "an", "object", "or", "a", "queryset", "." ]
train
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/models.py#L50-L62
tknapen/FIRDeconvolution
src/FIRDeconvolution.py
FIRDeconvolution.create_event_regressors
def create_event_regressors(self, event_times_indices, covariates = None, durations = None): """create_event_regressors creates the part of the design matrix corresponding to one event type. :param event_times_indices: indices in the resampled data, on which the events occurred. :type ...
python
def create_event_regressors(self, event_times_indices, covariates = None, durations = None): """create_event_regressors creates the part of the design matrix corresponding to one event type. :param event_times_indices: indices in the resampled data, on which the events occurred. :type ...
[ "def", "create_event_regressors", "(", "self", ",", "event_times_indices", ",", "covariates", "=", "None", ",", "durations", "=", "None", ")", ":", "# check covariates", "if", "covariates", "is", "None", ":", "covariates", "=", "np", ".", "ones", "(", "self", ...
create_event_regressors creates the part of the design matrix corresponding to one event type. :param event_times_indices: indices in the resampled data, on which the events occurred. :type event_times_indices: numpy array, (nr_events) :param covariates: covariates belonging to thi...
[ "create_event_regressors", "creates", "the", "part", "of", "the", "design", "matrix", "corresponding", "to", "one", "event", "type", "." ]
train
https://github.com/tknapen/FIRDeconvolution/blob/6263496a356c449062fe4c216fef56541f6dc151/src/FIRDeconvolution.py#L121-L172
tknapen/FIRDeconvolution
src/FIRDeconvolution.py
FIRDeconvolution.create_design_matrix
def create_design_matrix(self, demean = False, intercept = True): """create_design_matrix calls create_event_regressors for each of the covariates in the self.covariates dict. self.designmatrix is created and is shaped (nr_regressors, self.resampled_signal.shape[-1]) """ self.design_matrix = np....
python
def create_design_matrix(self, demean = False, intercept = True): """create_design_matrix calls create_event_regressors for each of the covariates in the self.covariates dict. self.designmatrix is created and is shaped (nr_regressors, self.resampled_signal.shape[-1]) """ self.design_matrix = np....
[ "def", "create_design_matrix", "(", "self", ",", "demean", "=", "False", ",", "intercept", "=", "True", ")", ":", "self", ".", "design_matrix", "=", "np", ".", "zeros", "(", "(", "int", "(", "self", ".", "number_of_event_types", "*", "self", ".", "deconv...
create_design_matrix calls create_event_regressors for each of the covariates in the self.covariates dict. self.designmatrix is created and is shaped (nr_regressors, self.resampled_signal.shape[-1])
[ "create_design_matrix", "calls", "create_event_regressors", "for", "each", "of", "the", "covariates", "in", "the", "self", ".", "covariates", "dict", ".", "self", ".", "designmatrix", "is", "created", "and", "is", "shaped", "(", "nr_regressors", "self", ".", "re...
train
https://github.com/tknapen/FIRDeconvolution/blob/6263496a356c449062fe4c216fef56541f6dc151/src/FIRDeconvolution.py#L174-L200
tknapen/FIRDeconvolution
src/FIRDeconvolution.py
FIRDeconvolution.add_continuous_regressors_to_design_matrix
def add_continuous_regressors_to_design_matrix(self, regressors): """add_continuous_regressors_to_design_matrix appends continuously sampled regressors to the existing design matrix. One uses this addition to the design matrix when one expects the data to contain nuisance factors that aren't tied to the moments...
python
def add_continuous_regressors_to_design_matrix(self, regressors): """add_continuous_regressors_to_design_matrix appends continuously sampled regressors to the existing design matrix. One uses this addition to the design matrix when one expects the data to contain nuisance factors that aren't tied to the moments...
[ "def", "add_continuous_regressors_to_design_matrix", "(", "self", ",", "regressors", ")", ":", "previous_design_matrix_shape", "=", "self", ".", "design_matrix", ".", "shape", "if", "len", "(", "regressors", ".", "shape", ")", "==", "1", ":", "regressors", "=", ...
add_continuous_regressors_to_design_matrix appends continuously sampled regressors to the existing design matrix. One uses this addition to the design matrix when one expects the data to contain nuisance factors that aren't tied to the moments of specific events. For instance, in fMRI analysis this allows us to add car...
[ "add_continuous_regressors_to_design_matrix", "appends", "continuously", "sampled", "regressors", "to", "the", "existing", "design", "matrix", ".", "One", "uses", "this", "addition", "to", "the", "design", "matrix", "when", "one", "expects", "the", "data", "to", "co...
train
https://github.com/tknapen/FIRDeconvolution/blob/6263496a356c449062fe4c216fef56541f6dc151/src/FIRDeconvolution.py#L202-L215
tknapen/FIRDeconvolution
src/FIRDeconvolution.py
FIRDeconvolution.regress
def regress(self, method = 'lstsq'): """regress performs linear least squares regression of the designmatrix on the data. :param method: method, or backend to be used for the regression analysis. :type method: string, one of ['lstsq', 'sm_ols'] :returns: instance variables ...
python
def regress(self, method = 'lstsq'): """regress performs linear least squares regression of the designmatrix on the data. :param method: method, or backend to be used for the regression analysis. :type method: string, one of ['lstsq', 'sm_ols'] :returns: instance variables ...
[ "def", "regress", "(", "self", ",", "method", "=", "'lstsq'", ")", ":", "if", "method", "is", "'lstsq'", ":", "self", ".", "betas", ",", "residuals_sum", ",", "rank", ",", "s", "=", "LA", ".", "lstsq", "(", "self", ".", "design_matrix", ".", "T", "...
regress performs linear least squares regression of the designmatrix on the data. :param method: method, or backend to be used for the regression analysis. :type method: string, one of ['lstsq', 'sm_ols'] :returns: instance variables 'betas' (nr_betas x nr_signals) and 'residuals' ...
[ "regress", "performs", "linear", "least", "squares", "regression", "of", "the", "designmatrix", "on", "the", "data", "." ]
train
https://github.com/tknapen/FIRDeconvolution/blob/6263496a356c449062fe4c216fef56541f6dc151/src/FIRDeconvolution.py#L217-L239
tknapen/FIRDeconvolution
src/FIRDeconvolution.py
FIRDeconvolution.ridge_regress
def ridge_regress(self, cv = 20, alphas = None ): """perform k-folds cross-validated ridge regression on the design_matrix. To be used when the design matrix contains very collinear regressors. For cross-validation and ridge fitting, we use sklearn's RidgeCV functionality. Note: intercept is not fit, and data a...
python
def ridge_regress(self, cv = 20, alphas = None ): """perform k-folds cross-validated ridge regression on the design_matrix. To be used when the design matrix contains very collinear regressors. For cross-validation and ridge fitting, we use sklearn's RidgeCV functionality. Note: intercept is not fit, and data a...
[ "def", "ridge_regress", "(", "self", ",", "cv", "=", "20", ",", "alphas", "=", "None", ")", ":", "if", "alphas", "is", "None", ":", "alphas", "=", "np", ".", "logspace", "(", "7", ",", "0", ",", "20", ")", "self", ".", "rcv", "=", "linear_model",...
perform k-folds cross-validated ridge regression on the design_matrix. To be used when the design matrix contains very collinear regressors. For cross-validation and ridge fitting, we use sklearn's RidgeCV functionality. Note: intercept is not fit, and data are not prenormalized. :param cv: cross-validate...
[ "perform", "k", "-", "folds", "cross", "-", "validated", "ridge", "regression", "on", "the", "design_matrix", ".", "To", "be", "used", "when", "the", "design", "matrix", "contains", "very", "collinear", "regressors", ".", "For", "cross", "-", "validation", "...
train
https://github.com/tknapen/FIRDeconvolution/blob/6263496a356c449062fe4c216fef56541f6dc151/src/FIRDeconvolution.py#L241-L260
tknapen/FIRDeconvolution
src/FIRDeconvolution.py
FIRDeconvolution.betas_for_cov
def betas_for_cov(self, covariate = '0'): """betas_for_cov returns the beta values (i.e. IRF) associated with a specific covariate. :param covariate: name of covariate. :type covariate: string """ # find the index in the designmatrix of the current covariate this...
python
def betas_for_cov(self, covariate = '0'): """betas_for_cov returns the beta values (i.e. IRF) associated with a specific covariate. :param covariate: name of covariate. :type covariate: string """ # find the index in the designmatrix of the current covariate this...
[ "def", "betas_for_cov", "(", "self", ",", "covariate", "=", "'0'", ")", ":", "# find the index in the designmatrix of the current covariate", "this_covariate_index", "=", "list", "(", "self", ".", "covariates", ".", "keys", "(", ")", ")", ".", "index", "(", "covar...
betas_for_cov returns the beta values (i.e. IRF) associated with a specific covariate. :param covariate: name of covariate. :type covariate: string
[ "betas_for_cov", "returns", "the", "beta", "values", "(", "i", ".", "e", ".", "IRF", ")", "associated", "with", "a", "specific", "covariate", "." ]
train
https://github.com/tknapen/FIRDeconvolution/blob/6263496a356c449062fe4c216fef56541f6dc151/src/FIRDeconvolution.py#L262-L270
tknapen/FIRDeconvolution
src/FIRDeconvolution.py
FIRDeconvolution.betas_for_events
def betas_for_events(self): """betas_for_events creates an internal self.betas_per_event_type array, of (nr_covariates x self.devonvolution_interval_size), which holds the outcome betas per event type,in the order generated by self.covariates.keys() """ self.betas_per_event_type = np.ze...
python
def betas_for_events(self): """betas_for_events creates an internal self.betas_per_event_type array, of (nr_covariates x self.devonvolution_interval_size), which holds the outcome betas per event type,in the order generated by self.covariates.keys() """ self.betas_per_event_type = np.ze...
[ "def", "betas_for_events", "(", "self", ")", ":", "self", ".", "betas_per_event_type", "=", "np", ".", "zeros", "(", "(", "len", "(", "self", ".", "covariates", ")", ",", "self", ".", "deconvolution_interval_size", ",", "self", ".", "resampled_signal", ".", ...
betas_for_events creates an internal self.betas_per_event_type array, of (nr_covariates x self.devonvolution_interval_size), which holds the outcome betas per event type,in the order generated by self.covariates.keys()
[ "betas_for_events", "creates", "an", "internal", "self", ".", "betas_per_event_type", "array", "of", "(", "nr_covariates", "x", "self", ".", "devonvolution_interval_size", ")", "which", "holds", "the", "outcome", "betas", "per", "event", "type", "in", "the", "orde...
train
https://github.com/tknapen/FIRDeconvolution/blob/6263496a356c449062fe4c216fef56541f6dc151/src/FIRDeconvolution.py#L272-L278