repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
rmed/pyemtmad | pyemtmad/util.py | check_result | def check_result(data, key=''):
"""Check the result of an API response.
Ideally, this should be done by checking that the value of the ``resultCode``
attribute is 0, but there are endpoints that simply do not follow this rule.
Args:
data (dict): Response obtained from the API endpoint.
key (string): Key to check for existence in the dict.
Returns:
bool: True if result was correct, False otherwise.
"""
if not isinstance(data, dict):
return False
if key:
if key in data:
return True
return False
if 'resultCode' in data.keys():
# OpenBus
return True if data.get('resultCode', -1) == 0 else False
elif 'code' in data.keys():
# Parking
return True if data.get('code', -1) == 0 else False
return False | python | def check_result(data, key=''):
"""Check the result of an API response.
Ideally, this should be done by checking that the value of the ``resultCode``
attribute is 0, but there are endpoints that simply do not follow this rule.
Args:
data (dict): Response obtained from the API endpoint.
key (string): Key to check for existence in the dict.
Returns:
bool: True if result was correct, False otherwise.
"""
if not isinstance(data, dict):
return False
if key:
if key in data:
return True
return False
if 'resultCode' in data.keys():
# OpenBus
return True if data.get('resultCode', -1) == 0 else False
elif 'code' in data.keys():
# Parking
return True if data.get('code', -1) == 0 else False
return False | [
"def",
"check_result",
"(",
"data",
",",
"key",
"=",
"''",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"return",
"False",
"if",
"key",
":",
"if",
"key",
"in",
"data",
":",
"return",
"True",
"return",
"False",
"if",
"'re... | Check the result of an API response.
Ideally, this should be done by checking that the value of the ``resultCode``
attribute is 0, but there are endpoints that simply do not follow this rule.
Args:
data (dict): Response obtained from the API endpoint.
key (string): Key to check for existence in the dict.
Returns:
bool: True if result was correct, False otherwise. | [
"Check",
"the",
"result",
"of",
"an",
"API",
"response",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/util.py#L39-L69 |
rmed/pyemtmad | pyemtmad/util.py | datetime_string | def datetime_string(day, month, year, hour, minute):
"""Build a date string using the provided day, month, year numbers.
Automatically adds a leading zero to ``day`` and ``month`` if they only have
one digit.
Args:
day (int): Day number.
month(int): Month number.
year(int): Year number.
hour (int): Hour of the day in 24h format.
minute (int): Minute of the hour.
Returns:
str: Date in the format *YYYY-MM-DDThh:mm:ss*.
"""
# Overflow
if hour < 0 or hour > 23: hour = 0
if minute < 0 or minute > 60: minute = 0
return '%d-%02d-%02dT%02d:%02d:00' % (year, month, day, hour, minute) | python | def datetime_string(day, month, year, hour, minute):
"""Build a date string using the provided day, month, year numbers.
Automatically adds a leading zero to ``day`` and ``month`` if they only have
one digit.
Args:
day (int): Day number.
month(int): Month number.
year(int): Year number.
hour (int): Hour of the day in 24h format.
minute (int): Minute of the hour.
Returns:
str: Date in the format *YYYY-MM-DDThh:mm:ss*.
"""
# Overflow
if hour < 0 or hour > 23: hour = 0
if minute < 0 or minute > 60: minute = 0
return '%d-%02d-%02dT%02d:%02d:00' % (year, month, day, hour, minute) | [
"def",
"datetime_string",
"(",
"day",
",",
"month",
",",
"year",
",",
"hour",
",",
"minute",
")",
":",
"# Overflow",
"if",
"hour",
"<",
"0",
"or",
"hour",
">",
"23",
":",
"hour",
"=",
"0",
"if",
"minute",
"<",
"0",
"or",
"minute",
">",
"60",
":",... | Build a date string using the provided day, month, year numbers.
Automatically adds a leading zero to ``day`` and ``month`` if they only have
one digit.
Args:
day (int): Day number.
month(int): Month number.
year(int): Year number.
hour (int): Hour of the day in 24h format.
minute (int): Minute of the hour.
Returns:
str: Date in the format *YYYY-MM-DDThh:mm:ss*. | [
"Build",
"a",
"date",
"string",
"using",
"the",
"provided",
"day",
"month",
"year",
"numbers",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/util.py#L87-L107 |
rmed/pyemtmad | pyemtmad/util.py | ints_to_string | def ints_to_string(ints):
"""Convert a list of integers to a *|* separated string.
Args:
ints (list[int]|int): List of integer items to convert or single
integer to convert.
Returns:
str: Formatted string
"""
if not isinstance(ints, list):
return six.u(str(ints))
return '|'.join(six.u(str(l)) for l in ints) | python | def ints_to_string(ints):
"""Convert a list of integers to a *|* separated string.
Args:
ints (list[int]|int): List of integer items to convert or single
integer to convert.
Returns:
str: Formatted string
"""
if not isinstance(ints, list):
return six.u(str(ints))
return '|'.join(six.u(str(l)) for l in ints) | [
"def",
"ints_to_string",
"(",
"ints",
")",
":",
"if",
"not",
"isinstance",
"(",
"ints",
",",
"list",
")",
":",
"return",
"six",
".",
"u",
"(",
"str",
"(",
"ints",
")",
")",
"return",
"'|'",
".",
"join",
"(",
"six",
".",
"u",
"(",
"str",
"(",
"l... | Convert a list of integers to a *|* separated string.
Args:
ints (list[int]|int): List of integer items to convert or single
integer to convert.
Returns:
str: Formatted string | [
"Convert",
"a",
"list",
"of",
"integers",
"to",
"a",
"*",
"|",
"*",
"separated",
"string",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/util.py#L123-L136 |
rmed/pyemtmad | pyemtmad/util.py | response_list | def response_list(data, key):
"""Obtain the relevant response data in a list.
If the response does not already contain the result in a list, a new one
will be created to ease iteration in the parser methods.
Args:
data (dict): API response.
key (str): Attribute of the response that contains the result values.
Returns:
List of response items (usually dict) or None if the key is not present.
"""
if key not in data:
return None
if isinstance(data[key], list):
return data[key]
else:
return [data[key],] | python | def response_list(data, key):
"""Obtain the relevant response data in a list.
If the response does not already contain the result in a list, a new one
will be created to ease iteration in the parser methods.
Args:
data (dict): API response.
key (str): Attribute of the response that contains the result values.
Returns:
List of response items (usually dict) or None if the key is not present.
"""
if key not in data:
return None
if isinstance(data[key], list):
return data[key]
else:
return [data[key],] | [
"def",
"response_list",
"(",
"data",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"data",
":",
"return",
"None",
"if",
"isinstance",
"(",
"data",
"[",
"key",
"]",
",",
"list",
")",
":",
"return",
"data",
"[",
"key",
"]",
"else",
":",
"return",
... | Obtain the relevant response data in a list.
If the response does not already contain the result in a list, a new one
will be created to ease iteration in the parser methods.
Args:
data (dict): API response.
key (str): Attribute of the response that contains the result values.
Returns:
List of response items (usually dict) or None if the key is not present. | [
"Obtain",
"the",
"relevant",
"response",
"data",
"in",
"a",
"list",
"."
] | train | https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/util.py#L154-L174 |
pudo/jsongraph | jsongraph/graph.py | Graph.base_uri | def base_uri(self):
""" Resolution base for JSON schema. Also used as the default
graph ID for RDF. """
if self._base_uri is None:
if self._resolver is not None:
self._base_uri = self.resolver.resolution_scope
else:
self._base_uri = 'http://pudo.github.io/jsongraph'
return URIRef(self._base_uri) | python | def base_uri(self):
""" Resolution base for JSON schema. Also used as the default
graph ID for RDF. """
if self._base_uri is None:
if self._resolver is not None:
self._base_uri = self.resolver.resolution_scope
else:
self._base_uri = 'http://pudo.github.io/jsongraph'
return URIRef(self._base_uri) | [
"def",
"base_uri",
"(",
"self",
")",
":",
"if",
"self",
".",
"_base_uri",
"is",
"None",
":",
"if",
"self",
".",
"_resolver",
"is",
"not",
"None",
":",
"self",
".",
"_base_uri",
"=",
"self",
".",
"resolver",
".",
"resolution_scope",
"else",
":",
"self",... | Resolution base for JSON schema. Also used as the default
graph ID for RDF. | [
"Resolution",
"base",
"for",
"JSON",
"schema",
".",
"Also",
"used",
"as",
"the",
"default",
"graph",
"ID",
"for",
"RDF",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L39-L47 |
pudo/jsongraph | jsongraph/graph.py | Graph.resolver | def resolver(self):
""" Resolver for JSON Schema references. This can be based around a
file or HTTP-based resolution base URI. """
if self._resolver is None:
self._resolver = RefResolver(self.base_uri, {})
# if self.base_uri not in self._resolver.store:
# self._resolver.store[self.base_uri] = self.config
return self._resolver | python | def resolver(self):
""" Resolver for JSON Schema references. This can be based around a
file or HTTP-based resolution base URI. """
if self._resolver is None:
self._resolver = RefResolver(self.base_uri, {})
# if self.base_uri not in self._resolver.store:
# self._resolver.store[self.base_uri] = self.config
return self._resolver | [
"def",
"resolver",
"(",
"self",
")",
":",
"if",
"self",
".",
"_resolver",
"is",
"None",
":",
"self",
".",
"_resolver",
"=",
"RefResolver",
"(",
"self",
".",
"base_uri",
",",
"{",
"}",
")",
"# if self.base_uri not in self._resolver.store:",
"# self._resolver.s... | Resolver for JSON Schema references. This can be based around a
file or HTTP-based resolution base URI. | [
"Resolver",
"for",
"JSON",
"Schema",
"references",
".",
"This",
"can",
"be",
"based",
"around",
"a",
"file",
"or",
"HTTP",
"-",
"based",
"resolution",
"base",
"URI",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L50-L57 |
pudo/jsongraph | jsongraph/graph.py | Graph.store | def store(self):
""" Backend storage for RDF data. Either an in-memory store, or an
external triple store controlled via SPARQL. """
if self._store is None:
config = self.config.get('store', {})
if 'query' in config and 'update' in config:
self._store = sparql_store(config.get('query'),
config.get('update'))
else:
self._store = plugin.get('IOMemory', Store)()
log.debug('Created store: %r', self._store)
return self._store | python | def store(self):
""" Backend storage for RDF data. Either an in-memory store, or an
external triple store controlled via SPARQL. """
if self._store is None:
config = self.config.get('store', {})
if 'query' in config and 'update' in config:
self._store = sparql_store(config.get('query'),
config.get('update'))
else:
self._store = plugin.get('IOMemory', Store)()
log.debug('Created store: %r', self._store)
return self._store | [
"def",
"store",
"(",
"self",
")",
":",
"if",
"self",
".",
"_store",
"is",
"None",
":",
"config",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'store'",
",",
"{",
"}",
")",
"if",
"'query'",
"in",
"config",
"and",
"'update'",
"in",
"config",
":",
... | Backend storage for RDF data. Either an in-memory store, or an
external triple store controlled via SPARQL. | [
"Backend",
"storage",
"for",
"RDF",
"data",
".",
"Either",
"an",
"in",
"-",
"memory",
"store",
"or",
"an",
"external",
"triple",
"store",
"controlled",
"via",
"SPARQL",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L60-L71 |
pudo/jsongraph | jsongraph/graph.py | Graph.graph | def graph(self):
""" A conjunctive graph of all statements in the current instance. """
if not hasattr(self, '_graph') or self._graph is None:
self._graph = ConjunctiveGraph(store=self.store,
identifier=self.base_uri)
return self._graph | python | def graph(self):
""" A conjunctive graph of all statements in the current instance. """
if not hasattr(self, '_graph') or self._graph is None:
self._graph = ConjunctiveGraph(store=self.store,
identifier=self.base_uri)
return self._graph | [
"def",
"graph",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_graph'",
")",
"or",
"self",
".",
"_graph",
"is",
"None",
":",
"self",
".",
"_graph",
"=",
"ConjunctiveGraph",
"(",
"store",
"=",
"self",
".",
"store",
",",
"identifie... | A conjunctive graph of all statements in the current instance. | [
"A",
"conjunctive",
"graph",
"of",
"all",
"statements",
"in",
"the",
"current",
"instance",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L74-L79 |
pudo/jsongraph | jsongraph/graph.py | Graph.buffered | def buffered(self):
""" Whether write operations should be buffered, i.e. run against a
local graph before being stored to the main data store. """
if 'buffered' not in self.config:
return not isinstance(self.store, (Memory, IOMemory))
return self.config.get('buffered') | python | def buffered(self):
""" Whether write operations should be buffered, i.e. run against a
local graph before being stored to the main data store. """
if 'buffered' not in self.config:
return not isinstance(self.store, (Memory, IOMemory))
return self.config.get('buffered') | [
"def",
"buffered",
"(",
"self",
")",
":",
"if",
"'buffered'",
"not",
"in",
"self",
".",
"config",
":",
"return",
"not",
"isinstance",
"(",
"self",
".",
"store",
",",
"(",
"Memory",
",",
"IOMemory",
")",
")",
"return",
"self",
".",
"config",
".",
"get... | Whether write operations should be buffered, i.e. run against a
local graph before being stored to the main data store. | [
"Whether",
"write",
"operations",
"should",
"be",
"buffered",
"i",
".",
"e",
".",
"run",
"against",
"a",
"local",
"graph",
"before",
"being",
"stored",
"to",
"the",
"main",
"data",
"store",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L82-L87 |
pudo/jsongraph | jsongraph/graph.py | Graph.context | def context(self, identifier=None, meta=None):
""" Get or create a context, with the given identifier and/or
provenance meta data. A context can be used to add, update or delete
objects in the store. """
return Context(self, identifier=identifier, meta=meta) | python | def context(self, identifier=None, meta=None):
""" Get or create a context, with the given identifier and/or
provenance meta data. A context can be used to add, update or delete
objects in the store. """
return Context(self, identifier=identifier, meta=meta) | [
"def",
"context",
"(",
"self",
",",
"identifier",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"return",
"Context",
"(",
"self",
",",
"identifier",
"=",
"identifier",
",",
"meta",
"=",
"meta",
")"
] | Get or create a context, with the given identifier and/or
provenance meta data. A context can be used to add, update or delete
objects in the store. | [
"Get",
"or",
"create",
"a",
"context",
"with",
"the",
"given",
"identifier",
"and",
"/",
"or",
"provenance",
"meta",
"data",
".",
"A",
"context",
"can",
"be",
"used",
"to",
"add",
"update",
"or",
"delete",
"objects",
"in",
"the",
"store",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L89-L93 |
pudo/jsongraph | jsongraph/graph.py | Graph.register | def register(self, alias, uri):
""" Register a new schema URI under a given name. """
# TODO: do we want to constrain the valid alias names.
if isinstance(uri, dict):
id = uri.get('id', alias)
self.resolver.store[id] = uri
uri = id
self.aliases[alias] = uri | python | def register(self, alias, uri):
""" Register a new schema URI under a given name. """
# TODO: do we want to constrain the valid alias names.
if isinstance(uri, dict):
id = uri.get('id', alias)
self.resolver.store[id] = uri
uri = id
self.aliases[alias] = uri | [
"def",
"register",
"(",
"self",
",",
"alias",
",",
"uri",
")",
":",
"# TODO: do we want to constrain the valid alias names.",
"if",
"isinstance",
"(",
"uri",
",",
"dict",
")",
":",
"id",
"=",
"uri",
".",
"get",
"(",
"'id'",
",",
"alias",
")",
"self",
".",
... | Register a new schema URI under a given name. | [
"Register",
"a",
"new",
"schema",
"URI",
"under",
"a",
"given",
"name",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L95-L102 |
pudo/jsongraph | jsongraph/graph.py | Graph.get_uri | def get_uri(self, alias):
""" Get the URI for a given alias. A registered URI will return itself,
otherwise ``None`` is returned. """
if alias in self.aliases.keys():
return self.aliases[alias]
if alias in self.aliases.values():
return alias
raise GraphException('No such schema: %r' % alias) | python | def get_uri(self, alias):
""" Get the URI for a given alias. A registered URI will return itself,
otherwise ``None`` is returned. """
if alias in self.aliases.keys():
return self.aliases[alias]
if alias in self.aliases.values():
return alias
raise GraphException('No such schema: %r' % alias) | [
"def",
"get_uri",
"(",
"self",
",",
"alias",
")",
":",
"if",
"alias",
"in",
"self",
".",
"aliases",
".",
"keys",
"(",
")",
":",
"return",
"self",
".",
"aliases",
"[",
"alias",
"]",
"if",
"alias",
"in",
"self",
".",
"aliases",
".",
"values",
"(",
... | Get the URI for a given alias. A registered URI will return itself,
otherwise ``None`` is returned. | [
"Get",
"the",
"URI",
"for",
"a",
"given",
"alias",
".",
"A",
"registered",
"URI",
"will",
"return",
"itself",
"otherwise",
"None",
"is",
"returned",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L104-L111 |
pudo/jsongraph | jsongraph/graph.py | Graph.get_schema | def get_schema(self, alias):
""" Actually resolve the schema for the given alias/URI. """
if isinstance(alias, dict):
return alias
uri = self.get_uri(alias)
if uri is None:
raise GraphException('No such schema: %r' % alias)
uri, schema = self.resolver.resolve(uri)
return schema | python | def get_schema(self, alias):
""" Actually resolve the schema for the given alias/URI. """
if isinstance(alias, dict):
return alias
uri = self.get_uri(alias)
if uri is None:
raise GraphException('No such schema: %r' % alias)
uri, schema = self.resolver.resolve(uri)
return schema | [
"def",
"get_schema",
"(",
"self",
",",
"alias",
")",
":",
"if",
"isinstance",
"(",
"alias",
",",
"dict",
")",
":",
"return",
"alias",
"uri",
"=",
"self",
".",
"get_uri",
"(",
"alias",
")",
"if",
"uri",
"is",
"None",
":",
"raise",
"GraphException",
"(... | Actually resolve the schema for the given alias/URI. | [
"Actually",
"resolve",
"the",
"schema",
"for",
"the",
"given",
"alias",
"/",
"URI",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L113-L121 |
pudo/jsongraph | jsongraph/graph.py | Graph.clear | def clear(self, context=None):
""" Delete all data from the graph. """
context = URIRef(context).n3() if context is not None else '?g'
query = """
DELETE { GRAPH %s { ?s ?p ?o } } WHERE { GRAPH %s { ?s ?p ?o } }
""" % (context, context)
self.parent.graph.update(query) | python | def clear(self, context=None):
""" Delete all data from the graph. """
context = URIRef(context).n3() if context is not None else '?g'
query = """
DELETE { GRAPH %s { ?s ?p ?o } } WHERE { GRAPH %s { ?s ?p ?o } }
""" % (context, context)
self.parent.graph.update(query) | [
"def",
"clear",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"context",
"=",
"URIRef",
"(",
"context",
")",
".",
"n3",
"(",
")",
"if",
"context",
"is",
"not",
"None",
"else",
"'?g'",
"query",
"=",
"\"\"\"\n DELETE { GRAPH %s { ?s ?p ?o } } ... | Delete all data from the graph. | [
"Delete",
"all",
"data",
"from",
"the",
"graph",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/graph.py#L123-L129 |
pudo/jsongraph | jsongraph/util.py | is_url | def is_url(text):
""" Check if the given text looks like a URL. """
if text is None:
return False
text = text.lower()
return text.startswith('http://') or text.startswith('https://') or \
text.startswith('urn:') or text.startswith('file://') | python | def is_url(text):
""" Check if the given text looks like a URL. """
if text is None:
return False
text = text.lower()
return text.startswith('http://') or text.startswith('https://') or \
text.startswith('urn:') or text.startswith('file://') | [
"def",
"is_url",
"(",
"text",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",
"False",
"text",
"=",
"text",
".",
"lower",
"(",
")",
"return",
"text",
".",
"startswith",
"(",
"'http://'",
")",
"or",
"text",
".",
"startswith",
"(",
"'https://'",
"... | Check if the given text looks like a URL. | [
"Check",
"if",
"the",
"given",
"text",
"looks",
"like",
"a",
"URL",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/util.py#L5-L11 |
pudo/jsongraph | jsongraph/util.py | safe_uriref | def safe_uriref(text):
""" Escape a URL properly. """
url_ = url.parse(text).sanitize().deuserinfo().canonical()
return URIRef(url_.punycode().unicode()) | python | def safe_uriref(text):
""" Escape a URL properly. """
url_ = url.parse(text).sanitize().deuserinfo().canonical()
return URIRef(url_.punycode().unicode()) | [
"def",
"safe_uriref",
"(",
"text",
")",
":",
"url_",
"=",
"url",
".",
"parse",
"(",
"text",
")",
".",
"sanitize",
"(",
")",
".",
"deuserinfo",
"(",
")",
".",
"canonical",
"(",
")",
"return",
"URIRef",
"(",
"url_",
".",
"punycode",
"(",
")",
".",
... | Escape a URL properly. | [
"Escape",
"a",
"URL",
"properly",
"."
] | train | https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/util.py#L14-L17 |
zenotech/MyCluster | mycluster/pbs.py | job_stats_enhanced | def job_stats_enhanced(job_id):
"""
Get full job and step stats for job_id
"""
stats_dict = {}
with os.popen('qstat -xf ' + str(job_id)) as f:
try:
line = f.readline().strip()
while line:
if line.startswith('Job Id:'):
stats_dict['job_id'] = line.split(':')[1].split('.')[0].strip()
elif line.startswith('resources_used.walltime'):
stats_dict['wallclock'] = get_timedelta(line.split('=')[1])
elif line.startswith('resources_used.cput'):
stats_dict['cpu'] = get_timedelta(line.split('=')[1])
elif line.startswith('queue'):
stats_dict['queue'] = line.split('=')[1].strip()
elif line.startswith('job_state'):
stats_dict['status'] = line.split('=')[1].strip()
elif line.startswith('Exit_status'):
stats_dict['exit_code'] = line.split('=')[1].strip()
elif line.startswith('Exit_status'):
stats_dict['exit_code'] = line.split('=')[1].strip()
elif line.startswith('stime'):
stats_dict['start'] = line.split('=')[1].strip()
line = f.readline().strip()
if stats_dict['status'] == 'F' and 'exit_code' not in stats_dict:
stats_dict['status'] = 'CA'
elif stats_dict['status'] == 'F' and stats_dict['exit_code'] == '0':
stats_dict['status'] = 'PBS_F'
except Exception as e:
with os.popen('qstat -xaw ' + str(job_id)) as f:
try:
output = f.readlines()
for line in output:
if str(job_id) in line:
cols = line.split()
stats_dict['job_id'] = cols[0].split('.')[0]
stats_dict['queue'] = cols[2]
stats_dict['status'] = cols[9]
stats_dict['wallclock'] = get_timedelta(cols[10])
return stats_dict
except Exception as e:
print(e)
print('PBS: Error reading job stats')
stats_dict['status'] = 'UNKNOWN'
return stats_dict | python | def job_stats_enhanced(job_id):
"""
Get full job and step stats for job_id
"""
stats_dict = {}
with os.popen('qstat -xf ' + str(job_id)) as f:
try:
line = f.readline().strip()
while line:
if line.startswith('Job Id:'):
stats_dict['job_id'] = line.split(':')[1].split('.')[0].strip()
elif line.startswith('resources_used.walltime'):
stats_dict['wallclock'] = get_timedelta(line.split('=')[1])
elif line.startswith('resources_used.cput'):
stats_dict['cpu'] = get_timedelta(line.split('=')[1])
elif line.startswith('queue'):
stats_dict['queue'] = line.split('=')[1].strip()
elif line.startswith('job_state'):
stats_dict['status'] = line.split('=')[1].strip()
elif line.startswith('Exit_status'):
stats_dict['exit_code'] = line.split('=')[1].strip()
elif line.startswith('Exit_status'):
stats_dict['exit_code'] = line.split('=')[1].strip()
elif line.startswith('stime'):
stats_dict['start'] = line.split('=')[1].strip()
line = f.readline().strip()
if stats_dict['status'] == 'F' and 'exit_code' not in stats_dict:
stats_dict['status'] = 'CA'
elif stats_dict['status'] == 'F' and stats_dict['exit_code'] == '0':
stats_dict['status'] = 'PBS_F'
except Exception as e:
with os.popen('qstat -xaw ' + str(job_id)) as f:
try:
output = f.readlines()
for line in output:
if str(job_id) in line:
cols = line.split()
stats_dict['job_id'] = cols[0].split('.')[0]
stats_dict['queue'] = cols[2]
stats_dict['status'] = cols[9]
stats_dict['wallclock'] = get_timedelta(cols[10])
return stats_dict
except Exception as e:
print(e)
print('PBS: Error reading job stats')
stats_dict['status'] = 'UNKNOWN'
return stats_dict | [
"def",
"job_stats_enhanced",
"(",
"job_id",
")",
":",
"stats_dict",
"=",
"{",
"}",
"with",
"os",
".",
"popen",
"(",
"'qstat -xf '",
"+",
"str",
"(",
"job_id",
")",
")",
"as",
"f",
":",
"try",
":",
"line",
"=",
"f",
".",
"readline",
"(",
")",
".",
... | Get full job and step stats for job_id | [
"Get",
"full",
"job",
"and",
"step",
"stats",
"for",
"job_id"
] | train | https://github.com/zenotech/MyCluster/blob/d2b7e35c57a515926e83bbc083d26930cd67e1bd/mycluster/pbs.py#L181-L227 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.getOrigin | def getOrigin(self, cartesian=False):
"""Return the ra/decs of the channel corners if the S/C
is pointed at the origin (ra,dec = 0,0)
Inputs:
cartesian (bool) If True, return each channel corner
as a unit vector
Returns:
A 2d numpy array. Each row represents a channel corner
The columns are module, output, channel, ra, dec
If cartestian is True, ra, and dec are replaced by the
coordinates of a 3 vector
"""
out = self.origin.copy()
if cartesian is False:
out = self.getRaDecs(out)
return out | python | def getOrigin(self, cartesian=False):
"""Return the ra/decs of the channel corners if the S/C
is pointed at the origin (ra,dec = 0,0)
Inputs:
cartesian (bool) If True, return each channel corner
as a unit vector
Returns:
A 2d numpy array. Each row represents a channel corner
The columns are module, output, channel, ra, dec
If cartestian is True, ra, and dec are replaced by the
coordinates of a 3 vector
"""
out = self.origin.copy()
if cartesian is False:
out = self.getRaDecs(out)
return out | [
"def",
"getOrigin",
"(",
"self",
",",
"cartesian",
"=",
"False",
")",
":",
"out",
"=",
"self",
".",
"origin",
".",
"copy",
"(",
")",
"if",
"cartesian",
"is",
"False",
":",
"out",
"=",
"self",
".",
"getRaDecs",
"(",
"out",
")",
"return",
"out"
] | Return the ra/decs of the channel corners if the S/C
is pointed at the origin (ra,dec = 0,0)
Inputs:
cartesian (bool) If True, return each channel corner
as a unit vector
Returns:
A 2d numpy array. Each row represents a channel corner
The columns are module, output, channel, ra, dec
If cartestian is True, ra, and dec are replaced by the
coordinates of a 3 vector | [
"Return",
"the",
"ra",
"/",
"decs",
"of",
"the",
"channel",
"corners",
"if",
"the",
"S",
"/",
"C",
"is",
"pointed",
"at",
"the",
"origin",
"(",
"ra",
"dec",
"=",
"0",
"0",
")"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L123-L142 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.computePointing | def computePointing(self, ra_deg, dec_deg, roll_deg, cartesian=False):
"""Compute a pointing model without changing the internal object pointing"""
# Roll FOV
Rrotate = r.rotateInXMat(roll_deg) # Roll
# Slew from ra/dec of zero
Ra = r.rightAscensionRotationMatrix(ra_deg)
Rd = r.declinationRotationMatrix(dec_deg)
Rslew = np.dot(Ra, Rd)
R = np.dot(Rslew, Rrotate)
slew = self.origin*1
for i, row in enumerate(self.origin):
slew[i, 3:6] = np.dot(R, row[3:6])
if cartesian is False:
slew = self.getRaDecs(slew)
return slew | python | def computePointing(self, ra_deg, dec_deg, roll_deg, cartesian=False):
"""Compute a pointing model without changing the internal object pointing"""
# Roll FOV
Rrotate = r.rotateInXMat(roll_deg) # Roll
# Slew from ra/dec of zero
Ra = r.rightAscensionRotationMatrix(ra_deg)
Rd = r.declinationRotationMatrix(dec_deg)
Rslew = np.dot(Ra, Rd)
R = np.dot(Rslew, Rrotate)
slew = self.origin*1
for i, row in enumerate(self.origin):
slew[i, 3:6] = np.dot(R, row[3:6])
if cartesian is False:
slew = self.getRaDecs(slew)
return slew | [
"def",
"computePointing",
"(",
"self",
",",
"ra_deg",
",",
"dec_deg",
",",
"roll_deg",
",",
"cartesian",
"=",
"False",
")",
":",
"# Roll FOV",
"Rrotate",
"=",
"r",
".",
"rotateInXMat",
"(",
"roll_deg",
")",
"# Roll",
"# Slew from ra/dec of zero",
"Ra",
"=",
... | Compute a pointing model without changing the internal object pointing | [
"Compute",
"a",
"pointing",
"model",
"without",
"changing",
"the",
"internal",
"object",
"pointing"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L153-L171 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.getRaDecs | def getRaDecs(self, mods):
"""Internal function converting cartesian coords to
ra dec"""
raDecOut = np.empty( (len(mods), 5))
raDecOut[:,0:3] = mods[:,0:3]
for i, row in enumerate(mods):
raDecOut[i, 3:5] = r.raDecFromVec(row[3:6])
return raDecOut | python | def getRaDecs(self, mods):
"""Internal function converting cartesian coords to
ra dec"""
raDecOut = np.empty( (len(mods), 5))
raDecOut[:,0:3] = mods[:,0:3]
for i, row in enumerate(mods):
raDecOut[i, 3:5] = r.raDecFromVec(row[3:6])
return raDecOut | [
"def",
"getRaDecs",
"(",
"self",
",",
"mods",
")",
":",
"raDecOut",
"=",
"np",
".",
"empty",
"(",
"(",
"len",
"(",
"mods",
")",
",",
"5",
")",
")",
"raDecOut",
"[",
":",
",",
"0",
":",
"3",
"]",
"=",
"mods",
"[",
":",
",",
"0",
":",
"3",
... | Internal function converting cartesian coords to
ra dec | [
"Internal",
"function",
"converting",
"cartesian",
"coords",
"to",
"ra",
"dec"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L173-L181 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.isOnSiliconList | def isOnSiliconList(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING):
"""similar to isOnSilicon() but takes lists as input"""
ch, col, row = self.getChannelColRowList(ra_deg, dec_deg)
out = np.zeros(len(ch), dtype=bool)
for channel in set(ch):
mask = (ch == channel)
if channel in self.brokenChannels:
continue
if channel > 84:
continue
out[mask] = self.colRowIsOnSciencePixelList(col[mask], row[mask], padding_pix)
return out | python | def isOnSiliconList(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING):
"""similar to isOnSilicon() but takes lists as input"""
ch, col, row = self.getChannelColRowList(ra_deg, dec_deg)
out = np.zeros(len(ch), dtype=bool)
for channel in set(ch):
mask = (ch == channel)
if channel in self.brokenChannels:
continue
if channel > 84:
continue
out[mask] = self.colRowIsOnSciencePixelList(col[mask], row[mask], padding_pix)
return out | [
"def",
"isOnSiliconList",
"(",
"self",
",",
"ra_deg",
",",
"dec_deg",
",",
"padding_pix",
"=",
"DEFAULT_PADDING",
")",
":",
"ch",
",",
"col",
",",
"row",
"=",
"self",
".",
"getChannelColRowList",
"(",
"ra_deg",
",",
"dec_deg",
")",
"out",
"=",
"np",
".",... | similar to isOnSilicon() but takes lists as input | [
"similar",
"to",
"isOnSilicon",
"()",
"but",
"takes",
"lists",
"as",
"input"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L215-L226 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.getChannelColRowList | def getChannelColRowList(self, ra, dec, wantZeroOffset=False,
allowIllegalReturnValues=True):
"""similar to getChannelColRow() but takes lists as input"""
try:
ch = self.pickAChannelList(ra, dec)
except ValueError:
logger.warning("WARN: %.7f %.7f not on any channel" % (ra, dec))
return (0, 0, 0)
col = np.zeros(len(ch))
row = np.zeros(len(ch))
for channel in set(ch):
mask = (ch == channel)
col[mask], row[mask] = self.getColRowWithinChannelList(ra[mask], dec[mask], channel,
wantZeroOffset, allowIllegalReturnValues)
return (ch, col, row) | python | def getChannelColRowList(self, ra, dec, wantZeroOffset=False,
allowIllegalReturnValues=True):
"""similar to getChannelColRow() but takes lists as input"""
try:
ch = self.pickAChannelList(ra, dec)
except ValueError:
logger.warning("WARN: %.7f %.7f not on any channel" % (ra, dec))
return (0, 0, 0)
col = np.zeros(len(ch))
row = np.zeros(len(ch))
for channel in set(ch):
mask = (ch == channel)
col[mask], row[mask] = self.getColRowWithinChannelList(ra[mask], dec[mask], channel,
wantZeroOffset, allowIllegalReturnValues)
return (ch, col, row) | [
"def",
"getChannelColRowList",
"(",
"self",
",",
"ra",
",",
"dec",
",",
"wantZeroOffset",
"=",
"False",
",",
"allowIllegalReturnValues",
"=",
"True",
")",
":",
"try",
":",
"ch",
"=",
"self",
".",
"pickAChannelList",
"(",
"ra",
",",
"dec",
")",
"except",
... | similar to getChannelColRow() but takes lists as input | [
"similar",
"to",
"getChannelColRow",
"()",
"but",
"takes",
"lists",
"as",
"input"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L228-L243 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.pickAChannelList | def pickAChannelList(self, ra_deg, dec_deg):
"""Similar to pickAChannel() but takes lists as input.
This will require AstroPy to be installed.
"""
try:
from astropy.coordinates import SkyCoord
from astropy import units as u
except ImportError:
raise ImportError("AstroPy needs to be installed to use this feature.")
cRa = self.currentRaDec[:, 3] # Ra of each channel corner
cDec = self.currentRaDec[:, 4] # dec of each channel corner
catalog = SkyCoord(cRa*u.deg, cDec*u.deg)
position = SkyCoord(ra_deg*u.deg, dec_deg*u.deg)
idx, _, _ = position.match_to_catalog_sky(catalog)
return self.currentRaDec[idx, 2] | python | def pickAChannelList(self, ra_deg, dec_deg):
"""Similar to pickAChannel() but takes lists as input.
This will require AstroPy to be installed.
"""
try:
from astropy.coordinates import SkyCoord
from astropy import units as u
except ImportError:
raise ImportError("AstroPy needs to be installed to use this feature.")
cRa = self.currentRaDec[:, 3] # Ra of each channel corner
cDec = self.currentRaDec[:, 4] # dec of each channel corner
catalog = SkyCoord(cRa*u.deg, cDec*u.deg)
position = SkyCoord(ra_deg*u.deg, dec_deg*u.deg)
idx, _, _ = position.match_to_catalog_sky(catalog)
return self.currentRaDec[idx, 2] | [
"def",
"pickAChannelList",
"(",
"self",
",",
"ra_deg",
",",
"dec_deg",
")",
":",
"try",
":",
"from",
"astropy",
".",
"coordinates",
"import",
"SkyCoord",
"from",
"astropy",
"import",
"units",
"as",
"u",
"except",
"ImportError",
":",
"raise",
"ImportError",
"... | Similar to pickAChannel() but takes lists as input.
This will require AstroPy to be installed. | [
"Similar",
"to",
"pickAChannel",
"()",
"but",
"takes",
"lists",
"as",
"input",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L245-L260 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.colRowIsOnSciencePixelList | def colRowIsOnSciencePixelList(self, col, row, padding=DEFAULT_PADDING):
"""similar to colRowIsOnSciencePixelList() but takes lists as input"""
out = np.ones(len(col), dtype=bool)
col_arr = np.array(col)
row_arr = np.array(row)
mask = np.bitwise_or(col_arr < 12. - padding, col_arr > 1111 + padding)
out[mask] = False
mask = np.bitwise_or(row_arr < 20. - padding, row_arr > 1043 + padding)
out[mask] = False
return out | python | def colRowIsOnSciencePixelList(self, col, row, padding=DEFAULT_PADDING):
"""similar to colRowIsOnSciencePixelList() but takes lists as input"""
out = np.ones(len(col), dtype=bool)
col_arr = np.array(col)
row_arr = np.array(row)
mask = np.bitwise_or(col_arr < 12. - padding, col_arr > 1111 + padding)
out[mask] = False
mask = np.bitwise_or(row_arr < 20. - padding, row_arr > 1043 + padding)
out[mask] = False
return out | [
"def",
"colRowIsOnSciencePixelList",
"(",
"self",
",",
"col",
",",
"row",
",",
"padding",
"=",
"DEFAULT_PADDING",
")",
":",
"out",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"col",
")",
",",
"dtype",
"=",
"bool",
")",
"col_arr",
"=",
"np",
".",
"array"... | similar to colRowIsOnSciencePixelList() but takes lists as input | [
"similar",
"to",
"colRowIsOnSciencePixelList",
"()",
"but",
"takes",
"lists",
"as",
"input"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L291-L300 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.isOnSilicon | def isOnSilicon(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING):
"""Returns True if the given location is observable with a science CCD.
Parameters
----------
ra_deg : float
Right Ascension (J2000) in decimal degrees.
dec_deg : float
Declination (J2000) in decimal degrees.
padding : float
Objects <= this many pixels off the edge of a channel are counted
as inside. This allows one to compensate for the slight
inaccuracy in `K2fov` that results from e.g. the lack of optical
distortion modeling.
"""
ch, col, row = self.getChannelColRow(ra_deg, dec_deg)
# Modules 3 and 7 are no longer operational
if ch in self.brokenChannels:
return False
# K2fov encodes the Fine Guidance Sensors (FGS) as
# "channel" numbers 85-88; they are not science CCDs.
if ch > 84:
return False
return self.colRowIsOnSciencePixel(col, row, padding_pix) | python | def isOnSilicon(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING):
"""Returns True if the given location is observable with a science CCD.
Parameters
----------
ra_deg : float
Right Ascension (J2000) in decimal degrees.
dec_deg : float
Declination (J2000) in decimal degrees.
padding : float
Objects <= this many pixels off the edge of a channel are counted
as inside. This allows one to compensate for the slight
inaccuracy in `K2fov` that results from e.g. the lack of optical
distortion modeling.
"""
ch, col, row = self.getChannelColRow(ra_deg, dec_deg)
# Modules 3 and 7 are no longer operational
if ch in self.brokenChannels:
return False
# K2fov encodes the Fine Guidance Sensors (FGS) as
# "channel" numbers 85-88; they are not science CCDs.
if ch > 84:
return False
return self.colRowIsOnSciencePixel(col, row, padding_pix) | [
"def",
"isOnSilicon",
"(",
"self",
",",
"ra_deg",
",",
"dec_deg",
",",
"padding_pix",
"=",
"DEFAULT_PADDING",
")",
":",
"ch",
",",
"col",
",",
"row",
"=",
"self",
".",
"getChannelColRow",
"(",
"ra_deg",
",",
"dec_deg",
")",
"# Modules 3 and 7 are no longer ope... | Returns True if the given location is observable with a science CCD.
Parameters
----------
ra_deg : float
Right Ascension (J2000) in decimal degrees.
dec_deg : float
Declination (J2000) in decimal degrees.
padding : float
Objects <= this many pixels off the edge of a channel are counted
as inside. This allows one to compensate for the slight
inaccuracy in `K2fov` that results from e.g. the lack of optical
distortion modeling. | [
"Returns",
"True",
"if",
"the",
"given",
"location",
"is",
"observable",
"with",
"a",
"science",
"CCD",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L302-L327 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.getChannelColRow | def getChannelColRow(self, ra, dec, wantZeroOffset=False,
allowIllegalReturnValues=True):
"""Returns (channel, column, row) given an (ra, dec) coordinate.
Returns (0, 0, 0) or a ValueError if the coordinate is not on silicon.
"""
try:
ch = self.pickAChannel(ra, dec)
except ValueError:
logger.warning("WARN: %.7f %.7f not on any channel" % (ra, dec))
return (0, 0, 0)
col, row = self.getColRowWithinChannel(ra, dec, ch, wantZeroOffset,
allowIllegalReturnValues)
return (ch, col, row) | python | def getChannelColRow(self, ra, dec, wantZeroOffset=False,
allowIllegalReturnValues=True):
"""Returns (channel, column, row) given an (ra, dec) coordinate.
Returns (0, 0, 0) or a ValueError if the coordinate is not on silicon.
"""
try:
ch = self.pickAChannel(ra, dec)
except ValueError:
logger.warning("WARN: %.7f %.7f not on any channel" % (ra, dec))
return (0, 0, 0)
col, row = self.getColRowWithinChannel(ra, dec, ch, wantZeroOffset,
allowIllegalReturnValues)
return (ch, col, row) | [
"def",
"getChannelColRow",
"(",
"self",
",",
"ra",
",",
"dec",
",",
"wantZeroOffset",
"=",
"False",
",",
"allowIllegalReturnValues",
"=",
"True",
")",
":",
"try",
":",
"ch",
"=",
"self",
".",
"pickAChannel",
"(",
"ra",
",",
"dec",
")",
"except",
"ValueEr... | Returns (channel, column, row) given an (ra, dec) coordinate.
Returns (0, 0, 0) or a ValueError if the coordinate is not on silicon. | [
"Returns",
"(",
"channel",
"column",
"row",
")",
"given",
"an",
"(",
"ra",
"dec",
")",
"coordinate",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L329-L343 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.pickAChannel | def pickAChannel(self, ra_deg, dec_deg):
"""Returns the channel number closest to a given (ra, dec) coordinate.
"""
# Could improve speed by doing this in the projection plane
# instead of sky coords
cRa = self.currentRaDec[:, 3] # Ra of each channel corner
cDec = self.currentRaDec[:, 4] # dec of each channel corner
dist = cRa * 0
for i in range(len(dist)):
dist[i] = gcircle.sphericalAngSep(cRa[i], cDec[i], ra_deg, dec_deg)
i = np.argmin(dist)
return self.currentRaDec[i, 2] | python | def pickAChannel(self, ra_deg, dec_deg):
"""Returns the channel number closest to a given (ra, dec) coordinate.
"""
# Could improve speed by doing this in the projection plane
# instead of sky coords
cRa = self.currentRaDec[:, 3] # Ra of each channel corner
cDec = self.currentRaDec[:, 4] # dec of each channel corner
dist = cRa * 0
for i in range(len(dist)):
dist[i] = gcircle.sphericalAngSep(cRa[i], cDec[i], ra_deg, dec_deg)
i = np.argmin(dist)
return self.currentRaDec[i, 2] | [
"def",
"pickAChannel",
"(",
"self",
",",
"ra_deg",
",",
"dec_deg",
")",
":",
"# Could improve speed by doing this in the projection plane",
"# instead of sky coords",
"cRa",
"=",
"self",
".",
"currentRaDec",
"[",
":",
",",
"3",
"]",
"# Ra of each channel corner",
"cDec"... | Returns the channel number closest to a given (ra, dec) coordinate. | [
"Returns",
"the",
"channel",
"number",
"closest",
"to",
"a",
"given",
"(",
"ra",
"dec",
")",
"coordinate",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L345-L358 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.getColRowWithinChannel | def getColRowWithinChannel(self, ra, dec, ch, wantZeroOffset=False,
allowIllegalReturnValues=True):
"""Returns (col, row) given a (ra, dec) coordinate and channel number.
"""
# How close is a given ra/dec to the origin of a KeplerModule?
x, y = self.defaultMap.skyToPix(ra, dec)
kepModule = self.getChannelAsPolygon(ch)
r = np.array([x[0],y[0]]) - kepModule.polygon[0, :]
v1 = kepModule.polygon[1, :] - kepModule.polygon[0, :]
v3 = kepModule.polygon[3, :] - kepModule.polygon[0, :]
# Divide by |v|^2 because you're normalising v and r
colFrac = np.dot(r, v1) / np.linalg.norm(v1)**2
rowFrac = np.dot(r, v3) / np.linalg.norm(v3)**2
# This is where it gets a little hairy. The channel "corners"
# supplied to me actually represent points 5x5 pixels inside
# the science array. Which isn't what you'd expect.
# These magic numbers are the pixel numbers of the corner
# edges given in fov.txt
col = colFrac*(1106-17) + 17
row = rowFrac*(1038-25) + 25
if not allowIllegalReturnValues:
if not self.colRowIsOnSciencePixel(col, row):
msg = "Request position %7f %.7f " % (ra, dec)
msg += "does not lie on science pixels for channel %i " % (ch)
msg += "[ %.1f %.1f]" % (col, row)
raise ValueError(msg)
# Convert from zero-offset to one-offset coords
if not wantZeroOffset:
col += 1
row += 1
return (col, row) | python | def getColRowWithinChannel(self, ra, dec, ch, wantZeroOffset=False,
allowIllegalReturnValues=True):
"""Returns (col, row) given a (ra, dec) coordinate and channel number.
"""
# How close is a given ra/dec to the origin of a KeplerModule?
x, y = self.defaultMap.skyToPix(ra, dec)
kepModule = self.getChannelAsPolygon(ch)
r = np.array([x[0],y[0]]) - kepModule.polygon[0, :]
v1 = kepModule.polygon[1, :] - kepModule.polygon[0, :]
v3 = kepModule.polygon[3, :] - kepModule.polygon[0, :]
# Divide by |v|^2 because you're normalising v and r
colFrac = np.dot(r, v1) / np.linalg.norm(v1)**2
rowFrac = np.dot(r, v3) / np.linalg.norm(v3)**2
# This is where it gets a little hairy. The channel "corners"
# supplied to me actually represent points 5x5 pixels inside
# the science array. Which isn't what you'd expect.
# These magic numbers are the pixel numbers of the corner
# edges given in fov.txt
col = colFrac*(1106-17) + 17
row = rowFrac*(1038-25) + 25
if not allowIllegalReturnValues:
if not self.colRowIsOnSciencePixel(col, row):
msg = "Request position %7f %.7f " % (ra, dec)
msg += "does not lie on science pixels for channel %i " % (ch)
msg += "[ %.1f %.1f]" % (col, row)
raise ValueError(msg)
# Convert from zero-offset to one-offset coords
if not wantZeroOffset:
col += 1
row += 1
return (col, row) | [
"def",
"getColRowWithinChannel",
"(",
"self",
",",
"ra",
",",
"dec",
",",
"ch",
",",
"wantZeroOffset",
"=",
"False",
",",
"allowIllegalReturnValues",
"=",
"True",
")",
":",
"# How close is a given ra/dec to the origin of a KeplerModule?",
"x",
",",
"y",
"=",
"self",... | Returns (col, row) given a (ra, dec) coordinate and channel number. | [
"Returns",
"(",
"col",
"row",
")",
"given",
"a",
"(",
"ra",
"dec",
")",
"coordinate",
"and",
"channel",
"number",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L361-L397 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.colRowIsOnSciencePixel | def colRowIsOnSciencePixel(self, col, row, padding=DEFAULT_PADDING):
"""Is col row on a science pixel?
Ranges taken from Fig 25 or Instrument Handbook (p50)
Padding allows for the fact that distortion means the
results from getColRowWithinChannel can be off by a bit.
Setting padding > 0 means that objects that are computed
to lie a small amount off silicon will return True.
To be conservative, set padding to negative
"""
if col < 12. - padding or col > 1111 + padding:
return False
if row < 20 - padding or row > 1043 + padding:
return False
return True | python | def colRowIsOnSciencePixel(self, col, row, padding=DEFAULT_PADDING):
"""Is col row on a science pixel?
Ranges taken from Fig 25 or Instrument Handbook (p50)
Padding allows for the fact that distortion means the
results from getColRowWithinChannel can be off by a bit.
Setting padding > 0 means that objects that are computed
to lie a small amount off silicon will return True.
To be conservative, set padding to negative
"""
if col < 12. - padding or col > 1111 + padding:
return False
if row < 20 - padding or row > 1043 + padding:
return False
return True | [
"def",
"colRowIsOnSciencePixel",
"(",
"self",
",",
"col",
",",
"row",
",",
"padding",
"=",
"DEFAULT_PADDING",
")",
":",
"if",
"col",
"<",
"12.",
"-",
"padding",
"or",
"col",
">",
"1111",
"+",
"padding",
":",
"return",
"False",
"if",
"row",
"<",
"20",
... | Is col row on a science pixel?
Ranges taken from Fig 25 or Instrument Handbook (p50)
Padding allows for the fact that distortion means the
results from getColRowWithinChannel can be off by a bit.
Setting padding > 0 means that objects that are computed
to lie a small amount off silicon will return True.
To be conservative, set padding to negative | [
"Is",
"col",
"row",
"on",
"a",
"science",
"pixel?"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L399-L416 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.colRowIsOnFgsPixel | def colRowIsOnFgsPixel(self, col, row, padding=-50):
"""Is col row on a science pixel?
#See Kepler Flight Segment User's Manual (SP0039-702) \S 5.4 (p88)
Inputs:
col, row (floats or ints)
padding If padding <0, pixel must be on silicon and this many
pixels away from the edge of the CCD to return True
Returns:
boolean
"""
if col < 12. - padding or col > 547 + padding:
return False
if row < 0 - padding or row > 527 + padding :
return False
return True | python | def colRowIsOnFgsPixel(self, col, row, padding=-50):
"""Is col row on a science pixel?
#See Kepler Flight Segment User's Manual (SP0039-702) \S 5.4 (p88)
Inputs:
col, row (floats or ints)
padding If padding <0, pixel must be on silicon and this many
pixels away from the edge of the CCD to return True
Returns:
boolean
"""
if col < 12. - padding or col > 547 + padding:
return False
if row < 0 - padding or row > 527 + padding :
return False
return True | [
"def",
"colRowIsOnFgsPixel",
"(",
"self",
",",
"col",
",",
"row",
",",
"padding",
"=",
"-",
"50",
")",
":",
"if",
"col",
"<",
"12.",
"-",
"padding",
"or",
"col",
">",
"547",
"+",
"padding",
":",
"return",
"False",
"if",
"row",
"<",
"0",
"-",
"pad... | Is col row on a science pixel?
#See Kepler Flight Segment User's Manual (SP0039-702) \S 5.4 (p88)
Inputs:
col, row (floats or ints)
padding If padding <0, pixel must be on silicon and this many
pixels away from the edge of the CCD to return True
Returns:
boolean | [
"Is",
"col",
"row",
"on",
"a",
"science",
"pixel?"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L451-L469 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.getAllChannelsAsPolygons | def getAllChannelsAsPolygons(self, maptype=None):
"""Return slew the telescope and return the corners of the modules
as Polygon objects.
If a projection is supplied, the ras and
decs are mapped onto x, y using that projection
"""
polyList = []
for ch in self.origin[:, 2]:
poly = self.getChannelAsPolygon(ch, maptype)
polyList.append(poly)
return polyList | python | def getAllChannelsAsPolygons(self, maptype=None):
"""Return slew the telescope and return the corners of the modules
as Polygon objects.
If a projection is supplied, the ras and
decs are mapped onto x, y using that projection
"""
polyList = []
for ch in self.origin[:, 2]:
poly = self.getChannelAsPolygon(ch, maptype)
polyList.append(poly)
return polyList | [
"def",
"getAllChannelsAsPolygons",
"(",
"self",
",",
"maptype",
"=",
"None",
")",
":",
"polyList",
"=",
"[",
"]",
"for",
"ch",
"in",
"self",
".",
"origin",
"[",
":",
",",
"2",
"]",
":",
"poly",
"=",
"self",
".",
"getChannelAsPolygon",
"(",
"ch",
",",... | Return slew the telescope and return the corners of the modules
as Polygon objects.
If a projection is supplied, the ras and
decs are mapped onto x, y using that projection | [
"Return",
"slew",
"the",
"telescope",
"and",
"return",
"the",
"corners",
"of",
"the",
"modules",
"as",
"Polygon",
"objects",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L537-L548 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.plotPointing | def plotPointing(self, maptype=None, colour='b', mod3='r', showOuts=True, **kwargs):
"""Plot the FOV
"""
if maptype is None:
maptype=self.defaultMap
radec = self.currentRaDec
for ch in radec[:,2][::4]:
idx = np.where(radec[:,2].astype(np.int) == ch)[0]
idx = np.append(idx, idx[0]) #% points to draw a box
c = colour
if ch in self.brokenChannels:
c = mod3
maptype.plot(radec[idx, 3], radec[idx, 4], '-', color=c, **kwargs)
#Show the origin of the col and row coords for this ch
if showOuts:
maptype.plot(radec[idx[0], 3], radec[idx[0],4], 'o', color=c) | python | def plotPointing(self, maptype=None, colour='b', mod3='r', showOuts=True, **kwargs):
"""Plot the FOV
"""
if maptype is None:
maptype=self.defaultMap
radec = self.currentRaDec
for ch in radec[:,2][::4]:
idx = np.where(radec[:,2].astype(np.int) == ch)[0]
idx = np.append(idx, idx[0]) #% points to draw a box
c = colour
if ch in self.brokenChannels:
c = mod3
maptype.plot(radec[idx, 3], radec[idx, 4], '-', color=c, **kwargs)
#Show the origin of the col and row coords for this ch
if showOuts:
maptype.plot(radec[idx[0], 3], radec[idx[0],4], 'o', color=c) | [
"def",
"plotPointing",
"(",
"self",
",",
"maptype",
"=",
"None",
",",
"colour",
"=",
"'b'",
",",
"mod3",
"=",
"'r'",
",",
"showOuts",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"maptype",
"is",
"None",
":",
"maptype",
"=",
"self",
".",
... | Plot the FOV | [
"Plot",
"the",
"FOV"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L568-L587 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.plotOutline | def plotOutline(self, maptype=None, colour='#AAAAAA', **kwargs):
"""Plot an outline of the FOV.
"""
if maptype is None:
maptype=self.defaultMap
xarr = []
yarr = []
radec = self.currentRaDec
for ch in [20,4,11,28,32, 71,68, 84, 75, 60, 56, 15 ]:
idx = np.where(radec[:,2].astype(np.int) == ch)[0]
idx = idx[0] #Take on the first one
x, y = maptype.skyToPix(radec[idx][3], radec[idx][4])
xarr.append(x)
yarr.append(y)
verts = np.empty( (len(xarr), 2))
verts[:,0] = xarr
verts[:,1] = yarr
#There are two ways to specify line colour
ec = kwargs.pop('ec', "none")
ec = kwargs.pop('edgecolor', ec)
p = matplotlib.patches.Polygon(verts, fill=True, ec=ec, fc=colour, **kwargs)
mp.gca().add_patch(p) | python | def plotOutline(self, maptype=None, colour='#AAAAAA', **kwargs):
"""Plot an outline of the FOV.
"""
if maptype is None:
maptype=self.defaultMap
xarr = []
yarr = []
radec = self.currentRaDec
for ch in [20,4,11,28,32, 71,68, 84, 75, 60, 56, 15 ]:
idx = np.where(radec[:,2].astype(np.int) == ch)[0]
idx = idx[0] #Take on the first one
x, y = maptype.skyToPix(radec[idx][3], radec[idx][4])
xarr.append(x)
yarr.append(y)
verts = np.empty( (len(xarr), 2))
verts[:,0] = xarr
verts[:,1] = yarr
#There are two ways to specify line colour
ec = kwargs.pop('ec', "none")
ec = kwargs.pop('edgecolor', ec)
p = matplotlib.patches.Polygon(verts, fill=True, ec=ec, fc=colour, **kwargs)
mp.gca().add_patch(p) | [
"def",
"plotOutline",
"(",
"self",
",",
"maptype",
"=",
"None",
",",
"colour",
"=",
"'#AAAAAA'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"maptype",
"is",
"None",
":",
"maptype",
"=",
"self",
".",
"defaultMap",
"xarr",
"=",
"[",
"]",
"yarr",
"=",
"... | Plot an outline of the FOV. | [
"Plot",
"an",
"outline",
"of",
"the",
"FOV",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L590-L615 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.plotSpacecraftYAxis | def plotSpacecraftYAxis(self, maptype=None):
"""Plot a line pointing in the direction of the spacecraft
y-axis (i.e normal to the solar panel
"""
if maptype is None:
maptype=self.defaultMap
#Plot direction of spacecraft +y axis. The subtraction of
#90 degrees accounts for the different defintions of where
#zero roll is.
yAngle_deg = getSpacecraftRollAngleFromFovAngle(self.roll0_deg)
yAngle_deg -=90
a,d = gcircle.sphericalAngDestination(self.ra0_deg, self.dec0_deg, -yAngle_deg, 12.0)
x0, y0 = maptype.skyToPix(self.ra0_deg, self.dec0_deg)
x1, y1 = maptype.skyToPix(a, d)
mp.plot([x0, x1], [y0, y1], 'k-') | python | def plotSpacecraftYAxis(self, maptype=None):
"""Plot a line pointing in the direction of the spacecraft
y-axis (i.e normal to the solar panel
"""
if maptype is None:
maptype=self.defaultMap
#Plot direction of spacecraft +y axis. The subtraction of
#90 degrees accounts for the different defintions of where
#zero roll is.
yAngle_deg = getSpacecraftRollAngleFromFovAngle(self.roll0_deg)
yAngle_deg -=90
a,d = gcircle.sphericalAngDestination(self.ra0_deg, self.dec0_deg, -yAngle_deg, 12.0)
x0, y0 = maptype.skyToPix(self.ra0_deg, self.dec0_deg)
x1, y1 = maptype.skyToPix(a, d)
mp.plot([x0, x1], [y0, y1], 'k-') | [
"def",
"plotSpacecraftYAxis",
"(",
"self",
",",
"maptype",
"=",
"None",
")",
":",
"if",
"maptype",
"is",
"None",
":",
"maptype",
"=",
"self",
".",
"defaultMap",
"#Plot direction of spacecraft +y axis. The subtraction of",
"#90 degrees accounts for the different defintions o... | Plot a line pointing in the direction of the spacecraft
y-axis (i.e normal to the solar panel | [
"Plot",
"a",
"line",
"pointing",
"in",
"the",
"direction",
"of",
"the",
"spacecraft",
"y",
"-",
"axis",
"(",
"i",
".",
"e",
"normal",
"to",
"the",
"solar",
"panel"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L618-L634 |
KeplerGO/K2fov | K2fov/fov.py | KeplerFov.plotChIds | def plotChIds(self, maptype=None, modout=False):
"""Print the channel numbers on the plotting display
Note:
---------
This method will behave poorly if you are plotting in
mixed projections. Because the channel vertex polygons
are already projected using self.defaultMap, applying
this function when plotting in a different reference frame
may cause trouble.
"""
if maptype is None:
maptype = self.defaultMap
polyList = self.getAllChannelsAsPolygons(maptype)
for p in polyList:
p.identifyModule(modout=modout) | python | def plotChIds(self, maptype=None, modout=False):
"""Print the channel numbers on the plotting display
Note:
---------
This method will behave poorly if you are plotting in
mixed projections. Because the channel vertex polygons
are already projected using self.defaultMap, applying
this function when plotting in a different reference frame
may cause trouble.
"""
if maptype is None:
maptype = self.defaultMap
polyList = self.getAllChannelsAsPolygons(maptype)
for p in polyList:
p.identifyModule(modout=modout) | [
"def",
"plotChIds",
"(",
"self",
",",
"maptype",
"=",
"None",
",",
"modout",
"=",
"False",
")",
":",
"if",
"maptype",
"is",
"None",
":",
"maptype",
"=",
"self",
".",
"defaultMap",
"polyList",
"=",
"self",
".",
"getAllChannelsAsPolygons",
"(",
"maptype",
... | Print the channel numbers on the plotting display
Note:
---------
This method will behave poorly if you are plotting in
mixed projections. Because the channel vertex polygons
are already projected using self.defaultMap, applying
this function when plotting in a different reference frame
may cause trouble. | [
"Print",
"the",
"channel",
"numbers",
"on",
"the",
"plotting",
"display"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L637-L653 |
KeplerGO/K2fov | K2fov/fov.py | Polygon.isPointInside | def isPointInside(self, xp, yp):
"""Is the given point inside the polygon?
Input:
------------
xp, yp
(floats) Coordinates of point in same units that
array vertices are specified when object created.
Returns:
-----------
**True** / **False**
"""
point = np.array([xp, yp]).transpose()
polygon = self.polygon
numVert, numDim = polygon.shape
#Subtract each point from the previous one.
polyVec = np.roll(polygon, -1, 0) - polygon
#Get the vector from each vertex to the given point
pointVec = point - polygon
crossProduct = np.cross(polyVec, pointVec)
if np.all(crossProduct < 0) or np.all(crossProduct > 0):
return True
return False | python | def isPointInside(self, xp, yp):
"""Is the given point inside the polygon?
Input:
------------
xp, yp
(floats) Coordinates of point in same units that
array vertices are specified when object created.
Returns:
-----------
**True** / **False**
"""
point = np.array([xp, yp]).transpose()
polygon = self.polygon
numVert, numDim = polygon.shape
#Subtract each point from the previous one.
polyVec = np.roll(polygon, -1, 0) - polygon
#Get the vector from each vertex to the given point
pointVec = point - polygon
crossProduct = np.cross(polyVec, pointVec)
if np.all(crossProduct < 0) or np.all(crossProduct > 0):
return True
return False | [
"def",
"isPointInside",
"(",
"self",
",",
"xp",
",",
"yp",
")",
":",
"point",
"=",
"np",
".",
"array",
"(",
"[",
"xp",
",",
"yp",
"]",
")",
".",
"transpose",
"(",
")",
"polygon",
"=",
"self",
".",
"polygon",
"numVert",
",",
"numDim",
"=",
"polygo... | Is the given point inside the polygon?
Input:
------------
xp, yp
(floats) Coordinates of point in same units that
array vertices are specified when object created.
Returns:
-----------
**True** / **False** | [
"Is",
"the",
"given",
"point",
"inside",
"the",
"polygon?"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L728-L754 |
KeplerGO/K2fov | K2fov/fov.py | Polygon.draw | def draw(self, **kwargs):
"""Draw the polygon
Optional Inputs:
------------
All optional inputs are passed to ``matplotlib.patches.Polygon``
Notes:
---------
Does not accept maptype as an argument.
"""
ax = mp.gca()
shape = matplotlib.patches.Polygon(self.polygon, **kwargs)
ax.add_artist(shape) | python | def draw(self, **kwargs):
"""Draw the polygon
Optional Inputs:
------------
All optional inputs are passed to ``matplotlib.patches.Polygon``
Notes:
---------
Does not accept maptype as an argument.
"""
ax = mp.gca()
shape = matplotlib.patches.Polygon(self.polygon, **kwargs)
ax.add_artist(shape) | [
"def",
"draw",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"mp",
".",
"gca",
"(",
")",
"shape",
"=",
"matplotlib",
".",
"patches",
".",
"Polygon",
"(",
"self",
".",
"polygon",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"add_artist",
... | Draw the polygon
Optional Inputs:
------------
All optional inputs are passed to ``matplotlib.patches.Polygon``
Notes:
---------
Does not accept maptype as an argument. | [
"Draw",
"the",
"polygon"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L756-L770 |
KeplerGO/K2fov | K2fov/fov.py | KeplerModOut.identifyModule | def identifyModule(self, modout=False):
"""Write the name of a channel/modout on a plot
Optional Inputs:
-----------
modout
(boolean). If True, write module and output. Otherwise
write channel number
Returns:
------------
**None**
Output:
-----------
Channel numbers are written to the current axis.
"""
x,y = np.mean(self.polygon, 0)
if modout:
modout = modOutFromChannel(self.channel)
mp.text(x, y, "%i-%i" %(modout[0], modout[1]), fontsize=8, \
ha="center", clip_on=True)
else:
mp.text(x,y, "%i" %(self.channel), fontsize=8, \
ha="center", clip_on=True) | python | def identifyModule(self, modout=False):
"""Write the name of a channel/modout on a plot
Optional Inputs:
-----------
modout
(boolean). If True, write module and output. Otherwise
write channel number
Returns:
------------
**None**
Output:
-----------
Channel numbers are written to the current axis.
"""
x,y = np.mean(self.polygon, 0)
if modout:
modout = modOutFromChannel(self.channel)
mp.text(x, y, "%i-%i" %(modout[0], modout[1]), fontsize=8, \
ha="center", clip_on=True)
else:
mp.text(x,y, "%i" %(self.channel), fontsize=8, \
ha="center", clip_on=True) | [
"def",
"identifyModule",
"(",
"self",
",",
"modout",
"=",
"False",
")",
":",
"x",
",",
"y",
"=",
"np",
".",
"mean",
"(",
"self",
".",
"polygon",
",",
"0",
")",
"if",
"modout",
":",
"modout",
"=",
"modOutFromChannel",
"(",
"self",
".",
"channel",
")... | Write the name of a channel/modout on a plot
Optional Inputs:
-----------
modout
(boolean). If True, write module and output. Otherwise
write channel number
Returns:
------------
**None**
Output:
-----------
Channel numbers are written to the current axis. | [
"Write",
"the",
"name",
"of",
"a",
"channel",
"/",
"modout",
"on",
"a",
"plot"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/fov.py#L783-L809 |
p3trus/slave | slave/protocol.py | IEC60488.parse_response | def parse_response(self, response, header=None):
"""Parses the response message.
The following graph shows the structure of response messages.
::
+----------+
+--+ data sep +<-+
| +----------+ |
| |
+--------+ +------------+ | +------+ |
+-->| header +------->+ header sep +---+--->+ data +----+----+
| +--------+ +------------+ +------+ |
| |
--+ +----------+ +-->
| +--+ data sep +<-+ |
| | +----------+ | |
| | | |
| | +------+ | |
+--------------------------------------+--->+ data +----+----+
+------+
"""
response = response.decode(self.encoding)
if header:
header = "".join((self.resp_prefix, header, self.resp_header_sep))
if not response.startswith(header):
raise IEC60488.ParsingError('Response header mismatch')
response = response[len(header):]
return response.split(self.resp_data_sep) | python | def parse_response(self, response, header=None):
"""Parses the response message.
The following graph shows the structure of response messages.
::
+----------+
+--+ data sep +<-+
| +----------+ |
| |
+--------+ +------------+ | +------+ |
+-->| header +------->+ header sep +---+--->+ data +----+----+
| +--------+ +------------+ +------+ |
| |
--+ +----------+ +-->
| +--+ data sep +<-+ |
| | +----------+ | |
| | | |
| | +------+ | |
+--------------------------------------+--->+ data +----+----+
+------+
"""
response = response.decode(self.encoding)
if header:
header = "".join((self.resp_prefix, header, self.resp_header_sep))
if not response.startswith(header):
raise IEC60488.ParsingError('Response header mismatch')
response = response[len(header):]
return response.split(self.resp_data_sep) | [
"def",
"parse_response",
"(",
"self",
",",
"response",
",",
"header",
"=",
"None",
")",
":",
"response",
"=",
"response",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"if",
"header",
":",
"header",
"=",
"\"\"",
".",
"join",
"(",
"(",
"self",
"."... | Parses the response message.
The following graph shows the structure of response messages.
::
+----------+
+--+ data sep +<-+
| +----------+ |
| |
+--------+ +------------+ | +------+ |
+-->| header +------->+ header sep +---+--->+ data +----+----+
| +--------+ +------------+ +------+ |
| |
--+ +----------+ +-->
| +--+ data sep +<-+ |
| | +----------+ | |
| | | |
| | +------+ | |
+--------------------------------------+--->+ data +----+----+
+------+ | [
"Parses",
"the",
"response",
"message",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/protocol.py#L117-L147 |
p3trus/slave | slave/protocol.py | IEC60488.trigger | def trigger(self, transport):
"""Triggers the transport."""
logger.debug('IEC60488 trigger')
with transport:
try:
transport.trigger()
except AttributeError:
trigger_msg = self.create_message('*TRG')
transport.write(trigger_msg) | python | def trigger(self, transport):
"""Triggers the transport."""
logger.debug('IEC60488 trigger')
with transport:
try:
transport.trigger()
except AttributeError:
trigger_msg = self.create_message('*TRG')
transport.write(trigger_msg) | [
"def",
"trigger",
"(",
"self",
",",
"transport",
")",
":",
"logger",
".",
"debug",
"(",
"'IEC60488 trigger'",
")",
"with",
"transport",
":",
"try",
":",
"transport",
".",
"trigger",
"(",
")",
"except",
"AttributeError",
":",
"trigger_msg",
"=",
"self",
"."... | Triggers the transport. | [
"Triggers",
"the",
"transport",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/protocol.py#L167-L175 |
p3trus/slave | slave/protocol.py | IEC60488.clear | def clear(self, transport):
"""Issues a device clear command."""
logger.debug('IEC60488 clear')
with transport:
try:
transport.clear()
except AttributeError:
clear_msg = self.create_message('*CLS')
transport.write(clear_msg) | python | def clear(self, transport):
"""Issues a device clear command."""
logger.debug('IEC60488 clear')
with transport:
try:
transport.clear()
except AttributeError:
clear_msg = self.create_message('*CLS')
transport.write(clear_msg) | [
"def",
"clear",
"(",
"self",
",",
"transport",
")",
":",
"logger",
".",
"debug",
"(",
"'IEC60488 clear'",
")",
"with",
"transport",
":",
"try",
":",
"transport",
".",
"clear",
"(",
")",
"except",
"AttributeError",
":",
"clear_msg",
"=",
"self",
".",
"cre... | Issues a device clear command. | [
"Issues",
"a",
"device",
"clear",
"command",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/protocol.py#L177-L185 |
p3trus/slave | slave/protocol.py | SignalRecovery.query_bytes | def query_bytes(self, transport, num_bytes, header, *data):
"""Queries for binary data
:param transport: A transport object.
:param num_bytes: The exact number of data bytes expected.
:param header: The message header.
:param data: Optional data.
:returns: The raw unparsed data bytearray.
"""
message = self.create_message(header, *data)
logger.debug('SignalRecovery query bytes: %r', message)
with transport:
transport.write(message)
response = transport.read_exactly(num_bytes)
logger.debug('SignalRecovery response: %r', response)
# We need to read 3 bytes, because there is a \0 character
# separating the data from the status bytes.
_, status_byte, overload_byte = transport.read_exactly(3)
logger.debug('SignalRecovery stb: %r olb: %r', status_byte, overload_byte)
self.call_byte_handler(status_byte, overload_byte)
# returns raw unparsed bytes.
return response | python | def query_bytes(self, transport, num_bytes, header, *data):
"""Queries for binary data
:param transport: A transport object.
:param num_bytes: The exact number of data bytes expected.
:param header: The message header.
:param data: Optional data.
:returns: The raw unparsed data bytearray.
"""
message = self.create_message(header, *data)
logger.debug('SignalRecovery query bytes: %r', message)
with transport:
transport.write(message)
response = transport.read_exactly(num_bytes)
logger.debug('SignalRecovery response: %r', response)
# We need to read 3 bytes, because there is a \0 character
# separating the data from the status bytes.
_, status_byte, overload_byte = transport.read_exactly(3)
logger.debug('SignalRecovery stb: %r olb: %r', status_byte, overload_byte)
self.call_byte_handler(status_byte, overload_byte)
# returns raw unparsed bytes.
return response | [
"def",
"query_bytes",
"(",
"self",
",",
"transport",
",",
"num_bytes",
",",
"header",
",",
"*",
"data",
")",
":",
"message",
"=",
"self",
".",
"create_message",
"(",
"header",
",",
"*",
"data",
")",
"logger",
".",
"debug",
"(",
"'SignalRecovery query bytes... | Queries for binary data
:param transport: A transport object.
:param num_bytes: The exact number of data bytes expected.
:param header: The message header.
:param data: Optional data.
:returns: The raw unparsed data bytearray. | [
"Queries",
"for",
"binary",
"data"
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/protocol.py#L263-L287 |
KeplerGO/K2fov | K2fov/rotate.py | raDecFromVec | def raDecFromVec(v):
"""
Taken from
http://www.math.montana.edu/frankw/ccp/multiworld/multipleIVP/spherical/learn.htm
Search for "convert from Cartestion to spherical coordinates"
Adapted because I'm dealing with declination which is defined
with 90degrees at zenith
"""
#Ensure v is a normal vector
v /= np.linalg.norm(v)
ra_deg=0 #otherwise not in namespace0
dec_rad = np.arcsin(v[2])
s = np.hypot(v[0], v[1])
if s ==0:
ra_rad = 0
else:
ra_rad = np.arcsin(v[1]/s)
ra_deg = np.degrees(ra_rad)
if v[0] >= 0:
if v[1] >= 0:
pass
else:
ra_deg = 360 + ra_deg
else:
if v[1] > 0:
ra_deg = 180 - ra_deg
else:
ra_deg = 180 - ra_deg
raDec = ra_deg, np.degrees(dec_rad)
return np.array(raDec) | python | def raDecFromVec(v):
"""
Taken from
http://www.math.montana.edu/frankw/ccp/multiworld/multipleIVP/spherical/learn.htm
Search for "convert from Cartestion to spherical coordinates"
Adapted because I'm dealing with declination which is defined
with 90degrees at zenith
"""
#Ensure v is a normal vector
v /= np.linalg.norm(v)
ra_deg=0 #otherwise not in namespace0
dec_rad = np.arcsin(v[2])
s = np.hypot(v[0], v[1])
if s ==0:
ra_rad = 0
else:
ra_rad = np.arcsin(v[1]/s)
ra_deg = np.degrees(ra_rad)
if v[0] >= 0:
if v[1] >= 0:
pass
else:
ra_deg = 360 + ra_deg
else:
if v[1] > 0:
ra_deg = 180 - ra_deg
else:
ra_deg = 180 - ra_deg
raDec = ra_deg, np.degrees(dec_rad)
return np.array(raDec) | [
"def",
"raDecFromVec",
"(",
"v",
")",
":",
"#Ensure v is a normal vector",
"v",
"/=",
"np",
".",
"linalg",
".",
"norm",
"(",
"v",
")",
"ra_deg",
"=",
"0",
"#otherwise not in namespace0",
"dec_rad",
"=",
"np",
".",
"arcsin",
"(",
"v",
"[",
"2",
"]",
")",
... | Taken from
http://www.math.montana.edu/frankw/ccp/multiworld/multipleIVP/spherical/learn.htm
Search for "convert from Cartestion to spherical coordinates"
Adapted because I'm dealing with declination which is defined
with 90degrees at zenith | [
"Taken",
"from",
"http",
":",
"//",
"www",
".",
"math",
".",
"montana",
".",
"edu",
"/",
"frankw",
"/",
"ccp",
"/",
"multiworld",
"/",
"multipleIVP",
"/",
"spherical",
"/",
"learn",
".",
"htm",
"Search",
"for",
"convert",
"from",
"Cartestion",
"to",
"s... | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/rotate.py#L22-L55 |
KeplerGO/K2fov | K2fov/rotate.py | rotateAroundVector | def rotateAroundVector(v1, w, theta_deg):
"""Rotate vector v1 by an angle theta around w
Taken from https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation
(see Section "Rotating a vector")
Notes:
Rotating the x axis 90 degrees about the y axis gives -z
Rotating the x axis 90 degrees about the z axis gives +y
"""
ct = np.cos(np.radians(theta_deg))
st = np.sin(np.radians(theta_deg))
term1 = v1*ct
term2 = np.cross(w, v1) * st
term3 = np.dot(w, v1)
term3 = w * term3 * (1-ct)
return term1 + term2 + term3 | python | def rotateAroundVector(v1, w, theta_deg):
"""Rotate vector v1 by an angle theta around w
Taken from https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation
(see Section "Rotating a vector")
Notes:
Rotating the x axis 90 degrees about the y axis gives -z
Rotating the x axis 90 degrees about the z axis gives +y
"""
ct = np.cos(np.radians(theta_deg))
st = np.sin(np.radians(theta_deg))
term1 = v1*ct
term2 = np.cross(w, v1) * st
term3 = np.dot(w, v1)
term3 = w * term3 * (1-ct)
return term1 + term2 + term3 | [
"def",
"rotateAroundVector",
"(",
"v1",
",",
"w",
",",
"theta_deg",
")",
":",
"ct",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"theta_deg",
")",
")",
"st",
"=",
"np",
".",
"sin",
"(",
"np",
".",
"radians",
"(",
"theta_deg",
")",
")",
... | Rotate vector v1 by an angle theta around w
Taken from https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation
(see Section "Rotating a vector")
Notes:
Rotating the x axis 90 degrees about the y axis gives -z
Rotating the x axis 90 degrees about the z axis gives +y | [
"Rotate",
"vector",
"v1",
"by",
"an",
"angle",
"theta",
"around",
"w"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/rotate.py#L69-L87 |
KeplerGO/K2fov | K2fov/rotate.py | rotateInDeclination | def rotateInDeclination(v1, theta_deg):
"""Rotation is chosen so a rotation of 90 degrees from zenith
ends up at ra=0, dec=0"""
axis = np.array([0,-1,0])
return rotateAroundVector(v1, axis, theta_deg) | python | def rotateInDeclination(v1, theta_deg):
"""Rotation is chosen so a rotation of 90 degrees from zenith
ends up at ra=0, dec=0"""
axis = np.array([0,-1,0])
return rotateAroundVector(v1, axis, theta_deg) | [
"def",
"rotateInDeclination",
"(",
"v1",
",",
"theta_deg",
")",
":",
"axis",
"=",
"np",
".",
"array",
"(",
"[",
"0",
",",
"-",
"1",
",",
"0",
"]",
")",
"return",
"rotateAroundVector",
"(",
"v1",
",",
"axis",
",",
"theta_deg",
")"
] | Rotation is chosen so a rotation of 90 degrees from zenith
ends up at ra=0, dec=0 | [
"Rotation",
"is",
"chosen",
"so",
"a",
"rotation",
"of",
"90",
"degrees",
"from",
"zenith",
"ends",
"up",
"at",
"ra",
"=",
"0",
"dec",
"=",
"0"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/rotate.py#L90-L94 |
KeplerGO/K2fov | K2fov/rotate.py | declinationRotationMatrix | def declinationRotationMatrix(theta_deg):
"""Construct the rotation matrix for a rotation of the declination
coords (i.e around the axis of ra=90, dec=0)
Taken from Section 3.3 of Arfken and Weber (Eqn 3.91)
Modfied the signs of the sines so that a rotation of the zenith
vector by 90 degrees ends up at ra, dec = 0,0
"""
ct = np.cos(np.radians(theta_deg))
st = np.sin(np.radians(theta_deg))
mat = np.zeros((3,3))
mat[0,0] = ct
mat[0,2] = -st
mat[1,1] = 1
mat[2,0] = st
mat[2,2] = ct
return mat | python | def declinationRotationMatrix(theta_deg):
"""Construct the rotation matrix for a rotation of the declination
coords (i.e around the axis of ra=90, dec=0)
Taken from Section 3.3 of Arfken and Weber (Eqn 3.91)
Modfied the signs of the sines so that a rotation of the zenith
vector by 90 degrees ends up at ra, dec = 0,0
"""
ct = np.cos(np.radians(theta_deg))
st = np.sin(np.radians(theta_deg))
mat = np.zeros((3,3))
mat[0,0] = ct
mat[0,2] = -st
mat[1,1] = 1
mat[2,0] = st
mat[2,2] = ct
return mat | [
"def",
"declinationRotationMatrix",
"(",
"theta_deg",
")",
":",
"ct",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"theta_deg",
")",
")",
"st",
"=",
"np",
".",
"sin",
"(",
"np",
".",
"radians",
"(",
"theta_deg",
")",
")",
"mat",
"=",
"np"... | Construct the rotation matrix for a rotation of the declination
coords (i.e around the axis of ra=90, dec=0)
Taken from Section 3.3 of Arfken and Weber (Eqn 3.91)
Modfied the signs of the sines so that a rotation of the zenith
vector by 90 degrees ends up at ra, dec = 0,0 | [
"Construct",
"the",
"rotation",
"matrix",
"for",
"a",
"rotation",
"of",
"the",
"declination",
"coords",
"(",
"i",
".",
"e",
"around",
"the",
"axis",
"of",
"ra",
"=",
"90",
"dec",
"=",
"0",
")"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/rotate.py#L101-L121 |
p3trus/slave | slave/cryomagnetics/mps4g.py | MPS4G.sweep | def sweep(self, mode, speed=None):
"""Starts the output current sweep.
:param mode: The sweep mode. Valid entries are `'UP'`, `'DOWN'`,
`'PAUSE'`or `'ZERO'`. If in shim mode, `'LIMIT'` is valid as well.
:param speed: The sweeping speed. Valid entries are `'FAST'`, `'SLOW'`
or `None`.
"""
sweep_modes = ['UP', 'DOWN', 'PAUSE', 'ZERO', 'LIMIT']
sweep_speed = ['SLOW', 'FAST', None]
if not mode in sweep_modes:
raise ValueError('Invalid sweep mode.')
if not speed in sweep_speed:
raise ValueError('Invalid sweep speed.')
if speed is None:
self._write('SWEEP {0}'.format(mode))
else:
self._write('SWEEP {0} {1}'.format(mode, speed)) | python | def sweep(self, mode, speed=None):
"""Starts the output current sweep.
:param mode: The sweep mode. Valid entries are `'UP'`, `'DOWN'`,
`'PAUSE'`or `'ZERO'`. If in shim mode, `'LIMIT'` is valid as well.
:param speed: The sweeping speed. Valid entries are `'FAST'`, `'SLOW'`
or `None`.
"""
sweep_modes = ['UP', 'DOWN', 'PAUSE', 'ZERO', 'LIMIT']
sweep_speed = ['SLOW', 'FAST', None]
if not mode in sweep_modes:
raise ValueError('Invalid sweep mode.')
if not speed in sweep_speed:
raise ValueError('Invalid sweep speed.')
if speed is None:
self._write('SWEEP {0}'.format(mode))
else:
self._write('SWEEP {0} {1}'.format(mode, speed)) | [
"def",
"sweep",
"(",
"self",
",",
"mode",
",",
"speed",
"=",
"None",
")",
":",
"sweep_modes",
"=",
"[",
"'UP'",
",",
"'DOWN'",
",",
"'PAUSE'",
",",
"'ZERO'",
",",
"'LIMIT'",
"]",
"sweep_speed",
"=",
"[",
"'SLOW'",
",",
"'FAST'",
",",
"None",
"]",
"... | Starts the output current sweep.
:param mode: The sweep mode. Valid entries are `'UP'`, `'DOWN'`,
`'PAUSE'`or `'ZERO'`. If in shim mode, `'LIMIT'` is valid as well.
:param speed: The sweeping speed. Valid entries are `'FAST'`, `'SLOW'`
or `None`. | [
"Starts",
"the",
"output",
"current",
"sweep",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/cryomagnetics/mps4g.py#L224-L242 |
vladcalin/gemstone | gemstone/event/transport/base.py | BaseEventTransport.run_on_main_thread | def run_on_main_thread(self, func, args=None, kwargs=None):
"""
Runs the ``func`` callable on the main thread, by using the provided microservice
instance's IOLoop.
:param func: callable to run on the main thread
:param args: tuple or list with the positional arguments.
:param kwargs: dict with the keyword arguments.
:return:
"""
if not args:
args = ()
if not kwargs:
kwargs = {}
self.microservice.get_io_loop().add_callback(func, *args, **kwargs) | python | def run_on_main_thread(self, func, args=None, kwargs=None):
"""
Runs the ``func`` callable on the main thread, by using the provided microservice
instance's IOLoop.
:param func: callable to run on the main thread
:param args: tuple or list with the positional arguments.
:param kwargs: dict with the keyword arguments.
:return:
"""
if not args:
args = ()
if not kwargs:
kwargs = {}
self.microservice.get_io_loop().add_callback(func, *args, **kwargs) | [
"def",
"run_on_main_thread",
"(",
"self",
",",
"func",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"not",
"args",
":",
"args",
"=",
"(",
")",
"if",
"not",
"kwargs",
":",
"kwargs",
"=",
"{",
"}",
"self",
".",
"microservice"... | Runs the ``func`` callable on the main thread, by using the provided microservice
instance's IOLoop.
:param func: callable to run on the main thread
:param args: tuple or list with the positional arguments.
:param kwargs: dict with the keyword arguments.
:return: | [
"Runs",
"the",
"func",
"callable",
"on",
"the",
"main",
"thread",
"by",
"using",
"the",
"provided",
"microservice",
"instance",
"s",
"IOLoop",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/event/transport/base.py#L69-L83 |
KeplerGO/K2fov | K2fov/rotate2.py | rotateAboutVectorMatrix | def rotateAboutVectorMatrix(vec, theta_deg):
"""Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:
A matrix
To rotate a vector, premultiply by this matrix.
To rotate the coord sys underneath the vector, post multiply
"""
ct = np.cos(np.radians(theta_deg))
st = np.sin(np.radians(theta_deg))
# Ensure vector has normal length
vec /= np.linalg.norm(vec)
assert( np.all( np.isfinite(vec)))
# compute the three terms
term1 = ct * np.eye(3)
ucross = np.zeros( (3,3))
ucross[0] = [0, -vec[2], vec[1]]
ucross[1] = [vec[2], 0, -vec[0]]
ucross[2] = [-vec[1], vec[0], 0]
term2 = st*ucross
ufunny = np.zeros( (3,3))
for i in range(0,3):
for j in range(i,3):
ufunny[i,j] = vec[i]*vec[j]
ufunny[j,i] = ufunny[i,j]
term3 = (1-ct) * ufunny
return term1 + term2 + term3 | python | def rotateAboutVectorMatrix(vec, theta_deg):
"""Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:
A matrix
To rotate a vector, premultiply by this matrix.
To rotate the coord sys underneath the vector, post multiply
"""
ct = np.cos(np.radians(theta_deg))
st = np.sin(np.radians(theta_deg))
# Ensure vector has normal length
vec /= np.linalg.norm(vec)
assert( np.all( np.isfinite(vec)))
# compute the three terms
term1 = ct * np.eye(3)
ucross = np.zeros( (3,3))
ucross[0] = [0, -vec[2], vec[1]]
ucross[1] = [vec[2], 0, -vec[0]]
ucross[2] = [-vec[1], vec[0], 0]
term2 = st*ucross
ufunny = np.zeros( (3,3))
for i in range(0,3):
for j in range(i,3):
ufunny[i,j] = vec[i]*vec[j]
ufunny[j,i] = ufunny[i,j]
term3 = (1-ct) * ufunny
return term1 + term2 + term3 | [
"def",
"rotateAboutVectorMatrix",
"(",
"vec",
",",
"theta_deg",
")",
":",
"ct",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"theta_deg",
")",
")",
"st",
"=",
"np",
".",
"sin",
"(",
"np",
".",
"radians",
"(",
"theta_deg",
")",
")",
"# Ens... | Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:
A matrix
To rotate a vector, premultiply by this matrix.
To rotate the coord sys underneath the vector, post multiply | [
"Construct",
"the",
"matrix",
"that",
"rotates",
"vector",
"a",
"about",
"vector",
"vec",
"by",
"an",
"angle",
"of",
"theta_deg",
"degrees"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/rotate2.py#L128-L171 |
KeplerGO/K2fov | K2fov/rotate2.py | rotateInZMat | def rotateInZMat(theta_deg):
"""Rotate a vector theta degrees around the z-axis
Equivalent to yaw left
Rotates the vector in the sense that the x-axis is rotated
towards the y-axis. If looking along the z-axis (which is
not the way you usually look at it), the vector rotates
clockwise.
If sitting on the vector [1,0,0], the rotation is towards the left
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:
A matrix
To rotate a vector, premultiply by this matrix.
To rotate the coord sys underneath the vector, post multiply
"""
ct = np.cos( np.radians(theta_deg))
st = np.sin( np.radians(theta_deg))
rMat = np.array([ [ ct, -st, 0],
[ st, ct, 0],
[ 0, 0, 1],
])
return rMat | python | def rotateInZMat(theta_deg):
"""Rotate a vector theta degrees around the z-axis
Equivalent to yaw left
Rotates the vector in the sense that the x-axis is rotated
towards the y-axis. If looking along the z-axis (which is
not the way you usually look at it), the vector rotates
clockwise.
If sitting on the vector [1,0,0], the rotation is towards the left
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:
A matrix
To rotate a vector, premultiply by this matrix.
To rotate the coord sys underneath the vector, post multiply
"""
ct = np.cos( np.radians(theta_deg))
st = np.sin( np.radians(theta_deg))
rMat = np.array([ [ ct, -st, 0],
[ st, ct, 0],
[ 0, 0, 1],
])
return rMat | [
"def",
"rotateInZMat",
"(",
"theta_deg",
")",
":",
"ct",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"theta_deg",
")",
")",
"st",
"=",
"np",
".",
"sin",
"(",
"np",
".",
"radians",
"(",
"theta_deg",
")",
")",
"rMat",
"=",
"np",
".",
"... | Rotate a vector theta degrees around the z-axis
Equivalent to yaw left
Rotates the vector in the sense that the x-axis is rotated
towards the y-axis. If looking along the z-axis (which is
not the way you usually look at it), the vector rotates
clockwise.
If sitting on the vector [1,0,0], the rotation is towards the left
Input:
theta_deg (float) Angle through which vectors should be
rotated in degrees
Returns:
A matrix
To rotate a vector, premultiply by this matrix.
To rotate the coord sys underneath the vector, post multiply | [
"Rotate",
"a",
"vector",
"theta",
"degrees",
"around",
"the",
"z",
"-",
"axis"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/rotate2.py#L174-L205 |
mishbahr/djangocms-twitter2 | djangocms_twitter/templatetags/djangocms_twitter.py | urlize_tweet | def urlize_tweet(tweet):
""" Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
Replace shortened URLs with long URLs in the twitter status,
and add the "RT" flag. Should be used before urlize_tweet
"""
if tweet['retweeted']:
text = 'RT {user}: {text}'.format(
user=TWITTER_USERNAME_URL.format(screen_name=tweet['user']['screen_name']),
text=tweet['text'])
else:
text = tweet['text']
for hashtag in tweet['entities']['hashtags']:
text = text.replace(
'#%s' % hashtag['text'],
TWITTER_HASHTAG_URL.format(hashtag=hashtag['text']))
for mention in tweet['entities']['user_mentions']:
text = text.replace(
'@%s' % mention['screen_name'],
TWITTER_USERNAME_URL.format(screen_name=mention['screen_name']))
urls = tweet['entities']['urls']
for url in urls:
text = text.replace(
url['url'], TWITTER_URL.format(
url=url['expanded_url'], display_url=url['display_url']))
if 'media' in tweet['entities']:
for media in tweet['entities']['media']:
text = text.replace(
media['url'],
TWITTER_MEDIA_URL.format(
url=media['expanded_url'],
display_url=media['display_url']))
return mark_safe(text) | python | def urlize_tweet(tweet):
""" Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
Replace shortened URLs with long URLs in the twitter status,
and add the "RT" flag. Should be used before urlize_tweet
"""
if tweet['retweeted']:
text = 'RT {user}: {text}'.format(
user=TWITTER_USERNAME_URL.format(screen_name=tweet['user']['screen_name']),
text=tweet['text'])
else:
text = tweet['text']
for hashtag in tweet['entities']['hashtags']:
text = text.replace(
'#%s' % hashtag['text'],
TWITTER_HASHTAG_URL.format(hashtag=hashtag['text']))
for mention in tweet['entities']['user_mentions']:
text = text.replace(
'@%s' % mention['screen_name'],
TWITTER_USERNAME_URL.format(screen_name=mention['screen_name']))
urls = tweet['entities']['urls']
for url in urls:
text = text.replace(
url['url'], TWITTER_URL.format(
url=url['expanded_url'], display_url=url['display_url']))
if 'media' in tweet['entities']:
for media in tweet['entities']['media']:
text = text.replace(
media['url'],
TWITTER_MEDIA_URL.format(
url=media['expanded_url'],
display_url=media['display_url']))
return mark_safe(text) | [
"def",
"urlize_tweet",
"(",
"tweet",
")",
":",
"if",
"tweet",
"[",
"'retweeted'",
"]",
":",
"text",
"=",
"'RT {user}: {text}'",
".",
"format",
"(",
"user",
"=",
"TWITTER_USERNAME_URL",
".",
"format",
"(",
"screen_name",
"=",
"tweet",
"[",
"'user'",
"]",
"[... | Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
Replace shortened URLs with long URLs in the twitter status,
and add the "RT" flag. Should be used before urlize_tweet | [
"Turn",
"#hashtag",
"and",
"@username",
"in",
"a",
"text",
"to",
"Twitter",
"hyperlinks",
"similar",
"to",
"the",
"urlize",
"()",
"function",
"in",
"Django",
"."
] | train | https://github.com/mishbahr/djangocms-twitter2/blob/01b6f63f812ceee80c0b6ffe8bddbd52723fd71a/djangocms_twitter/templatetags/djangocms_twitter.py#L26-L64 |
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | SqlDAM.getReadSession | def getReadSession(self):
''' return scopted session '''
if self.ReadSession is None:
self.ReadSession=scoped_session(sessionmaker(bind=self.engine))
return self.ReadSession | python | def getReadSession(self):
''' return scopted session '''
if self.ReadSession is None:
self.ReadSession=scoped_session(sessionmaker(bind=self.engine))
return self.ReadSession | [
"def",
"getReadSession",
"(",
"self",
")",
":",
"if",
"self",
".",
"ReadSession",
"is",
"None",
":",
"self",
".",
"ReadSession",
"=",
"scoped_session",
"(",
"sessionmaker",
"(",
"bind",
"=",
"self",
".",
"engine",
")",
")",
"return",
"self",
".",
"ReadSe... | return scopted session | [
"return",
"scopted",
"session"
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L56-L61 |
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | SqlDAM.getWriteSession | def getWriteSession(self):
''' return unscope session, TODO, make it clear '''
if self.WriteSession is None:
self.WriteSession=sessionmaker(bind=self.engine)
self.writeSession=self.WriteSession()
return self.writeSession | python | def getWriteSession(self):
''' return unscope session, TODO, make it clear '''
if self.WriteSession is None:
self.WriteSession=sessionmaker(bind=self.engine)
self.writeSession=self.WriteSession()
return self.writeSession | [
"def",
"getWriteSession",
"(",
"self",
")",
":",
"if",
"self",
".",
"WriteSession",
"is",
"None",
":",
"self",
".",
"WriteSession",
"=",
"sessionmaker",
"(",
"bind",
"=",
"self",
".",
"engine",
")",
"self",
".",
"writeSession",
"=",
"self",
".",
"WriteSe... | return unscope session, TODO, make it clear | [
"return",
"unscope",
"session",
"TODO",
"make",
"it",
"clear"
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L63-L69 |
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | SqlDAM.readTupleQuotes | def readTupleQuotes(self, symbol, start, end):
''' read quotes as tuple '''
if end is None:
end=sys.maxint
session=self.getReadSession()()
try:
rows=session.query(Quote).filter(and_(Quote.symbol == symbol,
Quote.time >= int(start),
Quote.time < int(end)))
finally:
self.getReadSession().remove()
return rows | python | def readTupleQuotes(self, symbol, start, end):
''' read quotes as tuple '''
if end is None:
end=sys.maxint
session=self.getReadSession()()
try:
rows=session.query(Quote).filter(and_(Quote.symbol == symbol,
Quote.time >= int(start),
Quote.time < int(end)))
finally:
self.getReadSession().remove()
return rows | [
"def",
"readTupleQuotes",
"(",
"self",
",",
"symbol",
",",
"start",
",",
"end",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"sys",
".",
"maxint",
"session",
"=",
"self",
".",
"getReadSession",
"(",
")",
"(",
")",
"try",
":",
"rows",
"=",
... | read quotes as tuple | [
"read",
"quotes",
"as",
"tuple"
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L86-L99 |
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | SqlDAM.readBatchTupleQuotes | def readBatchTupleQuotes(self, symbols, start, end):
'''
read batch quotes as tuple to save memory
'''
if end is None:
end=sys.maxint
ret={}
session=self.getReadSession()()
try:
symbolChunks=splitListEqually(symbols, 100)
for chunk in symbolChunks:
rows=session.query(Quote.symbol, Quote.time, Quote.close, Quote.volume,
Quote.low, Quote.high).filter(and_(Quote.symbol.in_(chunk),
Quote.time >= int(start),
Quote.time < int(end)))
for row in rows:
if row.time not in ret:
ret[row.time]={}
ret[row.time][row.symbol]=self.__sqlToTupleQuote(row)
finally:
self.getReadSession().remove()
return ret | python | def readBatchTupleQuotes(self, symbols, start, end):
'''
read batch quotes as tuple to save memory
'''
if end is None:
end=sys.maxint
ret={}
session=self.getReadSession()()
try:
symbolChunks=splitListEqually(symbols, 100)
for chunk in symbolChunks:
rows=session.query(Quote.symbol, Quote.time, Quote.close, Quote.volume,
Quote.low, Quote.high).filter(and_(Quote.symbol.in_(chunk),
Quote.time >= int(start),
Quote.time < int(end)))
for row in rows:
if row.time not in ret:
ret[row.time]={}
ret[row.time][row.symbol]=self.__sqlToTupleQuote(row)
finally:
self.getReadSession().remove()
return ret | [
"def",
"readBatchTupleQuotes",
"(",
"self",
",",
"symbols",
",",
"start",
",",
"end",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"sys",
".",
"maxint",
"ret",
"=",
"{",
"}",
"session",
"=",
"self",
".",
"getReadSession",
"(",
")",
"(",
")... | read batch quotes as tuple to save memory | [
"read",
"batch",
"quotes",
"as",
"tuple",
"to",
"save",
"memory"
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L101-L126 |
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | SqlDAM.read_tuple_ticks | def read_tuple_ticks(self, symbol, start, end):
''' read ticks as tuple '''
if end is None:
end=sys.maxint
session=self.getReadSession()()
try:
rows=session.query(Tick).filter(and_(Tick.symbol == symbol,
Tick.time >= int(start),
Tick.time < int(end)))
finally:
self.getReadSession().remove()
return [self.__sqlToTupleTick(row) for row in rows] | python | def read_tuple_ticks(self, symbol, start, end):
''' read ticks as tuple '''
if end is None:
end=sys.maxint
session=self.getReadSession()()
try:
rows=session.query(Tick).filter(and_(Tick.symbol == symbol,
Tick.time >= int(start),
Tick.time < int(end)))
finally:
self.getReadSession().remove()
return [self.__sqlToTupleTick(row) for row in rows] | [
"def",
"read_tuple_ticks",
"(",
"self",
",",
"symbol",
",",
"start",
",",
"end",
")",
":",
"if",
"end",
"is",
"None",
":",
"end",
"=",
"sys",
".",
"maxint",
"session",
"=",
"self",
".",
"getReadSession",
"(",
")",
"(",
")",
"try",
":",
"rows",
"=",... | read ticks as tuple | [
"read",
"ticks",
"as",
"tuple"
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L128-L141 |
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | SqlDAM.write_quotes | def write_quotes(self, quotes):
''' write quotes '''
if self.first:
Base.metadata.create_all(self.engine, checkfirst=True)
self.first=False
session=self.getWriteSession()
session.add_all([self.__quoteToSql(quote) for quote in quotes]) | python | def write_quotes(self, quotes):
''' write quotes '''
if self.first:
Base.metadata.create_all(self.engine, checkfirst=True)
self.first=False
session=self.getWriteSession()
session.add_all([self.__quoteToSql(quote) for quote in quotes]) | [
"def",
"write_quotes",
"(",
"self",
",",
"quotes",
")",
":",
"if",
"self",
".",
"first",
":",
"Base",
".",
"metadata",
".",
"create_all",
"(",
"self",
".",
"engine",
",",
"checkfirst",
"=",
"True",
")",
"self",
".",
"first",
"=",
"False",
"session",
... | write quotes | [
"write",
"quotes"
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L158-L165 |
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | SqlDAM.write_ticks | def write_ticks(self, ticks):
''' write ticks '''
if self.first:
Base.metadata.create_all(self.engine, checkfirst=True)
self.first=False
session=self.getWriteSession()
session.add_all([self.__tickToSql(tick) for tick in ticks]) | python | def write_ticks(self, ticks):
''' write ticks '''
if self.first:
Base.metadata.create_all(self.engine, checkfirst=True)
self.first=False
session=self.getWriteSession()
session.add_all([self.__tickToSql(tick) for tick in ticks]) | [
"def",
"write_ticks",
"(",
"self",
",",
"ticks",
")",
":",
"if",
"self",
".",
"first",
":",
"Base",
".",
"metadata",
".",
"create_all",
"(",
"self",
".",
"engine",
",",
"checkfirst",
"=",
"True",
")",
"self",
".",
"first",
"=",
"False",
"session",
"=... | write ticks | [
"write",
"ticks"
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L167-L174 |
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | SqlDAM.write_fundamental | def write_fundamental(self, keyTimeValueDict):
''' write fundamental '''
if self.first:
Base.metadata.create_all(self.__getEngine(), checkfirst=True)
self.first=False
sqls=self._fundamentalToSqls(keyTimeValueDict)
session=self.Session()
try:
session.add_all(sqls)
finally:
self.Session.remove() | python | def write_fundamental(self, keyTimeValueDict):
''' write fundamental '''
if self.first:
Base.metadata.create_all(self.__getEngine(), checkfirst=True)
self.first=False
sqls=self._fundamentalToSqls(keyTimeValueDict)
session=self.Session()
try:
session.add_all(sqls)
finally:
self.Session.remove() | [
"def",
"write_fundamental",
"(",
"self",
",",
"keyTimeValueDict",
")",
":",
"if",
"self",
".",
"first",
":",
"Base",
".",
"metadata",
".",
"create_all",
"(",
"self",
".",
"__getEngine",
"(",
")",
",",
"checkfirst",
"=",
"True",
")",
"self",
".",
"first",... | write fundamental | [
"write",
"fundamental"
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L181-L192 |
llazzaro/analyzerdam | analyzerdam/sqlDAM.py | SqlDAM._fundamentalToSqls | def _fundamentalToSqls(self, symbol, keyTimeValueDict):
''' convert fundament dict to sqls '''
sqls=[]
for key, timeValues in keyTimeValueDict.iteritems():
for timeStamp, value in timeValues.iteritems():
sqls.append(FmSql(symbol, key, timeStamp, value))
return sqls | python | def _fundamentalToSqls(self, symbol, keyTimeValueDict):
''' convert fundament dict to sqls '''
sqls=[]
for key, timeValues in keyTimeValueDict.iteritems():
for timeStamp, value in timeValues.iteritems():
sqls.append(FmSql(symbol, key, timeStamp, value))
return sqls | [
"def",
"_fundamentalToSqls",
"(",
"self",
",",
"symbol",
",",
"keyTimeValueDict",
")",
":",
"sqls",
"=",
"[",
"]",
"for",
"key",
",",
"timeValues",
"in",
"keyTimeValueDict",
".",
"iteritems",
"(",
")",
":",
"for",
"timeStamp",
",",
"value",
"in",
"timeValu... | convert fundament dict to sqls | [
"convert",
"fundament",
"dict",
"to",
"sqls"
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/sqlDAM.py#L208-L215 |
p3trus/slave | slave/lakeshore/ls340.py | Curve.delete | def delete(self):
"""Deletes the current curve.
:raises RuntimeError: Raises when` when one tries to delete a read-only
curve.
"""
if self._writeable:
self._write(('CRVDEL', Integer), self.idx)
else:
raise RuntimeError('Can not delete read-only curves.') | python | def delete(self):
"""Deletes the current curve.
:raises RuntimeError: Raises when` when one tries to delete a read-only
curve.
"""
if self._writeable:
self._write(('CRVDEL', Integer), self.idx)
else:
raise RuntimeError('Can not delete read-only curves.') | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writeable",
":",
"self",
".",
"_write",
"(",
"(",
"'CRVDEL'",
",",
"Integer",
")",
",",
"self",
".",
"idx",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'Can not delete read-only curves.'",
... | Deletes the current curve.
:raises RuntimeError: Raises when` when one tries to delete a read-only
curve. | [
"Deletes",
"the",
"current",
"curve",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/lakeshore/ls340.py#L163-L173 |
p3trus/slave | slave/lakeshore/ls340.py | Program.line | def line(self, idx):
"""Return the i'th program line.
:param i: The i'th program line.
"""
# TODO: We should parse the response properly.
return self._query(('PGM?', [Integer, Integer], String), self.idx, idx) | python | def line(self, idx):
"""Return the i'th program line.
:param i: The i'th program line.
"""
# TODO: We should parse the response properly.
return self._query(('PGM?', [Integer, Integer], String), self.idx, idx) | [
"def",
"line",
"(",
"self",
",",
"idx",
")",
":",
"# TODO: We should parse the response properly.",
"return",
"self",
".",
"_query",
"(",
"(",
"'PGM?'",
",",
"[",
"Integer",
",",
"Integer",
"]",
",",
"String",
")",
",",
"self",
".",
"idx",
",",
"idx",
")... | Return the i'th program line.
:param i: The i'th program line. | [
"Return",
"the",
"i",
"th",
"program",
"line",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/lakeshore/ls340.py#L419-L426 |
p3trus/slave | slave/lakeshore/ls340.py | Program.append_line | def append_line(self, new_line):
"""Appends the new_line to the LS340 program."""
# TODO: The user still has to write the raw line, this is error prone.
self._write(('PGM', [Integer, String]), self.idx, new_line) | python | def append_line(self, new_line):
"""Appends the new_line to the LS340 program."""
# TODO: The user still has to write the raw line, this is error prone.
self._write(('PGM', [Integer, String]), self.idx, new_line) | [
"def",
"append_line",
"(",
"self",
",",
"new_line",
")",
":",
"# TODO: The user still has to write the raw line, this is error prone.",
"self",
".",
"_write",
"(",
"(",
"'PGM'",
",",
"[",
"Integer",
",",
"String",
"]",
")",
",",
"self",
".",
"idx",
",",
"new_lin... | Appends the new_line to the LS340 program. | [
"Appends",
"the",
"new_line",
"to",
"the",
"LS340",
"program",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/lakeshore/ls340.py#L428-L431 |
p3trus/slave | slave/lakeshore/ls340.py | LS340.softcal | def softcal(self, std, dest, serial, T1, U1, T2, U2, T3=None, U3=None):
"""Generates a softcal curve.
:param std: The standard curve index used to calculate the softcal
curve. Valid entries are 1-20
:param dest: The user curve index where the softcal curve is stored.
Valid entries are 21-60.
:param serial: The serial number of the new curve. A maximum of 10
characters is allowed.
:param T1: The first temperature point.
:param U1: The first sensor units point.
:param T2: The second temperature point.
:param U2: The second sensor units point.
:param T3: The third temperature point. Default: `None`.
:param U3: The third sensor units point. Default: `None`.
"""
args = [std, dest, serial, T1, U1, T2, U2]
dtype = [Integer(min=1, max=21), Integer(min=21, max=61), String(max=10), Float, Float, Float, Float]
if (T3 is not None) and (U3 is not None):
args.extend([T3, U3])
dtype.extend([Float, Float])
self._write(('SCAL', dtype), *args) | python | def softcal(self, std, dest, serial, T1, U1, T2, U2, T3=None, U3=None):
"""Generates a softcal curve.
:param std: The standard curve index used to calculate the softcal
curve. Valid entries are 1-20
:param dest: The user curve index where the softcal curve is stored.
Valid entries are 21-60.
:param serial: The serial number of the new curve. A maximum of 10
characters is allowed.
:param T1: The first temperature point.
:param U1: The first sensor units point.
:param T2: The second temperature point.
:param U2: The second sensor units point.
:param T3: The third temperature point. Default: `None`.
:param U3: The third sensor units point. Default: `None`.
"""
args = [std, dest, serial, T1, U1, T2, U2]
dtype = [Integer(min=1, max=21), Integer(min=21, max=61), String(max=10), Float, Float, Float, Float]
if (T3 is not None) and (U3 is not None):
args.extend([T3, U3])
dtype.extend([Float, Float])
self._write(('SCAL', dtype), *args) | [
"def",
"softcal",
"(",
"self",
",",
"std",
",",
"dest",
",",
"serial",
",",
"T1",
",",
"U1",
",",
"T2",
",",
"U2",
",",
"T3",
"=",
"None",
",",
"U3",
"=",
"None",
")",
":",
"args",
"=",
"[",
"std",
",",
"dest",
",",
"serial",
",",
"T1",
","... | Generates a softcal curve.
:param std: The standard curve index used to calculate the softcal
curve. Valid entries are 1-20
:param dest: The user curve index where the softcal curve is stored.
Valid entries are 21-60.
:param serial: The serial number of the new curve. A maximum of 10
characters is allowed.
:param T1: The first temperature point.
:param U1: The first sensor units point.
:param T2: The second temperature point.
:param U2: The second sensor units point.
:param T3: The third temperature point. Default: `None`.
:param U3: The third sensor units point. Default: `None`. | [
"Generates",
"a",
"softcal",
"curve",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/lakeshore/ls340.py#L899-L921 |
twisted/mantissa | xmantissa/people.py | makeThumbnail | def makeThumbnail(inputFile, outputFile, thumbnailSize, outputFormat='jpeg'):
"""
Make a thumbnail of the image stored at C{inputPath}, preserving its
aspect ratio, and write the result to C{outputPath}.
@param inputFile: The image file (or path to the file) to thumbnail.
@type inputFile: C{file} or C{str}
@param outputFile: The file (or path to the file) to write the thumbnail
to.
@type outputFile: C{file} or C{str}
@param thumbnailSize: The maximum length (in pixels) of the longest side of
the thumbnail image.
@type thumbnailSize: C{int}
@param outputFormat: The C{format} argument to pass to L{Image.save}.
Defaults to I{jpeg}.
@type format: C{str}
"""
if Image is None:
# throw the ImportError here
import PIL
image = Image.open(inputFile)
# Resize needed?
if thumbnailSize < max(image.size):
# Convert bilevel and paletted images to grayscale and RGB respectively;
# otherwise PIL silently switches to Image.NEAREST sampling.
if image.mode == '1':
image = image.convert('L')
elif image.mode == 'P':
image = image.convert('RGB')
image.thumbnail((thumbnailSize, thumbnailSize), Image.ANTIALIAS)
image.save(outputFile, outputFormat) | python | def makeThumbnail(inputFile, outputFile, thumbnailSize, outputFormat='jpeg'):
"""
Make a thumbnail of the image stored at C{inputPath}, preserving its
aspect ratio, and write the result to C{outputPath}.
@param inputFile: The image file (or path to the file) to thumbnail.
@type inputFile: C{file} or C{str}
@param outputFile: The file (or path to the file) to write the thumbnail
to.
@type outputFile: C{file} or C{str}
@param thumbnailSize: The maximum length (in pixels) of the longest side of
the thumbnail image.
@type thumbnailSize: C{int}
@param outputFormat: The C{format} argument to pass to L{Image.save}.
Defaults to I{jpeg}.
@type format: C{str}
"""
if Image is None:
# throw the ImportError here
import PIL
image = Image.open(inputFile)
# Resize needed?
if thumbnailSize < max(image.size):
# Convert bilevel and paletted images to grayscale and RGB respectively;
# otherwise PIL silently switches to Image.NEAREST sampling.
if image.mode == '1':
image = image.convert('L')
elif image.mode == 'P':
image = image.convert('RGB')
image.thumbnail((thumbnailSize, thumbnailSize), Image.ANTIALIAS)
image.save(outputFile, outputFormat) | [
"def",
"makeThumbnail",
"(",
"inputFile",
",",
"outputFile",
",",
"thumbnailSize",
",",
"outputFormat",
"=",
"'jpeg'",
")",
":",
"if",
"Image",
"is",
"None",
":",
"# throw the ImportError here",
"import",
"PIL",
"image",
"=",
"Image",
".",
"open",
"(",
"inputF... | Make a thumbnail of the image stored at C{inputPath}, preserving its
aspect ratio, and write the result to C{outputPath}.
@param inputFile: The image file (or path to the file) to thumbnail.
@type inputFile: C{file} or C{str}
@param outputFile: The file (or path to the file) to write the thumbnail
to.
@type outputFile: C{file} or C{str}
@param thumbnailSize: The maximum length (in pixels) of the longest side of
the thumbnail image.
@type thumbnailSize: C{int}
@param outputFormat: The C{format} argument to pass to L{Image.save}.
Defaults to I{jpeg}.
@type format: C{str} | [
"Make",
"a",
"thumbnail",
"of",
"the",
"image",
"stored",
"at",
"C",
"{",
"inputPath",
"}",
"preserving",
"its",
"aspect",
"ratio",
"and",
"write",
"the",
"result",
"to",
"C",
"{",
"outputPath",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L57-L90 |
twisted/mantissa | xmantissa/people.py | _descriptiveIdentifier | def _descriptiveIdentifier(contactType):
"""
Get a descriptive identifier for C{contactType}, taking into account the
fact that it might not have implemented the C{descriptiveIdentifier}
method.
@type contactType: L{IContactType} provider.
@rtype: C{unicode}
"""
descriptiveIdentifierMethod = getattr(
contactType, 'descriptiveIdentifier', None)
if descriptiveIdentifierMethod is not None:
return descriptiveIdentifierMethod()
warn(
"IContactType now has the 'descriptiveIdentifier'"
" method, %s did not implement it" % (contactType.__class__,),
category=PendingDeprecationWarning)
return _objectToName(contactType).decode('ascii') | python | def _descriptiveIdentifier(contactType):
"""
Get a descriptive identifier for C{contactType}, taking into account the
fact that it might not have implemented the C{descriptiveIdentifier}
method.
@type contactType: L{IContactType} provider.
@rtype: C{unicode}
"""
descriptiveIdentifierMethod = getattr(
contactType, 'descriptiveIdentifier', None)
if descriptiveIdentifierMethod is not None:
return descriptiveIdentifierMethod()
warn(
"IContactType now has the 'descriptiveIdentifier'"
" method, %s did not implement it" % (contactType.__class__,),
category=PendingDeprecationWarning)
return _objectToName(contactType).decode('ascii') | [
"def",
"_descriptiveIdentifier",
"(",
"contactType",
")",
":",
"descriptiveIdentifierMethod",
"=",
"getattr",
"(",
"contactType",
",",
"'descriptiveIdentifier'",
",",
"None",
")",
"if",
"descriptiveIdentifierMethod",
"is",
"not",
"None",
":",
"return",
"descriptiveIdent... | Get a descriptive identifier for C{contactType}, taking into account the
fact that it might not have implemented the C{descriptiveIdentifier}
method.
@type contactType: L{IContactType} provider.
@rtype: C{unicode} | [
"Get",
"a",
"descriptive",
"identifier",
"for",
"C",
"{",
"contactType",
"}",
"taking",
"into",
"account",
"the",
"fact",
"that",
"it",
"might",
"not",
"have",
"implemented",
"the",
"C",
"{",
"descriptiveIdentifier",
"}",
"method",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L116-L134 |
twisted/mantissa | xmantissa/people.py | _organizerPluginName | def _organizerPluginName(plugin):
"""
Get a name for C{plugin}, taking into account the fact that it might not
have defined L{IOrganizerPlugin.name}.
@type plugin: L{IOrganizerPlugin} provider.
@rtype: C{unicode}
"""
name = getattr(plugin, 'name', None)
if name is not None:
return name
warn(
"IOrganizerPlugin now has the 'name' attribute"
" and %s does not define it" % (plugin.__class__,),
category=PendingDeprecationWarning)
return _objectToName(plugin).decode('ascii') | python | def _organizerPluginName(plugin):
"""
Get a name for C{plugin}, taking into account the fact that it might not
have defined L{IOrganizerPlugin.name}.
@type plugin: L{IOrganizerPlugin} provider.
@rtype: C{unicode}
"""
name = getattr(plugin, 'name', None)
if name is not None:
return name
warn(
"IOrganizerPlugin now has the 'name' attribute"
" and %s does not define it" % (plugin.__class__,),
category=PendingDeprecationWarning)
return _objectToName(plugin).decode('ascii') | [
"def",
"_organizerPluginName",
"(",
"plugin",
")",
":",
"name",
"=",
"getattr",
"(",
"plugin",
",",
"'name'",
",",
"None",
")",
"if",
"name",
"is",
"not",
"None",
":",
"return",
"name",
"warn",
"(",
"\"IOrganizerPlugin now has the 'name' attribute\"",
"\" and %s... | Get a name for C{plugin}, taking into account the fact that it might not
have defined L{IOrganizerPlugin.name}.
@type plugin: L{IOrganizerPlugin} provider.
@rtype: C{unicode} | [
"Get",
"a",
"name",
"for",
"C",
"{",
"plugin",
"}",
"taking",
"into",
"account",
"the",
"fact",
"that",
"it",
"might",
"not",
"have",
"defined",
"L",
"{",
"IOrganizerPlugin",
".",
"name",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L138-L154 |
twisted/mantissa | xmantissa/people.py | _stringifyKeys | def _stringifyKeys(d):
"""
Return a copy of C{d} with C{str} keys.
@type d: C{dict} with C{unicode} keys.
@rtype: C{dict} with C{str} keys.
"""
return dict((k.encode('ascii'), v) for (k, v) in d.iteritems()) | python | def _stringifyKeys(d):
"""
Return a copy of C{d} with C{str} keys.
@type d: C{dict} with C{unicode} keys.
@rtype: C{dict} with C{str} keys.
"""
return dict((k.encode('ascii'), v) for (k, v) in d.iteritems()) | [
"def",
"_stringifyKeys",
"(",
"d",
")",
":",
"return",
"dict",
"(",
"(",
"k",
".",
"encode",
"(",
"'ascii'",
")",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"d",
".",
"iteritems",
"(",
")",
")"
] | Return a copy of C{d} with C{str} keys.
@type d: C{dict} with C{unicode} keys.
@rtype: C{dict} with C{str} keys. | [
"Return",
"a",
"copy",
"of",
"C",
"{",
"d",
"}",
"with",
"C",
"{",
"str",
"}",
"keys",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L599-L606 |
twisted/mantissa | xmantissa/people.py | mugshot1to2 | def mugshot1to2(old):
"""
Upgrader for L{Mugshot} from version 1 to version 2, which sets the
C{smallerBody} attribute to the path of a smaller mugshot image.
"""
smallerBody = Mugshot.makeThumbnail(old.body.open(),
old.person,
old.type.split('/')[1],
smaller=True)
return old.upgradeVersion(Mugshot.typeName, 1, 2,
person=old.person,
type=old.type,
body=old.body,
smallerBody=smallerBody) | python | def mugshot1to2(old):
"""
Upgrader for L{Mugshot} from version 1 to version 2, which sets the
C{smallerBody} attribute to the path of a smaller mugshot image.
"""
smallerBody = Mugshot.makeThumbnail(old.body.open(),
old.person,
old.type.split('/')[1],
smaller=True)
return old.upgradeVersion(Mugshot.typeName, 1, 2,
person=old.person,
type=old.type,
body=old.body,
smallerBody=smallerBody) | [
"def",
"mugshot1to2",
"(",
"old",
")",
":",
"smallerBody",
"=",
"Mugshot",
".",
"makeThumbnail",
"(",
"old",
".",
"body",
".",
"open",
"(",
")",
",",
"old",
".",
"person",
",",
"old",
".",
"type",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
","... | Upgrader for L{Mugshot} from version 1 to version 2, which sets the
C{smallerBody} attribute to the path of a smaller mugshot image. | [
"Upgrader",
"for",
"L",
"{",
"Mugshot",
"}",
"from",
"version",
"1",
"to",
"version",
"2",
"which",
"sets",
"the",
"C",
"{",
"smallerBody",
"}",
"attribute",
"to",
"the",
"path",
"of",
"a",
"smaller",
"mugshot",
"image",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2651-L2665 |
twisted/mantissa | xmantissa/people.py | mugshot2to3 | def mugshot2to3(old):
"""
Upgrader for L{Mugshot} from version 2 to version 3, which re-thumbnails
the mugshot to take into account the new value of L{Mugshot.smallerSize}.
"""
new = old.upgradeVersion(Mugshot.typeName, 2, 3,
person=old.person,
type=old.type,
body=old.body,
smallerBody=old.smallerBody)
new.smallerBody = new.makeThumbnail(
new.body.open(), new.person, new.type[len('image/'):], smaller=True)
return new | python | def mugshot2to3(old):
"""
Upgrader for L{Mugshot} from version 2 to version 3, which re-thumbnails
the mugshot to take into account the new value of L{Mugshot.smallerSize}.
"""
new = old.upgradeVersion(Mugshot.typeName, 2, 3,
person=old.person,
type=old.type,
body=old.body,
smallerBody=old.smallerBody)
new.smallerBody = new.makeThumbnail(
new.body.open(), new.person, new.type[len('image/'):], smaller=True)
return new | [
"def",
"mugshot2to3",
"(",
"old",
")",
":",
"new",
"=",
"old",
".",
"upgradeVersion",
"(",
"Mugshot",
".",
"typeName",
",",
"2",
",",
"3",
",",
"person",
"=",
"old",
".",
"person",
",",
"type",
"=",
"old",
".",
"type",
",",
"body",
"=",
"old",
".... | Upgrader for L{Mugshot} from version 2 to version 3, which re-thumbnails
the mugshot to take into account the new value of L{Mugshot.smallerSize}. | [
"Upgrader",
"for",
"L",
"{",
"Mugshot",
"}",
"from",
"version",
"2",
"to",
"version",
"3",
"which",
"re",
"-",
"thumbnails",
"the",
"mugshot",
"to",
"take",
"into",
"account",
"the",
"new",
"value",
"of",
"L",
"{",
"Mugshot",
".",
"smallerSize",
"}",
"... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2681-L2693 |
twisted/mantissa | xmantissa/people.py | VIPPersonContactType.getParameters | def getParameters(self, contactItem):
"""
Return a list containing a single parameter suitable for changing the
VIP status of a person.
@type contactItem: L{_PersonVIPStatus}
@rtype: C{list} of L{liveform.Parameter}
"""
isVIP = False # default
if contactItem is not None:
isVIP = contactItem.person.vip
return [liveform.Parameter(
'vip', liveform.CHECKBOX_INPUT, bool, 'VIP', default=isVIP)] | python | def getParameters(self, contactItem):
"""
Return a list containing a single parameter suitable for changing the
VIP status of a person.
@type contactItem: L{_PersonVIPStatus}
@rtype: C{list} of L{liveform.Parameter}
"""
isVIP = False # default
if contactItem is not None:
isVIP = contactItem.person.vip
return [liveform.Parameter(
'vip', liveform.CHECKBOX_INPUT, bool, 'VIP', default=isVIP)] | [
"def",
"getParameters",
"(",
"self",
",",
"contactItem",
")",
":",
"isVIP",
"=",
"False",
"# default",
"if",
"contactItem",
"is",
"not",
"None",
":",
"isVIP",
"=",
"contactItem",
".",
"person",
".",
"vip",
"return",
"[",
"liveform",
".",
"Parameter",
"(",
... | Return a list containing a single parameter suitable for changing the
VIP status of a person.
@type contactItem: L{_PersonVIPStatus}
@rtype: C{list} of L{liveform.Parameter} | [
"Return",
"a",
"list",
"containing",
"a",
"single",
"parameter",
"suitable",
"for",
"changing",
"the",
"VIP",
"status",
"of",
"a",
"person",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L284-L297 |
twisted/mantissa | xmantissa/people.py | EmailContactType.getParameters | def getParameters(self, emailAddress):
"""
Return a C{list} of one L{LiveForm} parameter for editing an
L{EmailAddress}.
@type emailAddress: L{EmailAddress} or C{NoneType}
@param emailAddress: If not C{None}, an existing contact item from
which to get the email address default value.
@rtype: C{list}
@return: The parameters necessary for specifying an email address.
"""
if emailAddress is not None:
address = emailAddress.address
else:
address = u''
return [
liveform.Parameter('email', liveform.TEXT_INPUT,
_normalizeWhitespace, 'Email Address',
default=address)] | python | def getParameters(self, emailAddress):
"""
Return a C{list} of one L{LiveForm} parameter for editing an
L{EmailAddress}.
@type emailAddress: L{EmailAddress} or C{NoneType}
@param emailAddress: If not C{None}, an existing contact item from
which to get the email address default value.
@rtype: C{list}
@return: The parameters necessary for specifying an email address.
"""
if emailAddress is not None:
address = emailAddress.address
else:
address = u''
return [
liveform.Parameter('email', liveform.TEXT_INPUT,
_normalizeWhitespace, 'Email Address',
default=address)] | [
"def",
"getParameters",
"(",
"self",
",",
"emailAddress",
")",
":",
"if",
"emailAddress",
"is",
"not",
"None",
":",
"address",
"=",
"emailAddress",
".",
"address",
"else",
":",
"address",
"=",
"u''",
"return",
"[",
"liveform",
".",
"Parameter",
"(",
"'emai... | Return a C{list} of one L{LiveForm} parameter for editing an
L{EmailAddress}.
@type emailAddress: L{EmailAddress} or C{NoneType}
@param emailAddress: If not C{None}, an existing contact item from
which to get the email address default value.
@rtype: C{list}
@return: The parameters necessary for specifying an email address. | [
"Return",
"a",
"C",
"{",
"list",
"}",
"of",
"one",
"L",
"{",
"LiveForm",
"}",
"parameter",
"for",
"editing",
"an",
"L",
"{",
"EmailAddress",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L364-L383 |
twisted/mantissa | xmantissa/people.py | EmailContactType._existing | def _existing(self, email):
"""
Return the existing L{EmailAddress} item with the given address, or
C{None} if there isn't one.
"""
return self.store.findUnique(
EmailAddress,
EmailAddress.address == email,
default=None) | python | def _existing(self, email):
"""
Return the existing L{EmailAddress} item with the given address, or
C{None} if there isn't one.
"""
return self.store.findUnique(
EmailAddress,
EmailAddress.address == email,
default=None) | [
"def",
"_existing",
"(",
"self",
",",
"email",
")",
":",
"return",
"self",
".",
"store",
".",
"findUnique",
"(",
"EmailAddress",
",",
"EmailAddress",
".",
"address",
"==",
"email",
",",
"default",
"=",
"None",
")"
] | Return the existing L{EmailAddress} item with the given address, or
C{None} if there isn't one. | [
"Return",
"the",
"existing",
"L",
"{",
"EmailAddress",
"}",
"item",
"with",
"the",
"given",
"address",
"or",
"C",
"{",
"None",
"}",
"if",
"there",
"isn",
"t",
"one",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L393-L401 |
twisted/mantissa | xmantissa/people.py | EmailContactType.createContactItem | def createContactItem(self, person, email):
"""
Create a new L{EmailAddress} associated with the given person based on
the given email address.
@type person: L{Person}
@param person: The person with whom to associate the new
L{EmailAddress}.
@type email: C{unicode}
@param email: The value to use for the I{address} attribute of the
newly created L{EmailAddress}. If C{''}, no L{EmailAddress} will
be created.
@return: C{None}
"""
if email:
address = self._existing(email)
if address is not None:
raise ValueError('There is already a person with that email '
'address (%s): ' % (address.person.name,))
return EmailAddress(store=self.store,
address=email,
person=person) | python | def createContactItem(self, person, email):
"""
Create a new L{EmailAddress} associated with the given person based on
the given email address.
@type person: L{Person}
@param person: The person with whom to associate the new
L{EmailAddress}.
@type email: C{unicode}
@param email: The value to use for the I{address} attribute of the
newly created L{EmailAddress}. If C{''}, no L{EmailAddress} will
be created.
@return: C{None}
"""
if email:
address = self._existing(email)
if address is not None:
raise ValueError('There is already a person with that email '
'address (%s): ' % (address.person.name,))
return EmailAddress(store=self.store,
address=email,
person=person) | [
"def",
"createContactItem",
"(",
"self",
",",
"person",
",",
"email",
")",
":",
"if",
"email",
":",
"address",
"=",
"self",
".",
"_existing",
"(",
"email",
")",
"if",
"address",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'There is already a per... | Create a new L{EmailAddress} associated with the given person based on
the given email address.
@type person: L{Person}
@param person: The person with whom to associate the new
L{EmailAddress}.
@type email: C{unicode}
@param email: The value to use for the I{address} attribute of the
newly created L{EmailAddress}. If C{''}, no L{EmailAddress} will
be created.
@return: C{None} | [
"Create",
"a",
"new",
"L",
"{",
"EmailAddress",
"}",
"associated",
"with",
"the",
"given",
"person",
"based",
"on",
"the",
"given",
"email",
"address",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L404-L427 |
twisted/mantissa | xmantissa/people.py | EmailContactType.getContactItems | def getContactItems(self, person):
"""
Return all L{EmailAddress} instances associated with the given person.
@type person: L{Person}
"""
return person.store.query(
EmailAddress,
EmailAddress.person == person) | python | def getContactItems(self, person):
"""
Return all L{EmailAddress} instances associated with the given person.
@type person: L{Person}
"""
return person.store.query(
EmailAddress,
EmailAddress.person == person) | [
"def",
"getContactItems",
"(",
"self",
",",
"person",
")",
":",
"return",
"person",
".",
"store",
".",
"query",
"(",
"EmailAddress",
",",
"EmailAddress",
".",
"person",
"==",
"person",
")"
] | Return all L{EmailAddress} instances associated with the given person.
@type person: L{Person} | [
"Return",
"all",
"L",
"{",
"EmailAddress",
"}",
"instances",
"associated",
"with",
"the",
"given",
"person",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L430-L438 |
twisted/mantissa | xmantissa/people.py | EmailContactType.editContactItem | def editContactItem(self, contact, email):
"""
Change the email address of the given L{EmailAddress} to that specified
by C{email}.
@type email: C{unicode}
@param email: The new value to use for the I{address} attribute of the
L{EmailAddress}.
@return: C{None}
"""
address = self._existing(email)
if address is not None and address is not contact:
raise ValueError('There is already a person with that email '
'address (%s): ' % (address.person.name,))
contact.address = email | python | def editContactItem(self, contact, email):
"""
Change the email address of the given L{EmailAddress} to that specified
by C{email}.
@type email: C{unicode}
@param email: The new value to use for the I{address} attribute of the
L{EmailAddress}.
@return: C{None}
"""
address = self._existing(email)
if address is not None and address is not contact:
raise ValueError('There is already a person with that email '
'address (%s): ' % (address.person.name,))
contact.address = email | [
"def",
"editContactItem",
"(",
"self",
",",
"contact",
",",
"email",
")",
":",
"address",
"=",
"self",
".",
"_existing",
"(",
"email",
")",
"if",
"address",
"is",
"not",
"None",
"and",
"address",
"is",
"not",
"contact",
":",
"raise",
"ValueError",
"(",
... | Change the email address of the given L{EmailAddress} to that specified
by C{email}.
@type email: C{unicode}
@param email: The new value to use for the I{address} attribute of the
L{EmailAddress}.
@return: C{None} | [
"Change",
"the",
"email",
"address",
"of",
"the",
"given",
"L",
"{",
"EmailAddress",
"}",
"to",
"that",
"specified",
"by",
"C",
"{",
"email",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L441-L456 |
twisted/mantissa | xmantissa/people.py | Person.getEmailAddresses | def getEmailAddresses(self):
"""
Return an iterator of all email addresses associated with this person.
@return: an iterator of unicode strings in RFC2822 address format.
"""
return self.store.query(
EmailAddress,
EmailAddress.person == self).getColumn('address') | python | def getEmailAddresses(self):
"""
Return an iterator of all email addresses associated with this person.
@return: an iterator of unicode strings in RFC2822 address format.
"""
return self.store.query(
EmailAddress,
EmailAddress.person == self).getColumn('address') | [
"def",
"getEmailAddresses",
"(",
"self",
")",
":",
"return",
"self",
".",
"store",
".",
"query",
"(",
"EmailAddress",
",",
"EmailAddress",
".",
"person",
"==",
"self",
")",
".",
"getColumn",
"(",
"'address'",
")"
] | Return an iterator of all email addresses associated with this person.
@return: an iterator of unicode strings in RFC2822 address format. | [
"Return",
"an",
"iterator",
"of",
"all",
"email",
"addresses",
"associated",
"with",
"this",
"person",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L514-L522 |
twisted/mantissa | xmantissa/people.py | Person.getMugshot | def getMugshot(self):
"""
Return the L{Mugshot} associated with this L{Person}, or an unstored
L{Mugshot} pointing at a placeholder mugshot image.
"""
mugshot = self.store.findUnique(
Mugshot, Mugshot.person == self, default=None)
if mugshot is not None:
return mugshot
return Mugshot.placeholderForPerson(self) | python | def getMugshot(self):
"""
Return the L{Mugshot} associated with this L{Person}, or an unstored
L{Mugshot} pointing at a placeholder mugshot image.
"""
mugshot = self.store.findUnique(
Mugshot, Mugshot.person == self, default=None)
if mugshot is not None:
return mugshot
return Mugshot.placeholderForPerson(self) | [
"def",
"getMugshot",
"(",
"self",
")",
":",
"mugshot",
"=",
"self",
".",
"store",
".",
"findUnique",
"(",
"Mugshot",
",",
"Mugshot",
".",
"person",
"==",
"self",
",",
"default",
"=",
"None",
")",
"if",
"mugshot",
"is",
"not",
"None",
":",
"return",
"... | Return the L{Mugshot} associated with this L{Person}, or an unstored
L{Mugshot} pointing at a placeholder mugshot image. | [
"Return",
"the",
"L",
"{",
"Mugshot",
"}",
"associated",
"with",
"this",
"L",
"{",
"Person",
"}",
"or",
"an",
"unstored",
"L",
"{",
"Mugshot",
"}",
"pointing",
"at",
"a",
"placeholder",
"mugshot",
"image",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L538-L547 |
twisted/mantissa | xmantissa/people.py | Organizer._makeStoreOwnerPerson | def _makeStoreOwnerPerson(self):
"""
Make a L{Person} representing the owner of the store that this
L{Organizer} is installed in.
@rtype: L{Person}
"""
if self.store is None:
return None
userInfo = self.store.findFirst(signup.UserInfo)
name = u''
if userInfo is not None:
name = userInfo.realName
account = self.store.findUnique(LoginAccount,
LoginAccount.avatars == self.store, None)
ownerPerson = self.createPerson(name)
if account is not None:
for method in (self.store.query(
LoginMethod,
attributes.AND(LoginMethod.account == account,
LoginMethod.internal == False))):
self.createContactItem(
EmailContactType(self.store),
ownerPerson, dict(
email=method.localpart + u'@' + method.domain))
return ownerPerson | python | def _makeStoreOwnerPerson(self):
"""
Make a L{Person} representing the owner of the store that this
L{Organizer} is installed in.
@rtype: L{Person}
"""
if self.store is None:
return None
userInfo = self.store.findFirst(signup.UserInfo)
name = u''
if userInfo is not None:
name = userInfo.realName
account = self.store.findUnique(LoginAccount,
LoginAccount.avatars == self.store, None)
ownerPerson = self.createPerson(name)
if account is not None:
for method in (self.store.query(
LoginMethod,
attributes.AND(LoginMethod.account == account,
LoginMethod.internal == False))):
self.createContactItem(
EmailContactType(self.store),
ownerPerson, dict(
email=method.localpart + u'@' + method.domain))
return ownerPerson | [
"def",
"_makeStoreOwnerPerson",
"(",
"self",
")",
":",
"if",
"self",
".",
"store",
"is",
"None",
":",
"return",
"None",
"userInfo",
"=",
"self",
".",
"store",
".",
"findFirst",
"(",
"signup",
".",
"UserInfo",
")",
"name",
"=",
"u''",
"if",
"userInfo",
... | Make a L{Person} representing the owner of the store that this
L{Organizer} is installed in.
@rtype: L{Person} | [
"Make",
"a",
"L",
"{",
"Person",
"}",
"representing",
"the",
"owner",
"of",
"the",
"store",
"that",
"this",
"L",
"{",
"Organizer",
"}",
"is",
"installed",
"in",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L762-L787 |
twisted/mantissa | xmantissa/people.py | Organizer._gatherPluginMethods | def _gatherPluginMethods(self, methodName):
"""
Walk through each L{IOrganizerPlugin} powerup, yielding the bound
method if the powerup implements C{methodName}. Upon encountering a
plugin which fails to implement it, issue a
L{PendingDeprecationWarning}.
@param methodName: The name of a L{IOrganizerPlugin} method.
@type methodName: C{str}
@return: Iterable of methods.
"""
for plugin in self.getOrganizerPlugins():
implementation = getattr(plugin, methodName, None)
if implementation is not None:
yield implementation
else:
warn(
('IOrganizerPlugin now has the %r method, %s'
' did not implement it') % (
methodName, plugin.__class__),
category=PendingDeprecationWarning) | python | def _gatherPluginMethods(self, methodName):
"""
Walk through each L{IOrganizerPlugin} powerup, yielding the bound
method if the powerup implements C{methodName}. Upon encountering a
plugin which fails to implement it, issue a
L{PendingDeprecationWarning}.
@param methodName: The name of a L{IOrganizerPlugin} method.
@type methodName: C{str}
@return: Iterable of methods.
"""
for plugin in self.getOrganizerPlugins():
implementation = getattr(plugin, methodName, None)
if implementation is not None:
yield implementation
else:
warn(
('IOrganizerPlugin now has the %r method, %s'
' did not implement it') % (
methodName, plugin.__class__),
category=PendingDeprecationWarning) | [
"def",
"_gatherPluginMethods",
"(",
"self",
",",
"methodName",
")",
":",
"for",
"plugin",
"in",
"self",
".",
"getOrganizerPlugins",
"(",
")",
":",
"implementation",
"=",
"getattr",
"(",
"plugin",
",",
"methodName",
",",
"None",
")",
"if",
"implementation",
"... | Walk through each L{IOrganizerPlugin} powerup, yielding the bound
method if the powerup implements C{methodName}. Upon encountering a
plugin which fails to implement it, issue a
L{PendingDeprecationWarning}.
@param methodName: The name of a L{IOrganizerPlugin} method.
@type methodName: C{str}
@return: Iterable of methods. | [
"Walk",
"through",
"each",
"L",
"{",
"IOrganizerPlugin",
"}",
"powerup",
"yielding",
"the",
"bound",
"method",
"if",
"the",
"powerup",
"implements",
"C",
"{",
"methodName",
"}",
".",
"Upon",
"encountering",
"a",
"plugin",
"which",
"fails",
"to",
"implement",
... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L798-L819 |
twisted/mantissa | xmantissa/people.py | Organizer._checkContactType | def _checkContactType(self, contactType):
"""
Possibly emit some warnings about C{contactType}'s implementation of
L{IContactType}.
@type contactType: L{IContactType} provider
"""
if getattr(contactType, 'getEditFormForPerson', None) is None:
warn(
"IContactType now has the 'getEditFormForPerson'"
" method, but %s did not implement it." % (
contactType.__class__,),
category=PendingDeprecationWarning)
if getattr(contactType, 'getEditorialForm', None) is not None:
warn(
"The IContactType %s defines the 'getEditorialForm'"
" method, which is deprecated. 'getEditFormForPerson'"
" does something vaguely similar." % (contactType.__class__,),
category=DeprecationWarning) | python | def _checkContactType(self, contactType):
"""
Possibly emit some warnings about C{contactType}'s implementation of
L{IContactType}.
@type contactType: L{IContactType} provider
"""
if getattr(contactType, 'getEditFormForPerson', None) is None:
warn(
"IContactType now has the 'getEditFormForPerson'"
" method, but %s did not implement it." % (
contactType.__class__,),
category=PendingDeprecationWarning)
if getattr(contactType, 'getEditorialForm', None) is not None:
warn(
"The IContactType %s defines the 'getEditorialForm'"
" method, which is deprecated. 'getEditFormForPerson'"
" does something vaguely similar." % (contactType.__class__,),
category=DeprecationWarning) | [
"def",
"_checkContactType",
"(",
"self",
",",
"contactType",
")",
":",
"if",
"getattr",
"(",
"contactType",
",",
"'getEditFormForPerson'",
",",
"None",
")",
"is",
"None",
":",
"warn",
"(",
"\"IContactType now has the 'getEditFormForPerson'\"",
"\" method, but %s did not... | Possibly emit some warnings about C{contactType}'s implementation of
L{IContactType}.
@type contactType: L{IContactType} provider | [
"Possibly",
"emit",
"some",
"warnings",
"about",
"C",
"{",
"contactType",
"}",
"s",
"implementation",
"of",
"L",
"{",
"IContactType",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L822-L841 |
twisted/mantissa | xmantissa/people.py | Organizer.getContactTypes | def getContactTypes(self):
"""
Return an iterator of L{IContactType} providers available to this
organizer's store.
"""
yield VIPPersonContactType()
yield EmailContactType(self.store)
yield PostalContactType()
yield PhoneNumberContactType()
yield NotesContactType()
for getContactTypes in self._gatherPluginMethods('getContactTypes'):
for contactType in getContactTypes():
self._checkContactType(contactType)
yield contactType | python | def getContactTypes(self):
"""
Return an iterator of L{IContactType} providers available to this
organizer's store.
"""
yield VIPPersonContactType()
yield EmailContactType(self.store)
yield PostalContactType()
yield PhoneNumberContactType()
yield NotesContactType()
for getContactTypes in self._gatherPluginMethods('getContactTypes'):
for contactType in getContactTypes():
self._checkContactType(contactType)
yield contactType | [
"def",
"getContactTypes",
"(",
"self",
")",
":",
"yield",
"VIPPersonContactType",
"(",
")",
"yield",
"EmailContactType",
"(",
"self",
".",
"store",
")",
"yield",
"PostalContactType",
"(",
")",
"yield",
"PhoneNumberContactType",
"(",
")",
"yield",
"NotesContactType... | Return an iterator of L{IContactType} providers available to this
organizer's store. | [
"Return",
"an",
"iterator",
"of",
"L",
"{",
"IContactType",
"}",
"providers",
"available",
"to",
"this",
"organizer",
"s",
"store",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L844-L857 |
twisted/mantissa | xmantissa/people.py | Organizer.getPeopleFilters | def getPeopleFilters(self):
"""
Return an iterator of L{IPeopleFilter} providers available to this
organizer's store.
"""
yield AllPeopleFilter()
yield VIPPeopleFilter()
for getPeopleFilters in self._gatherPluginMethods('getPeopleFilters'):
for peopleFilter in getPeopleFilters():
yield peopleFilter
for tag in sorted(self.getPeopleTags()):
yield TaggedPeopleFilter(tag) | python | def getPeopleFilters(self):
"""
Return an iterator of L{IPeopleFilter} providers available to this
organizer's store.
"""
yield AllPeopleFilter()
yield VIPPeopleFilter()
for getPeopleFilters in self._gatherPluginMethods('getPeopleFilters'):
for peopleFilter in getPeopleFilters():
yield peopleFilter
for tag in sorted(self.getPeopleTags()):
yield TaggedPeopleFilter(tag) | [
"def",
"getPeopleFilters",
"(",
"self",
")",
":",
"yield",
"AllPeopleFilter",
"(",
")",
"yield",
"VIPPeopleFilter",
"(",
")",
"for",
"getPeopleFilters",
"in",
"self",
".",
"_gatherPluginMethods",
"(",
"'getPeopleFilters'",
")",
":",
"for",
"peopleFilter",
"in",
... | Return an iterator of L{IPeopleFilter} providers available to this
organizer's store. | [
"Return",
"an",
"iterator",
"of",
"L",
"{",
"IPeopleFilter",
"}",
"providers",
"available",
"to",
"this",
"organizer",
"s",
"store",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L860-L871 |
twisted/mantissa | xmantissa/people.py | Organizer.getPeopleTags | def getPeopleTags(self):
"""
Return a sequence of tags which have been applied to L{Person} items.
@rtype: C{set}
"""
query = self.store.query(
Tag, Tag.object == Person.storeID)
return set(query.getColumn('name').distinct()) | python | def getPeopleTags(self):
"""
Return a sequence of tags which have been applied to L{Person} items.
@rtype: C{set}
"""
query = self.store.query(
Tag, Tag.object == Person.storeID)
return set(query.getColumn('name').distinct()) | [
"def",
"getPeopleTags",
"(",
"self",
")",
":",
"query",
"=",
"self",
".",
"store",
".",
"query",
"(",
"Tag",
",",
"Tag",
".",
"object",
"==",
"Person",
".",
"storeID",
")",
"return",
"set",
"(",
"query",
".",
"getColumn",
"(",
"'name'",
")",
".",
"... | Return a sequence of tags which have been applied to L{Person} items.
@rtype: C{set} | [
"Return",
"a",
"sequence",
"of",
"tags",
"which",
"have",
"been",
"applied",
"to",
"L",
"{",
"Person",
"}",
"items",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L874-L882 |
twisted/mantissa | xmantissa/people.py | Organizer.groupReadOnlyViews | def groupReadOnlyViews(self, person):
"""
Collect all contact items from the available contact types for the
given person, organize them by contact group, and turn them into
read-only views.
@type person: L{Person}
@param person: The person whose contact items we're interested in.
@return: A mapping of of L{ContactGroup} names to the read-only views
of their member contact items, with C{None} being the key for
groupless contact items.
@rtype: C{dict} of C{str}
"""
# this is a slightly awkward, specific API, but at the time of
# writing, read-only views are the thing that the only caller cares
# about. we need the contact type to get a read-only view for a
# contact item. there is no way to get from a contact item to a
# contact type, so this method can't be "groupContactItems" (which
# seems to make more sense), unless it returned some weird data
# structure which managed to associate contact items and contact
# types.
grouped = {}
for contactType in self.getContactTypes():
for contactItem in contactType.getContactItems(person):
contactGroup = contactType.getContactGroup(contactItem)
if contactGroup is not None:
contactGroup = contactGroup.groupName
if contactGroup not in grouped:
grouped[contactGroup] = []
grouped[contactGroup].append(
contactType.getReadOnlyView(contactItem))
return grouped | python | def groupReadOnlyViews(self, person):
"""
Collect all contact items from the available contact types for the
given person, organize them by contact group, and turn them into
read-only views.
@type person: L{Person}
@param person: The person whose contact items we're interested in.
@return: A mapping of of L{ContactGroup} names to the read-only views
of their member contact items, with C{None} being the key for
groupless contact items.
@rtype: C{dict} of C{str}
"""
# this is a slightly awkward, specific API, but at the time of
# writing, read-only views are the thing that the only caller cares
# about. we need the contact type to get a read-only view for a
# contact item. there is no way to get from a contact item to a
# contact type, so this method can't be "groupContactItems" (which
# seems to make more sense), unless it returned some weird data
# structure which managed to associate contact items and contact
# types.
grouped = {}
for contactType in self.getContactTypes():
for contactItem in contactType.getContactItems(person):
contactGroup = contactType.getContactGroup(contactItem)
if contactGroup is not None:
contactGroup = contactGroup.groupName
if contactGroup not in grouped:
grouped[contactGroup] = []
grouped[contactGroup].append(
contactType.getReadOnlyView(contactItem))
return grouped | [
"def",
"groupReadOnlyViews",
"(",
"self",
",",
"person",
")",
":",
"# this is a slightly awkward, specific API, but at the time of",
"# writing, read-only views are the thing that the only caller cares",
"# about. we need the contact type to get a read-only view for a",
"# contact item. ther... | Collect all contact items from the available contact types for the
given person, organize them by contact group, and turn them into
read-only views.
@type person: L{Person}
@param person: The person whose contact items we're interested in.
@return: A mapping of of L{ContactGroup} names to the read-only views
of their member contact items, with C{None} being the key for
groupless contact items.
@rtype: C{dict} of C{str} | [
"Collect",
"all",
"contact",
"items",
"from",
"the",
"available",
"contact",
"types",
"for",
"the",
"given",
"person",
"organize",
"them",
"by",
"contact",
"group",
"and",
"turn",
"them",
"into",
"read",
"-",
"only",
"views",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L885-L917 |
twisted/mantissa | xmantissa/people.py | Organizer.getContactCreationParameters | def getContactCreationParameters(self):
"""
Yield a L{Parameter} for each L{IContactType} known.
Each yielded object can be used with a L{LiveForm} to create a new
instance of a particular L{IContactType}.
"""
for contactType in self.getContactTypes():
if contactType.allowMultipleContactItems:
descriptiveIdentifier = _descriptiveIdentifier(contactType)
yield liveform.ListChangeParameter(
contactType.uniqueIdentifier(),
contactType.getParameters(None),
defaults=[],
modelObjects=[],
modelObjectDescription=descriptiveIdentifier)
else:
yield liveform.FormParameter(
contactType.uniqueIdentifier(),
liveform.LiveForm(
lambda **k: k,
contactType.getParameters(None))) | python | def getContactCreationParameters(self):
"""
Yield a L{Parameter} for each L{IContactType} known.
Each yielded object can be used with a L{LiveForm} to create a new
instance of a particular L{IContactType}.
"""
for contactType in self.getContactTypes():
if contactType.allowMultipleContactItems:
descriptiveIdentifier = _descriptiveIdentifier(contactType)
yield liveform.ListChangeParameter(
contactType.uniqueIdentifier(),
contactType.getParameters(None),
defaults=[],
modelObjects=[],
modelObjectDescription=descriptiveIdentifier)
else:
yield liveform.FormParameter(
contactType.uniqueIdentifier(),
liveform.LiveForm(
lambda **k: k,
contactType.getParameters(None))) | [
"def",
"getContactCreationParameters",
"(",
"self",
")",
":",
"for",
"contactType",
"in",
"self",
".",
"getContactTypes",
"(",
")",
":",
"if",
"contactType",
".",
"allowMultipleContactItems",
":",
"descriptiveIdentifier",
"=",
"_descriptiveIdentifier",
"(",
"contactTy... | Yield a L{Parameter} for each L{IContactType} known.
Each yielded object can be used with a L{LiveForm} to create a new
instance of a particular L{IContactType}. | [
"Yield",
"a",
"L",
"{",
"Parameter",
"}",
"for",
"each",
"L",
"{",
"IContactType",
"}",
"known",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L920-L941 |
twisted/mantissa | xmantissa/people.py | Organizer._parametersToDefaults | def _parametersToDefaults(self, parameters):
"""
Extract the defaults from C{parameters}, constructing a dictionary
mapping parameter names to default values, suitable for passing to
L{ListChangeParameter}.
@type parameters: C{list} of L{liveform.Parameter} or
L{liveform.ChoiceParameter}.
@rtype: C{dict}
"""
defaults = {}
for p in parameters:
if isinstance(p, liveform.ChoiceParameter):
selected = []
for choice in p.choices:
if choice.selected:
selected.append(choice.value)
defaults[p.name] = selected
else:
defaults[p.name] = p.default
return defaults | python | def _parametersToDefaults(self, parameters):
"""
Extract the defaults from C{parameters}, constructing a dictionary
mapping parameter names to default values, suitable for passing to
L{ListChangeParameter}.
@type parameters: C{list} of L{liveform.Parameter} or
L{liveform.ChoiceParameter}.
@rtype: C{dict}
"""
defaults = {}
for p in parameters:
if isinstance(p, liveform.ChoiceParameter):
selected = []
for choice in p.choices:
if choice.selected:
selected.append(choice.value)
defaults[p.name] = selected
else:
defaults[p.name] = p.default
return defaults | [
"def",
"_parametersToDefaults",
"(",
"self",
",",
"parameters",
")",
":",
"defaults",
"=",
"{",
"}",
"for",
"p",
"in",
"parameters",
":",
"if",
"isinstance",
"(",
"p",
",",
"liveform",
".",
"ChoiceParameter",
")",
":",
"selected",
"=",
"[",
"]",
"for",
... | Extract the defaults from C{parameters}, constructing a dictionary
mapping parameter names to default values, suitable for passing to
L{ListChangeParameter}.
@type parameters: C{list} of L{liveform.Parameter} or
L{liveform.ChoiceParameter}.
@rtype: C{dict} | [
"Extract",
"the",
"defaults",
"from",
"C",
"{",
"parameters",
"}",
"constructing",
"a",
"dictionary",
"mapping",
"parameter",
"names",
"to",
"default",
"values",
"suitable",
"for",
"passing",
"to",
"L",
"{",
"ListChangeParameter",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L944-L965 |
twisted/mantissa | xmantissa/people.py | Organizer.toContactEditorialParameter | def toContactEditorialParameter(self, contactType, person):
"""
Convert the given contact type into a L{liveform.LiveForm} parameter.
@type contactType: L{IContactType} provider.
@type person: L{Person}
@rtype: L{liveform.Parameter} or similar.
"""
contactItems = list(contactType.getContactItems(person))
if contactType.allowMultipleContactItems:
defaults = []
modelObjects = []
for contactItem in contactItems:
defaultedParameters = contactType.getParameters(contactItem)
if defaultedParameters is None:
continue
defaults.append(self._parametersToDefaults(
defaultedParameters))
modelObjects.append(contactItem)
descriptiveIdentifier = _descriptiveIdentifier(contactType)
return liveform.ListChangeParameter(
contactType.uniqueIdentifier(),
contactType.getParameters(None),
defaults=defaults,
modelObjects=modelObjects,
modelObjectDescription=descriptiveIdentifier)
(contactItem,) = contactItems
return liveform.FormParameter(
contactType.uniqueIdentifier(),
liveform.LiveForm(
lambda **k: k,
contactType.getParameters(contactItem))) | python | def toContactEditorialParameter(self, contactType, person):
"""
Convert the given contact type into a L{liveform.LiveForm} parameter.
@type contactType: L{IContactType} provider.
@type person: L{Person}
@rtype: L{liveform.Parameter} or similar.
"""
contactItems = list(contactType.getContactItems(person))
if contactType.allowMultipleContactItems:
defaults = []
modelObjects = []
for contactItem in contactItems:
defaultedParameters = contactType.getParameters(contactItem)
if defaultedParameters is None:
continue
defaults.append(self._parametersToDefaults(
defaultedParameters))
modelObjects.append(contactItem)
descriptiveIdentifier = _descriptiveIdentifier(contactType)
return liveform.ListChangeParameter(
contactType.uniqueIdentifier(),
contactType.getParameters(None),
defaults=defaults,
modelObjects=modelObjects,
modelObjectDescription=descriptiveIdentifier)
(contactItem,) = contactItems
return liveform.FormParameter(
contactType.uniqueIdentifier(),
liveform.LiveForm(
lambda **k: k,
contactType.getParameters(contactItem))) | [
"def",
"toContactEditorialParameter",
"(",
"self",
",",
"contactType",
",",
"person",
")",
":",
"contactItems",
"=",
"list",
"(",
"contactType",
".",
"getContactItems",
"(",
"person",
")",
")",
"if",
"contactType",
".",
"allowMultipleContactItems",
":",
"defaults"... | Convert the given contact type into a L{liveform.LiveForm} parameter.
@type contactType: L{IContactType} provider.
@type person: L{Person}
@rtype: L{liveform.Parameter} or similar. | [
"Convert",
"the",
"given",
"contact",
"type",
"into",
"a",
"L",
"{",
"liveform",
".",
"LiveForm",
"}",
"parameter",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L968-L1001 |
twisted/mantissa | xmantissa/people.py | Organizer.getContactEditorialParameters | def getContactEditorialParameters(self, person):
"""
Yield L{LiveForm} parameters to edit each contact item of each contact
type for the given person.
@type person: L{Person}
@return: An iterable of two-tuples. The first element of each tuple
is an L{IContactType} provider. The third element of each tuple
is the L{LiveForm} parameter object for that contact item.
"""
for contactType in self.getContactTypes():
yield (
contactType,
self.toContactEditorialParameter(contactType, person)) | python | def getContactEditorialParameters(self, person):
"""
Yield L{LiveForm} parameters to edit each contact item of each contact
type for the given person.
@type person: L{Person}
@return: An iterable of two-tuples. The first element of each tuple
is an L{IContactType} provider. The third element of each tuple
is the L{LiveForm} parameter object for that contact item.
"""
for contactType in self.getContactTypes():
yield (
contactType,
self.toContactEditorialParameter(contactType, person)) | [
"def",
"getContactEditorialParameters",
"(",
"self",
",",
"person",
")",
":",
"for",
"contactType",
"in",
"self",
".",
"getContactTypes",
"(",
")",
":",
"yield",
"(",
"contactType",
",",
"self",
".",
"toContactEditorialParameter",
"(",
"contactType",
",",
"perso... | Yield L{LiveForm} parameters to edit each contact item of each contact
type for the given person.
@type person: L{Person}
@return: An iterable of two-tuples. The first element of each tuple
is an L{IContactType} provider. The third element of each tuple
is the L{LiveForm} parameter object for that contact item. | [
"Yield",
"L",
"{",
"LiveForm",
"}",
"parameters",
"to",
"edit",
"each",
"contact",
"item",
"of",
"each",
"contact",
"type",
"for",
"the",
"given",
"person",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1004-L1017 |
twisted/mantissa | xmantissa/people.py | Organizer.createPerson | def createPerson(self, nickname, vip=_NO_VIP):
"""
Create a new L{Person} with the given name in this organizer.
@type nickname: C{unicode}
@param nickname: The value for the new person's C{name} attribute.
@type vip: C{bool}
@param vip: Value to set the created person's C{vip} attribute to
(deprecated).
@rtype: L{Person}
"""
for person in (self.store.query(
Person, attributes.AND(
Person.name == nickname,
Person.organizer == self))):
raise ValueError("Person with name %r exists already." % (nickname,))
person = Person(
store=self.store,
created=extime.Time(),
organizer=self,
name=nickname)
if vip is not self._NO_VIP:
warn(
"Usage of Organizer.createPerson's 'vip' parameter"
" is deprecated",
category=DeprecationWarning)
person.vip = vip
self._callOnOrganizerPlugins('personCreated', person)
return person | python | def createPerson(self, nickname, vip=_NO_VIP):
"""
Create a new L{Person} with the given name in this organizer.
@type nickname: C{unicode}
@param nickname: The value for the new person's C{name} attribute.
@type vip: C{bool}
@param vip: Value to set the created person's C{vip} attribute to
(deprecated).
@rtype: L{Person}
"""
for person in (self.store.query(
Person, attributes.AND(
Person.name == nickname,
Person.organizer == self))):
raise ValueError("Person with name %r exists already." % (nickname,))
person = Person(
store=self.store,
created=extime.Time(),
organizer=self,
name=nickname)
if vip is not self._NO_VIP:
warn(
"Usage of Organizer.createPerson's 'vip' parameter"
" is deprecated",
category=DeprecationWarning)
person.vip = vip
self._callOnOrganizerPlugins('personCreated', person)
return person | [
"def",
"createPerson",
"(",
"self",
",",
"nickname",
",",
"vip",
"=",
"_NO_VIP",
")",
":",
"for",
"person",
"in",
"(",
"self",
".",
"store",
".",
"query",
"(",
"Person",
",",
"attributes",
".",
"AND",
"(",
"Person",
".",
"name",
"==",
"nickname",
","... | Create a new L{Person} with the given name in this organizer.
@type nickname: C{unicode}
@param nickname: The value for the new person's C{name} attribute.
@type vip: C{bool}
@param vip: Value to set the created person's C{vip} attribute to
(deprecated).
@rtype: L{Person} | [
"Create",
"a",
"new",
"L",
"{",
"Person",
"}",
"with",
"the",
"given",
"name",
"in",
"this",
"organizer",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1022-L1054 |
twisted/mantissa | xmantissa/people.py | Organizer.createContactItem | def createContactItem(self, contactType, person, contactInfo):
"""
Create a new contact item for the given person with the given contact
type. Broadcast a creation to all L{IOrganizerPlugin} powerups.
@type contactType: L{IContactType}
@param contactType: The contact type which will be used to create the
contact item.
@type person: L{Person}
@param person: The person with whom the contact item will be
associated.
@type contactInfo: C{dict}
@param contactInfo: The contact information to use to create the
contact item.
@return: The contact item, as created by the given contact type.
"""
contactItem = contactType.createContactItem(
person, **_stringifyKeys(contactInfo))
if contactItem is not None:
self._callOnOrganizerPlugins('contactItemCreated', contactItem)
return contactItem | python | def createContactItem(self, contactType, person, contactInfo):
"""
Create a new contact item for the given person with the given contact
type. Broadcast a creation to all L{IOrganizerPlugin} powerups.
@type contactType: L{IContactType}
@param contactType: The contact type which will be used to create the
contact item.
@type person: L{Person}
@param person: The person with whom the contact item will be
associated.
@type contactInfo: C{dict}
@param contactInfo: The contact information to use to create the
contact item.
@return: The contact item, as created by the given contact type.
"""
contactItem = contactType.createContactItem(
person, **_stringifyKeys(contactInfo))
if contactItem is not None:
self._callOnOrganizerPlugins('contactItemCreated', contactItem)
return contactItem | [
"def",
"createContactItem",
"(",
"self",
",",
"contactType",
",",
"person",
",",
"contactInfo",
")",
":",
"contactItem",
"=",
"contactType",
".",
"createContactItem",
"(",
"person",
",",
"*",
"*",
"_stringifyKeys",
"(",
"contactInfo",
")",
")",
"if",
"contactI... | Create a new contact item for the given person with the given contact
type. Broadcast a creation to all L{IOrganizerPlugin} powerups.
@type contactType: L{IContactType}
@param contactType: The contact type which will be used to create the
contact item.
@type person: L{Person}
@param person: The person with whom the contact item will be
associated.
@type contactInfo: C{dict}
@param contactInfo: The contact information to use to create the
contact item.
@return: The contact item, as created by the given contact type. | [
"Create",
"a",
"new",
"contact",
"item",
"for",
"the",
"given",
"person",
"with",
"the",
"given",
"contact",
"type",
".",
"Broadcast",
"a",
"creation",
"to",
"all",
"L",
"{",
"IOrganizerPlugin",
"}",
"powerups",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1057-L1080 |
twisted/mantissa | xmantissa/people.py | Organizer.editContactItem | def editContactItem(self, contactType, contactItem, contactInfo):
"""
Edit the given contact item with the given contact type. Broadcast
the edit to all L{IOrganizerPlugin} powerups.
@type contactType: L{IContactType}
@param contactType: The contact type which will be used to edit the
contact item.
@param contactItem: The contact item to edit.
@type contactInfo: C{dict}
@param contactInfo: The contact information to use to edit the
contact item.
@return: C{None}
"""
contactType.editContactItem(
contactItem, **_stringifyKeys(contactInfo))
self._callOnOrganizerPlugins('contactItemEdited', contactItem) | python | def editContactItem(self, contactType, contactItem, contactInfo):
"""
Edit the given contact item with the given contact type. Broadcast
the edit to all L{IOrganizerPlugin} powerups.
@type contactType: L{IContactType}
@param contactType: The contact type which will be used to edit the
contact item.
@param contactItem: The contact item to edit.
@type contactInfo: C{dict}
@param contactInfo: The contact information to use to edit the
contact item.
@return: C{None}
"""
contactType.editContactItem(
contactItem, **_stringifyKeys(contactInfo))
self._callOnOrganizerPlugins('contactItemEdited', contactItem) | [
"def",
"editContactItem",
"(",
"self",
",",
"contactType",
",",
"contactItem",
",",
"contactInfo",
")",
":",
"contactType",
".",
"editContactItem",
"(",
"contactItem",
",",
"*",
"*",
"_stringifyKeys",
"(",
"contactInfo",
")",
")",
"self",
".",
"_callOnOrganizerP... | Edit the given contact item with the given contact type. Broadcast
the edit to all L{IOrganizerPlugin} powerups.
@type contactType: L{IContactType}
@param contactType: The contact type which will be used to edit the
contact item.
@param contactItem: The contact item to edit.
@type contactInfo: C{dict}
@param contactInfo: The contact information to use to edit the
contact item.
@return: C{None} | [
"Edit",
"the",
"given",
"contact",
"item",
"with",
"the",
"given",
"contact",
"type",
".",
"Broadcast",
"the",
"edit",
"to",
"all",
"L",
"{",
"IOrganizerPlugin",
"}",
"powerups",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1083-L1102 |
twisted/mantissa | xmantissa/people.py | Organizer._callOnOrganizerPlugins | def _callOnOrganizerPlugins(self, methodName, *args):
"""
Call a method on all L{IOrganizerPlugin} powerups on C{self.store}, or
emit a deprecation warning for each one which does not implement that
method.
"""
for observer in self.getOrganizerPlugins():
method = getattr(observer, methodName, None)
if method is not None:
method(*args)
else:
warn(
"IOrganizerPlugin now has the %s method, %s "
"did not implement it" % (methodName, observer.__class__,),
category=PendingDeprecationWarning) | python | def _callOnOrganizerPlugins(self, methodName, *args):
"""
Call a method on all L{IOrganizerPlugin} powerups on C{self.store}, or
emit a deprecation warning for each one which does not implement that
method.
"""
for observer in self.getOrganizerPlugins():
method = getattr(observer, methodName, None)
if method is not None:
method(*args)
else:
warn(
"IOrganizerPlugin now has the %s method, %s "
"did not implement it" % (methodName, observer.__class__,),
category=PendingDeprecationWarning) | [
"def",
"_callOnOrganizerPlugins",
"(",
"self",
",",
"methodName",
",",
"*",
"args",
")",
":",
"for",
"observer",
"in",
"self",
".",
"getOrganizerPlugins",
"(",
")",
":",
"method",
"=",
"getattr",
"(",
"observer",
",",
"methodName",
",",
"None",
")",
"if",
... | Call a method on all L{IOrganizerPlugin} powerups on C{self.store}, or
emit a deprecation warning for each one which does not implement that
method. | [
"Call",
"a",
"method",
"on",
"all",
"L",
"{",
"IOrganizerPlugin",
"}",
"powerups",
"on",
"C",
"{",
"self",
".",
"store",
"}",
"or",
"emit",
"a",
"deprecation",
"warning",
"for",
"each",
"one",
"which",
"does",
"not",
"implement",
"that",
"method",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1105-L1119 |
twisted/mantissa | xmantissa/people.py | Organizer.editPerson | def editPerson(self, person, nickname, edits):
"""
Change the name and contact information associated with the given
L{Person}.
@type person: L{Person}
@param person: The person which will be modified.
@type nickname: C{unicode}
@param nickname: The new value for L{Person.name}
@type edits: C{list}
@param edits: list of tuples of L{IContactType} providers and
corresponding L{ListChanges} objects or dictionaries of parameter
values.
"""
for existing in self.store.query(Person, Person.name == nickname):
if existing is person:
continue
raise ValueError(
"A person with the name %r exists already." % (nickname,))
oldname = person.name
person.name = nickname
self._callOnOrganizerPlugins('personNameChanged', person, oldname)
for contactType, submission in edits:
if contactType.allowMultipleContactItems:
for edit in submission.edit:
self.editContactItem(
contactType, edit.object, edit.values)
for create in submission.create:
create.setter(
self.createContactItem(
contactType, person, create.values))
for delete in submission.delete:
delete.deleteFromStore()
else:
(contactItem,) = contactType.getContactItems(person)
self.editContactItem(
contactType, contactItem, submission) | python | def editPerson(self, person, nickname, edits):
"""
Change the name and contact information associated with the given
L{Person}.
@type person: L{Person}
@param person: The person which will be modified.
@type nickname: C{unicode}
@param nickname: The new value for L{Person.name}
@type edits: C{list}
@param edits: list of tuples of L{IContactType} providers and
corresponding L{ListChanges} objects or dictionaries of parameter
values.
"""
for existing in self.store.query(Person, Person.name == nickname):
if existing is person:
continue
raise ValueError(
"A person with the name %r exists already." % (nickname,))
oldname = person.name
person.name = nickname
self._callOnOrganizerPlugins('personNameChanged', person, oldname)
for contactType, submission in edits:
if contactType.allowMultipleContactItems:
for edit in submission.edit:
self.editContactItem(
contactType, edit.object, edit.values)
for create in submission.create:
create.setter(
self.createContactItem(
contactType, person, create.values))
for delete in submission.delete:
delete.deleteFromStore()
else:
(contactItem,) = contactType.getContactItems(person)
self.editContactItem(
contactType, contactItem, submission) | [
"def",
"editPerson",
"(",
"self",
",",
"person",
",",
"nickname",
",",
"edits",
")",
":",
"for",
"existing",
"in",
"self",
".",
"store",
".",
"query",
"(",
"Person",
",",
"Person",
".",
"name",
"==",
"nickname",
")",
":",
"if",
"existing",
"is",
"per... | Change the name and contact information associated with the given
L{Person}.
@type person: L{Person}
@param person: The person which will be modified.
@type nickname: C{unicode}
@param nickname: The new value for L{Person.name}
@type edits: C{list}
@param edits: list of tuples of L{IContactType} providers and
corresponding L{ListChanges} objects or dictionaries of parameter
values. | [
"Change",
"the",
"name",
"and",
"contact",
"information",
"associated",
"with",
"the",
"given",
"L",
"{",
"Person",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1122-L1160 |
twisted/mantissa | xmantissa/people.py | Organizer.personByName | def personByName(self, name):
"""
Retrieve the L{Person} item for the given Q2Q address,
creating it first if necessary.
@type name: C{unicode}
"""
return self.store.findOrCreate(Person, organizer=self, name=name) | python | def personByName(self, name):
"""
Retrieve the L{Person} item for the given Q2Q address,
creating it first if necessary.
@type name: C{unicode}
"""
return self.store.findOrCreate(Person, organizer=self, name=name) | [
"def",
"personByName",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"store",
".",
"findOrCreate",
"(",
"Person",
",",
"organizer",
"=",
"self",
",",
"name",
"=",
"name",
")"
] | Retrieve the L{Person} item for the given Q2Q address,
creating it first if necessary.
@type name: C{unicode} | [
"Retrieve",
"the",
"L",
"{",
"Person",
"}",
"item",
"for",
"the",
"given",
"Q2Q",
"address",
"creating",
"it",
"first",
"if",
"necessary",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1170-L1177 |
twisted/mantissa | xmantissa/people.py | Organizer.personByEmailAddress | def personByEmailAddress(self, address):
"""
Retrieve the L{Person} item for the given email address
(or return None if no such person exists)
@type name: C{unicode}
"""
email = self.store.findUnique(EmailAddress,
EmailAddress.address == address,
default=None)
if email is not None:
return email.person | python | def personByEmailAddress(self, address):
"""
Retrieve the L{Person} item for the given email address
(or return None if no such person exists)
@type name: C{unicode}
"""
email = self.store.findUnique(EmailAddress,
EmailAddress.address == address,
default=None)
if email is not None:
return email.person | [
"def",
"personByEmailAddress",
"(",
"self",
",",
"address",
")",
":",
"email",
"=",
"self",
".",
"store",
".",
"findUnique",
"(",
"EmailAddress",
",",
"EmailAddress",
".",
"address",
"==",
"address",
",",
"default",
"=",
"None",
")",
"if",
"email",
"is",
... | Retrieve the L{Person} item for the given email address
(or return None if no such person exists)
@type name: C{unicode} | [
"Retrieve",
"the",
"L",
"{",
"Person",
"}",
"item",
"for",
"the",
"given",
"email",
"address",
"(",
"or",
"return",
"None",
"if",
"no",
"such",
"person",
"exists",
")"
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1180-L1191 |
twisted/mantissa | xmantissa/people.py | Organizer.urlForViewState | def urlForViewState(self, person, viewState):
"""
Return a url for L{OrganizerFragment} which will display C{person} in
state C{viewState}.
@type person: L{Person}
@type viewState: L{ORGANIZER_VIEW_STATES} constant.
@rtype: L{url.URL}
"""
# ideally there would be a more general mechanism for encoding state
# like this in a url, rather than ad-hoc query arguments for each
# fragment which needs to do it.
organizerURL = self._webTranslator.linkTo(self.storeID)
return url.URL(
netloc='', scheme='',
pathsegs=organizerURL.split('/')[1:],
querysegs=(('initial-person', person.name),
('initial-state', viewState))) | python | def urlForViewState(self, person, viewState):
"""
Return a url for L{OrganizerFragment} which will display C{person} in
state C{viewState}.
@type person: L{Person}
@type viewState: L{ORGANIZER_VIEW_STATES} constant.
@rtype: L{url.URL}
"""
# ideally there would be a more general mechanism for encoding state
# like this in a url, rather than ad-hoc query arguments for each
# fragment which needs to do it.
organizerURL = self._webTranslator.linkTo(self.storeID)
return url.URL(
netloc='', scheme='',
pathsegs=organizerURL.split('/')[1:],
querysegs=(('initial-person', person.name),
('initial-state', viewState))) | [
"def",
"urlForViewState",
"(",
"self",
",",
"person",
",",
"viewState",
")",
":",
"# ideally there would be a more general mechanism for encoding state",
"# like this in a url, rather than ad-hoc query arguments for each",
"# fragment which needs to do it.",
"organizerURL",
"=",
"self"... | Return a url for L{OrganizerFragment} which will display C{person} in
state C{viewState}.
@type person: L{Person}
@type viewState: L{ORGANIZER_VIEW_STATES} constant.
@rtype: L{url.URL} | [
"Return",
"a",
"url",
"for",
"L",
"{",
"OrganizerFragment",
"}",
"which",
"will",
"display",
"C",
"{",
"person",
"}",
"in",
"state",
"C",
"{",
"viewState",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1202-L1220 |
twisted/mantissa | xmantissa/people.py | PersonScrollingFragment.filterByFilter | def filterByFilter(self, filterName):
"""
Swap L{baseConstraint} with the result of calling
L{IPeopleFilter.getPeopleQueryComparison} on the named filter.
@type filterName: C{unicode}
"""
filter = self.filters[filterName]
self.baseConstraint = filter.getPeopleQueryComparison(self.store) | python | def filterByFilter(self, filterName):
"""
Swap L{baseConstraint} with the result of calling
L{IPeopleFilter.getPeopleQueryComparison} on the named filter.
@type filterName: C{unicode}
"""
filter = self.filters[filterName]
self.baseConstraint = filter.getPeopleQueryComparison(self.store) | [
"def",
"filterByFilter",
"(",
"self",
",",
"filterName",
")",
":",
"filter",
"=",
"self",
".",
"filters",
"[",
"filterName",
"]",
"self",
".",
"baseConstraint",
"=",
"filter",
".",
"getPeopleQueryComparison",
"(",
"self",
".",
"store",
")"
] | Swap L{baseConstraint} with the result of calling
L{IPeopleFilter.getPeopleQueryComparison} on the named filter.
@type filterName: C{unicode} | [
"Swap",
"L",
"{",
"baseConstraint",
"}",
"with",
"the",
"result",
"of",
"calling",
"L",
"{",
"IPeopleFilter",
".",
"getPeopleQueryComparison",
"}",
"on",
"the",
"named",
"filter",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1338-L1346 |
twisted/mantissa | xmantissa/people.py | ReadOnlyContactInfoView.contactInfo | def contactInfo(self, request, tag):
"""
Render the result of calling L{IContactType.getReadOnlyView} on the
corresponding L{IContactType} for each piece of contact info
associated with L{person}. Arrange the result by group, using
C{tag}'s I{contact-group} pattern. Groupless contact items will have
their views yielded directly.
The I{contact-group} pattern appears once for each distinct
L{ContactGroup}, with the following slots filled:
I{name} - The group's C{groupName}.
I{views} - A sequence of read-only views belonging to the group.
"""
groupPattern = inevow.IQ(tag).patternGenerator('contact-group')
groupedViews = self.organizer.groupReadOnlyViews(self.person)
for (groupName, views) in sorted(groupedViews.items()):
if groupName is None:
yield views
else:
yield groupPattern().fillSlots(
'name', groupName).fillSlots(
'views', views) | python | def contactInfo(self, request, tag):
"""
Render the result of calling L{IContactType.getReadOnlyView} on the
corresponding L{IContactType} for each piece of contact info
associated with L{person}. Arrange the result by group, using
C{tag}'s I{contact-group} pattern. Groupless contact items will have
their views yielded directly.
The I{contact-group} pattern appears once for each distinct
L{ContactGroup}, with the following slots filled:
I{name} - The group's C{groupName}.
I{views} - A sequence of read-only views belonging to the group.
"""
groupPattern = inevow.IQ(tag).patternGenerator('contact-group')
groupedViews = self.organizer.groupReadOnlyViews(self.person)
for (groupName, views) in sorted(groupedViews.items()):
if groupName is None:
yield views
else:
yield groupPattern().fillSlots(
'name', groupName).fillSlots(
'views', views) | [
"def",
"contactInfo",
"(",
"self",
",",
"request",
",",
"tag",
")",
":",
"groupPattern",
"=",
"inevow",
".",
"IQ",
"(",
"tag",
")",
".",
"patternGenerator",
"(",
"'contact-group'",
")",
"groupedViews",
"=",
"self",
".",
"organizer",
".",
"groupReadOnlyViews"... | Render the result of calling L{IContactType.getReadOnlyView} on the
corresponding L{IContactType} for each piece of contact info
associated with L{person}. Arrange the result by group, using
C{tag}'s I{contact-group} pattern. Groupless contact items will have
their views yielded directly.
The I{contact-group} pattern appears once for each distinct
L{ContactGroup}, with the following slots filled:
I{name} - The group's C{groupName}.
I{views} - A sequence of read-only views belonging to the group. | [
"Render",
"the",
"result",
"of",
"calling",
"L",
"{",
"IContactType",
".",
"getReadOnlyView",
"}",
"on",
"the",
"corresponding",
"L",
"{",
"IContactType",
"}",
"for",
"each",
"piece",
"of",
"contact",
"info",
"associated",
"with",
"L",
"{",
"person",
"}",
... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1422-L1443 |
twisted/mantissa | xmantissa/people.py | PersonPluginView.pluginTabbedPane | def pluginTabbedPane(self, request, tag):
"""
Render a L{tabbedPane.TabbedPaneFragment} with an entry for each item
in L{plugins}.
"""
iq = inevow.IQ(tag)
tabNames = [
_organizerPluginName(p).encode('ascii') # gunk
for p in self.plugins]
child = tabbedPane.TabbedPaneFragment(
zip(tabNames,
([self.getPluginWidget(tabNames[0])]
+ [iq.onePattern('pane-body') for _ in tabNames[1:]])))
child.jsClass = u'Mantissa.People.PluginTabbedPane'
child.setFragmentParent(self)
return child | python | def pluginTabbedPane(self, request, tag):
"""
Render a L{tabbedPane.TabbedPaneFragment} with an entry for each item
in L{plugins}.
"""
iq = inevow.IQ(tag)
tabNames = [
_organizerPluginName(p).encode('ascii') # gunk
for p in self.plugins]
child = tabbedPane.TabbedPaneFragment(
zip(tabNames,
([self.getPluginWidget(tabNames[0])]
+ [iq.onePattern('pane-body') for _ in tabNames[1:]])))
child.jsClass = u'Mantissa.People.PluginTabbedPane'
child.setFragmentParent(self)
return child | [
"def",
"pluginTabbedPane",
"(",
"self",
",",
"request",
",",
"tag",
")",
":",
"iq",
"=",
"inevow",
".",
"IQ",
"(",
"tag",
")",
"tabNames",
"=",
"[",
"_organizerPluginName",
"(",
"p",
")",
".",
"encode",
"(",
"'ascii'",
")",
"# gunk",
"for",
"p",
"in"... | Render a L{tabbedPane.TabbedPaneFragment} with an entry for each item
in L{plugins}. | [
"Render",
"a",
"L",
"{",
"tabbedPane",
".",
"TabbedPaneFragment",
"}",
"with",
"an",
"entry",
"for",
"each",
"item",
"in",
"L",
"{",
"plugins",
"}",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1509-L1524 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.