repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
Unbabel/unbabel-py
unbabel/xliff_converter.py
generate_xliff
def generate_xliff(entry_dict): """ Given a dictionary with keys = ids and values equals to strings generates and xliff file to send to unbabel. Example: {"123": "This is blue car", "234": "This house is yellow" } returns <xliff version = "1.2"> <file original = "" source-language = "en" target-language = "fr"> <head> </ head> <body> <trans-unit id = "14077"> <source> T2 apartment, as new building with swimming pool, sauna and gym. Inserted in Quinta da Beloura 1, which offers a variety of services such as private security 24 hours, tennis, golf, hotel, restaurants, and more. The apartment has air conditioning in all rooms, central heating, balcony and security screen for children in all windows. </ source> </ trans-unit> </ body> </ file> </ xliff> """ entries = "" for key,value in entry_dict.iteritems(): entries+=create_trans_unit(key,value).strip()+"\n" xliff_str = get_head_xliff().strip()+"\n"+entries+get_tail_xliff().strip() return xliff_str
python
def generate_xliff(entry_dict): """ Given a dictionary with keys = ids and values equals to strings generates and xliff file to send to unbabel. Example: {"123": "This is blue car", "234": "This house is yellow" } returns <xliff version = "1.2"> <file original = "" source-language = "en" target-language = "fr"> <head> </ head> <body> <trans-unit id = "14077"> <source> T2 apartment, as new building with swimming pool, sauna and gym. Inserted in Quinta da Beloura 1, which offers a variety of services such as private security 24 hours, tennis, golf, hotel, restaurants, and more. The apartment has air conditioning in all rooms, central heating, balcony and security screen for children in all windows. </ source> </ trans-unit> </ body> </ file> </ xliff> """ entries = "" for key,value in entry_dict.iteritems(): entries+=create_trans_unit(key,value).strip()+"\n" xliff_str = get_head_xliff().strip()+"\n"+entries+get_tail_xliff().strip() return xliff_str
[ "def", "generate_xliff", "(", "entry_dict", ")", ":", "entries", "=", "\"\"", "for", "key", ",", "value", "in", "entry_dict", ".", "iteritems", "(", ")", ":", "entries", "+=", "create_trans_unit", "(", "key", ",", "value", ")", ".", "strip", "(", ")", "+", "\"\\n\"", "xliff_str", "=", "get_head_xliff", "(", ")", ".", "strip", "(", ")", "+", "\"\\n\"", "+", "entries", "+", "get_tail_xliff", "(", ")", ".", "strip", "(", ")", "return", "xliff_str" ]
Given a dictionary with keys = ids and values equals to strings generates and xliff file to send to unbabel. Example: {"123": "This is blue car", "234": "This house is yellow" } returns <xliff version = "1.2"> <file original = "" source-language = "en" target-language = "fr"> <head> </ head> <body> <trans-unit id = "14077"> <source> T2 apartment, as new building with swimming pool, sauna and gym. Inserted in Quinta da Beloura 1, which offers a variety of services such as private security 24 hours, tennis, golf, hotel, restaurants, and more. The apartment has air conditioning in all rooms, central heating, balcony and security screen for children in all windows. </ source> </ trans-unit> </ body> </ file> </ xliff>
[ "Given", "a", "dictionary", "with", "keys", "=", "ids", "and", "values", "equals", "to", "strings", "generates", "and", "xliff", "file", "to", "send", "to", "unbabel", "." ]
3bd6397174e184d89d2a11149d87be5d12570c64
https://github.com/Unbabel/unbabel-py/blob/3bd6397174e184d89d2a11149d87be5d12570c64/unbabel/xliff_converter.py#L5-L34
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/alert.py
Alerts.Get
def Get(self,key): """Get alert by providing name, ID, or other unique key. If key is not unique and finds multiple matches only the first will be returned """ for alert in self.alerts: if alert.id == key: return(alert) elif alert.name == key: return(alert)
python
def Get(self,key): """Get alert by providing name, ID, or other unique key. If key is not unique and finds multiple matches only the first will be returned """ for alert in self.alerts: if alert.id == key: return(alert) elif alert.name == key: return(alert)
[ "def", "Get", "(", "self", ",", "key", ")", ":", "for", "alert", "in", "self", ".", "alerts", ":", "if", "alert", ".", "id", "==", "key", ":", "return", "(", "alert", ")", "elif", "alert", ".", "name", "==", "key", ":", "return", "(", "alert", ")" ]
Get alert by providing name, ID, or other unique key. If key is not unique and finds multiple matches only the first will be returned
[ "Get", "alert", "by", "providing", "name", "ID", "or", "other", "unique", "key", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/alert.py#L30-L39
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/alert.py
Alerts.Search
def Search(self,key): """Search alert list by providing partial name, ID, or other key. """ results = [] for alert in self.alerts: if alert.id.lower().find(key.lower()) != -1: results.append(alert) elif alert.name.lower().find(key.lower()) != -1: results.append(alert) return(results)
python
def Search(self,key): """Search alert list by providing partial name, ID, or other key. """ results = [] for alert in self.alerts: if alert.id.lower().find(key.lower()) != -1: results.append(alert) elif alert.name.lower().find(key.lower()) != -1: results.append(alert) return(results)
[ "def", "Search", "(", "self", ",", "key", ")", ":", "results", "=", "[", "]", "for", "alert", "in", "self", ".", "alerts", ":", "if", "alert", ".", "id", ".", "lower", "(", ")", ".", "find", "(", "key", ".", "lower", "(", ")", ")", "!=", "-", "1", ":", "results", ".", "append", "(", "alert", ")", "elif", "alert", ".", "name", ".", "lower", "(", ")", ".", "find", "(", "key", ".", "lower", "(", ")", ")", "!=", "-", "1", ":", "results", ".", "append", "(", "alert", ")", "return", "(", "results", ")" ]
Search alert list by providing partial name, ID, or other key.
[ "Search", "alert", "list", "by", "providing", "partial", "name", "ID", "or", "other", "key", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/alert.py#L42-L52
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/api.py
API._Login
def _Login(): """Login to retrieve bearer token and set default accoutn and location aliases.""" if not clc.v2.V2_API_USERNAME or not clc.v2.V2_API_PASSWD: clc.v1.output.Status('ERROR',3,'V2 API username and password not provided') raise(clc.APIV2NotEnabled) session = clc._REQUESTS_SESSION session.headers['content-type'] = "application/json" r = session.request("POST", "%s/v2/%s" % (clc.defaults.ENDPOINT_URL_V2,"authentication/login"), json={"username": clc.v2.V2_API_USERNAME, "password": clc.v2.V2_API_PASSWD}, verify=API._ResourcePath('clc/cacert.pem')) if r.status_code == 200: clc._LOGIN_TOKEN_V2 = r.json()['bearerToken'] clc.ALIAS = r.json()['accountAlias'] clc.LOCATION = r.json()['locationAlias'] elif r.status_code == 400: raise(Exception("Invalid V2 API login. %s" % (r.json()['message']))) else: raise(Exception("Error logging into V2 API. Response code %s. message %s" % (r.status_code,r.json()['message'])))
python
def _Login(): """Login to retrieve bearer token and set default accoutn and location aliases.""" if not clc.v2.V2_API_USERNAME or not clc.v2.V2_API_PASSWD: clc.v1.output.Status('ERROR',3,'V2 API username and password not provided') raise(clc.APIV2NotEnabled) session = clc._REQUESTS_SESSION session.headers['content-type'] = "application/json" r = session.request("POST", "%s/v2/%s" % (clc.defaults.ENDPOINT_URL_V2,"authentication/login"), json={"username": clc.v2.V2_API_USERNAME, "password": clc.v2.V2_API_PASSWD}, verify=API._ResourcePath('clc/cacert.pem')) if r.status_code == 200: clc._LOGIN_TOKEN_V2 = r.json()['bearerToken'] clc.ALIAS = r.json()['accountAlias'] clc.LOCATION = r.json()['locationAlias'] elif r.status_code == 400: raise(Exception("Invalid V2 API login. %s" % (r.json()['message']))) else: raise(Exception("Error logging into V2 API. Response code %s. message %s" % (r.status_code,r.json()['message'])))
[ "def", "_Login", "(", ")", ":", "if", "not", "clc", ".", "v2", ".", "V2_API_USERNAME", "or", "not", "clc", ".", "v2", ".", "V2_API_PASSWD", ":", "clc", ".", "v1", ".", "output", ".", "Status", "(", "'ERROR'", ",", "3", ",", "'V2 API username and password not provided'", ")", "raise", "(", "clc", ".", "APIV2NotEnabled", ")", "session", "=", "clc", ".", "_REQUESTS_SESSION", "session", ".", "headers", "[", "'content-type'", "]", "=", "\"application/json\"", "r", "=", "session", ".", "request", "(", "\"POST\"", ",", "\"%s/v2/%s\"", "%", "(", "clc", ".", "defaults", ".", "ENDPOINT_URL_V2", ",", "\"authentication/login\"", ")", ",", "json", "=", "{", "\"username\"", ":", "clc", ".", "v2", ".", "V2_API_USERNAME", ",", "\"password\"", ":", "clc", ".", "v2", ".", "V2_API_PASSWD", "}", ",", "verify", "=", "API", ".", "_ResourcePath", "(", "'clc/cacert.pem'", ")", ")", "if", "r", ".", "status_code", "==", "200", ":", "clc", ".", "_LOGIN_TOKEN_V2", "=", "r", ".", "json", "(", ")", "[", "'bearerToken'", "]", "clc", ".", "ALIAS", "=", "r", ".", "json", "(", ")", "[", "'accountAlias'", "]", "clc", ".", "LOCATION", "=", "r", ".", "json", "(", ")", "[", "'locationAlias'", "]", "elif", "r", ".", "status_code", "==", "400", ":", "raise", "(", "Exception", "(", "\"Invalid V2 API login. %s\"", "%", "(", "r", ".", "json", "(", ")", "[", "'message'", "]", ")", ")", ")", "else", ":", "raise", "(", "Exception", "(", "\"Error logging into V2 API. Response code %s. message %s\"", "%", "(", "r", ".", "status_code", ",", "r", ".", "json", "(", ")", "[", "'message'", "]", ")", ")", ")" ]
Login to retrieve bearer token and set default accoutn and location aliases.
[ "Login", "to", "retrieve", "bearer", "token", "and", "set", "default", "accoutn", "and", "location", "aliases", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/api.py#L62-L83
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/api.py
API.Call
def Call(method,url,payload=None,session=None,debug=False): """Execute v2 API call. :param url: URL paths associated with the API call :param payload: dict containing all parameters to submit with POST call :returns: decoded API json result """ if session is not None: token = session['token'] http_session = session['http_session'] else: if not clc._LOGIN_TOKEN_V2: API._Login() token = clc._LOGIN_TOKEN_V2 http_session = clc._REQUESTS_SESSION if payload is None: payload = {} # If executing refs provided in API they are abs paths, # Else refs we build in the sdk are relative if url[0]=='/': fq_url = "%s%s" % (clc.defaults.ENDPOINT_URL_V2,url) else: fq_url = "%s/v2/%s" % (clc.defaults.ENDPOINT_URL_V2,url) http_session.headers.update({'Authorization': "Bearer %s" % token}) if isinstance(payload, basestring): http_session.headers['content-type'] = "Application/json" # added for server ops with str payload else: http_session.headers['content-type'] = "application/x-www-form-urlencoded" if method=="GET": r = http_session.request(method,fq_url, params=payload, verify=API._ResourcePath('clc/cacert.pem')) else: r = http_session.request(method,fq_url, data=payload, verify=API._ResourcePath('clc/cacert.pem')) if debug: API._DebugRequest(request=requests.Request(method,fq_url,data=payload,headers=http_session.headers).prepare(), response=r) if r.status_code>=200 and r.status_code<300: try: return(r.json()) except: return({}) else: try: e = clc.APIFailedResponse("Response code %s. %s %s %s" % (r.status_code,r.json()['message'],method,fq_url)) e.response_status_code = r.status_code e.response_json = r.json() e.response_text = r.text raise(e) except clc.APIFailedResponse: raise except: e = clc.APIFailedResponse("Response code %s. %s. %s %s" % (r.status_code,r.text,method,fq_url)) e.response_status_code = r.status_code e.response_json = {} # or should this be None? e.response_text = r.text raise(e)
python
def Call(method,url,payload=None,session=None,debug=False): """Execute v2 API call. :param url: URL paths associated with the API call :param payload: dict containing all parameters to submit with POST call :returns: decoded API json result """ if session is not None: token = session['token'] http_session = session['http_session'] else: if not clc._LOGIN_TOKEN_V2: API._Login() token = clc._LOGIN_TOKEN_V2 http_session = clc._REQUESTS_SESSION if payload is None: payload = {} # If executing refs provided in API they are abs paths, # Else refs we build in the sdk are relative if url[0]=='/': fq_url = "%s%s" % (clc.defaults.ENDPOINT_URL_V2,url) else: fq_url = "%s/v2/%s" % (clc.defaults.ENDPOINT_URL_V2,url) http_session.headers.update({'Authorization': "Bearer %s" % token}) if isinstance(payload, basestring): http_session.headers['content-type'] = "Application/json" # added for server ops with str payload else: http_session.headers['content-type'] = "application/x-www-form-urlencoded" if method=="GET": r = http_session.request(method,fq_url, params=payload, verify=API._ResourcePath('clc/cacert.pem')) else: r = http_session.request(method,fq_url, data=payload, verify=API._ResourcePath('clc/cacert.pem')) if debug: API._DebugRequest(request=requests.Request(method,fq_url,data=payload,headers=http_session.headers).prepare(), response=r) if r.status_code>=200 and r.status_code<300: try: return(r.json()) except: return({}) else: try: e = clc.APIFailedResponse("Response code %s. %s %s %s" % (r.status_code,r.json()['message'],method,fq_url)) e.response_status_code = r.status_code e.response_json = r.json() e.response_text = r.text raise(e) except clc.APIFailedResponse: raise except: e = clc.APIFailedResponse("Response code %s. %s. %s %s" % (r.status_code,r.text,method,fq_url)) e.response_status_code = r.status_code e.response_json = {} # or should this be None? e.response_text = r.text raise(e)
[ "def", "Call", "(", "method", ",", "url", ",", "payload", "=", "None", ",", "session", "=", "None", ",", "debug", "=", "False", ")", ":", "if", "session", "is", "not", "None", ":", "token", "=", "session", "[", "'token'", "]", "http_session", "=", "session", "[", "'http_session'", "]", "else", ":", "if", "not", "clc", ".", "_LOGIN_TOKEN_V2", ":", "API", ".", "_Login", "(", ")", "token", "=", "clc", ".", "_LOGIN_TOKEN_V2", "http_session", "=", "clc", ".", "_REQUESTS_SESSION", "if", "payload", "is", "None", ":", "payload", "=", "{", "}", "# If executing refs provided in API they are abs paths,", "# Else refs we build in the sdk are relative", "if", "url", "[", "0", "]", "==", "'/'", ":", "fq_url", "=", "\"%s%s\"", "%", "(", "clc", ".", "defaults", ".", "ENDPOINT_URL_V2", ",", "url", ")", "else", ":", "fq_url", "=", "\"%s/v2/%s\"", "%", "(", "clc", ".", "defaults", ".", "ENDPOINT_URL_V2", ",", "url", ")", "http_session", ".", "headers", ".", "update", "(", "{", "'Authorization'", ":", "\"Bearer %s\"", "%", "token", "}", ")", "if", "isinstance", "(", "payload", ",", "basestring", ")", ":", "http_session", ".", "headers", "[", "'content-type'", "]", "=", "\"Application/json\"", "# added for server ops with str payload", "else", ":", "http_session", ".", "headers", "[", "'content-type'", "]", "=", "\"application/x-www-form-urlencoded\"", "if", "method", "==", "\"GET\"", ":", "r", "=", "http_session", ".", "request", "(", "method", ",", "fq_url", ",", "params", "=", "payload", ",", "verify", "=", "API", ".", "_ResourcePath", "(", "'clc/cacert.pem'", ")", ")", "else", ":", "r", "=", "http_session", ".", "request", "(", "method", ",", "fq_url", ",", "data", "=", "payload", ",", "verify", "=", "API", ".", "_ResourcePath", "(", "'clc/cacert.pem'", ")", ")", "if", "debug", ":", "API", ".", "_DebugRequest", "(", "request", "=", "requests", ".", "Request", "(", "method", ",", "fq_url", ",", "data", "=", "payload", ",", "headers", "=", "http_session", ".", "headers", ")", ".", "prepare", "(", ")", ",", "response", "=", "r", ")", "if", "r", ".", "status_code", ">=", "200", "and", "r", ".", "status_code", "<", "300", ":", "try", ":", "return", "(", "r", ".", "json", "(", ")", ")", "except", ":", "return", "(", "{", "}", ")", "else", ":", "try", ":", "e", "=", "clc", ".", "APIFailedResponse", "(", "\"Response code %s. %s %s %s\"", "%", "(", "r", ".", "status_code", ",", "r", ".", "json", "(", ")", "[", "'message'", "]", ",", "method", ",", "fq_url", ")", ")", "e", ".", "response_status_code", "=", "r", ".", "status_code", "e", ".", "response_json", "=", "r", ".", "json", "(", ")", "e", ".", "response_text", "=", "r", ".", "text", "raise", "(", "e", ")", "except", "clc", ".", "APIFailedResponse", ":", "raise", "except", ":", "e", "=", "clc", ".", "APIFailedResponse", "(", "\"Response code %s. %s. %s %s\"", "%", "(", "r", ".", "status_code", ",", "r", ".", "text", ",", "method", ",", "fq_url", ")", ")", "e", ".", "response_status_code", "=", "r", ".", "status_code", "e", ".", "response_json", "=", "{", "}", "# or should this be None?", "e", ".", "response_text", "=", "r", ".", "text", "raise", "(", "e", ")" ]
Execute v2 API call. :param url: URL paths associated with the API call :param payload: dict containing all parameters to submit with POST call :returns: decoded API json result
[ "Execute", "v2", "API", "call", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/api.py#L87-L152
train
cltl/KafNafParserPy
KafNafParserPy/srl_data.py
Crole.get_external_references
def get_external_references(self): """ Returns the external references of the element @rtype: L{CexternalReference} @return: the external references (iterator) """ node = self.node.find('externalReferences') if node is not None: ext_refs = CexternalReferences(node) for ext_ref in ext_refs: yield ext_ref
python
def get_external_references(self): """ Returns the external references of the element @rtype: L{CexternalReference} @return: the external references (iterator) """ node = self.node.find('externalReferences') if node is not None: ext_refs = CexternalReferences(node) for ext_ref in ext_refs: yield ext_ref
[ "def", "get_external_references", "(", "self", ")", ":", "node", "=", "self", ".", "node", ".", "find", "(", "'externalReferences'", ")", "if", "node", "is", "not", "None", ":", "ext_refs", "=", "CexternalReferences", "(", "node", ")", "for", "ext_ref", "in", "ext_refs", ":", "yield", "ext_ref" ]
Returns the external references of the element @rtype: L{CexternalReference} @return: the external references (iterator)
[ "Returns", "the", "external", "references", "of", "the", "element" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/srl_data.py#L102-L112
train
cltl/KafNafParserPy
KafNafParserPy/srl_data.py
Crole.add_external_reference
def add_external_reference(self,ext_ref): """ Adds an external reference to the role @param ext_ref: the external reference object @type ext_ref: L{CexternalReference} """ #check if the externalreferences sublayer exist for the role, and create it in case node_ext_refs = self.node.find('externalReferences') ext_refs = None if node_ext_refs == None: ext_refs = CexternalReferences() self.node.append(ext_refs.get_node()) else: ext_refs = CexternalReferences(node_ext_refs) ext_refs.add_external_reference(ext_ref)
python
def add_external_reference(self,ext_ref): """ Adds an external reference to the role @param ext_ref: the external reference object @type ext_ref: L{CexternalReference} """ #check if the externalreferences sublayer exist for the role, and create it in case node_ext_refs = self.node.find('externalReferences') ext_refs = None if node_ext_refs == None: ext_refs = CexternalReferences() self.node.append(ext_refs.get_node()) else: ext_refs = CexternalReferences(node_ext_refs) ext_refs.add_external_reference(ext_ref)
[ "def", "add_external_reference", "(", "self", ",", "ext_ref", ")", ":", "#check if the externalreferences sublayer exist for the role, and create it in case", "node_ext_refs", "=", "self", ".", "node", ".", "find", "(", "'externalReferences'", ")", "ext_refs", "=", "None", "if", "node_ext_refs", "==", "None", ":", "ext_refs", "=", "CexternalReferences", "(", ")", "self", ".", "node", ".", "append", "(", "ext_refs", ".", "get_node", "(", ")", ")", "else", ":", "ext_refs", "=", "CexternalReferences", "(", "node_ext_refs", ")", "ext_refs", ".", "add_external_reference", "(", "ext_ref", ")" ]
Adds an external reference to the role @param ext_ref: the external reference object @type ext_ref: L{CexternalReference}
[ "Adds", "an", "external", "reference", "to", "the", "role" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/srl_data.py#L114-L129
train
cltl/KafNafParserPy
KafNafParserPy/srl_data.py
Crole.remove_external_references
def remove_external_references(self): """ Removes any external reference from the role """ for ex_ref_node in self.node.findall('externalReferences'): self.node.remove(ex_ref_node)
python
def remove_external_references(self): """ Removes any external reference from the role """ for ex_ref_node in self.node.findall('externalReferences'): self.node.remove(ex_ref_node)
[ "def", "remove_external_references", "(", "self", ")", ":", "for", "ex_ref_node", "in", "self", ".", "node", ".", "findall", "(", "'externalReferences'", ")", ":", "self", ".", "node", ".", "remove", "(", "ex_ref_node", ")" ]
Removes any external reference from the role
[ "Removes", "any", "external", "reference", "from", "the", "role" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/srl_data.py#L132-L137
train
cltl/KafNafParserPy
KafNafParserPy/srl_data.py
Cpredicate.remove_external_references_from_roles
def remove_external_references_from_roles(self): """ Removes any external references on any of the roles from the predicate """ for node_role in self.node.findall('role'): role = Crole(node_role) role.remove_external_references()
python
def remove_external_references_from_roles(self): """ Removes any external references on any of the roles from the predicate """ for node_role in self.node.findall('role'): role = Crole(node_role) role.remove_external_references()
[ "def", "remove_external_references_from_roles", "(", "self", ")", ":", "for", "node_role", "in", "self", ".", "node", ".", "findall", "(", "'role'", ")", ":", "role", "=", "Crole", "(", "node_role", ")", "role", ".", "remove_external_references", "(", ")" ]
Removes any external references on any of the roles from the predicate
[ "Removes", "any", "external", "references", "on", "any", "of", "the", "roles", "from", "the", "predicate" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/srl_data.py#L290-L297
train
cltl/KafNafParserPy
KafNafParserPy/srl_data.py
Cpredicate.add_roles
def add_roles(self, list_of_roles): """ Adds a list of roles to the predicate @type list_of_roles: list @param list_of_roles: list of roles """ for role in list_of_roles: role_node = role.get_node() self.node.append(role_node)
python
def add_roles(self, list_of_roles): """ Adds a list of roles to the predicate @type list_of_roles: list @param list_of_roles: list of roles """ for role in list_of_roles: role_node = role.get_node() self.node.append(role_node)
[ "def", "add_roles", "(", "self", ",", "list_of_roles", ")", ":", "for", "role", "in", "list_of_roles", ":", "role_node", "=", "role", ".", "get_node", "(", ")", "self", ".", "node", ".", "append", "(", "role_node", ")" ]
Adds a list of roles to the predicate @type list_of_roles: list @param list_of_roles: list of roles
[ "Adds", "a", "list", "of", "roles", "to", "the", "predicate" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/srl_data.py#L308-L316
train
cltl/KafNafParserPy
KafNafParserPy/srl_data.py
Cpredicate.add_role
def add_role(self, role_obj): """ Add a role to the predicate @type role_obj: L{Crole} @param role_obj: the role object """ role_node = role_obj.get_node() self.node.append(role_node)
python
def add_role(self, role_obj): """ Add a role to the predicate @type role_obj: L{Crole} @param role_obj: the role object """ role_node = role_obj.get_node() self.node.append(role_node)
[ "def", "add_role", "(", "self", ",", "role_obj", ")", ":", "role_node", "=", "role_obj", ".", "get_node", "(", ")", "self", ".", "node", ".", "append", "(", "role_node", ")" ]
Add a role to the predicate @type role_obj: L{Crole} @param role_obj: the role object
[ "Add", "a", "role", "to", "the", "predicate" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/srl_data.py#L318-L325
train
cltl/KafNafParserPy
KafNafParserPy/srl_data.py
Csrl.add_external_reference_to_role
def add_external_reference_to_role(self,role_id,ext_ref): """ Adds an external reference to a role identifier @param role_id: the role identifier @type role_id: string @param ext_ref: the external reference @type ext_ref: L{CexternalReference} """ node_role = self.map_roleid_node[role_id] obj_role = Crole(node_role) obj_role.add_external_reference(ext_ref)
python
def add_external_reference_to_role(self,role_id,ext_ref): """ Adds an external reference to a role identifier @param role_id: the role identifier @type role_id: string @param ext_ref: the external reference @type ext_ref: L{CexternalReference} """ node_role = self.map_roleid_node[role_id] obj_role = Crole(node_role) obj_role.add_external_reference(ext_ref)
[ "def", "add_external_reference_to_role", "(", "self", ",", "role_id", ",", "ext_ref", ")", ":", "node_role", "=", "self", ".", "map_roleid_node", "[", "role_id", "]", "obj_role", "=", "Crole", "(", "node_role", ")", "obj_role", ".", "add_external_reference", "(", "ext_ref", ")" ]
Adds an external reference to a role identifier @param role_id: the role identifier @type role_id: string @param ext_ref: the external reference @type ext_ref: L{CexternalReference}
[ "Adds", "an", "external", "reference", "to", "a", "role", "identifier" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/srl_data.py#L377-L387
train
cltl/KafNafParserPy
KafNafParserPy/srl_data.py
Csrl.add_predicate
def add_predicate(self, pred_obj): """ Adds a predicate object to the layer @type pred_obj: L{Cpredicate} @param pred_obj: the predicate object """ pred_id = pred_obj.get_id() if not pred_id in self.idx: pred_node = pred_obj.get_node() self.node.append(pred_node) self.idx[pred_id] = pred_node else: #FIXME we want new id rather than ignoring the element print('Error: trying to add new element, but id has already been given')
python
def add_predicate(self, pred_obj): """ Adds a predicate object to the layer @type pred_obj: L{Cpredicate} @param pred_obj: the predicate object """ pred_id = pred_obj.get_id() if not pred_id in self.idx: pred_node = pred_obj.get_node() self.node.append(pred_node) self.idx[pred_id] = pred_node else: #FIXME we want new id rather than ignoring the element print('Error: trying to add new element, but id has already been given')
[ "def", "add_predicate", "(", "self", ",", "pred_obj", ")", ":", "pred_id", "=", "pred_obj", ".", "get_id", "(", ")", "if", "not", "pred_id", "in", "self", ".", "idx", ":", "pred_node", "=", "pred_obj", ".", "get_node", "(", ")", "self", ".", "node", ".", "append", "(", "pred_node", ")", "self", ".", "idx", "[", "pred_id", "]", "=", "pred_node", "else", ":", "#FIXME we want new id rather than ignoring the element", "print", "(", "'Error: trying to add new element, but id has already been given'", ")" ]
Adds a predicate object to the layer @type pred_obj: L{Cpredicate} @param pred_obj: the predicate object
[ "Adds", "a", "predicate", "object", "to", "the", "layer" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/srl_data.py#L390-L403
train
thombashi/DataProperty
examples/py/to_dp_matrix.py
display_dp_matrix_attr
def display_dp_matrix_attr(dp_matrix, attr_name): """ show a value assocciated with an attribute for each DataProperty instance in the dp_matrix """ print() print("---------- {:s} ----------".format(attr_name)) for dp_list in dp_matrix: print([getattr(dp, attr_name) for dp in dp_list])
python
def display_dp_matrix_attr(dp_matrix, attr_name): """ show a value assocciated with an attribute for each DataProperty instance in the dp_matrix """ print() print("---------- {:s} ----------".format(attr_name)) for dp_list in dp_matrix: print([getattr(dp, attr_name) for dp in dp_list])
[ "def", "display_dp_matrix_attr", "(", "dp_matrix", ",", "attr_name", ")", ":", "print", "(", ")", "print", "(", "\"---------- {:s} ----------\"", ".", "format", "(", "attr_name", ")", ")", "for", "dp_list", "in", "dp_matrix", ":", "print", "(", "[", "getattr", "(", "dp", ",", "attr_name", ")", "for", "dp", "in", "dp_list", "]", ")" ]
show a value assocciated with an attribute for each DataProperty instance in the dp_matrix
[ "show", "a", "value", "assocciated", "with", "an", "attribute", "for", "each", "DataProperty", "instance", "in", "the", "dp_matrix" ]
1d1a4c6abee87264c2f870a932c0194895d80a18
https://github.com/thombashi/DataProperty/blob/1d1a4c6abee87264c2f870a932c0194895d80a18/examples/py/to_dp_matrix.py#L16-L25
train
kamicut/tilepie
tilepie/reader.py
MBTilesReader._query
def _query(self, sql, *args): """ Executes the specified `sql` query and returns the cursor """ if not self._con: logger.debug(("Open MBTiles file '%s'") % self.filename) self._con = sqlite3.connect(self.filename) self._cur = self._con.cursor() sql = ' '.join(sql.split()) logger.debug(("Execute query '%s' %s") % (sql, args)) try: self._cur.execute(sql, *args) except (sqlite3.OperationalError, sqlite3.DatabaseError) as e: raise InvalidFormatError(("%s while reading %s") % (e, self.filename)) return self._cur
python
def _query(self, sql, *args): """ Executes the specified `sql` query and returns the cursor """ if not self._con: logger.debug(("Open MBTiles file '%s'") % self.filename) self._con = sqlite3.connect(self.filename) self._cur = self._con.cursor() sql = ' '.join(sql.split()) logger.debug(("Execute query '%s' %s") % (sql, args)) try: self._cur.execute(sql, *args) except (sqlite3.OperationalError, sqlite3.DatabaseError) as e: raise InvalidFormatError(("%s while reading %s") % (e, self.filename)) return self._cur
[ "def", "_query", "(", "self", ",", "sql", ",", "*", "args", ")", ":", "if", "not", "self", ".", "_con", ":", "logger", ".", "debug", "(", "(", "\"Open MBTiles file '%s'\"", ")", "%", "self", ".", "filename", ")", "self", ".", "_con", "=", "sqlite3", ".", "connect", "(", "self", ".", "filename", ")", "self", ".", "_cur", "=", "self", ".", "_con", ".", "cursor", "(", ")", "sql", "=", "' '", ".", "join", "(", "sql", ".", "split", "(", ")", ")", "logger", ".", "debug", "(", "(", "\"Execute query '%s' %s\"", ")", "%", "(", "sql", ",", "args", ")", ")", "try", ":", "self", ".", "_cur", ".", "execute", "(", "sql", ",", "*", "args", ")", "except", "(", "sqlite3", ".", "OperationalError", ",", "sqlite3", ".", "DatabaseError", ")", "as", "e", ":", "raise", "InvalidFormatError", "(", "(", "\"%s while reading %s\"", ")", "%", "(", "e", ",", "self", ".", "filename", ")", ")", "return", "self", ".", "_cur" ]
Executes the specified `sql` query and returns the cursor
[ "Executes", "the", "specified", "sql", "query", "and", "returns", "the", "cursor" ]
103ae2be1c3c4e6f7ec4a3bdd265ffcddee92b96
https://github.com/kamicut/tilepie/blob/103ae2be1c3c4e6f7ec4a3bdd265ffcddee92b96/tilepie/reader.py#L33-L45
train
cltl/KafNafParserPy
KafNafParserPy/opinion_data.py
Cholder.set_comment
def set_comment(self,c): """ Sets the comment for the element @type c: string @param c: comment for the element """ c = ' '+c.replace('-','').strip()+' ' self.node.insert(0,etree.Comment(c))
python
def set_comment(self,c): """ Sets the comment for the element @type c: string @param c: comment for the element """ c = ' '+c.replace('-','').strip()+' ' self.node.insert(0,etree.Comment(c))
[ "def", "set_comment", "(", "self", ",", "c", ")", ":", "c", "=", "' '", "+", "c", ".", "replace", "(", "'-'", ",", "''", ")", ".", "strip", "(", ")", "+", "' '", "self", ".", "node", ".", "insert", "(", "0", ",", "etree", ".", "Comment", "(", "c", ")", ")" ]
Sets the comment for the element @type c: string @param c: comment for the element
[ "Sets", "the", "comment", "for", "the", "element" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/opinion_data.py#L47-L54
train
cltl/KafNafParserPy
KafNafParserPy/opinion_data.py
Copinion.set_id
def set_id(self,my_id): """ Sets the opinion identifier @type my_id: string @param my_id: the opinion identifier """ if self.type == 'NAF': self.node.set('id',my_id) elif self.type == 'KAF': self.node.set('oid',my_id)
python
def set_id(self,my_id): """ Sets the opinion identifier @type my_id: string @param my_id: the opinion identifier """ if self.type == 'NAF': self.node.set('id',my_id) elif self.type == 'KAF': self.node.set('oid',my_id)
[ "def", "set_id", "(", "self", ",", "my_id", ")", ":", "if", "self", ".", "type", "==", "'NAF'", ":", "self", ".", "node", ".", "set", "(", "'id'", ",", "my_id", ")", "elif", "self", ".", "type", "==", "'KAF'", ":", "self", ".", "node", ".", "set", "(", "'oid'", ",", "my_id", ")" ]
Sets the opinion identifier @type my_id: string @param my_id: the opinion identifier
[ "Sets", "the", "opinion", "identifier" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/opinion_data.py#L325-L334
train
cltl/KafNafParserPy
KafNafParserPy/opinion_data.py
Copinions.to_kaf
def to_kaf(self): """ Converts the opinion layer to KAF """ if self.type == 'NAF': for node in self.__get_opinion_nodes(): node.set('oid',node.get('id')) del node.attrib['id']
python
def to_kaf(self): """ Converts the opinion layer to KAF """ if self.type == 'NAF': for node in self.__get_opinion_nodes(): node.set('oid',node.get('id')) del node.attrib['id']
[ "def", "to_kaf", "(", "self", ")", ":", "if", "self", ".", "type", "==", "'NAF'", ":", "for", "node", "in", "self", ".", "__get_opinion_nodes", "(", ")", ":", "node", ".", "set", "(", "'oid'", ",", "node", ".", "get", "(", "'id'", ")", ")", "del", "node", ".", "attrib", "[", "'id'", "]" ]
Converts the opinion layer to KAF
[ "Converts", "the", "opinion", "layer", "to", "KAF" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/opinion_data.py#L453-L460
train
cltl/KafNafParserPy
KafNafParserPy/opinion_data.py
Copinions.to_naf
def to_naf(self): """ Converts the opinion layer to NAF """ if self.type == 'KAF': for node in self.__get_opinion_nodes(): node.set('id',node.get('oid')) del node.attrib['oid']
python
def to_naf(self): """ Converts the opinion layer to NAF """ if self.type == 'KAF': for node in self.__get_opinion_nodes(): node.set('id',node.get('oid')) del node.attrib['oid']
[ "def", "to_naf", "(", "self", ")", ":", "if", "self", ".", "type", "==", "'KAF'", ":", "for", "node", "in", "self", ".", "__get_opinion_nodes", "(", ")", ":", "node", ".", "set", "(", "'id'", ",", "node", ".", "get", "(", "'oid'", ")", ")", "del", "node", ".", "attrib", "[", "'oid'", "]" ]
Converts the opinion layer to NAF
[ "Converts", "the", "opinion", "layer", "to", "NAF" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/opinion_data.py#L462-L469
train
cltl/KafNafParserPy
KafNafParserPy/opinion_data.py
Copinions.remove_this_opinion
def remove_this_opinion(self,opinion_id): """ Removes the opinion for the given opinion identifier @type opinion_id: string @param opinion_id: the opinion identifier to be removed """ for opi in self.get_opinions(): if opi.get_id() == opinion_id: self.node.remove(opi.get_node()) break
python
def remove_this_opinion(self,opinion_id): """ Removes the opinion for the given opinion identifier @type opinion_id: string @param opinion_id: the opinion identifier to be removed """ for opi in self.get_opinions(): if opi.get_id() == opinion_id: self.node.remove(opi.get_node()) break
[ "def", "remove_this_opinion", "(", "self", ",", "opinion_id", ")", ":", "for", "opi", "in", "self", ".", "get_opinions", "(", ")", ":", "if", "opi", ".", "get_id", "(", ")", "==", "opinion_id", ":", "self", ".", "node", ".", "remove", "(", "opi", ".", "get_node", "(", ")", ")", "break" ]
Removes the opinion for the given opinion identifier @type opinion_id: string @param opinion_id: the opinion identifier to be removed
[ "Removes", "the", "opinion", "for", "the", "given", "opinion", "identifier" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/opinion_data.py#L488-L497
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/account.py
Account.GetAccountDetails
def GetAccountDetails(alias=None): """Return account details dict associated with the provided alias.""" if not alias: alias = Account.GetAlias() r = clc.v1.API.Call('post','Account/GetAccountDetails',{'AccountAlias': alias}) if r['Success'] != True: if clc.args: clc.v1.output.Status('ERROR',3,'Error calling %s. Status code %s. %s' % ('Account/GetAccountDetails',r['StatusCode'],r['Message'])) raise Exception('Error calling %s. Status code %s. %s' % ('Account/GetAccountDetails',r['StatusCode'],r['Message'])) elif int(r['StatusCode']) == 0: r['AccountDetails']['Status'] = Account.account_status_itos[r['AccountDetails']['Status']] return(r['AccountDetails'])
python
def GetAccountDetails(alias=None): """Return account details dict associated with the provided alias.""" if not alias: alias = Account.GetAlias() r = clc.v1.API.Call('post','Account/GetAccountDetails',{'AccountAlias': alias}) if r['Success'] != True: if clc.args: clc.v1.output.Status('ERROR',3,'Error calling %s. Status code %s. %s' % ('Account/GetAccountDetails',r['StatusCode'],r['Message'])) raise Exception('Error calling %s. Status code %s. %s' % ('Account/GetAccountDetails',r['StatusCode'],r['Message'])) elif int(r['StatusCode']) == 0: r['AccountDetails']['Status'] = Account.account_status_itos[r['AccountDetails']['Status']] return(r['AccountDetails'])
[ "def", "GetAccountDetails", "(", "alias", "=", "None", ")", ":", "if", "not", "alias", ":", "alias", "=", "Account", ".", "GetAlias", "(", ")", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Account/GetAccountDetails'", ",", "{", "'AccountAlias'", ":", "alias", "}", ")", "if", "r", "[", "'Success'", "]", "!=", "True", ":", "if", "clc", ".", "args", ":", "clc", ".", "v1", ".", "output", ".", "Status", "(", "'ERROR'", ",", "3", ",", "'Error calling %s. Status code %s. %s'", "%", "(", "'Account/GetAccountDetails'", ",", "r", "[", "'StatusCode'", "]", ",", "r", "[", "'Message'", "]", ")", ")", "raise", "Exception", "(", "'Error calling %s. Status code %s. %s'", "%", "(", "'Account/GetAccountDetails'", ",", "r", "[", "'StatusCode'", "]", ",", "r", "[", "'Message'", "]", ")", ")", "elif", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "r", "[", "'AccountDetails'", "]", "[", "'Status'", "]", "=", "Account", ".", "account_status_itos", "[", "r", "[", "'AccountDetails'", "]", "[", "'Status'", "]", "]", "return", "(", "r", "[", "'AccountDetails'", "]", ")" ]
Return account details dict associated with the provided alias.
[ "Return", "account", "details", "dict", "associated", "with", "the", "provided", "alias", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/account.py#L31-L40
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/account.py
Account.GetAccounts
def GetAccounts(alias=None): """Return account inventory dict containing all subaccounts for the given alias. If None search from default alias.""" if alias is not None: payload = {'AccountAlias': alias} else: payload = {} r = clc.v1.API.Call('post','Account/GetAccounts',payload) if int(r['StatusCode']) == 0: # Assume first response is always the original account. Not sure if this is reliable if not clc.ALIAS: clc.ALIAS = r['Accounts'][0]['AccountAlias'] if not clc.LOCATION: clc.LOCATION = r['Accounts'][0]['Location'] return(r['Accounts'])
python
def GetAccounts(alias=None): """Return account inventory dict containing all subaccounts for the given alias. If None search from default alias.""" if alias is not None: payload = {'AccountAlias': alias} else: payload = {} r = clc.v1.API.Call('post','Account/GetAccounts',payload) if int(r['StatusCode']) == 0: # Assume first response is always the original account. Not sure if this is reliable if not clc.ALIAS: clc.ALIAS = r['Accounts'][0]['AccountAlias'] if not clc.LOCATION: clc.LOCATION = r['Accounts'][0]['Location'] return(r['Accounts'])
[ "def", "GetAccounts", "(", "alias", "=", "None", ")", ":", "if", "alias", "is", "not", "None", ":", "payload", "=", "{", "'AccountAlias'", ":", "alias", "}", "else", ":", "payload", "=", "{", "}", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Account/GetAccounts'", ",", "payload", ")", "if", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "# Assume first response is always the original account. Not sure if this is reliable", "if", "not", "clc", ".", "ALIAS", ":", "clc", ".", "ALIAS", "=", "r", "[", "'Accounts'", "]", "[", "0", "]", "[", "'AccountAlias'", "]", "if", "not", "clc", ".", "LOCATION", ":", "clc", ".", "LOCATION", "=", "r", "[", "'Accounts'", "]", "[", "0", "]", "[", "'Location'", "]", "return", "(", "r", "[", "'Accounts'", "]", ")" ]
Return account inventory dict containing all subaccounts for the given alias. If None search from default alias.
[ "Return", "account", "inventory", "dict", "containing", "all", "subaccounts", "for", "the", "given", "alias", ".", "If", "None", "search", "from", "default", "alias", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/account.py#L56-L66
train
nickpandolfi/Cyther
cyther/project.py
assure_cache
def assure_cache(project_path=None): """ Assure that a project directory has a cache folder. If not, it will create it. """ project_path = path(project_path, ISDIR) cache_path = os.path.join(project_path, CACHE_NAME) if not os.path.isdir(cache_path): os.mkdir(cache_path)
python
def assure_cache(project_path=None): """ Assure that a project directory has a cache folder. If not, it will create it. """ project_path = path(project_path, ISDIR) cache_path = os.path.join(project_path, CACHE_NAME) if not os.path.isdir(cache_path): os.mkdir(cache_path)
[ "def", "assure_cache", "(", "project_path", "=", "None", ")", ":", "project_path", "=", "path", "(", "project_path", ",", "ISDIR", ")", "cache_path", "=", "os", ".", "path", ".", "join", "(", "project_path", ",", "CACHE_NAME", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "cache_path", ")", ":", "os", ".", "mkdir", "(", "cache_path", ")" ]
Assure that a project directory has a cache folder. If not, it will create it.
[ "Assure", "that", "a", "project", "directory", "has", "a", "cache", "folder", ".", "If", "not", "it", "will", "create", "it", "." ]
9fb0bd77af594008aa6ee8af460aa8c953abf5bc
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/project.py#L13-L23
train
nickpandolfi/Cyther
cyther/project.py
purge_project
def purge_project(): """ Purge a directory of anything cyther related """ print('Current Directory: {}'.format(os.getcwd())) directories = os.listdir(os.getcwd()) if CACHE_NAME in directories: response = get_input("Would you like to delete the cache and" "everything in it? [y/n]: ", ('y', 'n')) if response == 'y': print("Listing local '__cythercache__':") cache_dir = os.path.join(os.getcwd(), "__cythercache__") to_delete = [] contents = os.listdir(cache_dir) if contents: for filename in contents: print('\t' + filename) filepath = os.path.join(cache_dir, filename) to_delete.append(filepath) else: print("\tNothing was found in the cache") check_response = get_input("Delete all these files? (^)" "[y/n]: ", ('y', 'n')) if check_response == 'y': for filepath in to_delete: os.remove(filepath) os.rmdir(cache_dir) else: print("Skipping the deletion... all files are fine!") else: print("Skipping deletion of the cache") else: print("Couldn't find a cache file ('{}') in this " "directory".format(CACHE_NAME))
python
def purge_project(): """ Purge a directory of anything cyther related """ print('Current Directory: {}'.format(os.getcwd())) directories = os.listdir(os.getcwd()) if CACHE_NAME in directories: response = get_input("Would you like to delete the cache and" "everything in it? [y/n]: ", ('y', 'n')) if response == 'y': print("Listing local '__cythercache__':") cache_dir = os.path.join(os.getcwd(), "__cythercache__") to_delete = [] contents = os.listdir(cache_dir) if contents: for filename in contents: print('\t' + filename) filepath = os.path.join(cache_dir, filename) to_delete.append(filepath) else: print("\tNothing was found in the cache") check_response = get_input("Delete all these files? (^)" "[y/n]: ", ('y', 'n')) if check_response == 'y': for filepath in to_delete: os.remove(filepath) os.rmdir(cache_dir) else: print("Skipping the deletion... all files are fine!") else: print("Skipping deletion of the cache") else: print("Couldn't find a cache file ('{}') in this " "directory".format(CACHE_NAME))
[ "def", "purge_project", "(", ")", ":", "print", "(", "'Current Directory: {}'", ".", "format", "(", "os", ".", "getcwd", "(", ")", ")", ")", "directories", "=", "os", ".", "listdir", "(", "os", ".", "getcwd", "(", ")", ")", "if", "CACHE_NAME", "in", "directories", ":", "response", "=", "get_input", "(", "\"Would you like to delete the cache and\"", "\"everything in it? [y/n]: \"", ",", "(", "'y'", ",", "'n'", ")", ")", "if", "response", "==", "'y'", ":", "print", "(", "\"Listing local '__cythercache__':\"", ")", "cache_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "\"__cythercache__\"", ")", "to_delete", "=", "[", "]", "contents", "=", "os", ".", "listdir", "(", "cache_dir", ")", "if", "contents", ":", "for", "filename", "in", "contents", ":", "print", "(", "'\\t'", "+", "filename", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "cache_dir", ",", "filename", ")", "to_delete", ".", "append", "(", "filepath", ")", "else", ":", "print", "(", "\"\\tNothing was found in the cache\"", ")", "check_response", "=", "get_input", "(", "\"Delete all these files? (^)\"", "\"[y/n]: \"", ",", "(", "'y'", ",", "'n'", ")", ")", "if", "check_response", "==", "'y'", ":", "for", "filepath", "in", "to_delete", ":", "os", ".", "remove", "(", "filepath", ")", "os", ".", "rmdir", "(", "cache_dir", ")", "else", ":", "print", "(", "\"Skipping the deletion... all files are fine!\"", ")", "else", ":", "print", "(", "\"Skipping deletion of the cache\"", ")", "else", ":", "print", "(", "\"Couldn't find a cache file ('{}') in this \"", "\"directory\"", ".", "format", "(", "CACHE_NAME", ")", ")" ]
Purge a directory of anything cyther related
[ "Purge", "a", "directory", "of", "anything", "cyther", "related" ]
9fb0bd77af594008aa6ee8af460aa8c953abf5bc
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/project.py#L33-L67
train
teepark/greenhouse
greenhouse/pool.py
map
def map(func, items, pool_size=10): """a parallelized work-alike to the built-in ``map`` function this function works by creating an :class:`OrderedPool` and placing all the arguments in :meth:`put<OrderedPool.put>` calls, then yielding items produced by the pool's :meth:`get<OrderedPool.get>` method. :param func: the mapper function to use :type func: function :param items: the items to use as the mapper's arguments :type items: iterable :param pool_size: the number of workers for the pool -- this amounts to the concurrency with which the map is accomplished (default 10) :type pool_size: int :returns: a lazy iterator (like python3's map or python2's itertools.imap) over the results of the mapping """ with OrderedPool(func, pool_size) as pool: for count, item in enumerate(items): pool.put(item) for i in xrange(count + 1): yield pool.get()
python
def map(func, items, pool_size=10): """a parallelized work-alike to the built-in ``map`` function this function works by creating an :class:`OrderedPool` and placing all the arguments in :meth:`put<OrderedPool.put>` calls, then yielding items produced by the pool's :meth:`get<OrderedPool.get>` method. :param func: the mapper function to use :type func: function :param items: the items to use as the mapper's arguments :type items: iterable :param pool_size: the number of workers for the pool -- this amounts to the concurrency with which the map is accomplished (default 10) :type pool_size: int :returns: a lazy iterator (like python3's map or python2's itertools.imap) over the results of the mapping """ with OrderedPool(func, pool_size) as pool: for count, item in enumerate(items): pool.put(item) for i in xrange(count + 1): yield pool.get()
[ "def", "map", "(", "func", ",", "items", ",", "pool_size", "=", "10", ")", ":", "with", "OrderedPool", "(", "func", ",", "pool_size", ")", "as", "pool", ":", "for", "count", ",", "item", "in", "enumerate", "(", "items", ")", ":", "pool", ".", "put", "(", "item", ")", "for", "i", "in", "xrange", "(", "count", "+", "1", ")", ":", "yield", "pool", ".", "get", "(", ")" ]
a parallelized work-alike to the built-in ``map`` function this function works by creating an :class:`OrderedPool` and placing all the arguments in :meth:`put<OrderedPool.put>` calls, then yielding items produced by the pool's :meth:`get<OrderedPool.get>` method. :param func: the mapper function to use :type func: function :param items: the items to use as the mapper's arguments :type items: iterable :param pool_size: the number of workers for the pool -- this amounts to the concurrency with which the map is accomplished (default 10) :type pool_size: int :returns: a lazy iterator (like python3's map or python2's itertools.imap) over the results of the mapping
[ "a", "parallelized", "work", "-", "alike", "to", "the", "built", "-", "in", "map", "function" ]
8fd1be4f5443ba090346b5ec82fdbeb0a060d956
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/pool.py#L255-L280
train
teepark/greenhouse
greenhouse/pool.py
OneWayPool.start
def start(self): "start the pool's workers" for i in xrange(self.size): scheduler.schedule(self._runner) self._closing = False
python
def start(self): "start the pool's workers" for i in xrange(self.size): scheduler.schedule(self._runner) self._closing = False
[ "def", "start", "(", "self", ")", ":", "for", "i", "in", "xrange", "(", "self", ".", "size", ")", ":", "scheduler", ".", "schedule", "(", "self", ".", "_runner", ")", "self", ".", "_closing", "=", "False" ]
start the pool's workers
[ "start", "the", "pool", "s", "workers" ]
8fd1be4f5443ba090346b5ec82fdbeb0a060d956
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/pool.py#L36-L40
train
teepark/greenhouse
greenhouse/pool.py
OrderedPool.put
def put(self, *args, **kwargs): """place a new item into the pool to be handled by the workers all positional and keyword arguments will be passed in as the arguments to the function run by the pool's workers """ self.inq.put((self._putcount, (args, kwargs))) self._putcount += 1
python
def put(self, *args, **kwargs): """place a new item into the pool to be handled by the workers all positional and keyword arguments will be passed in as the arguments to the function run by the pool's workers """ self.inq.put((self._putcount, (args, kwargs))) self._putcount += 1
[ "def", "put", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "inq", ".", "put", "(", "(", "self", ".", "_putcount", ",", "(", "args", ",", "kwargs", ")", ")", ")", "self", ".", "_putcount", "+=", "1" ]
place a new item into the pool to be handled by the workers all positional and keyword arguments will be passed in as the arguments to the function run by the pool's workers
[ "place", "a", "new", "item", "into", "the", "pool", "to", "be", "handled", "by", "the", "workers" ]
8fd1be4f5443ba090346b5ec82fdbeb0a060d956
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/pool.py#L207-L214
train
cltl/KafNafParserPy
KafNafParserPy/entity_data.py
Centities.get_entity
def get_entity(self,entity_id): """ Returns the entity object for the given entity identifier @type entity_id: string @param entity_id: the token identifier @rtype: L{Centity} @return: the entity object """ entity_node = self.map_entity_id_to_node.get(entity_id) if entity_node is not None: return Centity(node=entity_node,type=self.type) else: for entity_node in self.__get_entity_nodes(): if self.type == 'NAF': label_id = 'id' elif self.type == 'KAF': label_id = 'eid' if entity_node.get(label_id) == entity_id: return Centity(node=entity_node, type=self.type) return None
python
def get_entity(self,entity_id): """ Returns the entity object for the given entity identifier @type entity_id: string @param entity_id: the token identifier @rtype: L{Centity} @return: the entity object """ entity_node = self.map_entity_id_to_node.get(entity_id) if entity_node is not None: return Centity(node=entity_node,type=self.type) else: for entity_node in self.__get_entity_nodes(): if self.type == 'NAF': label_id = 'id' elif self.type == 'KAF': label_id = 'eid' if entity_node.get(label_id) == entity_id: return Centity(node=entity_node, type=self.type) return None
[ "def", "get_entity", "(", "self", ",", "entity_id", ")", ":", "entity_node", "=", "self", ".", "map_entity_id_to_node", ".", "get", "(", "entity_id", ")", "if", "entity_node", "is", "not", "None", ":", "return", "Centity", "(", "node", "=", "entity_node", ",", "type", "=", "self", ".", "type", ")", "else", ":", "for", "entity_node", "in", "self", ".", "__get_entity_nodes", "(", ")", ":", "if", "self", ".", "type", "==", "'NAF'", ":", "label_id", "=", "'id'", "elif", "self", ".", "type", "==", "'KAF'", ":", "label_id", "=", "'eid'", "if", "entity_node", ".", "get", "(", "label_id", ")", "==", "entity_id", ":", "return", "Centity", "(", "node", "=", "entity_node", ",", "type", "=", "self", ".", "type", ")", "return", "None" ]
Returns the entity object for the given entity identifier @type entity_id: string @param entity_id: the token identifier @rtype: L{Centity} @return: the entity object
[ "Returns", "the", "entity", "object", "for", "the", "given", "entity", "identifier" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/entity_data.py#L181-L200
train
cltl/KafNafParserPy
KafNafParserPy/entity_data.py
Centities.add_external_reference_to_entity
def add_external_reference_to_entity(self,entity_id,ext_ref): """ Adds an external reference to a entity specified by the entity identifier @param entity_id: the entity identifier @type entity_id: string @param ext_ref: the external reference @type ext_ref: L{CexternalReference} """ node_entity = self.map_entity_id_to_node.get(entity_id) if node_entity is not None: entity = Centity(node_entity,self.type) entity.add_external_reference(ext_ref) else: print>>sys.stderr,'Trying to add a reference to the entity',entity_id,'but can not be found in this file'
python
def add_external_reference_to_entity(self,entity_id,ext_ref): """ Adds an external reference to a entity specified by the entity identifier @param entity_id: the entity identifier @type entity_id: string @param ext_ref: the external reference @type ext_ref: L{CexternalReference} """ node_entity = self.map_entity_id_to_node.get(entity_id) if node_entity is not None: entity = Centity(node_entity,self.type) entity.add_external_reference(ext_ref) else: print>>sys.stderr,'Trying to add a reference to the entity',entity_id,'but can not be found in this file'
[ "def", "add_external_reference_to_entity", "(", "self", ",", "entity_id", ",", "ext_ref", ")", ":", "node_entity", "=", "self", ".", "map_entity_id_to_node", ".", "get", "(", "entity_id", ")", "if", "node_entity", "is", "not", "None", ":", "entity", "=", "Centity", "(", "node_entity", ",", "self", ".", "type", ")", "entity", ".", "add_external_reference", "(", "ext_ref", ")", "else", ":", "print", ">>", "sys", ".", "stderr", ",", "'Trying to add a reference to the entity'", ",", "entity_id", ",", "'but can not be found in this file'" ]
Adds an external reference to a entity specified by the entity identifier @param entity_id: the entity identifier @type entity_id: string @param ext_ref: the external reference @type ext_ref: L{CexternalReference}
[ "Adds", "an", "external", "reference", "to", "a", "entity", "specified", "by", "the", "entity", "identifier" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/entity_data.py#L202-L215
train
cltl/KafNafParserPy
KafNafParserPy/entity_data.py
Centities.to_kaf
def to_kaf(self): """ Converts the layer from KAF to NAF """ if self.type == 'NAF': for node in self.__get_entity_nodes(): node.set('eid',node.get('id')) del node.attrib['id']
python
def to_kaf(self): """ Converts the layer from KAF to NAF """ if self.type == 'NAF': for node in self.__get_entity_nodes(): node.set('eid',node.get('id')) del node.attrib['id']
[ "def", "to_kaf", "(", "self", ")", ":", "if", "self", ".", "type", "==", "'NAF'", ":", "for", "node", "in", "self", ".", "__get_entity_nodes", "(", ")", ":", "node", ".", "set", "(", "'eid'", ",", "node", ".", "get", "(", "'id'", ")", ")", "del", "node", ".", "attrib", "[", "'id'", "]" ]
Converts the layer from KAF to NAF
[ "Converts", "the", "layer", "from", "KAF", "to", "NAF" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/entity_data.py#L226-L233
train
cltl/KafNafParserPy
KafNafParserPy/entity_data.py
Centities.to_naf
def to_naf(self): """ Converts the layer from NAF to KAF """ if self.type == 'KAF': for node in self.__get_entity_nodes(): node.set('id',node.get('eid')) del node.attrib['eid']
python
def to_naf(self): """ Converts the layer from NAF to KAF """ if self.type == 'KAF': for node in self.__get_entity_nodes(): node.set('id',node.get('eid')) del node.attrib['eid']
[ "def", "to_naf", "(", "self", ")", ":", "if", "self", ".", "type", "==", "'KAF'", ":", "for", "node", "in", "self", ".", "__get_entity_nodes", "(", ")", ":", "node", ".", "set", "(", "'id'", ",", "node", ".", "get", "(", "'eid'", ")", ")", "del", "node", ".", "attrib", "[", "'eid'", "]" ]
Converts the layer from NAF to KAF
[ "Converts", "the", "layer", "from", "NAF", "to", "KAF" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/entity_data.py#L235-L242
train
mjirik/imtools
imtools/uiThreshold.py
uiThreshold.updateImage
def updateImage(self, val): """ Hlavni update metoda. Cinny kod pro gaussovske filtrovani, prahovani, binarni uzavreni a otevreni a vraceni nejvetsich nebo oznacenych objektu. """ # import ipdb # ipdb.set_trace() # Filtrovani # Zjisteni jakou sigmu pouzit if(self.firstRun == True and self.inputSigma >= 0): sigma = np.round(self.inputSigma, 2) elif self.interactivity: sigma = np.round(self.ssigma.val, 2) else: sigma = np.round(self.inputSigma, 2) # Prahovani (smin, smax) # max_threshold = self.threshold_upper # min_threshold = self.threshold if self.interactivity: self.smin.val = (np.round(self.smin.val, 2)) self.smin.valtext.set_text('{}'.format(self.smin.val)) self.smax.val = (np.round(self.smax.val, 2)) self.smax.valtext.set_text('{}'.format(self.smax.val)) self.threshold = self.smin.val self.threshold_upper = self.smax.val closeNum = int(np.round(self.sclose.val, 0)) openNum = int(np.round(self.sopen.val, 0)) self.sclose.valtext.set_text('{}'.format(closeNum)) self.sopen.valtext.set_text('{}'.format(openNum)) else: closeNum = self.ICBinaryClosingIterations openNum = self.ICBinaryOpeningIterations # make_image_processing(sigma, min_threshold, max_threshold, closeNum, openNum, auto_method=self.) self.imgFiltering, self.threshold = make_image_processing(data=self.data, voxelsize_mm=self.voxelsize_mm, seeds=self.seeds, sigma_mm=sigma, min_threshold=self.threshold, max_threshold=self.threshold_upper, closeNum=closeNum, openNum=openNum, min_threshold_auto_method=self.auto_method, fill_holes=self.fillHoles, get_priority_objects=self.get_priority_objects, nObj=self.nObj) # Vykresleni dat if (self.interactivity == True): self.drawVisualization() # Nastaveni kontrolnich hodnot self.firstRun = False garbage.collect() self.debugInfo()
python
def updateImage(self, val): """ Hlavni update metoda. Cinny kod pro gaussovske filtrovani, prahovani, binarni uzavreni a otevreni a vraceni nejvetsich nebo oznacenych objektu. """ # import ipdb # ipdb.set_trace() # Filtrovani # Zjisteni jakou sigmu pouzit if(self.firstRun == True and self.inputSigma >= 0): sigma = np.round(self.inputSigma, 2) elif self.interactivity: sigma = np.round(self.ssigma.val, 2) else: sigma = np.round(self.inputSigma, 2) # Prahovani (smin, smax) # max_threshold = self.threshold_upper # min_threshold = self.threshold if self.interactivity: self.smin.val = (np.round(self.smin.val, 2)) self.smin.valtext.set_text('{}'.format(self.smin.val)) self.smax.val = (np.round(self.smax.val, 2)) self.smax.valtext.set_text('{}'.format(self.smax.val)) self.threshold = self.smin.val self.threshold_upper = self.smax.val closeNum = int(np.round(self.sclose.val, 0)) openNum = int(np.round(self.sopen.val, 0)) self.sclose.valtext.set_text('{}'.format(closeNum)) self.sopen.valtext.set_text('{}'.format(openNum)) else: closeNum = self.ICBinaryClosingIterations openNum = self.ICBinaryOpeningIterations # make_image_processing(sigma, min_threshold, max_threshold, closeNum, openNum, auto_method=self.) self.imgFiltering, self.threshold = make_image_processing(data=self.data, voxelsize_mm=self.voxelsize_mm, seeds=self.seeds, sigma_mm=sigma, min_threshold=self.threshold, max_threshold=self.threshold_upper, closeNum=closeNum, openNum=openNum, min_threshold_auto_method=self.auto_method, fill_holes=self.fillHoles, get_priority_objects=self.get_priority_objects, nObj=self.nObj) # Vykresleni dat if (self.interactivity == True): self.drawVisualization() # Nastaveni kontrolnich hodnot self.firstRun = False garbage.collect() self.debugInfo()
[ "def", "updateImage", "(", "self", ",", "val", ")", ":", "# import ipdb", "# ipdb.set_trace()", "# Filtrovani", "# Zjisteni jakou sigmu pouzit", "if", "(", "self", ".", "firstRun", "==", "True", "and", "self", ".", "inputSigma", ">=", "0", ")", ":", "sigma", "=", "np", ".", "round", "(", "self", ".", "inputSigma", ",", "2", ")", "elif", "self", ".", "interactivity", ":", "sigma", "=", "np", ".", "round", "(", "self", ".", "ssigma", ".", "val", ",", "2", ")", "else", ":", "sigma", "=", "np", ".", "round", "(", "self", ".", "inputSigma", ",", "2", ")", "# Prahovani (smin, smax)", "# max_threshold = self.threshold_upper", "# min_threshold = self.threshold", "if", "self", ".", "interactivity", ":", "self", ".", "smin", ".", "val", "=", "(", "np", ".", "round", "(", "self", ".", "smin", ".", "val", ",", "2", ")", ")", "self", ".", "smin", ".", "valtext", ".", "set_text", "(", "'{}'", ".", "format", "(", "self", ".", "smin", ".", "val", ")", ")", "self", ".", "smax", ".", "val", "=", "(", "np", ".", "round", "(", "self", ".", "smax", ".", "val", ",", "2", ")", ")", "self", ".", "smax", ".", "valtext", ".", "set_text", "(", "'{}'", ".", "format", "(", "self", ".", "smax", ".", "val", ")", ")", "self", ".", "threshold", "=", "self", ".", "smin", ".", "val", "self", ".", "threshold_upper", "=", "self", ".", "smax", ".", "val", "closeNum", "=", "int", "(", "np", ".", "round", "(", "self", ".", "sclose", ".", "val", ",", "0", ")", ")", "openNum", "=", "int", "(", "np", ".", "round", "(", "self", ".", "sopen", ".", "val", ",", "0", ")", ")", "self", ".", "sclose", ".", "valtext", ".", "set_text", "(", "'{}'", ".", "format", "(", "closeNum", ")", ")", "self", ".", "sopen", ".", "valtext", ".", "set_text", "(", "'{}'", ".", "format", "(", "openNum", ")", ")", "else", ":", "closeNum", "=", "self", ".", "ICBinaryClosingIterations", "openNum", "=", "self", ".", "ICBinaryOpeningIterations", "# make_image_processing(sigma, min_threshold, max_threshold, closeNum, openNum, auto_method=self.)", "self", ".", "imgFiltering", ",", "self", ".", "threshold", "=", "make_image_processing", "(", "data", "=", "self", ".", "data", ",", "voxelsize_mm", "=", "self", ".", "voxelsize_mm", ",", "seeds", "=", "self", ".", "seeds", ",", "sigma_mm", "=", "sigma", ",", "min_threshold", "=", "self", ".", "threshold", ",", "max_threshold", "=", "self", ".", "threshold_upper", ",", "closeNum", "=", "closeNum", ",", "openNum", "=", "openNum", ",", "min_threshold_auto_method", "=", "self", ".", "auto_method", ",", "fill_holes", "=", "self", ".", "fillHoles", ",", "get_priority_objects", "=", "self", ".", "get_priority_objects", ",", "nObj", "=", "self", ".", "nObj", ")", "# Vykresleni dat", "if", "(", "self", ".", "interactivity", "==", "True", ")", ":", "self", ".", "drawVisualization", "(", ")", "# Nastaveni kontrolnich hodnot", "self", ".", "firstRun", "=", "False", "garbage", ".", "collect", "(", ")", "self", ".", "debugInfo", "(", ")" ]
Hlavni update metoda. Cinny kod pro gaussovske filtrovani, prahovani, binarni uzavreni a otevreni a vraceni nejvetsich nebo oznacenych objektu.
[ "Hlavni", "update", "metoda", ".", "Cinny", "kod", "pro", "gaussovske", "filtrovani", "prahovani", "binarni", "uzavreni", "a", "otevreni", "a", "vraceni", "nejvetsich", "nebo", "oznacenych", "objektu", "." ]
eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/uiThreshold.py#L413-L479
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/anti_affinity.py
AntiAffinity.GetAll
def GetAll(alias=None,location=None,session=None): """Gets a list of anti-affinity policies within a given account. https://t3n.zendesk.com/entries/44657214-Get-Anti-Affinity-Policies >>> clc.v2.AntiAffinity.GetAll() [<clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65e910>, <clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65ec90>] """ if not alias: alias = clc.v2.Account.GetAlias(session=session) policies = [] policy_resp = clc.v2.API.Call('GET','antiAffinityPolicies/%s' % alias,{},session=session) for k in policy_resp: r_val = policy_resp[k] for r in r_val: if r.get('location'): if location and r['location'].lower()!=location.lower(): continue servers = [obj['id'] for obj in r['links'] if obj['rel'] == "server"] policies.append(AntiAffinity(id=r['id'],name=r['name'],location=r['location'],servers=servers,session=session)) return(policies)
python
def GetAll(alias=None,location=None,session=None): """Gets a list of anti-affinity policies within a given account. https://t3n.zendesk.com/entries/44657214-Get-Anti-Affinity-Policies >>> clc.v2.AntiAffinity.GetAll() [<clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65e910>, <clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65ec90>] """ if not alias: alias = clc.v2.Account.GetAlias(session=session) policies = [] policy_resp = clc.v2.API.Call('GET','antiAffinityPolicies/%s' % alias,{},session=session) for k in policy_resp: r_val = policy_resp[k] for r in r_val: if r.get('location'): if location and r['location'].lower()!=location.lower(): continue servers = [obj['id'] for obj in r['links'] if obj['rel'] == "server"] policies.append(AntiAffinity(id=r['id'],name=r['name'],location=r['location'],servers=servers,session=session)) return(policies)
[ "def", "GetAll", "(", "alias", "=", "None", ",", "location", "=", "None", ",", "session", "=", "None", ")", ":", "if", "not", "alias", ":", "alias", "=", "clc", ".", "v2", ".", "Account", ".", "GetAlias", "(", "session", "=", "session", ")", "policies", "=", "[", "]", "policy_resp", "=", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'GET'", ",", "'antiAffinityPolicies/%s'", "%", "alias", ",", "{", "}", ",", "session", "=", "session", ")", "for", "k", "in", "policy_resp", ":", "r_val", "=", "policy_resp", "[", "k", "]", "for", "r", "in", "r_val", ":", "if", "r", ".", "get", "(", "'location'", ")", ":", "if", "location", "and", "r", "[", "'location'", "]", ".", "lower", "(", ")", "!=", "location", ".", "lower", "(", ")", ":", "continue", "servers", "=", "[", "obj", "[", "'id'", "]", "for", "obj", "in", "r", "[", "'links'", "]", "if", "obj", "[", "'rel'", "]", "==", "\"server\"", "]", "policies", ".", "append", "(", "AntiAffinity", "(", "id", "=", "r", "[", "'id'", "]", ",", "name", "=", "r", "[", "'name'", "]", ",", "location", "=", "r", "[", "'location'", "]", ",", "servers", "=", "servers", ",", "session", "=", "session", ")", ")", "return", "(", "policies", ")" ]
Gets a list of anti-affinity policies within a given account. https://t3n.zendesk.com/entries/44657214-Get-Anti-Affinity-Policies >>> clc.v2.AntiAffinity.GetAll() [<clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65e910>, <clc.APIv2.anti_affinity.AntiAffinity object at 0x10c65ec90>]
[ "Gets", "a", "list", "of", "anti", "-", "affinity", "policies", "within", "a", "given", "account", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/anti_affinity.py#L28-L49
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/anti_affinity.py
AntiAffinity.GetLocation
def GetLocation(location=None,alias=None,session=None): """Returns a list of anti-affinity policies within a specific location. >>> clc.v2.AntiAffinity.GetLocation("VA1") [<clc.APIv2.anti_affinity.AntiAffinity object at 0x105eeded0>] """ if not location: location = clc.v2.Account.GetLocation(session=session) return(AntiAffinity.GetAll(alias=alias,location=location,session=session))
python
def GetLocation(location=None,alias=None,session=None): """Returns a list of anti-affinity policies within a specific location. >>> clc.v2.AntiAffinity.GetLocation("VA1") [<clc.APIv2.anti_affinity.AntiAffinity object at 0x105eeded0>] """ if not location: location = clc.v2.Account.GetLocation(session=session) return(AntiAffinity.GetAll(alias=alias,location=location,session=session))
[ "def", "GetLocation", "(", "location", "=", "None", ",", "alias", "=", "None", ",", "session", "=", "None", ")", ":", "if", "not", "location", ":", "location", "=", "clc", ".", "v2", ".", "Account", ".", "GetLocation", "(", "session", "=", "session", ")", "return", "(", "AntiAffinity", ".", "GetAll", "(", "alias", "=", "alias", ",", "location", "=", "location", ",", "session", "=", "session", ")", ")" ]
Returns a list of anti-affinity policies within a specific location. >>> clc.v2.AntiAffinity.GetLocation("VA1") [<clc.APIv2.anti_affinity.AntiAffinity object at 0x105eeded0>]
[ "Returns", "a", "list", "of", "anti", "-", "affinity", "policies", "within", "a", "specific", "location", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/anti_affinity.py#L53-L62
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/anti_affinity.py
AntiAffinity.Create
def Create(name,alias=None,location=None,session=None): """Creates a new anti-affinity policy within a given account. https://t3n.zendesk.com/entries/45042770-Create-Anti-Affinity-Policy *TODO* Currently returning 400 error: clc.APIFailedResponse: Response code 400. . POST https://api.tier3.com/v2/antiAffinityPolicies/BTDI """ if not alias: alias = clc.v2.Account.GetAlias(session=session) if not location: location = clc.v2.Account.GetLocation(session=session) r = clc.v2.API.Call('POST','antiAffinityPolicies/%s' % alias, json.dumps({'name': name, 'location': location}), session=session) return(AntiAffinity(id=r['id'],name=r['name'],location=r['location'],servers=[],session=session))
python
def Create(name,alias=None,location=None,session=None): """Creates a new anti-affinity policy within a given account. https://t3n.zendesk.com/entries/45042770-Create-Anti-Affinity-Policy *TODO* Currently returning 400 error: clc.APIFailedResponse: Response code 400. . POST https://api.tier3.com/v2/antiAffinityPolicies/BTDI """ if not alias: alias = clc.v2.Account.GetAlias(session=session) if not location: location = clc.v2.Account.GetLocation(session=session) r = clc.v2.API.Call('POST','antiAffinityPolicies/%s' % alias, json.dumps({'name': name, 'location': location}), session=session) return(AntiAffinity(id=r['id'],name=r['name'],location=r['location'],servers=[],session=session))
[ "def", "Create", "(", "name", ",", "alias", "=", "None", ",", "location", "=", "None", ",", "session", "=", "None", ")", ":", "if", "not", "alias", ":", "alias", "=", "clc", ".", "v2", ".", "Account", ".", "GetAlias", "(", "session", "=", "session", ")", "if", "not", "location", ":", "location", "=", "clc", ".", "v2", ".", "Account", ".", "GetLocation", "(", "session", "=", "session", ")", "r", "=", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'POST'", ",", "'antiAffinityPolicies/%s'", "%", "alias", ",", "json", ".", "dumps", "(", "{", "'name'", ":", "name", ",", "'location'", ":", "location", "}", ")", ",", "session", "=", "session", ")", "return", "(", "AntiAffinity", "(", "id", "=", "r", "[", "'id'", "]", ",", "name", "=", "r", "[", "'name'", "]", ",", "location", "=", "r", "[", "'location'", "]", ",", "servers", "=", "[", "]", ",", "session", "=", "session", ")", ")" ]
Creates a new anti-affinity policy within a given account. https://t3n.zendesk.com/entries/45042770-Create-Anti-Affinity-Policy *TODO* Currently returning 400 error: clc.APIFailedResponse: Response code 400. . POST https://api.tier3.com/v2/antiAffinityPolicies/BTDI
[ "Creates", "a", "new", "anti", "-", "affinity", "policy", "within", "a", "given", "account", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/anti_affinity.py#L66-L82
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/anti_affinity.py
AntiAffinity.Update
def Update(self,name): """Change the policy's name. https://t3n.zendesk.com/entries/45066480-Update-Anti-Affinity-Policy *TODO* - currently returning 500 error """ r = clc.v2.API.Call('PUT','antiAffinityPolicies/%s/%s' % (self.alias,self.id),{'name': name},session=self.session) self.name = name
python
def Update(self,name): """Change the policy's name. https://t3n.zendesk.com/entries/45066480-Update-Anti-Affinity-Policy *TODO* - currently returning 500 error """ r = clc.v2.API.Call('PUT','antiAffinityPolicies/%s/%s' % (self.alias,self.id),{'name': name},session=self.session) self.name = name
[ "def", "Update", "(", "self", ",", "name", ")", ":", "r", "=", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'PUT'", ",", "'antiAffinityPolicies/%s/%s'", "%", "(", "self", ".", "alias", ",", "self", ".", "id", ")", ",", "{", "'name'", ":", "name", "}", ",", "session", "=", "self", ".", "session", ")", "self", ".", "name", "=", "name" ]
Change the policy's name. https://t3n.zendesk.com/entries/45066480-Update-Anti-Affinity-Policy *TODO* - currently returning 500 error
[ "Change", "the", "policy", "s", "name", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/anti_affinity.py#L115-L125
train
polysquare/cmake-ast
cmakeast/ast_visitor.py
_node
def _node(handler, single=None, multi=None): """Return an _AbstractSyntaxTreeNode with some elements defaulted.""" return _AbstractSyntaxTreeNode(handler=handler, single=(single if single else []), multi=(multi if multi else []))
python
def _node(handler, single=None, multi=None): """Return an _AbstractSyntaxTreeNode with some elements defaulted.""" return _AbstractSyntaxTreeNode(handler=handler, single=(single if single else []), multi=(multi if multi else []))
[ "def", "_node", "(", "handler", ",", "single", "=", "None", ",", "multi", "=", "None", ")", ":", "return", "_AbstractSyntaxTreeNode", "(", "handler", "=", "handler", ",", "single", "=", "(", "single", "if", "single", "else", "[", "]", ")", ",", "multi", "=", "(", "multi", "if", "multi", "else", "[", "]", ")", ")" ]
Return an _AbstractSyntaxTreeNode with some elements defaulted.
[ "Return", "an", "_AbstractSyntaxTreeNode", "with", "some", "elements", "defaulted", "." ]
431a32d595d76f1f8f993eb6ddcc79effbadff9d
https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast_visitor.py#L14-L18
train
polysquare/cmake-ast
cmakeast/ast_visitor.py
_recurse
def _recurse(node, *args, **kwargs): """Recursive print worker - recurses the AST and prints each node.""" node_name = node.__class__.__name__ try: info_for_node = _NODE_INFO_TABLE[node_name] except KeyError: return action = kwargs[info_for_node.handler] depth = kwargs["depth"] # Invoke action if available if action is not None: action(node_name, node, depth) # Recurse recurse_kwargs = kwargs kwargs["depth"] = depth + 1 for single in info_for_node.single: _recurse(getattr(node, single), *args, **recurse_kwargs) for multi in info_for_node.multi: for statement in getattr(node, multi): _recurse(statement, *args, **recurse_kwargs)
python
def _recurse(node, *args, **kwargs): """Recursive print worker - recurses the AST and prints each node.""" node_name = node.__class__.__name__ try: info_for_node = _NODE_INFO_TABLE[node_name] except KeyError: return action = kwargs[info_for_node.handler] depth = kwargs["depth"] # Invoke action if available if action is not None: action(node_name, node, depth) # Recurse recurse_kwargs = kwargs kwargs["depth"] = depth + 1 for single in info_for_node.single: _recurse(getattr(node, single), *args, **recurse_kwargs) for multi in info_for_node.multi: for statement in getattr(node, multi): _recurse(statement, *args, **recurse_kwargs)
[ "def", "_recurse", "(", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "node_name", "=", "node", ".", "__class__", ".", "__name__", "try", ":", "info_for_node", "=", "_NODE_INFO_TABLE", "[", "node_name", "]", "except", "KeyError", ":", "return", "action", "=", "kwargs", "[", "info_for_node", ".", "handler", "]", "depth", "=", "kwargs", "[", "\"depth\"", "]", "# Invoke action if available", "if", "action", "is", "not", "None", ":", "action", "(", "node_name", ",", "node", ",", "depth", ")", "# Recurse", "recurse_kwargs", "=", "kwargs", "kwargs", "[", "\"depth\"", "]", "=", "depth", "+", "1", "for", "single", "in", "info_for_node", ".", "single", ":", "_recurse", "(", "getattr", "(", "node", ",", "single", ")", ",", "*", "args", ",", "*", "*", "recurse_kwargs", ")", "for", "multi", "in", "info_for_node", ".", "multi", ":", "for", "statement", "in", "getattr", "(", "node", ",", "multi", ")", ":", "_recurse", "(", "statement", ",", "*", "args", ",", "*", "*", "recurse_kwargs", ")" ]
Recursive print worker - recurses the AST and prints each node.
[ "Recursive", "print", "worker", "-", "recurses", "the", "AST", "and", "prints", "each", "node", "." ]
431a32d595d76f1f8f993eb6ddcc79effbadff9d
https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast_visitor.py#L43-L71
train
polysquare/cmake-ast
cmakeast/ast_visitor.py
recurse
def recurse(node, *args, **kwargs): """Entry point for AST recursion.""" # Construct a default table of actions, using action from kwargs # if it is available. These are forwarded to _recurse. fwd = dict() for node_info in _NODE_INFO_TABLE.values(): fwd[node_info.handler] = kwargs.get(node_info.handler, None) fwd["depth"] = 0 _recurse(node, *args, **fwd)
python
def recurse(node, *args, **kwargs): """Entry point for AST recursion.""" # Construct a default table of actions, using action from kwargs # if it is available. These are forwarded to _recurse. fwd = dict() for node_info in _NODE_INFO_TABLE.values(): fwd[node_info.handler] = kwargs.get(node_info.handler, None) fwd["depth"] = 0 _recurse(node, *args, **fwd)
[ "def", "recurse", "(", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Construct a default table of actions, using action from kwargs", "# if it is available. These are forwarded to _recurse.", "fwd", "=", "dict", "(", ")", "for", "node_info", "in", "_NODE_INFO_TABLE", ".", "values", "(", ")", ":", "fwd", "[", "node_info", ".", "handler", "]", "=", "kwargs", ".", "get", "(", "node_info", ".", "handler", ",", "None", ")", "fwd", "[", "\"depth\"", "]", "=", "0", "_recurse", "(", "node", ",", "*", "args", ",", "*", "*", "fwd", ")" ]
Entry point for AST recursion.
[ "Entry", "point", "for", "AST", "recursion", "." ]
431a32d595d76f1f8f993eb6ddcc79effbadff9d
https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast_visitor.py#L74-L83
train
mjirik/imtools
imtools/show_segmentation_qt.py
ShowSegmentationWidget.get_filename_filled_with_checked_labels
def get_filename_filled_with_checked_labels(self, labels=None): """ Fill used labels into filename """ if labels is None: labels = self.slab_wg.action_check_slab_ui() string_labels = imma.get_nlabels(slab=self.slab_wg.slab, labels=labels, return_mode="str") filename = self.vtk_file.format( "-".join(string_labels)) return filename
python
def get_filename_filled_with_checked_labels(self, labels=None): """ Fill used labels into filename """ if labels is None: labels = self.slab_wg.action_check_slab_ui() string_labels = imma.get_nlabels(slab=self.slab_wg.slab, labels=labels, return_mode="str") filename = self.vtk_file.format( "-".join(string_labels)) return filename
[ "def", "get_filename_filled_with_checked_labels", "(", "self", ",", "labels", "=", "None", ")", ":", "if", "labels", "is", "None", ":", "labels", "=", "self", ".", "slab_wg", ".", "action_check_slab_ui", "(", ")", "string_labels", "=", "imma", ".", "get_nlabels", "(", "slab", "=", "self", ".", "slab_wg", ".", "slab", ",", "labels", "=", "labels", ",", "return_mode", "=", "\"str\"", ")", "filename", "=", "self", ".", "vtk_file", ".", "format", "(", "\"-\"", ".", "join", "(", "string_labels", ")", ")", "return", "filename" ]
Fill used labels into filename
[ "Fill", "used", "labels", "into", "filename" ]
eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/show_segmentation_qt.py#L322-L329
train
teepark/greenhouse
greenhouse/emulation/__init__.py
patched
def patched(module_name): """import and return a named module with patches applied locally only this function returns a module after importing it in such as way that it will operate cooperatively, but not overriding the module globally. >>> green_httplib = patched("httplib") >>> # using green_httplib will only block greenlets >>> import httplib >>> # using httplib will block threads/processes >>> # both can exist simultaneously :param module_name: the module's name that is to be imported. this can be a dot-delimited name, in which case the module at the end of the path is the one that will be returned :type module_name: str :returns: the module indicated by module_name, imported so that it will not block globally, but also not touching existing global modules """ if module_name in _patchers: return _patched_copy(module_name, _patchers[module_name]) # grab the unpatched version of the module for posterity old_module = sys.modules.pop(module_name, None) # apply all the standard library patches we have saved = [(module_name, old_module)] for name, patch in _patchers.iteritems(): new_mod = _patched_copy(name, patch) saved.append((name, sys.modules.pop(name))) sys.modules[name] = new_mod try: # import the requested module with patches in place result = __import__(module_name, {}, {}, module_name.rsplit(".", 1)[0]) finally: # put all the original modules back as they were for name, old_mod in saved: if old_mod is None: sys.modules.pop(name, None) else: sys.modules[name] = old_mod return result
python
def patched(module_name): """import and return a named module with patches applied locally only this function returns a module after importing it in such as way that it will operate cooperatively, but not overriding the module globally. >>> green_httplib = patched("httplib") >>> # using green_httplib will only block greenlets >>> import httplib >>> # using httplib will block threads/processes >>> # both can exist simultaneously :param module_name: the module's name that is to be imported. this can be a dot-delimited name, in which case the module at the end of the path is the one that will be returned :type module_name: str :returns: the module indicated by module_name, imported so that it will not block globally, but also not touching existing global modules """ if module_name in _patchers: return _patched_copy(module_name, _patchers[module_name]) # grab the unpatched version of the module for posterity old_module = sys.modules.pop(module_name, None) # apply all the standard library patches we have saved = [(module_name, old_module)] for name, patch in _patchers.iteritems(): new_mod = _patched_copy(name, patch) saved.append((name, sys.modules.pop(name))) sys.modules[name] = new_mod try: # import the requested module with patches in place result = __import__(module_name, {}, {}, module_name.rsplit(".", 1)[0]) finally: # put all the original modules back as they were for name, old_mod in saved: if old_mod is None: sys.modules.pop(name, None) else: sys.modules[name] = old_mod return result
[ "def", "patched", "(", "module_name", ")", ":", "if", "module_name", "in", "_patchers", ":", "return", "_patched_copy", "(", "module_name", ",", "_patchers", "[", "module_name", "]", ")", "# grab the unpatched version of the module for posterity", "old_module", "=", "sys", ".", "modules", ".", "pop", "(", "module_name", ",", "None", ")", "# apply all the standard library patches we have", "saved", "=", "[", "(", "module_name", ",", "old_module", ")", "]", "for", "name", ",", "patch", "in", "_patchers", ".", "iteritems", "(", ")", ":", "new_mod", "=", "_patched_copy", "(", "name", ",", "patch", ")", "saved", ".", "append", "(", "(", "name", ",", "sys", ".", "modules", ".", "pop", "(", "name", ")", ")", ")", "sys", ".", "modules", "[", "name", "]", "=", "new_mod", "try", ":", "# import the requested module with patches in place", "result", "=", "__import__", "(", "module_name", ",", "{", "}", ",", "{", "}", ",", "module_name", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "0", "]", ")", "finally", ":", "# put all the original modules back as they were", "for", "name", ",", "old_mod", "in", "saved", ":", "if", "old_mod", "is", "None", ":", "sys", ".", "modules", ".", "pop", "(", "name", ",", "None", ")", "else", ":", "sys", ".", "modules", "[", "name", "]", "=", "old_mod", "return", "result" ]
import and return a named module with patches applied locally only this function returns a module after importing it in such as way that it will operate cooperatively, but not overriding the module globally. >>> green_httplib = patched("httplib") >>> # using green_httplib will only block greenlets >>> import httplib >>> # using httplib will block threads/processes >>> # both can exist simultaneously :param module_name: the module's name that is to be imported. this can be a dot-delimited name, in which case the module at the end of the path is the one that will be returned :type module_name: str :returns: the module indicated by module_name, imported so that it will not block globally, but also not touching existing global modules
[ "import", "and", "return", "a", "named", "module", "with", "patches", "applied", "locally", "only" ]
8fd1be4f5443ba090346b5ec82fdbeb0a060d956
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/emulation/__init__.py#L26-L72
train
teepark/greenhouse
greenhouse/emulation/__init__.py
patched_context
def patched_context(*module_names, **kwargs): """apply emulation patches only for a specific context :param module_names: var-args for the modules to patch, as in :func:`patch` :param local: if True, unpatching is done on every switch-out, and re-patching on every switch-in, so that they are only applied for the one coroutine :returns: a contextmanager that patches on ``__enter__`` and unpatches on ``__exit__`` """ local = kwargs.pop('local', False) if kwargs: raise TypeError("patched_context() got an unexpected keyword " + "argument %r" % kwargs.keys()[0]) patch(*module_names) if local: @scheduler.local_incoming_hook @scheduler.local_outgoing_hook def hook(direction, target): {1: patch, 2: unpatch}[direction](*module_names) yield unpatch(*module_names) if local: scheduler.remove_local_incoming_hook(hook) scheduler.remove_local_outgoing_hook(hook)
python
def patched_context(*module_names, **kwargs): """apply emulation patches only for a specific context :param module_names: var-args for the modules to patch, as in :func:`patch` :param local: if True, unpatching is done on every switch-out, and re-patching on every switch-in, so that they are only applied for the one coroutine :returns: a contextmanager that patches on ``__enter__`` and unpatches on ``__exit__`` """ local = kwargs.pop('local', False) if kwargs: raise TypeError("patched_context() got an unexpected keyword " + "argument %r" % kwargs.keys()[0]) patch(*module_names) if local: @scheduler.local_incoming_hook @scheduler.local_outgoing_hook def hook(direction, target): {1: patch, 2: unpatch}[direction](*module_names) yield unpatch(*module_names) if local: scheduler.remove_local_incoming_hook(hook) scheduler.remove_local_outgoing_hook(hook)
[ "def", "patched_context", "(", "*", "module_names", ",", "*", "*", "kwargs", ")", ":", "local", "=", "kwargs", ".", "pop", "(", "'local'", ",", "False", ")", "if", "kwargs", ":", "raise", "TypeError", "(", "\"patched_context() got an unexpected keyword \"", "+", "\"argument %r\"", "%", "kwargs", ".", "keys", "(", ")", "[", "0", "]", ")", "patch", "(", "*", "module_names", ")", "if", "local", ":", "@", "scheduler", ".", "local_incoming_hook", "@", "scheduler", ".", "local_outgoing_hook", "def", "hook", "(", "direction", ",", "target", ")", ":", "{", "1", ":", "patch", ",", "2", ":", "unpatch", "}", "[", "direction", "]", "(", "*", "module_names", ")", "yield", "unpatch", "(", "*", "module_names", ")", "if", "local", ":", "scheduler", ".", "remove_local_incoming_hook", "(", "hook", ")", "scheduler", ".", "remove_local_outgoing_hook", "(", "hook", ")" ]
apply emulation patches only for a specific context :param module_names: var-args for the modules to patch, as in :func:`patch` :param local: if True, unpatching is done on every switch-out, and re-patching on every switch-in, so that they are only applied for the one coroutine :returns: a contextmanager that patches on ``__enter__`` and unpatches on ``__exit__``
[ "apply", "emulation", "patches", "only", "for", "a", "specific", "context" ]
8fd1be4f5443ba090346b5ec82fdbeb0a060d956
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/emulation/__init__.py#L76-L105
train
teepark/greenhouse
greenhouse/emulation/__init__.py
patch
def patch(*module_names): """apply monkey-patches to stdlib modules in-place imports the relevant modules and simply overwrites attributes on the module objects themselves. those attributes may be functions, classes or other attributes. valid arguments are: - __builtin__ - Queue - fcntl - os - select - signal - socket - ssl - sys - thread - threading - time - zmq with no arguments, patches everything it can in all of the above modules :raises: ``ValueError`` if an unknown module name is provided .. note:: lots more standard library modules can be made non-blocking by virtue of patching some combination of the the above (because they only block by using blocking functions defined elsewhere). a few examples: - ``subprocess`` works cooperatively with ``os`` and ``select`` patched - ``httplib``, ``urllib`` and ``urllib2`` will all operate cooperatively with ``socket`` and ``ssl`` patched """ if not module_names: module_names = _patchers.keys() log.info("monkey-patching in-place (%d modules)" % len(module_names)) for module_name in module_names: if module_name not in _patchers: raise ValueError("'%s' is not greenhouse-patchable" % module_name) for module_name in module_names: if module_name in sys.modules: module = sys.modules[module_name] else: module = __import__( module_name, {}, {}, module_name.rsplit(".", 1)[0]) for attr, patch in _patchers[module_name].items(): setattr(module, attr, patch)
python
def patch(*module_names): """apply monkey-patches to stdlib modules in-place imports the relevant modules and simply overwrites attributes on the module objects themselves. those attributes may be functions, classes or other attributes. valid arguments are: - __builtin__ - Queue - fcntl - os - select - signal - socket - ssl - sys - thread - threading - time - zmq with no arguments, patches everything it can in all of the above modules :raises: ``ValueError`` if an unknown module name is provided .. note:: lots more standard library modules can be made non-blocking by virtue of patching some combination of the the above (because they only block by using blocking functions defined elsewhere). a few examples: - ``subprocess`` works cooperatively with ``os`` and ``select`` patched - ``httplib``, ``urllib`` and ``urllib2`` will all operate cooperatively with ``socket`` and ``ssl`` patched """ if not module_names: module_names = _patchers.keys() log.info("monkey-patching in-place (%d modules)" % len(module_names)) for module_name in module_names: if module_name not in _patchers: raise ValueError("'%s' is not greenhouse-patchable" % module_name) for module_name in module_names: if module_name in sys.modules: module = sys.modules[module_name] else: module = __import__( module_name, {}, {}, module_name.rsplit(".", 1)[0]) for attr, patch in _patchers[module_name].items(): setattr(module, attr, patch)
[ "def", "patch", "(", "*", "module_names", ")", ":", "if", "not", "module_names", ":", "module_names", "=", "_patchers", ".", "keys", "(", ")", "log", ".", "info", "(", "\"monkey-patching in-place (%d modules)\"", "%", "len", "(", "module_names", ")", ")", "for", "module_name", "in", "module_names", ":", "if", "module_name", "not", "in", "_patchers", ":", "raise", "ValueError", "(", "\"'%s' is not greenhouse-patchable\"", "%", "module_name", ")", "for", "module_name", "in", "module_names", ":", "if", "module_name", "in", "sys", ".", "modules", ":", "module", "=", "sys", ".", "modules", "[", "module_name", "]", "else", ":", "module", "=", "__import__", "(", "module_name", ",", "{", "}", ",", "{", "}", ",", "module_name", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "0", "]", ")", "for", "attr", ",", "patch", "in", "_patchers", "[", "module_name", "]", ".", "items", "(", ")", ":", "setattr", "(", "module", ",", "attr", ",", "patch", ")" ]
apply monkey-patches to stdlib modules in-place imports the relevant modules and simply overwrites attributes on the module objects themselves. those attributes may be functions, classes or other attributes. valid arguments are: - __builtin__ - Queue - fcntl - os - select - signal - socket - ssl - sys - thread - threading - time - zmq with no arguments, patches everything it can in all of the above modules :raises: ``ValueError`` if an unknown module name is provided .. note:: lots more standard library modules can be made non-blocking by virtue of patching some combination of the the above (because they only block by using blocking functions defined elsewhere). a few examples: - ``subprocess`` works cooperatively with ``os`` and ``select`` patched - ``httplib``, ``urllib`` and ``urllib2`` will all operate cooperatively with ``socket`` and ``ssl`` patched
[ "apply", "monkey", "-", "patches", "to", "stdlib", "modules", "in", "-", "place" ]
8fd1be4f5443ba090346b5ec82fdbeb0a060d956
https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/emulation/__init__.py#L142-L194
train
nuclio/nuclio-sdk-py
nuclio_sdk/event.py
Event.from_json
def from_json(data): """Decode event encoded as JSON by processor""" parsed_data = json.loads(data) trigger = TriggerInfo( parsed_data['trigger']['class'], parsed_data['trigger']['kind'], ) # extract content type, needed to decode body content_type = parsed_data['content_type'] return Event(body=Event.decode_body(parsed_data['body'], content_type), content_type=content_type, trigger=trigger, fields=parsed_data.get('fields'), headers=parsed_data.get('headers'), _id=parsed_data['id'], method=parsed_data['method'], path=parsed_data['path'], size=parsed_data['size'], timestamp=datetime.datetime.utcfromtimestamp(parsed_data['timestamp']), url=parsed_data['url'], _type=parsed_data['type'], type_version=parsed_data['type_version'], version=parsed_data['version'])
python
def from_json(data): """Decode event encoded as JSON by processor""" parsed_data = json.loads(data) trigger = TriggerInfo( parsed_data['trigger']['class'], parsed_data['trigger']['kind'], ) # extract content type, needed to decode body content_type = parsed_data['content_type'] return Event(body=Event.decode_body(parsed_data['body'], content_type), content_type=content_type, trigger=trigger, fields=parsed_data.get('fields'), headers=parsed_data.get('headers'), _id=parsed_data['id'], method=parsed_data['method'], path=parsed_data['path'], size=parsed_data['size'], timestamp=datetime.datetime.utcfromtimestamp(parsed_data['timestamp']), url=parsed_data['url'], _type=parsed_data['type'], type_version=parsed_data['type_version'], version=parsed_data['version'])
[ "def", "from_json", "(", "data", ")", ":", "parsed_data", "=", "json", ".", "loads", "(", "data", ")", "trigger", "=", "TriggerInfo", "(", "parsed_data", "[", "'trigger'", "]", "[", "'class'", "]", ",", "parsed_data", "[", "'trigger'", "]", "[", "'kind'", "]", ",", ")", "# extract content type, needed to decode body", "content_type", "=", "parsed_data", "[", "'content_type'", "]", "return", "Event", "(", "body", "=", "Event", ".", "decode_body", "(", "parsed_data", "[", "'body'", "]", ",", "content_type", ")", ",", "content_type", "=", "content_type", ",", "trigger", "=", "trigger", ",", "fields", "=", "parsed_data", ".", "get", "(", "'fields'", ")", ",", "headers", "=", "parsed_data", ".", "get", "(", "'headers'", ")", ",", "_id", "=", "parsed_data", "[", "'id'", "]", ",", "method", "=", "parsed_data", "[", "'method'", "]", ",", "path", "=", "parsed_data", "[", "'path'", "]", ",", "size", "=", "parsed_data", "[", "'size'", "]", ",", "timestamp", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "parsed_data", "[", "'timestamp'", "]", ")", ",", "url", "=", "parsed_data", "[", "'url'", "]", ",", "_type", "=", "parsed_data", "[", "'type'", "]", ",", "type_version", "=", "parsed_data", "[", "'type_version'", "]", ",", "version", "=", "parsed_data", "[", "'version'", "]", ")" ]
Decode event encoded as JSON by processor
[ "Decode", "event", "encoded", "as", "JSON", "by", "processor" ]
5af9ffc19a0d96255ff430bc358be9cd7a57f424
https://github.com/nuclio/nuclio-sdk-py/blob/5af9ffc19a0d96255ff430bc358be9cd7a57f424/nuclio_sdk/event.py#L74-L99
train
nuclio/nuclio-sdk-py
nuclio_sdk/event.py
Event.decode_body
def decode_body(body, content_type): """Decode event body""" if isinstance(body, dict): return body else: try: decoded_body = base64.b64decode(body) except: return body if content_type == 'application/json': try: return json.loads(decoded_body) except: pass return decoded_body
python
def decode_body(body, content_type): """Decode event body""" if isinstance(body, dict): return body else: try: decoded_body = base64.b64decode(body) except: return body if content_type == 'application/json': try: return json.loads(decoded_body) except: pass return decoded_body
[ "def", "decode_body", "(", "body", ",", "content_type", ")", ":", "if", "isinstance", "(", "body", ",", "dict", ")", ":", "return", "body", "else", ":", "try", ":", "decoded_body", "=", "base64", ".", "b64decode", "(", "body", ")", "except", ":", "return", "body", "if", "content_type", "==", "'application/json'", ":", "try", ":", "return", "json", ".", "loads", "(", "decoded_body", ")", "except", ":", "pass", "return", "decoded_body" ]
Decode event body
[ "Decode", "event", "body" ]
5af9ffc19a0d96255ff430bc358be9cd7a57f424
https://github.com/nuclio/nuclio-sdk-py/blob/5af9ffc19a0d96255ff430bc358be9cd7a57f424/nuclio_sdk/event.py#L102-L119
train
nickpandolfi/Cyther
cyther/commands.py
furtherArgsProcessing
def furtherArgsProcessing(args): """ Converts args, and deals with incongruities that argparse couldn't handle """ if isinstance(args, str): unprocessed = args.strip().split(' ') if unprocessed[0] == 'cyther': del unprocessed[0] args = parser.parse_args(unprocessed).__dict__ elif isinstance(args, argparse.Namespace): args = args.__dict__ elif isinstance(args, dict): pass else: raise CytherError( "Args must be a instance of str or argparse.Namespace, not '{}'".format( str(type(args)))) if args['watch']: args['timestamp'] = True args['watch_stats'] = {'counter': 0, 'errors': 0, 'compiles': 0, 'polls': 0} args['print_args'] = True return args
python
def furtherArgsProcessing(args): """ Converts args, and deals with incongruities that argparse couldn't handle """ if isinstance(args, str): unprocessed = args.strip().split(' ') if unprocessed[0] == 'cyther': del unprocessed[0] args = parser.parse_args(unprocessed).__dict__ elif isinstance(args, argparse.Namespace): args = args.__dict__ elif isinstance(args, dict): pass else: raise CytherError( "Args must be a instance of str or argparse.Namespace, not '{}'".format( str(type(args)))) if args['watch']: args['timestamp'] = True args['watch_stats'] = {'counter': 0, 'errors': 0, 'compiles': 0, 'polls': 0} args['print_args'] = True return args
[ "def", "furtherArgsProcessing", "(", "args", ")", ":", "if", "isinstance", "(", "args", ",", "str", ")", ":", "unprocessed", "=", "args", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", "if", "unprocessed", "[", "0", "]", "==", "'cyther'", ":", "del", "unprocessed", "[", "0", "]", "args", "=", "parser", ".", "parse_args", "(", "unprocessed", ")", ".", "__dict__", "elif", "isinstance", "(", "args", ",", "argparse", ".", "Namespace", ")", ":", "args", "=", "args", ".", "__dict__", "elif", "isinstance", "(", "args", ",", "dict", ")", ":", "pass", "else", ":", "raise", "CytherError", "(", "\"Args must be a instance of str or argparse.Namespace, not '{}'\"", ".", "format", "(", "str", "(", "type", "(", "args", ")", ")", ")", ")", "if", "args", "[", "'watch'", "]", ":", "args", "[", "'timestamp'", "]", "=", "True", "args", "[", "'watch_stats'", "]", "=", "{", "'counter'", ":", "0", ",", "'errors'", ":", "0", ",", "'compiles'", ":", "0", ",", "'polls'", ":", "0", "}", "args", "[", "'print_args'", "]", "=", "True", "return", "args" ]
Converts args, and deals with incongruities that argparse couldn't handle
[ "Converts", "args", "and", "deals", "with", "incongruities", "that", "argparse", "couldn", "t", "handle" ]
9fb0bd77af594008aa6ee8af460aa8c953abf5bc
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/commands.py#L65-L90
train
nickpandolfi/Cyther
cyther/commands.py
processFiles
def processFiles(args): """ Generates and error checks each file's information before the compilation actually starts """ to_process = [] for filename in args['filenames']: file = dict() if args['include']: file['include'] = INCLUDE_STRING + ''.join( ['-I' + item for item in args['include']]) else: file['include'] = INCLUDE_STRING file['file_path'] = getPath(filename) file['file_base_name'] = \ os.path.splitext(os.path.basename(file['file_path']))[0] file['no_extension'], file['extension'] = os.path.splitext( file['file_path']) if file['extension'] not in CYTHONIZABLE_FILE_EXTS: raise CytherError( "The file '{}' is not a designated cython file".format( file['file_path'])) base_path = os.path.dirname(file['file_path']) local_build = args['local'] if not local_build: cache_name = os.path.join(base_path, '__cythercache__') os.makedirs(cache_name, exist_ok=True) file['c_name'] = os.path.join(cache_name, file['file_base_name']) + '.c' else: file['c_name'] = file['no_extension'] + '.c' file['object_file_name'] = os.path.splitext(file['c_name'])[0] + '.o' output_name = args['output_name'] if args['watch']: file['output_name'] = file['no_extension']+DEFAULT_OUTPUT_EXTENSION elif output_name: if os.path.exists(output_name) and os.path.isfile(output_name): file['output_name'] = output_name else: dirname = os.path.dirname(output_name) if not dirname: dirname = os.getcwd() if os.path.exists(dirname): file['output_name'] = output_name else: raise CytherError('The directory specified to write' 'the output file in does not exist') else: file['output_name'] = file['no_extension']+DEFAULT_OUTPUT_EXTENSION file['stamp_if_error'] = 0 to_process.append(file) return to_process
python
def processFiles(args): """ Generates and error checks each file's information before the compilation actually starts """ to_process = [] for filename in args['filenames']: file = dict() if args['include']: file['include'] = INCLUDE_STRING + ''.join( ['-I' + item for item in args['include']]) else: file['include'] = INCLUDE_STRING file['file_path'] = getPath(filename) file['file_base_name'] = \ os.path.splitext(os.path.basename(file['file_path']))[0] file['no_extension'], file['extension'] = os.path.splitext( file['file_path']) if file['extension'] not in CYTHONIZABLE_FILE_EXTS: raise CytherError( "The file '{}' is not a designated cython file".format( file['file_path'])) base_path = os.path.dirname(file['file_path']) local_build = args['local'] if not local_build: cache_name = os.path.join(base_path, '__cythercache__') os.makedirs(cache_name, exist_ok=True) file['c_name'] = os.path.join(cache_name, file['file_base_name']) + '.c' else: file['c_name'] = file['no_extension'] + '.c' file['object_file_name'] = os.path.splitext(file['c_name'])[0] + '.o' output_name = args['output_name'] if args['watch']: file['output_name'] = file['no_extension']+DEFAULT_OUTPUT_EXTENSION elif output_name: if os.path.exists(output_name) and os.path.isfile(output_name): file['output_name'] = output_name else: dirname = os.path.dirname(output_name) if not dirname: dirname = os.getcwd() if os.path.exists(dirname): file['output_name'] = output_name else: raise CytherError('The directory specified to write' 'the output file in does not exist') else: file['output_name'] = file['no_extension']+DEFAULT_OUTPUT_EXTENSION file['stamp_if_error'] = 0 to_process.append(file) return to_process
[ "def", "processFiles", "(", "args", ")", ":", "to_process", "=", "[", "]", "for", "filename", "in", "args", "[", "'filenames'", "]", ":", "file", "=", "dict", "(", ")", "if", "args", "[", "'include'", "]", ":", "file", "[", "'include'", "]", "=", "INCLUDE_STRING", "+", "''", ".", "join", "(", "[", "'-I'", "+", "item", "for", "item", "in", "args", "[", "'include'", "]", "]", ")", "else", ":", "file", "[", "'include'", "]", "=", "INCLUDE_STRING", "file", "[", "'file_path'", "]", "=", "getPath", "(", "filename", ")", "file", "[", "'file_base_name'", "]", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "file", "[", "'file_path'", "]", ")", ")", "[", "0", "]", "file", "[", "'no_extension'", "]", ",", "file", "[", "'extension'", "]", "=", "os", ".", "path", ".", "splitext", "(", "file", "[", "'file_path'", "]", ")", "if", "file", "[", "'extension'", "]", "not", "in", "CYTHONIZABLE_FILE_EXTS", ":", "raise", "CytherError", "(", "\"The file '{}' is not a designated cython file\"", ".", "format", "(", "file", "[", "'file_path'", "]", ")", ")", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "file", "[", "'file_path'", "]", ")", "local_build", "=", "args", "[", "'local'", "]", "if", "not", "local_build", ":", "cache_name", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "'__cythercache__'", ")", "os", ".", "makedirs", "(", "cache_name", ",", "exist_ok", "=", "True", ")", "file", "[", "'c_name'", "]", "=", "os", ".", "path", ".", "join", "(", "cache_name", ",", "file", "[", "'file_base_name'", "]", ")", "+", "'.c'", "else", ":", "file", "[", "'c_name'", "]", "=", "file", "[", "'no_extension'", "]", "+", "'.c'", "file", "[", "'object_file_name'", "]", "=", "os", ".", "path", ".", "splitext", "(", "file", "[", "'c_name'", "]", ")", "[", "0", "]", "+", "'.o'", "output_name", "=", "args", "[", "'output_name'", "]", "if", "args", "[", "'watch'", "]", ":", "file", "[", "'output_name'", "]", "=", "file", "[", "'no_extension'", "]", "+", "DEFAULT_OUTPUT_EXTENSION", "elif", "output_name", ":", "if", "os", ".", "path", ".", "exists", "(", "output_name", ")", "and", "os", ".", "path", ".", "isfile", "(", "output_name", ")", ":", "file", "[", "'output_name'", "]", "=", "output_name", "else", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "output_name", ")", "if", "not", "dirname", ":", "dirname", "=", "os", ".", "getcwd", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "file", "[", "'output_name'", "]", "=", "output_name", "else", ":", "raise", "CytherError", "(", "'The directory specified to write'", "'the output file in does not exist'", ")", "else", ":", "file", "[", "'output_name'", "]", "=", "file", "[", "'no_extension'", "]", "+", "DEFAULT_OUTPUT_EXTENSION", "file", "[", "'stamp_if_error'", "]", "=", "0", "to_process", ".", "append", "(", "file", ")", "return", "to_process" ]
Generates and error checks each file's information before the compilation actually starts
[ "Generates", "and", "error", "checks", "each", "file", "s", "information", "before", "the", "compilation", "actually", "starts" ]
9fb0bd77af594008aa6ee8af460aa8c953abf5bc
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/commands.py#L93-L147
train
nickpandolfi/Cyther
cyther/commands.py
makeCommands
def makeCommands(file): """ Given a high level preset, it will construct the basic args to pass over. 'ninja', 'beast', 'minimal', 'swift' """ commands = [['cython', '-a', '-p', '-o', file['c_name'], file['file_path']], ['gcc', '-DNDEBUG', '-g', '-fwrapv', '-O3', '-Wall', '-Wextra', '-pthread', '-fPIC', '-c', file['include'], '-o', file['object_file_name'], file['c_name']], ['gcc', '-g', '-Wall', '-Wextra', '-pthread', '-shared', RUNTIME_STRING, '-o', file['output_name'], file['object_file_name'], L_OPTION]] return commands
python
def makeCommands(file): """ Given a high level preset, it will construct the basic args to pass over. 'ninja', 'beast', 'minimal', 'swift' """ commands = [['cython', '-a', '-p', '-o', file['c_name'], file['file_path']], ['gcc', '-DNDEBUG', '-g', '-fwrapv', '-O3', '-Wall', '-Wextra', '-pthread', '-fPIC', '-c', file['include'], '-o', file['object_file_name'], file['c_name']], ['gcc', '-g', '-Wall', '-Wextra', '-pthread', '-shared', RUNTIME_STRING, '-o', file['output_name'], file['object_file_name'], L_OPTION]] return commands
[ "def", "makeCommands", "(", "file", ")", ":", "commands", "=", "[", "[", "'cython'", ",", "'-a'", ",", "'-p'", ",", "'-o'", ",", "file", "[", "'c_name'", "]", ",", "file", "[", "'file_path'", "]", "]", ",", "[", "'gcc'", ",", "'-DNDEBUG'", ",", "'-g'", ",", "'-fwrapv'", ",", "'-O3'", ",", "'-Wall'", ",", "'-Wextra'", ",", "'-pthread'", ",", "'-fPIC'", ",", "'-c'", ",", "file", "[", "'include'", "]", ",", "'-o'", ",", "file", "[", "'object_file_name'", "]", ",", "file", "[", "'c_name'", "]", "]", ",", "[", "'gcc'", ",", "'-g'", ",", "'-Wall'", ",", "'-Wextra'", ",", "'-pthread'", ",", "'-shared'", ",", "RUNTIME_STRING", ",", "'-o'", ",", "file", "[", "'output_name'", "]", ",", "file", "[", "'object_file_name'", "]", ",", "L_OPTION", "]", "]", "return", "commands" ]
Given a high level preset, it will construct the basic args to pass over. 'ninja', 'beast', 'minimal', 'swift'
[ "Given", "a", "high", "level", "preset", "it", "will", "construct", "the", "basic", "args", "to", "pass", "over", ".", "ninja", "beast", "minimal", "swift" ]
9fb0bd77af594008aa6ee8af460aa8c953abf5bc
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/commands.py#L206-L220
train
Open-ET/openet-core-beta
openet/core/api.py
collection
def collection( et_model, variable, collections, start_date, end_date, t_interval, geometry, **kwargs ): """Generic OpenET Collection Parameters ---------- self : et_model : {'ndvi', 'ssebop'} ET model. variable : str collections : list GEE satellite image collection IDs. start_date : str ISO format inclusive start date (i.e. YYYY-MM-DD). end_date : str ISO format exclusive end date (i.e. YYYY-MM-DD). t_interval : {'daily', 'monthly', 'annual', 'overpass'} Time interval over which to interpolate and aggregate values. Selecting 'overpass' will return values only for the overpass dates. geometry : ee.Geometry The geometry object will be used to filter the input collections. kwargs : Returns ------- ee.ImageCollection Notes ----- The following is just a basic framework for what needs to happen to go from input parameters to an output image collection. A lot of this might make more sense in the init function above. """ # Load the ET model if et_model.lower() == 'ndvi': # # DEADBEEF - Manually adding OpenET Model to system path # # This will eventually be handled by import openet modules # import os # model_path = os.path.dirname(os.path.dirname(os.path.dirname( # os.path.abspath(os.path.realpath(__file__))))) # print(model_path) # sys.path.insert(0, os.path.join(model_path, 'openet-ndvi-test')) # print(sys.path) try: import openet.ndvi as model except ModuleNotFoundError: print( '\nThe ET model {} could not be imported'.format(et_model) + '\nPlease ensure that the model has been installed') return False except Exception as e: print('Unhandled Exception: {}'.format(e)) raise elif et_model.lower() == 'ssebop': # # DEADBEEF - Manually adding OpenET Models to system path # # This will eventually be handled by import openet modules # import os # model_path = os.path.dirname(os.path.dirname(os.path.dirname( # os.path.abspath(os.path.realpath(__file__))))) # print(model_path) # sys.path.insert(0, os.path.join(model_path, 'openet-ssebop-test')) try: import openet.ssebop as model except ModuleNotFoundError: print( '\nThe ET model {} could not be imported'.format(et_model) + '\nPlease ensure that the model has been installed') return False except Exception as e: print('Unhandled Exception: {}'.format(e)) raise else: # CGM - This could just be a value error exception raise ValueError('unsupported et_model type') variable_coll = model.collection( variable, collections, start_date, end_date, t_interval, geometry, **kwargs ) return variable_coll
python
def collection( et_model, variable, collections, start_date, end_date, t_interval, geometry, **kwargs ): """Generic OpenET Collection Parameters ---------- self : et_model : {'ndvi', 'ssebop'} ET model. variable : str collections : list GEE satellite image collection IDs. start_date : str ISO format inclusive start date (i.e. YYYY-MM-DD). end_date : str ISO format exclusive end date (i.e. YYYY-MM-DD). t_interval : {'daily', 'monthly', 'annual', 'overpass'} Time interval over which to interpolate and aggregate values. Selecting 'overpass' will return values only for the overpass dates. geometry : ee.Geometry The geometry object will be used to filter the input collections. kwargs : Returns ------- ee.ImageCollection Notes ----- The following is just a basic framework for what needs to happen to go from input parameters to an output image collection. A lot of this might make more sense in the init function above. """ # Load the ET model if et_model.lower() == 'ndvi': # # DEADBEEF - Manually adding OpenET Model to system path # # This will eventually be handled by import openet modules # import os # model_path = os.path.dirname(os.path.dirname(os.path.dirname( # os.path.abspath(os.path.realpath(__file__))))) # print(model_path) # sys.path.insert(0, os.path.join(model_path, 'openet-ndvi-test')) # print(sys.path) try: import openet.ndvi as model except ModuleNotFoundError: print( '\nThe ET model {} could not be imported'.format(et_model) + '\nPlease ensure that the model has been installed') return False except Exception as e: print('Unhandled Exception: {}'.format(e)) raise elif et_model.lower() == 'ssebop': # # DEADBEEF - Manually adding OpenET Models to system path # # This will eventually be handled by import openet modules # import os # model_path = os.path.dirname(os.path.dirname(os.path.dirname( # os.path.abspath(os.path.realpath(__file__))))) # print(model_path) # sys.path.insert(0, os.path.join(model_path, 'openet-ssebop-test')) try: import openet.ssebop as model except ModuleNotFoundError: print( '\nThe ET model {} could not be imported'.format(et_model) + '\nPlease ensure that the model has been installed') return False except Exception as e: print('Unhandled Exception: {}'.format(e)) raise else: # CGM - This could just be a value error exception raise ValueError('unsupported et_model type') variable_coll = model.collection( variable, collections, start_date, end_date, t_interval, geometry, **kwargs ) return variable_coll
[ "def", "collection", "(", "et_model", ",", "variable", ",", "collections", ",", "start_date", ",", "end_date", ",", "t_interval", ",", "geometry", ",", "*", "*", "kwargs", ")", ":", "# Load the ET model", "if", "et_model", ".", "lower", "(", ")", "==", "'ndvi'", ":", "# # DEADBEEF - Manually adding OpenET Model to system path", "# # This will eventually be handled by import openet modules", "# import os", "# model_path = os.path.dirname(os.path.dirname(os.path.dirname(", "# os.path.abspath(os.path.realpath(__file__)))))", "# print(model_path)", "# sys.path.insert(0, os.path.join(model_path, 'openet-ndvi-test'))", "# print(sys.path)", "try", ":", "import", "openet", ".", "ndvi", "as", "model", "except", "ModuleNotFoundError", ":", "print", "(", "'\\nThe ET model {} could not be imported'", ".", "format", "(", "et_model", ")", "+", "'\\nPlease ensure that the model has been installed'", ")", "return", "False", "except", "Exception", "as", "e", ":", "print", "(", "'Unhandled Exception: {}'", ".", "format", "(", "e", ")", ")", "raise", "elif", "et_model", ".", "lower", "(", ")", "==", "'ssebop'", ":", "# # DEADBEEF - Manually adding OpenET Models to system path", "# # This will eventually be handled by import openet modules", "# import os", "# model_path = os.path.dirname(os.path.dirname(os.path.dirname(", "# os.path.abspath(os.path.realpath(__file__)))))", "# print(model_path)", "# sys.path.insert(0, os.path.join(model_path, 'openet-ssebop-test'))", "try", ":", "import", "openet", ".", "ssebop", "as", "model", "except", "ModuleNotFoundError", ":", "print", "(", "'\\nThe ET model {} could not be imported'", ".", "format", "(", "et_model", ")", "+", "'\\nPlease ensure that the model has been installed'", ")", "return", "False", "except", "Exception", "as", "e", ":", "print", "(", "'Unhandled Exception: {}'", ".", "format", "(", "e", ")", ")", "raise", "else", ":", "# CGM - This could just be a value error exception", "raise", "ValueError", "(", "'unsupported et_model type'", ")", "variable_coll", "=", "model", ".", "collection", "(", "variable", ",", "collections", ",", "start_date", ",", "end_date", ",", "t_interval", ",", "geometry", ",", "*", "*", "kwargs", ")", "return", "variable_coll" ]
Generic OpenET Collection Parameters ---------- self : et_model : {'ndvi', 'ssebop'} ET model. variable : str collections : list GEE satellite image collection IDs. start_date : str ISO format inclusive start date (i.e. YYYY-MM-DD). end_date : str ISO format exclusive end date (i.e. YYYY-MM-DD). t_interval : {'daily', 'monthly', 'annual', 'overpass'} Time interval over which to interpolate and aggregate values. Selecting 'overpass' will return values only for the overpass dates. geometry : ee.Geometry The geometry object will be used to filter the input collections. kwargs : Returns ------- ee.ImageCollection Notes ----- The following is just a basic framework for what needs to happen to go from input parameters to an output image collection. A lot of this might make more sense in the init function above.
[ "Generic", "OpenET", "Collection" ]
f2b81ccf87bf7e7fe1b9f3dd1d4081d0ec7852db
https://github.com/Open-ET/openet-core-beta/blob/f2b81ccf87bf7e7fe1b9f3dd1d4081d0ec7852db/openet/core/api.py#L16-L117
train
cltl/KafNafParserPy
KafNafParserPy/constituency_data.py
Ctree.get_terminals_as_list
def get_terminals_as_list(self): """ Iterator that returns all the terminal objects @rtype: L{Cterminal} @return: terminal objects as list """ terminalList = [] for t_node in self.__get_t_nodes(): terminalList.append(Cterminal(t_node)) return terminalList
python
def get_terminals_as_list(self): """ Iterator that returns all the terminal objects @rtype: L{Cterminal} @return: terminal objects as list """ terminalList = [] for t_node in self.__get_t_nodes(): terminalList.append(Cterminal(t_node)) return terminalList
[ "def", "get_terminals_as_list", "(", "self", ")", ":", "terminalList", "=", "[", "]", "for", "t_node", "in", "self", ".", "__get_t_nodes", "(", ")", ":", "terminalList", ".", "append", "(", "Cterminal", "(", "t_node", ")", ")", "return", "terminalList" ]
Iterator that returns all the terminal objects @rtype: L{Cterminal} @return: terminal objects as list
[ "Iterator", "that", "returns", "all", "the", "terminal", "objects" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/constituency_data.py#L308-L317
train
cltl/KafNafParserPy
KafNafParserPy/constituency_data.py
Ctree.get_edges_as_list
def get_edges_as_list(self): """ Iterator that returns all the edge objects @rtype: L{Cedge} @return: terminal objects (iterator) """ my_edges = [] for edge_node in self.__get_edge_nodes(): my_edges.append(Cedge(edge_node)) return my_edges
python
def get_edges_as_list(self): """ Iterator that returns all the edge objects @rtype: L{Cedge} @return: terminal objects (iterator) """ my_edges = [] for edge_node in self.__get_edge_nodes(): my_edges.append(Cedge(edge_node)) return my_edges
[ "def", "get_edges_as_list", "(", "self", ")", ":", "my_edges", "=", "[", "]", "for", "edge_node", "in", "self", ".", "__get_edge_nodes", "(", ")", ":", "my_edges", ".", "append", "(", "Cedge", "(", "edge_node", ")", ")", "return", "my_edges" ]
Iterator that returns all the edge objects @rtype: L{Cedge} @return: terminal objects (iterator)
[ "Iterator", "that", "returns", "all", "the", "edge", "objects" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/constituency_data.py#L374-L383
train
mjirik/imtools
imtools/show_segmentation.py
SegmentationToMesh.select_labels
def select_labels(self, labels=None): """ Prepare binar segmentation based on input segmentation and labels. :param labels: :return: """ self._resize_if_required() segmentation = self._select_labels(self.resized_segmentation, labels) # logger.debug("select labels in show_segmentation {} sum {}".format(labels, np.sum(segmentation))) self.resized_binar_segmentation = segmentation
python
def select_labels(self, labels=None): """ Prepare binar segmentation based on input segmentation and labels. :param labels: :return: """ self._resize_if_required() segmentation = self._select_labels(self.resized_segmentation, labels) # logger.debug("select labels in show_segmentation {} sum {}".format(labels, np.sum(segmentation))) self.resized_binar_segmentation = segmentation
[ "def", "select_labels", "(", "self", ",", "labels", "=", "None", ")", ":", "self", ".", "_resize_if_required", "(", ")", "segmentation", "=", "self", ".", "_select_labels", "(", "self", ".", "resized_segmentation", ",", "labels", ")", "# logger.debug(\"select labels in show_segmentation {} sum {}\".format(labels, np.sum(segmentation)))", "self", ".", "resized_binar_segmentation", "=", "segmentation" ]
Prepare binar segmentation based on input segmentation and labels. :param labels: :return:
[ "Prepare", "binar", "segmentation", "based", "on", "input", "segmentation", "and", "labels", "." ]
eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/show_segmentation.py#L126-L135
train
mjirik/imtools
imtools/show_segmentation.py
SegmentationToMesh._select_labels
def _select_labels(self, segmentation, labels=None): """ Get selection of labels from input segmentation :param segmentation: :param labels: :return: """ logger.debug("select_labels() started with labels={}".format(labels)) if self.slab is not None and labels is not None: segmentation_out = select_labels(segmentation, labels, slab=self.slab) else: logger.warning("Nothing found for labels " + str(labels)) un = np.unique(segmentation) if len(un) < 2: logger.error("Just one label found in input segmenation") segmentation_out = (segmentation > un[0]).astype(segmentation.dtype) return segmentation_out
python
def _select_labels(self, segmentation, labels=None): """ Get selection of labels from input segmentation :param segmentation: :param labels: :return: """ logger.debug("select_labels() started with labels={}".format(labels)) if self.slab is not None and labels is not None: segmentation_out = select_labels(segmentation, labels, slab=self.slab) else: logger.warning("Nothing found for labels " + str(labels)) un = np.unique(segmentation) if len(un) < 2: logger.error("Just one label found in input segmenation") segmentation_out = (segmentation > un[0]).astype(segmentation.dtype) return segmentation_out
[ "def", "_select_labels", "(", "self", ",", "segmentation", ",", "labels", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"select_labels() started with labels={}\"", ".", "format", "(", "labels", ")", ")", "if", "self", ".", "slab", "is", "not", "None", "and", "labels", "is", "not", "None", ":", "segmentation_out", "=", "select_labels", "(", "segmentation", ",", "labels", ",", "slab", "=", "self", ".", "slab", ")", "else", ":", "logger", ".", "warning", "(", "\"Nothing found for labels \"", "+", "str", "(", "labels", ")", ")", "un", "=", "np", ".", "unique", "(", "segmentation", ")", "if", "len", "(", "un", ")", "<", "2", ":", "logger", ".", "error", "(", "\"Just one label found in input segmenation\"", ")", "segmentation_out", "=", "(", "segmentation", ">", "un", "[", "0", "]", ")", ".", "astype", "(", "segmentation", ".", "dtype", ")", "return", "segmentation_out" ]
Get selection of labels from input segmentation :param segmentation: :param labels: :return:
[ "Get", "selection", "of", "labels", "from", "input", "segmentation" ]
eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/show_segmentation.py#L137-L154
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/template.py
Templates.Get
def Get(self,key): """Get template by providing name, ID, or other unique key. If key is not unique and finds multiple matches only the first will be returned """ for template in self.templates: if template.id == key: return(template)
python
def Get(self,key): """Get template by providing name, ID, or other unique key. If key is not unique and finds multiple matches only the first will be returned """ for template in self.templates: if template.id == key: return(template)
[ "def", "Get", "(", "self", ",", "key", ")", ":", "for", "template", "in", "self", ".", "templates", ":", "if", "template", ".", "id", "==", "key", ":", "return", "(", "template", ")" ]
Get template by providing name, ID, or other unique key. If key is not unique and finds multiple matches only the first will be returned
[ "Get", "template", "by", "providing", "name", "ID", "or", "other", "unique", "key", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/template.py#L25-L33
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/template.py
Templates.Search
def Search(self,key): """Search template list by providing partial name, ID, or other key. """ results = [] for template in self.templates: if template.id.lower().find(key.lower()) != -1: results.append(template) elif template.name.lower().find(key.lower()) != -1: results.append(template) return(results)
python
def Search(self,key): """Search template list by providing partial name, ID, or other key. """ results = [] for template in self.templates: if template.id.lower().find(key.lower()) != -1: results.append(template) elif template.name.lower().find(key.lower()) != -1: results.append(template) return(results)
[ "def", "Search", "(", "self", ",", "key", ")", ":", "results", "=", "[", "]", "for", "template", "in", "self", ".", "templates", ":", "if", "template", ".", "id", ".", "lower", "(", ")", ".", "find", "(", "key", ".", "lower", "(", ")", ")", "!=", "-", "1", ":", "results", ".", "append", "(", "template", ")", "elif", "template", ".", "name", ".", "lower", "(", ")", ".", "find", "(", "key", ".", "lower", "(", ")", ")", "!=", "-", "1", ":", "results", ".", "append", "(", "template", ")", "return", "(", "results", ")" ]
Search template list by providing partial name, ID, or other key.
[ "Search", "template", "list", "by", "providing", "partial", "name", "ID", "or", "other", "key", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/template.py#L36-L46
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/time_utils.py
SecondsToZuluTS
def SecondsToZuluTS(secs=None): """Returns Zulu TS from unix time seconds. If secs is not provided will convert the current time. """ if not secs: secs = int(time.time()) return(datetime.utcfromtimestamp(secs).strftime("%Y-%m-%dT%H:%M:%SZ"))
python
def SecondsToZuluTS(secs=None): """Returns Zulu TS from unix time seconds. If secs is not provided will convert the current time. """ if not secs: secs = int(time.time()) return(datetime.utcfromtimestamp(secs).strftime("%Y-%m-%dT%H:%M:%SZ"))
[ "def", "SecondsToZuluTS", "(", "secs", "=", "None", ")", ":", "if", "not", "secs", ":", "secs", "=", "int", "(", "time", ".", "time", "(", ")", ")", "return", "(", "datetime", ".", "utcfromtimestamp", "(", "secs", ")", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%SZ\"", ")", ")" ]
Returns Zulu TS from unix time seconds. If secs is not provided will convert the current time.
[ "Returns", "Zulu", "TS", "from", "unix", "time", "seconds", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/time_utils.py#L16-L24
train
lacava/DistanceClassifier
DistanceClassifier/DistanceClassifier.py
main
def main(): """Main function that is called when DistanceClassifier is run on the command line""" parser = argparse.ArgumentParser(description='DistanceClassifier for classification based on distance measure in feature space.', add_help=False) parser.add_argument('INPUT_FILE', type=str, help='Data file to perform DistanceClassifier on; ensure that the class label column is labeled as "class".') parser.add_argument('-h', '--help', action='help', help='Show this help message and exit.') parser.add_argument('-is', action='store', dest='INPUT_SEPARATOR', default='\t', type=str, help='Character used to separate columns in the input file.') parser.add_argument('-d', action='store', dest='D', default='mahalanobis',choices = ['mahalanobis','euclidean'], type=str, help='Distance metric to use.') parser.add_argument('-v', action='store', dest='VERBOSITY', default=1, choices=[0, 1, 2], type=int, help='How much information DistanceClassifier communicates while it is running: 0 = none, 1 = minimal, 2 = all.') parser.add_argument('-s', action='store', dest='RANDOM_STATE', default=0, type=int, help='Random state for train/test split.') parser.add_argument('--version', action='version', version='DistanceClassifier {version}'.format(version=__version__), help='Show DistanceClassifier\'s version number and exit.') args = parser.parse_args() if args.VERBOSITY >= 2: print('\nDistanceClassifier settings:') for arg in sorted(args.__dict__): print('{}\t=\t{}'.format(arg, args.__dict__[arg])) print('') input_data = pd.read_csv(args.INPUT_FILE, sep=args.INPUT_SEPARATOR) if 'Class' in input_data.columns.values: input_data.rename(columns={'Label': 'label'}, inplace=True) RANDOM_STATE = args.RANDOM_STATE if args.RANDOM_STATE > 0 else None # # training_indices, testing_indices = train_test_split(input_data.index, # stratify=input_data['label'].values, # train_size=0.75, # test_size=0.25, # random_state=RANDOM_STATE) # # training_features = input_data.loc[training_indices].drop('label', axis=1).values # training_classes = input_data.loc[training_indices, 'label'].values # # testing_features = input_data.loc[testing_indices].drop('label', axis=1).values # testing_classes = input_data.loc[testing_indices, 'label'].values # Run and evaluate DistanceClassifier on the training and testing data dc = DistanceClassifier(d = args.D) # dc.fit(training_features, training_classes) dc.fit(input_data.drop('label',axis=1).values, input_data['label'].values) print(dc.score(input_data.drop('label',axis=1).values, input_data['label'].values))
python
def main(): """Main function that is called when DistanceClassifier is run on the command line""" parser = argparse.ArgumentParser(description='DistanceClassifier for classification based on distance measure in feature space.', add_help=False) parser.add_argument('INPUT_FILE', type=str, help='Data file to perform DistanceClassifier on; ensure that the class label column is labeled as "class".') parser.add_argument('-h', '--help', action='help', help='Show this help message and exit.') parser.add_argument('-is', action='store', dest='INPUT_SEPARATOR', default='\t', type=str, help='Character used to separate columns in the input file.') parser.add_argument('-d', action='store', dest='D', default='mahalanobis',choices = ['mahalanobis','euclidean'], type=str, help='Distance metric to use.') parser.add_argument('-v', action='store', dest='VERBOSITY', default=1, choices=[0, 1, 2], type=int, help='How much information DistanceClassifier communicates while it is running: 0 = none, 1 = minimal, 2 = all.') parser.add_argument('-s', action='store', dest='RANDOM_STATE', default=0, type=int, help='Random state for train/test split.') parser.add_argument('--version', action='version', version='DistanceClassifier {version}'.format(version=__version__), help='Show DistanceClassifier\'s version number and exit.') args = parser.parse_args() if args.VERBOSITY >= 2: print('\nDistanceClassifier settings:') for arg in sorted(args.__dict__): print('{}\t=\t{}'.format(arg, args.__dict__[arg])) print('') input_data = pd.read_csv(args.INPUT_FILE, sep=args.INPUT_SEPARATOR) if 'Class' in input_data.columns.values: input_data.rename(columns={'Label': 'label'}, inplace=True) RANDOM_STATE = args.RANDOM_STATE if args.RANDOM_STATE > 0 else None # # training_indices, testing_indices = train_test_split(input_data.index, # stratify=input_data['label'].values, # train_size=0.75, # test_size=0.25, # random_state=RANDOM_STATE) # # training_features = input_data.loc[training_indices].drop('label', axis=1).values # training_classes = input_data.loc[training_indices, 'label'].values # # testing_features = input_data.loc[testing_indices].drop('label', axis=1).values # testing_classes = input_data.loc[testing_indices, 'label'].values # Run and evaluate DistanceClassifier on the training and testing data dc = DistanceClassifier(d = args.D) # dc.fit(training_features, training_classes) dc.fit(input_data.drop('label',axis=1).values, input_data['label'].values) print(dc.score(input_data.drop('label',axis=1).values, input_data['label'].values))
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'DistanceClassifier for classification based on distance measure in feature space.'", ",", "add_help", "=", "False", ")", "parser", ".", "add_argument", "(", "'INPUT_FILE'", ",", "type", "=", "str", ",", "help", "=", "'Data file to perform DistanceClassifier on; ensure that the class label column is labeled as \"class\".'", ")", "parser", ".", "add_argument", "(", "'-h'", ",", "'--help'", ",", "action", "=", "'help'", ",", "help", "=", "'Show this help message and exit.'", ")", "parser", ".", "add_argument", "(", "'-is'", ",", "action", "=", "'store'", ",", "dest", "=", "'INPUT_SEPARATOR'", ",", "default", "=", "'\\t'", ",", "type", "=", "str", ",", "help", "=", "'Character used to separate columns in the input file.'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "action", "=", "'store'", ",", "dest", "=", "'D'", ",", "default", "=", "'mahalanobis'", ",", "choices", "=", "[", "'mahalanobis'", ",", "'euclidean'", "]", ",", "type", "=", "str", ",", "help", "=", "'Distance metric to use.'", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "action", "=", "'store'", ",", "dest", "=", "'VERBOSITY'", ",", "default", "=", "1", ",", "choices", "=", "[", "0", ",", "1", ",", "2", "]", ",", "type", "=", "int", ",", "help", "=", "'How much information DistanceClassifier communicates while it is running: 0 = none, 1 = minimal, 2 = all.'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "action", "=", "'store'", ",", "dest", "=", "'RANDOM_STATE'", ",", "default", "=", "0", ",", "type", "=", "int", ",", "help", "=", "'Random state for train/test split.'", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "'DistanceClassifier {version}'", ".", "format", "(", "version", "=", "__version__", ")", ",", "help", "=", "'Show DistanceClassifier\\'s version number and exit.'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "VERBOSITY", ">=", "2", ":", "print", "(", "'\\nDistanceClassifier settings:'", ")", "for", "arg", "in", "sorted", "(", "args", ".", "__dict__", ")", ":", "print", "(", "'{}\\t=\\t{}'", ".", "format", "(", "arg", ",", "args", ".", "__dict__", "[", "arg", "]", ")", ")", "print", "(", "''", ")", "input_data", "=", "pd", ".", "read_csv", "(", "args", ".", "INPUT_FILE", ",", "sep", "=", "args", ".", "INPUT_SEPARATOR", ")", "if", "'Class'", "in", "input_data", ".", "columns", ".", "values", ":", "input_data", ".", "rename", "(", "columns", "=", "{", "'Label'", ":", "'label'", "}", ",", "inplace", "=", "True", ")", "RANDOM_STATE", "=", "args", ".", "RANDOM_STATE", "if", "args", ".", "RANDOM_STATE", ">", "0", "else", "None", "#", "# training_indices, testing_indices = train_test_split(input_data.index,", "# stratify=input_data['label'].values,", "# train_size=0.75,", "# test_size=0.25,", "# random_state=RANDOM_STATE)", "#", "# training_features = input_data.loc[training_indices].drop('label', axis=1).values", "# training_classes = input_data.loc[training_indices, 'label'].values", "#", "# testing_features = input_data.loc[testing_indices].drop('label', axis=1).values", "# testing_classes = input_data.loc[testing_indices, 'label'].values", "# Run and evaluate DistanceClassifier on the training and testing data", "dc", "=", "DistanceClassifier", "(", "d", "=", "args", ".", "D", ")", "# dc.fit(training_features, training_classes)", "dc", ".", "fit", "(", "input_data", ".", "drop", "(", "'label'", ",", "axis", "=", "1", ")", ".", "values", ",", "input_data", "[", "'label'", "]", ".", "values", ")", "print", "(", "dc", ".", "score", "(", "input_data", ".", "drop", "(", "'label'", ",", "axis", "=", "1", ")", ".", "values", ",", "input_data", "[", "'label'", "]", ".", "values", ")", ")" ]
Main function that is called when DistanceClassifier is run on the command line
[ "Main", "function", "that", "is", "called", "when", "DistanceClassifier", "is", "run", "on", "the", "command", "line" ]
cbb8a38a82b453c5821d2a2c3328b581f62e47bc
https://github.com/lacava/DistanceClassifier/blob/cbb8a38a82b453c5821d2a2c3328b581f62e47bc/DistanceClassifier/DistanceClassifier.py#L172-L227
train
lacava/DistanceClassifier
DistanceClassifier/DistanceClassifier.py
DistanceClassifier.fit
def fit(self, features, classes): """Constructs the DistanceClassifier from the provided training data Parameters ---------- features: array-like {n_samples, n_features} Feature matrix classes: array-like {n_samples} List of class labels for prediction Returns ------- None """ # class labels classes = self.le.fit_transform(classes) # group the data by class label X = [] self.mu = [] self.Z = [] for i in np.unique(classes): X.append(features[classes == i]) self.mu.append(np.mean(X[i],axis=0)) if self.d == 'mahalanobis': self.Z.append(np.cov(X[i].transpose())) return self
python
def fit(self, features, classes): """Constructs the DistanceClassifier from the provided training data Parameters ---------- features: array-like {n_samples, n_features} Feature matrix classes: array-like {n_samples} List of class labels for prediction Returns ------- None """ # class labels classes = self.le.fit_transform(classes) # group the data by class label X = [] self.mu = [] self.Z = [] for i in np.unique(classes): X.append(features[classes == i]) self.mu.append(np.mean(X[i],axis=0)) if self.d == 'mahalanobis': self.Z.append(np.cov(X[i].transpose())) return self
[ "def", "fit", "(", "self", ",", "features", ",", "classes", ")", ":", "# class labels", "classes", "=", "self", ".", "le", ".", "fit_transform", "(", "classes", ")", "# group the data by class label", "X", "=", "[", "]", "self", ".", "mu", "=", "[", "]", "self", ".", "Z", "=", "[", "]", "for", "i", "in", "np", ".", "unique", "(", "classes", ")", ":", "X", ".", "append", "(", "features", "[", "classes", "==", "i", "]", ")", "self", ".", "mu", ".", "append", "(", "np", ".", "mean", "(", "X", "[", "i", "]", ",", "axis", "=", "0", ")", ")", "if", "self", ".", "d", "==", "'mahalanobis'", ":", "self", ".", "Z", ".", "append", "(", "np", ".", "cov", "(", "X", "[", "i", "]", ".", "transpose", "(", ")", ")", ")", "return", "self" ]
Constructs the DistanceClassifier from the provided training data Parameters ---------- features: array-like {n_samples, n_features} Feature matrix classes: array-like {n_samples} List of class labels for prediction Returns ------- None
[ "Constructs", "the", "DistanceClassifier", "from", "the", "provided", "training", "data" ]
cbb8a38a82b453c5821d2a2c3328b581f62e47bc
https://github.com/lacava/DistanceClassifier/blob/cbb8a38a82b453c5821d2a2c3328b581f62e47bc/DistanceClassifier/DistanceClassifier.py#L56-L84
train
lacava/DistanceClassifier
DistanceClassifier/DistanceClassifier.py
DistanceClassifier.predict
def predict(self, features): """Predict class outputs for an unlabelled feature set""" # get distance of features to class clusters distances = [self._distance(x) for x in features] # assign class label belonging to smallest distance class_predict = [np.argmin(d) for d in distances] return self.le.inverse_transform(class_predict)
python
def predict(self, features): """Predict class outputs for an unlabelled feature set""" # get distance of features to class clusters distances = [self._distance(x) for x in features] # assign class label belonging to smallest distance class_predict = [np.argmin(d) for d in distances] return self.le.inverse_transform(class_predict)
[ "def", "predict", "(", "self", ",", "features", ")", ":", "# get distance of features to class clusters", "distances", "=", "[", "self", ".", "_distance", "(", "x", ")", "for", "x", "in", "features", "]", "# assign class label belonging to smallest distance", "class_predict", "=", "[", "np", ".", "argmin", "(", "d", ")", "for", "d", "in", "distances", "]", "return", "self", ".", "le", ".", "inverse_transform", "(", "class_predict", ")" ]
Predict class outputs for an unlabelled feature set
[ "Predict", "class", "outputs", "for", "an", "unlabelled", "feature", "set" ]
cbb8a38a82b453c5821d2a2c3328b581f62e47bc
https://github.com/lacava/DistanceClassifier/blob/cbb8a38a82b453c5821d2a2c3328b581f62e47bc/DistanceClassifier/DistanceClassifier.py#L86-L95
train
lacava/DistanceClassifier
DistanceClassifier/DistanceClassifier.py
DistanceClassifier._distance
def _distance(self,x): """returns distance measures for features""" distance = np.empty([len(self.mu)]) for i in np.arange(len(self.mu)): if self.d == 'mahalanobis' and self.is_invertible(self.Z[i]): distance[i] = (x - self.mu[i]).dot(np.linalg.inv(self.Z[i])).dot((x - self.mu[i]).transpose()) else: distance[i] = (x - self.mu[i]).dot((x - self.mu[i]).transpose()) return distance
python
def _distance(self,x): """returns distance measures for features""" distance = np.empty([len(self.mu)]) for i in np.arange(len(self.mu)): if self.d == 'mahalanobis' and self.is_invertible(self.Z[i]): distance[i] = (x - self.mu[i]).dot(np.linalg.inv(self.Z[i])).dot((x - self.mu[i]).transpose()) else: distance[i] = (x - self.mu[i]).dot((x - self.mu[i]).transpose()) return distance
[ "def", "_distance", "(", "self", ",", "x", ")", ":", "distance", "=", "np", ".", "empty", "(", "[", "len", "(", "self", ".", "mu", ")", "]", ")", "for", "i", "in", "np", ".", "arange", "(", "len", "(", "self", ".", "mu", ")", ")", ":", "if", "self", ".", "d", "==", "'mahalanobis'", "and", "self", ".", "is_invertible", "(", "self", ".", "Z", "[", "i", "]", ")", ":", "distance", "[", "i", "]", "=", "(", "x", "-", "self", ".", "mu", "[", "i", "]", ")", ".", "dot", "(", "np", ".", "linalg", ".", "inv", "(", "self", ".", "Z", "[", "i", "]", ")", ")", ".", "dot", "(", "(", "x", "-", "self", ".", "mu", "[", "i", "]", ")", ".", "transpose", "(", ")", ")", "else", ":", "distance", "[", "i", "]", "=", "(", "x", "-", "self", ".", "mu", "[", "i", "]", ")", ".", "dot", "(", "(", "x", "-", "self", ".", "mu", "[", "i", "]", ")", ".", "transpose", "(", ")", ")", "return", "distance" ]
returns distance measures for features
[ "returns", "distance", "measures", "for", "features" ]
cbb8a38a82b453c5821d2a2c3328b581f62e47bc
https://github.com/lacava/DistanceClassifier/blob/cbb8a38a82b453c5821d2a2c3328b581f62e47bc/DistanceClassifier/DistanceClassifier.py#L97-L107
train
lacava/DistanceClassifier
DistanceClassifier/DistanceClassifier.py
DistanceClassifier.score
def score(self, features, classes, scoring_function=accuracy_score, **scoring_function_kwargs): """Estimates the accuracy of the predictions from the constructed feature Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to predict from classes: array-like {n_samples} List of true class labels Returns ------- accuracy_score: float The estimated accuracy based on the constructed feature """ if not self.mu: raise ValueError('The DistanceClassifier model must be fit before score() can be called') return scoring_function(classes, self.predict(features), **scoring_function_kwargs)
python
def score(self, features, classes, scoring_function=accuracy_score, **scoring_function_kwargs): """Estimates the accuracy of the predictions from the constructed feature Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to predict from classes: array-like {n_samples} List of true class labels Returns ------- accuracy_score: float The estimated accuracy based on the constructed feature """ if not self.mu: raise ValueError('The DistanceClassifier model must be fit before score() can be called') return scoring_function(classes, self.predict(features), **scoring_function_kwargs)
[ "def", "score", "(", "self", ",", "features", ",", "classes", ",", "scoring_function", "=", "accuracy_score", ",", "*", "*", "scoring_function_kwargs", ")", ":", "if", "not", "self", ".", "mu", ":", "raise", "ValueError", "(", "'The DistanceClassifier model must be fit before score() can be called'", ")", "return", "scoring_function", "(", "classes", ",", "self", ".", "predict", "(", "features", ")", ",", "*", "*", "scoring_function_kwargs", ")" ]
Estimates the accuracy of the predictions from the constructed feature Parameters ---------- features: array-like {n_samples, n_features} Feature matrix to predict from classes: array-like {n_samples} List of true class labels Returns ------- accuracy_score: float The estimated accuracy based on the constructed feature
[ "Estimates", "the", "accuracy", "of", "the", "predictions", "from", "the", "constructed", "feature" ]
cbb8a38a82b453c5821d2a2c3328b581f62e47bc
https://github.com/lacava/DistanceClassifier/blob/cbb8a38a82b453c5821d2a2c3328b581f62e47bc/DistanceClassifier/DistanceClassifier.py#L126-L145
train
lacava/DistanceClassifier
DistanceClassifier/DistanceClassifier.py
DistanceClassifier.is_invertible
def is_invertible(self,X): """checks if Z is invertible""" if len(X.shape) == 2: return X.shape[0] == X.shape[1] and np.linalg.matrix_rank(X) == X.shape[0] else: return False
python
def is_invertible(self,X): """checks if Z is invertible""" if len(X.shape) == 2: return X.shape[0] == X.shape[1] and np.linalg.matrix_rank(X) == X.shape[0] else: return False
[ "def", "is_invertible", "(", "self", ",", "X", ")", ":", "if", "len", "(", "X", ".", "shape", ")", "==", "2", ":", "return", "X", ".", "shape", "[", "0", "]", "==", "X", ".", "shape", "[", "1", "]", "and", "np", ".", "linalg", ".", "matrix_rank", "(", "X", ")", "==", "X", ".", "shape", "[", "0", "]", "else", ":", "return", "False" ]
checks if Z is invertible
[ "checks", "if", "Z", "is", "invertible" ]
cbb8a38a82b453c5821d2a2c3328b581f62e47bc
https://github.com/lacava/DistanceClassifier/blob/cbb8a38a82b453c5821d2a2c3328b581f62e47bc/DistanceClassifier/DistanceClassifier.py#L165-L170
train
cltl/KafNafParserPy
KafNafParserPy/term_data.py
Cterm.get_span_ids
def get_span_ids(self): """ Returns the span object of the term @rtype: List @return: the term span as list of wf ids """ node_span = self.node.find('span') if node_span is not None: mySpan = Cspan(node_span) span_ids = mySpan.get_span_ids() return span_ids else: return []
python
def get_span_ids(self): """ Returns the span object of the term @rtype: List @return: the term span as list of wf ids """ node_span = self.node.find('span') if node_span is not None: mySpan = Cspan(node_span) span_ids = mySpan.get_span_ids() return span_ids else: return []
[ "def", "get_span_ids", "(", "self", ")", ":", "node_span", "=", "self", ".", "node", ".", "find", "(", "'span'", ")", "if", "node_span", "is", "not", "None", ":", "mySpan", "=", "Cspan", "(", "node_span", ")", "span_ids", "=", "mySpan", ".", "get_span_ids", "(", ")", "return", "span_ids", "else", ":", "return", "[", "]" ]
Returns the span object of the term @rtype: List @return: the term span as list of wf ids
[ "Returns", "the", "span", "object", "of", "the", "term" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/term_data.py#L177-L189
train
cltl/KafNafParserPy
KafNafParserPy/term_data.py
Cterm.set_span_from_ids
def set_span_from_ids(self, span_list): """ Sets the span for the term from list of ids @type span_list: [] @param span_list: list of wf ids forming span """ this_span = Cspan() this_span.create_from_ids(span_list) self.node.append(this_span.get_node())
python
def set_span_from_ids(self, span_list): """ Sets the span for the term from list of ids @type span_list: [] @param span_list: list of wf ids forming span """ this_span = Cspan() this_span.create_from_ids(span_list) self.node.append(this_span.get_node())
[ "def", "set_span_from_ids", "(", "self", ",", "span_list", ")", ":", "this_span", "=", "Cspan", "(", ")", "this_span", ".", "create_from_ids", "(", "span_list", ")", "self", ".", "node", ".", "append", "(", "this_span", ".", "get_node", "(", ")", ")" ]
Sets the span for the term from list of ids @type span_list: [] @param span_list: list of wf ids forming span
[ "Sets", "the", "span", "for", "the", "term", "from", "list", "of", "ids" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/term_data.py#L191-L199
train
cltl/KafNafParserPy
KafNafParserPy/term_data.py
Cterms.get_term
def get_term(self,term_id): """ Returns the term object for the supplied identifier @type term_id: string @param term_id: term identifier """ if term_id in self.idx: return Cterm(self.idx[term_id],self.type) else: return None
python
def get_term(self,term_id): """ Returns the term object for the supplied identifier @type term_id: string @param term_id: term identifier """ if term_id in self.idx: return Cterm(self.idx[term_id],self.type) else: return None
[ "def", "get_term", "(", "self", ",", "term_id", ")", ":", "if", "term_id", "in", "self", ".", "idx", ":", "return", "Cterm", "(", "self", ".", "idx", "[", "term_id", "]", ",", "self", ".", "type", ")", "else", ":", "return", "None" ]
Returns the term object for the supplied identifier @type term_id: string @param term_id: term identifier
[ "Returns", "the", "term", "object", "for", "the", "supplied", "identifier" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/term_data.py#L327-L336
train
cltl/KafNafParserPy
KafNafParserPy/term_data.py
Cterms.add_term
def add_term(self,term_obj): """ Adds a term object to the layer @type term_obj: L{Cterm} @param term_obj: the term object """ if term_obj.get_id() in self.idx: raise ValueError("Term with id {} already exists!" .format(term_obj.get_id())) self.node.append(term_obj.get_node()) self.idx[term_obj.get_id()] = term_obj
python
def add_term(self,term_obj): """ Adds a term object to the layer @type term_obj: L{Cterm} @param term_obj: the term object """ if term_obj.get_id() in self.idx: raise ValueError("Term with id {} already exists!" .format(term_obj.get_id())) self.node.append(term_obj.get_node()) self.idx[term_obj.get_id()] = term_obj
[ "def", "add_term", "(", "self", ",", "term_obj", ")", ":", "if", "term_obj", ".", "get_id", "(", ")", "in", "self", ".", "idx", ":", "raise", "ValueError", "(", "\"Term with id {} already exists!\"", ".", "format", "(", "term_obj", ".", "get_id", "(", ")", ")", ")", "self", ".", "node", ".", "append", "(", "term_obj", ".", "get_node", "(", ")", ")", "self", ".", "idx", "[", "term_obj", ".", "get_id", "(", ")", "]", "=", "term_obj" ]
Adds a term object to the layer @type term_obj: L{Cterm} @param term_obj: the term object
[ "Adds", "a", "term", "object", "to", "the", "layer" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/term_data.py#L338-L348
train
cltl/KafNafParserPy
KafNafParserPy/term_data.py
Cterms.add_external_reference
def add_external_reference(self,term_id, external_ref): """ Adds an external reference for the given term @type term_id: string @param term_id: the term identifier @type external_ref: L{CexternalReference} @param external_ref: the external reference object """ if term_id in self.idx: term_obj = Cterm(self.idx[term_id],self.type) term_obj.add_external_reference(external_ref) else: print('{term_id} not in self.idx'.format(**locals()))
python
def add_external_reference(self,term_id, external_ref): """ Adds an external reference for the given term @type term_id: string @param term_id: the term identifier @type external_ref: L{CexternalReference} @param external_ref: the external reference object """ if term_id in self.idx: term_obj = Cterm(self.idx[term_id],self.type) term_obj.add_external_reference(external_ref) else: print('{term_id} not in self.idx'.format(**locals()))
[ "def", "add_external_reference", "(", "self", ",", "term_id", ",", "external_ref", ")", ":", "if", "term_id", "in", "self", ".", "idx", ":", "term_obj", "=", "Cterm", "(", "self", ".", "idx", "[", "term_id", "]", ",", "self", ".", "type", ")", "term_obj", ".", "add_external_reference", "(", "external_ref", ")", "else", ":", "print", "(", "'{term_id} not in self.idx'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", ")" ]
Adds an external reference for the given term @type term_id: string @param term_id: the term identifier @type external_ref: L{CexternalReference} @param external_ref: the external reference object
[ "Adds", "an", "external", "reference", "for", "the", "given", "term" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/term_data.py#L350-L362
train
mjirik/imtools
imtools/select_label_qt.py
SelectLabelWidget.init_slab
def init_slab(self, slab=None, segmentation=None, voxelsize_mm=None, show_ok_button=False): """ Create widget with segmentation labels information used to select labels. :param slab: dict with label name and its id :param segmentation: 3D label ndarray :param voxelsize_mm: size of voxel in mm :return: """ self.segmentation = segmentation self.voxelsize_mm = voxelsize_mm from . import show_segmentation self.slab = show_segmentation.create_slab_from_segmentation( self.segmentation, slab=slab) if show_ok_button: ok_button = QPushButton("Ok") ok_button.clicked.connect(self._action_ok_button) self.superMainScrollLayout.addWidget(ok_button)
python
def init_slab(self, slab=None, segmentation=None, voxelsize_mm=None, show_ok_button=False): """ Create widget with segmentation labels information used to select labels. :param slab: dict with label name and its id :param segmentation: 3D label ndarray :param voxelsize_mm: size of voxel in mm :return: """ self.segmentation = segmentation self.voxelsize_mm = voxelsize_mm from . import show_segmentation self.slab = show_segmentation.create_slab_from_segmentation( self.segmentation, slab=slab) if show_ok_button: ok_button = QPushButton("Ok") ok_button.clicked.connect(self._action_ok_button) self.superMainScrollLayout.addWidget(ok_button)
[ "def", "init_slab", "(", "self", ",", "slab", "=", "None", ",", "segmentation", "=", "None", ",", "voxelsize_mm", "=", "None", ",", "show_ok_button", "=", "False", ")", ":", "self", ".", "segmentation", "=", "segmentation", "self", ".", "voxelsize_mm", "=", "voxelsize_mm", "from", ".", "import", "show_segmentation", "self", ".", "slab", "=", "show_segmentation", ".", "create_slab_from_segmentation", "(", "self", ".", "segmentation", ",", "slab", "=", "slab", ")", "if", "show_ok_button", ":", "ok_button", "=", "QPushButton", "(", "\"Ok\"", ")", "ok_button", ".", "clicked", ".", "connect", "(", "self", ".", "_action_ok_button", ")", "self", ".", "superMainScrollLayout", ".", "addWidget", "(", "ok_button", ")" ]
Create widget with segmentation labels information used to select labels. :param slab: dict with label name and its id :param segmentation: 3D label ndarray :param voxelsize_mm: size of voxel in mm :return:
[ "Create", "widget", "with", "segmentation", "labels", "information", "used", "to", "select", "labels", "." ]
eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/select_label_qt.py#L47-L67
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/server.py
Server.GetServers
def GetServers(location,group=None,alias=None,name_groups=False): """Gets a deep list of all Servers for a given Hardware Group and its sub groups, or all Servers for a given location. https://www.ctl.io/api-docs/v1/#server-getallservers :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param group: group name """ if alias is None: alias = clc.v1.Account.GetAlias() payload = {'AccountAlias': alias } if group: payload['HardwareGroupUUID'] = clc.v1.Group.GetGroupUUID(group,alias,location) else: payload['Location'] = location try: r = clc.v1.API.Call('post','Server/GetAllServers', payload) if name_groups: r['Servers'] = clc.v1.Group.NameGroups(r['Servers'],'HardwareGroupUUID') if int(r['StatusCode']) == 0: return(r['Servers']) except Exception as e: if str(e)=="Hardware does not exist for location": return([]) else: raise
python
def GetServers(location,group=None,alias=None,name_groups=False): """Gets a deep list of all Servers for a given Hardware Group and its sub groups, or all Servers for a given location. https://www.ctl.io/api-docs/v1/#server-getallservers :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param group: group name """ if alias is None: alias = clc.v1.Account.GetAlias() payload = {'AccountAlias': alias } if group: payload['HardwareGroupUUID'] = clc.v1.Group.GetGroupUUID(group,alias,location) else: payload['Location'] = location try: r = clc.v1.API.Call('post','Server/GetAllServers', payload) if name_groups: r['Servers'] = clc.v1.Group.NameGroups(r['Servers'],'HardwareGroupUUID') if int(r['StatusCode']) == 0: return(r['Servers']) except Exception as e: if str(e)=="Hardware does not exist for location": return([]) else: raise
[ "def", "GetServers", "(", "location", ",", "group", "=", "None", ",", "alias", "=", "None", ",", "name_groups", "=", "False", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "payload", "=", "{", "'AccountAlias'", ":", "alias", "}", "if", "group", ":", "payload", "[", "'HardwareGroupUUID'", "]", "=", "clc", ".", "v1", ".", "Group", ".", "GetGroupUUID", "(", "group", ",", "alias", ",", "location", ")", "else", ":", "payload", "[", "'Location'", "]", "=", "location", "try", ":", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Server/GetAllServers'", ",", "payload", ")", "if", "name_groups", ":", "r", "[", "'Servers'", "]", "=", "clc", ".", "v1", ".", "Group", ".", "NameGroups", "(", "r", "[", "'Servers'", "]", ",", "'HardwareGroupUUID'", ")", "if", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "return", "(", "r", "[", "'Servers'", "]", ")", "except", "Exception", "as", "e", ":", "if", "str", "(", "e", ")", "==", "\"Hardware does not exist for location\"", ":", "return", "(", "[", "]", ")", "else", ":", "raise" ]
Gets a deep list of all Servers for a given Hardware Group and its sub groups, or all Servers for a given location. https://www.ctl.io/api-docs/v1/#server-getallservers :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param group: group name
[ "Gets", "a", "deep", "list", "of", "all", "Servers", "for", "a", "given", "Hardware", "Group", "and", "its", "sub", "groups", "or", "all", "Servers", "for", "a", "given", "location", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/server.py#L37-L57
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/server.py
Server.GetAllServers
def GetAllServers(alias=None,name_groups=False): """Gets a deep list of all Servers in all groups and datacenters. :param alias: short code for a particular account. If none will use account's default alias """ if alias is None: alias = clc.v1.Account.GetAlias() servers = [] clc.v1.Account.GetLocations() for location in clc.LOCATIONS: try: r = clc.v1.API.Call('post','Server/GetAllServers', {'AccountAlias': alias, 'Location': location }, hide_errors=[5,] ) if name_groups: r['Servers'] = clc.v1.Group.NameGroups(r['Servers'],'HardwareGroupUUID') if int(r['StatusCode']) == 0: servers += r['Servers'] except: pass return(servers)
python
def GetAllServers(alias=None,name_groups=False): """Gets a deep list of all Servers in all groups and datacenters. :param alias: short code for a particular account. If none will use account's default alias """ if alias is None: alias = clc.v1.Account.GetAlias() servers = [] clc.v1.Account.GetLocations() for location in clc.LOCATIONS: try: r = clc.v1.API.Call('post','Server/GetAllServers', {'AccountAlias': alias, 'Location': location }, hide_errors=[5,] ) if name_groups: r['Servers'] = clc.v1.Group.NameGroups(r['Servers'],'HardwareGroupUUID') if int(r['StatusCode']) == 0: servers += r['Servers'] except: pass return(servers)
[ "def", "GetAllServers", "(", "alias", "=", "None", ",", "name_groups", "=", "False", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "servers", "=", "[", "]", "clc", ".", "v1", ".", "Account", ".", "GetLocations", "(", ")", "for", "location", "in", "clc", ".", "LOCATIONS", ":", "try", ":", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Server/GetAllServers'", ",", "{", "'AccountAlias'", ":", "alias", ",", "'Location'", ":", "location", "}", ",", "hide_errors", "=", "[", "5", ",", "]", ")", "if", "name_groups", ":", "r", "[", "'Servers'", "]", "=", "clc", ".", "v1", ".", "Group", ".", "NameGroups", "(", "r", "[", "'Servers'", "]", ",", "'HardwareGroupUUID'", ")", "if", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "servers", "+=", "r", "[", "'Servers'", "]", "except", ":", "pass", "return", "(", "servers", ")" ]
Gets a deep list of all Servers in all groups and datacenters. :param alias: short code for a particular account. If none will use account's default alias
[ "Gets", "a", "deep", "list", "of", "all", "Servers", "in", "all", "groups", "and", "datacenters", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/server.py#L61-L76
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/server.py
Server.GetTemplateID
def GetTemplateID(alias,location,name): """Given a template name return the unique OperatingSystem ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param name: template name """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() r = Server.GetTemplates(alias,location) for row in r: if row['Name'].lower() == name.lower(): return(row['OperatingSystem']) else: if clc.args: clc.v1.output.Status("ERROR",3,"Template %s not found in account %s datacenter %s" % (name,alias,location)) raise Exception("Template not found")
python
def GetTemplateID(alias,location,name): """Given a template name return the unique OperatingSystem ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param name: template name """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() r = Server.GetTemplates(alias,location) for row in r: if row['Name'].lower() == name.lower(): return(row['OperatingSystem']) else: if clc.args: clc.v1.output.Status("ERROR",3,"Template %s not found in account %s datacenter %s" % (name,alias,location)) raise Exception("Template not found")
[ "def", "GetTemplateID", "(", "alias", ",", "location", ",", "name", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "if", "location", "is", "None", ":", "location", "=", "clc", ".", "v1", ".", "Account", ".", "GetLocation", "(", ")", "r", "=", "Server", ".", "GetTemplates", "(", "alias", ",", "location", ")", "for", "row", "in", "r", ":", "if", "row", "[", "'Name'", "]", ".", "lower", "(", ")", "==", "name", ".", "lower", "(", ")", ":", "return", "(", "row", "[", "'OperatingSystem'", "]", ")", "else", ":", "if", "clc", ".", "args", ":", "clc", ".", "v1", ".", "output", ".", "Status", "(", "\"ERROR\"", ",", "3", ",", "\"Template %s not found in account %s datacenter %s\"", "%", "(", "name", ",", "alias", ",", "location", ")", ")", "raise", "Exception", "(", "\"Template not found\"", ")" ]
Given a template name return the unique OperatingSystem ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param name: template name
[ "Given", "a", "template", "name", "return", "the", "unique", "OperatingSystem", "ID", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/server.py#L96-L111
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/server.py
Server.ConvertToTemplate
def ConvertToTemplate(server,template,password=None,alias=None): """Converts an existing server into a template. http://www.centurylinkcloud.com/api-docs/v1/#server-convert-server-to-template :param server: source server to convert :param template: name of destination template :param password: source server password (optional - will lookup password if None) :param alias: short code for a particular account. If none will use account's default alias """ if alias is None: alias = clc.v1.Account.GetAlias() if password is None: password = clc.v1.Server.GetCredentials([server,],alias)[0]['Password'] r = clc.v1.API.Call('post','Server/ConvertServerToTemplate', { 'AccountAlias': alias, 'Name': server, 'Password': password, 'TemplateAlias': template }) return(r)
python
def ConvertToTemplate(server,template,password=None,alias=None): """Converts an existing server into a template. http://www.centurylinkcloud.com/api-docs/v1/#server-convert-server-to-template :param server: source server to convert :param template: name of destination template :param password: source server password (optional - will lookup password if None) :param alias: short code for a particular account. If none will use account's default alias """ if alias is None: alias = clc.v1.Account.GetAlias() if password is None: password = clc.v1.Server.GetCredentials([server,],alias)[0]['Password'] r = clc.v1.API.Call('post','Server/ConvertServerToTemplate', { 'AccountAlias': alias, 'Name': server, 'Password': password, 'TemplateAlias': template }) return(r)
[ "def", "ConvertToTemplate", "(", "server", ",", "template", ",", "password", "=", "None", ",", "alias", "=", "None", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "if", "password", "is", "None", ":", "password", "=", "clc", ".", "v1", ".", "Server", ".", "GetCredentials", "(", "[", "server", ",", "]", ",", "alias", ")", "[", "0", "]", "[", "'Password'", "]", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Server/ConvertServerToTemplate'", ",", "{", "'AccountAlias'", ":", "alias", ",", "'Name'", ":", "server", ",", "'Password'", ":", "password", ",", "'TemplateAlias'", ":", "template", "}", ")", "return", "(", "r", ")" ]
Converts an existing server into a template. http://www.centurylinkcloud.com/api-docs/v1/#server-convert-server-to-template :param server: source server to convert :param template: name of destination template :param password: source server password (optional - will lookup password if None) :param alias: short code for a particular account. If none will use account's default alias
[ "Converts", "an", "existing", "server", "into", "a", "template", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/server.py#L146-L161
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/server.py
Server.RestoreServer
def RestoreServer(server,group,alias,location): """Restores an archived server. https://www.centurylinkcloud.com/api-docs/v1/#restoreserver :param server: archived server to restore :param group: name of group or group ID for server to belong to :param alias: short code for a particular account. If None will use account's default alias :param location: datacenter where group resides. If None will use account's default location """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() if re.match("([a-zA-Z0-9]){32}",group.replace("-","")): groups_uuid = group else: groups_uuid = clc.v1.Group.GetGroupUUID(group,alias,location) r = clc.v1.API.Call('post','Server/RestoreServer', { 'AccountAlias': alias, 'Name': server, 'HardwareGroupUUID': groups_uuid }) if int(r['StatusCode']) == 0: return(r)
python
def RestoreServer(server,group,alias,location): """Restores an archived server. https://www.centurylinkcloud.com/api-docs/v1/#restoreserver :param server: archived server to restore :param group: name of group or group ID for server to belong to :param alias: short code for a particular account. If None will use account's default alias :param location: datacenter where group resides. If None will use account's default location """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() if re.match("([a-zA-Z0-9]){32}",group.replace("-","")): groups_uuid = group else: groups_uuid = clc.v1.Group.GetGroupUUID(group,alias,location) r = clc.v1.API.Call('post','Server/RestoreServer', { 'AccountAlias': alias, 'Name': server, 'HardwareGroupUUID': groups_uuid }) if int(r['StatusCode']) == 0: return(r)
[ "def", "RestoreServer", "(", "server", ",", "group", ",", "alias", ",", "location", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "if", "location", "is", "None", ":", "location", "=", "clc", ".", "v1", ".", "Account", ".", "GetLocation", "(", ")", "if", "re", ".", "match", "(", "\"([a-zA-Z0-9]){32}\"", ",", "group", ".", "replace", "(", "\"-\"", ",", "\"\"", ")", ")", ":", "groups_uuid", "=", "group", "else", ":", "groups_uuid", "=", "clc", ".", "v1", ".", "Group", ".", "GetGroupUUID", "(", "group", ",", "alias", ",", "location", ")", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Server/RestoreServer'", ",", "{", "'AccountAlias'", ":", "alias", ",", "'Name'", ":", "server", ",", "'HardwareGroupUUID'", ":", "groups_uuid", "}", ")", "if", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "return", "(", "r", ")" ]
Restores an archived server. https://www.centurylinkcloud.com/api-docs/v1/#restoreserver :param server: archived server to restore :param group: name of group or group ID for server to belong to :param alias: short code for a particular account. If None will use account's default alias :param location: datacenter where group resides. If None will use account's default location
[ "Restores", "an", "archived", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/server.py#L165-L182
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/server.py
Server._ServerActions
def _ServerActions(action,alias,servers): """Archives the specified servers. :param action: the server action url to exec against :param alias: short code for a particular account. If none will use account's default alias :param servers: list of server names """ if alias is None: alias = clc.v1.Account.GetAlias() results = [] for server in servers: r = clc.v1.API.Call('post','Server/%sServer' % (action), {'AccountAlias': alias, 'Name': server }) if int(r['StatusCode']) == 0: results.append(r) return(results)
python
def _ServerActions(action,alias,servers): """Archives the specified servers. :param action: the server action url to exec against :param alias: short code for a particular account. If none will use account's default alias :param servers: list of server names """ if alias is None: alias = clc.v1.Account.GetAlias() results = [] for server in servers: r = clc.v1.API.Call('post','Server/%sServer' % (action), {'AccountAlias': alias, 'Name': server }) if int(r['StatusCode']) == 0: results.append(r) return(results)
[ "def", "_ServerActions", "(", "action", ",", "alias", ",", "servers", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "results", "=", "[", "]", "for", "server", "in", "servers", ":", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Server/%sServer'", "%", "(", "action", ")", ",", "{", "'AccountAlias'", ":", "alias", ",", "'Name'", ":", "server", "}", ")", "if", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "results", ".", "append", "(", "r", ")", "return", "(", "results", ")" ]
Archives the specified servers. :param action: the server action url to exec against :param alias: short code for a particular account. If none will use account's default alias :param servers: list of server names
[ "Archives", "the", "specified", "servers", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/server.py#L187-L199
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/server.py
Server.GetDisks
def GetDisks(server,alias=None,guest_names=True): """Returns list of disks configured for the server https://www.ctl.io/api-docs/v1/#server-listdisks :param alias: short code for a particular account. If none will use account's default alias :param server: server name :param guest_names: query guest disk names and mount points """ if alias is None: alias = clc.v1.Account.GetAlias() r = clc.v1.API.Call('post','Server/ListDisks', { 'AccountAlias': alias, 'Name': server, 'QueryGuestDiskNames': guest_names } ) return(r['Disks'])
python
def GetDisks(server,alias=None,guest_names=True): """Returns list of disks configured for the server https://www.ctl.io/api-docs/v1/#server-listdisks :param alias: short code for a particular account. If none will use account's default alias :param server: server name :param guest_names: query guest disk names and mount points """ if alias is None: alias = clc.v1.Account.GetAlias() r = clc.v1.API.Call('post','Server/ListDisks', { 'AccountAlias': alias, 'Name': server, 'QueryGuestDiskNames': guest_names } ) return(r['Disks'])
[ "def", "GetDisks", "(", "server", ",", "alias", "=", "None", ",", "guest_names", "=", "True", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Server/ListDisks'", ",", "{", "'AccountAlias'", ":", "alias", ",", "'Name'", ":", "server", ",", "'QueryGuestDiskNames'", ":", "guest_names", "}", ")", "return", "(", "r", "[", "'Disks'", "]", ")" ]
Returns list of disks configured for the server https://www.ctl.io/api-docs/v1/#server-listdisks :param alias: short code for a particular account. If none will use account's default alias :param server: server name :param guest_names: query guest disk names and mount points
[ "Returns", "list", "of", "disks", "configured", "for", "the", "server" ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/server.py#L329-L341
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/server.py
Server.DeleteDisk
def DeleteDisk(server,scsi_bus_id,scsi_device_id,alias=None): """Deletes the specified disk. https://www.ctl.io/api-docs/v1/#server-delete-disk :param alias: short code for a particular account. If None will use account's default alias :param server: server name :param scsi_bus_id: bus ID associated with disk :param scsi_device_id: disk ID associated with disk """ if alias is None: alias = clc.v1.Account.GetAlias() r = clc.v1.API.Call('post','Server/DeleteDisk', {'AccountAlias': alias, 'Name': server, 'OverrideFailsafes': True, 'ScsiBusID': scsi_bus_id, 'ScsiDeviceID': scsi_device_id }) return(r)
python
def DeleteDisk(server,scsi_bus_id,scsi_device_id,alias=None): """Deletes the specified disk. https://www.ctl.io/api-docs/v1/#server-delete-disk :param alias: short code for a particular account. If None will use account's default alias :param server: server name :param scsi_bus_id: bus ID associated with disk :param scsi_device_id: disk ID associated with disk """ if alias is None: alias = clc.v1.Account.GetAlias() r = clc.v1.API.Call('post','Server/DeleteDisk', {'AccountAlias': alias, 'Name': server, 'OverrideFailsafes': True, 'ScsiBusID': scsi_bus_id, 'ScsiDeviceID': scsi_device_id }) return(r)
[ "def", "DeleteDisk", "(", "server", ",", "scsi_bus_id", ",", "scsi_device_id", ",", "alias", "=", "None", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Server/DeleteDisk'", ",", "{", "'AccountAlias'", ":", "alias", ",", "'Name'", ":", "server", ",", "'OverrideFailsafes'", ":", "True", ",", "'ScsiBusID'", ":", "scsi_bus_id", ",", "'ScsiDeviceID'", ":", "scsi_device_id", "}", ")", "return", "(", "r", ")" ]
Deletes the specified disk. https://www.ctl.io/api-docs/v1/#server-delete-disk :param alias: short code for a particular account. If None will use account's default alias :param server: server name :param scsi_bus_id: bus ID associated with disk :param scsi_device_id: disk ID associated with disk
[ "Deletes", "the", "specified", "disk", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/server.py#L345-L360
train
cltl/KafNafParserPy
KafNafParserPy/external_references_data.py
CexternalReferences.get_external_references
def get_external_references(self): """ Iterator that returns all the external reference objects of the external references object @rtype: L{CexternalReference} @return: the external reference objects """ for ext_ref_node in self.node.findall('externalRef'): ext_refs_obj = CexternalReference(ext_ref_node) for ref in ext_refs_obj: yield ref
python
def get_external_references(self): """ Iterator that returns all the external reference objects of the external references object @rtype: L{CexternalReference} @return: the external reference objects """ for ext_ref_node in self.node.findall('externalRef'): ext_refs_obj = CexternalReference(ext_ref_node) for ref in ext_refs_obj: yield ref
[ "def", "get_external_references", "(", "self", ")", ":", "for", "ext_ref_node", "in", "self", ".", "node", ".", "findall", "(", "'externalRef'", ")", ":", "ext_refs_obj", "=", "CexternalReference", "(", "ext_ref_node", ")", "for", "ref", "in", "ext_refs_obj", ":", "yield", "ref" ]
Iterator that returns all the external reference objects of the external references object @rtype: L{CexternalReference} @return: the external reference objects
[ "Iterator", "that", "returns", "all", "the", "external", "reference", "objects", "of", "the", "external", "references", "object" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/external_references_data.py#L184-L193
train
cltl/KafNafParserPy
KafNafParserPy/text_data.py
Cwf.set_id
def set_id(self,this_id): """ Set the identifier for the token @type this_id: string @param this_id: the identifier """ if self.type == 'NAF': return self.node.set('id',this_id) elif self.type == 'KAF': return self.node.set('wid',this_id)
python
def set_id(self,this_id): """ Set the identifier for the token @type this_id: string @param this_id: the identifier """ if self.type == 'NAF': return self.node.set('id',this_id) elif self.type == 'KAF': return self.node.set('wid',this_id)
[ "def", "set_id", "(", "self", ",", "this_id", ")", ":", "if", "self", ".", "type", "==", "'NAF'", ":", "return", "self", ".", "node", ".", "set", "(", "'id'", ",", "this_id", ")", "elif", "self", ".", "type", "==", "'KAF'", ":", "return", "self", ".", "node", ".", "set", "(", "'wid'", ",", "this_id", ")" ]
Set the identifier for the token @type this_id: string @param this_id: the identifier
[ "Set", "the", "identifier", "for", "the", "token" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/text_data.py#L34-L43
train
cltl/KafNafParserPy
KafNafParserPy/text_data.py
Ctext.to_naf
def to_naf(self): """ Converts the object to NAF """ if self.type == 'KAF': self.type = 'NAF' for node in self.__get_wf_nodes(): node.set('id',node.get('wid')) del node.attrib['wid']
python
def to_naf(self): """ Converts the object to NAF """ if self.type == 'KAF': self.type = 'NAF' for node in self.__get_wf_nodes(): node.set('id',node.get('wid')) del node.attrib['wid']
[ "def", "to_naf", "(", "self", ")", ":", "if", "self", ".", "type", "==", "'KAF'", ":", "self", ".", "type", "=", "'NAF'", "for", "node", "in", "self", ".", "__get_wf_nodes", "(", ")", ":", "node", ".", "set", "(", "'id'", ",", "node", ".", "get", "(", "'wid'", ")", ")", "del", "node", ".", "attrib", "[", "'wid'", "]" ]
Converts the object to NAF
[ "Converts", "the", "object", "to", "NAF" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/text_data.py#L212-L220
train
cltl/KafNafParserPy
KafNafParserPy/text_data.py
Ctext.get_wf
def get_wf(self,token_id): """ Returns the token object for the given token identifier @type token_id: string @param token_id: the token identifier @rtype: L{Cwf} @return: the token object """ wf_node = self.idx.get(token_id) if wf_node is not None: return Cwf(node=wf_node,type=self.type) else: for wf_node in self.__get_wf_nodes(): if self.type == 'NAF': label_id = 'id' elif self.type == 'KAF': label_id = 'wid' if wf_node.get(label_id) == token_id: return Cwf(node=wf_node, type=self.type) return None
python
def get_wf(self,token_id): """ Returns the token object for the given token identifier @type token_id: string @param token_id: the token identifier @rtype: L{Cwf} @return: the token object """ wf_node = self.idx.get(token_id) if wf_node is not None: return Cwf(node=wf_node,type=self.type) else: for wf_node in self.__get_wf_nodes(): if self.type == 'NAF': label_id = 'id' elif self.type == 'KAF': label_id = 'wid' if wf_node.get(label_id) == token_id: return Cwf(node=wf_node, type=self.type) return None
[ "def", "get_wf", "(", "self", ",", "token_id", ")", ":", "wf_node", "=", "self", ".", "idx", ".", "get", "(", "token_id", ")", "if", "wf_node", "is", "not", "None", ":", "return", "Cwf", "(", "node", "=", "wf_node", ",", "type", "=", "self", ".", "type", ")", "else", ":", "for", "wf_node", "in", "self", ".", "__get_wf_nodes", "(", ")", ":", "if", "self", ".", "type", "==", "'NAF'", ":", "label_id", "=", "'id'", "elif", "self", ".", "type", "==", "'KAF'", ":", "label_id", "=", "'wid'", "if", "wf_node", ".", "get", "(", "label_id", ")", "==", "token_id", ":", "return", "Cwf", "(", "node", "=", "wf_node", ",", "type", "=", "self", ".", "type", ")", "return", "None" ]
Returns the token object for the given token identifier @type token_id: string @param token_id: the token identifier @rtype: L{Cwf} @return: the token object
[ "Returns", "the", "token", "object", "for", "the", "given", "token", "identifier" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/text_data.py#L235-L252
train
cltl/KafNafParserPy
KafNafParserPy/text_data.py
Ctext.add_wf
def add_wf(self,wf_obj): """ Adds a token object to the text layer @type wf_obj: L{Cwf} @param wf_obj: token object """ if wf_obj.get_id() in self.idx: raise ValueError("Text node (wf) with id {} already exists!" .format(wf_obj.get_id())) self.node.append(wf_obj.get_node()) self.idx[wf_obj.get_id()] = wf_obj
python
def add_wf(self,wf_obj): """ Adds a token object to the text layer @type wf_obj: L{Cwf} @param wf_obj: token object """ if wf_obj.get_id() in self.idx: raise ValueError("Text node (wf) with id {} already exists!" .format(wf_obj.get_id())) self.node.append(wf_obj.get_node()) self.idx[wf_obj.get_id()] = wf_obj
[ "def", "add_wf", "(", "self", ",", "wf_obj", ")", ":", "if", "wf_obj", ".", "get_id", "(", ")", "in", "self", ".", "idx", ":", "raise", "ValueError", "(", "\"Text node (wf) with id {} already exists!\"", ".", "format", "(", "wf_obj", ".", "get_id", "(", ")", ")", ")", "self", ".", "node", ".", "append", "(", "wf_obj", ".", "get_node", "(", ")", ")", "self", ".", "idx", "[", "wf_obj", ".", "get_id", "(", ")", "]", "=", "wf_obj" ]
Adds a token object to the text layer @type wf_obj: L{Cwf} @param wf_obj: token object
[ "Adds", "a", "token", "object", "to", "the", "text", "layer" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/text_data.py#L254-L264
train
cltl/KafNafParserPy
KafNafParserPy/text_data.py
Ctext.remove_tokens_of_sentence
def remove_tokens_of_sentence(self,sentence_id): """ Removes the tokens of the given sentence @type sentence_id: string @param sentence_id: the sentence identifier """ nodes_to_remove = set() for wf in self: if wf.get_sent() == sentence_id: nodes_to_remove.add(wf.get_node()) for node in nodes_to_remove: self.node.remove(node)
python
def remove_tokens_of_sentence(self,sentence_id): """ Removes the tokens of the given sentence @type sentence_id: string @param sentence_id: the sentence identifier """ nodes_to_remove = set() for wf in self: if wf.get_sent() == sentence_id: nodes_to_remove.add(wf.get_node()) for node in nodes_to_remove: self.node.remove(node)
[ "def", "remove_tokens_of_sentence", "(", "self", ",", "sentence_id", ")", ":", "nodes_to_remove", "=", "set", "(", ")", "for", "wf", "in", "self", ":", "if", "wf", ".", "get_sent", "(", ")", "==", "sentence_id", ":", "nodes_to_remove", ".", "add", "(", "wf", ".", "get_node", "(", ")", ")", "for", "node", "in", "nodes_to_remove", ":", "self", ".", "node", ".", "remove", "(", "node", ")" ]
Removes the tokens of the given sentence @type sentence_id: string @param sentence_id: the sentence identifier
[ "Removes", "the", "tokens", "of", "the", "given", "sentence" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/text_data.py#L267-L279
train
Open-ET/openet-core-beta
openet/core/interp.py
aggregate_daily
def aggregate_daily(image_coll, start_date=None, end_date=None, agg_type='mean'): """Aggregate images by day without using joins The primary purpose of this function is to join separate Landsat images from the same path into a single daily image. Parameters ---------- image_coll : ee.ImageCollection Input image collection. start_date : date, number, string, optional Start date. Needs to be an EE readable date (i.e. ISO Date string or milliseconds). end_date : date, number, string, optional Exclusive end date. Needs to be an EE readable date (i.e. ISO Date string or milliseconds). agg_type : {'mean'}, optional Aggregation type (the default is 'mean'). Currently only a 'mean' aggregation type is supported. Returns ------- ee.ImageCollection() Notes ----- This function should be used to mosaic Landsat images from same path but different rows. system:time_start of returned images will be 0 UTC (not the image time). """ if start_date and end_date: test_coll = image_coll.filterDate(ee.Date(start_date), ee.Date(end_date)) elif start_date: test_coll = image_coll.filter(ee.Filter.greaterThanOrEquals( 'system:time_start', ee.Date(start_date).millis())) elif end_date: test_coll = image_coll.filter(ee.Filter.lessThan( 'system:time_start', ee.Date(end_date).millis())) else: test_coll = image_coll # Build a list of dates in the image_coll def get_date(time): return ee.Date(ee.Number(time)).format('yyyy-MM-dd') date_list = ee.List(test_coll.aggregate_array('system:time_start'))\ .map(get_date).distinct().sort() def aggregate_func(date_str): start_date = ee.Date(ee.String(date_str)) end_date = start_date.advance(1, 'day') agg_coll = image_coll.filterDate(start_date, end_date) # if agg_type.lower() == 'mean': agg_img = agg_coll.mean() # elif agg_type.lower() == 'median': # agg_img = agg_coll.median() return agg_img.set({ 'system:index': start_date.format('yyyyMMdd'), 'system:time_start': start_date.millis(), 'date': start_date.format('yyyy-MM-dd'), }) return ee.ImageCollection(date_list.map(aggregate_func))
python
def aggregate_daily(image_coll, start_date=None, end_date=None, agg_type='mean'): """Aggregate images by day without using joins The primary purpose of this function is to join separate Landsat images from the same path into a single daily image. Parameters ---------- image_coll : ee.ImageCollection Input image collection. start_date : date, number, string, optional Start date. Needs to be an EE readable date (i.e. ISO Date string or milliseconds). end_date : date, number, string, optional Exclusive end date. Needs to be an EE readable date (i.e. ISO Date string or milliseconds). agg_type : {'mean'}, optional Aggregation type (the default is 'mean'). Currently only a 'mean' aggregation type is supported. Returns ------- ee.ImageCollection() Notes ----- This function should be used to mosaic Landsat images from same path but different rows. system:time_start of returned images will be 0 UTC (not the image time). """ if start_date and end_date: test_coll = image_coll.filterDate(ee.Date(start_date), ee.Date(end_date)) elif start_date: test_coll = image_coll.filter(ee.Filter.greaterThanOrEquals( 'system:time_start', ee.Date(start_date).millis())) elif end_date: test_coll = image_coll.filter(ee.Filter.lessThan( 'system:time_start', ee.Date(end_date).millis())) else: test_coll = image_coll # Build a list of dates in the image_coll def get_date(time): return ee.Date(ee.Number(time)).format('yyyy-MM-dd') date_list = ee.List(test_coll.aggregate_array('system:time_start'))\ .map(get_date).distinct().sort() def aggregate_func(date_str): start_date = ee.Date(ee.String(date_str)) end_date = start_date.advance(1, 'day') agg_coll = image_coll.filterDate(start_date, end_date) # if agg_type.lower() == 'mean': agg_img = agg_coll.mean() # elif agg_type.lower() == 'median': # agg_img = agg_coll.median() return agg_img.set({ 'system:index': start_date.format('yyyyMMdd'), 'system:time_start': start_date.millis(), 'date': start_date.format('yyyy-MM-dd'), }) return ee.ImageCollection(date_list.map(aggregate_func))
[ "def", "aggregate_daily", "(", "image_coll", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "agg_type", "=", "'mean'", ")", ":", "if", "start_date", "and", "end_date", ":", "test_coll", "=", "image_coll", ".", "filterDate", "(", "ee", ".", "Date", "(", "start_date", ")", ",", "ee", ".", "Date", "(", "end_date", ")", ")", "elif", "start_date", ":", "test_coll", "=", "image_coll", ".", "filter", "(", "ee", ".", "Filter", ".", "greaterThanOrEquals", "(", "'system:time_start'", ",", "ee", ".", "Date", "(", "start_date", ")", ".", "millis", "(", ")", ")", ")", "elif", "end_date", ":", "test_coll", "=", "image_coll", ".", "filter", "(", "ee", ".", "Filter", ".", "lessThan", "(", "'system:time_start'", ",", "ee", ".", "Date", "(", "end_date", ")", ".", "millis", "(", ")", ")", ")", "else", ":", "test_coll", "=", "image_coll", "# Build a list of dates in the image_coll", "def", "get_date", "(", "time", ")", ":", "return", "ee", ".", "Date", "(", "ee", ".", "Number", "(", "time", ")", ")", ".", "format", "(", "'yyyy-MM-dd'", ")", "date_list", "=", "ee", ".", "List", "(", "test_coll", ".", "aggregate_array", "(", "'system:time_start'", ")", ")", ".", "map", "(", "get_date", ")", ".", "distinct", "(", ")", ".", "sort", "(", ")", "def", "aggregate_func", "(", "date_str", ")", ":", "start_date", "=", "ee", ".", "Date", "(", "ee", ".", "String", "(", "date_str", ")", ")", "end_date", "=", "start_date", ".", "advance", "(", "1", ",", "'day'", ")", "agg_coll", "=", "image_coll", ".", "filterDate", "(", "start_date", ",", "end_date", ")", "# if agg_type.lower() == 'mean':", "agg_img", "=", "agg_coll", ".", "mean", "(", ")", "# elif agg_type.lower() == 'median':", "# agg_img = agg_coll.median()", "return", "agg_img", ".", "set", "(", "{", "'system:index'", ":", "start_date", ".", "format", "(", "'yyyyMMdd'", ")", ",", "'system:time_start'", ":", "start_date", ".", "millis", "(", ")", ",", "'date'", ":", "start_date", ".", "format", "(", "'yyyy-MM-dd'", ")", ",", "}", ")", "return", "ee", ".", "ImageCollection", "(", "date_list", ".", "map", "(", "aggregate_func", ")", ")" ]
Aggregate images by day without using joins The primary purpose of this function is to join separate Landsat images from the same path into a single daily image. Parameters ---------- image_coll : ee.ImageCollection Input image collection. start_date : date, number, string, optional Start date. Needs to be an EE readable date (i.e. ISO Date string or milliseconds). end_date : date, number, string, optional Exclusive end date. Needs to be an EE readable date (i.e. ISO Date string or milliseconds). agg_type : {'mean'}, optional Aggregation type (the default is 'mean'). Currently only a 'mean' aggregation type is supported. Returns ------- ee.ImageCollection() Notes ----- This function should be used to mosaic Landsat images from same path but different rows. system:time_start of returned images will be 0 UTC (not the image time).
[ "Aggregate", "images", "by", "day", "without", "using", "joins" ]
f2b81ccf87bf7e7fe1b9f3dd1d4081d0ec7852db
https://github.com/Open-ET/openet-core-beta/blob/f2b81ccf87bf7e7fe1b9f3dd1d4081d0ec7852db/openet/core/interp.py#L161-L227
train
cltl/KafNafParserPy
KafNafParserPy/causal_data.py
CcausalRelations.remove_this_clink
def remove_this_clink(self,clink_id): """ Removes the clink for the given clink identifier @type clink_id: string @param clink_id: the clink identifier to be removed """ for clink in self.get_clinks(): if clink.get_id() == clink_id: self.node.remove(clink.get_node()) break
python
def remove_this_clink(self,clink_id): """ Removes the clink for the given clink identifier @type clink_id: string @param clink_id: the clink identifier to be removed """ for clink in self.get_clinks(): if clink.get_id() == clink_id: self.node.remove(clink.get_node()) break
[ "def", "remove_this_clink", "(", "self", ",", "clink_id", ")", ":", "for", "clink", "in", "self", ".", "get_clinks", "(", ")", ":", "if", "clink", ".", "get_id", "(", ")", "==", "clink_id", ":", "self", ".", "node", ".", "remove", "(", "clink", ".", "get_node", "(", ")", ")", "break" ]
Removes the clink for the given clink identifier @type clink_id: string @param clink_id: the clink identifier to be removed
[ "Removes", "the", "clink", "for", "the", "given", "clink", "identifier" ]
9bc32e803c176404b255ba317479b8780ed5f569
https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/causal_data.py#L156-L165
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/billing.py
Billing.GetGroupEstimate
def GetGroupEstimate(group,alias=None,location=None): """Gets estimated costs for a group of servers. https://t3n.zendesk.com/entries/22423906-GetGroupEstimate :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param group: group name """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() group_uuid = clc.v1.Group.GetGroupUUID(group,alias,location) r = clc.v1.API.Call('post','Billing/GetGroupEstimate',{'AccountAlias': alias, 'HardwareGroupUUID': group_uuid}) if int(r['StatusCode']) == 0: return(r)
python
def GetGroupEstimate(group,alias=None,location=None): """Gets estimated costs for a group of servers. https://t3n.zendesk.com/entries/22423906-GetGroupEstimate :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param group: group name """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() group_uuid = clc.v1.Group.GetGroupUUID(group,alias,location) r = clc.v1.API.Call('post','Billing/GetGroupEstimate',{'AccountAlias': alias, 'HardwareGroupUUID': group_uuid}) if int(r['StatusCode']) == 0: return(r)
[ "def", "GetGroupEstimate", "(", "group", ",", "alias", "=", "None", ",", "location", "=", "None", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "if", "location", "is", "None", ":", "location", "=", "clc", ".", "v1", ".", "Account", ".", "GetLocation", "(", ")", "group_uuid", "=", "clc", ".", "v1", ".", "Group", ".", "GetGroupUUID", "(", "group", ",", "alias", ",", "location", ")", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Billing/GetGroupEstimate'", ",", "{", "'AccountAlias'", ":", "alias", ",", "'HardwareGroupUUID'", ":", "group_uuid", "}", ")", "if", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "return", "(", "r", ")" ]
Gets estimated costs for a group of servers. https://t3n.zendesk.com/entries/22423906-GetGroupEstimate :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param group: group name
[ "Gets", "estimated", "costs", "for", "a", "group", "of", "servers", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/billing.py#L14-L29
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/billing.py
Billing.GetGroupSummaries
def GetGroupSummaries(alias=None,date_start=None,date_end=None): """Gets the charges for groups and servers within a given account, and for any date range. https://t3n.zendesk.com/entries/22423916-GetGroupSummaries :param alias: short code for a particular account. If none will use account's default alias :param date_start: YYYY-MM-DD string for start date. If None defaults to start of current month :param date_end: YYYY-MM-DD string for end date. If None defaults to current day of current month """ if alias is None: alias = clc.v1.Account.GetAlias() payload = {'AccountAlias': alias} if date_start is not None: payload['StartDate'] = date_start if date_end is not None: payload['EndDate'] = date_end r = clc.v1.API.Call('post','Billing/GetGroupSummaries',payload) if int(r['StatusCode']) == 0: return(r['GroupTotals'])
python
def GetGroupSummaries(alias=None,date_start=None,date_end=None): """Gets the charges for groups and servers within a given account, and for any date range. https://t3n.zendesk.com/entries/22423916-GetGroupSummaries :param alias: short code for a particular account. If none will use account's default alias :param date_start: YYYY-MM-DD string for start date. If None defaults to start of current month :param date_end: YYYY-MM-DD string for end date. If None defaults to current day of current month """ if alias is None: alias = clc.v1.Account.GetAlias() payload = {'AccountAlias': alias} if date_start is not None: payload['StartDate'] = date_start if date_end is not None: payload['EndDate'] = date_end r = clc.v1.API.Call('post','Billing/GetGroupSummaries',payload) if int(r['StatusCode']) == 0: return(r['GroupTotals'])
[ "def", "GetGroupSummaries", "(", "alias", "=", "None", ",", "date_start", "=", "None", ",", "date_end", "=", "None", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "payload", "=", "{", "'AccountAlias'", ":", "alias", "}", "if", "date_start", "is", "not", "None", ":", "payload", "[", "'StartDate'", "]", "=", "date_start", "if", "date_end", "is", "not", "None", ":", "payload", "[", "'EndDate'", "]", "=", "date_end", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Billing/GetGroupSummaries'", ",", "payload", ")", "if", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "return", "(", "r", "[", "'GroupTotals'", "]", ")" ]
Gets the charges for groups and servers within a given account, and for any date range. https://t3n.zendesk.com/entries/22423916-GetGroupSummaries :param alias: short code for a particular account. If none will use account's default alias :param date_start: YYYY-MM-DD string for start date. If None defaults to start of current month :param date_end: YYYY-MM-DD string for end date. If None defaults to current day of current month
[ "Gets", "the", "charges", "for", "groups", "and", "servers", "within", "a", "given", "account", "and", "for", "any", "date", "range", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/billing.py#L34-L50
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/billing.py
Billing.GetServerEstimate
def GetServerEstimate(server,alias=None): """Gets the estimated monthly cost for a given server. https://t3n.zendesk.com/entries/22422323-GetServerEstimate :param alias: short code for a particular account. If none will use account's default alias :param server: name of server to query """ if alias is None: alias = clc.v1.Account.GetAlias() r = clc.v1.API.Call('post','Billing/GetServerEstimate',{'AccountAlias': alias, 'ServerName': server}) if int(r['StatusCode']) == 0: return(r)
python
def GetServerEstimate(server,alias=None): """Gets the estimated monthly cost for a given server. https://t3n.zendesk.com/entries/22422323-GetServerEstimate :param alias: short code for a particular account. If none will use account's default alias :param server: name of server to query """ if alias is None: alias = clc.v1.Account.GetAlias() r = clc.v1.API.Call('post','Billing/GetServerEstimate',{'AccountAlias': alias, 'ServerName': server}) if int(r['StatusCode']) == 0: return(r)
[ "def", "GetServerEstimate", "(", "server", ",", "alias", "=", "None", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Billing/GetServerEstimate'", ",", "{", "'AccountAlias'", ":", "alias", ",", "'ServerName'", ":", "server", "}", ")", "if", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "return", "(", "r", ")" ]
Gets the estimated monthly cost for a given server. https://t3n.zendesk.com/entries/22422323-GetServerEstimate :param alias: short code for a particular account. If none will use account's default alias :param server: name of server to query
[ "Gets", "the", "estimated", "monthly", "cost", "for", "a", "given", "server", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/billing.py#L54-L65
train
nickpandolfi/Cyther
cyther/direct.py
display_direct
def display_direct(): """ Displays the output of 'get_direct_config', formatted nicely """ include_dirs, runtime_dirs, runtime = get_direct_config() print("Include Search Dirs: {}".format(include_dirs)) print("\tContents: {}\n".format(get_dir_contents(include_dirs))) print("Runtime Search Dirs: {}".format(runtime_dirs)) print("\tContents: {}\n".format(get_dir_contents(runtime_dirs))) print("Runtime Libs: '{}'".format(runtime))
python
def display_direct(): """ Displays the output of 'get_direct_config', formatted nicely """ include_dirs, runtime_dirs, runtime = get_direct_config() print("Include Search Dirs: {}".format(include_dirs)) print("\tContents: {}\n".format(get_dir_contents(include_dirs))) print("Runtime Search Dirs: {}".format(runtime_dirs)) print("\tContents: {}\n".format(get_dir_contents(runtime_dirs))) print("Runtime Libs: '{}'".format(runtime))
[ "def", "display_direct", "(", ")", ":", "include_dirs", ",", "runtime_dirs", ",", "runtime", "=", "get_direct_config", "(", ")", "print", "(", "\"Include Search Dirs: {}\"", ".", "format", "(", "include_dirs", ")", ")", "print", "(", "\"\\tContents: {}\\n\"", ".", "format", "(", "get_dir_contents", "(", "include_dirs", ")", ")", ")", "print", "(", "\"Runtime Search Dirs: {}\"", ".", "format", "(", "runtime_dirs", ")", ")", "print", "(", "\"\\tContents: {}\\n\"", ".", "format", "(", "get_dir_contents", "(", "runtime_dirs", ")", ")", ")", "print", "(", "\"Runtime Libs: '{}'\"", ".", "format", "(", "runtime", ")", ")" ]
Displays the output of 'get_direct_config', formatted nicely
[ "Displays", "the", "output", "of", "get_direct_config", "formatted", "nicely" ]
9fb0bd77af594008aa6ee8af460aa8c953abf5bc
https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/direct.py#L20-L30
train
mjirik/imtools
imtools/trainer3d.py
Trainer3D.save
def save(self, filename='saved.ol.p'): """ Save model to pickle file """ import dill as pickle sv = { # 'feature_function': self.feature_function, 'cl': self.cl } pickle.dump(sv, open(filename, "wb"))
python
def save(self, filename='saved.ol.p'): """ Save model to pickle file """ import dill as pickle sv = { # 'feature_function': self.feature_function, 'cl': self.cl } pickle.dump(sv, open(filename, "wb"))
[ "def", "save", "(", "self", ",", "filename", "=", "'saved.ol.p'", ")", ":", "import", "dill", "as", "pickle", "sv", "=", "{", "# 'feature_function': self.feature_function,", "'cl'", ":", "self", ".", "cl", "}", "pickle", ".", "dump", "(", "sv", ",", "open", "(", "filename", ",", "\"wb\"", ")", ")" ]
Save model to pickle file
[ "Save", "model", "to", "pickle", "file" ]
eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a
https://github.com/mjirik/imtools/blob/eb29fa59df0e0684d8334eb3bc5ef36ea46d1d3a/imtools/trainer3d.py#L36-L46
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/group.py
Group.GetGroupUUID
def GetGroupUUID(group,alias=None,location=None): """Given a group name return the unique group ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param group: group name """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() r = Group.GetGroups(location,alias) for row in r: if row['Name'] == group: return(row['UUID']) else: if clc.args: clc.v1.output.Status("ERROR",3,"Group %s not found in account %s datacenter %s" % (group,alias,location)) raise Exception("Group not found")
python
def GetGroupUUID(group,alias=None,location=None): """Given a group name return the unique group ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param group: group name """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() r = Group.GetGroups(location,alias) for row in r: if row['Name'] == group: return(row['UUID']) else: if clc.args: clc.v1.output.Status("ERROR",3,"Group %s not found in account %s datacenter %s" % (group,alias,location)) raise Exception("Group not found")
[ "def", "GetGroupUUID", "(", "group", ",", "alias", "=", "None", ",", "location", "=", "None", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "if", "location", "is", "None", ":", "location", "=", "clc", ".", "v1", ".", "Account", ".", "GetLocation", "(", ")", "r", "=", "Group", ".", "GetGroups", "(", "location", ",", "alias", ")", "for", "row", "in", "r", ":", "if", "row", "[", "'Name'", "]", "==", "group", ":", "return", "(", "row", "[", "'UUID'", "]", ")", "else", ":", "if", "clc", ".", "args", ":", "clc", ".", "v1", ".", "output", ".", "Status", "(", "\"ERROR\"", ",", "3", ",", "\"Group %s not found in account %s datacenter %s\"", "%", "(", "group", ",", "alias", ",", "location", ")", ")", "raise", "Exception", "(", "\"Group not found\"", ")" ]
Given a group name return the unique group ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param group: group name
[ "Given", "a", "group", "name", "return", "the", "unique", "group", "ID", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/group.py#L14-L28
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/group.py
Group.NameGroups
def NameGroups(data_arr,id_key): """Get group name associated with ID. TODO - not yet implemented """ new_data_arr = [] for data in data_arr: try: data_arr[id_key] = clc._GROUP_MAPPING[data[id_key]] except: pass new_data_arr.append(data) if clc.args: clc.v1.output.Status("ERROR",2,"Group name conversion not yet implemented") return(new_data_arr)
python
def NameGroups(data_arr,id_key): """Get group name associated with ID. TODO - not yet implemented """ new_data_arr = [] for data in data_arr: try: data_arr[id_key] = clc._GROUP_MAPPING[data[id_key]] except: pass new_data_arr.append(data) if clc.args: clc.v1.output.Status("ERROR",2,"Group name conversion not yet implemented") return(new_data_arr)
[ "def", "NameGroups", "(", "data_arr", ",", "id_key", ")", ":", "new_data_arr", "=", "[", "]", "for", "data", "in", "data_arr", ":", "try", ":", "data_arr", "[", "id_key", "]", "=", "clc", ".", "_GROUP_MAPPING", "[", "data", "[", "id_key", "]", "]", "except", ":", "pass", "new_data_arr", ".", "append", "(", "data", ")", "if", "clc", ".", "args", ":", "clc", ".", "v1", ".", "output", ".", "Status", "(", "\"ERROR\"", ",", "2", ",", "\"Group name conversion not yet implemented\"", ")", "return", "(", "new_data_arr", ")" ]
Get group name associated with ID. TODO - not yet implemented
[ "Get", "group", "name", "associated", "with", "ID", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/group.py#L33-L46
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/group.py
Group.GetGroups
def GetGroups(location=None,alias=None): """Return all of alias' groups in the given location. http://www.centurylinkcloud.com/api-docs/v2/#groups-get-group :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() r = clc.v1.API.Call('post','Group/GetGroups',{'AccountAlias': alias, 'Location': location}) for group in r['HardwareGroups']: clc._GROUP_MAPPING[group['UUID']] = group['Name'] if int(r['StatusCode']) == 0: return(r['HardwareGroups'])
python
def GetGroups(location=None,alias=None): """Return all of alias' groups in the given location. http://www.centurylinkcloud.com/api-docs/v2/#groups-get-group :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() r = clc.v1.API.Call('post','Group/GetGroups',{'AccountAlias': alias, 'Location': location}) for group in r['HardwareGroups']: clc._GROUP_MAPPING[group['UUID']] = group['Name'] if int(r['StatusCode']) == 0: return(r['HardwareGroups'])
[ "def", "GetGroups", "(", "location", "=", "None", ",", "alias", "=", "None", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "if", "location", "is", "None", ":", "location", "=", "clc", ".", "v1", ".", "Account", ".", "GetLocation", "(", ")", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Group/GetGroups'", ",", "{", "'AccountAlias'", ":", "alias", ",", "'Location'", ":", "location", "}", ")", "for", "group", "in", "r", "[", "'HardwareGroups'", "]", ":", "clc", ".", "_GROUP_MAPPING", "[", "group", "[", "'UUID'", "]", "]", "=", "group", "[", "'Name'", "]", "if", "int", "(", "r", "[", "'StatusCode'", "]", ")", "==", "0", ":", "return", "(", "r", "[", "'HardwareGroups'", "]", ")" ]
Return all of alias' groups in the given location. http://www.centurylinkcloud.com/api-docs/v2/#groups-get-group :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides
[ "Return", "all", "of", "alias", "groups", "in", "the", "given", "location", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/group.py#L50-L62
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv1/group.py
Group._GroupActions
def _GroupActions(action,group,alias,location): """Applies group level actions. :param action: the server action url to exec against :param group: group name :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter location. If none will use account's default alias """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() groups_uuid = Group.GetGroupUUID(group,alias,location) r = clc.v1.API.Call('post','Group/%sHardwareGroup' % (action), {'UUID': groups_uuid, 'AccountAlias': alias }) return(r)
python
def _GroupActions(action,group,alias,location): """Applies group level actions. :param action: the server action url to exec against :param group: group name :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter location. If none will use account's default alias """ if alias is None: alias = clc.v1.Account.GetAlias() if location is None: location = clc.v1.Account.GetLocation() groups_uuid = Group.GetGroupUUID(group,alias,location) r = clc.v1.API.Call('post','Group/%sHardwareGroup' % (action), {'UUID': groups_uuid, 'AccountAlias': alias }) return(r)
[ "def", "_GroupActions", "(", "action", ",", "group", ",", "alias", ",", "location", ")", ":", "if", "alias", "is", "None", ":", "alias", "=", "clc", ".", "v1", ".", "Account", ".", "GetAlias", "(", ")", "if", "location", "is", "None", ":", "location", "=", "clc", ".", "v1", ".", "Account", ".", "GetLocation", "(", ")", "groups_uuid", "=", "Group", ".", "GetGroupUUID", "(", "group", ",", "alias", ",", "location", ")", "r", "=", "clc", ".", "v1", ".", "API", ".", "Call", "(", "'post'", ",", "'Group/%sHardwareGroup'", "%", "(", "action", ")", ",", "{", "'UUID'", ":", "groups_uuid", ",", "'AccountAlias'", ":", "alias", "}", ")", "return", "(", "r", ")" ]
Applies group level actions. :param action: the server action url to exec against :param group: group name :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter location. If none will use account's default alias
[ "Applies", "group", "level", "actions", "." ]
f4dba40c627cb08dd4b7d0d277e8d67578010b05
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv1/group.py#L89-L102
train
sio2project/filetracker
filetracker/servers/base.py
get_endpoint_and_path
def get_endpoint_and_path(environ): """Extracts "endpoint" and "path" from the request URL. Endpoint is the first path component, and path is the rest. Both of them are without leading slashes. """ path = environ['PATH_INFO'] components = path.split('/') if '..' in components: raise HttpError('400 Bad Request', 'Path cannot contain "..".') # Strip closing slash if components and components[-1] == '': components.pop() # If path contained '//', get the segment after the last occurence try: first = _rindex(components, '') + 1 except ValueError: first = 0 components = components[first:] if len(components) == 0: return '', '' else: return components[0], '/'.join(components[1:])
python
def get_endpoint_and_path(environ): """Extracts "endpoint" and "path" from the request URL. Endpoint is the first path component, and path is the rest. Both of them are without leading slashes. """ path = environ['PATH_INFO'] components = path.split('/') if '..' in components: raise HttpError('400 Bad Request', 'Path cannot contain "..".') # Strip closing slash if components and components[-1] == '': components.pop() # If path contained '//', get the segment after the last occurence try: first = _rindex(components, '') + 1 except ValueError: first = 0 components = components[first:] if len(components) == 0: return '', '' else: return components[0], '/'.join(components[1:])
[ "def", "get_endpoint_and_path", "(", "environ", ")", ":", "path", "=", "environ", "[", "'PATH_INFO'", "]", "components", "=", "path", ".", "split", "(", "'/'", ")", "if", "'..'", "in", "components", ":", "raise", "HttpError", "(", "'400 Bad Request'", ",", "'Path cannot contain \"..\".'", ")", "# Strip closing slash", "if", "components", "and", "components", "[", "-", "1", "]", "==", "''", ":", "components", ".", "pop", "(", ")", "# If path contained '//', get the segment after the last occurence", "try", ":", "first", "=", "_rindex", "(", "components", ",", "''", ")", "+", "1", "except", "ValueError", ":", "first", "=", "0", "components", "=", "components", "[", "first", ":", "]", "if", "len", "(", "components", ")", "==", "0", ":", "return", "''", ",", "''", "else", ":", "return", "components", "[", "0", "]", ",", "'/'", ".", "join", "(", "components", "[", "1", ":", "]", ")" ]
Extracts "endpoint" and "path" from the request URL. Endpoint is the first path component, and path is the rest. Both of them are without leading slashes.
[ "Extracts", "endpoint", "and", "path", "from", "the", "request", "URL", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/servers/base.py#L63-L90
train
srossross/rpmfile
rpmfile/cpiofile.py
StructBase.pack
def pack(self): """convenience function for packing""" block = bytearray(self.size) self.pack_into(block) return block
python
def pack(self): """convenience function for packing""" block = bytearray(self.size) self.pack_into(block) return block
[ "def", "pack", "(", "self", ")", ":", "block", "=", "bytearray", "(", "self", ".", "size", ")", "self", ".", "pack_into", "(", "block", ")", "return", "block" ]
convenience function for packing
[ "convenience", "function", "for", "packing" ]
3ab96f211da7b56f5e99d8cc248f714a6e542d31
https://github.com/srossross/rpmfile/blob/3ab96f211da7b56f5e99d8cc248f714a6e542d31/rpmfile/cpiofile.py#L108-L112
train
srossross/rpmfile
rpmfile/cpiofile.py
CpioMember.encoded_class
def encoded_class(block, offset=0): """ predicate indicating whether a block of memory includes a magic number """ if not block: raise InvalidFileFormatNull for key in __magicmap__: if block.find(key, offset, offset + len(key)) > -1: return __magicmap__[key] raise InvalidFileFormat
python
def encoded_class(block, offset=0): """ predicate indicating whether a block of memory includes a magic number """ if not block: raise InvalidFileFormatNull for key in __magicmap__: if block.find(key, offset, offset + len(key)) > -1: return __magicmap__[key] raise InvalidFileFormat
[ "def", "encoded_class", "(", "block", ",", "offset", "=", "0", ")", ":", "if", "not", "block", ":", "raise", "InvalidFileFormatNull", "for", "key", "in", "__magicmap__", ":", "if", "block", ".", "find", "(", "key", ",", "offset", ",", "offset", "+", "len", "(", "key", ")", ")", ">", "-", "1", ":", "return", "__magicmap__", "[", "key", "]", "raise", "InvalidFileFormat" ]
predicate indicating whether a block of memory includes a magic number
[ "predicate", "indicating", "whether", "a", "block", "of", "memory", "includes", "a", "magic", "number" ]
3ab96f211da7b56f5e99d8cc248f714a6e542d31
https://github.com/srossross/rpmfile/blob/3ab96f211da7b56f5e99d8cc248f714a6e542d31/rpmfile/cpiofile.py#L295-L306
train
sio2project/filetracker
filetracker/servers/storage.py
_copy_stream
def _copy_stream(src, dest, length=0): """Similar to shutil.copyfileobj, but supports limiting data size. As for why this is required, refer to https://www.python.org/dev/peps/pep-0333/#input-and-error-streams Yes, there are WSGI implementations which do not support EOFs, and believe me, you don't want to debug this. Args: src: source file-like object dest: destination file-like object length: optional file size hint If not 0, exactly length bytes will be written. If 0, write will continue until EOF is encountered. """ if length == 0: shutil.copyfileobj(src, dest) return bytes_left = length while bytes_left > 0: buf_size = min(_BUFFER_SIZE, bytes_left) buf = src.read(buf_size) dest.write(buf) bytes_left -= buf_size
python
def _copy_stream(src, dest, length=0): """Similar to shutil.copyfileobj, but supports limiting data size. As for why this is required, refer to https://www.python.org/dev/peps/pep-0333/#input-and-error-streams Yes, there are WSGI implementations which do not support EOFs, and believe me, you don't want to debug this. Args: src: source file-like object dest: destination file-like object length: optional file size hint If not 0, exactly length bytes will be written. If 0, write will continue until EOF is encountered. """ if length == 0: shutil.copyfileobj(src, dest) return bytes_left = length while bytes_left > 0: buf_size = min(_BUFFER_SIZE, bytes_left) buf = src.read(buf_size) dest.write(buf) bytes_left -= buf_size
[ "def", "_copy_stream", "(", "src", ",", "dest", ",", "length", "=", "0", ")", ":", "if", "length", "==", "0", ":", "shutil", ".", "copyfileobj", "(", "src", ",", "dest", ")", "return", "bytes_left", "=", "length", "while", "bytes_left", ">", "0", ":", "buf_size", "=", "min", "(", "_BUFFER_SIZE", ",", "bytes_left", ")", "buf", "=", "src", ".", "read", "(", "buf_size", ")", "dest", ".", "write", "(", "buf", ")", "bytes_left", "-=", "buf_size" ]
Similar to shutil.copyfileobj, but supports limiting data size. As for why this is required, refer to https://www.python.org/dev/peps/pep-0333/#input-and-error-streams Yes, there are WSGI implementations which do not support EOFs, and believe me, you don't want to debug this. Args: src: source file-like object dest: destination file-like object length: optional file size hint If not 0, exactly length bytes will be written. If 0, write will continue until EOF is encountered.
[ "Similar", "to", "shutil", ".", "copyfileobj", "but", "supports", "limiting", "data", "size", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/servers/storage.py#L375-L400
train
sio2project/filetracker
filetracker/servers/storage.py
_path_exists
def _path_exists(path): """Checks if the path exists - is a file, a directory or a symbolic link that may be broken.""" return os.path.exists(path) or os.path.islink(path)
python
def _path_exists(path): """Checks if the path exists - is a file, a directory or a symbolic link that may be broken.""" return os.path.exists(path) or os.path.islink(path)
[ "def", "_path_exists", "(", "path", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "path", ")", "or", "os", ".", "path", ".", "islink", "(", "path", ")" ]
Checks if the path exists - is a file, a directory or a symbolic link that may be broken.
[ "Checks", "if", "the", "path", "exists", "-", "is", "a", "file", "a", "directory", "or", "a", "symbolic", "link", "that", "may", "be", "broken", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/servers/storage.py#L420-L423
train
sio2project/filetracker
filetracker/servers/storage.py
_exclusive_lock
def _exclusive_lock(path): """A simple wrapper for fcntl exclusive lock.""" _create_file_dirs(path) fd = os.open(path, os.O_WRONLY | os.O_CREAT, 0o600) try: retries_left = _LOCK_RETRIES success = False while retries_left > 0: # try to acquire the lock in a loop # because gevent doesn't treat flock as IO, # so waiting here without yielding would get the worker killed try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) success = True break except IOError as e: if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]: # This yields execution to other green threads. gevent.sleep(_LOCK_SLEEP_TIME_S) retries_left -= 1 else: raise if success: yield else: raise ConcurrentModificationError(path) finally: if success: fcntl.flock(fd, fcntl.LOCK_UN) os.close(fd)
python
def _exclusive_lock(path): """A simple wrapper for fcntl exclusive lock.""" _create_file_dirs(path) fd = os.open(path, os.O_WRONLY | os.O_CREAT, 0o600) try: retries_left = _LOCK_RETRIES success = False while retries_left > 0: # try to acquire the lock in a loop # because gevent doesn't treat flock as IO, # so waiting here without yielding would get the worker killed try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) success = True break except IOError as e: if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK]: # This yields execution to other green threads. gevent.sleep(_LOCK_SLEEP_TIME_S) retries_left -= 1 else: raise if success: yield else: raise ConcurrentModificationError(path) finally: if success: fcntl.flock(fd, fcntl.LOCK_UN) os.close(fd)
[ "def", "_exclusive_lock", "(", "path", ")", ":", "_create_file_dirs", "(", "path", ")", "fd", "=", "os", ".", "open", "(", "path", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREAT", ",", "0o600", ")", "try", ":", "retries_left", "=", "_LOCK_RETRIES", "success", "=", "False", "while", "retries_left", ">", "0", ":", "# try to acquire the lock in a loop", "# because gevent doesn't treat flock as IO,", "# so waiting here without yielding would get the worker killed", "try", ":", "fcntl", ".", "flock", "(", "fd", ",", "fcntl", ".", "LOCK_EX", "|", "fcntl", ".", "LOCK_NB", ")", "success", "=", "True", "break", "except", "IOError", "as", "e", ":", "if", "e", ".", "errno", "in", "[", "errno", ".", "EAGAIN", ",", "errno", ".", "EWOULDBLOCK", "]", ":", "# This yields execution to other green threads.", "gevent", ".", "sleep", "(", "_LOCK_SLEEP_TIME_S", ")", "retries_left", "-=", "1", "else", ":", "raise", "if", "success", ":", "yield", "else", ":", "raise", "ConcurrentModificationError", "(", "path", ")", "finally", ":", "if", "success", ":", "fcntl", ".", "flock", "(", "fd", ",", "fcntl", ".", "LOCK_UN", ")", "os", ".", "close", "(", "fd", ")" ]
A simple wrapper for fcntl exclusive lock.
[ "A", "simple", "wrapper", "for", "fcntl", "exclusive", "lock", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/servers/storage.py#L431-L463
train
sio2project/filetracker
filetracker/servers/storage.py
FileStorage.delete
def delete(self, name, version, _lock=True): """Removes a file from the storage. Args: name: name of the file being deleted. May contain slashes that are treated as path separators. version: file "version" that is meant to be deleted If the file that is stored has newer version than provided, it will not be deleted. lock: whether or not to acquire locks This is for internal use only, normal users should always leave it set to True. Returns whether or not the file has been deleted. """ link_path = self._link_path(name) if _lock: file_lock = _exclusive_lock(self._lock_path('links', name)) else: file_lock = _no_lock() with file_lock: logger.debug('Acquired or inherited lock for link %s.', name) if not _path_exists(link_path): raise FiletrackerFileNotFoundError if _file_version(link_path) > version: logger.info( 'Tried to delete newer version of %s (%d < %d), ignoring.', name, version, _file_version(link_path)) return False digest = self._digest_for_link(name) with _exclusive_lock(self._lock_path('blobs', digest)): logger.debug('Acquired lock for blob %s.', digest) should_delete_blob = False with self._db_transaction() as txn: logger.debug('Started DB transaction (deleting link).') digest_bytes = digest.encode() link_count = self.db.get(digest_bytes, txn=txn) if link_count is None: raise RuntimeError("File exists but has no key in db") link_count = int(link_count) if link_count == 1: logger.debug('Deleting last link to blob %s.', digest) self.db.delete(digest_bytes, txn=txn) self.db.delete( '{}:logical_size'.format(digest).encode(), txn=txn) should_delete_blob = True else: new_count = str(link_count - 1).encode() self.db.put(digest_bytes, new_count, txn=txn) logger.debug('Committing DB transaction (deleting link).') logger.debug('Committed DB transaction (deleting link).') os.unlink(link_path) logger.debug('Deleted link %s.', name) if should_delete_blob: os.unlink(self._blob_path(digest)) logger.debug('Released lock for blob %s.', digest) logger.debug('Released (or gave back) lock for link %s.', name) return True
python
def delete(self, name, version, _lock=True): """Removes a file from the storage. Args: name: name of the file being deleted. May contain slashes that are treated as path separators. version: file "version" that is meant to be deleted If the file that is stored has newer version than provided, it will not be deleted. lock: whether or not to acquire locks This is for internal use only, normal users should always leave it set to True. Returns whether or not the file has been deleted. """ link_path = self._link_path(name) if _lock: file_lock = _exclusive_lock(self._lock_path('links', name)) else: file_lock = _no_lock() with file_lock: logger.debug('Acquired or inherited lock for link %s.', name) if not _path_exists(link_path): raise FiletrackerFileNotFoundError if _file_version(link_path) > version: logger.info( 'Tried to delete newer version of %s (%d < %d), ignoring.', name, version, _file_version(link_path)) return False digest = self._digest_for_link(name) with _exclusive_lock(self._lock_path('blobs', digest)): logger.debug('Acquired lock for blob %s.', digest) should_delete_blob = False with self._db_transaction() as txn: logger.debug('Started DB transaction (deleting link).') digest_bytes = digest.encode() link_count = self.db.get(digest_bytes, txn=txn) if link_count is None: raise RuntimeError("File exists but has no key in db") link_count = int(link_count) if link_count == 1: logger.debug('Deleting last link to blob %s.', digest) self.db.delete(digest_bytes, txn=txn) self.db.delete( '{}:logical_size'.format(digest).encode(), txn=txn) should_delete_blob = True else: new_count = str(link_count - 1).encode() self.db.put(digest_bytes, new_count, txn=txn) logger.debug('Committing DB transaction (deleting link).') logger.debug('Committed DB transaction (deleting link).') os.unlink(link_path) logger.debug('Deleted link %s.', name) if should_delete_blob: os.unlink(self._blob_path(digest)) logger.debug('Released lock for blob %s.', digest) logger.debug('Released (or gave back) lock for link %s.', name) return True
[ "def", "delete", "(", "self", ",", "name", ",", "version", ",", "_lock", "=", "True", ")", ":", "link_path", "=", "self", ".", "_link_path", "(", "name", ")", "if", "_lock", ":", "file_lock", "=", "_exclusive_lock", "(", "self", ".", "_lock_path", "(", "'links'", ",", "name", ")", ")", "else", ":", "file_lock", "=", "_no_lock", "(", ")", "with", "file_lock", ":", "logger", ".", "debug", "(", "'Acquired or inherited lock for link %s.'", ",", "name", ")", "if", "not", "_path_exists", "(", "link_path", ")", ":", "raise", "FiletrackerFileNotFoundError", "if", "_file_version", "(", "link_path", ")", ">", "version", ":", "logger", ".", "info", "(", "'Tried to delete newer version of %s (%d < %d), ignoring.'", ",", "name", ",", "version", ",", "_file_version", "(", "link_path", ")", ")", "return", "False", "digest", "=", "self", ".", "_digest_for_link", "(", "name", ")", "with", "_exclusive_lock", "(", "self", ".", "_lock_path", "(", "'blobs'", ",", "digest", ")", ")", ":", "logger", ".", "debug", "(", "'Acquired lock for blob %s.'", ",", "digest", ")", "should_delete_blob", "=", "False", "with", "self", ".", "_db_transaction", "(", ")", "as", "txn", ":", "logger", ".", "debug", "(", "'Started DB transaction (deleting link).'", ")", "digest_bytes", "=", "digest", ".", "encode", "(", ")", "link_count", "=", "self", ".", "db", ".", "get", "(", "digest_bytes", ",", "txn", "=", "txn", ")", "if", "link_count", "is", "None", ":", "raise", "RuntimeError", "(", "\"File exists but has no key in db\"", ")", "link_count", "=", "int", "(", "link_count", ")", "if", "link_count", "==", "1", ":", "logger", ".", "debug", "(", "'Deleting last link to blob %s.'", ",", "digest", ")", "self", ".", "db", ".", "delete", "(", "digest_bytes", ",", "txn", "=", "txn", ")", "self", ".", "db", ".", "delete", "(", "'{}:logical_size'", ".", "format", "(", "digest", ")", ".", "encode", "(", ")", ",", "txn", "=", "txn", ")", "should_delete_blob", "=", "True", "else", ":", "new_count", "=", "str", "(", "link_count", "-", "1", ")", ".", "encode", "(", ")", "self", ".", "db", ".", "put", "(", "digest_bytes", ",", "new_count", ",", "txn", "=", "txn", ")", "logger", ".", "debug", "(", "'Committing DB transaction (deleting link).'", ")", "logger", ".", "debug", "(", "'Committed DB transaction (deleting link).'", ")", "os", ".", "unlink", "(", "link_path", ")", "logger", ".", "debug", "(", "'Deleted link %s.'", ",", "name", ")", "if", "should_delete_blob", ":", "os", ".", "unlink", "(", "self", ".", "_blob_path", "(", "digest", ")", ")", "logger", ".", "debug", "(", "'Released lock for blob %s.'", ",", "digest", ")", "logger", ".", "debug", "(", "'Released (or gave back) lock for link %s.'", ",", "name", ")", "return", "True" ]
Removes a file from the storage. Args: name: name of the file being deleted. May contain slashes that are treated as path separators. version: file "version" that is meant to be deleted If the file that is stored has newer version than provided, it will not be deleted. lock: whether or not to acquire locks This is for internal use only, normal users should always leave it set to True. Returns whether or not the file has been deleted.
[ "Removes", "a", "file", "from", "the", "storage", "." ]
359b474850622e3d0c25ee2596d7242c02f84efb
https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/servers/storage.py#L222-L287
train