id
int32
0
252k
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
247,800
KnowledgeLinks/rdfframework
rdfframework/utilities/codetimer.py
CodeTimer.log
def log(self, timer_name, node): ''' logs a event in the timer ''' timestamp = time.time() if hasattr(self, timer_name): getattr(self, timer_name).append({ "node":node, "time":timestamp}) else: setattr(self, timer_name, [{"node":node, "time":timestamp}])
python
def log(self, timer_name, node): ''' logs a event in the timer ''' timestamp = time.time() if hasattr(self, timer_name): getattr(self, timer_name).append({ "node":node, "time":timestamp}) else: setattr(self, timer_name, [{"node":node, "time":timestamp}])
[ "def", "log", "(", "self", ",", "timer_name", ",", "node", ")", ":", "timestamp", "=", "time", ".", "time", "(", ")", "if", "hasattr", "(", "self", ",", "timer_name", ")", ":", "getattr", "(", "self", ",", "timer_name", ")", ".", "append", "(", "{", "\"node\"", ":", "node", ",", "\"time\"", ":", "timestamp", "}", ")", "else", ":", "setattr", "(", "self", ",", "timer_name", ",", "[", "{", "\"node\"", ":", "node", ",", "\"time\"", ":", "timestamp", "}", "]", ")" ]
logs a event in the timer
[ "logs", "a", "event", "in", "the", "timer" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/codetimer.py#L16-L24
247,801
KnowledgeLinks/rdfframework
rdfframework/utilities/codetimer.py
CodeTimer.print_timer
def print_timer(self, timer_name, **kwargs): ''' prints the timer to the terminal keyword args: delete -> True/False -deletes the timer after printing ''' if hasattr(self, timer_name): _delete_timer = kwargs.get("delete", False) print("|-------- {} [Time Log Calculation]-----------------|".format(\ timer_name)) print("StartDiff\tLastNodeDiff\tNodeName") time_log = getattr(self, timer_name) start_time = time_log[0]['time'] previous_time = start_time for entry in time_log: time_diff = (entry['time'] - previous_time) *1000 time_from_start = (entry['time'] - start_time) * 1000 previous_time = entry['time'] print("{:.1f}\t\t{:.1f}\t\t{}".format(time_from_start, time_diff, entry['node'])) print("|--------------------------------------------------------|") if _delete_timer: self.delete_timer(timer_name)
python
def print_timer(self, timer_name, **kwargs): ''' prints the timer to the terminal keyword args: delete -> True/False -deletes the timer after printing ''' if hasattr(self, timer_name): _delete_timer = kwargs.get("delete", False) print("|-------- {} [Time Log Calculation]-----------------|".format(\ timer_name)) print("StartDiff\tLastNodeDiff\tNodeName") time_log = getattr(self, timer_name) start_time = time_log[0]['time'] previous_time = start_time for entry in time_log: time_diff = (entry['time'] - previous_time) *1000 time_from_start = (entry['time'] - start_time) * 1000 previous_time = entry['time'] print("{:.1f}\t\t{:.1f}\t\t{}".format(time_from_start, time_diff, entry['node'])) print("|--------------------------------------------------------|") if _delete_timer: self.delete_timer(timer_name)
[ "def", "print_timer", "(", "self", ",", "timer_name", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "timer_name", ")", ":", "_delete_timer", "=", "kwargs", ".", "get", "(", "\"delete\"", ",", "False", ")", "print", "(", "\"|-------- {} [Time Log Calculation]-----------------|\"", ".", "format", "(", "timer_name", ")", ")", "print", "(", "\"StartDiff\\tLastNodeDiff\\tNodeName\"", ")", "time_log", "=", "getattr", "(", "self", ",", "timer_name", ")", "start_time", "=", "time_log", "[", "0", "]", "[", "'time'", "]", "previous_time", "=", "start_time", "for", "entry", "in", "time_log", ":", "time_diff", "=", "(", "entry", "[", "'time'", "]", "-", "previous_time", ")", "*", "1000", "time_from_start", "=", "(", "entry", "[", "'time'", "]", "-", "start_time", ")", "*", "1000", "previous_time", "=", "entry", "[", "'time'", "]", "print", "(", "\"{:.1f}\\t\\t{:.1f}\\t\\t{}\"", ".", "format", "(", "time_from_start", ",", "time_diff", ",", "entry", "[", "'node'", "]", ")", ")", "print", "(", "\"|--------------------------------------------------------|\"", ")", "if", "_delete_timer", ":", "self", ".", "delete_timer", "(", "timer_name", ")" ]
prints the timer to the terminal keyword args: delete -> True/False -deletes the timer after printing
[ "prints", "the", "timer", "to", "the", "terminal" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/codetimer.py#L25-L48
247,802
townsenddw/jhubctl
jhubctl/clusters/clusters.py
ClusterList.check_cluster_exists
def check_cluster_exists(self, name): """Check if cluster exists. If it does not, raise exception.""" self.kubeconf.open() clusters = self.kubeconf.get_clusters() names = [c['name'] for c in clusters] if name in names: return True return False
python
def check_cluster_exists(self, name): """Check if cluster exists. If it does not, raise exception.""" self.kubeconf.open() clusters = self.kubeconf.get_clusters() names = [c['name'] for c in clusters] if name in names: return True return False
[ "def", "check_cluster_exists", "(", "self", ",", "name", ")", ":", "self", ".", "kubeconf", ".", "open", "(", ")", "clusters", "=", "self", ".", "kubeconf", ".", "get_clusters", "(", ")", "names", "=", "[", "c", "[", "'name'", "]", "for", "c", "in", "clusters", "]", "if", "name", "in", "names", ":", "return", "True", "return", "False" ]
Check if cluster exists. If it does not, raise exception.
[ "Check", "if", "cluster", "exists", ".", "If", "it", "does", "not", "raise", "exception", "." ]
c8c20f86a16e9d01dd90e4607d81423417cc773b
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/clusters.py#L14-L21
247,803
townsenddw/jhubctl
jhubctl/clusters/clusters.py
ClusterList.get
def get(self, name=None, provider='AwsEKS', print_output=True): """List all cluster. """ # Create cluster object Cluster = getattr(providers, provider) cluster = Cluster(name) self.kubeconf.open() if name is None: clusters = self.kubeconf.get_clusters() print("Running Clusters:") for cluster in clusters: print(f" - {cluster['name']}") else: # Check that cluster exists. if self.check_cluster_exists(name) is False: raise JhubctlError("Cluster name not found in availabe clusters.") cluster = self.kubeconf.get_cluster(name=cluster.cluster_name) pprint.pprint(cluster, depth=4)
python
def get(self, name=None, provider='AwsEKS', print_output=True): """List all cluster. """ # Create cluster object Cluster = getattr(providers, provider) cluster = Cluster(name) self.kubeconf.open() if name is None: clusters = self.kubeconf.get_clusters() print("Running Clusters:") for cluster in clusters: print(f" - {cluster['name']}") else: # Check that cluster exists. if self.check_cluster_exists(name) is False: raise JhubctlError("Cluster name not found in availabe clusters.") cluster = self.kubeconf.get_cluster(name=cluster.cluster_name) pprint.pprint(cluster, depth=4)
[ "def", "get", "(", "self", ",", "name", "=", "None", ",", "provider", "=", "'AwsEKS'", ",", "print_output", "=", "True", ")", ":", "# Create cluster object", "Cluster", "=", "getattr", "(", "providers", ",", "provider", ")", "cluster", "=", "Cluster", "(", "name", ")", "self", ".", "kubeconf", ".", "open", "(", ")", "if", "name", "is", "None", ":", "clusters", "=", "self", ".", "kubeconf", ".", "get_clusters", "(", ")", "print", "(", "\"Running Clusters:\"", ")", "for", "cluster", "in", "clusters", ":", "print", "(", "f\" - {cluster['name']}\"", ")", "else", ":", "# Check that cluster exists.", "if", "self", ".", "check_cluster_exists", "(", "name", ")", "is", "False", ":", "raise", "JhubctlError", "(", "\"Cluster name not found in availabe clusters.\"", ")", "cluster", "=", "self", ".", "kubeconf", ".", "get_cluster", "(", "name", "=", "cluster", ".", "cluster_name", ")", "pprint", ".", "pprint", "(", "cluster", ",", "depth", "=", "4", ")" ]
List all cluster.
[ "List", "all", "cluster", "." ]
c8c20f86a16e9d01dd90e4607d81423417cc773b
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/clusters.py#L23-L42
247,804
townsenddw/jhubctl
jhubctl/clusters/clusters.py
ClusterList.create
def create(self, name, provider='AwsEKS'): """Create a Kubernetes cluster on a given provider. """ # ----- Create K8s cluster on provider ------- # Create cluster object Cluster = getattr(providers, provider) cluster = Cluster(name=name, ssh_key_name='zsailer') cluster.create() # -------- Add cluster to kubeconf ----------- # Add cluster to kubeconf self.kubeconf.open() self.kubeconf.add_cluster( cluster.cluster_name, server=cluster.endpoint_url, certificate_authority_data=cluster.ca_cert ) # Add a user to kubeconf self.kubeconf.add_user(name) # Add a user exec call for this provider. self.kubeconf.add_to_user( name, **cluster.kube_user_data ) # Add context mapping user to cluster. self.kubeconf.add_context( name, cluster_name=cluster.cluster_name, user_name=cluster.name ) # Switch contexts. self.kubeconf.set_current_context(name) # Commit changes to file. self.kubeconf.close() # ------ Setup autorization ------- kubectl('apply', input=cluster.get_auth_config()) # -------- Setup Storage ---------- kubectl('delete', 'storageclass', 'gp2') kubectl('apply', input=cluster.get_storage_config()) # ------- setup helm locally ------ kubectl( '--namespace', 'kube-system', 'create', 'serviceaccount', 'tiller' ) kubectl( 'create', 'clusterrolebinding', 'tiller', '--clusterrole=cluster-admin', '--serviceaccount=kube-system:tiller' ) # -------- Initialize Helm ----------- helm( 'init', '--service-account', 'tiller' ) # --------- Secure Helm -------------- kubectl( 'patch', 'deployment', 'tiller-deploy', namespace='kube-system', type='json', patch='[{"op": "add", "path": "/spec/template/spec/containers/0/command", "value": ["/tiller", "--listen=localhost:44134"]}]' )
python
def create(self, name, provider='AwsEKS'): """Create a Kubernetes cluster on a given provider. """ # ----- Create K8s cluster on provider ------- # Create cluster object Cluster = getattr(providers, provider) cluster = Cluster(name=name, ssh_key_name='zsailer') cluster.create() # -------- Add cluster to kubeconf ----------- # Add cluster to kubeconf self.kubeconf.open() self.kubeconf.add_cluster( cluster.cluster_name, server=cluster.endpoint_url, certificate_authority_data=cluster.ca_cert ) # Add a user to kubeconf self.kubeconf.add_user(name) # Add a user exec call for this provider. self.kubeconf.add_to_user( name, **cluster.kube_user_data ) # Add context mapping user to cluster. self.kubeconf.add_context( name, cluster_name=cluster.cluster_name, user_name=cluster.name ) # Switch contexts. self.kubeconf.set_current_context(name) # Commit changes to file. self.kubeconf.close() # ------ Setup autorization ------- kubectl('apply', input=cluster.get_auth_config()) # -------- Setup Storage ---------- kubectl('delete', 'storageclass', 'gp2') kubectl('apply', input=cluster.get_storage_config()) # ------- setup helm locally ------ kubectl( '--namespace', 'kube-system', 'create', 'serviceaccount', 'tiller' ) kubectl( 'create', 'clusterrolebinding', 'tiller', '--clusterrole=cluster-admin', '--serviceaccount=kube-system:tiller' ) # -------- Initialize Helm ----------- helm( 'init', '--service-account', 'tiller' ) # --------- Secure Helm -------------- kubectl( 'patch', 'deployment', 'tiller-deploy', namespace='kube-system', type='json', patch='[{"op": "add", "path": "/spec/template/spec/containers/0/command", "value": ["/tiller", "--listen=localhost:44134"]}]' )
[ "def", "create", "(", "self", ",", "name", ",", "provider", "=", "'AwsEKS'", ")", ":", "# ----- Create K8s cluster on provider -------", "# Create cluster object", "Cluster", "=", "getattr", "(", "providers", ",", "provider", ")", "cluster", "=", "Cluster", "(", "name", "=", "name", ",", "ssh_key_name", "=", "'zsailer'", ")", "cluster", ".", "create", "(", ")", "# -------- Add cluster to kubeconf -----------", "# Add cluster to kubeconf", "self", ".", "kubeconf", ".", "open", "(", ")", "self", ".", "kubeconf", ".", "add_cluster", "(", "cluster", ".", "cluster_name", ",", "server", "=", "cluster", ".", "endpoint_url", ",", "certificate_authority_data", "=", "cluster", ".", "ca_cert", ")", "# Add a user to kubeconf", "self", ".", "kubeconf", ".", "add_user", "(", "name", ")", "# Add a user exec call for this provider.", "self", ".", "kubeconf", ".", "add_to_user", "(", "name", ",", "*", "*", "cluster", ".", "kube_user_data", ")", "# Add context mapping user to cluster.", "self", ".", "kubeconf", ".", "add_context", "(", "name", ",", "cluster_name", "=", "cluster", ".", "cluster_name", ",", "user_name", "=", "cluster", ".", "name", ")", "# Switch contexts.", "self", ".", "kubeconf", ".", "set_current_context", "(", "name", ")", "# Commit changes to file.", "self", ".", "kubeconf", ".", "close", "(", ")", "# ------ Setup autorization -------", "kubectl", "(", "'apply'", ",", "input", "=", "cluster", ".", "get_auth_config", "(", ")", ")", "# -------- Setup Storage ----------", "kubectl", "(", "'delete'", ",", "'storageclass'", ",", "'gp2'", ")", "kubectl", "(", "'apply'", ",", "input", "=", "cluster", ".", "get_storage_config", "(", ")", ")", "# ------- setup helm locally ------", "kubectl", "(", "'--namespace'", ",", "'kube-system'", ",", "'create'", ",", "'serviceaccount'", ",", "'tiller'", ")", "kubectl", "(", "'create'", ",", "'clusterrolebinding'", ",", "'tiller'", ",", "'--clusterrole=cluster-admin'", ",", "'--serviceaccount=kube-system:tiller'", ")", "# -------- Initialize Helm -----------", "helm", "(", "'init'", ",", "'--service-account'", ",", "'tiller'", ")", "# --------- Secure Helm --------------", "kubectl", "(", "'patch'", ",", "'deployment'", ",", "'tiller-deploy'", ",", "namespace", "=", "'kube-system'", ",", "type", "=", "'json'", ",", "patch", "=", "'[{\"op\": \"add\", \"path\": \"/spec/template/spec/containers/0/command\", \"value\": [\"/tiller\", \"--listen=localhost:44134\"]}]'", ")" ]
Create a Kubernetes cluster on a given provider.
[ "Create", "a", "Kubernetes", "cluster", "on", "a", "given", "provider", "." ]
c8c20f86a16e9d01dd90e4607d81423417cc773b
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/clusters.py#L44-L124
247,805
townsenddw/jhubctl
jhubctl/clusters/clusters.py
ClusterList.delete
def delete(self, name, provider='AwsEKS'): """Delete a Kubernetes cluster. """ # if self.check_cluster_exists(name) is False: # raise JhubctlError("Cluster name not found in availabe clusters.") # Create cluster object Cluster = getattr(providers, provider) cluster = Cluster(name) cluster.delete() # Remove from kubeconf self.kubeconf.open() self.kubeconf.remove_context(name) self.kubeconf.remove_user(name) self.kubeconf.remove_cluster(cluster.cluster_name) self.kubeconf.close()
python
def delete(self, name, provider='AwsEKS'): """Delete a Kubernetes cluster. """ # if self.check_cluster_exists(name) is False: # raise JhubctlError("Cluster name not found in availabe clusters.") # Create cluster object Cluster = getattr(providers, provider) cluster = Cluster(name) cluster.delete() # Remove from kubeconf self.kubeconf.open() self.kubeconf.remove_context(name) self.kubeconf.remove_user(name) self.kubeconf.remove_cluster(cluster.cluster_name) self.kubeconf.close()
[ "def", "delete", "(", "self", ",", "name", ",", "provider", "=", "'AwsEKS'", ")", ":", "# if self.check_cluster_exists(name) is False:", "# raise JhubctlError(\"Cluster name not found in availabe clusters.\")", "# Create cluster object", "Cluster", "=", "getattr", "(", "providers", ",", "provider", ")", "cluster", "=", "Cluster", "(", "name", ")", "cluster", ".", "delete", "(", ")", "# Remove from kubeconf", "self", ".", "kubeconf", ".", "open", "(", ")", "self", ".", "kubeconf", ".", "remove_context", "(", "name", ")", "self", ".", "kubeconf", ".", "remove_user", "(", "name", ")", "self", ".", "kubeconf", ".", "remove_cluster", "(", "cluster", ".", "cluster_name", ")", "self", ".", "kubeconf", ".", "close", "(", ")" ]
Delete a Kubernetes cluster.
[ "Delete", "a", "Kubernetes", "cluster", "." ]
c8c20f86a16e9d01dd90e4607d81423417cc773b
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/clusters.py#L126-L142
247,806
EdwinvO/pyutillib
pyutillib/string_utils.py
random_string
def random_string(length=8, charset=None): ''' Generates a string with random characters. If no charset is specified, only letters and digits are used. Args: length (int) length of the returned string charset (string) list of characters to choose from Returns: (str) with random characters from charset Raises: - ''' if length < 1: raise ValueError('Length must be > 0') if not charset: charset = string.letters + string.digits return ''.join(random.choice(charset) for unused in xrange(length))
python
def random_string(length=8, charset=None): ''' Generates a string with random characters. If no charset is specified, only letters and digits are used. Args: length (int) length of the returned string charset (string) list of characters to choose from Returns: (str) with random characters from charset Raises: - ''' if length < 1: raise ValueError('Length must be > 0') if not charset: charset = string.letters + string.digits return ''.join(random.choice(charset) for unused in xrange(length))
[ "def", "random_string", "(", "length", "=", "8", ",", "charset", "=", "None", ")", ":", "if", "length", "<", "1", ":", "raise", "ValueError", "(", "'Length must be > 0'", ")", "if", "not", "charset", ":", "charset", "=", "string", ".", "letters", "+", "string", ".", "digits", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "charset", ")", "for", "unused", "in", "xrange", "(", "length", ")", ")" ]
Generates a string with random characters. If no charset is specified, only letters and digits are used. Args: length (int) length of the returned string charset (string) list of characters to choose from Returns: (str) with random characters from charset Raises: -
[ "Generates", "a", "string", "with", "random", "characters", ".", "If", "no", "charset", "is", "specified", "only", "letters", "and", "digits", "are", "used", "." ]
6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L28-L45
247,807
EdwinvO/pyutillib
pyutillib/string_utils.py
str2dict
def str2dict(str_in): ''' Extracts a dict from a string. Args: str_in (string) that contains python dict Returns: (dict) or None if no valid dict was found Raises: - ''' dict_out = safe_eval(str_in) if not isinstance(dict_out, dict): dict_out = None return dict_out
python
def str2dict(str_in): ''' Extracts a dict from a string. Args: str_in (string) that contains python dict Returns: (dict) or None if no valid dict was found Raises: - ''' dict_out = safe_eval(str_in) if not isinstance(dict_out, dict): dict_out = None return dict_out
[ "def", "str2dict", "(", "str_in", ")", ":", "dict_out", "=", "safe_eval", "(", "str_in", ")", "if", "not", "isinstance", "(", "dict_out", ",", "dict", ")", ":", "dict_out", "=", "None", "return", "dict_out" ]
Extracts a dict from a string. Args: str_in (string) that contains python dict Returns: (dict) or None if no valid dict was found Raises: -
[ "Extracts", "a", "dict", "from", "a", "string", "." ]
6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L65-L79
247,808
EdwinvO/pyutillib
pyutillib/string_utils.py
str2tuple
def str2tuple(str_in): ''' Extracts a tuple from a string. Args: str_in (string) that contains python tuple Returns: (dict) or None if no valid tuple was found Raises: - ''' tuple_out = safe_eval(str_in) if not isinstance(tuple_out, tuple): tuple_out = None return tuple_out
python
def str2tuple(str_in): ''' Extracts a tuple from a string. Args: str_in (string) that contains python tuple Returns: (dict) or None if no valid tuple was found Raises: - ''' tuple_out = safe_eval(str_in) if not isinstance(tuple_out, tuple): tuple_out = None return tuple_out
[ "def", "str2tuple", "(", "str_in", ")", ":", "tuple_out", "=", "safe_eval", "(", "str_in", ")", "if", "not", "isinstance", "(", "tuple_out", ",", "tuple", ")", ":", "tuple_out", "=", "None", "return", "tuple_out" ]
Extracts a tuple from a string. Args: str_in (string) that contains python tuple Returns: (dict) or None if no valid tuple was found Raises: -
[ "Extracts", "a", "tuple", "from", "a", "string", "." ]
6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L82-L96
247,809
EdwinvO/pyutillib
pyutillib/string_utils.py
str2dict_keys
def str2dict_keys(str_in): ''' Extracts the keys from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with keys or None if no valid dict was found Raises: - ''' tmp_dict = str2dict(str_in) if tmp_dict is None: return None return sorted([k for k in tmp_dict])
python
def str2dict_keys(str_in): ''' Extracts the keys from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with keys or None if no valid dict was found Raises: - ''' tmp_dict = str2dict(str_in) if tmp_dict is None: return None return sorted([k for k in tmp_dict])
[ "def", "str2dict_keys", "(", "str_in", ")", ":", "tmp_dict", "=", "str2dict", "(", "str_in", ")", "if", "tmp_dict", "is", "None", ":", "return", "None", "return", "sorted", "(", "[", "k", "for", "k", "in", "tmp_dict", "]", ")" ]
Extracts the keys from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with keys or None if no valid dict was found Raises: -
[ "Extracts", "the", "keys", "from", "a", "string", "that", "represents", "a", "dict", "and", "returns", "them", "sorted", "by", "key", "." ]
6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L100-L115
247,810
EdwinvO/pyutillib
pyutillib/string_utils.py
str2dict_values
def str2dict_values(str_in): ''' Extracts the values from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with values or None if no valid dict was found Raises: - ''' tmp_dict = str2dict(str_in) if tmp_dict is None: return None return [tmp_dict[key] for key in sorted(k for k in tmp_dict)]
python
def str2dict_values(str_in): ''' Extracts the values from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with values or None if no valid dict was found Raises: - ''' tmp_dict = str2dict(str_in) if tmp_dict is None: return None return [tmp_dict[key] for key in sorted(k for k in tmp_dict)]
[ "def", "str2dict_values", "(", "str_in", ")", ":", "tmp_dict", "=", "str2dict", "(", "str_in", ")", "if", "tmp_dict", "is", "None", ":", "return", "None", "return", "[", "tmp_dict", "[", "key", "]", "for", "key", "in", "sorted", "(", "k", "for", "k", "in", "tmp_dict", ")", "]" ]
Extracts the values from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with values or None if no valid dict was found Raises: -
[ "Extracts", "the", "values", "from", "a", "string", "that", "represents", "a", "dict", "and", "returns", "them", "sorted", "by", "key", "." ]
6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L119-L134
247,811
sirrice/scorpionsql
scorpionsql/sqlparser.py
expr_to_str
def expr_to_str(n, l=None): """ construct SQL string from expression node """ op = n[0] if op.startswith('_') and op.endswith('_'): op = op.strip('_') if op == 'var': return n[1] elif op == 'literal': if isinstance(n[1], basestring): return "'%s'" % n[1] return str(n[1]) elif op == 'cast': return "(%s)::%s" % (expr_to_str(n[1]), n[2]) elif op in '+-*/': return "(%s) %s (%s)" % (expr_to_str(n[1]), op, expr_to_str(n[2])) elif op == "extract": return "extract( %s from %s )" % (n[1], expr_to_str(n[2])) else: arg = ','.join(map(expr_to_str, n[1:])) return "%s(%s)" % (op, arg)
python
def expr_to_str(n, l=None): """ construct SQL string from expression node """ op = n[0] if op.startswith('_') and op.endswith('_'): op = op.strip('_') if op == 'var': return n[1] elif op == 'literal': if isinstance(n[1], basestring): return "'%s'" % n[1] return str(n[1]) elif op == 'cast': return "(%s)::%s" % (expr_to_str(n[1]), n[2]) elif op in '+-*/': return "(%s) %s (%s)" % (expr_to_str(n[1]), op, expr_to_str(n[2])) elif op == "extract": return "extract( %s from %s )" % (n[1], expr_to_str(n[2])) else: arg = ','.join(map(expr_to_str, n[1:])) return "%s(%s)" % (op, arg)
[ "def", "expr_to_str", "(", "n", ",", "l", "=", "None", ")", ":", "op", "=", "n", "[", "0", "]", "if", "op", ".", "startswith", "(", "'_'", ")", "and", "op", ".", "endswith", "(", "'_'", ")", ":", "op", "=", "op", ".", "strip", "(", "'_'", ")", "if", "op", "==", "'var'", ":", "return", "n", "[", "1", "]", "elif", "op", "==", "'literal'", ":", "if", "isinstance", "(", "n", "[", "1", "]", ",", "basestring", ")", ":", "return", "\"'%s'\"", "%", "n", "[", "1", "]", "return", "str", "(", "n", "[", "1", "]", ")", "elif", "op", "==", "'cast'", ":", "return", "\"(%s)::%s\"", "%", "(", "expr_to_str", "(", "n", "[", "1", "]", ")", ",", "n", "[", "2", "]", ")", "elif", "op", "in", "'+-*/'", ":", "return", "\"(%s) %s (%s)\"", "%", "(", "expr_to_str", "(", "n", "[", "1", "]", ")", ",", "op", ",", "expr_to_str", "(", "n", "[", "2", "]", ")", ")", "elif", "op", "==", "\"extract\"", ":", "return", "\"extract( %s from %s )\"", "%", "(", "n", "[", "1", "]", ",", "expr_to_str", "(", "n", "[", "2", "]", ")", ")", "else", ":", "arg", "=", "','", ".", "join", "(", "map", "(", "expr_to_str", ",", "n", "[", "1", ":", "]", ")", ")", "return", "\"%s(%s)\"", "%", "(", "op", ",", "arg", ")" ]
construct SQL string from expression node
[ "construct", "SQL", "string", "from", "expression", "node" ]
baa05b745fae5df3171244c3e32160bd36c99e86
https://github.com/sirrice/scorpionsql/blob/baa05b745fae5df3171244c3e32160bd36c99e86/scorpionsql/sqlparser.py#L95-L116
247,812
sirrice/scorpionsql
scorpionsql/sqlparser.py
construct_func_expr
def construct_func_expr(n): """ construct the function expression """ op = n[0] if op.startswith('_') and op.endswith('_'): op = op.strip('_') if op == 'var': return Var(str(n[1])) elif op == 'literal': if isinstance(n[1], basestring): raise "not implemented" return Constant(n[1]) elif op == 'cast': raise "not implemented" elif op in '+-/*': return ArithErrFunc(op, *map(construct_func_expr,n[1:])) else: klass = __agg2f__.get(op, None) if klass: return klass(map(construct_func_expr, n[1:])) raise "no klass"
python
def construct_func_expr(n): """ construct the function expression """ op = n[0] if op.startswith('_') and op.endswith('_'): op = op.strip('_') if op == 'var': return Var(str(n[1])) elif op == 'literal': if isinstance(n[1], basestring): raise "not implemented" return Constant(n[1]) elif op == 'cast': raise "not implemented" elif op in '+-/*': return ArithErrFunc(op, *map(construct_func_expr,n[1:])) else: klass = __agg2f__.get(op, None) if klass: return klass(map(construct_func_expr, n[1:])) raise "no klass"
[ "def", "construct_func_expr", "(", "n", ")", ":", "op", "=", "n", "[", "0", "]", "if", "op", ".", "startswith", "(", "'_'", ")", "and", "op", ".", "endswith", "(", "'_'", ")", ":", "op", "=", "op", ".", "strip", "(", "'_'", ")", "if", "op", "==", "'var'", ":", "return", "Var", "(", "str", "(", "n", "[", "1", "]", ")", ")", "elif", "op", "==", "'literal'", ":", "if", "isinstance", "(", "n", "[", "1", "]", ",", "basestring", ")", ":", "raise", "\"not implemented\"", "return", "Constant", "(", "n", "[", "1", "]", ")", "elif", "op", "==", "'cast'", ":", "raise", "\"not implemented\"", "elif", "op", "in", "'+-/*'", ":", "return", "ArithErrFunc", "(", "op", ",", "*", "map", "(", "construct_func_expr", ",", "n", "[", "1", ":", "]", ")", ")", "else", ":", "klass", "=", "__agg2f__", ".", "get", "(", "op", ",", "None", ")", "if", "klass", ":", "return", "klass", "(", "map", "(", "construct_func_expr", ",", "n", "[", "1", ":", "]", ")", ")", "raise", "\"no klass\"" ]
construct the function expression
[ "construct", "the", "function", "expression" ]
baa05b745fae5df3171244c3e32160bd36c99e86
https://github.com/sirrice/scorpionsql/blob/baa05b745fae5df3171244c3e32160bd36c99e86/scorpionsql/sqlparser.py#L138-L159
247,813
robertdfrench/psychic-disco
psychic_disco/api_gateway_config.py
fetch_api_by_name
def fetch_api_by_name(api_name): """ Fetch an api record by its name """ api_records = console.get_rest_apis()['items'] matches = filter(lambda x: x['name'] == api_name, api_records) if not matches: return None return matches[0]
python
def fetch_api_by_name(api_name): """ Fetch an api record by its name """ api_records = console.get_rest_apis()['items'] matches = filter(lambda x: x['name'] == api_name, api_records) if not matches: return None return matches[0]
[ "def", "fetch_api_by_name", "(", "api_name", ")", ":", "api_records", "=", "console", ".", "get_rest_apis", "(", ")", "[", "'items'", "]", "matches", "=", "filter", "(", "lambda", "x", ":", "x", "[", "'name'", "]", "==", "api_name", ",", "api_records", ")", "if", "not", "matches", ":", "return", "None", "return", "matches", "[", "0", "]" ]
Fetch an api record by its name
[ "Fetch", "an", "api", "record", "by", "its", "name" ]
3cf167b44c64d64606691fc186be7d9ef8e8e938
https://github.com/robertdfrench/psychic-disco/blob/3cf167b44c64d64606691fc186be7d9ef8e8e938/psychic_disco/api_gateway_config.py#L8-L14
247,814
robertdfrench/psychic-disco
psychic_disco/api_gateway_config.py
fetch_method
def fetch_method(api_id, resource_id, verb): """ Fetch extra metadata for this particular method """ return console.get_method( restApiId=api_id, resourceId=resource_id, httpMethod=verb)
python
def fetch_method(api_id, resource_id, verb): """ Fetch extra metadata for this particular method """ return console.get_method( restApiId=api_id, resourceId=resource_id, httpMethod=verb)
[ "def", "fetch_method", "(", "api_id", ",", "resource_id", ",", "verb", ")", ":", "return", "console", ".", "get_method", "(", "restApiId", "=", "api_id", ",", "resourceId", "=", "resource_id", ",", "httpMethod", "=", "verb", ")" ]
Fetch extra metadata for this particular method
[ "Fetch", "extra", "metadata", "for", "this", "particular", "method" ]
3cf167b44c64d64606691fc186be7d9ef8e8e938
https://github.com/robertdfrench/psychic-disco/blob/3cf167b44c64d64606691fc186be7d9ef8e8e938/psychic_disco/api_gateway_config.py#L27-L32
247,815
artizirk/python-axp209
axp209.py
AXP209.battery_voltage
def battery_voltage(self): """ Returns voltage in mV """ msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG) lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG) voltage_bin = msb << 4 | lsb & 0x0f return voltage_bin * 1.1
python
def battery_voltage(self): """ Returns voltage in mV """ msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG) lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG) voltage_bin = msb << 4 | lsb & 0x0f return voltage_bin * 1.1
[ "def", "battery_voltage", "(", "self", ")", ":", "msb", "=", "self", ".", "bus", ".", "read_byte_data", "(", "AXP209_ADDRESS", ",", "BATTERY_VOLTAGE_MSB_REG", ")", "lsb", "=", "self", ".", "bus", ".", "read_byte_data", "(", "AXP209_ADDRESS", ",", "BATTERY_VOLTAGE_LSB_REG", ")", "voltage_bin", "=", "msb", "<<", "4", "|", "lsb", "&", "0x0f", "return", "voltage_bin", "*", "1.1" ]
Returns voltage in mV
[ "Returns", "voltage", "in", "mV" ]
dc48015b23ea3695bf1ee076355c96ea434b77e4
https://github.com/artizirk/python-axp209/blob/dc48015b23ea3695bf1ee076355c96ea434b77e4/axp209.py#L189-L194
247,816
artizirk/python-axp209
axp209.py
AXP209.internal_temperature
def internal_temperature(self): """ Returns temperature in celsius C """ temp_msb = self.bus.read_byte_data(AXP209_ADDRESS, INTERNAL_TEMPERATURE_MSB_REG) temp_lsb = self.bus.read_byte_data(AXP209_ADDRESS, INTERNAL_TEMPERATURE_LSB_REG) # MSB is 8 bits, LSB is lower 4 bits temp = temp_msb << 4 | temp_lsb & 0x0f # -144.7c -> 000h, 0.1c/bit FFFh -> 264.8c return temp*0.1-144.7
python
def internal_temperature(self): """ Returns temperature in celsius C """ temp_msb = self.bus.read_byte_data(AXP209_ADDRESS, INTERNAL_TEMPERATURE_MSB_REG) temp_lsb = self.bus.read_byte_data(AXP209_ADDRESS, INTERNAL_TEMPERATURE_LSB_REG) # MSB is 8 bits, LSB is lower 4 bits temp = temp_msb << 4 | temp_lsb & 0x0f # -144.7c -> 000h, 0.1c/bit FFFh -> 264.8c return temp*0.1-144.7
[ "def", "internal_temperature", "(", "self", ")", ":", "temp_msb", "=", "self", ".", "bus", ".", "read_byte_data", "(", "AXP209_ADDRESS", ",", "INTERNAL_TEMPERATURE_MSB_REG", ")", "temp_lsb", "=", "self", ".", "bus", ".", "read_byte_data", "(", "AXP209_ADDRESS", ",", "INTERNAL_TEMPERATURE_LSB_REG", ")", "# MSB is 8 bits, LSB is lower 4 bits", "temp", "=", "temp_msb", "<<", "4", "|", "temp_lsb", "&", "0x0f", "# -144.7c -> 000h,\t0.1c/bit\tFFFh -> 264.8c", "return", "temp", "*", "0.1", "-", "144.7" ]
Returns temperature in celsius C
[ "Returns", "temperature", "in", "celsius", "C" ]
dc48015b23ea3695bf1ee076355c96ea434b77e4
https://github.com/artizirk/python-axp209/blob/dc48015b23ea3695bf1ee076355c96ea434b77e4/axp209.py#L217-L224
247,817
TheOneHyer/arandomness
build/lib.linux-x86_64-3.6/arandomness/files/copen.py
copen
def copen(fileobj, mode='rb', **kwargs): """Detects and opens compressed file for reading and writing. Args: fileobj (File): any File-like object supported by an underlying compression algorithm mode (unicode): mode to open fileobj with **kwargs: keyword-arguments to pass to the compression algorithm Returns: File: TextWrapper if no compression, else returns appropriate wrapper for the compression type Example: .. code-block:: Python >>> from tempfile import NamedTemporaryFile >>> # Write compressed file >>> temp = NamedTemporaryFile(delete=False, suffix='.bz2') >>> test_bz2 = copen(temp.name, 'wb') >>> test_bz2.write(b'bzip2') >>> test_bz2.close() >>> # Read compressed bzip file >>> test_bz2 = copen(temp.name, 'rb') >>> test_bz2.read() b'bzip2' """ algo = io.open # Only used as io.open in write mode mode = mode.lower().strip() modules = {} # Later populated by compression algorithms write_mode = False if mode.lstrip('U')[0] == 'r' else True kwargs['mode'] = mode # Currently supported compression algorithms modules_to_import = { 'bz2': 'BZ2File', 'gzip': 'GzipFile', 'lzma': 'LZMAFile' } # Dynamically import compression libraries and warn about failures for mod, _class in modules_to_import.items(): try: modules[_class] = getattr(import_module(mod), _class) except (ImportError, AttributeError) as e: modules[_class] = open warn('Cannot process {0} files due to following error:' '{1}{2}{1}You will need to install the {0} library to ' 'properly use these files. Currently, such files will ' 'open in "text" mode.'.format(mod, linesep, e)) # Write mode if write_mode is True: # Map file extensions to decompression classes algo_map = { 'bz2': modules['BZ2File'], 'gz': modules['GzipFile'], 'xz': modules['LZMAFile'] } # Determine the compression algorithm via the file extension ext = fileobj.split('.')[-1] try: algo = algo_map[ext] except KeyError: pass # Read mode else: algo = io.TextIOWrapper # Default to plaintext buffer # Magic headers of encryption formats file_sigs = { b'\x42\x5a\x68': modules['BZ2File'], b'\x1f\x8b\x08': modules['GzipFile'], b'\xfd7zXZ\x00': modules['LZMAFile'] } # Open the file, buffer it, and identify the compression algorithm fileobj = io.BufferedReader(io.open(fileobj, 'rb')) max_len = max(len(x) for x in file_sigs.keys()) start = fileobj.peek(max_len) for sig in file_sigs.keys(): if start.startswith(sig): algo = file_sigs[sig] break # Stop iterating once a good signature is found # Filter all **kwargs by the args accepted by the compression algorithm algo_args = set(getfullargspec(algo).args) good_args = set(kwargs.keys()).intersection(algo_args) _kwargs = {arg: kwargs[arg] for arg in good_args} # Open the file using parameters defined above and store in namespace if write_mode is True: handle = algo(fileobj, **_kwargs) else: try: # For algorithms that need to be explicitly given a fileobj handle = algo(fileobj=fileobj, **_kwargs) except TypeError: # For algorithms that detect file objects handle = algo(fileobj, **_kwargs) return handle
python
def copen(fileobj, mode='rb', **kwargs): """Detects and opens compressed file for reading and writing. Args: fileobj (File): any File-like object supported by an underlying compression algorithm mode (unicode): mode to open fileobj with **kwargs: keyword-arguments to pass to the compression algorithm Returns: File: TextWrapper if no compression, else returns appropriate wrapper for the compression type Example: .. code-block:: Python >>> from tempfile import NamedTemporaryFile >>> # Write compressed file >>> temp = NamedTemporaryFile(delete=False, suffix='.bz2') >>> test_bz2 = copen(temp.name, 'wb') >>> test_bz2.write(b'bzip2') >>> test_bz2.close() >>> # Read compressed bzip file >>> test_bz2 = copen(temp.name, 'rb') >>> test_bz2.read() b'bzip2' """ algo = io.open # Only used as io.open in write mode mode = mode.lower().strip() modules = {} # Later populated by compression algorithms write_mode = False if mode.lstrip('U')[0] == 'r' else True kwargs['mode'] = mode # Currently supported compression algorithms modules_to_import = { 'bz2': 'BZ2File', 'gzip': 'GzipFile', 'lzma': 'LZMAFile' } # Dynamically import compression libraries and warn about failures for mod, _class in modules_to_import.items(): try: modules[_class] = getattr(import_module(mod), _class) except (ImportError, AttributeError) as e: modules[_class] = open warn('Cannot process {0} files due to following error:' '{1}{2}{1}You will need to install the {0} library to ' 'properly use these files. Currently, such files will ' 'open in "text" mode.'.format(mod, linesep, e)) # Write mode if write_mode is True: # Map file extensions to decompression classes algo_map = { 'bz2': modules['BZ2File'], 'gz': modules['GzipFile'], 'xz': modules['LZMAFile'] } # Determine the compression algorithm via the file extension ext = fileobj.split('.')[-1] try: algo = algo_map[ext] except KeyError: pass # Read mode else: algo = io.TextIOWrapper # Default to plaintext buffer # Magic headers of encryption formats file_sigs = { b'\x42\x5a\x68': modules['BZ2File'], b'\x1f\x8b\x08': modules['GzipFile'], b'\xfd7zXZ\x00': modules['LZMAFile'] } # Open the file, buffer it, and identify the compression algorithm fileobj = io.BufferedReader(io.open(fileobj, 'rb')) max_len = max(len(x) for x in file_sigs.keys()) start = fileobj.peek(max_len) for sig in file_sigs.keys(): if start.startswith(sig): algo = file_sigs[sig] break # Stop iterating once a good signature is found # Filter all **kwargs by the args accepted by the compression algorithm algo_args = set(getfullargspec(algo).args) good_args = set(kwargs.keys()).intersection(algo_args) _kwargs = {arg: kwargs[arg] for arg in good_args} # Open the file using parameters defined above and store in namespace if write_mode is True: handle = algo(fileobj, **_kwargs) else: try: # For algorithms that need to be explicitly given a fileobj handle = algo(fileobj=fileobj, **_kwargs) except TypeError: # For algorithms that detect file objects handle = algo(fileobj, **_kwargs) return handle
[ "def", "copen", "(", "fileobj", ",", "mode", "=", "'rb'", ",", "*", "*", "kwargs", ")", ":", "algo", "=", "io", ".", "open", "# Only used as io.open in write mode", "mode", "=", "mode", ".", "lower", "(", ")", ".", "strip", "(", ")", "modules", "=", "{", "}", "# Later populated by compression algorithms", "write_mode", "=", "False", "if", "mode", ".", "lstrip", "(", "'U'", ")", "[", "0", "]", "==", "'r'", "else", "True", "kwargs", "[", "'mode'", "]", "=", "mode", "# Currently supported compression algorithms", "modules_to_import", "=", "{", "'bz2'", ":", "'BZ2File'", ",", "'gzip'", ":", "'GzipFile'", ",", "'lzma'", ":", "'LZMAFile'", "}", "# Dynamically import compression libraries and warn about failures", "for", "mod", ",", "_class", "in", "modules_to_import", ".", "items", "(", ")", ":", "try", ":", "modules", "[", "_class", "]", "=", "getattr", "(", "import_module", "(", "mod", ")", ",", "_class", ")", "except", "(", "ImportError", ",", "AttributeError", ")", "as", "e", ":", "modules", "[", "_class", "]", "=", "open", "warn", "(", "'Cannot process {0} files due to following error:'", "'{1}{2}{1}You will need to install the {0} library to '", "'properly use these files. Currently, such files will '", "'open in \"text\" mode.'", ".", "format", "(", "mod", ",", "linesep", ",", "e", ")", ")", "# Write mode", "if", "write_mode", "is", "True", ":", "# Map file extensions to decompression classes", "algo_map", "=", "{", "'bz2'", ":", "modules", "[", "'BZ2File'", "]", ",", "'gz'", ":", "modules", "[", "'GzipFile'", "]", ",", "'xz'", ":", "modules", "[", "'LZMAFile'", "]", "}", "# Determine the compression algorithm via the file extension", "ext", "=", "fileobj", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "try", ":", "algo", "=", "algo_map", "[", "ext", "]", "except", "KeyError", ":", "pass", "# Read mode", "else", ":", "algo", "=", "io", ".", "TextIOWrapper", "# Default to plaintext buffer", "# Magic headers of encryption formats", "file_sigs", "=", "{", "b'\\x42\\x5a\\x68'", ":", "modules", "[", "'BZ2File'", "]", ",", "b'\\x1f\\x8b\\x08'", ":", "modules", "[", "'GzipFile'", "]", ",", "b'\\xfd7zXZ\\x00'", ":", "modules", "[", "'LZMAFile'", "]", "}", "# Open the file, buffer it, and identify the compression algorithm", "fileobj", "=", "io", ".", "BufferedReader", "(", "io", ".", "open", "(", "fileobj", ",", "'rb'", ")", ")", "max_len", "=", "max", "(", "len", "(", "x", ")", "for", "x", "in", "file_sigs", ".", "keys", "(", ")", ")", "start", "=", "fileobj", ".", "peek", "(", "max_len", ")", "for", "sig", "in", "file_sigs", ".", "keys", "(", ")", ":", "if", "start", ".", "startswith", "(", "sig", ")", ":", "algo", "=", "file_sigs", "[", "sig", "]", "break", "# Stop iterating once a good signature is found", "# Filter all **kwargs by the args accepted by the compression algorithm", "algo_args", "=", "set", "(", "getfullargspec", "(", "algo", ")", ".", "args", ")", "good_args", "=", "set", "(", "kwargs", ".", "keys", "(", ")", ")", ".", "intersection", "(", "algo_args", ")", "_kwargs", "=", "{", "arg", ":", "kwargs", "[", "arg", "]", "for", "arg", "in", "good_args", "}", "# Open the file using parameters defined above and store in namespace", "if", "write_mode", "is", "True", ":", "handle", "=", "algo", "(", "fileobj", ",", "*", "*", "_kwargs", ")", "else", ":", "try", ":", "# For algorithms that need to be explicitly given a fileobj", "handle", "=", "algo", "(", "fileobj", "=", "fileobj", ",", "*", "*", "_kwargs", ")", "except", "TypeError", ":", "# For algorithms that detect file objects", "handle", "=", "algo", "(", "fileobj", ",", "*", "*", "_kwargs", ")", "return", "handle" ]
Detects and opens compressed file for reading and writing. Args: fileobj (File): any File-like object supported by an underlying compression algorithm mode (unicode): mode to open fileobj with **kwargs: keyword-arguments to pass to the compression algorithm Returns: File: TextWrapper if no compression, else returns appropriate wrapper for the compression type Example: .. code-block:: Python >>> from tempfile import NamedTemporaryFile >>> # Write compressed file >>> temp = NamedTemporaryFile(delete=False, suffix='.bz2') >>> test_bz2 = copen(temp.name, 'wb') >>> test_bz2.write(b'bzip2') >>> test_bz2.close() >>> # Read compressed bzip file >>> test_bz2 = copen(temp.name, 'rb') >>> test_bz2.read() b'bzip2'
[ "Detects", "and", "opens", "compressed", "file", "for", "reading", "and", "writing", "." ]
ae9f630e9a1d67b0eb6d61644a49756de8a5268c
https://github.com/TheOneHyer/arandomness/blob/ae9f630e9a1d67b0eb6d61644a49756de8a5268c/build/lib.linux-x86_64-3.6/arandomness/files/copen.py#L41-L147
247,818
rackerlabs/rackspace-python-neutronclient
neutronclient/neutron/v2_0/securitygroup.py
ListSecurityGroupRule._get_sg_name_dict
def _get_sg_name_dict(self, data, page_size, no_nameconv): """Get names of security groups referred in the retrieved rules. :return: a dict from secgroup ID to secgroup name """ if no_nameconv: return {} neutron_client = self.get_client() search_opts = {'fields': ['id', 'name']} if self.pagination_support: if page_size: search_opts.update({'limit': page_size}) sec_group_ids = set() for rule in data: for key in self.replace_rules: if rule.get(key): sec_group_ids.add(rule[key]) sec_group_ids = list(sec_group_ids) def _get_sec_group_list(sec_group_ids): search_opts['id'] = sec_group_ids return neutron_client.list_security_groups( **search_opts).get('security_groups', []) try: secgroups = _get_sec_group_list(sec_group_ids) except exceptions.RequestURITooLong as uri_len_exc: # Length of a query filter on security group rule id # id=<uuid>& (with len(uuid)=36) sec_group_id_filter_len = 40 # The URI is too long because of too many sec_group_id filters # Use the excess attribute of the exception to know how many # sec_group_id filters can be inserted into a single request sec_group_count = len(sec_group_ids) max_size = ((sec_group_id_filter_len * sec_group_count) - uri_len_exc.excess) chunk_size = max_size // sec_group_id_filter_len secgroups = [] for i in range(0, sec_group_count, chunk_size): secgroups.extend( _get_sec_group_list(sec_group_ids[i: i + chunk_size])) return dict([(sg['id'], sg['name']) for sg in secgroups if sg['name']])
python
def _get_sg_name_dict(self, data, page_size, no_nameconv): """Get names of security groups referred in the retrieved rules. :return: a dict from secgroup ID to secgroup name """ if no_nameconv: return {} neutron_client = self.get_client() search_opts = {'fields': ['id', 'name']} if self.pagination_support: if page_size: search_opts.update({'limit': page_size}) sec_group_ids = set() for rule in data: for key in self.replace_rules: if rule.get(key): sec_group_ids.add(rule[key]) sec_group_ids = list(sec_group_ids) def _get_sec_group_list(sec_group_ids): search_opts['id'] = sec_group_ids return neutron_client.list_security_groups( **search_opts).get('security_groups', []) try: secgroups = _get_sec_group_list(sec_group_ids) except exceptions.RequestURITooLong as uri_len_exc: # Length of a query filter on security group rule id # id=<uuid>& (with len(uuid)=36) sec_group_id_filter_len = 40 # The URI is too long because of too many sec_group_id filters # Use the excess attribute of the exception to know how many # sec_group_id filters can be inserted into a single request sec_group_count = len(sec_group_ids) max_size = ((sec_group_id_filter_len * sec_group_count) - uri_len_exc.excess) chunk_size = max_size // sec_group_id_filter_len secgroups = [] for i in range(0, sec_group_count, chunk_size): secgroups.extend( _get_sec_group_list(sec_group_ids[i: i + chunk_size])) return dict([(sg['id'], sg['name']) for sg in secgroups if sg['name']])
[ "def", "_get_sg_name_dict", "(", "self", ",", "data", ",", "page_size", ",", "no_nameconv", ")", ":", "if", "no_nameconv", ":", "return", "{", "}", "neutron_client", "=", "self", ".", "get_client", "(", ")", "search_opts", "=", "{", "'fields'", ":", "[", "'id'", ",", "'name'", "]", "}", "if", "self", ".", "pagination_support", ":", "if", "page_size", ":", "search_opts", ".", "update", "(", "{", "'limit'", ":", "page_size", "}", ")", "sec_group_ids", "=", "set", "(", ")", "for", "rule", "in", "data", ":", "for", "key", "in", "self", ".", "replace_rules", ":", "if", "rule", ".", "get", "(", "key", ")", ":", "sec_group_ids", ".", "add", "(", "rule", "[", "key", "]", ")", "sec_group_ids", "=", "list", "(", "sec_group_ids", ")", "def", "_get_sec_group_list", "(", "sec_group_ids", ")", ":", "search_opts", "[", "'id'", "]", "=", "sec_group_ids", "return", "neutron_client", ".", "list_security_groups", "(", "*", "*", "search_opts", ")", ".", "get", "(", "'security_groups'", ",", "[", "]", ")", "try", ":", "secgroups", "=", "_get_sec_group_list", "(", "sec_group_ids", ")", "except", "exceptions", ".", "RequestURITooLong", "as", "uri_len_exc", ":", "# Length of a query filter on security group rule id", "# id=<uuid>& (with len(uuid)=36)", "sec_group_id_filter_len", "=", "40", "# The URI is too long because of too many sec_group_id filters", "# Use the excess attribute of the exception to know how many", "# sec_group_id filters can be inserted into a single request", "sec_group_count", "=", "len", "(", "sec_group_ids", ")", "max_size", "=", "(", "(", "sec_group_id_filter_len", "*", "sec_group_count", ")", "-", "uri_len_exc", ".", "excess", ")", "chunk_size", "=", "max_size", "//", "sec_group_id_filter_len", "secgroups", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "sec_group_count", ",", "chunk_size", ")", ":", "secgroups", ".", "extend", "(", "_get_sec_group_list", "(", "sec_group_ids", "[", "i", ":", "i", "+", "chunk_size", "]", ")", ")", "return", "dict", "(", "[", "(", "sg", "[", "'id'", "]", ",", "sg", "[", "'name'", "]", ")", "for", "sg", "in", "secgroups", "if", "sg", "[", "'name'", "]", "]", ")" ]
Get names of security groups referred in the retrieved rules. :return: a dict from secgroup ID to secgroup name
[ "Get", "names", "of", "security", "groups", "referred", "in", "the", "retrieved", "rules", "." ]
5a5009a8fe078e3aa1d582176669f1b28ab26bef
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/neutron/v2_0/securitygroup.py#L215-L258
247,819
jmgilman/Neolib
neolib/user/Bank.py
Bank.load
def load(self): """ Loads the user's account details and Raises parseException """ pg = self.usr.getPage("http://www.neopets.com/bank.phtml") # Verifies account exists if not "great to see you again" in pg.content: logging.getLogger("neolib.user").info("Could not load user's bank. Most likely does not have an account.", {'pg': pg}) raise noBankAcct self.__loadDetails(pg)
python
def load(self): """ Loads the user's account details and Raises parseException """ pg = self.usr.getPage("http://www.neopets.com/bank.phtml") # Verifies account exists if not "great to see you again" in pg.content: logging.getLogger("neolib.user").info("Could not load user's bank. Most likely does not have an account.", {'pg': pg}) raise noBankAcct self.__loadDetails(pg)
[ "def", "load", "(", "self", ")", ":", "pg", "=", "self", ".", "usr", ".", "getPage", "(", "\"http://www.neopets.com/bank.phtml\"", ")", "# Verifies account exists", "if", "not", "\"great to see you again\"", "in", "pg", ".", "content", ":", "logging", ".", "getLogger", "(", "\"neolib.user\"", ")", ".", "info", "(", "\"Could not load user's bank. Most likely does not have an account.\"", ",", "{", "'pg'", ":", "pg", "}", ")", "raise", "noBankAcct", "self", ".", "__loadDetails", "(", "pg", ")" ]
Loads the user's account details and Raises parseException
[ "Loads", "the", "user", "s", "account", "details", "and", "Raises", "parseException" ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/user/Bank.py#L51-L64
247,820
jmgilman/Neolib
neolib/user/Bank.py
Bank.collectInterest
def collectInterest(self): """ Collects user's daily interest, returns result Returns bool - True if successful, False otherwise """ if self.collectedInterest: return False pg = self.usr.getPage("http://www.neopets.com/bank.phtml") form = pg.form(action="process_bank.phtml") form['type'] = "interest" pg = form.submit() # Success redirects to bank page if "It's great to see you again" in pg.content: self.__loadDetails(pg) return True else: logging.getLogger("neolib.user").info("Failed to collect daily interest for unknown reason.", {'pg': pg}) return False
python
def collectInterest(self): """ Collects user's daily interest, returns result Returns bool - True if successful, False otherwise """ if self.collectedInterest: return False pg = self.usr.getPage("http://www.neopets.com/bank.phtml") form = pg.form(action="process_bank.phtml") form['type'] = "interest" pg = form.submit() # Success redirects to bank page if "It's great to see you again" in pg.content: self.__loadDetails(pg) return True else: logging.getLogger("neolib.user").info("Failed to collect daily interest for unknown reason.", {'pg': pg}) return False
[ "def", "collectInterest", "(", "self", ")", ":", "if", "self", ".", "collectedInterest", ":", "return", "False", "pg", "=", "self", ".", "usr", ".", "getPage", "(", "\"http://www.neopets.com/bank.phtml\"", ")", "form", "=", "pg", ".", "form", "(", "action", "=", "\"process_bank.phtml\"", ")", "form", "[", "'type'", "]", "=", "\"interest\"", "pg", "=", "form", ".", "submit", "(", ")", "# Success redirects to bank page", "if", "\"It's great to see you again\"", "in", "pg", ".", "content", ":", "self", ".", "__loadDetails", "(", "pg", ")", "return", "True", "else", ":", "logging", ".", "getLogger", "(", "\"neolib.user\"", ")", ".", "info", "(", "\"Failed to collect daily interest for unknown reason.\"", ",", "{", "'pg'", ":", "pg", "}", ")", "return", "False" ]
Collects user's daily interest, returns result Returns bool - True if successful, False otherwise
[ "Collects", "user", "s", "daily", "interest", "returns", "result", "Returns", "bool", "-", "True", "if", "successful", "False", "otherwise" ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/user/Bank.py#L132-L153
247,821
svasilev94/GraphLibrary
graphlibrary/prim.py
connected_components
def connected_components(G): """ Check if G is connected and return list of sets. Every set contains all vertices in one connected component. """ result = [] vertices = set(G.vertices) while vertices: n = vertices.pop() group = {n} queue = Queue() queue.put(n) while not queue.empty(): n = queue.get() neighbors = set(G.vertices[n]) neighbors.difference_update(group) vertices.difference_update(neighbors) group.update(neighbors) for element in neighbors: queue.put(element) result.append(group) return result
python
def connected_components(G): """ Check if G is connected and return list of sets. Every set contains all vertices in one connected component. """ result = [] vertices = set(G.vertices) while vertices: n = vertices.pop() group = {n} queue = Queue() queue.put(n) while not queue.empty(): n = queue.get() neighbors = set(G.vertices[n]) neighbors.difference_update(group) vertices.difference_update(neighbors) group.update(neighbors) for element in neighbors: queue.put(element) result.append(group) return result
[ "def", "connected_components", "(", "G", ")", ":", "result", "=", "[", "]", "vertices", "=", "set", "(", "G", ".", "vertices", ")", "while", "vertices", ":", "n", "=", "vertices", ".", "pop", "(", ")", "group", "=", "{", "n", "}", "queue", "=", "Queue", "(", ")", "queue", ".", "put", "(", "n", ")", "while", "not", "queue", ".", "empty", "(", ")", ":", "n", "=", "queue", ".", "get", "(", ")", "neighbors", "=", "set", "(", "G", ".", "vertices", "[", "n", "]", ")", "neighbors", ".", "difference_update", "(", "group", ")", "vertices", ".", "difference_update", "(", "neighbors", ")", "group", ".", "update", "(", "neighbors", ")", "for", "element", "in", "neighbors", ":", "queue", ".", "put", "(", "element", ")", "result", ".", "append", "(", "group", ")", "return", "result" ]
Check if G is connected and return list of sets. Every set contains all vertices in one connected component.
[ "Check", "if", "G", "is", "connected", "and", "return", "list", "of", "sets", ".", "Every", "set", "contains", "all", "vertices", "in", "one", "connected", "component", "." ]
bf979a80bdea17eeb25955f0c119ca8f711ef62b
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/prim.py#L8-L29
247,822
svasilev94/GraphLibrary
graphlibrary/prim.py
prim
def prim(G, start, weight='weight'): """ Algorithm for finding a minimum spanning tree for a weighted undirected graph. """ if len(connected_components(G)) != 1: raise GraphInsertError("Prim algorithm work with connected graph only") if start not in G.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (start,)) pred = {} key = {} pqueue = {} lowest = 0 for edge in G.edges: if G.edges[edge][weight] > lowest: lowest = G.edges[edge][weight] for vertex in G.vertices: pred[vertex] = None key[vertex] = 2 * lowest key[start] = 0 for vertex in G.vertices: pqueue[vertex] = key[vertex] while pqueue: current = popmin(pqueue, lowest) for neighbor in G.vertices[current]: if (neighbor in pqueue and G.edges[(current, neighbor)][weight] < key[neighbor]): pred[neighbor] = current key[neighbor] = G.edges[(current, neighbor)][weight] pqueue[neighbor] = G.edges[(current, neighbor)][weight] return pred
python
def prim(G, start, weight='weight'): """ Algorithm for finding a minimum spanning tree for a weighted undirected graph. """ if len(connected_components(G)) != 1: raise GraphInsertError("Prim algorithm work with connected graph only") if start not in G.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (start,)) pred = {} key = {} pqueue = {} lowest = 0 for edge in G.edges: if G.edges[edge][weight] > lowest: lowest = G.edges[edge][weight] for vertex in G.vertices: pred[vertex] = None key[vertex] = 2 * lowest key[start] = 0 for vertex in G.vertices: pqueue[vertex] = key[vertex] while pqueue: current = popmin(pqueue, lowest) for neighbor in G.vertices[current]: if (neighbor in pqueue and G.edges[(current, neighbor)][weight] < key[neighbor]): pred[neighbor] = current key[neighbor] = G.edges[(current, neighbor)][weight] pqueue[neighbor] = G.edges[(current, neighbor)][weight] return pred
[ "def", "prim", "(", "G", ",", "start", ",", "weight", "=", "'weight'", ")", ":", "if", "len", "(", "connected_components", "(", "G", ")", ")", "!=", "1", ":", "raise", "GraphInsertError", "(", "\"Prim algorithm work with connected graph only\"", ")", "if", "start", "not", "in", "G", ".", "vertices", ":", "raise", "GraphInsertError", "(", "\"Vertex %s doesn't exist.\"", "%", "(", "start", ",", ")", ")", "pred", "=", "{", "}", "key", "=", "{", "}", "pqueue", "=", "{", "}", "lowest", "=", "0", "for", "edge", "in", "G", ".", "edges", ":", "if", "G", ".", "edges", "[", "edge", "]", "[", "weight", "]", ">", "lowest", ":", "lowest", "=", "G", ".", "edges", "[", "edge", "]", "[", "weight", "]", "for", "vertex", "in", "G", ".", "vertices", ":", "pred", "[", "vertex", "]", "=", "None", "key", "[", "vertex", "]", "=", "2", "*", "lowest", "key", "[", "start", "]", "=", "0", "for", "vertex", "in", "G", ".", "vertices", ":", "pqueue", "[", "vertex", "]", "=", "key", "[", "vertex", "]", "while", "pqueue", ":", "current", "=", "popmin", "(", "pqueue", ",", "lowest", ")", "for", "neighbor", "in", "G", ".", "vertices", "[", "current", "]", ":", "if", "(", "neighbor", "in", "pqueue", "and", "G", ".", "edges", "[", "(", "current", ",", "neighbor", ")", "]", "[", "weight", "]", "<", "key", "[", "neighbor", "]", ")", ":", "pred", "[", "neighbor", "]", "=", "current", "key", "[", "neighbor", "]", "=", "G", ".", "edges", "[", "(", "current", ",", "neighbor", ")", "]", "[", "weight", "]", "pqueue", "[", "neighbor", "]", "=", "G", ".", "edges", "[", "(", "current", ",", "neighbor", ")", "]", "[", "weight", "]", "return", "pred" ]
Algorithm for finding a minimum spanning tree for a weighted undirected graph.
[ "Algorithm", "for", "finding", "a", "minimum", "spanning", "tree", "for", "a", "weighted", "undirected", "graph", "." ]
bf979a80bdea17eeb25955f0c119ca8f711ef62b
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/prim.py#L43-L73
247,823
robertdfrench/psychic-disco
psychic_disco/rest_api.py
RestApi.find
def find(cls, api_name): """ Find or create an API model object by name """ if api_name in cls.apis_by_name: return cls.apis_by_name[api_name] api = cls(api_name) api._fetch_from_aws() if api.exists_in_aws: api._fetch_resources() cls.apis_by_name[api_name] = api return api
python
def find(cls, api_name): """ Find or create an API model object by name """ if api_name in cls.apis_by_name: return cls.apis_by_name[api_name] api = cls(api_name) api._fetch_from_aws() if api.exists_in_aws: api._fetch_resources() cls.apis_by_name[api_name] = api return api
[ "def", "find", "(", "cls", ",", "api_name", ")", ":", "if", "api_name", "in", "cls", ".", "apis_by_name", ":", "return", "cls", ".", "apis_by_name", "[", "api_name", "]", "api", "=", "cls", "(", "api_name", ")", "api", ".", "_fetch_from_aws", "(", ")", "if", "api", ".", "exists_in_aws", ":", "api", ".", "_fetch_resources", "(", ")", "cls", ".", "apis_by_name", "[", "api_name", "]", "=", "api", "return", "api" ]
Find or create an API model object by name
[ "Find", "or", "create", "an", "API", "model", "object", "by", "name" ]
3cf167b44c64d64606691fc186be7d9ef8e8e938
https://github.com/robertdfrench/psychic-disco/blob/3cf167b44c64d64606691fc186be7d9ef8e8e938/psychic_disco/rest_api.py#L20-L29
247,824
hapylestat/apputils
apputils/settings/general.py
Configuration._load_from_configs
def _load_from_configs(self, filename): """ Return content of file which located in configuration directory """ config_filename = os.path.join(self._config_path, filename) if os.path.exists(config_filename): try: f = open(config_filename, 'r') content = ''.join(f.readlines()) f.close() return content except Exception as err: raise err else: raise IOError("File not found: {}".format(config_filename))
python
def _load_from_configs(self, filename): """ Return content of file which located in configuration directory """ config_filename = os.path.join(self._config_path, filename) if os.path.exists(config_filename): try: f = open(config_filename, 'r') content = ''.join(f.readlines()) f.close() return content except Exception as err: raise err else: raise IOError("File not found: {}".format(config_filename))
[ "def", "_load_from_configs", "(", "self", ",", "filename", ")", ":", "config_filename", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_config_path", ",", "filename", ")", "if", "os", ".", "path", ".", "exists", "(", "config_filename", ")", ":", "try", ":", "f", "=", "open", "(", "config_filename", ",", "'r'", ")", "content", "=", "''", ".", "join", "(", "f", ".", "readlines", "(", ")", ")", "f", ".", "close", "(", ")", "return", "content", "except", "Exception", "as", "err", ":", "raise", "err", "else", ":", "raise", "IOError", "(", "\"File not found: {}\"", ".", "format", "(", "config_filename", ")", ")" ]
Return content of file which located in configuration directory
[ "Return", "content", "of", "file", "which", "located", "in", "configuration", "directory" ]
5d185616feda27e6e21273307161471ef11a3518
https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/settings/general.py#L70-L84
247,825
hapylestat/apputils
apputils/settings/general.py
Configuration.load
def load(self): """ Load application configuration """ try: if not self.__in_memory: self._json = json.loads(self._load_from_configs(self._main_config)) # ToDo: make this via extension for root logger # self._log = aLogger.getLogger(__name__, cfg=self) # reload logger using loaded configuration self._load_modules() else: self._json = {} # parse command line, currently used for re-assign settings in configuration, but can't be used as replacement self._load_from_commandline() except Exception as err: self._json = None raise
python
def load(self): """ Load application configuration """ try: if not self.__in_memory: self._json = json.loads(self._load_from_configs(self._main_config)) # ToDo: make this via extension for root logger # self._log = aLogger.getLogger(__name__, cfg=self) # reload logger using loaded configuration self._load_modules() else: self._json = {} # parse command line, currently used for re-assign settings in configuration, but can't be used as replacement self._load_from_commandline() except Exception as err: self._json = None raise
[ "def", "load", "(", "self", ")", ":", "try", ":", "if", "not", "self", ".", "__in_memory", ":", "self", ".", "_json", "=", "json", ".", "loads", "(", "self", ".", "_load_from_configs", "(", "self", ".", "_main_config", ")", ")", "# ToDo: make this via extension for root logger", "# self._log = aLogger.getLogger(__name__, cfg=self) # reload logger using loaded configuration", "self", ".", "_load_modules", "(", ")", "else", ":", "self", ".", "_json", "=", "{", "}", "# parse command line, currently used for re-assign settings in configuration, but can't be used as replacement", "self", ".", "_load_from_commandline", "(", ")", "except", "Exception", "as", "err", ":", "self", ".", "_json", "=", "None", "raise" ]
Load application configuration
[ "Load", "application", "configuration" ]
5d185616feda27e6e21273307161471ef11a3518
https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/settings/general.py#L86-L102
247,826
hapylestat/apputils
apputils/settings/general.py
Configuration.get
def get(self, path, default=None, check_type=None, module_name=None): """ Get option property :param path: full path to the property with name :param default: default value if original is not present :param check_type: cast param to passed type, if fail, default will returned :param module_name: get property from module name :return: """ if self._json is not None: # process whole json or just concrete module node = self._json if module_name is None else self.get_module_config(module_name) path_data = path.split('.') try: while len(path_data) > 0: node = node[path_data.pop(0)] if check_type is not None: return check_type(node) else: return node except KeyError: if default is not None: return default else: raise KeyError("Key {} not present".format(path)) except ValueError: if default is not None: return default else: raise KeyError("Key {} has a wrong format".format(path)) else: return ""
python
def get(self, path, default=None, check_type=None, module_name=None): """ Get option property :param path: full path to the property with name :param default: default value if original is not present :param check_type: cast param to passed type, if fail, default will returned :param module_name: get property from module name :return: """ if self._json is not None: # process whole json or just concrete module node = self._json if module_name is None else self.get_module_config(module_name) path_data = path.split('.') try: while len(path_data) > 0: node = node[path_data.pop(0)] if check_type is not None: return check_type(node) else: return node except KeyError: if default is not None: return default else: raise KeyError("Key {} not present".format(path)) except ValueError: if default is not None: return default else: raise KeyError("Key {} has a wrong format".format(path)) else: return ""
[ "def", "get", "(", "self", ",", "path", ",", "default", "=", "None", ",", "check_type", "=", "None", ",", "module_name", "=", "None", ")", ":", "if", "self", ".", "_json", "is", "not", "None", ":", "# process whole json or just concrete module", "node", "=", "self", ".", "_json", "if", "module_name", "is", "None", "else", "self", ".", "get_module_config", "(", "module_name", ")", "path_data", "=", "path", ".", "split", "(", "'.'", ")", "try", ":", "while", "len", "(", "path_data", ")", ">", "0", ":", "node", "=", "node", "[", "path_data", ".", "pop", "(", "0", ")", "]", "if", "check_type", "is", "not", "None", ":", "return", "check_type", "(", "node", ")", "else", ":", "return", "node", "except", "KeyError", ":", "if", "default", "is", "not", "None", ":", "return", "default", "else", ":", "raise", "KeyError", "(", "\"Key {} not present\"", ".", "format", "(", "path", ")", ")", "except", "ValueError", ":", "if", "default", "is", "not", "None", ":", "return", "default", "else", ":", "raise", "KeyError", "(", "\"Key {} has a wrong format\"", ".", "format", "(", "path", ")", ")", "else", ":", "return", "\"\"" ]
Get option property :param path: full path to the property with name :param default: default value if original is not present :param check_type: cast param to passed type, if fail, default will returned :param module_name: get property from module name :return:
[ "Get", "option", "property" ]
5d185616feda27e6e21273307161471ef11a3518
https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/settings/general.py#L156-L189
247,827
hapylestat/apputils
apputils/settings/general.py
Configuration.get_module_config
def get_module_config(self, name): """ Return module configuration loaded from separate file or None """ if self.exists("modules"): if name in self._json["modules"] and not isinstance(self._json["modules"][name], str): return self._json["modules"][name] return None
python
def get_module_config(self, name): """ Return module configuration loaded from separate file or None """ if self.exists("modules"): if name in self._json["modules"] and not isinstance(self._json["modules"][name], str): return self._json["modules"][name] return None
[ "def", "get_module_config", "(", "self", ",", "name", ")", ":", "if", "self", ".", "exists", "(", "\"modules\"", ")", ":", "if", "name", "in", "self", ".", "_json", "[", "\"modules\"", "]", "and", "not", "isinstance", "(", "self", ".", "_json", "[", "\"modules\"", "]", "[", "name", "]", ",", "str", ")", ":", "return", "self", ".", "_json", "[", "\"modules\"", "]", "[", "name", "]", "return", "None" ]
Return module configuration loaded from separate file or None
[ "Return", "module", "configuration", "loaded", "from", "separate", "file", "or", "None" ]
5d185616feda27e6e21273307161471ef11a3518
https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/settings/general.py#L191-L198
247,828
naphatkrit/easyci
easyci/hooks/hooks_manager.py
get_hook
def get_hook(hook_name): """Returns the specified hook. Args: hook_name (str) Returns: str - (the content of) the hook Raises: HookNotFoundError """ if not pkg_resources.resource_exists(__name__, hook_name): raise HookNotFoundError return pkg_resources.resource_string(__name__, hook_name)
python
def get_hook(hook_name): """Returns the specified hook. Args: hook_name (str) Returns: str - (the content of) the hook Raises: HookNotFoundError """ if not pkg_resources.resource_exists(__name__, hook_name): raise HookNotFoundError return pkg_resources.resource_string(__name__, hook_name)
[ "def", "get_hook", "(", "hook_name", ")", ":", "if", "not", "pkg_resources", ".", "resource_exists", "(", "__name__", ",", "hook_name", ")", ":", "raise", "HookNotFoundError", "return", "pkg_resources", ".", "resource_string", "(", "__name__", ",", "hook_name", ")" ]
Returns the specified hook. Args: hook_name (str) Returns: str - (the content of) the hook Raises: HookNotFoundError
[ "Returns", "the", "specified", "hook", "." ]
7aee8d7694fe4e2da42ce35b0f700bc840c8b95f
https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/hooks/hooks_manager.py#L8-L22
247,829
Othernet-Project/conz
conz/progress.py
Progress.end
def end(self, s=None, post=None, noraise=False): """ Prints the end banner and raises ``ProgressOK`` exception When ``noraise`` flag is set to ``True``, then the exception is not raised, and progress is allowed to continue. If ``post`` function is supplied it is invoked with no arguments after the close banner is printed, but before exceptions are raised. The ``post`` function takes no arguments. """ s = s or self.end_msg self.printer(self.color.green(s)) if post: post() if noraise: return raise ProgressOK()
python
def end(self, s=None, post=None, noraise=False): """ Prints the end banner and raises ``ProgressOK`` exception When ``noraise`` flag is set to ``True``, then the exception is not raised, and progress is allowed to continue. If ``post`` function is supplied it is invoked with no arguments after the close banner is printed, but before exceptions are raised. The ``post`` function takes no arguments. """ s = s or self.end_msg self.printer(self.color.green(s)) if post: post() if noraise: return raise ProgressOK()
[ "def", "end", "(", "self", ",", "s", "=", "None", ",", "post", "=", "None", ",", "noraise", "=", "False", ")", ":", "s", "=", "s", "or", "self", ".", "end_msg", "self", ".", "printer", "(", "self", ".", "color", ".", "green", "(", "s", ")", ")", "if", "post", ":", "post", "(", ")", "if", "noraise", ":", "return", "raise", "ProgressOK", "(", ")" ]
Prints the end banner and raises ``ProgressOK`` exception When ``noraise`` flag is set to ``True``, then the exception is not raised, and progress is allowed to continue. If ``post`` function is supplied it is invoked with no arguments after the close banner is printed, but before exceptions are raised. The ``post`` function takes no arguments.
[ "Prints", "the", "end", "banner", "and", "raises", "ProgressOK", "exception" ]
051214fa95a837c21595b03426a2c54c522d07a0
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/progress.py#L55-L71
247,830
Othernet-Project/conz
conz/progress.py
Progress.abrt
def abrt(self, s=None, post=None, noraise=False): """ Prints the abrt banner and raises ``ProgressAbrt`` exception When ``noraise`` flag is set to ``True``, then the exception is not raised, and progress is allowed to continue. If ``post`` function is supplied it is invoked with no arguments after the close banner is printed, but before exceptions are raised. The ``post`` function takes no arguments. """ s = s or self.abrt_msg self.printer(self.color.red(s)) if post: post() if noraise: return raise ProgressAbrt()
python
def abrt(self, s=None, post=None, noraise=False): """ Prints the abrt banner and raises ``ProgressAbrt`` exception When ``noraise`` flag is set to ``True``, then the exception is not raised, and progress is allowed to continue. If ``post`` function is supplied it is invoked with no arguments after the close banner is printed, but before exceptions are raised. The ``post`` function takes no arguments. """ s = s or self.abrt_msg self.printer(self.color.red(s)) if post: post() if noraise: return raise ProgressAbrt()
[ "def", "abrt", "(", "self", ",", "s", "=", "None", ",", "post", "=", "None", ",", "noraise", "=", "False", ")", ":", "s", "=", "s", "or", "self", ".", "abrt_msg", "self", ".", "printer", "(", "self", ".", "color", ".", "red", "(", "s", ")", ")", "if", "post", ":", "post", "(", ")", "if", "noraise", ":", "return", "raise", "ProgressAbrt", "(", ")" ]
Prints the abrt banner and raises ``ProgressAbrt`` exception When ``noraise`` flag is set to ``True``, then the exception is not raised, and progress is allowed to continue. If ``post`` function is supplied it is invoked with no arguments after the close banner is printed, but before exceptions are raised. The ``post`` function takes no arguments.
[ "Prints", "the", "abrt", "banner", "and", "raises", "ProgressAbrt", "exception" ]
051214fa95a837c21595b03426a2c54c522d07a0
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/progress.py#L73-L89
247,831
Othernet-Project/conz
conz/progress.py
Progress.prog
def prog(self, s=None): """ Prints the progress indicator """ s = s or self.prog_msg self.printer(s, end='')
python
def prog(self, s=None): """ Prints the progress indicator """ s = s or self.prog_msg self.printer(s, end='')
[ "def", "prog", "(", "self", ",", "s", "=", "None", ")", ":", "s", "=", "s", "or", "self", ".", "prog_msg", "self", ".", "printer", "(", "s", ",", "end", "=", "''", ")" ]
Prints the progress indicator
[ "Prints", "the", "progress", "indicator" ]
051214fa95a837c21595b03426a2c54c522d07a0
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/progress.py#L91-L94
247,832
ECESeniorDesign/lazy_record
lazy_record/repo.py
Repo.where
def where(self, custom_restrictions=[], **restrictions): """ Analog to SQL "WHERE". Does not perform a query until `select` is called. Returns a repo object. Options selected through keyword arguments are assumed to use == unles the value is a list, tuple, or dictionary. List or tuple values translate to an SQL `IN` over those values, and a dictionary looks up under a different table when joined. ex) >>> Repo("foos").where(id=11).select("*") SELECT foos.* FROM foos WHERE foos.id == 11 >>> Repo("foos").where([("id > ?", 12)]).select("*") SELECT foos.* FROM foos WHERE foos.id > 12 >>> Repo("foos").where(id=[1,2,3]).select("*") SELECT foos.* FROM foos WHERE foos.id IN (1, 2, 3) """ # Generate the SQL pieces and the relevant values standard_names, standard_values = self._standard_items(restrictions) custom_names, custom_values = self._custom_items(custom_restrictions) in_names, in_values = self._in_items(restrictions) query_names = standard_names + custom_names + in_names # Stitch them into a clause with values if query_names: self.where_values = standard_values + custom_values + in_values self.where_clause = "where {query} ".format( query=" and ".join(query_names)) return self
python
def where(self, custom_restrictions=[], **restrictions): """ Analog to SQL "WHERE". Does not perform a query until `select` is called. Returns a repo object. Options selected through keyword arguments are assumed to use == unles the value is a list, tuple, or dictionary. List or tuple values translate to an SQL `IN` over those values, and a dictionary looks up under a different table when joined. ex) >>> Repo("foos").where(id=11).select("*") SELECT foos.* FROM foos WHERE foos.id == 11 >>> Repo("foos").where([("id > ?", 12)]).select("*") SELECT foos.* FROM foos WHERE foos.id > 12 >>> Repo("foos").where(id=[1,2,3]).select("*") SELECT foos.* FROM foos WHERE foos.id IN (1, 2, 3) """ # Generate the SQL pieces and the relevant values standard_names, standard_values = self._standard_items(restrictions) custom_names, custom_values = self._custom_items(custom_restrictions) in_names, in_values = self._in_items(restrictions) query_names = standard_names + custom_names + in_names # Stitch them into a clause with values if query_names: self.where_values = standard_values + custom_values + in_values self.where_clause = "where {query} ".format( query=" and ".join(query_names)) return self
[ "def", "where", "(", "self", ",", "custom_restrictions", "=", "[", "]", ",", "*", "*", "restrictions", ")", ":", "# Generate the SQL pieces and the relevant values", "standard_names", ",", "standard_values", "=", "self", ".", "_standard_items", "(", "restrictions", ")", "custom_names", ",", "custom_values", "=", "self", ".", "_custom_items", "(", "custom_restrictions", ")", "in_names", ",", "in_values", "=", "self", ".", "_in_items", "(", "restrictions", ")", "query_names", "=", "standard_names", "+", "custom_names", "+", "in_names", "# Stitch them into a clause with values", "if", "query_names", ":", "self", ".", "where_values", "=", "standard_values", "+", "custom_values", "+", "in_values", "self", ".", "where_clause", "=", "\"where {query} \"", ".", "format", "(", "query", "=", "\" and \"", ".", "join", "(", "query_names", ")", ")", "return", "self" ]
Analog to SQL "WHERE". Does not perform a query until `select` is called. Returns a repo object. Options selected through keyword arguments are assumed to use == unles the value is a list, tuple, or dictionary. List or tuple values translate to an SQL `IN` over those values, and a dictionary looks up under a different table when joined. ex) >>> Repo("foos").where(id=11).select("*") SELECT foos.* FROM foos WHERE foos.id == 11 >>> Repo("foos").where([("id > ?", 12)]).select("*") SELECT foos.* FROM foos WHERE foos.id > 12 >>> Repo("foos").where(id=[1,2,3]).select("*") SELECT foos.* FROM foos WHERE foos.id IN (1, 2, 3)
[ "Analog", "to", "SQL", "WHERE", ".", "Does", "not", "perform", "a", "query", "until", "select", "is", "called", ".", "Returns", "a", "repo", "object", ".", "Options", "selected", "through", "keyword", "arguments", "are", "assumed", "to", "use", "==", "unles", "the", "value", "is", "a", "list", "tuple", "or", "dictionary", ".", "List", "or", "tuple", "values", "translate", "to", "an", "SQL", "IN", "over", "those", "values", "and", "a", "dictionary", "looks", "up", "under", "a", "different", "table", "when", "joined", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/repo.py#L34-L61
247,833
ECESeniorDesign/lazy_record
lazy_record/repo.py
Repo.order_by
def order_by(self, **kwargs): """ Analog to SQL "ORDER BY". +kwargs+ should only contain one item. examples) NO: repo.order_by() NO: repo.order_by(id="desc", name="asc") YES: repo.order_by(id="asc) """ if kwargs: col, order = kwargs.popitem() self.order_clause = "order by {col} {order} ".format( col=col, order=order) return self
python
def order_by(self, **kwargs): """ Analog to SQL "ORDER BY". +kwargs+ should only contain one item. examples) NO: repo.order_by() NO: repo.order_by(id="desc", name="asc") YES: repo.order_by(id="asc) """ if kwargs: col, order = kwargs.popitem() self.order_clause = "order by {col} {order} ".format( col=col, order=order) return self
[ "def", "order_by", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "col", ",", "order", "=", "kwargs", ".", "popitem", "(", ")", "self", ".", "order_clause", "=", "\"order by {col} {order} \"", ".", "format", "(", "col", "=", "col", ",", "order", "=", "order", ")", "return", "self" ]
Analog to SQL "ORDER BY". +kwargs+ should only contain one item. examples) NO: repo.order_by() NO: repo.order_by(id="desc", name="asc") YES: repo.order_by(id="asc)
[ "Analog", "to", "SQL", "ORDER", "BY", ".", "+", "kwargs", "+", "should", "only", "contain", "one", "item", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/repo.py#L140-L155
247,834
ECESeniorDesign/lazy_record
lazy_record/repo.py
Repo.select
def select(self, *attributes): """ Select the passed +attributes+ from the table, subject to the restrictions provided by the other methods in this class. ex) >>> Repo("foos").select("name", "id") SELECT foos.name, foos.id FROM foos """ namespaced_attributes = [ "{table}.{attr}".format(table=self.table_name, attr=attr) for attr in attributes ] cmd = ('select {attrs} from {table} ' '{join_clause}{where_clause}{order_clause}' '{group_clause}{having_clause}{limit_clause}').format( table=self.table_name, attrs=", ".join(namespaced_attributes), where_clause=self.where_clause, join_clause=self.join_clause, order_clause=self.order_clause, group_clause=self.group_clause, having_clause=self.having_clause, limit_clause=self.limit_clause, ).rstrip() return Repo.db.execute(cmd, self.where_values + self.having_values + \ self.limit_value)
python
def select(self, *attributes): """ Select the passed +attributes+ from the table, subject to the restrictions provided by the other methods in this class. ex) >>> Repo("foos").select("name", "id") SELECT foos.name, foos.id FROM foos """ namespaced_attributes = [ "{table}.{attr}".format(table=self.table_name, attr=attr) for attr in attributes ] cmd = ('select {attrs} from {table} ' '{join_clause}{where_clause}{order_clause}' '{group_clause}{having_clause}{limit_clause}').format( table=self.table_name, attrs=", ".join(namespaced_attributes), where_clause=self.where_clause, join_clause=self.join_clause, order_clause=self.order_clause, group_clause=self.group_clause, having_clause=self.having_clause, limit_clause=self.limit_clause, ).rstrip() return Repo.db.execute(cmd, self.where_values + self.having_values + \ self.limit_value)
[ "def", "select", "(", "self", ",", "*", "attributes", ")", ":", "namespaced_attributes", "=", "[", "\"{table}.{attr}\"", ".", "format", "(", "table", "=", "self", ".", "table_name", ",", "attr", "=", "attr", ")", "for", "attr", "in", "attributes", "]", "cmd", "=", "(", "'select {attrs} from {table} '", "'{join_clause}{where_clause}{order_clause}'", "'{group_clause}{having_clause}{limit_clause}'", ")", ".", "format", "(", "table", "=", "self", ".", "table_name", ",", "attrs", "=", "\", \"", ".", "join", "(", "namespaced_attributes", ")", ",", "where_clause", "=", "self", ".", "where_clause", ",", "join_clause", "=", "self", ".", "join_clause", ",", "order_clause", "=", "self", ".", "order_clause", ",", "group_clause", "=", "self", ".", "group_clause", ",", "having_clause", "=", "self", ".", "having_clause", ",", "limit_clause", "=", "self", ".", "limit_clause", ",", ")", ".", "rstrip", "(", ")", "return", "Repo", ".", "db", ".", "execute", "(", "cmd", ",", "self", ".", "where_values", "+", "self", ".", "having_values", "+", "self", ".", "limit_value", ")" ]
Select the passed +attributes+ from the table, subject to the restrictions provided by the other methods in this class. ex) >>> Repo("foos").select("name", "id") SELECT foos.name, foos.id FROM foos
[ "Select", "the", "passed", "+", "attributes", "+", "from", "the", "table", "subject", "to", "the", "restrictions", "provided", "by", "the", "other", "methods", "in", "this", "class", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/repo.py#L197-L224
247,835
ECESeniorDesign/lazy_record
lazy_record/repo.py
Repo.count
def count(self): """ Count the number of records in the table, subject to the query. """ cmd = ("select COUNT(*) from {table} " "{join_clause}{where_clause}{order_clause}").format( table=self.table_name, where_clause=self.where_clause, join_clause=self.join_clause, order_clause=self.order_clause).rstrip() return Repo.db.execute(cmd, self.where_values)
python
def count(self): """ Count the number of records in the table, subject to the query. """ cmd = ("select COUNT(*) from {table} " "{join_clause}{where_clause}{order_clause}").format( table=self.table_name, where_clause=self.where_clause, join_clause=self.join_clause, order_clause=self.order_clause).rstrip() return Repo.db.execute(cmd, self.where_values)
[ "def", "count", "(", "self", ")", ":", "cmd", "=", "(", "\"select COUNT(*) from {table} \"", "\"{join_clause}{where_clause}{order_clause}\"", ")", ".", "format", "(", "table", "=", "self", ".", "table_name", ",", "where_clause", "=", "self", ".", "where_clause", ",", "join_clause", "=", "self", ".", "join_clause", ",", "order_clause", "=", "self", ".", "order_clause", ")", ".", "rstrip", "(", ")", "return", "Repo", ".", "db", ".", "execute", "(", "cmd", ",", "self", ".", "where_values", ")" ]
Count the number of records in the table, subject to the query.
[ "Count", "the", "number", "of", "records", "in", "the", "table", "subject", "to", "the", "query", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/repo.py#L226-L236
247,836
ECESeniorDesign/lazy_record
lazy_record/repo.py
Repo.update
def update(self, **data): """ Update records in the table with +data+. Often combined with `where`, as it acts on all records in the table unless restricted. ex) >>> Repo("foos").update(name="bar") UPDATE foos SET name = "bar" """ data = data.items() update_command_arg = ", ".join("{} = ?".format(entry[0]) for entry in data) cmd = "update {table} set {update_command_arg} {where_clause}".format( update_command_arg=update_command_arg, where_clause=self.where_clause, table=self.table_name).rstrip() Repo.db.execute(cmd, [entry[1] for entry in data] + self.where_values)
python
def update(self, **data): """ Update records in the table with +data+. Often combined with `where`, as it acts on all records in the table unless restricted. ex) >>> Repo("foos").update(name="bar") UPDATE foos SET name = "bar" """ data = data.items() update_command_arg = ", ".join("{} = ?".format(entry[0]) for entry in data) cmd = "update {table} set {update_command_arg} {where_clause}".format( update_command_arg=update_command_arg, where_clause=self.where_clause, table=self.table_name).rstrip() Repo.db.execute(cmd, [entry[1] for entry in data] + self.where_values)
[ "def", "update", "(", "self", ",", "*", "*", "data", ")", ":", "data", "=", "data", ".", "items", "(", ")", "update_command_arg", "=", "\", \"", ".", "join", "(", "\"{} = ?\"", ".", "format", "(", "entry", "[", "0", "]", ")", "for", "entry", "in", "data", ")", "cmd", "=", "\"update {table} set {update_command_arg} {where_clause}\"", ".", "format", "(", "update_command_arg", "=", "update_command_arg", ",", "where_clause", "=", "self", ".", "where_clause", ",", "table", "=", "self", ".", "table_name", ")", ".", "rstrip", "(", ")", "Repo", ".", "db", ".", "execute", "(", "cmd", ",", "[", "entry", "[", "1", "]", "for", "entry", "in", "data", "]", "+", "self", ".", "where_values", ")" ]
Update records in the table with +data+. Often combined with `where`, as it acts on all records in the table unless restricted. ex) >>> Repo("foos").update(name="bar") UPDATE foos SET name = "bar"
[ "Update", "records", "in", "the", "table", "with", "+", "data", "+", ".", "Often", "combined", "with", "where", "as", "it", "acts", "on", "all", "records", "in", "the", "table", "unless", "restricted", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/repo.py#L256-L273
247,837
ECESeniorDesign/lazy_record
lazy_record/repo.py
Repo.delete
def delete(self): """ Remove entries from the table. Often combined with `where`, as it acts on all records in the table unless restricted. """ cmd = "delete from {table} {where_clause}".format( table=self.table_name, where_clause=self.where_clause ).rstrip() Repo.db.execute(cmd, self.where_values)
python
def delete(self): """ Remove entries from the table. Often combined with `where`, as it acts on all records in the table unless restricted. """ cmd = "delete from {table} {where_clause}".format( table=self.table_name, where_clause=self.where_clause ).rstrip() Repo.db.execute(cmd, self.where_values)
[ "def", "delete", "(", "self", ")", ":", "cmd", "=", "\"delete from {table} {where_clause}\"", ".", "format", "(", "table", "=", "self", ".", "table_name", ",", "where_clause", "=", "self", ".", "where_clause", ")", ".", "rstrip", "(", ")", "Repo", ".", "db", ".", "execute", "(", "cmd", ",", "self", ".", "where_values", ")" ]
Remove entries from the table. Often combined with `where`, as it acts on all records in the table unless restricted.
[ "Remove", "entries", "from", "the", "table", ".", "Often", "combined", "with", "where", "as", "it", "acts", "on", "all", "records", "in", "the", "table", "unless", "restricted", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/repo.py#L275-L284
247,838
ECESeniorDesign/lazy_record
lazy_record/repo.py
Repo.connect_db
def connect_db(Repo, database=":memory:"): """ Connect Repo to a database with path +database+ so all instances can interact with the database. """ Repo.db = sqlite3.connect(database, detect_types=sqlite3.PARSE_DECLTYPES) return Repo.db
python
def connect_db(Repo, database=":memory:"): """ Connect Repo to a database with path +database+ so all instances can interact with the database. """ Repo.db = sqlite3.connect(database, detect_types=sqlite3.PARSE_DECLTYPES) return Repo.db
[ "def", "connect_db", "(", "Repo", ",", "database", "=", "\":memory:\"", ")", ":", "Repo", ".", "db", "=", "sqlite3", ".", "connect", "(", "database", ",", "detect_types", "=", "sqlite3", ".", "PARSE_DECLTYPES", ")", "return", "Repo", ".", "db" ]
Connect Repo to a database with path +database+ so all instances can interact with the database.
[ "Connect", "Repo", "to", "a", "database", "with", "path", "+", "database", "+", "so", "all", "instances", "can", "interact", "with", "the", "database", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/repo.py#L294-L301
247,839
dcramer/peek
peek/tracer.py
Tracer._trace
def _trace(self, frame, event, arg_unused): """ The trace function passed to sys.settrace. """ cur_time = time.time() lineno = frame.f_lineno depth = self.depth filename = inspect.getfile(frame) if self.last_exc_back: if frame == self.last_exc_back: self.data['time_spent'] += (cur_time - self.start_time) self.depth -= 1 self.data = self.data_stack.pop() self.last_exc_back = None if event == 'call': # Update our state self.depth += 1 if self.log: print >> sys.stdout, '%s >> %s:%s' % (' ' * (depth - 1), filename, frame.f_code.co_name) # origin line number (where it was called from) o_lineno = frame.f_back.f_lineno if self.pause_until is not None: if depth == self.pause_until: self.pause_until = None else: return self._trace if o_lineno not in self.data['lines']: self.pause_until = depth return self._trace # Append it to the stack self.data_stack.append(self.data) call_sig = '%s:%s' % (inspect.getfile(frame), frame.f_code.co_name) if call_sig not in self.data['children']: self.data['children'][o_lineno][call_sig] = self._get_struct(frame, event) self.data = self.data['children'][o_lineno][call_sig] self.data['num_calls'] += 1 elif event == 'line': # Record an executed line. if self.pause_until is None and lineno in self.data['lines']: self.data['lines'][lineno]['num_calls'] += 1 self.data['lines'][lineno]['time_spent'] += (cur_time - self.start_time) if self.log: print >> sys.stdout, '%s -- %s:%s executing line %d' % (' ' * (depth - 1), filename, frame.f_code.co_name, lineno) elif event == 'return': timing = (cur_time - self.start_time) # Leaving this function, pop the filename stack. if self.pause_until is None: self.data['time_spent'] += timing self.data = self.data_stack.pop() self.data['time_spent'] += timing # self.data['lines'][lineno]['num_calls'] += 1 # self.data['lines'][lineno]['time_spent'] += (cur_time - self.start_time) if self.log: print >> sys.stdout, '%s << %s:%s %.3fs' % (' ' * (depth - 1), filename, frame.f_code.co_name, timing) self.depth -= 1 elif event == 'exception': self.last_exc_back = frame.f_back self.last_exc_firstlineno = frame.f_code.co_firstlineno return self._trace
python
def _trace(self, frame, event, arg_unused): """ The trace function passed to sys.settrace. """ cur_time = time.time() lineno = frame.f_lineno depth = self.depth filename = inspect.getfile(frame) if self.last_exc_back: if frame == self.last_exc_back: self.data['time_spent'] += (cur_time - self.start_time) self.depth -= 1 self.data = self.data_stack.pop() self.last_exc_back = None if event == 'call': # Update our state self.depth += 1 if self.log: print >> sys.stdout, '%s >> %s:%s' % (' ' * (depth - 1), filename, frame.f_code.co_name) # origin line number (where it was called from) o_lineno = frame.f_back.f_lineno if self.pause_until is not None: if depth == self.pause_until: self.pause_until = None else: return self._trace if o_lineno not in self.data['lines']: self.pause_until = depth return self._trace # Append it to the stack self.data_stack.append(self.data) call_sig = '%s:%s' % (inspect.getfile(frame), frame.f_code.co_name) if call_sig not in self.data['children']: self.data['children'][o_lineno][call_sig] = self._get_struct(frame, event) self.data = self.data['children'][o_lineno][call_sig] self.data['num_calls'] += 1 elif event == 'line': # Record an executed line. if self.pause_until is None and lineno in self.data['lines']: self.data['lines'][lineno]['num_calls'] += 1 self.data['lines'][lineno]['time_spent'] += (cur_time - self.start_time) if self.log: print >> sys.stdout, '%s -- %s:%s executing line %d' % (' ' * (depth - 1), filename, frame.f_code.co_name, lineno) elif event == 'return': timing = (cur_time - self.start_time) # Leaving this function, pop the filename stack. if self.pause_until is None: self.data['time_spent'] += timing self.data = self.data_stack.pop() self.data['time_spent'] += timing # self.data['lines'][lineno]['num_calls'] += 1 # self.data['lines'][lineno]['time_spent'] += (cur_time - self.start_time) if self.log: print >> sys.stdout, '%s << %s:%s %.3fs' % (' ' * (depth - 1), filename, frame.f_code.co_name, timing) self.depth -= 1 elif event == 'exception': self.last_exc_back = frame.f_back self.last_exc_firstlineno = frame.f_code.co_firstlineno return self._trace
[ "def", "_trace", "(", "self", ",", "frame", ",", "event", ",", "arg_unused", ")", ":", "cur_time", "=", "time", ".", "time", "(", ")", "lineno", "=", "frame", ".", "f_lineno", "depth", "=", "self", ".", "depth", "filename", "=", "inspect", ".", "getfile", "(", "frame", ")", "if", "self", ".", "last_exc_back", ":", "if", "frame", "==", "self", ".", "last_exc_back", ":", "self", ".", "data", "[", "'time_spent'", "]", "+=", "(", "cur_time", "-", "self", ".", "start_time", ")", "self", ".", "depth", "-=", "1", "self", ".", "data", "=", "self", ".", "data_stack", ".", "pop", "(", ")", "self", ".", "last_exc_back", "=", "None", "if", "event", "==", "'call'", ":", "# Update our state", "self", ".", "depth", "+=", "1", "if", "self", ".", "log", ":", "print", ">>", "sys", ".", "stdout", ",", "'%s >> %s:%s'", "%", "(", "' '", "*", "(", "depth", "-", "1", ")", ",", "filename", ",", "frame", ".", "f_code", ".", "co_name", ")", "# origin line number (where it was called from)", "o_lineno", "=", "frame", ".", "f_back", ".", "f_lineno", "if", "self", ".", "pause_until", "is", "not", "None", ":", "if", "depth", "==", "self", ".", "pause_until", ":", "self", ".", "pause_until", "=", "None", "else", ":", "return", "self", ".", "_trace", "if", "o_lineno", "not", "in", "self", ".", "data", "[", "'lines'", "]", ":", "self", ".", "pause_until", "=", "depth", "return", "self", ".", "_trace", "# Append it to the stack", "self", ".", "data_stack", ".", "append", "(", "self", ".", "data", ")", "call_sig", "=", "'%s:%s'", "%", "(", "inspect", ".", "getfile", "(", "frame", ")", ",", "frame", ".", "f_code", ".", "co_name", ")", "if", "call_sig", "not", "in", "self", ".", "data", "[", "'children'", "]", ":", "self", ".", "data", "[", "'children'", "]", "[", "o_lineno", "]", "[", "call_sig", "]", "=", "self", ".", "_get_struct", "(", "frame", ",", "event", ")", "self", ".", "data", "=", "self", ".", "data", "[", "'children'", "]", "[", "o_lineno", "]", "[", "call_sig", "]", "self", ".", "data", "[", "'num_calls'", "]", "+=", "1", "elif", "event", "==", "'line'", ":", "# Record an executed line.", "if", "self", ".", "pause_until", "is", "None", "and", "lineno", "in", "self", ".", "data", "[", "'lines'", "]", ":", "self", ".", "data", "[", "'lines'", "]", "[", "lineno", "]", "[", "'num_calls'", "]", "+=", "1", "self", ".", "data", "[", "'lines'", "]", "[", "lineno", "]", "[", "'time_spent'", "]", "+=", "(", "cur_time", "-", "self", ".", "start_time", ")", "if", "self", ".", "log", ":", "print", ">>", "sys", ".", "stdout", ",", "'%s -- %s:%s executing line %d'", "%", "(", "' '", "*", "(", "depth", "-", "1", ")", ",", "filename", ",", "frame", ".", "f_code", ".", "co_name", ",", "lineno", ")", "elif", "event", "==", "'return'", ":", "timing", "=", "(", "cur_time", "-", "self", ".", "start_time", ")", "# Leaving this function, pop the filename stack.", "if", "self", ".", "pause_until", "is", "None", ":", "self", ".", "data", "[", "'time_spent'", "]", "+=", "timing", "self", ".", "data", "=", "self", ".", "data_stack", ".", "pop", "(", ")", "self", ".", "data", "[", "'time_spent'", "]", "+=", "timing", "# self.data['lines'][lineno]['num_calls'] += 1", "# self.data['lines'][lineno]['time_spent'] += (cur_time - self.start_time)", "if", "self", ".", "log", ":", "print", ">>", "sys", ".", "stdout", ",", "'%s << %s:%s %.3fs'", "%", "(", "' '", "*", "(", "depth", "-", "1", ")", ",", "filename", ",", "frame", ".", "f_code", ".", "co_name", ",", "timing", ")", "self", ".", "depth", "-=", "1", "elif", "event", "==", "'exception'", ":", "self", ".", "last_exc_back", "=", "frame", ".", "f_back", "self", ".", "last_exc_firstlineno", "=", "frame", ".", "f_code", ".", "co_firstlineno", "return", "self", ".", "_trace" ]
The trace function passed to sys.settrace.
[ "The", "trace", "function", "passed", "to", "sys", ".", "settrace", "." ]
da7c086660fc870c6632c4dc5ccb2ff9bfbee52e
https://github.com/dcramer/peek/blob/da7c086660fc870c6632c4dc5ccb2ff9bfbee52e/peek/tracer.py#L153-L235
247,840
dcramer/peek
peek/tracer.py
Tracer.start
def start(self, origin): """ Start this Tracer. Return a Python function suitable for use with sys.settrace(). """ self.start_time = time.time() self.pause_until = None self.data.update(self._get_struct(origin, 'origin')) self.data_stack.append(self.data) sys.settrace(self._trace) return self._trace
python
def start(self, origin): """ Start this Tracer. Return a Python function suitable for use with sys.settrace(). """ self.start_time = time.time() self.pause_until = None self.data.update(self._get_struct(origin, 'origin')) self.data_stack.append(self.data) sys.settrace(self._trace) return self._trace
[ "def", "start", "(", "self", ",", "origin", ")", ":", "self", ".", "start_time", "=", "time", ".", "time", "(", ")", "self", ".", "pause_until", "=", "None", "self", ".", "data", ".", "update", "(", "self", ".", "_get_struct", "(", "origin", ",", "'origin'", ")", ")", "self", ".", "data_stack", ".", "append", "(", "self", ".", "data", ")", "sys", ".", "settrace", "(", "self", ".", "_trace", ")", "return", "self", ".", "_trace" ]
Start this Tracer. Return a Python function suitable for use with sys.settrace().
[ "Start", "this", "Tracer", "." ]
da7c086660fc870c6632c4dc5ccb2ff9bfbee52e
https://github.com/dcramer/peek/blob/da7c086660fc870c6632c4dc5ccb2ff9bfbee52e/peek/tracer.py#L237-L248
247,841
dcramer/peek
peek/tracer.py
Tracer.stop
def stop(self): """ Stop this Tracer. """ if hasattr(sys, "gettrace") and self.log: if sys.gettrace() != self._trace: msg = "Trace function changed, measurement is likely wrong: %r" print >> sys.stdout, msg % sys.gettrace() sys.settrace(None)
python
def stop(self): """ Stop this Tracer. """ if hasattr(sys, "gettrace") and self.log: if sys.gettrace() != self._trace: msg = "Trace function changed, measurement is likely wrong: %r" print >> sys.stdout, msg % sys.gettrace() sys.settrace(None)
[ "def", "stop", "(", "self", ")", ":", "if", "hasattr", "(", "sys", ",", "\"gettrace\"", ")", "and", "self", ".", "log", ":", "if", "sys", ".", "gettrace", "(", ")", "!=", "self", ".", "_trace", ":", "msg", "=", "\"Trace function changed, measurement is likely wrong: %r\"", "print", ">>", "sys", ".", "stdout", ",", "msg", "%", "sys", ".", "gettrace", "(", ")", "sys", ".", "settrace", "(", "None", ")" ]
Stop this Tracer.
[ "Stop", "this", "Tracer", "." ]
da7c086660fc870c6632c4dc5ccb2ff9bfbee52e
https://github.com/dcramer/peek/blob/da7c086660fc870c6632c4dc5ccb2ff9bfbee52e/peek/tracer.py#L250-L258
247,842
zzzsochi/resolver_deco
resolver_deco.py
resolver
def resolver(*for_resolve, attr_package='__package_for_resolve_deco__'): """ Resolve dotted names in function arguments Usage: >>> @resolver('obj') >>> def func(param, obj): >>> assert isinstance(param, str) >>> assert not isinstance(obj, str) >>> >>> func('os.path', 'sys.exit') """ def decorator(func): spec = inspect.getargspec(func).args if set(for_resolve) - set(spec): raise ValueError('bad arguments') @wraps(func) def wrapper(*args, **kwargs): args = list(args) if args and attr_package: package = getattr(args[0], attr_package, None) else: package = None for item in for_resolve: n = spec.index(item) if n >= len(args): continue if n is not None and isinstance(args[n], str): args[n] = resolve(args[n], package) for kw, value in kwargs.copy().items(): if kw in for_resolve and isinstance(value, str): kwargs[kw] = resolve(value, package) return func(*args, **kwargs) return wrapper return decorator
python
def resolver(*for_resolve, attr_package='__package_for_resolve_deco__'): """ Resolve dotted names in function arguments Usage: >>> @resolver('obj') >>> def func(param, obj): >>> assert isinstance(param, str) >>> assert not isinstance(obj, str) >>> >>> func('os.path', 'sys.exit') """ def decorator(func): spec = inspect.getargspec(func).args if set(for_resolve) - set(spec): raise ValueError('bad arguments') @wraps(func) def wrapper(*args, **kwargs): args = list(args) if args and attr_package: package = getattr(args[0], attr_package, None) else: package = None for item in for_resolve: n = spec.index(item) if n >= len(args): continue if n is not None and isinstance(args[n], str): args[n] = resolve(args[n], package) for kw, value in kwargs.copy().items(): if kw in for_resolve and isinstance(value, str): kwargs[kw] = resolve(value, package) return func(*args, **kwargs) return wrapper return decorator
[ "def", "resolver", "(", "*", "for_resolve", ",", "attr_package", "=", "'__package_for_resolve_deco__'", ")", ":", "def", "decorator", "(", "func", ")", ":", "spec", "=", "inspect", ".", "getargspec", "(", "func", ")", ".", "args", "if", "set", "(", "for_resolve", ")", "-", "set", "(", "spec", ")", ":", "raise", "ValueError", "(", "'bad arguments'", ")", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "if", "args", "and", "attr_package", ":", "package", "=", "getattr", "(", "args", "[", "0", "]", ",", "attr_package", ",", "None", ")", "else", ":", "package", "=", "None", "for", "item", "in", "for_resolve", ":", "n", "=", "spec", ".", "index", "(", "item", ")", "if", "n", ">=", "len", "(", "args", ")", ":", "continue", "if", "n", "is", "not", "None", "and", "isinstance", "(", "args", "[", "n", "]", ",", "str", ")", ":", "args", "[", "n", "]", "=", "resolve", "(", "args", "[", "n", "]", ",", "package", ")", "for", "kw", ",", "value", "in", "kwargs", ".", "copy", "(", ")", ".", "items", "(", ")", ":", "if", "kw", "in", "for_resolve", "and", "isinstance", "(", "value", ",", "str", ")", ":", "kwargs", "[", "kw", "]", "=", "resolve", "(", "value", ",", "package", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper", "return", "decorator" ]
Resolve dotted names in function arguments Usage: >>> @resolver('obj') >>> def func(param, obj): >>> assert isinstance(param, str) >>> assert not isinstance(obj, str) >>> >>> func('os.path', 'sys.exit')
[ "Resolve", "dotted", "names", "in", "function", "arguments" ]
fe40ad5f931d1edd444d854cb2e3038a2cd16c7c
https://github.com/zzzsochi/resolver_deco/blob/fe40ad5f931d1edd444d854cb2e3038a2cd16c7c/resolver_deco.py#L7-L49
247,843
ttinies/sc2common
sc2common/commonUtilFuncs.py
relateObjectLocs
def relateObjectLocs(obj, entities, selectF): """calculate the minimum distance to reach any iterable of entities with a loc""" #if obj in entities: return 0 # is already one of the entities try: obj = obj.loc # get object's location, if it has one except AttributeError: pass # assume obj is already a MapPoint try: func = obj.direct2dDistance # assume obj is a MapPoint except AttributeError: raise ValueError("object %s (%s) does not possess and is not a %s"%(obj, type(obj), MapPoint)) try: return selectF([(func(b.loc), b) for b in entities]) except AttributeError: return selectF([(func(b) , b) for b in entities])
python
def relateObjectLocs(obj, entities, selectF): """calculate the minimum distance to reach any iterable of entities with a loc""" #if obj in entities: return 0 # is already one of the entities try: obj = obj.loc # get object's location, if it has one except AttributeError: pass # assume obj is already a MapPoint try: func = obj.direct2dDistance # assume obj is a MapPoint except AttributeError: raise ValueError("object %s (%s) does not possess and is not a %s"%(obj, type(obj), MapPoint)) try: return selectF([(func(b.loc), b) for b in entities]) except AttributeError: return selectF([(func(b) , b) for b in entities])
[ "def", "relateObjectLocs", "(", "obj", ",", "entities", ",", "selectF", ")", ":", "#if obj in entities: return 0 # is already one of the entities", "try", ":", "obj", "=", "obj", ".", "loc", "# get object's location, if it has one", "except", "AttributeError", ":", "pass", "# assume obj is already a MapPoint", "try", ":", "func", "=", "obj", ".", "direct2dDistance", "# assume obj is a MapPoint", "except", "AttributeError", ":", "raise", "ValueError", "(", "\"object %s (%s) does not possess and is not a %s\"", "%", "(", "obj", ",", "type", "(", "obj", ")", ",", "MapPoint", ")", ")", "try", ":", "return", "selectF", "(", "[", "(", "func", "(", "b", ".", "loc", ")", ",", "b", ")", "for", "b", "in", "entities", "]", ")", "except", "AttributeError", ":", "return", "selectF", "(", "[", "(", "func", "(", "b", ")", ",", "b", ")", "for", "b", "in", "entities", "]", ")" ]
calculate the minimum distance to reach any iterable of entities with a loc
[ "calculate", "the", "minimum", "distance", "to", "reach", "any", "iterable", "of", "entities", "with", "a", "loc" ]
469623c319c7ab7af799551055839ea3b3f87d54
https://github.com/ttinies/sc2common/blob/469623c319c7ab7af799551055839ea3b3f87d54/sc2common/commonUtilFuncs.py#L52-L60
247,844
ttinies/sc2common
sc2common/commonUtilFuncs.py
convertToMapPic
def convertToMapPic(byteString, mapWidth): """convert a bytestring into a 2D row x column array, representing an existing map of fog-of-war, creep, etc.""" data = [] line = "" for idx,char in enumerate(byteString): line += str(ord(char)) if ((idx+1)%mapWidth)==0: data.append(line) line = "" return data
python
def convertToMapPic(byteString, mapWidth): """convert a bytestring into a 2D row x column array, representing an existing map of fog-of-war, creep, etc.""" data = [] line = "" for idx,char in enumerate(byteString): line += str(ord(char)) if ((idx+1)%mapWidth)==0: data.append(line) line = "" return data
[ "def", "convertToMapPic", "(", "byteString", ",", "mapWidth", ")", ":", "data", "=", "[", "]", "line", "=", "\"\"", "for", "idx", ",", "char", "in", "enumerate", "(", "byteString", ")", ":", "line", "+=", "str", "(", "ord", "(", "char", ")", ")", "if", "(", "(", "idx", "+", "1", ")", "%", "mapWidth", ")", "==", "0", ":", "data", ".", "append", "(", "line", ")", "line", "=", "\"\"", "return", "data" ]
convert a bytestring into a 2D row x column array, representing an existing map of fog-of-war, creep, etc.
[ "convert", "a", "bytestring", "into", "a", "2D", "row", "x", "column", "array", "representing", "an", "existing", "map", "of", "fog", "-", "of", "-", "war", "creep", "etc", "." ]
469623c319c7ab7af799551055839ea3b3f87d54
https://github.com/ttinies/sc2common/blob/469623c319c7ab7af799551055839ea3b3f87d54/sc2common/commonUtilFuncs.py#L89-L98
247,845
tjomasc/snekbol
snekbol/document.py
Document.add_component_definition
def add_component_definition(self, definition): """ Add a ComponentDefinition to the document """ # definition.identity = self._to_uri_from_namespace(definition.identity) if definition.identity not in self._components.keys(): self._components[definition.identity] = definition else: raise ValueError("{} has already been defined".format(definition.identity))
python
def add_component_definition(self, definition): """ Add a ComponentDefinition to the document """ # definition.identity = self._to_uri_from_namespace(definition.identity) if definition.identity not in self._components.keys(): self._components[definition.identity] = definition else: raise ValueError("{} has already been defined".format(definition.identity))
[ "def", "add_component_definition", "(", "self", ",", "definition", ")", ":", "# definition.identity = self._to_uri_from_namespace(definition.identity)", "if", "definition", ".", "identity", "not", "in", "self", ".", "_components", ".", "keys", "(", ")", ":", "self", ".", "_components", "[", "definition", ".", "identity", "]", "=", "definition", "else", ":", "raise", "ValueError", "(", "\"{} has already been defined\"", ".", "format", "(", "definition", ".", "identity", ")", ")" ]
Add a ComponentDefinition to the document
[ "Add", "a", "ComponentDefinition", "to", "the", "document" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L79-L87
247,846
tjomasc/snekbol
snekbol/document.py
Document.assemble_component
def assemble_component(self, into_component, using_components): """ Assemble a list of already defined components into a structual hirearchy """ if not isinstance(using_components, list) or len(using_components) == 0: raise Exception('Must supply list of ComponentDefinitions') components = [] sequence_annotations = [] seq_elements = '' for k, c in enumerate(using_components): try: self._components[c.identity] except KeyError: raise Exception('Must already have defined ComponentDefinition in document') else: identity = into_component.identity + '/' + c.identity # All components are initially public, this can be changed later component = Component(identity, c, 'public', display_id=c.identity) components.append(component) # If there is a sequence on the ComponentDefinition use the first element if len(c.sequences) > 0: # Add the sequence to the document self._add_sequence(c.sequences[0]) # Get start/end points of sequence start = len(seq_elements) + 1 # The sequence is usually 1 indexed end = start + len(c.sequences[0].elements) # Add to the component sequence element seq_elements += c.sequences[0].elements # Create a Range object to hold seq range range_identity = identity + '_sequence_annotation/range' seq_range = Range(range_identity, start, end, display_id='range') # Create a SequenceAnnotation object to hold the range annot_identity = identity + '_sequence_annotation' seq_annot = SequenceAnnotation(annot_identity, component=component, locations=[seq_range], display_id=c.identity + '_sequence_annotation') sequence_annotations.append(seq_annot) if seq_elements != '': seq_encoding = using_components[0].sequences[0].encoding seq_identity = '{}_sequence'.format(into_component.identity) seq = Sequence(seq_identity, seq_elements, encoding=seq_encoding) self._add_sequence(seq) into_component.sequences.append(seq) into_component.components = components into_component.sequence_annotations = sequence_annotations
python
def assemble_component(self, into_component, using_components): """ Assemble a list of already defined components into a structual hirearchy """ if not isinstance(using_components, list) or len(using_components) == 0: raise Exception('Must supply list of ComponentDefinitions') components = [] sequence_annotations = [] seq_elements = '' for k, c in enumerate(using_components): try: self._components[c.identity] except KeyError: raise Exception('Must already have defined ComponentDefinition in document') else: identity = into_component.identity + '/' + c.identity # All components are initially public, this can be changed later component = Component(identity, c, 'public', display_id=c.identity) components.append(component) # If there is a sequence on the ComponentDefinition use the first element if len(c.sequences) > 0: # Add the sequence to the document self._add_sequence(c.sequences[0]) # Get start/end points of sequence start = len(seq_elements) + 1 # The sequence is usually 1 indexed end = start + len(c.sequences[0].elements) # Add to the component sequence element seq_elements += c.sequences[0].elements # Create a Range object to hold seq range range_identity = identity + '_sequence_annotation/range' seq_range = Range(range_identity, start, end, display_id='range') # Create a SequenceAnnotation object to hold the range annot_identity = identity + '_sequence_annotation' seq_annot = SequenceAnnotation(annot_identity, component=component, locations=[seq_range], display_id=c.identity + '_sequence_annotation') sequence_annotations.append(seq_annot) if seq_elements != '': seq_encoding = using_components[0].sequences[0].encoding seq_identity = '{}_sequence'.format(into_component.identity) seq = Sequence(seq_identity, seq_elements, encoding=seq_encoding) self._add_sequence(seq) into_component.sequences.append(seq) into_component.components = components into_component.sequence_annotations = sequence_annotations
[ "def", "assemble_component", "(", "self", ",", "into_component", ",", "using_components", ")", ":", "if", "not", "isinstance", "(", "using_components", ",", "list", ")", "or", "len", "(", "using_components", ")", "==", "0", ":", "raise", "Exception", "(", "'Must supply list of ComponentDefinitions'", ")", "components", "=", "[", "]", "sequence_annotations", "=", "[", "]", "seq_elements", "=", "''", "for", "k", ",", "c", "in", "enumerate", "(", "using_components", ")", ":", "try", ":", "self", ".", "_components", "[", "c", ".", "identity", "]", "except", "KeyError", ":", "raise", "Exception", "(", "'Must already have defined ComponentDefinition in document'", ")", "else", ":", "identity", "=", "into_component", ".", "identity", "+", "'/'", "+", "c", ".", "identity", "# All components are initially public, this can be changed later", "component", "=", "Component", "(", "identity", ",", "c", ",", "'public'", ",", "display_id", "=", "c", ".", "identity", ")", "components", ".", "append", "(", "component", ")", "# If there is a sequence on the ComponentDefinition use the first element", "if", "len", "(", "c", ".", "sequences", ")", ">", "0", ":", "# Add the sequence to the document", "self", ".", "_add_sequence", "(", "c", ".", "sequences", "[", "0", "]", ")", "# Get start/end points of sequence", "start", "=", "len", "(", "seq_elements", ")", "+", "1", "# The sequence is usually 1 indexed", "end", "=", "start", "+", "len", "(", "c", ".", "sequences", "[", "0", "]", ".", "elements", ")", "# Add to the component sequence element", "seq_elements", "+=", "c", ".", "sequences", "[", "0", "]", ".", "elements", "# Create a Range object to hold seq range", "range_identity", "=", "identity", "+", "'_sequence_annotation/range'", "seq_range", "=", "Range", "(", "range_identity", ",", "start", ",", "end", ",", "display_id", "=", "'range'", ")", "# Create a SequenceAnnotation object to hold the range", "annot_identity", "=", "identity", "+", "'_sequence_annotation'", "seq_annot", "=", "SequenceAnnotation", "(", "annot_identity", ",", "component", "=", "component", ",", "locations", "=", "[", "seq_range", "]", ",", "display_id", "=", "c", ".", "identity", "+", "'_sequence_annotation'", ")", "sequence_annotations", ".", "append", "(", "seq_annot", ")", "if", "seq_elements", "!=", "''", ":", "seq_encoding", "=", "using_components", "[", "0", "]", ".", "sequences", "[", "0", "]", ".", "encoding", "seq_identity", "=", "'{}_sequence'", ".", "format", "(", "into_component", ".", "identity", ")", "seq", "=", "Sequence", "(", "seq_identity", ",", "seq_elements", ",", "encoding", "=", "seq_encoding", ")", "self", ".", "_add_sequence", "(", "seq", ")", "into_component", ".", "sequences", ".", "append", "(", "seq", ")", "into_component", ".", "components", "=", "components", "into_component", ".", "sequence_annotations", "=", "sequence_annotations" ]
Assemble a list of already defined components into a structual hirearchy
[ "Assemble", "a", "list", "of", "already", "defined", "components", "into", "a", "structual", "hirearchy" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L114-L168
247,847
tjomasc/snekbol
snekbol/document.py
Document._add_sequence
def _add_sequence(self, sequence): """ Add a Sequence to the document """ if sequence.identity not in self._sequences.keys(): self._sequences[sequence.identity] = sequence else: raise ValueError("{} has already been defined".format(sequence.identity))
python
def _add_sequence(self, sequence): """ Add a Sequence to the document """ if sequence.identity not in self._sequences.keys(): self._sequences[sequence.identity] = sequence else: raise ValueError("{} has already been defined".format(sequence.identity))
[ "def", "_add_sequence", "(", "self", ",", "sequence", ")", ":", "if", "sequence", ".", "identity", "not", "in", "self", ".", "_sequences", ".", "keys", "(", ")", ":", "self", ".", "_sequences", "[", "sequence", ".", "identity", "]", "=", "sequence", "else", ":", "raise", "ValueError", "(", "\"{} has already been defined\"", ".", "format", "(", "sequence", ".", "identity", ")", ")" ]
Add a Sequence to the document
[ "Add", "a", "Sequence", "to", "the", "document" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L170-L177
247,848
tjomasc/snekbol
snekbol/document.py
Document.add_model
def add_model(self, model): """ Add a model to the document """ if model.identity not in self._models.keys(): self._models[model.identity] = model else: raise ValueError("{} has already been defined".format(model.identity))
python
def add_model(self, model): """ Add a model to the document """ if model.identity not in self._models.keys(): self._models[model.identity] = model else: raise ValueError("{} has already been defined".format(model.identity))
[ "def", "add_model", "(", "self", ",", "model", ")", ":", "if", "model", ".", "identity", "not", "in", "self", ".", "_models", ".", "keys", "(", ")", ":", "self", ".", "_models", "[", "model", ".", "identity", "]", "=", "model", "else", ":", "raise", "ValueError", "(", "\"{} has already been defined\"", ".", "format", "(", "model", ".", "identity", ")", ")" ]
Add a model to the document
[ "Add", "a", "model", "to", "the", "document" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L179-L186
247,849
tjomasc/snekbol
snekbol/document.py
Document.add_module_definition
def add_module_definition(self, module_definition): """ Add a ModuleDefinition to the document """ if module_definition.identity not in self._module_definitions.keys(): self._module_definitions[module_definition.identity] = module_definition else: raise ValueError("{} has already been defined".format(module_definition.identity))
python
def add_module_definition(self, module_definition): """ Add a ModuleDefinition to the document """ if module_definition.identity not in self._module_definitions.keys(): self._module_definitions[module_definition.identity] = module_definition else: raise ValueError("{} has already been defined".format(module_definition.identity))
[ "def", "add_module_definition", "(", "self", ",", "module_definition", ")", ":", "if", "module_definition", ".", "identity", "not", "in", "self", ".", "_module_definitions", ".", "keys", "(", ")", ":", "self", ".", "_module_definitions", "[", "module_definition", ".", "identity", "]", "=", "module_definition", "else", ":", "raise", "ValueError", "(", "\"{} has already been defined\"", ".", "format", "(", "module_definition", ".", "identity", ")", ")" ]
Add a ModuleDefinition to the document
[ "Add", "a", "ModuleDefinition", "to", "the", "document" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L203-L210
247,850
tjomasc/snekbol
snekbol/document.py
Document.get_components
def get_components(self, uri): """ Get components from a component definition in order """ try: component_definition = self._components[uri] except KeyError: return False sorted_sequences = sorted(component_definition.sequence_annotations, key=attrgetter('first_location')) return [c.component for c in sorted_sequences]
python
def get_components(self, uri): """ Get components from a component definition in order """ try: component_definition = self._components[uri] except KeyError: return False sorted_sequences = sorted(component_definition.sequence_annotations, key=attrgetter('first_location')) return [c.component for c in sorted_sequences]
[ "def", "get_components", "(", "self", ",", "uri", ")", ":", "try", ":", "component_definition", "=", "self", ".", "_components", "[", "uri", "]", "except", "KeyError", ":", "return", "False", "sorted_sequences", "=", "sorted", "(", "component_definition", ".", "sequence_annotations", ",", "key", "=", "attrgetter", "(", "'first_location'", ")", ")", "return", "[", "c", ".", "component", "for", "c", "in", "sorted_sequences", "]" ]
Get components from a component definition in order
[ "Get", "components", "from", "a", "component", "definition", "in", "order" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L233-L244
247,851
tjomasc/snekbol
snekbol/document.py
Document.clear_document
def clear_document(self): """ Clears ALL items from document, reseting it to clean """ self._components.clear() self._sequences.clear() self._namespaces.clear() self._models.clear() self._modules.clear() self._collections.clear() self._annotations.clear() self._functional_component_store.clear() self._collection_store.clear()
python
def clear_document(self): """ Clears ALL items from document, reseting it to clean """ self._components.clear() self._sequences.clear() self._namespaces.clear() self._models.clear() self._modules.clear() self._collections.clear() self._annotations.clear() self._functional_component_store.clear() self._collection_store.clear()
[ "def", "clear_document", "(", "self", ")", ":", "self", ".", "_components", ".", "clear", "(", ")", "self", ".", "_sequences", ".", "clear", "(", ")", "self", ".", "_namespaces", ".", "clear", "(", ")", "self", ".", "_models", ".", "clear", "(", ")", "self", ".", "_modules", ".", "clear", "(", ")", "self", ".", "_collections", ".", "clear", "(", ")", "self", ".", "_annotations", ".", "clear", "(", ")", "self", ".", "_functional_component_store", ".", "clear", "(", ")", "self", ".", "_collection_store", ".", "clear", "(", ")" ]
Clears ALL items from document, reseting it to clean
[ "Clears", "ALL", "items", "from", "document", "reseting", "it", "to", "clean" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L246-L258
247,852
tjomasc/snekbol
snekbol/document.py
Document._get_triplet_value
def _get_triplet_value(self, graph, identity, rdf_type): """ Get a value from an RDF triple """ value = graph.value(subject=identity, predicate=rdf_type) return value.toPython() if value is not None else value
python
def _get_triplet_value(self, graph, identity, rdf_type): """ Get a value from an RDF triple """ value = graph.value(subject=identity, predicate=rdf_type) return value.toPython() if value is not None else value
[ "def", "_get_triplet_value", "(", "self", ",", "graph", ",", "identity", ",", "rdf_type", ")", ":", "value", "=", "graph", ".", "value", "(", "subject", "=", "identity", ",", "predicate", "=", "rdf_type", ")", "return", "value", ".", "toPython", "(", ")", "if", "value", "is", "not", "None", "else", "value" ]
Get a value from an RDF triple
[ "Get", "a", "value", "from", "an", "RDF", "triple" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L263-L268
247,853
tjomasc/snekbol
snekbol/document.py
Document._get_triplet_value_list
def _get_triplet_value_list(self, graph, identity, rdf_type): """ Get a list of values from RDF triples when more than one may be present """ values = [] for elem in graph.objects(identity, rdf_type): values.append(elem.toPython()) return values
python
def _get_triplet_value_list(self, graph, identity, rdf_type): """ Get a list of values from RDF triples when more than one may be present """ values = [] for elem in graph.objects(identity, rdf_type): values.append(elem.toPython()) return values
[ "def", "_get_triplet_value_list", "(", "self", ",", "graph", ",", "identity", ",", "rdf_type", ")", ":", "values", "=", "[", "]", "for", "elem", "in", "graph", ".", "objects", "(", "identity", ",", "rdf_type", ")", ":", "values", ".", "append", "(", "elem", ".", "toPython", "(", ")", ")", "return", "values" ]
Get a list of values from RDF triples when more than one may be present
[ "Get", "a", "list", "of", "values", "from", "RDF", "triples", "when", "more", "than", "one", "may", "be", "present" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L270-L277
247,854
tjomasc/snekbol
snekbol/document.py
Document._read_sequences
def _read_sequences(self, graph): """ Read graph and add sequences to document """ for e in self._get_elements(graph, SBOL.Sequence): identity = e[0] c = self._get_rdf_identified(graph, identity) c['elements'] = self._get_triplet_value(graph, identity, SBOL.elements) c['encoding'] = self._get_triplet_value(graph, identity, SBOL.encoding) seq = Sequence(**c) self._sequences[identity.toPython()] = seq self._collection_store[identity.toPython()] = seq
python
def _read_sequences(self, graph): """ Read graph and add sequences to document """ for e in self._get_elements(graph, SBOL.Sequence): identity = e[0] c = self._get_rdf_identified(graph, identity) c['elements'] = self._get_triplet_value(graph, identity, SBOL.elements) c['encoding'] = self._get_triplet_value(graph, identity, SBOL.encoding) seq = Sequence(**c) self._sequences[identity.toPython()] = seq self._collection_store[identity.toPython()] = seq
[ "def", "_read_sequences", "(", "self", ",", "graph", ")", ":", "for", "e", "in", "self", ".", "_get_elements", "(", "graph", ",", "SBOL", ".", "Sequence", ")", ":", "identity", "=", "e", "[", "0", "]", "c", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "identity", ")", "c", "[", "'elements'", "]", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "identity", ",", "SBOL", ".", "elements", ")", "c", "[", "'encoding'", "]", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "identity", ",", "SBOL", ".", "encoding", ")", "seq", "=", "Sequence", "(", "*", "*", "c", ")", "self", ".", "_sequences", "[", "identity", ".", "toPython", "(", ")", "]", "=", "seq", "self", ".", "_collection_store", "[", "identity", ".", "toPython", "(", ")", "]", "=", "seq" ]
Read graph and add sequences to document
[ "Read", "graph", "and", "add", "sequences", "to", "document" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L306-L317
247,855
tjomasc/snekbol
snekbol/document.py
Document._read_component_definitions
def _read_component_definitions(self, graph): """ Read graph and add component defintions to document """ for e in self._get_elements(graph, SBOL.ComponentDefinition): identity = e[0] # Store component values in dict c = self._get_rdf_identified(graph, identity) c['roles'] = self._get_triplet_value_list(graph, identity, SBOL.role) c['types'] = self._get_triplet_value_list(graph, identity, SBOL.type) obj = ComponentDefinition(**c) self._components[identity.toPython()] = obj self._collection_store[identity.toPython()] = obj
python
def _read_component_definitions(self, graph): """ Read graph and add component defintions to document """ for e in self._get_elements(graph, SBOL.ComponentDefinition): identity = e[0] # Store component values in dict c = self._get_rdf_identified(graph, identity) c['roles'] = self._get_triplet_value_list(graph, identity, SBOL.role) c['types'] = self._get_triplet_value_list(graph, identity, SBOL.type) obj = ComponentDefinition(**c) self._components[identity.toPython()] = obj self._collection_store[identity.toPython()] = obj
[ "def", "_read_component_definitions", "(", "self", ",", "graph", ")", ":", "for", "e", "in", "self", ".", "_get_elements", "(", "graph", ",", "SBOL", ".", "ComponentDefinition", ")", ":", "identity", "=", "e", "[", "0", "]", "# Store component values in dict", "c", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "identity", ")", "c", "[", "'roles'", "]", "=", "self", ".", "_get_triplet_value_list", "(", "graph", ",", "identity", ",", "SBOL", ".", "role", ")", "c", "[", "'types'", "]", "=", "self", ".", "_get_triplet_value_list", "(", "graph", ",", "identity", ",", "SBOL", ".", "type", ")", "obj", "=", "ComponentDefinition", "(", "*", "*", "c", ")", "self", ".", "_components", "[", "identity", ".", "toPython", "(", ")", "]", "=", "obj", "self", ".", "_collection_store", "[", "identity", ".", "toPython", "(", ")", "]", "=", "obj" ]
Read graph and add component defintions to document
[ "Read", "graph", "and", "add", "component", "defintions", "to", "document" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L319-L331
247,856
tjomasc/snekbol
snekbol/document.py
Document._read_models
def _read_models(self, graph): """ Read graph and add models to document """ for e in self._get_elements(graph, SBOL.Model): identity = e[0] m = self._get_rdf_identified(graph, identity) m['source'] = self._get_triplet_value(graph, identity, SBOL.source) m['language'] = self._get_triplet_value(graph, identity, SBOL.language) m['framework'] = self._get_triplet_value(graph, identity, SBOL.framework) obj = Model(**m) self._models[identity.toPython()] = obj self._collection_store[identity.toPython()] = obj
python
def _read_models(self, graph): """ Read graph and add models to document """ for e in self._get_elements(graph, SBOL.Model): identity = e[0] m = self._get_rdf_identified(graph, identity) m['source'] = self._get_triplet_value(graph, identity, SBOL.source) m['language'] = self._get_triplet_value(graph, identity, SBOL.language) m['framework'] = self._get_triplet_value(graph, identity, SBOL.framework) obj = Model(**m) self._models[identity.toPython()] = obj self._collection_store[identity.toPython()] = obj
[ "def", "_read_models", "(", "self", ",", "graph", ")", ":", "for", "e", "in", "self", ".", "_get_elements", "(", "graph", ",", "SBOL", ".", "Model", ")", ":", "identity", "=", "e", "[", "0", "]", "m", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "identity", ")", "m", "[", "'source'", "]", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "identity", ",", "SBOL", ".", "source", ")", "m", "[", "'language'", "]", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "identity", ",", "SBOL", ".", "language", ")", "m", "[", "'framework'", "]", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "identity", ",", "SBOL", ".", "framework", ")", "obj", "=", "Model", "(", "*", "*", "m", ")", "self", ".", "_models", "[", "identity", ".", "toPython", "(", ")", "]", "=", "obj", "self", ".", "_collection_store", "[", "identity", ".", "toPython", "(", ")", "]", "=", "obj" ]
Read graph and add models to document
[ "Read", "graph", "and", "add", "models", "to", "document" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L407-L419
247,857
tjomasc/snekbol
snekbol/document.py
Document._read_module_definitions
def _read_module_definitions(self, graph): """ Read graph and add module defintions to document """ for e in self._get_elements(graph, SBOL.ModuleDefinition): identity = e[0] m = self._get_rdf_identified(graph, identity) m['roles'] = self._get_triplet_value_list(graph, identity, SBOL.role) functional_components = {} for func_comp in graph.triples((identity, SBOL.functionalComponent, None)): func_identity = func_comp[2] fc = self._get_rdf_identified(graph, func_identity) definition = self._get_triplet_value(graph, func_identity, SBOL.definition) fc['definition'] = self._components[definition] fc['access'] = self._get_triplet_value(graph, func_identity, SBOL.access) fc['direction'] = self._get_triplet_value(graph, func_identity, SBOL.direction) functional_components[func_identity.toPython()] = FunctionalComponent(**fc) self._functional_component_store[func_identity.toPython()] = \ functional_components[func_identity.toPython()] interactions = [] for inter in graph.triples((identity, SBOL.interaction, None)): inter_identity = inter[2] it = self._get_rdf_identified(graph, inter_identity) it['types'] = self._get_triplet_value_list(graph, inter_identity, SBOL.types) participations = [] for p in graph.triples((inter_identity, SBOL.participation, None)): pc = self._get_rdf_identified(graph, p[2]) roles = self._get_triplet_value_list(graph, p[2], SBOL.role) # Need to use one of the functional component created above participant_id = self._get_triplet_value(graph, p[2], SBOL.participant) participant = functional_components[participant_id] participations.append(Participation(roles=roles, participant=participant, **pc)) interactions.append(Interaction(participations=participations, **it)) obj = ModuleDefinition(functional_components=functional_components.values(), interactions=interactions, **m) self._modules[identity.toPython()] = obj self._collection_store[identity.toPython()] = obj
python
def _read_module_definitions(self, graph): """ Read graph and add module defintions to document """ for e in self._get_elements(graph, SBOL.ModuleDefinition): identity = e[0] m = self._get_rdf_identified(graph, identity) m['roles'] = self._get_triplet_value_list(graph, identity, SBOL.role) functional_components = {} for func_comp in graph.triples((identity, SBOL.functionalComponent, None)): func_identity = func_comp[2] fc = self._get_rdf_identified(graph, func_identity) definition = self._get_triplet_value(graph, func_identity, SBOL.definition) fc['definition'] = self._components[definition] fc['access'] = self._get_triplet_value(graph, func_identity, SBOL.access) fc['direction'] = self._get_triplet_value(graph, func_identity, SBOL.direction) functional_components[func_identity.toPython()] = FunctionalComponent(**fc) self._functional_component_store[func_identity.toPython()] = \ functional_components[func_identity.toPython()] interactions = [] for inter in graph.triples((identity, SBOL.interaction, None)): inter_identity = inter[2] it = self._get_rdf_identified(graph, inter_identity) it['types'] = self._get_triplet_value_list(graph, inter_identity, SBOL.types) participations = [] for p in graph.triples((inter_identity, SBOL.participation, None)): pc = self._get_rdf_identified(graph, p[2]) roles = self._get_triplet_value_list(graph, p[2], SBOL.role) # Need to use one of the functional component created above participant_id = self._get_triplet_value(graph, p[2], SBOL.participant) participant = functional_components[participant_id] participations.append(Participation(roles=roles, participant=participant, **pc)) interactions.append(Interaction(participations=participations, **it)) obj = ModuleDefinition(functional_components=functional_components.values(), interactions=interactions, **m) self._modules[identity.toPython()] = obj self._collection_store[identity.toPython()] = obj
[ "def", "_read_module_definitions", "(", "self", ",", "graph", ")", ":", "for", "e", "in", "self", ".", "_get_elements", "(", "graph", ",", "SBOL", ".", "ModuleDefinition", ")", ":", "identity", "=", "e", "[", "0", "]", "m", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "identity", ")", "m", "[", "'roles'", "]", "=", "self", ".", "_get_triplet_value_list", "(", "graph", ",", "identity", ",", "SBOL", ".", "role", ")", "functional_components", "=", "{", "}", "for", "func_comp", "in", "graph", ".", "triples", "(", "(", "identity", ",", "SBOL", ".", "functionalComponent", ",", "None", ")", ")", ":", "func_identity", "=", "func_comp", "[", "2", "]", "fc", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "func_identity", ")", "definition", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "func_identity", ",", "SBOL", ".", "definition", ")", "fc", "[", "'definition'", "]", "=", "self", ".", "_components", "[", "definition", "]", "fc", "[", "'access'", "]", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "func_identity", ",", "SBOL", ".", "access", ")", "fc", "[", "'direction'", "]", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "func_identity", ",", "SBOL", ".", "direction", ")", "functional_components", "[", "func_identity", ".", "toPython", "(", ")", "]", "=", "FunctionalComponent", "(", "*", "*", "fc", ")", "self", ".", "_functional_component_store", "[", "func_identity", ".", "toPython", "(", ")", "]", "=", "functional_components", "[", "func_identity", ".", "toPython", "(", ")", "]", "interactions", "=", "[", "]", "for", "inter", "in", "graph", ".", "triples", "(", "(", "identity", ",", "SBOL", ".", "interaction", ",", "None", ")", ")", ":", "inter_identity", "=", "inter", "[", "2", "]", "it", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "inter_identity", ")", "it", "[", "'types'", "]", "=", "self", ".", "_get_triplet_value_list", "(", "graph", ",", "inter_identity", ",", "SBOL", ".", "types", ")", "participations", "=", "[", "]", "for", "p", "in", "graph", ".", "triples", "(", "(", "inter_identity", ",", "SBOL", ".", "participation", ",", "None", ")", ")", ":", "pc", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "p", "[", "2", "]", ")", "roles", "=", "self", ".", "_get_triplet_value_list", "(", "graph", ",", "p", "[", "2", "]", ",", "SBOL", ".", "role", ")", "# Need to use one of the functional component created above", "participant_id", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "p", "[", "2", "]", ",", "SBOL", ".", "participant", ")", "participant", "=", "functional_components", "[", "participant_id", "]", "participations", ".", "append", "(", "Participation", "(", "roles", "=", "roles", ",", "participant", "=", "participant", ",", "*", "*", "pc", ")", ")", "interactions", ".", "append", "(", "Interaction", "(", "participations", "=", "participations", ",", "*", "*", "it", ")", ")", "obj", "=", "ModuleDefinition", "(", "functional_components", "=", "functional_components", ".", "values", "(", ")", ",", "interactions", "=", "interactions", ",", "*", "*", "m", ")", "self", ".", "_modules", "[", "identity", ".", "toPython", "(", ")", "]", "=", "obj", "self", ".", "_collection_store", "[", "identity", ".", "toPython", "(", ")", "]", "=", "obj" ]
Read graph and add module defintions to document
[ "Read", "graph", "and", "add", "module", "defintions", "to", "document" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L421-L458
247,858
tjomasc/snekbol
snekbol/document.py
Document._extend_module_definitions
def _extend_module_definitions(self, graph): """ Using collected module definitions extend linkages """ for mod_id in self._modules: mod_identity = self._get_triplet_value(graph, URIRef(mod_id), SBOL.module) modules = [] for mod in graph.triples((mod_identity, SBOL.module, None)): md = self._get_rdf_identified(graph, mod[2]) definition_id = self._get_triplet_value(graph, mod[2], SBOL.definition) md['definition'] = self._modules[definition_id] maps_to = [] for m in graph.triples((mod[2], SBOL.mapsTo, None)): mt = self._get_rdf_identified(graph, m[2]) mt['refinement'] = self._get_triplet_value(graph, m[2], SBOL.refinement) local_id = self._get_triplet_value(graph, m[2], SBOL.local) remote_id = self._get_triplet_value(graph, m[2], SBOL.remote) mt['local'] = self._functional_component_store[local_id] mt['remote'] = self._functional_component_store[remote_id] maps_to.append(MapsTo(**mt)) modules.append(Module(maps_to=maps_to, **md)) self._modules[mod_id].modules = modules
python
def _extend_module_definitions(self, graph): """ Using collected module definitions extend linkages """ for mod_id in self._modules: mod_identity = self._get_triplet_value(graph, URIRef(mod_id), SBOL.module) modules = [] for mod in graph.triples((mod_identity, SBOL.module, None)): md = self._get_rdf_identified(graph, mod[2]) definition_id = self._get_triplet_value(graph, mod[2], SBOL.definition) md['definition'] = self._modules[definition_id] maps_to = [] for m in graph.triples((mod[2], SBOL.mapsTo, None)): mt = self._get_rdf_identified(graph, m[2]) mt['refinement'] = self._get_triplet_value(graph, m[2], SBOL.refinement) local_id = self._get_triplet_value(graph, m[2], SBOL.local) remote_id = self._get_triplet_value(graph, m[2], SBOL.remote) mt['local'] = self._functional_component_store[local_id] mt['remote'] = self._functional_component_store[remote_id] maps_to.append(MapsTo(**mt)) modules.append(Module(maps_to=maps_to, **md)) self._modules[mod_id].modules = modules
[ "def", "_extend_module_definitions", "(", "self", ",", "graph", ")", ":", "for", "mod_id", "in", "self", ".", "_modules", ":", "mod_identity", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "URIRef", "(", "mod_id", ")", ",", "SBOL", ".", "module", ")", "modules", "=", "[", "]", "for", "mod", "in", "graph", ".", "triples", "(", "(", "mod_identity", ",", "SBOL", ".", "module", ",", "None", ")", ")", ":", "md", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "mod", "[", "2", "]", ")", "definition_id", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "mod", "[", "2", "]", ",", "SBOL", ".", "definition", ")", "md", "[", "'definition'", "]", "=", "self", ".", "_modules", "[", "definition_id", "]", "maps_to", "=", "[", "]", "for", "m", "in", "graph", ".", "triples", "(", "(", "mod", "[", "2", "]", ",", "SBOL", ".", "mapsTo", ",", "None", ")", ")", ":", "mt", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "m", "[", "2", "]", ")", "mt", "[", "'refinement'", "]", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "m", "[", "2", "]", ",", "SBOL", ".", "refinement", ")", "local_id", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "m", "[", "2", "]", ",", "SBOL", ".", "local", ")", "remote_id", "=", "self", ".", "_get_triplet_value", "(", "graph", ",", "m", "[", "2", "]", ",", "SBOL", ".", "remote", ")", "mt", "[", "'local'", "]", "=", "self", ".", "_functional_component_store", "[", "local_id", "]", "mt", "[", "'remote'", "]", "=", "self", ".", "_functional_component_store", "[", "remote_id", "]", "maps_to", ".", "append", "(", "MapsTo", "(", "*", "*", "mt", ")", ")", "modules", ".", "append", "(", "Module", "(", "maps_to", "=", "maps_to", ",", "*", "*", "md", ")", ")", "self", ".", "_modules", "[", "mod_id", "]", ".", "modules", "=", "modules" ]
Using collected module definitions extend linkages
[ "Using", "collected", "module", "definitions", "extend", "linkages" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L460-L481
247,859
tjomasc/snekbol
snekbol/document.py
Document._read_annotations
def _read_annotations(self, graph): """ Find any non-defined elements at TopLevel and create annotations """ flipped_namespaces = {v: k for k, v in self._namespaces.items()} for triple in graph.triples((None, RDF.type, None)): namespace, obj = split_uri(triple[2]) prefix = flipped_namespaces[namespace] as_string = '{}:{}'.format(prefix, obj) if as_string not in VALID_ENTITIES: identity = triple[0] gt = self._get_rdf_identified(graph, identity) q_name = QName(namespace=namespace, local_name=obj, prefix=prefix) gt['rdf_type'] = q_name gt_obj = GenericTopLevel(**gt) self._annotations[identity.toPython()] = gt_obj self._collection_store[identity.toPython()] = gt_obj
python
def _read_annotations(self, graph): """ Find any non-defined elements at TopLevel and create annotations """ flipped_namespaces = {v: k for k, v in self._namespaces.items()} for triple in graph.triples((None, RDF.type, None)): namespace, obj = split_uri(triple[2]) prefix = flipped_namespaces[namespace] as_string = '{}:{}'.format(prefix, obj) if as_string not in VALID_ENTITIES: identity = triple[0] gt = self._get_rdf_identified(graph, identity) q_name = QName(namespace=namespace, local_name=obj, prefix=prefix) gt['rdf_type'] = q_name gt_obj = GenericTopLevel(**gt) self._annotations[identity.toPython()] = gt_obj self._collection_store[identity.toPython()] = gt_obj
[ "def", "_read_annotations", "(", "self", ",", "graph", ")", ":", "flipped_namespaces", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "self", ".", "_namespaces", ".", "items", "(", ")", "}", "for", "triple", "in", "graph", ".", "triples", "(", "(", "None", ",", "RDF", ".", "type", ",", "None", ")", ")", ":", "namespace", ",", "obj", "=", "split_uri", "(", "triple", "[", "2", "]", ")", "prefix", "=", "flipped_namespaces", "[", "namespace", "]", "as_string", "=", "'{}:{}'", ".", "format", "(", "prefix", ",", "obj", ")", "if", "as_string", "not", "in", "VALID_ENTITIES", ":", "identity", "=", "triple", "[", "0", "]", "gt", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "identity", ")", "q_name", "=", "QName", "(", "namespace", "=", "namespace", ",", "local_name", "=", "obj", ",", "prefix", "=", "prefix", ")", "gt", "[", "'rdf_type'", "]", "=", "q_name", "gt_obj", "=", "GenericTopLevel", "(", "*", "*", "gt", ")", "self", ".", "_annotations", "[", "identity", ".", "toPython", "(", ")", "]", "=", "gt_obj", "self", ".", "_collection_store", "[", "identity", ".", "toPython", "(", ")", "]", "=", "gt_obj" ]
Find any non-defined elements at TopLevel and create annotations
[ "Find", "any", "non", "-", "defined", "elements", "at", "TopLevel", "and", "create", "annotations" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L483-L499
247,860
tjomasc/snekbol
snekbol/document.py
Document._read_collections
def _read_collections(self, graph): """ Read graph and add collections to document """ for e in self._get_elements(graph, SBOL.Collection): identity = e[0] c = self._get_rdf_identified(graph, identity) members = [] # Need to handle other non-standard TopLevel objects first for m in graph.triples((identity, SBOL.member, None)): members.append(self._collection_store[m[2].toPython()]) obj = Collection(members=members, **c) self._collections[identity.toPython()] = obj
python
def _read_collections(self, graph): """ Read graph and add collections to document """ for e in self._get_elements(graph, SBOL.Collection): identity = e[0] c = self._get_rdf_identified(graph, identity) members = [] # Need to handle other non-standard TopLevel objects first for m in graph.triples((identity, SBOL.member, None)): members.append(self._collection_store[m[2].toPython()]) obj = Collection(members=members, **c) self._collections[identity.toPython()] = obj
[ "def", "_read_collections", "(", "self", ",", "graph", ")", ":", "for", "e", "in", "self", ".", "_get_elements", "(", "graph", ",", "SBOL", ".", "Collection", ")", ":", "identity", "=", "e", "[", "0", "]", "c", "=", "self", ".", "_get_rdf_identified", "(", "graph", ",", "identity", ")", "members", "=", "[", "]", "# Need to handle other non-standard TopLevel objects first", "for", "m", "in", "graph", ".", "triples", "(", "(", "identity", ",", "SBOL", ".", "member", ",", "None", ")", ")", ":", "members", ".", "append", "(", "self", ".", "_collection_store", "[", "m", "[", "2", "]", ".", "toPython", "(", ")", "]", ")", "obj", "=", "Collection", "(", "members", "=", "members", ",", "*", "*", "c", ")", "self", ".", "_collections", "[", "identity", ".", "toPython", "(", ")", "]", "=", "obj" ]
Read graph and add collections to document
[ "Read", "graph", "and", "add", "collections", "to", "document" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L501-L513
247,861
tjomasc/snekbol
snekbol/document.py
Document.read
def read(self, f): """ Read in an SBOL file, replacing current document contents """ self.clear_document() g = Graph() g.parse(f, format='xml') for n in g.namespaces(): ns = n[1].toPython() if not ns.endswith(('#', '/', ':')): ns = ns + '/' self._namespaces[n[0]] = ns # Extend the existing namespaces available XML_NS[n[0]] = ns self._read_sequences(g) self._read_component_definitions(g) self._extend_component_definitions(g) self._read_models(g) self._read_module_definitions(g) self._extend_module_definitions(g) self._read_annotations(g) # Last as this needs all other top level objects created self._read_collections(g)
python
def read(self, f): """ Read in an SBOL file, replacing current document contents """ self.clear_document() g = Graph() g.parse(f, format='xml') for n in g.namespaces(): ns = n[1].toPython() if not ns.endswith(('#', '/', ':')): ns = ns + '/' self._namespaces[n[0]] = ns # Extend the existing namespaces available XML_NS[n[0]] = ns self._read_sequences(g) self._read_component_definitions(g) self._extend_component_definitions(g) self._read_models(g) self._read_module_definitions(g) self._extend_module_definitions(g) self._read_annotations(g) # Last as this needs all other top level objects created self._read_collections(g)
[ "def", "read", "(", "self", ",", "f", ")", ":", "self", ".", "clear_document", "(", ")", "g", "=", "Graph", "(", ")", "g", ".", "parse", "(", "f", ",", "format", "=", "'xml'", ")", "for", "n", "in", "g", ".", "namespaces", "(", ")", ":", "ns", "=", "n", "[", "1", "]", ".", "toPython", "(", ")", "if", "not", "ns", ".", "endswith", "(", "(", "'#'", ",", "'/'", ",", "':'", ")", ")", ":", "ns", "=", "ns", "+", "'/'", "self", ".", "_namespaces", "[", "n", "[", "0", "]", "]", "=", "ns", "# Extend the existing namespaces available", "XML_NS", "[", "n", "[", "0", "]", "]", "=", "ns", "self", ".", "_read_sequences", "(", "g", ")", "self", ".", "_read_component_definitions", "(", "g", ")", "self", ".", "_extend_component_definitions", "(", "g", ")", "self", ".", "_read_models", "(", "g", ")", "self", ".", "_read_module_definitions", "(", "g", ")", "self", ".", "_extend_module_definitions", "(", "g", ")", "self", ".", "_read_annotations", "(", "g", ")", "# Last as this needs all other top level objects created", "self", ".", "_read_collections", "(", "g", ")" ]
Read in an SBOL file, replacing current document contents
[ "Read", "in", "an", "SBOL", "file", "replacing", "current", "document", "contents" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L515-L540
247,862
tjomasc/snekbol
snekbol/document.py
Document.write
def write(self, f): """ Write an SBOL file from current document contents """ rdf = ET.Element(NS('rdf', 'RDF'), nsmap=XML_NS) # TODO: TopLevel Annotations sequence_values = sorted(self._sequences.values(), key=lambda x: x.identity) self._add_to_root(rdf, sequence_values) component_values = sorted(self._components.values(), key=lambda x: x.identity) self._add_to_root(rdf, component_values) model_values = sorted(self._models.values(), key=lambda x: x.identity) self._add_to_root(rdf, model_values) module_values = sorted(self._modules.values(), key=lambda x: x.identity) self._add_to_root(rdf, module_values) collection_values = sorted(self._collections.values(), key=lambda x: x.identity) self._add_to_root(rdf, collection_values) annotation_values = sorted(self._annotations.values(), key=lambda x: x.identity) self._add_to_root(rdf, annotation_values) f.write(ET.tostring(rdf, pretty_print=True, xml_declaration=True, encoding='utf-8'))
python
def write(self, f): """ Write an SBOL file from current document contents """ rdf = ET.Element(NS('rdf', 'RDF'), nsmap=XML_NS) # TODO: TopLevel Annotations sequence_values = sorted(self._sequences.values(), key=lambda x: x.identity) self._add_to_root(rdf, sequence_values) component_values = sorted(self._components.values(), key=lambda x: x.identity) self._add_to_root(rdf, component_values) model_values = sorted(self._models.values(), key=lambda x: x.identity) self._add_to_root(rdf, model_values) module_values = sorted(self._modules.values(), key=lambda x: x.identity) self._add_to_root(rdf, module_values) collection_values = sorted(self._collections.values(), key=lambda x: x.identity) self._add_to_root(rdf, collection_values) annotation_values = sorted(self._annotations.values(), key=lambda x: x.identity) self._add_to_root(rdf, annotation_values) f.write(ET.tostring(rdf, pretty_print=True, xml_declaration=True, encoding='utf-8'))
[ "def", "write", "(", "self", ",", "f", ")", ":", "rdf", "=", "ET", ".", "Element", "(", "NS", "(", "'rdf'", ",", "'RDF'", ")", ",", "nsmap", "=", "XML_NS", ")", "# TODO: TopLevel Annotations", "sequence_values", "=", "sorted", "(", "self", ".", "_sequences", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "identity", ")", "self", ".", "_add_to_root", "(", "rdf", ",", "sequence_values", ")", "component_values", "=", "sorted", "(", "self", ".", "_components", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "identity", ")", "self", ".", "_add_to_root", "(", "rdf", ",", "component_values", ")", "model_values", "=", "sorted", "(", "self", ".", "_models", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "identity", ")", "self", ".", "_add_to_root", "(", "rdf", ",", "model_values", ")", "module_values", "=", "sorted", "(", "self", ".", "_modules", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "identity", ")", "self", ".", "_add_to_root", "(", "rdf", ",", "module_values", ")", "collection_values", "=", "sorted", "(", "self", ".", "_collections", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "identity", ")", "self", ".", "_add_to_root", "(", "rdf", ",", "collection_values", ")", "annotation_values", "=", "sorted", "(", "self", ".", "_annotations", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "identity", ")", "self", ".", "_add_to_root", "(", "rdf", ",", "annotation_values", ")", "f", ".", "write", "(", "ET", ".", "tostring", "(", "rdf", ",", "pretty_print", "=", "True", ",", "xml_declaration", "=", "True", ",", "encoding", "=", "'utf-8'", ")", ")" ]
Write an SBOL file from current document contents
[ "Write", "an", "SBOL", "file", "from", "current", "document", "contents" ]
0b491aa96e0b1bd09e6c80cfb43807dd8a876c83
https://github.com/tjomasc/snekbol/blob/0b491aa96e0b1bd09e6c80cfb43807dd8a876c83/snekbol/document.py#L553-L576
247,863
FujiMakoto/IPS-Vagrant
ips_vagrant/models/sites.py
Domain.get
def get(cls, dname): """ Get the requested domain @param dname: Domain name @type dname: str @rtype: Domain or None """ Domain = cls dname = dname.hostname if hasattr(dname, 'hostname') else dname.lower() return Session.query(Domain).filter(Domain.name == dname).first()
python
def get(cls, dname): """ Get the requested domain @param dname: Domain name @type dname: str @rtype: Domain or None """ Domain = cls dname = dname.hostname if hasattr(dname, 'hostname') else dname.lower() return Session.query(Domain).filter(Domain.name == dname).first()
[ "def", "get", "(", "cls", ",", "dname", ")", ":", "Domain", "=", "cls", "dname", "=", "dname", ".", "hostname", "if", "hasattr", "(", "dname", ",", "'hostname'", ")", "else", "dname", ".", "lower", "(", ")", "return", "Session", ".", "query", "(", "Domain", ")", ".", "filter", "(", "Domain", ".", "name", "==", "dname", ")", ".", "first", "(", ")" ]
Get the requested domain @param dname: Domain name @type dname: str @rtype: Domain or None
[ "Get", "the", "requested", "domain" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/models/sites.py#L56-L65
247,864
FujiMakoto/IPS-Vagrant
ips_vagrant/models/sites.py
Domain.get_or_create
def get_or_create(cls, dname): """ Get the requested domain, or create it if it doesn't exist already @param dname: Domain name @type dname: str @rtype: Domain """ Domain = cls dname = dname.hostname if hasattr(dname, 'hostname') else dname extras = 'www.{dn}'.format(dn=dname) if dname not in ('localhost', ) and not \ re.match('^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', dname) else None # Fetch the domain entry if it already exists logging.getLogger('ipsv.sites.domain').debug('Checking if the domain %s has already been registered', dname) domain = Session.query(Domain).filter(Domain.name == dname).first() # Otherwise create it now if not domain: logging.getLogger('ipsv.sites.domain')\ .debug('Domain name does not yet exist, creating a new database entry') domain = Domain(name=dname, extras=extras) Session.add(domain) Session.commit() return domain
python
def get_or_create(cls, dname): """ Get the requested domain, or create it if it doesn't exist already @param dname: Domain name @type dname: str @rtype: Domain """ Domain = cls dname = dname.hostname if hasattr(dname, 'hostname') else dname extras = 'www.{dn}'.format(dn=dname) if dname not in ('localhost', ) and not \ re.match('^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', dname) else None # Fetch the domain entry if it already exists logging.getLogger('ipsv.sites.domain').debug('Checking if the domain %s has already been registered', dname) domain = Session.query(Domain).filter(Domain.name == dname).first() # Otherwise create it now if not domain: logging.getLogger('ipsv.sites.domain')\ .debug('Domain name does not yet exist, creating a new database entry') domain = Domain(name=dname, extras=extras) Session.add(domain) Session.commit() return domain
[ "def", "get_or_create", "(", "cls", ",", "dname", ")", ":", "Domain", "=", "cls", "dname", "=", "dname", ".", "hostname", "if", "hasattr", "(", "dname", ",", "'hostname'", ")", "else", "dname", "extras", "=", "'www.{dn}'", ".", "format", "(", "dn", "=", "dname", ")", "if", "dname", "not", "in", "(", "'localhost'", ",", ")", "and", "not", "re", ".", "match", "(", "'^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$'", ",", "dname", ")", "else", "None", "# Fetch the domain entry if it already exists", "logging", ".", "getLogger", "(", "'ipsv.sites.domain'", ")", ".", "debug", "(", "'Checking if the domain %s has already been registered'", ",", "dname", ")", "domain", "=", "Session", ".", "query", "(", "Domain", ")", ".", "filter", "(", "Domain", ".", "name", "==", "dname", ")", ".", "first", "(", ")", "# Otherwise create it now", "if", "not", "domain", ":", "logging", ".", "getLogger", "(", "'ipsv.sites.domain'", ")", ".", "debug", "(", "'Domain name does not yet exist, creating a new database entry'", ")", "domain", "=", "Domain", "(", "name", "=", "dname", ",", "extras", "=", "extras", ")", "Session", ".", "add", "(", "domain", ")", "Session", ".", "commit", "(", ")", "return", "domain" ]
Get the requested domain, or create it if it doesn't exist already @param dname: Domain name @type dname: str @rtype: Domain
[ "Get", "the", "requested", "domain", "or", "create", "it", "if", "it", "doesn", "t", "exist", "already" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/models/sites.py#L68-L91
247,865
FujiMakoto/IPS-Vagrant
ips_vagrant/models/sites.py
Site.all
def all(cls, domain=None): """ Return all sites @param domain: The domain to filter by @type domain: Domain @rtype: list of Site """ Site = cls site = Session.query(Site) if domain: site.filter(Site.domain == domain) return site.all()
python
def all(cls, domain=None): """ Return all sites @param domain: The domain to filter by @type domain: Domain @rtype: list of Site """ Site = cls site = Session.query(Site) if domain: site.filter(Site.domain == domain) return site.all()
[ "def", "all", "(", "cls", ",", "domain", "=", "None", ")", ":", "Site", "=", "cls", "site", "=", "Session", ".", "query", "(", "Site", ")", "if", "domain", ":", "site", ".", "filter", "(", "Site", ".", "domain", "==", "domain", ")", "return", "site", ".", "all", "(", ")" ]
Return all sites @param domain: The domain to filter by @type domain: Domain @rtype: list of Site
[ "Return", "all", "sites" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/models/sites.py#L132-L143
247,866
FujiMakoto/IPS-Vagrant
ips_vagrant/models/sites.py
Site.get
def get(cls, domain, name): """ Get the requested site entry @param domain: Domain name @type domain: Domain @param name: Site name @type name: str @rtype: Domain """ Site = cls return Session.query(Site).filter(Site.domain == domain).filter(collate(Site.name, 'NOCASE') == name).first()
python
def get(cls, domain, name): """ Get the requested site entry @param domain: Domain name @type domain: Domain @param name: Site name @type name: str @rtype: Domain """ Site = cls return Session.query(Site).filter(Site.domain == domain).filter(collate(Site.name, 'NOCASE') == name).first()
[ "def", "get", "(", "cls", ",", "domain", ",", "name", ")", ":", "Site", "=", "cls", "return", "Session", ".", "query", "(", "Site", ")", ".", "filter", "(", "Site", ".", "domain", "==", "domain", ")", ".", "filter", "(", "collate", "(", "Site", ".", "name", ",", "'NOCASE'", ")", "==", "name", ")", ".", "first", "(", ")" ]
Get the requested site entry @param domain: Domain name @type domain: Domain @param name: Site name @type name: str @rtype: Domain
[ "Get", "the", "requested", "site", "entry" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/models/sites.py#L146-L156
247,867
FujiMakoto/IPS-Vagrant
ips_vagrant/models/sites.py
Site.delete
def delete(self, drop_database=True): """ Delete the site entry @param drop_database: Drop the sites associated MySQL database @type drop_database: bool """ self.disable() Session.delete(self) if drop_database and self.db_name: mysql = create_engine('mysql://root:secret@localhost') mysql.execute('DROP DATABASE IF EXISTS `{db}`'.format(db=self.db_name)) try: mysql.execute('DROP USER `{u}`'.format(u=self.db_user)) except SQLAlchemyError: pass
python
def delete(self, drop_database=True): """ Delete the site entry @param drop_database: Drop the sites associated MySQL database @type drop_database: bool """ self.disable() Session.delete(self) if drop_database and self.db_name: mysql = create_engine('mysql://root:secret@localhost') mysql.execute('DROP DATABASE IF EXISTS `{db}`'.format(db=self.db_name)) try: mysql.execute('DROP USER `{u}`'.format(u=self.db_user)) except SQLAlchemyError: pass
[ "def", "delete", "(", "self", ",", "drop_database", "=", "True", ")", ":", "self", ".", "disable", "(", ")", "Session", ".", "delete", "(", "self", ")", "if", "drop_database", "and", "self", ".", "db_name", ":", "mysql", "=", "create_engine", "(", "'mysql://root:secret@localhost'", ")", "mysql", ".", "execute", "(", "'DROP DATABASE IF EXISTS `{db}`'", ".", "format", "(", "db", "=", "self", ".", "db_name", ")", ")", "try", ":", "mysql", ".", "execute", "(", "'DROP USER `{u}`'", ".", "format", "(", "u", "=", "self", ".", "db_user", ")", ")", "except", "SQLAlchemyError", ":", "pass" ]
Delete the site entry @param drop_database: Drop the sites associated MySQL database @type drop_database: bool
[ "Delete", "the", "site", "entry" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/models/sites.py#L158-L173
247,868
FujiMakoto/IPS-Vagrant
ips_vagrant/models/sites.py
Site.version
def version(self, value): """ Save the Site's version from a string or version tuple @type value: tuple or str """ if isinstance(value, tuple): value = unparse_version(value) self._version = value
python
def version(self, value): """ Save the Site's version from a string or version tuple @type value: tuple or str """ if isinstance(value, tuple): value = unparse_version(value) self._version = value
[ "def", "version", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "tuple", ")", ":", "value", "=", "unparse_version", "(", "value", ")", "self", ".", "_version", "=", "value" ]
Save the Site's version from a string or version tuple @type value: tuple or str
[ "Save", "the", "Site", "s", "version", "from", "a", "string", "or", "version", "tuple" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/models/sites.py#L201-L209
247,869
FujiMakoto/IPS-Vagrant
ips_vagrant/models/sites.py
Site.enable
def enable(self, force=False): """ Enable this site """ log = logging.getLogger('ipsv.models.sites.site') log.debug('Disabling all other sites under the domain %s', self.domain.name) Session.query(Site).filter(Site.id != self.id).filter(Site.domain == self.domain).update({'enabled': 0}) sites_enabled_path = _cfg.get('Paths', 'NginxSitesEnabled') server_config_path = os.path.join(_cfg.get('Paths', 'NginxSitesAvailable'), self.domain.name) server_config_path = os.path.join(server_config_path, '{fn}.conf'.format(fn=self.slug)) symlink_path = os.path.join(sites_enabled_path, '{domain}-{fn}'.format(domain=self.domain.name, fn=os.path.basename(server_config_path))) links = glob(os.path.join(sites_enabled_path, '{domain}-*'.format(domain=self.domain.name))) for link in links: if os.path.islink(link): log.debug('Removing existing configuration symlink: %s', link) os.unlink(link) else: if not force: log.error('Configuration symlink path already exists, but it is not a symlink') raise Exception('Misconfiguration detected: symlink path already exists, but it is not a symlink ' 'and --force was not passed. Unable to continue') log.warn('Configuration symlink path already exists, but it is not a symlink. Removing anyways ' 'since --force was set') if os.path.isdir(symlink_path): shutil.rmtree(symlink_path) else: os.remove(symlink_path) log.info('Enabling Nginx configuration file') os.symlink(server_config_path, symlink_path) self.enabled = 1 Session.commit()
python
def enable(self, force=False): """ Enable this site """ log = logging.getLogger('ipsv.models.sites.site') log.debug('Disabling all other sites under the domain %s', self.domain.name) Session.query(Site).filter(Site.id != self.id).filter(Site.domain == self.domain).update({'enabled': 0}) sites_enabled_path = _cfg.get('Paths', 'NginxSitesEnabled') server_config_path = os.path.join(_cfg.get('Paths', 'NginxSitesAvailable'), self.domain.name) server_config_path = os.path.join(server_config_path, '{fn}.conf'.format(fn=self.slug)) symlink_path = os.path.join(sites_enabled_path, '{domain}-{fn}'.format(domain=self.domain.name, fn=os.path.basename(server_config_path))) links = glob(os.path.join(sites_enabled_path, '{domain}-*'.format(domain=self.domain.name))) for link in links: if os.path.islink(link): log.debug('Removing existing configuration symlink: %s', link) os.unlink(link) else: if not force: log.error('Configuration symlink path already exists, but it is not a symlink') raise Exception('Misconfiguration detected: symlink path already exists, but it is not a symlink ' 'and --force was not passed. Unable to continue') log.warn('Configuration symlink path already exists, but it is not a symlink. Removing anyways ' 'since --force was set') if os.path.isdir(symlink_path): shutil.rmtree(symlink_path) else: os.remove(symlink_path) log.info('Enabling Nginx configuration file') os.symlink(server_config_path, symlink_path) self.enabled = 1 Session.commit()
[ "def", "enable", "(", "self", ",", "force", "=", "False", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "'ipsv.models.sites.site'", ")", "log", ".", "debug", "(", "'Disabling all other sites under the domain %s'", ",", "self", ".", "domain", ".", "name", ")", "Session", ".", "query", "(", "Site", ")", ".", "filter", "(", "Site", ".", "id", "!=", "self", ".", "id", ")", ".", "filter", "(", "Site", ".", "domain", "==", "self", ".", "domain", ")", ".", "update", "(", "{", "'enabled'", ":", "0", "}", ")", "sites_enabled_path", "=", "_cfg", ".", "get", "(", "'Paths'", ",", "'NginxSitesEnabled'", ")", "server_config_path", "=", "os", ".", "path", ".", "join", "(", "_cfg", ".", "get", "(", "'Paths'", ",", "'NginxSitesAvailable'", ")", ",", "self", ".", "domain", ".", "name", ")", "server_config_path", "=", "os", ".", "path", ".", "join", "(", "server_config_path", ",", "'{fn}.conf'", ".", "format", "(", "fn", "=", "self", ".", "slug", ")", ")", "symlink_path", "=", "os", ".", "path", ".", "join", "(", "sites_enabled_path", ",", "'{domain}-{fn}'", ".", "format", "(", "domain", "=", "self", ".", "domain", ".", "name", ",", "fn", "=", "os", ".", "path", ".", "basename", "(", "server_config_path", ")", ")", ")", "links", "=", "glob", "(", "os", ".", "path", ".", "join", "(", "sites_enabled_path", ",", "'{domain}-*'", ".", "format", "(", "domain", "=", "self", ".", "domain", ".", "name", ")", ")", ")", "for", "link", "in", "links", ":", "if", "os", ".", "path", ".", "islink", "(", "link", ")", ":", "log", ".", "debug", "(", "'Removing existing configuration symlink: %s'", ",", "link", ")", "os", ".", "unlink", "(", "link", ")", "else", ":", "if", "not", "force", ":", "log", ".", "error", "(", "'Configuration symlink path already exists, but it is not a symlink'", ")", "raise", "Exception", "(", "'Misconfiguration detected: symlink path already exists, but it is not a symlink '", "'and --force was not passed. Unable to continue'", ")", "log", ".", "warn", "(", "'Configuration symlink path already exists, but it is not a symlink. Removing anyways '", "'since --force was set'", ")", "if", "os", ".", "path", ".", "isdir", "(", "symlink_path", ")", ":", "shutil", ".", "rmtree", "(", "symlink_path", ")", "else", ":", "os", ".", "remove", "(", "symlink_path", ")", "log", ".", "info", "(", "'Enabling Nginx configuration file'", ")", "os", ".", "symlink", "(", "server_config_path", ",", "symlink_path", ")", "self", ".", "enabled", "=", "1", "Session", ".", "commit", "(", ")" ]
Enable this site
[ "Enable", "this", "site" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/models/sites.py#L211-L245
247,870
FujiMakoto/IPS-Vagrant
ips_vagrant/models/sites.py
Site.disable
def disable(self): """ Disable this site """ log = logging.getLogger('ipsv.models.sites.site') sites_enabled_path = _cfg.get('Paths', 'NginxSitesEnabled') symlink_path = os.path.join(sites_enabled_path, '{domain}-{fn}.conf'.format(domain=self.domain.name, fn=self.slug)) log.debug('Symlink path: %s', symlink_path) if os.path.islink(symlink_path): log.info('Removing configuration symlink: %s', symlink_path) os.unlink(symlink_path) self.enabled = 0 Session.commit()
python
def disable(self): """ Disable this site """ log = logging.getLogger('ipsv.models.sites.site') sites_enabled_path = _cfg.get('Paths', 'NginxSitesEnabled') symlink_path = os.path.join(sites_enabled_path, '{domain}-{fn}.conf'.format(domain=self.domain.name, fn=self.slug)) log.debug('Symlink path: %s', symlink_path) if os.path.islink(symlink_path): log.info('Removing configuration symlink: %s', symlink_path) os.unlink(symlink_path) self.enabled = 0 Session.commit()
[ "def", "disable", "(", "self", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "'ipsv.models.sites.site'", ")", "sites_enabled_path", "=", "_cfg", ".", "get", "(", "'Paths'", ",", "'NginxSitesEnabled'", ")", "symlink_path", "=", "os", ".", "path", ".", "join", "(", "sites_enabled_path", ",", "'{domain}-{fn}.conf'", ".", "format", "(", "domain", "=", "self", ".", "domain", ".", "name", ",", "fn", "=", "self", ".", "slug", ")", ")", "log", ".", "debug", "(", "'Symlink path: %s'", ",", "symlink_path", ")", "if", "os", ".", "path", ".", "islink", "(", "symlink_path", ")", ":", "log", ".", "info", "(", "'Removing configuration symlink: %s'", ",", "symlink_path", ")", "os", ".", "unlink", "(", "symlink_path", ")", "self", ".", "enabled", "=", "0", "Session", ".", "commit", "(", ")" ]
Disable this site
[ "Disable", "this", "site" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/models/sites.py#L247-L261
247,871
FujiMakoto/IPS-Vagrant
ips_vagrant/models/sites.py
Site.write_nginx_config
def write_nginx_config(self): """ Write the Nginx configuration file for this Site """ log = logging.getLogger('ipsv.models.sites.site') if not os.path.exists(self.root): log.debug('Creating HTTP root directory: %s', self.root) os.makedirs(self.root, 0o755) # Generate our server block configuration server_block = ServerBlock(self) server_config_path = os.path.join(_cfg.get('Paths', 'NginxSitesAvailable'), self.domain.name) if not os.path.exists(server_config_path): log.debug('Creating new configuration path: %s', server_config_path) os.makedirs(server_config_path, 0o755) server_config_path = os.path.join(server_config_path, '{fn}.conf'.format(fn=self.slug)) if os.path.exists(server_config_path): log.info('Server block configuration file already exists, overwriting: %s', server_config_path) os.remove(server_config_path) log.info('Writing Nginx server block configuration file') with open(server_config_path, 'w') as f: f.write(server_block.template)
python
def write_nginx_config(self): """ Write the Nginx configuration file for this Site """ log = logging.getLogger('ipsv.models.sites.site') if not os.path.exists(self.root): log.debug('Creating HTTP root directory: %s', self.root) os.makedirs(self.root, 0o755) # Generate our server block configuration server_block = ServerBlock(self) server_config_path = os.path.join(_cfg.get('Paths', 'NginxSitesAvailable'), self.domain.name) if not os.path.exists(server_config_path): log.debug('Creating new configuration path: %s', server_config_path) os.makedirs(server_config_path, 0o755) server_config_path = os.path.join(server_config_path, '{fn}.conf'.format(fn=self.slug)) if os.path.exists(server_config_path): log.info('Server block configuration file already exists, overwriting: %s', server_config_path) os.remove(server_config_path) log.info('Writing Nginx server block configuration file') with open(server_config_path, 'w') as f: f.write(server_block.template)
[ "def", "write_nginx_config", "(", "self", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "'ipsv.models.sites.site'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "root", ")", ":", "log", ".", "debug", "(", "'Creating HTTP root directory: %s'", ",", "self", ".", "root", ")", "os", ".", "makedirs", "(", "self", ".", "root", ",", "0o755", ")", "# Generate our server block configuration", "server_block", "=", "ServerBlock", "(", "self", ")", "server_config_path", "=", "os", ".", "path", ".", "join", "(", "_cfg", ".", "get", "(", "'Paths'", ",", "'NginxSitesAvailable'", ")", ",", "self", ".", "domain", ".", "name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "server_config_path", ")", ":", "log", ".", "debug", "(", "'Creating new configuration path: %s'", ",", "server_config_path", ")", "os", ".", "makedirs", "(", "server_config_path", ",", "0o755", ")", "server_config_path", "=", "os", ".", "path", ".", "join", "(", "server_config_path", ",", "'{fn}.conf'", ".", "format", "(", "fn", "=", "self", ".", "slug", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "server_config_path", ")", ":", "log", ".", "info", "(", "'Server block configuration file already exists, overwriting: %s'", ",", "server_config_path", ")", "os", ".", "remove", "(", "server_config_path", ")", "log", ".", "info", "(", "'Writing Nginx server block configuration file'", ")", "with", "open", "(", "server_config_path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "server_block", ".", "template", ")" ]
Write the Nginx configuration file for this Site
[ "Write", "the", "Nginx", "configuration", "file", "for", "this", "Site" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/models/sites.py#L263-L287
247,872
rackerlabs/rackspace-python-neutronclient
neutronclient/neutron/v2_0/network.py
ListNetwork.extend_list
def extend_list(self, data, parsed_args): """Add subnet information to a network list.""" neutron_client = self.get_client() search_opts = {'fields': ['id', 'cidr']} if self.pagination_support: page_size = parsed_args.page_size if page_size: search_opts.update({'limit': page_size}) subnet_ids = [] for n in data: if 'subnets' in n: subnet_ids.extend(n['subnets']) def _get_subnet_list(sub_ids): search_opts['id'] = sub_ids return neutron_client.list_subnets( **search_opts).get('subnets', []) try: subnets = _get_subnet_list(subnet_ids) except exceptions.RequestURITooLong as uri_len_exc: # The URI is too long because of too many subnet_id filters # Use the excess attribute of the exception to know how many # subnet_id filters can be inserted into a single request subnet_count = len(subnet_ids) max_size = ((self.subnet_id_filter_len * subnet_count) - uri_len_exc.excess) chunk_size = max_size // self.subnet_id_filter_len subnets = [] for i in range(0, subnet_count, chunk_size): subnets.extend( _get_subnet_list(subnet_ids[i: i + chunk_size])) subnet_dict = dict([(s['id'], s) for s in subnets]) for n in data: if 'subnets' in n: n['subnets'] = [(subnet_dict.get(s) or {"id": s}) for s in n['subnets']]
python
def extend_list(self, data, parsed_args): """Add subnet information to a network list.""" neutron_client = self.get_client() search_opts = {'fields': ['id', 'cidr']} if self.pagination_support: page_size = parsed_args.page_size if page_size: search_opts.update({'limit': page_size}) subnet_ids = [] for n in data: if 'subnets' in n: subnet_ids.extend(n['subnets']) def _get_subnet_list(sub_ids): search_opts['id'] = sub_ids return neutron_client.list_subnets( **search_opts).get('subnets', []) try: subnets = _get_subnet_list(subnet_ids) except exceptions.RequestURITooLong as uri_len_exc: # The URI is too long because of too many subnet_id filters # Use the excess attribute of the exception to know how many # subnet_id filters can be inserted into a single request subnet_count = len(subnet_ids) max_size = ((self.subnet_id_filter_len * subnet_count) - uri_len_exc.excess) chunk_size = max_size // self.subnet_id_filter_len subnets = [] for i in range(0, subnet_count, chunk_size): subnets.extend( _get_subnet_list(subnet_ids[i: i + chunk_size])) subnet_dict = dict([(s['id'], s) for s in subnets]) for n in data: if 'subnets' in n: n['subnets'] = [(subnet_dict.get(s) or {"id": s}) for s in n['subnets']]
[ "def", "extend_list", "(", "self", ",", "data", ",", "parsed_args", ")", ":", "neutron_client", "=", "self", ".", "get_client", "(", ")", "search_opts", "=", "{", "'fields'", ":", "[", "'id'", ",", "'cidr'", "]", "}", "if", "self", ".", "pagination_support", ":", "page_size", "=", "parsed_args", ".", "page_size", "if", "page_size", ":", "search_opts", ".", "update", "(", "{", "'limit'", ":", "page_size", "}", ")", "subnet_ids", "=", "[", "]", "for", "n", "in", "data", ":", "if", "'subnets'", "in", "n", ":", "subnet_ids", ".", "extend", "(", "n", "[", "'subnets'", "]", ")", "def", "_get_subnet_list", "(", "sub_ids", ")", ":", "search_opts", "[", "'id'", "]", "=", "sub_ids", "return", "neutron_client", ".", "list_subnets", "(", "*", "*", "search_opts", ")", ".", "get", "(", "'subnets'", ",", "[", "]", ")", "try", ":", "subnets", "=", "_get_subnet_list", "(", "subnet_ids", ")", "except", "exceptions", ".", "RequestURITooLong", "as", "uri_len_exc", ":", "# The URI is too long because of too many subnet_id filters", "# Use the excess attribute of the exception to know how many", "# subnet_id filters can be inserted into a single request", "subnet_count", "=", "len", "(", "subnet_ids", ")", "max_size", "=", "(", "(", "self", ".", "subnet_id_filter_len", "*", "subnet_count", ")", "-", "uri_len_exc", ".", "excess", ")", "chunk_size", "=", "max_size", "//", "self", ".", "subnet_id_filter_len", "subnets", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "subnet_count", ",", "chunk_size", ")", ":", "subnets", ".", "extend", "(", "_get_subnet_list", "(", "subnet_ids", "[", "i", ":", "i", "+", "chunk_size", "]", ")", ")", "subnet_dict", "=", "dict", "(", "[", "(", "s", "[", "'id'", "]", ",", "s", ")", "for", "s", "in", "subnets", "]", ")", "for", "n", "in", "data", ":", "if", "'subnets'", "in", "n", ":", "n", "[", "'subnets'", "]", "=", "[", "(", "subnet_dict", ".", "get", "(", "s", ")", "or", "{", "\"id\"", ":", "s", "}", ")", "for", "s", "in", "n", "[", "'subnets'", "]", "]" ]
Add subnet information to a network list.
[ "Add", "subnet", "information", "to", "a", "network", "list", "." ]
5a5009a8fe078e3aa1d582176669f1b28ab26bef
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/neutron/v2_0/network.py#L86-L123
247,873
mbarakaja/braulio
braulio/version.py
Version.bump
def bump(self, bump_part): """Return a new bumped version instance.""" major, minor, patch, stage, n = tuple(self) # stage bump if bump_part not in {"major", "minor", "patch"}: if bump_part not in self.stages: raise ValueError(f"Unknown {bump_part} stage") # We can not bump from final stage to final again. if self.stage == "final" and bump_part == "final": raise ValueError(f"{self} is already in final stage.") # bump in the same stage (numeric part) if bump_part == self.stage: n += 1 else: new_stage_number = tuple(self.stages).index(bump_part) # We can not bump to a previous stage if new_stage_number < self._stage_number: raise ValueError(f"{bump_part} stage is previous to {self}") stage = bump_part n = 0 else: # major, minor, or patch bump # Only version in final stage can do a major, minor or patch # bump if self.stage != "final": raise ValueError( f"{self} is a pre-release version." f" Can't do a {bump_part} version bump" ) if bump_part == "major": major += 1 minor, patch = 0, 0 elif bump_part == "minor": minor += 1 patch = 0 else: patch += 1 return Version(major=major, minor=minor, patch=patch, stage=stage, n=n)
python
def bump(self, bump_part): """Return a new bumped version instance.""" major, minor, patch, stage, n = tuple(self) # stage bump if bump_part not in {"major", "minor", "patch"}: if bump_part not in self.stages: raise ValueError(f"Unknown {bump_part} stage") # We can not bump from final stage to final again. if self.stage == "final" and bump_part == "final": raise ValueError(f"{self} is already in final stage.") # bump in the same stage (numeric part) if bump_part == self.stage: n += 1 else: new_stage_number = tuple(self.stages).index(bump_part) # We can not bump to a previous stage if new_stage_number < self._stage_number: raise ValueError(f"{bump_part} stage is previous to {self}") stage = bump_part n = 0 else: # major, minor, or patch bump # Only version in final stage can do a major, minor or patch # bump if self.stage != "final": raise ValueError( f"{self} is a pre-release version." f" Can't do a {bump_part} version bump" ) if bump_part == "major": major += 1 minor, patch = 0, 0 elif bump_part == "minor": minor += 1 patch = 0 else: patch += 1 return Version(major=major, minor=minor, patch=patch, stage=stage, n=n)
[ "def", "bump", "(", "self", ",", "bump_part", ")", ":", "major", ",", "minor", ",", "patch", ",", "stage", ",", "n", "=", "tuple", "(", "self", ")", "# stage bump", "if", "bump_part", "not", "in", "{", "\"major\"", ",", "\"minor\"", ",", "\"patch\"", "}", ":", "if", "bump_part", "not", "in", "self", ".", "stages", ":", "raise", "ValueError", "(", "f\"Unknown {bump_part} stage\"", ")", "# We can not bump from final stage to final again.", "if", "self", ".", "stage", "==", "\"final\"", "and", "bump_part", "==", "\"final\"", ":", "raise", "ValueError", "(", "f\"{self} is already in final stage.\"", ")", "# bump in the same stage (numeric part)", "if", "bump_part", "==", "self", ".", "stage", ":", "n", "+=", "1", "else", ":", "new_stage_number", "=", "tuple", "(", "self", ".", "stages", ")", ".", "index", "(", "bump_part", ")", "# We can not bump to a previous stage", "if", "new_stage_number", "<", "self", ".", "_stage_number", ":", "raise", "ValueError", "(", "f\"{bump_part} stage is previous to {self}\"", ")", "stage", "=", "bump_part", "n", "=", "0", "else", ":", "# major, minor, or patch bump", "# Only version in final stage can do a major, minor or patch", "# bump", "if", "self", ".", "stage", "!=", "\"final\"", ":", "raise", "ValueError", "(", "f\"{self} is a pre-release version.\"", "f\" Can't do a {bump_part} version bump\"", ")", "if", "bump_part", "==", "\"major\"", ":", "major", "+=", "1", "minor", ",", "patch", "=", "0", ",", "0", "elif", "bump_part", "==", "\"minor\"", ":", "minor", "+=", "1", "patch", "=", "0", "else", ":", "patch", "+=", "1", "return", "Version", "(", "major", "=", "major", ",", "minor", "=", "minor", ",", "patch", "=", "patch", ",", "stage", "=", "stage", ",", "n", "=", "n", ")" ]
Return a new bumped version instance.
[ "Return", "a", "new", "bumped", "version", "instance", "." ]
70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b
https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/version.py#L108-L155
247,874
rorr73/LifeSOSpy
lifesospy/asynchelper.py
AsyncHelper.create_task
def create_task(self, target: Callable[..., Any], *args: Any)\ -> asyncio.tasks.Task: """Create task and add to our collection of pending tasks.""" if asyncio.iscoroutine(target): task = self._loop.create_task(target) elif asyncio.iscoroutinefunction(target): task = self._loop.create_task(target(*args)) else: raise ValueError("Expected coroutine as target") self._pending_tasks.append(task) return task
python
def create_task(self, target: Callable[..., Any], *args: Any)\ -> asyncio.tasks.Task: """Create task and add to our collection of pending tasks.""" if asyncio.iscoroutine(target): task = self._loop.create_task(target) elif asyncio.iscoroutinefunction(target): task = self._loop.create_task(target(*args)) else: raise ValueError("Expected coroutine as target") self._pending_tasks.append(task) return task
[ "def", "create_task", "(", "self", ",", "target", ":", "Callable", "[", "...", ",", "Any", "]", ",", "*", "args", ":", "Any", ")", "->", "asyncio", ".", "tasks", ".", "Task", ":", "if", "asyncio", ".", "iscoroutine", "(", "target", ")", ":", "task", "=", "self", ".", "_loop", ".", "create_task", "(", "target", ")", "elif", "asyncio", ".", "iscoroutinefunction", "(", "target", ")", ":", "task", "=", "self", ".", "_loop", ".", "create_task", "(", "target", "(", "*", "args", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Expected coroutine as target\"", ")", "self", ".", "_pending_tasks", ".", "append", "(", "task", ")", "return", "task" ]
Create task and add to our collection of pending tasks.
[ "Create", "task", "and", "add", "to", "our", "collection", "of", "pending", "tasks", "." ]
62360fbab2e90bf04d52b547093bdab2d4e389b4
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/asynchelper.py#L20-L30
247,875
rorr73/LifeSOSpy
lifesospy/asynchelper.py
AsyncHelper.cancel_pending_tasks
def cancel_pending_tasks(self): """Cancel all pending tasks.""" for task in self._pending_tasks: task.cancel() if not self._loop.is_running(): try: self._loop.run_until_complete(task) except asyncio.CancelledError: pass except Exception: # pylint: disable=broad-except _LOGGER.error("Unhandled exception from async task", exc_info=True)
python
def cancel_pending_tasks(self): """Cancel all pending tasks.""" for task in self._pending_tasks: task.cancel() if not self._loop.is_running(): try: self._loop.run_until_complete(task) except asyncio.CancelledError: pass except Exception: # pylint: disable=broad-except _LOGGER.error("Unhandled exception from async task", exc_info=True)
[ "def", "cancel_pending_tasks", "(", "self", ")", ":", "for", "task", "in", "self", ".", "_pending_tasks", ":", "task", ".", "cancel", "(", ")", "if", "not", "self", ".", "_loop", ".", "is_running", "(", ")", ":", "try", ":", "self", ".", "_loop", ".", "run_until_complete", "(", "task", ")", "except", "asyncio", ".", "CancelledError", ":", "pass", "except", "Exception", ":", "# pylint: disable=broad-except", "_LOGGER", ".", "error", "(", "\"Unhandled exception from async task\"", ",", "exc_info", "=", "True", ")" ]
Cancel all pending tasks.
[ "Cancel", "all", "pending", "tasks", "." ]
62360fbab2e90bf04d52b547093bdab2d4e389b4
https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/asynchelper.py#L32-L43
247,876
emilssolmanis/tapes
tapes/distributed/registry.py
RegistryAggregator.start
def start(self, fork=True): """Starts the registry aggregator. :param fork: whether to fork a process; if ``False``, blocks and stays in the existing process """ if not fork: distributed_logger.info('Starting metrics aggregator, not forking') _registry_aggregator(self.reporter, self.socket_addr) else: distributed_logger.info('Starting metrics aggregator, forking') p = Process(target=_registry_aggregator, args=(self.reporter, self.socket_addr, )) p.start() distributed_logger.info('Started metrics aggregator as PID %s', p.pid) self.process = p
python
def start(self, fork=True): """Starts the registry aggregator. :param fork: whether to fork a process; if ``False``, blocks and stays in the existing process """ if not fork: distributed_logger.info('Starting metrics aggregator, not forking') _registry_aggregator(self.reporter, self.socket_addr) else: distributed_logger.info('Starting metrics aggregator, forking') p = Process(target=_registry_aggregator, args=(self.reporter, self.socket_addr, )) p.start() distributed_logger.info('Started metrics aggregator as PID %s', p.pid) self.process = p
[ "def", "start", "(", "self", ",", "fork", "=", "True", ")", ":", "if", "not", "fork", ":", "distributed_logger", ".", "info", "(", "'Starting metrics aggregator, not forking'", ")", "_registry_aggregator", "(", "self", ".", "reporter", ",", "self", ".", "socket_addr", ")", "else", ":", "distributed_logger", ".", "info", "(", "'Starting metrics aggregator, forking'", ")", "p", "=", "Process", "(", "target", "=", "_registry_aggregator", ",", "args", "=", "(", "self", ".", "reporter", ",", "self", ".", "socket_addr", ",", ")", ")", "p", ".", "start", "(", ")", "distributed_logger", ".", "info", "(", "'Started metrics aggregator as PID %s'", ",", "p", ".", "pid", ")", "self", ".", "process", "=", "p" ]
Starts the registry aggregator. :param fork: whether to fork a process; if ``False``, blocks and stays in the existing process
[ "Starts", "the", "registry", "aggregator", "." ]
7797fc9ebcb359cb1ba5085570e3cab5ebcd1d3c
https://github.com/emilssolmanis/tapes/blob/7797fc9ebcb359cb1ba5085570e3cab5ebcd1d3c/tapes/distributed/registry.py#L68-L81
247,877
emilssolmanis/tapes
tapes/distributed/registry.py
RegistryAggregator.stop
def stop(self): """Terminates the forked process. Only valid if started as a fork, because... well you wouldn't get here otherwise. :return: """ distributed_logger.info('Stopping metrics aggregator') self.process.terminate() self.process.join() distributed_logger.info('Stopped metrics aggregator')
python
def stop(self): """Terminates the forked process. Only valid if started as a fork, because... well you wouldn't get here otherwise. :return: """ distributed_logger.info('Stopping metrics aggregator') self.process.terminate() self.process.join() distributed_logger.info('Stopped metrics aggregator')
[ "def", "stop", "(", "self", ")", ":", "distributed_logger", ".", "info", "(", "'Stopping metrics aggregator'", ")", "self", ".", "process", ".", "terminate", "(", ")", "self", ".", "process", ".", "join", "(", ")", "distributed_logger", ".", "info", "(", "'Stopped metrics aggregator'", ")" ]
Terminates the forked process. Only valid if started as a fork, because... well you wouldn't get here otherwise. :return:
[ "Terminates", "the", "forked", "process", "." ]
7797fc9ebcb359cb1ba5085570e3cab5ebcd1d3c
https://github.com/emilssolmanis/tapes/blob/7797fc9ebcb359cb1ba5085570e3cab5ebcd1d3c/tapes/distributed/registry.py#L83-L92
247,878
emilssolmanis/tapes
tapes/distributed/registry.py
DistributedRegistry.connect
def connect(self): """Connects to the 0MQ socket and starts publishing.""" distributed_logger.info('Connecting registry proxy to ZMQ socket %s', self.socket_addr) self.zmq_context = zmq.Context() sock = self.zmq_context.socket(zmq.PUB) sock.set_hwm(0) sock.setsockopt(zmq.LINGER, 0) sock.connect(self.socket_addr) distributed_logger.info('Connected registry proxy to ZMQ socket %s', self.socket_addr) def _reset_socket(values): for value in values: try: _reset_socket(value.values()) except AttributeError: value.socket = sock distributed_logger.debug('Resetting socket on metrics proxies') _reset_socket(self.stats.values()) self.socket = sock distributed_logger.debug('Reset socket on metrics proxies')
python
def connect(self): """Connects to the 0MQ socket and starts publishing.""" distributed_logger.info('Connecting registry proxy to ZMQ socket %s', self.socket_addr) self.zmq_context = zmq.Context() sock = self.zmq_context.socket(zmq.PUB) sock.set_hwm(0) sock.setsockopt(zmq.LINGER, 0) sock.connect(self.socket_addr) distributed_logger.info('Connected registry proxy to ZMQ socket %s', self.socket_addr) def _reset_socket(values): for value in values: try: _reset_socket(value.values()) except AttributeError: value.socket = sock distributed_logger.debug('Resetting socket on metrics proxies') _reset_socket(self.stats.values()) self.socket = sock distributed_logger.debug('Reset socket on metrics proxies')
[ "def", "connect", "(", "self", ")", ":", "distributed_logger", ".", "info", "(", "'Connecting registry proxy to ZMQ socket %s'", ",", "self", ".", "socket_addr", ")", "self", ".", "zmq_context", "=", "zmq", ".", "Context", "(", ")", "sock", "=", "self", ".", "zmq_context", ".", "socket", "(", "zmq", ".", "PUB", ")", "sock", ".", "set_hwm", "(", "0", ")", "sock", ".", "setsockopt", "(", "zmq", ".", "LINGER", ",", "0", ")", "sock", ".", "connect", "(", "self", ".", "socket_addr", ")", "distributed_logger", ".", "info", "(", "'Connected registry proxy to ZMQ socket %s'", ",", "self", ".", "socket_addr", ")", "def", "_reset_socket", "(", "values", ")", ":", "for", "value", "in", "values", ":", "try", ":", "_reset_socket", "(", "value", ".", "values", "(", ")", ")", "except", "AttributeError", ":", "value", ".", "socket", "=", "sock", "distributed_logger", ".", "debug", "(", "'Resetting socket on metrics proxies'", ")", "_reset_socket", "(", "self", ".", "stats", ".", "values", "(", ")", ")", "self", ".", "socket", "=", "sock", "distributed_logger", ".", "debug", "(", "'Reset socket on metrics proxies'", ")" ]
Connects to the 0MQ socket and starts publishing.
[ "Connects", "to", "the", "0MQ", "socket", "and", "starts", "publishing", "." ]
7797fc9ebcb359cb1ba5085570e3cab5ebcd1d3c
https://github.com/emilssolmanis/tapes/blob/7797fc9ebcb359cb1ba5085570e3cab5ebcd1d3c/tapes/distributed/registry.py#L122-L142
247,879
wooyek/django-powerbank
setup.py
get_version
def get_version(*file_paths): """Retrieves the version from path""" filename = os.path.join(os.path.dirname(__file__), *file_paths) print("Looking for version in: {}".format(filename)) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
python
def get_version(*file_paths): """Retrieves the version from path""" filename = os.path.join(os.path.dirname(__file__), *file_paths) print("Looking for version in: {}".format(filename)) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError('Unable to find version string.')
[ "def", "get_version", "(", "*", "file_paths", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "*", "file_paths", ")", "print", "(", "\"Looking for version in: {}\"", ".", "format", "(", "filename", ")", ")", "version_file", "=", "open", "(", "filename", ")", ".", "read", "(", ")", "version_match", "=", "re", ".", "search", "(", "r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"", ",", "version_file", ",", "re", ".", "M", ")", "if", "version_match", ":", "return", "version_match", ".", "group", "(", "1", ")", "raise", "RuntimeError", "(", "'Unable to find version string.'", ")" ]
Retrieves the version from path
[ "Retrieves", "the", "version", "from", "path" ]
df91189f2ac18bacc545ccf3c81c4465fb993949
https://github.com/wooyek/django-powerbank/blob/df91189f2ac18bacc545ccf3c81c4465fb993949/setup.py#L42-L50
247,880
zzzsochi/includer
includer.py
resolve_str
def resolve_str(name_or_func, module, default): """ Resolve and return object from dotted name """ assert isinstance(name_or_func, str) resolved = resolve(name_or_func, module=module) if isinstance(resolved, ModuleType): if not hasattr(resolved, default): raise ImportError("{}.{}".format(resolved.__name__, default)) resolved = getattr(resolved, default) if not callable(resolved): raise TypeError("{!r} is not callable" "".format(resolved)) return resolved
python
def resolve_str(name_or_func, module, default): """ Resolve and return object from dotted name """ assert isinstance(name_or_func, str) resolved = resolve(name_or_func, module=module) if isinstance(resolved, ModuleType): if not hasattr(resolved, default): raise ImportError("{}.{}".format(resolved.__name__, default)) resolved = getattr(resolved, default) if not callable(resolved): raise TypeError("{!r} is not callable" "".format(resolved)) return resolved
[ "def", "resolve_str", "(", "name_or_func", ",", "module", ",", "default", ")", ":", "assert", "isinstance", "(", "name_or_func", ",", "str", ")", "resolved", "=", "resolve", "(", "name_or_func", ",", "module", "=", "module", ")", "if", "isinstance", "(", "resolved", ",", "ModuleType", ")", ":", "if", "not", "hasattr", "(", "resolved", ",", "default", ")", ":", "raise", "ImportError", "(", "\"{}.{}\"", ".", "format", "(", "resolved", ".", "__name__", ",", "default", ")", ")", "resolved", "=", "getattr", "(", "resolved", ",", "default", ")", "if", "not", "callable", "(", "resolved", ")", ":", "raise", "TypeError", "(", "\"{!r} is not callable\"", "\"\"", ".", "format", "(", "resolved", ")", ")", "return", "resolved" ]
Resolve and return object from dotted name
[ "Resolve", "and", "return", "object", "from", "dotted", "name" ]
c0cbb7776fa416f5dac974b5bc19524683fbd99a
https://github.com/zzzsochi/includer/blob/c0cbb7776fa416f5dac974b5bc19524683fbd99a/includer.py#L6-L22
247,881
zzzsochi/includer
includer.py
include
def include(_name_or_func, *args, _module=None, _default='includeme', **kwargs): """ Resolve and call functions """ if callable(_name_or_func): resolved = _name_or_func else: resolved = resolve_str(_name_or_func, _module, _default) resolved(*args, **kwargs)
python
def include(_name_or_func, *args, _module=None, _default='includeme', **kwargs): """ Resolve and call functions """ if callable(_name_or_func): resolved = _name_or_func else: resolved = resolve_str(_name_or_func, _module, _default) resolved(*args, **kwargs)
[ "def", "include", "(", "_name_or_func", ",", "*", "args", ",", "_module", "=", "None", ",", "_default", "=", "'includeme'", ",", "*", "*", "kwargs", ")", ":", "if", "callable", "(", "_name_or_func", ")", ":", "resolved", "=", "_name_or_func", "else", ":", "resolved", "=", "resolve_str", "(", "_name_or_func", ",", "_module", ",", "_default", ")", "resolved", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Resolve and call functions
[ "Resolve", "and", "call", "functions" ]
c0cbb7776fa416f5dac974b5bc19524683fbd99a
https://github.com/zzzsochi/includer/blob/c0cbb7776fa416f5dac974b5bc19524683fbd99a/includer.py#L25-L34
247,882
honsiorovskyi/codeharvester
src/codeharvester/harvester.py
Harvester.parse_requirements
def parse_requirements(self, filename): """ Recursively find all the requirements needed storing them in req_parents, req_paths, req_linenos """ cwd = os.path.dirname(filename) try: fd = open(filename, 'r') for i, line in enumerate(fd.readlines(), 0): req = self.extract_requirement(line) # if the line is not a requirement statement if not req: continue req_path = req if not os.path.isabs(req_path): req_path = os.path.normpath(os.path.join(cwd, req_path)) if not os.path.exists(req_path): logging.warning("Requirement '{0}' could not be resolved: '{1}' does not exist.".format(req, req_path)) if self.flags['cleanup']: self.skip_unresolved_requirement(filename, i) continue # if the requirement is already added to the database, skip it if req_path in self.req_paths: logging.warning("Skipping duplicate requirement '{0}' at '{2}:{3}' [file '{1}'].".format( req, req_path, filename, i+1 # human-recognizable line number )) if self.flags['cleanup']: self.skip_unresolved_requirement(filename, i) continue # store requirements to the global database self.req_parents.append(filename) self.req_paths.append(req_path) self.req_linenos.append(i) # recursion self.parse_requirements(req_path) fd.close() except IOError as err: logging.warning("I/O error: {0}".format(err))
python
def parse_requirements(self, filename): """ Recursively find all the requirements needed storing them in req_parents, req_paths, req_linenos """ cwd = os.path.dirname(filename) try: fd = open(filename, 'r') for i, line in enumerate(fd.readlines(), 0): req = self.extract_requirement(line) # if the line is not a requirement statement if not req: continue req_path = req if not os.path.isabs(req_path): req_path = os.path.normpath(os.path.join(cwd, req_path)) if not os.path.exists(req_path): logging.warning("Requirement '{0}' could not be resolved: '{1}' does not exist.".format(req, req_path)) if self.flags['cleanup']: self.skip_unresolved_requirement(filename, i) continue # if the requirement is already added to the database, skip it if req_path in self.req_paths: logging.warning("Skipping duplicate requirement '{0}' at '{2}:{3}' [file '{1}'].".format( req, req_path, filename, i+1 # human-recognizable line number )) if self.flags['cleanup']: self.skip_unresolved_requirement(filename, i) continue # store requirements to the global database self.req_parents.append(filename) self.req_paths.append(req_path) self.req_linenos.append(i) # recursion self.parse_requirements(req_path) fd.close() except IOError as err: logging.warning("I/O error: {0}".format(err))
[ "def", "parse_requirements", "(", "self", ",", "filename", ")", ":", "cwd", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "try", ":", "fd", "=", "open", "(", "filename", ",", "'r'", ")", "for", "i", ",", "line", "in", "enumerate", "(", "fd", ".", "readlines", "(", ")", ",", "0", ")", ":", "req", "=", "self", ".", "extract_requirement", "(", "line", ")", "# if the line is not a requirement statement", "if", "not", "req", ":", "continue", "req_path", "=", "req", "if", "not", "os", ".", "path", ".", "isabs", "(", "req_path", ")", ":", "req_path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "cwd", ",", "req_path", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "req_path", ")", ":", "logging", ".", "warning", "(", "\"Requirement '{0}' could not be resolved: '{1}' does not exist.\"", ".", "format", "(", "req", ",", "req_path", ")", ")", "if", "self", ".", "flags", "[", "'cleanup'", "]", ":", "self", ".", "skip_unresolved_requirement", "(", "filename", ",", "i", ")", "continue", "# if the requirement is already added to the database, skip it", "if", "req_path", "in", "self", ".", "req_paths", ":", "logging", ".", "warning", "(", "\"Skipping duplicate requirement '{0}' at '{2}:{3}' [file '{1}'].\"", ".", "format", "(", "req", ",", "req_path", ",", "filename", ",", "i", "+", "1", "# human-recognizable line number", ")", ")", "if", "self", ".", "flags", "[", "'cleanup'", "]", ":", "self", ".", "skip_unresolved_requirement", "(", "filename", ",", "i", ")", "continue", "# store requirements to the global database", "self", ".", "req_parents", ".", "append", "(", "filename", ")", "self", ".", "req_paths", ".", "append", "(", "req_path", ")", "self", ".", "req_linenos", ".", "append", "(", "i", ")", "# recursion", "self", ".", "parse_requirements", "(", "req_path", ")", "fd", ".", "close", "(", ")", "except", "IOError", "as", "err", ":", "logging", ".", "warning", "(", "\"I/O error: {0}\"", ".", "format", "(", "err", ")", ")" ]
Recursively find all the requirements needed storing them in req_parents, req_paths, req_linenos
[ "Recursively", "find", "all", "the", "requirements", "needed", "storing", "them", "in", "req_parents", "req_paths", "req_linenos" ]
301b907b32ef9bbdb7099657100fbd3829c3ecc8
https://github.com/honsiorovskyi/codeharvester/blob/301b907b32ef9bbdb7099657100fbd3829c3ecc8/src/codeharvester/harvester.py#L56-L105
247,883
honsiorovskyi/codeharvester
src/codeharvester/harvester.py
Harvester.replace_requirements
def replace_requirements(self, infilename, outfile_initial=None): """ Recursively replaces the requirements in the files with the content of the requirements. Returns final temporary file opened for reading. """ infile = open(infilename, 'r') # extract the requirements for this file that were not skipped from the global database _indexes = tuple(z[0] for z in filter(lambda x: x[1] == infilename, enumerate(self.req_parents))) req_paths = tuple(z[1] for z in filter(lambda x: x[0] in _indexes, enumerate(self.req_paths))) req_linenos = tuple(z[1] for z in filter(lambda x: x[0] in _indexes, enumerate(self.req_linenos))) if outfile_initial: outfile = outfile_initial else: outfile = tempfile.TemporaryFile('w+') # write the input file to the output, replacing # the requirement statements with the requirements themselves for i, line in enumerate(infile.readlines()): if i in req_linenos: req_path = req_paths[req_linenos.index(i)] # skip unresolved requirement if not req_path: continue # recursion req_file = self.replace_requirements(req_path) # insert something at cursor position self.insert_requirement(outfile, req_file, req_path) req_file.close() else: outfile.write(line) infile.close() if not outfile_initial: outfile.seek(0) return outfile
python
def replace_requirements(self, infilename, outfile_initial=None): """ Recursively replaces the requirements in the files with the content of the requirements. Returns final temporary file opened for reading. """ infile = open(infilename, 'r') # extract the requirements for this file that were not skipped from the global database _indexes = tuple(z[0] for z in filter(lambda x: x[1] == infilename, enumerate(self.req_parents))) req_paths = tuple(z[1] for z in filter(lambda x: x[0] in _indexes, enumerate(self.req_paths))) req_linenos = tuple(z[1] for z in filter(lambda x: x[0] in _indexes, enumerate(self.req_linenos))) if outfile_initial: outfile = outfile_initial else: outfile = tempfile.TemporaryFile('w+') # write the input file to the output, replacing # the requirement statements with the requirements themselves for i, line in enumerate(infile.readlines()): if i in req_linenos: req_path = req_paths[req_linenos.index(i)] # skip unresolved requirement if not req_path: continue # recursion req_file = self.replace_requirements(req_path) # insert something at cursor position self.insert_requirement(outfile, req_file, req_path) req_file.close() else: outfile.write(line) infile.close() if not outfile_initial: outfile.seek(0) return outfile
[ "def", "replace_requirements", "(", "self", ",", "infilename", ",", "outfile_initial", "=", "None", ")", ":", "infile", "=", "open", "(", "infilename", ",", "'r'", ")", "# extract the requirements for this file that were not skipped from the global database", "_indexes", "=", "tuple", "(", "z", "[", "0", "]", "for", "z", "in", "filter", "(", "lambda", "x", ":", "x", "[", "1", "]", "==", "infilename", ",", "enumerate", "(", "self", ".", "req_parents", ")", ")", ")", "req_paths", "=", "tuple", "(", "z", "[", "1", "]", "for", "z", "in", "filter", "(", "lambda", "x", ":", "x", "[", "0", "]", "in", "_indexes", ",", "enumerate", "(", "self", ".", "req_paths", ")", ")", ")", "req_linenos", "=", "tuple", "(", "z", "[", "1", "]", "for", "z", "in", "filter", "(", "lambda", "x", ":", "x", "[", "0", "]", "in", "_indexes", ",", "enumerate", "(", "self", ".", "req_linenos", ")", ")", ")", "if", "outfile_initial", ":", "outfile", "=", "outfile_initial", "else", ":", "outfile", "=", "tempfile", ".", "TemporaryFile", "(", "'w+'", ")", "# write the input file to the output, replacing", "# the requirement statements with the requirements themselves", "for", "i", ",", "line", "in", "enumerate", "(", "infile", ".", "readlines", "(", ")", ")", ":", "if", "i", "in", "req_linenos", ":", "req_path", "=", "req_paths", "[", "req_linenos", ".", "index", "(", "i", ")", "]", "# skip unresolved requirement", "if", "not", "req_path", ":", "continue", "# recursion", "req_file", "=", "self", ".", "replace_requirements", "(", "req_path", ")", "# insert something at cursor position", "self", ".", "insert_requirement", "(", "outfile", ",", "req_file", ",", "req_path", ")", "req_file", ".", "close", "(", ")", "else", ":", "outfile", ".", "write", "(", "line", ")", "infile", ".", "close", "(", ")", "if", "not", "outfile_initial", ":", "outfile", ".", "seek", "(", "0", ")", "return", "outfile" ]
Recursively replaces the requirements in the files with the content of the requirements. Returns final temporary file opened for reading.
[ "Recursively", "replaces", "the", "requirements", "in", "the", "files", "with", "the", "content", "of", "the", "requirements", ".", "Returns", "final", "temporary", "file", "opened", "for", "reading", "." ]
301b907b32ef9bbdb7099657100fbd3829c3ecc8
https://github.com/honsiorovskyi/codeharvester/blob/301b907b32ef9bbdb7099657100fbd3829c3ecc8/src/codeharvester/harvester.py#L107-L150
247,884
synw/goerr
goerr/messages.py
Msg.fatal
def fatal(self, i: int=None) -> str: """ Returns a fatal error message """ head = "[" + colors.red("\033[1mfatal error") + "]" if i is not None: head = str(i) + " " + head return head
python
def fatal(self, i: int=None) -> str: """ Returns a fatal error message """ head = "[" + colors.red("\033[1mfatal error") + "]" if i is not None: head = str(i) + " " + head return head
[ "def", "fatal", "(", "self", ",", "i", ":", "int", "=", "None", ")", "->", "str", ":", "head", "=", "\"[\"", "+", "colors", ".", "red", "(", "\"\\033[1mfatal error\"", ")", "+", "\"]\"", "if", "i", "is", "not", "None", ":", "head", "=", "str", "(", "i", ")", "+", "\" \"", "+", "head", "return", "head" ]
Returns a fatal error message
[ "Returns", "a", "fatal", "error", "message" ]
08b3809d6715bffe26899a769d96fa5de8573faf
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/messages.py#L9-L16
247,885
synw/goerr
goerr/messages.py
Msg.error
def error(self, i: int=None) -> str: """ Returns an error message """ head = "[" + colors.red("error") + "]" if i is not None: head = str(i) + " " + head return head
python
def error(self, i: int=None) -> str: """ Returns an error message """ head = "[" + colors.red("error") + "]" if i is not None: head = str(i) + " " + head return head
[ "def", "error", "(", "self", ",", "i", ":", "int", "=", "None", ")", "->", "str", ":", "head", "=", "\"[\"", "+", "colors", ".", "red", "(", "\"error\"", ")", "+", "\"]\"", "if", "i", "is", "not", "None", ":", "head", "=", "str", "(", "i", ")", "+", "\" \"", "+", "head", "return", "head" ]
Returns an error message
[ "Returns", "an", "error", "message" ]
08b3809d6715bffe26899a769d96fa5de8573faf
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/messages.py#L18-L25
247,886
synw/goerr
goerr/messages.py
Msg.warning
def warning(self, i: int=None) -> str: """ Returns a warning message """ head = "[" + colors.purple("\033[1mwarning") + "]" if i is not None: head = str(i) + " " + head return head
python
def warning(self, i: int=None) -> str: """ Returns a warning message """ head = "[" + colors.purple("\033[1mwarning") + "]" if i is not None: head = str(i) + " " + head return head
[ "def", "warning", "(", "self", ",", "i", ":", "int", "=", "None", ")", "->", "str", ":", "head", "=", "\"[\"", "+", "colors", ".", "purple", "(", "\"\\033[1mwarning\"", ")", "+", "\"]\"", "if", "i", "is", "not", "None", ":", "head", "=", "str", "(", "i", ")", "+", "\" \"", "+", "head", "return", "head" ]
Returns a warning message
[ "Returns", "a", "warning", "message" ]
08b3809d6715bffe26899a769d96fa5de8573faf
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/messages.py#L27-L34
247,887
synw/goerr
goerr/messages.py
Msg.info
def info(self, i: int=None) -> str: """ Returns an info message """ head = "[" + colors.blue("info") + "]" if i is not None: head = str(i) + " " + head return head
python
def info(self, i: int=None) -> str: """ Returns an info message """ head = "[" + colors.blue("info") + "]" if i is not None: head = str(i) + " " + head return head
[ "def", "info", "(", "self", ",", "i", ":", "int", "=", "None", ")", "->", "str", ":", "head", "=", "\"[\"", "+", "colors", ".", "blue", "(", "\"info\"", ")", "+", "\"]\"", "if", "i", "is", "not", "None", ":", "head", "=", "str", "(", "i", ")", "+", "\" \"", "+", "head", "return", "head" ]
Returns an info message
[ "Returns", "an", "info", "message" ]
08b3809d6715bffe26899a769d96fa5de8573faf
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/messages.py#L36-L43
247,888
synw/goerr
goerr/messages.py
Msg.via
def via(self, i: int=None) -> str: """ Returns an via message """ head = "[" + colors.green("via") + "]" if i is not None: head = str(i) + " " + head return head
python
def via(self, i: int=None) -> str: """ Returns an via message """ head = "[" + colors.green("via") + "]" if i is not None: head = str(i) + " " + head return head
[ "def", "via", "(", "self", ",", "i", ":", "int", "=", "None", ")", "->", "str", ":", "head", "=", "\"[\"", "+", "colors", ".", "green", "(", "\"via\"", ")", "+", "\"]\"", "if", "i", "is", "not", "None", ":", "head", "=", "str", "(", "i", ")", "+", "\" \"", "+", "head", "return", "head" ]
Returns an via message
[ "Returns", "an", "via", "message" ]
08b3809d6715bffe26899a769d96fa5de8573faf
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/messages.py#L45-L52
247,889
synw/goerr
goerr/messages.py
Msg.debug
def debug(self, i: int=None) -> str: """ Returns a debug message """ head = "[" + colors.yellow("debug") + "]" if i is not None: head = str(i) + " " + head return head
python
def debug(self, i: int=None) -> str: """ Returns a debug message """ head = "[" + colors.yellow("debug") + "]" if i is not None: head = str(i) + " " + head return head
[ "def", "debug", "(", "self", ",", "i", ":", "int", "=", "None", ")", "->", "str", ":", "head", "=", "\"[\"", "+", "colors", ".", "yellow", "(", "\"debug\"", ")", "+", "\"]\"", "if", "i", "is", "not", "None", ":", "head", "=", "str", "(", "i", ")", "+", "\" \"", "+", "head", "return", "head" ]
Returns a debug message
[ "Returns", "a", "debug", "message" ]
08b3809d6715bffe26899a769d96fa5de8573faf
https://github.com/synw/goerr/blob/08b3809d6715bffe26899a769d96fa5de8573faf/goerr/messages.py#L54-L61
247,890
malthe/pop
src/pop/machine.py
MachineAgent.scan
def scan(self): """Analyze state and queue tasks.""" log.debug("scanning machine: %s..." % self.name) deployed = set() services = yield self.client.get_children(self.path + "/services") for name in services: log.debug("checking service: '%s'..." % name) try: value, metadata = yield self.client.get( self.path + "/services/" + name + "/machines" ) except NoNodeException: log.warn( "missing machines declaration for service: %s." % name ) machines = [] else: machines = json.loads(value) if machines: log.debug("machines: %s." % ", ".join(machines)) if self.name in machines: deployed.add(name) else: log.debug("service not configured for any machine.") count = len(deployed) log.debug("found %d service(s) configured for this machine." % count) running = yield self.client.get_children( self.path + "/machines/" + self.name ) self.stopped = deployed - set(running) if self.stopped: log.debug("services not running: %s." % ", ".join( map(repr, self.stopped))) elif running: log.debug("all services are up.")
python
def scan(self): """Analyze state and queue tasks.""" log.debug("scanning machine: %s..." % self.name) deployed = set() services = yield self.client.get_children(self.path + "/services") for name in services: log.debug("checking service: '%s'..." % name) try: value, metadata = yield self.client.get( self.path + "/services/" + name + "/machines" ) except NoNodeException: log.warn( "missing machines declaration for service: %s." % name ) machines = [] else: machines = json.loads(value) if machines: log.debug("machines: %s." % ", ".join(machines)) if self.name in machines: deployed.add(name) else: log.debug("service not configured for any machine.") count = len(deployed) log.debug("found %d service(s) configured for this machine." % count) running = yield self.client.get_children( self.path + "/machines/" + self.name ) self.stopped = deployed - set(running) if self.stopped: log.debug("services not running: %s." % ", ".join( map(repr, self.stopped))) elif running: log.debug("all services are up.")
[ "def", "scan", "(", "self", ")", ":", "log", ".", "debug", "(", "\"scanning machine: %s...\"", "%", "self", ".", "name", ")", "deployed", "=", "set", "(", ")", "services", "=", "yield", "self", ".", "client", ".", "get_children", "(", "self", ".", "path", "+", "\"/services\"", ")", "for", "name", "in", "services", ":", "log", ".", "debug", "(", "\"checking service: '%s'...\"", "%", "name", ")", "try", ":", "value", ",", "metadata", "=", "yield", "self", ".", "client", ".", "get", "(", "self", ".", "path", "+", "\"/services/\"", "+", "name", "+", "\"/machines\"", ")", "except", "NoNodeException", ":", "log", ".", "warn", "(", "\"missing machines declaration for service: %s.\"", "%", "name", ")", "machines", "=", "[", "]", "else", ":", "machines", "=", "json", ".", "loads", "(", "value", ")", "if", "machines", ":", "log", ".", "debug", "(", "\"machines: %s.\"", "%", "\", \"", ".", "join", "(", "machines", ")", ")", "if", "self", ".", "name", "in", "machines", ":", "deployed", ".", "add", "(", "name", ")", "else", ":", "log", ".", "debug", "(", "\"service not configured for any machine.\"", ")", "count", "=", "len", "(", "deployed", ")", "log", ".", "debug", "(", "\"found %d service(s) configured for this machine.\"", "%", "count", ")", "running", "=", "yield", "self", ".", "client", ".", "get_children", "(", "self", ".", "path", "+", "\"/machines/\"", "+", "self", ".", "name", ")", "self", ".", "stopped", "=", "deployed", "-", "set", "(", "running", ")", "if", "self", ".", "stopped", ":", "log", ".", "debug", "(", "\"services not running: %s.\"", "%", "\", \"", ".", "join", "(", "map", "(", "repr", ",", "self", ".", "stopped", ")", ")", ")", "elif", "running", ":", "log", ".", "debug", "(", "\"all services are up.\"", ")" ]
Analyze state and queue tasks.
[ "Analyze", "state", "and", "queue", "tasks", "." ]
3b58b91b41d8b9bee546eb40dc280a57500b8bed
https://github.com/malthe/pop/blob/3b58b91b41d8b9bee546eb40dc280a57500b8bed/src/pop/machine.py#L34-L79
247,891
tmacwill/stellata
stellata/database.py
initialize
def initialize(name='', pool_size=10, host='localhost', password='', port=5432, user=''): """Initialize a new database connection and return the pool object. Saves a reference to that instance in a module-level variable, so applications with only one database can just call this function and not worry about pool objects. """ global pool instance = Pool(name=name, pool_size=pool_size, host=host, password=password, port=port, user=user) pool = instance return instance
python
def initialize(name='', pool_size=10, host='localhost', password='', port=5432, user=''): """Initialize a new database connection and return the pool object. Saves a reference to that instance in a module-level variable, so applications with only one database can just call this function and not worry about pool objects. """ global pool instance = Pool(name=name, pool_size=pool_size, host=host, password=password, port=port, user=user) pool = instance return instance
[ "def", "initialize", "(", "name", "=", "''", ",", "pool_size", "=", "10", ",", "host", "=", "'localhost'", ",", "password", "=", "''", ",", "port", "=", "5432", ",", "user", "=", "''", ")", ":", "global", "pool", "instance", "=", "Pool", "(", "name", "=", "name", ",", "pool_size", "=", "pool_size", ",", "host", "=", "host", ",", "password", "=", "password", ",", "port", "=", "port", ",", "user", "=", "user", ")", "pool", "=", "instance", "return", "instance" ]
Initialize a new database connection and return the pool object. Saves a reference to that instance in a module-level variable, so applications with only one database can just call this function and not worry about pool objects.
[ "Initialize", "a", "new", "database", "connection", "and", "return", "the", "pool", "object", "." ]
9519c170397740eb6faf5d8a96b9a77f0d909b92
https://github.com/tmacwill/stellata/blob/9519c170397740eb6faf5d8a96b9a77f0d909b92/stellata/database.py#L57-L67
247,892
tmacwill/stellata
stellata/database.py
Pool.query
def query(self, sql: str, args: tuple = None): """Execute a SQL query with a return value.""" with self._cursor() as cursor: log.debug('Running SQL: ' + str((sql, args))) cursor.execute(sql, args) return cursor.fetchall()
python
def query(self, sql: str, args: tuple = None): """Execute a SQL query with a return value.""" with self._cursor() as cursor: log.debug('Running SQL: ' + str((sql, args))) cursor.execute(sql, args) return cursor.fetchall()
[ "def", "query", "(", "self", ",", "sql", ":", "str", ",", "args", ":", "tuple", "=", "None", ")", ":", "with", "self", ".", "_cursor", "(", ")", "as", "cursor", ":", "log", ".", "debug", "(", "'Running SQL: '", "+", "str", "(", "(", "sql", ",", "args", ")", ")", ")", "cursor", ".", "execute", "(", "sql", ",", "args", ")", "return", "cursor", ".", "fetchall", "(", ")" ]
Execute a SQL query with a return value.
[ "Execute", "a", "SQL", "query", "with", "a", "return", "value", "." ]
9519c170397740eb6faf5d8a96b9a77f0d909b92
https://github.com/tmacwill/stellata/blob/9519c170397740eb6faf5d8a96b9a77f0d909b92/stellata/database.py#L49-L55
247,893
davisd50/sparc.cache
sparc/cache/sources/csvdata.py
CSVSource.items
def items(self): """Returns a generator of available ICachableItem in the ICachableSource """ for dictreader in self._csv_dictreader_list: for entry in dictreader: item = self.factory() item.key = self.key() item.attributes = entry try: item.validate() except Exception as e: logger.debug("skipping entry due to item validation exception: %s", str(e)) continue logger.debug("found validated item in CSV source, key: %s", str(item.attributes[self.key()])) yield item
python
def items(self): """Returns a generator of available ICachableItem in the ICachableSource """ for dictreader in self._csv_dictreader_list: for entry in dictreader: item = self.factory() item.key = self.key() item.attributes = entry try: item.validate() except Exception as e: logger.debug("skipping entry due to item validation exception: %s", str(e)) continue logger.debug("found validated item in CSV source, key: %s", str(item.attributes[self.key()])) yield item
[ "def", "items", "(", "self", ")", ":", "for", "dictreader", "in", "self", ".", "_csv_dictreader_list", ":", "for", "entry", "in", "dictreader", ":", "item", "=", "self", ".", "factory", "(", ")", "item", ".", "key", "=", "self", ".", "key", "(", ")", "item", ".", "attributes", "=", "entry", "try", ":", "item", ".", "validate", "(", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "\"skipping entry due to item validation exception: %s\"", ",", "str", "(", "e", ")", ")", "continue", "logger", ".", "debug", "(", "\"found validated item in CSV source, key: %s\"", ",", "str", "(", "item", ".", "attributes", "[", "self", ".", "key", "(", ")", "]", ")", ")", "yield", "item" ]
Returns a generator of available ICachableItem in the ICachableSource
[ "Returns", "a", "generator", "of", "available", "ICachableItem", "in", "the", "ICachableSource" ]
f2378aad48c368a53820e97b093ace790d4d4121
https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sources/csvdata.py#L75-L89
247,894
davisd50/sparc.cache
sparc/cache/sources/csvdata.py
CSVSource.first
def first(self): """Returns the first ICachableItem in the ICachableSource""" # we need to create a new object to insure we don't corrupt the generator count csvsource = CSVSource(self.source, self.factory, self.key()) try: item = csvsource.items().next() return item except StopIteration: return None
python
def first(self): """Returns the first ICachableItem in the ICachableSource""" # we need to create a new object to insure we don't corrupt the generator count csvsource = CSVSource(self.source, self.factory, self.key()) try: item = csvsource.items().next() return item except StopIteration: return None
[ "def", "first", "(", "self", ")", ":", "# we need to create a new object to insure we don't corrupt the generator count", "csvsource", "=", "CSVSource", "(", "self", ".", "source", ",", "self", ".", "factory", ",", "self", ".", "key", "(", ")", ")", "try", ":", "item", "=", "csvsource", ".", "items", "(", ")", ".", "next", "(", ")", "return", "item", "except", "StopIteration", ":", "return", "None" ]
Returns the first ICachableItem in the ICachableSource
[ "Returns", "the", "first", "ICachableItem", "in", "the", "ICachableSource" ]
f2378aad48c368a53820e97b093ace790d4d4121
https://github.com/davisd50/sparc.cache/blob/f2378aad48c368a53820e97b093ace790d4d4121/sparc/cache/sources/csvdata.py#L106-L114
247,895
b3j0f/conf
b3j0f/conf/parser/resolver/registry.py
register
def register(name=None, exprresolver=None, params=None, reg=None): """Register an expression resolver. Can be used such as a decorator. For example all remainding expressions are the same. .. code-block:: python @register('myresolver') def myresolver(**kwargs): pass .. code-block:: python def myresolver(**kwargs): pass register('myresolver', myresolver) .. code-block:: python @register('myresolver') class MyResolver(): def __call__(**kwargs): pass .. code-block:: python class MyResolver(): def __call__(**kwargs): pass register('myresolver', MyResolver) .. code-block:: python class MyResolver(): def __call__(**kwargs): pass register('myresolver', MyResolver()) :param str name: register name to use. Default is the function/class name. :param exprresolver: function able to resolve an expression. :param dict kwargs: parameters of resolver instanciation if exprresolver is a class and this function is used such as a decorator. :param ResolverRegistry reg: registry to use. Default is the global registry . """ def _register(exprresolver, _name=name, _params=params): """Local registration for better use in a decoration context. :param exprresolver: function/class able to resolve an expression. :param str _name: private parameter used to set the name. :param dict _params: private parameter used to set resolver class constructor parameters.""" _exprresolver = exprresolver if isclass(exprresolver): # try to instanciate exprresolver if _params is None: _params = {} _exprresolver = _exprresolver(**_params) if _name is None: _name = getname(exprresolver) reg[_name] = _exprresolver if reg.default is None: reg.default = _name return exprresolver if name is None: name = getname(exprresolver) if reg is None: reg = _RESOLVER_REGISTRY if exprresolver is None: result = _register else: result = name _register(exprresolver) return result
python
def register(name=None, exprresolver=None, params=None, reg=None): """Register an expression resolver. Can be used such as a decorator. For example all remainding expressions are the same. .. code-block:: python @register('myresolver') def myresolver(**kwargs): pass .. code-block:: python def myresolver(**kwargs): pass register('myresolver', myresolver) .. code-block:: python @register('myresolver') class MyResolver(): def __call__(**kwargs): pass .. code-block:: python class MyResolver(): def __call__(**kwargs): pass register('myresolver', MyResolver) .. code-block:: python class MyResolver(): def __call__(**kwargs): pass register('myresolver', MyResolver()) :param str name: register name to use. Default is the function/class name. :param exprresolver: function able to resolve an expression. :param dict kwargs: parameters of resolver instanciation if exprresolver is a class and this function is used such as a decorator. :param ResolverRegistry reg: registry to use. Default is the global registry . """ def _register(exprresolver, _name=name, _params=params): """Local registration for better use in a decoration context. :param exprresolver: function/class able to resolve an expression. :param str _name: private parameter used to set the name. :param dict _params: private parameter used to set resolver class constructor parameters.""" _exprresolver = exprresolver if isclass(exprresolver): # try to instanciate exprresolver if _params is None: _params = {} _exprresolver = _exprresolver(**_params) if _name is None: _name = getname(exprresolver) reg[_name] = _exprresolver if reg.default is None: reg.default = _name return exprresolver if name is None: name = getname(exprresolver) if reg is None: reg = _RESOLVER_REGISTRY if exprresolver is None: result = _register else: result = name _register(exprresolver) return result
[ "def", "register", "(", "name", "=", "None", ",", "exprresolver", "=", "None", ",", "params", "=", "None", ",", "reg", "=", "None", ")", ":", "def", "_register", "(", "exprresolver", ",", "_name", "=", "name", ",", "_params", "=", "params", ")", ":", "\"\"\"Local registration for better use in a decoration context.\n\n :param exprresolver: function/class able to resolve an expression.\n :param str _name: private parameter used to set the name.\n :param dict _params: private parameter used to set resolver class\n constructor parameters.\"\"\"", "_exprresolver", "=", "exprresolver", "if", "isclass", "(", "exprresolver", ")", ":", "# try to instanciate exprresolver", "if", "_params", "is", "None", ":", "_params", "=", "{", "}", "_exprresolver", "=", "_exprresolver", "(", "*", "*", "_params", ")", "if", "_name", "is", "None", ":", "_name", "=", "getname", "(", "exprresolver", ")", "reg", "[", "_name", "]", "=", "_exprresolver", "if", "reg", ".", "default", "is", "None", ":", "reg", ".", "default", "=", "_name", "return", "exprresolver", "if", "name", "is", "None", ":", "name", "=", "getname", "(", "exprresolver", ")", "if", "reg", "is", "None", ":", "reg", "=", "_RESOLVER_REGISTRY", "if", "exprresolver", "is", "None", ":", "result", "=", "_register", "else", ":", "result", "=", "name", "_register", "(", "exprresolver", ")", "return", "result" ]
Register an expression resolver. Can be used such as a decorator. For example all remainding expressions are the same. .. code-block:: python @register('myresolver') def myresolver(**kwargs): pass .. code-block:: python def myresolver(**kwargs): pass register('myresolver', myresolver) .. code-block:: python @register('myresolver') class MyResolver(): def __call__(**kwargs): pass .. code-block:: python class MyResolver(): def __call__(**kwargs): pass register('myresolver', MyResolver) .. code-block:: python class MyResolver(): def __call__(**kwargs): pass register('myresolver', MyResolver()) :param str name: register name to use. Default is the function/class name. :param exprresolver: function able to resolve an expression. :param dict kwargs: parameters of resolver instanciation if exprresolver is a class and this function is used such as a decorator. :param ResolverRegistry reg: registry to use. Default is the global registry .
[ "Register", "an", "expression", "resolver", "." ]
18dd6d5d6560f9b202793739e2330a2181163511
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/resolver/registry.py#L170-L257
247,896
b3j0f/conf
b3j0f/conf/parser/resolver/registry.py
getname
def getname(exprresolver): """Get expression resolver name. Expression resolver name is given by the attribute __resolver__. If not exist, then the it is given by the attribute __name__. Otherwise, given by the __class__.__name__ attribute. :raises: TypeError if exprresolver is not callable.""" result = None if not callable(exprresolver): raise TypeError('Expression resolver must be a callable object.') result = getattr( exprresolver, __RESOLVER__, getattr( exprresolver, '__name__', getattr( exprresolver.__class__, '__name__' ) ) ) return result
python
def getname(exprresolver): """Get expression resolver name. Expression resolver name is given by the attribute __resolver__. If not exist, then the it is given by the attribute __name__. Otherwise, given by the __class__.__name__ attribute. :raises: TypeError if exprresolver is not callable.""" result = None if not callable(exprresolver): raise TypeError('Expression resolver must be a callable object.') result = getattr( exprresolver, __RESOLVER__, getattr( exprresolver, '__name__', getattr( exprresolver.__class__, '__name__' ) ) ) return result
[ "def", "getname", "(", "exprresolver", ")", ":", "result", "=", "None", "if", "not", "callable", "(", "exprresolver", ")", ":", "raise", "TypeError", "(", "'Expression resolver must be a callable object.'", ")", "result", "=", "getattr", "(", "exprresolver", ",", "__RESOLVER__", ",", "getattr", "(", "exprresolver", ",", "'__name__'", ",", "getattr", "(", "exprresolver", ".", "__class__", ",", "'__name__'", ")", ")", ")", "return", "result" ]
Get expression resolver name. Expression resolver name is given by the attribute __resolver__. If not exist, then the it is given by the attribute __name__. Otherwise, given by the __class__.__name__ attribute. :raises: TypeError if exprresolver is not callable.
[ "Get", "expression", "resolver", "name", "." ]
18dd6d5d6560f9b202793739e2330a2181163511
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/resolver/registry.py#L317-L339
247,897
b3j0f/conf
b3j0f/conf/parser/resolver/registry.py
ResolverRegistry.default
def default(self, value): """Change of resolver name. :param value: new default value to use. :type value: str or callable :raises: KeyError if value is a string not already registered.""" if value is None: if self: value = list(self.keys())[0] elif not isinstance(value, string_types): value = register(exprresolver=value, reg=self) elif value not in self: raise KeyError( '{0} not registered in {1}'.format(value, self) ) self._default = value
python
def default(self, value): """Change of resolver name. :param value: new default value to use. :type value: str or callable :raises: KeyError if value is a string not already registered.""" if value is None: if self: value = list(self.keys())[0] elif not isinstance(value, string_types): value = register(exprresolver=value, reg=self) elif value not in self: raise KeyError( '{0} not registered in {1}'.format(value, self) ) self._default = value
[ "def", "default", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "if", "self", ":", "value", "=", "list", "(", "self", ".", "keys", "(", ")", ")", "[", "0", "]", "elif", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "value", "=", "register", "(", "exprresolver", "=", "value", ",", "reg", "=", "self", ")", "elif", "value", "not", "in", "self", ":", "raise", "KeyError", "(", "'{0} not registered in {1}'", ".", "format", "(", "value", ",", "self", ")", ")", "self", ".", "_default", "=", "value" ]
Change of resolver name. :param value: new default value to use. :type value: str or callable :raises: KeyError if value is a string not already registered.
[ "Change", "of", "resolver", "name", "." ]
18dd6d5d6560f9b202793739e2330a2181163511
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/resolver/registry.py#L112-L131
247,898
django-stars/plankton
plankton/wkhtmltopdf/utils.py
wkhtmltopdf_args_mapping
def wkhtmltopdf_args_mapping(data): """ fix our names to wkhtmltopdf's args """ mapping = { 'cookies': 'cookie', 'custom-headers': 'custom-header', 'run-scripts': 'run-script' } return {mapping.get(k, k): v for k, v in data.items()}
python
def wkhtmltopdf_args_mapping(data): """ fix our names to wkhtmltopdf's args """ mapping = { 'cookies': 'cookie', 'custom-headers': 'custom-header', 'run-scripts': 'run-script' } return {mapping.get(k, k): v for k, v in data.items()}
[ "def", "wkhtmltopdf_args_mapping", "(", "data", ")", ":", "mapping", "=", "{", "'cookies'", ":", "'cookie'", ",", "'custom-headers'", ":", "'custom-header'", ",", "'run-scripts'", ":", "'run-script'", "}", "return", "{", "mapping", ".", "get", "(", "k", ",", "k", ")", ":", "v", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", "}" ]
fix our names to wkhtmltopdf's args
[ "fix", "our", "names", "to", "wkhtmltopdf", "s", "args" ]
83a672d8d40f8bea51dc772aa084139c409d47e4
https://github.com/django-stars/plankton/blob/83a672d8d40f8bea51dc772aa084139c409d47e4/plankton/wkhtmltopdf/utils.py#L18-L28
247,899
usc-isi-i2/dig-dictionary-extractor
digDictionaryExtractor/name_dictionary_extractor.py
get_name_dictionary_extractor
def get_name_dictionary_extractor(name_trie): """Method for creating default name dictionary extractor""" return DictionaryExtractor()\ .set_trie(name_trie)\ .set_pre_filter(VALID_TOKEN_RE.match)\ .set_pre_process(lambda x: x.lower())\ .set_metadata({'extractor': 'dig_name_dictionary_extractor'})
python
def get_name_dictionary_extractor(name_trie): """Method for creating default name dictionary extractor""" return DictionaryExtractor()\ .set_trie(name_trie)\ .set_pre_filter(VALID_TOKEN_RE.match)\ .set_pre_process(lambda x: x.lower())\ .set_metadata({'extractor': 'dig_name_dictionary_extractor'})
[ "def", "get_name_dictionary_extractor", "(", "name_trie", ")", ":", "return", "DictionaryExtractor", "(", ")", ".", "set_trie", "(", "name_trie", ")", ".", "set_pre_filter", "(", "VALID_TOKEN_RE", ".", "match", ")", ".", "set_pre_process", "(", "lambda", "x", ":", "x", ".", "lower", "(", ")", ")", ".", "set_metadata", "(", "{", "'extractor'", ":", "'dig_name_dictionary_extractor'", "}", ")" ]
Method for creating default name dictionary extractor
[ "Method", "for", "creating", "default", "name", "dictionary", "extractor" ]
1fe4f6c121fd09a8f194ccd419284d3c3760195d
https://github.com/usc-isi-i2/dig-dictionary-extractor/blob/1fe4f6c121fd09a8f194ccd419284d3c3760195d/digDictionaryExtractor/name_dictionary_extractor.py#L11-L18