id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 51
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
2,000 | HPAC/matchpy | matchpy/matching/syntactic.py | FlatTerm._combined_wildcards_iter | def _combined_wildcards_iter(flatterm: Iterator[TermAtom]) -> Iterator[TermAtom]:
"""Combine consecutive wildcards in a flatterm into a single one."""
last_wildcard = None # type: Optional[Wildcard]
for term in flatterm:
if isinstance(term, Wildcard) and not isinstance(term, SymbolWildcard):
if last_wildcard is not None:
new_min_count = last_wildcard.min_count + term.min_count
new_fixed_size = last_wildcard.fixed_size and term.fixed_size
last_wildcard = Wildcard(new_min_count, new_fixed_size)
else:
last_wildcard = Wildcard(term.min_count, term.fixed_size)
else:
if last_wildcard is not None:
yield last_wildcard
last_wildcard = None
yield term
if last_wildcard is not None:
yield last_wildcard | python | def _combined_wildcards_iter(flatterm: Iterator[TermAtom]) -> Iterator[TermAtom]:
last_wildcard = None # type: Optional[Wildcard]
for term in flatterm:
if isinstance(term, Wildcard) and not isinstance(term, SymbolWildcard):
if last_wildcard is not None:
new_min_count = last_wildcard.min_count + term.min_count
new_fixed_size = last_wildcard.fixed_size and term.fixed_size
last_wildcard = Wildcard(new_min_count, new_fixed_size)
else:
last_wildcard = Wildcard(term.min_count, term.fixed_size)
else:
if last_wildcard is not None:
yield last_wildcard
last_wildcard = None
yield term
if last_wildcard is not None:
yield last_wildcard | [
"def",
"_combined_wildcards_iter",
"(",
"flatterm",
":",
"Iterator",
"[",
"TermAtom",
"]",
")",
"->",
"Iterator",
"[",
"TermAtom",
"]",
":",
"last_wildcard",
"=",
"None",
"# type: Optional[Wildcard]",
"for",
"term",
"in",
"flatterm",
":",
"if",
"isinstance",
"(",
"term",
",",
"Wildcard",
")",
"and",
"not",
"isinstance",
"(",
"term",
",",
"SymbolWildcard",
")",
":",
"if",
"last_wildcard",
"is",
"not",
"None",
":",
"new_min_count",
"=",
"last_wildcard",
".",
"min_count",
"+",
"term",
".",
"min_count",
"new_fixed_size",
"=",
"last_wildcard",
".",
"fixed_size",
"and",
"term",
".",
"fixed_size",
"last_wildcard",
"=",
"Wildcard",
"(",
"new_min_count",
",",
"new_fixed_size",
")",
"else",
":",
"last_wildcard",
"=",
"Wildcard",
"(",
"term",
".",
"min_count",
",",
"term",
".",
"fixed_size",
")",
"else",
":",
"if",
"last_wildcard",
"is",
"not",
"None",
":",
"yield",
"last_wildcard",
"last_wildcard",
"=",
"None",
"yield",
"term",
"if",
"last_wildcard",
"is",
"not",
"None",
":",
"yield",
"last_wildcard"
] | Combine consecutive wildcards in a flatterm into a single one. | [
"Combine",
"consecutive",
"wildcards",
"in",
"a",
"flatterm",
"into",
"a",
"single",
"one",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L174-L191 |
2,001 | HPAC/matchpy | matchpy/matching/syntactic.py | _StateQueueItem.labels | def labels(self) -> Set[TransitionLabel]:
"""Return the set of transition labels to examine for this queue state.
This is the union of the transition label sets for both states.
However, if one of the states is fixed, it is excluded from this union and a wildcard transition is included
instead. Also, when already in a failed state (one of the states is ``None``), the :const:`OPERATION_END` is
also included.
"""
labels = set() # type: Set[TransitionLabel]
if self.state1 is not None and self.fixed != 1:
labels.update(self.state1.keys())
if self.state2 is not None and self.fixed != 2:
labels.update(self.state2.keys())
if self.fixed != 0:
if self.fixed == 1 and self.state2 is None:
labels.add(OPERATION_END)
elif self.fixed == 2 and self.state1 is None:
labels.add(OPERATION_END)
labels.add(Wildcard)
return labels | python | def labels(self) -> Set[TransitionLabel]:
labels = set() # type: Set[TransitionLabel]
if self.state1 is not None and self.fixed != 1:
labels.update(self.state1.keys())
if self.state2 is not None and self.fixed != 2:
labels.update(self.state2.keys())
if self.fixed != 0:
if self.fixed == 1 and self.state2 is None:
labels.add(OPERATION_END)
elif self.fixed == 2 and self.state1 is None:
labels.add(OPERATION_END)
labels.add(Wildcard)
return labels | [
"def",
"labels",
"(",
"self",
")",
"->",
"Set",
"[",
"TransitionLabel",
"]",
":",
"labels",
"=",
"set",
"(",
")",
"# type: Set[TransitionLabel]",
"if",
"self",
".",
"state1",
"is",
"not",
"None",
"and",
"self",
".",
"fixed",
"!=",
"1",
":",
"labels",
".",
"update",
"(",
"self",
".",
"state1",
".",
"keys",
"(",
")",
")",
"if",
"self",
".",
"state2",
"is",
"not",
"None",
"and",
"self",
".",
"fixed",
"!=",
"2",
":",
"labels",
".",
"update",
"(",
"self",
".",
"state2",
".",
"keys",
"(",
")",
")",
"if",
"self",
".",
"fixed",
"!=",
"0",
":",
"if",
"self",
".",
"fixed",
"==",
"1",
"and",
"self",
".",
"state2",
"is",
"None",
":",
"labels",
".",
"add",
"(",
"OPERATION_END",
")",
"elif",
"self",
".",
"fixed",
"==",
"2",
"and",
"self",
".",
"state1",
"is",
"None",
":",
"labels",
".",
"add",
"(",
"OPERATION_END",
")",
"labels",
".",
"add",
"(",
"Wildcard",
")",
"return",
"labels"
] | Return the set of transition labels to examine for this queue state.
This is the union of the transition label sets for both states.
However, if one of the states is fixed, it is excluded from this union and a wildcard transition is included
instead. Also, when already in a failed state (one of the states is ``None``), the :const:`OPERATION_END` is
also included. | [
"Return",
"the",
"set",
"of",
"transition",
"labels",
"to",
"examine",
"for",
"this",
"queue",
"state",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L280-L299 |
2,002 | HPAC/matchpy | matchpy/matching/syntactic.py | DiscriminationNet.add | def add(self, pattern: Union[Pattern, FlatTerm], final_label: T=None) -> int:
"""Add a pattern to the discrimination net.
Args:
pattern:
The pattern which is added to the DiscriminationNet. If an expression is given, it will be converted to
a `FlatTerm` for internal processing. You can also pass a `FlatTerm` directly.
final_label:
A label that is returned if the pattern matches when using :meth:`match`. This will default to the
pattern itself.
Returns:
The index of the newly added pattern. This is used internally to later to get the pattern and its final
label once a match is found.
"""
index = len(self._patterns)
self._patterns.append((pattern, final_label))
flatterm = FlatTerm(pattern.expression) if not isinstance(pattern, FlatTerm) else pattern
if flatterm.is_syntactic or len(flatterm) == 1:
net = self._generate_syntactic_net(flatterm, index)
else:
net = self._generate_net(flatterm, index)
if self._root:
self._root = self._product_net(self._root, net)
else:
self._root = net
return index | python | def add(self, pattern: Union[Pattern, FlatTerm], final_label: T=None) -> int:
index = len(self._patterns)
self._patterns.append((pattern, final_label))
flatterm = FlatTerm(pattern.expression) if not isinstance(pattern, FlatTerm) else pattern
if flatterm.is_syntactic or len(flatterm) == 1:
net = self._generate_syntactic_net(flatterm, index)
else:
net = self._generate_net(flatterm, index)
if self._root:
self._root = self._product_net(self._root, net)
else:
self._root = net
return index | [
"def",
"add",
"(",
"self",
",",
"pattern",
":",
"Union",
"[",
"Pattern",
",",
"FlatTerm",
"]",
",",
"final_label",
":",
"T",
"=",
"None",
")",
"->",
"int",
":",
"index",
"=",
"len",
"(",
"self",
".",
"_patterns",
")",
"self",
".",
"_patterns",
".",
"append",
"(",
"(",
"pattern",
",",
"final_label",
")",
")",
"flatterm",
"=",
"FlatTerm",
"(",
"pattern",
".",
"expression",
")",
"if",
"not",
"isinstance",
"(",
"pattern",
",",
"FlatTerm",
")",
"else",
"pattern",
"if",
"flatterm",
".",
"is_syntactic",
"or",
"len",
"(",
"flatterm",
")",
"==",
"1",
":",
"net",
"=",
"self",
".",
"_generate_syntactic_net",
"(",
"flatterm",
",",
"index",
")",
"else",
":",
"net",
"=",
"self",
".",
"_generate_net",
"(",
"flatterm",
",",
"index",
")",
"if",
"self",
".",
"_root",
":",
"self",
".",
"_root",
"=",
"self",
".",
"_product_net",
"(",
"self",
".",
"_root",
",",
"net",
")",
"else",
":",
"self",
".",
"_root",
"=",
"net",
"return",
"index"
] | Add a pattern to the discrimination net.
Args:
pattern:
The pattern which is added to the DiscriminationNet. If an expression is given, it will be converted to
a `FlatTerm` for internal processing. You can also pass a `FlatTerm` directly.
final_label:
A label that is returned if the pattern matches when using :meth:`match`. This will default to the
pattern itself.
Returns:
The index of the newly added pattern. This is used internally to later to get the pattern and its final
label once a match is found. | [
"Add",
"a",
"pattern",
"to",
"the",
"discrimination",
"net",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L329-L356 |
2,003 | HPAC/matchpy | matchpy/matching/syntactic.py | DiscriminationNet._generate_net | def _generate_net(cls, flatterm: FlatTerm, final_label: T) -> _State[T]:
"""Generates a DFA matching the given pattern."""
# Capture the last sequence wildcard for every level of operation nesting on a stack
# Used to add backtracking edges in case the "match" fails later
last_wildcards = [None]
# Generate a fail state for every level of nesting to backtrack to a sequence wildcard in a parent Expression
# in case no match can be found
fail_states = [None]
operand_counts = [0]
root = state = _State()
states = {root.id: root}
for term in flatterm:
if operand_counts[-1] >= 0:
operand_counts[-1] += 1
# For wildcards, generate a chain of #min_count Wildcard edges
# If the wildcard is unbounded (fixed_size = False),
# add a wildcard self loop at the end
if isinstance(term, Wildcard):
# Generate a chain of #min_count Wildcard edges
for _ in range(term.min_count):
state = cls._create_child_state(state, Wildcard)
states[state.id] = state
# If it is a sequence wildcard, add a self loop
if not term.fixed_size:
state[Wildcard] = state
last_wildcards[-1] = state
operand_counts[-1] = -1
else:
state = cls._create_child_state(state, term)
states[state.id] = state
if is_operation(term):
fail_state = None
if last_wildcards[-1] or fail_states[-1]:
last_fail_state = (
fail_states[-1]
if not isinstance(fail_states[-1], list) else fail_states[-1][operand_counts[-1]]
)
if term.arity.fixed_size:
fail_state = _State()
states[fail_state.id] = fail_state
new_fail_states = [fail_state]
for _ in range(term.arity.min_count):
new_fail_state = _State()
states[new_fail_state.id] = new_fail_state
fail_state[Wildcard] = new_fail_state
fail_state = new_fail_state
new_fail_states.append(new_fail_state)
fail_state[OPERATION_END] = last_wildcards[-1] or last_fail_state
fail_state = new_fail_states
else:
fail_state = _State()
states[fail_state.id] = fail_state
fail_state[OPERATION_END] = last_wildcards[-1] or last_fail_state
fail_state[Wildcard] = fail_state
fail_states.append(fail_state)
last_wildcards.append(None)
operand_counts.append(0)
elif term == OPERATION_END:
fail_states.pop()
last_wildcards.pop()
operand_counts.pop()
if last_wildcards[-1] != state:
if last_wildcards[-1]:
state[EPSILON] = last_wildcards[-1]
elif fail_states[-1]:
last_fail_state = (
fail_states[-1]
if not isinstance(fail_states[-1], list) else fail_states[-1][operand_counts[-1]]
)
state[EPSILON] = last_fail_state
state.payload = [final_label]
return cls._convert_nfa_to_dfa(root, states) | python | def _generate_net(cls, flatterm: FlatTerm, final_label: T) -> _State[T]:
# Capture the last sequence wildcard for every level of operation nesting on a stack
# Used to add backtracking edges in case the "match" fails later
last_wildcards = [None]
# Generate a fail state for every level of nesting to backtrack to a sequence wildcard in a parent Expression
# in case no match can be found
fail_states = [None]
operand_counts = [0]
root = state = _State()
states = {root.id: root}
for term in flatterm:
if operand_counts[-1] >= 0:
operand_counts[-1] += 1
# For wildcards, generate a chain of #min_count Wildcard edges
# If the wildcard is unbounded (fixed_size = False),
# add a wildcard self loop at the end
if isinstance(term, Wildcard):
# Generate a chain of #min_count Wildcard edges
for _ in range(term.min_count):
state = cls._create_child_state(state, Wildcard)
states[state.id] = state
# If it is a sequence wildcard, add a self loop
if not term.fixed_size:
state[Wildcard] = state
last_wildcards[-1] = state
operand_counts[-1] = -1
else:
state = cls._create_child_state(state, term)
states[state.id] = state
if is_operation(term):
fail_state = None
if last_wildcards[-1] or fail_states[-1]:
last_fail_state = (
fail_states[-1]
if not isinstance(fail_states[-1], list) else fail_states[-1][operand_counts[-1]]
)
if term.arity.fixed_size:
fail_state = _State()
states[fail_state.id] = fail_state
new_fail_states = [fail_state]
for _ in range(term.arity.min_count):
new_fail_state = _State()
states[new_fail_state.id] = new_fail_state
fail_state[Wildcard] = new_fail_state
fail_state = new_fail_state
new_fail_states.append(new_fail_state)
fail_state[OPERATION_END] = last_wildcards[-1] or last_fail_state
fail_state = new_fail_states
else:
fail_state = _State()
states[fail_state.id] = fail_state
fail_state[OPERATION_END] = last_wildcards[-1] or last_fail_state
fail_state[Wildcard] = fail_state
fail_states.append(fail_state)
last_wildcards.append(None)
operand_counts.append(0)
elif term == OPERATION_END:
fail_states.pop()
last_wildcards.pop()
operand_counts.pop()
if last_wildcards[-1] != state:
if last_wildcards[-1]:
state[EPSILON] = last_wildcards[-1]
elif fail_states[-1]:
last_fail_state = (
fail_states[-1]
if not isinstance(fail_states[-1], list) else fail_states[-1][operand_counts[-1]]
)
state[EPSILON] = last_fail_state
state.payload = [final_label]
return cls._convert_nfa_to_dfa(root, states) | [
"def",
"_generate_net",
"(",
"cls",
",",
"flatterm",
":",
"FlatTerm",
",",
"final_label",
":",
"T",
")",
"->",
"_State",
"[",
"T",
"]",
":",
"# Capture the last sequence wildcard for every level of operation nesting on a stack",
"# Used to add backtracking edges in case the \"match\" fails later",
"last_wildcards",
"=",
"[",
"None",
"]",
"# Generate a fail state for every level of nesting to backtrack to a sequence wildcard in a parent Expression",
"# in case no match can be found",
"fail_states",
"=",
"[",
"None",
"]",
"operand_counts",
"=",
"[",
"0",
"]",
"root",
"=",
"state",
"=",
"_State",
"(",
")",
"states",
"=",
"{",
"root",
".",
"id",
":",
"root",
"}",
"for",
"term",
"in",
"flatterm",
":",
"if",
"operand_counts",
"[",
"-",
"1",
"]",
">=",
"0",
":",
"operand_counts",
"[",
"-",
"1",
"]",
"+=",
"1",
"# For wildcards, generate a chain of #min_count Wildcard edges",
"# If the wildcard is unbounded (fixed_size = False),",
"# add a wildcard self loop at the end",
"if",
"isinstance",
"(",
"term",
",",
"Wildcard",
")",
":",
"# Generate a chain of #min_count Wildcard edges",
"for",
"_",
"in",
"range",
"(",
"term",
".",
"min_count",
")",
":",
"state",
"=",
"cls",
".",
"_create_child_state",
"(",
"state",
",",
"Wildcard",
")",
"states",
"[",
"state",
".",
"id",
"]",
"=",
"state",
"# If it is a sequence wildcard, add a self loop",
"if",
"not",
"term",
".",
"fixed_size",
":",
"state",
"[",
"Wildcard",
"]",
"=",
"state",
"last_wildcards",
"[",
"-",
"1",
"]",
"=",
"state",
"operand_counts",
"[",
"-",
"1",
"]",
"=",
"-",
"1",
"else",
":",
"state",
"=",
"cls",
".",
"_create_child_state",
"(",
"state",
",",
"term",
")",
"states",
"[",
"state",
".",
"id",
"]",
"=",
"state",
"if",
"is_operation",
"(",
"term",
")",
":",
"fail_state",
"=",
"None",
"if",
"last_wildcards",
"[",
"-",
"1",
"]",
"or",
"fail_states",
"[",
"-",
"1",
"]",
":",
"last_fail_state",
"=",
"(",
"fail_states",
"[",
"-",
"1",
"]",
"if",
"not",
"isinstance",
"(",
"fail_states",
"[",
"-",
"1",
"]",
",",
"list",
")",
"else",
"fail_states",
"[",
"-",
"1",
"]",
"[",
"operand_counts",
"[",
"-",
"1",
"]",
"]",
")",
"if",
"term",
".",
"arity",
".",
"fixed_size",
":",
"fail_state",
"=",
"_State",
"(",
")",
"states",
"[",
"fail_state",
".",
"id",
"]",
"=",
"fail_state",
"new_fail_states",
"=",
"[",
"fail_state",
"]",
"for",
"_",
"in",
"range",
"(",
"term",
".",
"arity",
".",
"min_count",
")",
":",
"new_fail_state",
"=",
"_State",
"(",
")",
"states",
"[",
"new_fail_state",
".",
"id",
"]",
"=",
"new_fail_state",
"fail_state",
"[",
"Wildcard",
"]",
"=",
"new_fail_state",
"fail_state",
"=",
"new_fail_state",
"new_fail_states",
".",
"append",
"(",
"new_fail_state",
")",
"fail_state",
"[",
"OPERATION_END",
"]",
"=",
"last_wildcards",
"[",
"-",
"1",
"]",
"or",
"last_fail_state",
"fail_state",
"=",
"new_fail_states",
"else",
":",
"fail_state",
"=",
"_State",
"(",
")",
"states",
"[",
"fail_state",
".",
"id",
"]",
"=",
"fail_state",
"fail_state",
"[",
"OPERATION_END",
"]",
"=",
"last_wildcards",
"[",
"-",
"1",
"]",
"or",
"last_fail_state",
"fail_state",
"[",
"Wildcard",
"]",
"=",
"fail_state",
"fail_states",
".",
"append",
"(",
"fail_state",
")",
"last_wildcards",
".",
"append",
"(",
"None",
")",
"operand_counts",
".",
"append",
"(",
"0",
")",
"elif",
"term",
"==",
"OPERATION_END",
":",
"fail_states",
".",
"pop",
"(",
")",
"last_wildcards",
".",
"pop",
"(",
")",
"operand_counts",
".",
"pop",
"(",
")",
"if",
"last_wildcards",
"[",
"-",
"1",
"]",
"!=",
"state",
":",
"if",
"last_wildcards",
"[",
"-",
"1",
"]",
":",
"state",
"[",
"EPSILON",
"]",
"=",
"last_wildcards",
"[",
"-",
"1",
"]",
"elif",
"fail_states",
"[",
"-",
"1",
"]",
":",
"last_fail_state",
"=",
"(",
"fail_states",
"[",
"-",
"1",
"]",
"if",
"not",
"isinstance",
"(",
"fail_states",
"[",
"-",
"1",
"]",
",",
"list",
")",
"else",
"fail_states",
"[",
"-",
"1",
"]",
"[",
"operand_counts",
"[",
"-",
"1",
"]",
"]",
")",
"state",
"[",
"EPSILON",
"]",
"=",
"last_fail_state",
"state",
".",
"payload",
"=",
"[",
"final_label",
"]",
"return",
"cls",
".",
"_convert_nfa_to_dfa",
"(",
"root",
",",
"states",
")"
] | Generates a DFA matching the given pattern. | [
"Generates",
"a",
"DFA",
"matching",
"the",
"given",
"pattern",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L385-L461 |
2,004 | HPAC/matchpy | matchpy/matching/syntactic.py | DiscriminationNet.match | def match(self, subject: Union[Expression, FlatTerm]) -> Iterator[Tuple[T, Substitution]]:
"""Match the given subject against all patterns in the net.
Args:
subject:
The subject that is matched. Must be constant.
Yields:
A tuple :code:`(final label, substitution)`, where the first component is the final label associated with
the pattern as given when using :meth:`add()` and the second one is the match substitution.
"""
for index in self._match(subject):
pattern, label = self._patterns[index]
subst = Substitution()
if subst.extract_substitution(subject, pattern.expression):
for constraint in pattern.constraints:
if not constraint(subst):
break
else:
yield label, subst | python | def match(self, subject: Union[Expression, FlatTerm]) -> Iterator[Tuple[T, Substitution]]:
for index in self._match(subject):
pattern, label = self._patterns[index]
subst = Substitution()
if subst.extract_substitution(subject, pattern.expression):
for constraint in pattern.constraints:
if not constraint(subst):
break
else:
yield label, subst | [
"def",
"match",
"(",
"self",
",",
"subject",
":",
"Union",
"[",
"Expression",
",",
"FlatTerm",
"]",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"T",
",",
"Substitution",
"]",
"]",
":",
"for",
"index",
"in",
"self",
".",
"_match",
"(",
"subject",
")",
":",
"pattern",
",",
"label",
"=",
"self",
".",
"_patterns",
"[",
"index",
"]",
"subst",
"=",
"Substitution",
"(",
")",
"if",
"subst",
".",
"extract_substitution",
"(",
"subject",
",",
"pattern",
".",
"expression",
")",
":",
"for",
"constraint",
"in",
"pattern",
".",
"constraints",
":",
"if",
"not",
"constraint",
"(",
"subst",
")",
":",
"break",
"else",
":",
"yield",
"label",
",",
"subst"
] | Match the given subject against all patterns in the net.
Args:
subject:
The subject that is matched. Must be constant.
Yields:
A tuple :code:`(final label, substitution)`, where the first component is the final label associated with
the pattern as given when using :meth:`add()` and the second one is the match substitution. | [
"Match",
"the",
"given",
"subject",
"against",
"all",
"patterns",
"in",
"the",
"net",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L645-L664 |
2,005 | HPAC/matchpy | matchpy/matching/syntactic.py | DiscriminationNet.is_match | def is_match(self, subject: Union[Expression, FlatTerm]) -> bool:
"""Check if the given subject matches any pattern in the net.
Args:
subject:
The subject that is matched. Must be constant.
Returns:
True, if any pattern matches the subject.
"""
try:
next(self.match(subject))
except StopIteration:
return False
return True | python | def is_match(self, subject: Union[Expression, FlatTerm]) -> bool:
try:
next(self.match(subject))
except StopIteration:
return False
return True | [
"def",
"is_match",
"(",
"self",
",",
"subject",
":",
"Union",
"[",
"Expression",
",",
"FlatTerm",
"]",
")",
"->",
"bool",
":",
"try",
":",
"next",
"(",
"self",
".",
"match",
"(",
"subject",
")",
")",
"except",
"StopIteration",
":",
"return",
"False",
"return",
"True"
] | Check if the given subject matches any pattern in the net.
Args:
subject:
The subject that is matched. Must be constant.
Returns:
True, if any pattern matches the subject. | [
"Check",
"if",
"the",
"given",
"subject",
"matches",
"any",
"pattern",
"in",
"the",
"net",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L666-L680 |
2,006 | HPAC/matchpy | matchpy/matching/syntactic.py | DiscriminationNet.as_graph | def as_graph(self) -> Digraph: # pragma: no cover
"""Renders the discrimination net as graphviz digraph."""
if Digraph is None:
raise ImportError('The graphviz package is required to draw the graph.')
dot = Digraph()
nodes = set()
queue = [self._root]
while queue:
state = queue.pop(0)
if not state.payload:
dot.node('n{!s}'.format(state.id), '', {'shape': ('circle' if state else 'doublecircle')})
else:
dot.node('n{!s}'.format(state.id), '\n'.join(map(str, state.payload)), {'shape': 'box'})
for next_state in state.values():
if next_state.id not in nodes:
queue.append(next_state)
nodes.add(state.id)
nodes = set()
queue = [self._root]
while queue:
state = queue.pop(0)
if state.id in nodes:
continue
nodes.add(state.id)
for (label, other) in state.items():
dot.edge('n{!s}'.format(state.id), 'n{!s}'.format(other.id), _term_str(label))
if other.id not in nodes:
queue.append(other)
return dot | python | def as_graph(self) -> Digraph: # pragma: no cover
if Digraph is None:
raise ImportError('The graphviz package is required to draw the graph.')
dot = Digraph()
nodes = set()
queue = [self._root]
while queue:
state = queue.pop(0)
if not state.payload:
dot.node('n{!s}'.format(state.id), '', {'shape': ('circle' if state else 'doublecircle')})
else:
dot.node('n{!s}'.format(state.id), '\n'.join(map(str, state.payload)), {'shape': 'box'})
for next_state in state.values():
if next_state.id not in nodes:
queue.append(next_state)
nodes.add(state.id)
nodes = set()
queue = [self._root]
while queue:
state = queue.pop(0)
if state.id in nodes:
continue
nodes.add(state.id)
for (label, other) in state.items():
dot.edge('n{!s}'.format(state.id), 'n{!s}'.format(other.id), _term_str(label))
if other.id not in nodes:
queue.append(other)
return dot | [
"def",
"as_graph",
"(",
"self",
")",
"->",
"Digraph",
":",
"# pragma: no cover",
"if",
"Digraph",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"'The graphviz package is required to draw the graph.'",
")",
"dot",
"=",
"Digraph",
"(",
")",
"nodes",
"=",
"set",
"(",
")",
"queue",
"=",
"[",
"self",
".",
"_root",
"]",
"while",
"queue",
":",
"state",
"=",
"queue",
".",
"pop",
"(",
"0",
")",
"if",
"not",
"state",
".",
"payload",
":",
"dot",
".",
"node",
"(",
"'n{!s}'",
".",
"format",
"(",
"state",
".",
"id",
")",
",",
"''",
",",
"{",
"'shape'",
":",
"(",
"'circle'",
"if",
"state",
"else",
"'doublecircle'",
")",
"}",
")",
"else",
":",
"dot",
".",
"node",
"(",
"'n{!s}'",
".",
"format",
"(",
"state",
".",
"id",
")",
",",
"'\\n'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"state",
".",
"payload",
")",
")",
",",
"{",
"'shape'",
":",
"'box'",
"}",
")",
"for",
"next_state",
"in",
"state",
".",
"values",
"(",
")",
":",
"if",
"next_state",
".",
"id",
"not",
"in",
"nodes",
":",
"queue",
".",
"append",
"(",
"next_state",
")",
"nodes",
".",
"add",
"(",
"state",
".",
"id",
")",
"nodes",
"=",
"set",
"(",
")",
"queue",
"=",
"[",
"self",
".",
"_root",
"]",
"while",
"queue",
":",
"state",
"=",
"queue",
".",
"pop",
"(",
"0",
")",
"if",
"state",
".",
"id",
"in",
"nodes",
":",
"continue",
"nodes",
".",
"add",
"(",
"state",
".",
"id",
")",
"for",
"(",
"label",
",",
"other",
")",
"in",
"state",
".",
"items",
"(",
")",
":",
"dot",
".",
"edge",
"(",
"'n{!s}'",
".",
"format",
"(",
"state",
".",
"id",
")",
",",
"'n{!s}'",
".",
"format",
"(",
"other",
".",
"id",
")",
",",
"_term_str",
"(",
"label",
")",
")",
"if",
"other",
".",
"id",
"not",
"in",
"nodes",
":",
"queue",
".",
"append",
"(",
"other",
")",
"return",
"dot"
] | Renders the discrimination net as graphviz digraph. | [
"Renders",
"the",
"discrimination",
"net",
"as",
"graphviz",
"digraph",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L682-L715 |
2,007 | HPAC/matchpy | matchpy/matching/syntactic.py | SequenceMatcher.add | def add(self, pattern: Pattern) -> int:
"""Add a pattern that will be recognized by the matcher.
Args:
pattern:
The pattern to add.
Returns:
An internal index for the pattern.
Raises:
ValueError:
If the pattern does not have the correct form.
TypeError:
If the pattern is not a non-commutative operation.
"""
inner = pattern.expression
if self.operation is None:
if not isinstance(inner, Operation) or isinstance(inner, CommutativeOperation):
raise TypeError("Pattern must be a non-commutative operation.")
self.operation = type(inner)
elif not isinstance(inner, self.operation):
raise TypeError(
"All patterns must be the same operation, expected {} but got {}".format(self.operation, type(inner))
)
if op_len(inner) < 3:
raise ValueError("Pattern has not enough operands.")
operands = list(op_iter(inner))
first_name = self._check_wildcard_and_get_name(operands[0])
last_name = self._check_wildcard_and_get_name(operands[-1])
index = len(self._patterns)
self._patterns.append((pattern, first_name, last_name))
flatterm = FlatTerm.merged(*(FlatTerm(o) for o in operands[1:-1]))
self._net.add(flatterm, index)
return index | python | def add(self, pattern: Pattern) -> int:
inner = pattern.expression
if self.operation is None:
if not isinstance(inner, Operation) or isinstance(inner, CommutativeOperation):
raise TypeError("Pattern must be a non-commutative operation.")
self.operation = type(inner)
elif not isinstance(inner, self.operation):
raise TypeError(
"All patterns must be the same operation, expected {} but got {}".format(self.operation, type(inner))
)
if op_len(inner) < 3:
raise ValueError("Pattern has not enough operands.")
operands = list(op_iter(inner))
first_name = self._check_wildcard_and_get_name(operands[0])
last_name = self._check_wildcard_and_get_name(operands[-1])
index = len(self._patterns)
self._patterns.append((pattern, first_name, last_name))
flatterm = FlatTerm.merged(*(FlatTerm(o) for o in operands[1:-1]))
self._net.add(flatterm, index)
return index | [
"def",
"add",
"(",
"self",
",",
"pattern",
":",
"Pattern",
")",
"->",
"int",
":",
"inner",
"=",
"pattern",
".",
"expression",
"if",
"self",
".",
"operation",
"is",
"None",
":",
"if",
"not",
"isinstance",
"(",
"inner",
",",
"Operation",
")",
"or",
"isinstance",
"(",
"inner",
",",
"CommutativeOperation",
")",
":",
"raise",
"TypeError",
"(",
"\"Pattern must be a non-commutative operation.\"",
")",
"self",
".",
"operation",
"=",
"type",
"(",
"inner",
")",
"elif",
"not",
"isinstance",
"(",
"inner",
",",
"self",
".",
"operation",
")",
":",
"raise",
"TypeError",
"(",
"\"All patterns must be the same operation, expected {} but got {}\"",
".",
"format",
"(",
"self",
".",
"operation",
",",
"type",
"(",
"inner",
")",
")",
")",
"if",
"op_len",
"(",
"inner",
")",
"<",
"3",
":",
"raise",
"ValueError",
"(",
"\"Pattern has not enough operands.\"",
")",
"operands",
"=",
"list",
"(",
"op_iter",
"(",
"inner",
")",
")",
"first_name",
"=",
"self",
".",
"_check_wildcard_and_get_name",
"(",
"operands",
"[",
"0",
"]",
")",
"last_name",
"=",
"self",
".",
"_check_wildcard_and_get_name",
"(",
"operands",
"[",
"-",
"1",
"]",
")",
"index",
"=",
"len",
"(",
"self",
".",
"_patterns",
")",
"self",
".",
"_patterns",
".",
"append",
"(",
"(",
"pattern",
",",
"first_name",
",",
"last_name",
")",
")",
"flatterm",
"=",
"FlatTerm",
".",
"merged",
"(",
"*",
"(",
"FlatTerm",
"(",
"o",
")",
"for",
"o",
"in",
"operands",
"[",
"1",
":",
"-",
"1",
"]",
")",
")",
"self",
".",
"_net",
".",
"add",
"(",
"flatterm",
",",
"index",
")",
"return",
"index"
] | Add a pattern that will be recognized by the matcher.
Args:
pattern:
The pattern to add.
Returns:
An internal index for the pattern.
Raises:
ValueError:
If the pattern does not have the correct form.
TypeError:
If the pattern is not a non-commutative operation. | [
"Add",
"a",
"pattern",
"that",
"will",
"be",
"recognized",
"by",
"the",
"matcher",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L750-L790 |
2,008 | HPAC/matchpy | matchpy/matching/syntactic.py | SequenceMatcher.match | def match(self, subject: Expression) -> Iterator[Tuple[Pattern, Substitution]]:
"""Match the given subject against all patterns in the sequence matcher.
Args:
subject:
The subject that is matched. Must be constant.
Yields:
A tuple :code:`(pattern, substitution)` for every matching pattern.
"""
if not isinstance(subject, self.operation):
return
subjects = list(op_iter(subject))
flatterms = [FlatTerm(o) for o in subjects]
for i in range(len(flatterms)):
flatterm = FlatTerm.merged(*flatterms[i:])
for index in self._net._match(flatterm, collect=True):
match_index = self._net._patterns[index][1]
pattern, first_name, last_name = self._patterns[match_index]
operand_count = op_len(pattern.expression) - 2
expr_operands = subjects[i:i + operand_count]
patt_operands = list(op_iter(pattern.expression))[1:-1]
substitution = Substitution()
if not all(itertools.starmap(substitution.extract_substitution, zip(expr_operands, patt_operands))):
continue
try:
if first_name is not None:
substitution.try_add_variable(first_name, tuple(subjects[:i]))
if last_name is not None:
substitution.try_add_variable(last_name, tuple(subjects[i + operand_count:]))
except ValueError:
continue
for constraint in pattern.constraints:
if not constraint(substitution):
break
else:
yield pattern, substitution | python | def match(self, subject: Expression) -> Iterator[Tuple[Pattern, Substitution]]:
if not isinstance(subject, self.operation):
return
subjects = list(op_iter(subject))
flatterms = [FlatTerm(o) for o in subjects]
for i in range(len(flatterms)):
flatterm = FlatTerm.merged(*flatterms[i:])
for index in self._net._match(flatterm, collect=True):
match_index = self._net._patterns[index][1]
pattern, first_name, last_name = self._patterns[match_index]
operand_count = op_len(pattern.expression) - 2
expr_operands = subjects[i:i + operand_count]
patt_operands = list(op_iter(pattern.expression))[1:-1]
substitution = Substitution()
if not all(itertools.starmap(substitution.extract_substitution, zip(expr_operands, patt_operands))):
continue
try:
if first_name is not None:
substitution.try_add_variable(first_name, tuple(subjects[:i]))
if last_name is not None:
substitution.try_add_variable(last_name, tuple(subjects[i + operand_count:]))
except ValueError:
continue
for constraint in pattern.constraints:
if not constraint(substitution):
break
else:
yield pattern, substitution | [
"def",
"match",
"(",
"self",
",",
"subject",
":",
"Expression",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"Pattern",
",",
"Substitution",
"]",
"]",
":",
"if",
"not",
"isinstance",
"(",
"subject",
",",
"self",
".",
"operation",
")",
":",
"return",
"subjects",
"=",
"list",
"(",
"op_iter",
"(",
"subject",
")",
")",
"flatterms",
"=",
"[",
"FlatTerm",
"(",
"o",
")",
"for",
"o",
"in",
"subjects",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"flatterms",
")",
")",
":",
"flatterm",
"=",
"FlatTerm",
".",
"merged",
"(",
"*",
"flatterms",
"[",
"i",
":",
"]",
")",
"for",
"index",
"in",
"self",
".",
"_net",
".",
"_match",
"(",
"flatterm",
",",
"collect",
"=",
"True",
")",
":",
"match_index",
"=",
"self",
".",
"_net",
".",
"_patterns",
"[",
"index",
"]",
"[",
"1",
"]",
"pattern",
",",
"first_name",
",",
"last_name",
"=",
"self",
".",
"_patterns",
"[",
"match_index",
"]",
"operand_count",
"=",
"op_len",
"(",
"pattern",
".",
"expression",
")",
"-",
"2",
"expr_operands",
"=",
"subjects",
"[",
"i",
":",
"i",
"+",
"operand_count",
"]",
"patt_operands",
"=",
"list",
"(",
"op_iter",
"(",
"pattern",
".",
"expression",
")",
")",
"[",
"1",
":",
"-",
"1",
"]",
"substitution",
"=",
"Substitution",
"(",
")",
"if",
"not",
"all",
"(",
"itertools",
".",
"starmap",
"(",
"substitution",
".",
"extract_substitution",
",",
"zip",
"(",
"expr_operands",
",",
"patt_operands",
")",
")",
")",
":",
"continue",
"try",
":",
"if",
"first_name",
"is",
"not",
"None",
":",
"substitution",
".",
"try_add_variable",
"(",
"first_name",
",",
"tuple",
"(",
"subjects",
"[",
":",
"i",
"]",
")",
")",
"if",
"last_name",
"is",
"not",
"None",
":",
"substitution",
".",
"try_add_variable",
"(",
"last_name",
",",
"tuple",
"(",
"subjects",
"[",
"i",
"+",
"operand_count",
":",
"]",
")",
")",
"except",
"ValueError",
":",
"continue",
"for",
"constraint",
"in",
"pattern",
".",
"constraints",
":",
"if",
"not",
"constraint",
"(",
"substitution",
")",
":",
"break",
"else",
":",
"yield",
"pattern",
",",
"substitution"
] | Match the given subject against all patterns in the sequence matcher.
Args:
subject:
The subject that is matched. Must be constant.
Yields:
A tuple :code:`(pattern, substitution)` for every matching pattern. | [
"Match",
"the",
"given",
"subject",
"against",
"all",
"patterns",
"in",
"the",
"sequence",
"matcher",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/syntactic.py#L826-L868 |
2,009 | HPAC/matchpy | matchpy/matching/one_to_one.py | _build_full_partition | def _build_full_partition(
optional_parts, sequence_var_partition: Sequence[int], subjects: Sequence[Expression], operation: Operation
) -> List[Sequence[Expression]]:
"""Distribute subject operands among pattern operands.
Given a partitoning for the variable part of the operands (i.e. a list of how many extra operands each sequence
variable gets assigned).
"""
i = 0
var_index = 0
opt_index = 0
result = []
for operand in op_iter(operation):
wrap_associative = False
if isinstance(operand, Wildcard):
count = operand.min_count if operand.optional is None else 0
if not operand.fixed_size or isinstance(operation, AssociativeOperation):
count += sequence_var_partition[var_index]
var_index += 1
wrap_associative = operand.fixed_size and operand.min_count
elif operand.optional is not None:
count = optional_parts[opt_index]
opt_index += 1
else:
count = 1
operand_expressions = list(op_iter(subjects))[i:i + count]
i += count
if wrap_associative and len(operand_expressions) > wrap_associative:
fixed = wrap_associative - 1
operand_expressions = tuple(operand_expressions[:fixed]) + (
create_operation_expression(operation, operand_expressions[fixed:]),
)
result.append(operand_expressions)
return result | python | def _build_full_partition(
optional_parts, sequence_var_partition: Sequence[int], subjects: Sequence[Expression], operation: Operation
) -> List[Sequence[Expression]]:
i = 0
var_index = 0
opt_index = 0
result = []
for operand in op_iter(operation):
wrap_associative = False
if isinstance(operand, Wildcard):
count = operand.min_count if operand.optional is None else 0
if not operand.fixed_size or isinstance(operation, AssociativeOperation):
count += sequence_var_partition[var_index]
var_index += 1
wrap_associative = operand.fixed_size and operand.min_count
elif operand.optional is not None:
count = optional_parts[opt_index]
opt_index += 1
else:
count = 1
operand_expressions = list(op_iter(subjects))[i:i + count]
i += count
if wrap_associative and len(operand_expressions) > wrap_associative:
fixed = wrap_associative - 1
operand_expressions = tuple(operand_expressions[:fixed]) + (
create_operation_expression(operation, operand_expressions[fixed:]),
)
result.append(operand_expressions)
return result | [
"def",
"_build_full_partition",
"(",
"optional_parts",
",",
"sequence_var_partition",
":",
"Sequence",
"[",
"int",
"]",
",",
"subjects",
":",
"Sequence",
"[",
"Expression",
"]",
",",
"operation",
":",
"Operation",
")",
"->",
"List",
"[",
"Sequence",
"[",
"Expression",
"]",
"]",
":",
"i",
"=",
"0",
"var_index",
"=",
"0",
"opt_index",
"=",
"0",
"result",
"=",
"[",
"]",
"for",
"operand",
"in",
"op_iter",
"(",
"operation",
")",
":",
"wrap_associative",
"=",
"False",
"if",
"isinstance",
"(",
"operand",
",",
"Wildcard",
")",
":",
"count",
"=",
"operand",
".",
"min_count",
"if",
"operand",
".",
"optional",
"is",
"None",
"else",
"0",
"if",
"not",
"operand",
".",
"fixed_size",
"or",
"isinstance",
"(",
"operation",
",",
"AssociativeOperation",
")",
":",
"count",
"+=",
"sequence_var_partition",
"[",
"var_index",
"]",
"var_index",
"+=",
"1",
"wrap_associative",
"=",
"operand",
".",
"fixed_size",
"and",
"operand",
".",
"min_count",
"elif",
"operand",
".",
"optional",
"is",
"not",
"None",
":",
"count",
"=",
"optional_parts",
"[",
"opt_index",
"]",
"opt_index",
"+=",
"1",
"else",
":",
"count",
"=",
"1",
"operand_expressions",
"=",
"list",
"(",
"op_iter",
"(",
"subjects",
")",
")",
"[",
"i",
":",
"i",
"+",
"count",
"]",
"i",
"+=",
"count",
"if",
"wrap_associative",
"and",
"len",
"(",
"operand_expressions",
")",
">",
"wrap_associative",
":",
"fixed",
"=",
"wrap_associative",
"-",
"1",
"operand_expressions",
"=",
"tuple",
"(",
"operand_expressions",
"[",
":",
"fixed",
"]",
")",
"+",
"(",
"create_operation_expression",
"(",
"operation",
",",
"operand_expressions",
"[",
"fixed",
":",
"]",
")",
",",
")",
"result",
".",
"append",
"(",
"operand_expressions",
")",
"return",
"result"
] | Distribute subject operands among pattern operands.
Given a partitoning for the variable part of the operands (i.e. a list of how many extra operands each sequence
variable gets assigned). | [
"Distribute",
"subject",
"operands",
"among",
"pattern",
"operands",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/one_to_one.py#L179-L216 |
2,010 | HPAC/matchpy | matchpy/matching/many_to_one.py | _MatchIter.grouped | def grouped(self):
"""
Yield the matches grouped by their final state in the automaton, i.e. structurally identical patterns
only differing in constraints will be yielded together. Each group is yielded as a list of tuples consisting of
a pattern and a match substitution.
Yields:
The grouped matches.
"""
for _ in self._match(self.matcher.root):
yield list(self._internal_iter()) | python | def grouped(self):
for _ in self._match(self.matcher.root):
yield list(self._internal_iter()) | [
"def",
"grouped",
"(",
"self",
")",
":",
"for",
"_",
"in",
"self",
".",
"_match",
"(",
"self",
".",
"matcher",
".",
"root",
")",
":",
"yield",
"list",
"(",
"self",
".",
"_internal_iter",
"(",
")",
")"
] | Yield the matches grouped by their final state in the automaton, i.e. structurally identical patterns
only differing in constraints will be yielded together. Each group is yielded as a list of tuples consisting of
a pattern and a match substitution.
Yields:
The grouped matches. | [
"Yield",
"the",
"matches",
"grouped",
"by",
"their",
"final",
"state",
"in",
"the",
"automaton",
"i",
".",
"e",
".",
"structurally",
"identical",
"patterns",
"only",
"differing",
"in",
"constraints",
"will",
"be",
"yielded",
"together",
".",
"Each",
"group",
"is",
"yielded",
"as",
"a",
"list",
"of",
"tuples",
"consisting",
"of",
"a",
"pattern",
"and",
"a",
"match",
"substitution",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L102-L112 |
2,011 | HPAC/matchpy | matchpy/matching/many_to_one.py | ManyToOneMatcher.match | def match(self, subject: Expression) -> Iterator[Tuple[Expression, Substitution]]:
"""Match the subject against all the matcher's patterns.
Args:
subject: The subject to match.
Yields:
For every match, a tuple of the matching pattern and the match substitution.
"""
return _MatchIter(self, subject) | python | def match(self, subject: Expression) -> Iterator[Tuple[Expression, Substitution]]:
return _MatchIter(self, subject) | [
"def",
"match",
"(",
"self",
",",
"subject",
":",
"Expression",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"Expression",
",",
"Substitution",
"]",
"]",
":",
"return",
"_MatchIter",
"(",
"self",
",",
"subject",
")"
] | Match the subject against all the matcher's patterns.
Args:
subject: The subject to match.
Yields:
For every match, a tuple of the matching pattern and the match substitution. | [
"Match",
"the",
"subject",
"against",
"all",
"the",
"matcher",
"s",
"patterns",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L434-L443 |
2,012 | HPAC/matchpy | matchpy/matching/many_to_one.py | ManyToOneMatcher._collect_variable_renaming | def _collect_variable_renaming(
cls, expression: Expression, position: List[int]=None, variables: Dict[str, str]=None
) -> Dict[str, str]:
"""Return renaming for the variables in the expression.
The variable names are generated according to the position of the variable in the expression. The goal is to
rename variables in structurally identical patterns so that the automaton contains less redundant states.
"""
if position is None:
position = [0]
if variables is None:
variables = {}
if getattr(expression, 'variable_name', False):
if expression.variable_name not in variables:
variables[expression.variable_name] = cls._get_name_for_position(position, variables.values())
position[-1] += 1
if isinstance(expression, Operation):
if isinstance(expression, CommutativeOperation):
for operand in op_iter(expression):
position.append(0)
cls._collect_variable_renaming(operand, position, variables)
position.pop()
else:
for operand in op_iter(expression):
cls._collect_variable_renaming(operand, position, variables)
return variables | python | def _collect_variable_renaming(
cls, expression: Expression, position: List[int]=None, variables: Dict[str, str]=None
) -> Dict[str, str]:
if position is None:
position = [0]
if variables is None:
variables = {}
if getattr(expression, 'variable_name', False):
if expression.variable_name not in variables:
variables[expression.variable_name] = cls._get_name_for_position(position, variables.values())
position[-1] += 1
if isinstance(expression, Operation):
if isinstance(expression, CommutativeOperation):
for operand in op_iter(expression):
position.append(0)
cls._collect_variable_renaming(operand, position, variables)
position.pop()
else:
for operand in op_iter(expression):
cls._collect_variable_renaming(operand, position, variables)
return variables | [
"def",
"_collect_variable_renaming",
"(",
"cls",
",",
"expression",
":",
"Expression",
",",
"position",
":",
"List",
"[",
"int",
"]",
"=",
"None",
",",
"variables",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"if",
"position",
"is",
"None",
":",
"position",
"=",
"[",
"0",
"]",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"{",
"}",
"if",
"getattr",
"(",
"expression",
",",
"'variable_name'",
",",
"False",
")",
":",
"if",
"expression",
".",
"variable_name",
"not",
"in",
"variables",
":",
"variables",
"[",
"expression",
".",
"variable_name",
"]",
"=",
"cls",
".",
"_get_name_for_position",
"(",
"position",
",",
"variables",
".",
"values",
"(",
")",
")",
"position",
"[",
"-",
"1",
"]",
"+=",
"1",
"if",
"isinstance",
"(",
"expression",
",",
"Operation",
")",
":",
"if",
"isinstance",
"(",
"expression",
",",
"CommutativeOperation",
")",
":",
"for",
"operand",
"in",
"op_iter",
"(",
"expression",
")",
":",
"position",
".",
"append",
"(",
"0",
")",
"cls",
".",
"_collect_variable_renaming",
"(",
"operand",
",",
"position",
",",
"variables",
")",
"position",
".",
"pop",
"(",
")",
"else",
":",
"for",
"operand",
"in",
"op_iter",
"(",
"expression",
")",
":",
"cls",
".",
"_collect_variable_renaming",
"(",
"operand",
",",
"position",
",",
"variables",
")",
"return",
"variables"
] | Return renaming for the variables in the expression.
The variable names are generated according to the position of the variable in the expression. The goal is to
rename variables in structurally identical patterns so that the automaton contains less redundant states. | [
"Return",
"renaming",
"for",
"the",
"variables",
"in",
"the",
"expression",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L532-L558 |
2,013 | HPAC/matchpy | matchpy/matching/many_to_one.py | ManyToOneReplacer.add | def add(self, rule: 'functions.ReplacementRule') -> None:
"""Add a new rule to the replacer.
Args:
rule:
The rule to add.
"""
self.matcher.add(rule.pattern, rule.replacement) | python | def add(self, rule: 'functions.ReplacementRule') -> None:
self.matcher.add(rule.pattern, rule.replacement) | [
"def",
"add",
"(",
"self",
",",
"rule",
":",
"'functions.ReplacementRule'",
")",
"->",
"None",
":",
"self",
".",
"matcher",
".",
"add",
"(",
"rule",
".",
"pattern",
",",
"rule",
".",
"replacement",
")"
] | Add a new rule to the replacer.
Args:
rule:
The rule to add. | [
"Add",
"a",
"new",
"rule",
"to",
"the",
"replacer",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/matching/many_to_one.py#L766-L773 |
2,014 | HPAC/matchpy | matchpy/expressions/expressions.py | Expression.collect_variables | def collect_variables(self, variables: MultisetOfVariables) -> None:
"""Recursively adds all variables occuring in the expression to the given multiset.
This is used internally by `variables`. Needs to be overwritten by inheriting container expression classes.
This method can be used when gathering the `variables` of multiple expressions, because only one multiset
needs to be created and that is more efficient.
Args:
variables:
Multiset of variables. All variables contained in the expression are recursively added to this multiset.
"""
if self.variable_name is not None:
variables.add(self.variable_name) | python | def collect_variables(self, variables: MultisetOfVariables) -> None:
if self.variable_name is not None:
variables.add(self.variable_name) | [
"def",
"collect_variables",
"(",
"self",
",",
"variables",
":",
"MultisetOfVariables",
")",
"->",
"None",
":",
"if",
"self",
".",
"variable_name",
"is",
"not",
"None",
":",
"variables",
".",
"add",
"(",
"self",
".",
"variable_name",
")"
] | Recursively adds all variables occuring in the expression to the given multiset.
This is used internally by `variables`. Needs to be overwritten by inheriting container expression classes.
This method can be used when gathering the `variables` of multiple expressions, because only one multiset
needs to be created and that is more efficient.
Args:
variables:
Multiset of variables. All variables contained in the expression are recursively added to this multiset. | [
"Recursively",
"adds",
"all",
"variables",
"occuring",
"in",
"the",
"expression",
"to",
"the",
"given",
"multiset",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/expressions.py#L97-L109 |
2,015 | HPAC/matchpy | matchpy/expressions/expressions.py | Operation.new | def new(
name: str,
arity: Arity,
class_name: str=None,
*,
associative: bool=False,
commutative: bool=False,
one_identity: bool=False,
infix: bool=False
) -> Type['Operation']:
"""Utility method to create a new operation type.
Example:
>>> Times = Operation.new('*', Arity.polyadic, 'Times', associative=True, commutative=True, one_identity=True)
>>> Times
Times['*', Arity(min_count=2, fixed_size=False), associative, commutative, one_identity]
>>> str(Times(Symbol('a'), Symbol('b')))
'*(a, b)'
Args:
name:
Name or symbol for the operator. Will be used as name for the new class if
`class_name` is not specified.
arity:
The arity of the operator as explained in the documentation of `Operation`.
class_name:
Name for the new operation class to be used instead of name. This argument
is required if `name` is not a valid python identifier.
Keyword Args:
associative:
See :attr:`~Operation.associative`.
commutative:
See :attr:`~Operation.commutative`.
one_identity:
See :attr:`~Operation.one_identity`.
infix:
See :attr:`~Operation.infix`.
Raises:
ValueError: if the class name of the operation is not a valid class identifier.
"""
class_name = class_name or name
if not class_name.isidentifier() or keyword.iskeyword(class_name):
raise ValueError("Invalid identifier for new operator class.")
return type(
class_name, (Operation, ), {
'name': name,
'arity': arity,
'associative': associative,
'commutative': commutative,
'one_identity': one_identity,
'infix': infix
}
) | python | def new(
name: str,
arity: Arity,
class_name: str=None,
*,
associative: bool=False,
commutative: bool=False,
one_identity: bool=False,
infix: bool=False
) -> Type['Operation']:
class_name = class_name or name
if not class_name.isidentifier() or keyword.iskeyword(class_name):
raise ValueError("Invalid identifier for new operator class.")
return type(
class_name, (Operation, ), {
'name': name,
'arity': arity,
'associative': associative,
'commutative': commutative,
'one_identity': one_identity,
'infix': infix
}
) | [
"def",
"new",
"(",
"name",
":",
"str",
",",
"arity",
":",
"Arity",
",",
"class_name",
":",
"str",
"=",
"None",
",",
"*",
",",
"associative",
":",
"bool",
"=",
"False",
",",
"commutative",
":",
"bool",
"=",
"False",
",",
"one_identity",
":",
"bool",
"=",
"False",
",",
"infix",
":",
"bool",
"=",
"False",
")",
"->",
"Type",
"[",
"'Operation'",
"]",
":",
"class_name",
"=",
"class_name",
"or",
"name",
"if",
"not",
"class_name",
".",
"isidentifier",
"(",
")",
"or",
"keyword",
".",
"iskeyword",
"(",
"class_name",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid identifier for new operator class.\"",
")",
"return",
"type",
"(",
"class_name",
",",
"(",
"Operation",
",",
")",
",",
"{",
"'name'",
":",
"name",
",",
"'arity'",
":",
"arity",
",",
"'associative'",
":",
"associative",
",",
"'commutative'",
":",
"commutative",
",",
"'one_identity'",
":",
"one_identity",
",",
"'infix'",
":",
"infix",
"}",
")"
] | Utility method to create a new operation type.
Example:
>>> Times = Operation.new('*', Arity.polyadic, 'Times', associative=True, commutative=True, one_identity=True)
>>> Times
Times['*', Arity(min_count=2, fixed_size=False), associative, commutative, one_identity]
>>> str(Times(Symbol('a'), Symbol('b')))
'*(a, b)'
Args:
name:
Name or symbol for the operator. Will be used as name for the new class if
`class_name` is not specified.
arity:
The arity of the operator as explained in the documentation of `Operation`.
class_name:
Name for the new operation class to be used instead of name. This argument
is required if `name` is not a valid python identifier.
Keyword Args:
associative:
See :attr:`~Operation.associative`.
commutative:
See :attr:`~Operation.commutative`.
one_identity:
See :attr:`~Operation.one_identity`.
infix:
See :attr:`~Operation.infix`.
Raises:
ValueError: if the class name of the operation is not a valid class identifier. | [
"Utility",
"method",
"to",
"create",
"a",
"new",
"operation",
"type",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/expressions.py#L426-L482 |
2,016 | HPAC/matchpy | matchpy/expressions/expressions.py | Wildcard.optional | def optional(name, default) -> 'Wildcard':
"""Create a `Wildcard` that matches a single argument with a default value.
If the wildcard does not match, the substitution will contain the
default value instead.
Args:
name:
The name for the wildcard.
default:
The default value of the wildcard.
Returns:
A n optional wildcard.
"""
return Wildcard(min_count=1, fixed_size=True, variable_name=name, optional=default) | python | def optional(name, default) -> 'Wildcard':
return Wildcard(min_count=1, fixed_size=True, variable_name=name, optional=default) | [
"def",
"optional",
"(",
"name",
",",
"default",
")",
"->",
"'Wildcard'",
":",
"return",
"Wildcard",
"(",
"min_count",
"=",
"1",
",",
"fixed_size",
"=",
"True",
",",
"variable_name",
"=",
"name",
",",
"optional",
"=",
"default",
")"
] | Create a `Wildcard` that matches a single argument with a default value.
If the wildcard does not match, the substitution will contain the
default value instead.
Args:
name:
The name for the wildcard.
default:
The default value of the wildcard.
Returns:
A n optional wildcard. | [
"Create",
"a",
"Wildcard",
"that",
"matches",
"a",
"single",
"argument",
"with",
"a",
"default",
"value",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/expressions.py#L755-L770 |
2,017 | HPAC/matchpy | matchpy/expressions/expressions.py | Wildcard.symbol | def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard':
"""Create a `SymbolWildcard` that matches a single `Symbol` argument.
Args:
name:
Optional variable name for the wildcard.
symbol_type:
An optional subclass of `Symbol` to further limit which kind of symbols are
matched by the wildcard.
Returns:
A `SymbolWildcard` that matches the *symbol_type*.
"""
if isinstance(name, type) and issubclass(name, Symbol) and symbol_type is Symbol:
return SymbolWildcard(name)
return SymbolWildcard(symbol_type, variable_name=name) | python | def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard':
if isinstance(name, type) and issubclass(name, Symbol) and symbol_type is Symbol:
return SymbolWildcard(name)
return SymbolWildcard(symbol_type, variable_name=name) | [
"def",
"symbol",
"(",
"name",
":",
"str",
"=",
"None",
",",
"symbol_type",
":",
"Type",
"[",
"Symbol",
"]",
"=",
"Symbol",
")",
"->",
"'SymbolWildcard'",
":",
"if",
"isinstance",
"(",
"name",
",",
"type",
")",
"and",
"issubclass",
"(",
"name",
",",
"Symbol",
")",
"and",
"symbol_type",
"is",
"Symbol",
":",
"return",
"SymbolWildcard",
"(",
"name",
")",
"return",
"SymbolWildcard",
"(",
"symbol_type",
",",
"variable_name",
"=",
"name",
")"
] | Create a `SymbolWildcard` that matches a single `Symbol` argument.
Args:
name:
Optional variable name for the wildcard.
symbol_type:
An optional subclass of `Symbol` to further limit which kind of symbols are
matched by the wildcard.
Returns:
A `SymbolWildcard` that matches the *symbol_type*. | [
"Create",
"a",
"SymbolWildcard",
"that",
"matches",
"a",
"single",
"Symbol",
"argument",
"."
] | 06b2ec50ee0efdf3dd183768c0ffdb51b7efc393 | https://github.com/HPAC/matchpy/blob/06b2ec50ee0efdf3dd183768c0ffdb51b7efc393/matchpy/expressions/expressions.py#L773-L788 |
2,018 | optimizely/optimizely-client-python | optimizely/client.py | Client.request | def request(self, method, url_parts, headers=None, data=None):
""" Method for making requests to the Optimizely API
"""
if method in self.ALLOWED_REQUESTS:
# add request token header
headers = headers or {}
# test if Oauth token
if self.token_type == 'legacy':
headers.update(
{'Token': self.api_key,
'User-Agent': 'optimizely-client-python/0.1.1'})
elif self.token_type == 'oauth':
headers.update(
{'Authorization': 'Bearer ' + self.api_key,
'User-Agent': 'optimizely-client-python/0.1.1'})
else:
raise ValueError(
'{} is not a valid token type.'.format(self.token_type))
# make request and return parsed response
url = urlparse.urljoin(
self.api_base,
'/'.join([str(url_part) for url_part in url_parts])
)
return self.parse_response(
getattr(requests, method)(url, headers=headers, data=data)
)
else:
raise error.BadRequestError(
'%s is not a valid request type.' % method) | python | def request(self, method, url_parts, headers=None, data=None):
if method in self.ALLOWED_REQUESTS:
# add request token header
headers = headers or {}
# test if Oauth token
if self.token_type == 'legacy':
headers.update(
{'Token': self.api_key,
'User-Agent': 'optimizely-client-python/0.1.1'})
elif self.token_type == 'oauth':
headers.update(
{'Authorization': 'Bearer ' + self.api_key,
'User-Agent': 'optimizely-client-python/0.1.1'})
else:
raise ValueError(
'{} is not a valid token type.'.format(self.token_type))
# make request and return parsed response
url = urlparse.urljoin(
self.api_base,
'/'.join([str(url_part) for url_part in url_parts])
)
return self.parse_response(
getattr(requests, method)(url, headers=headers, data=data)
)
else:
raise error.BadRequestError(
'%s is not a valid request type.' % method) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url_parts",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"if",
"method",
"in",
"self",
".",
"ALLOWED_REQUESTS",
":",
"# add request token header",
"headers",
"=",
"headers",
"or",
"{",
"}",
"# test if Oauth token",
"if",
"self",
".",
"token_type",
"==",
"'legacy'",
":",
"headers",
".",
"update",
"(",
"{",
"'Token'",
":",
"self",
".",
"api_key",
",",
"'User-Agent'",
":",
"'optimizely-client-python/0.1.1'",
"}",
")",
"elif",
"self",
".",
"token_type",
"==",
"'oauth'",
":",
"headers",
".",
"update",
"(",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"self",
".",
"api_key",
",",
"'User-Agent'",
":",
"'optimizely-client-python/0.1.1'",
"}",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'{} is not a valid token type.'",
".",
"format",
"(",
"self",
".",
"token_type",
")",
")",
"# make request and return parsed response",
"url",
"=",
"urlparse",
".",
"urljoin",
"(",
"self",
".",
"api_base",
",",
"'/'",
".",
"join",
"(",
"[",
"str",
"(",
"url_part",
")",
"for",
"url_part",
"in",
"url_parts",
"]",
")",
")",
"return",
"self",
".",
"parse_response",
"(",
"getattr",
"(",
"requests",
",",
"method",
")",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"data",
")",
")",
"else",
":",
"raise",
"error",
".",
"BadRequestError",
"(",
"'%s is not a valid request type.'",
"%",
"method",
")"
] | Method for making requests to the Optimizely API | [
"Method",
"for",
"making",
"requests",
"to",
"the",
"Optimizely",
"API"
] | c4a121e8ac66e44f6ef4ad4959ef46ed3992708a | https://github.com/optimizely/optimizely-client-python/blob/c4a121e8ac66e44f6ef4ad4959ef46ed3992708a/optimizely/client.py#L45-L74 |
2,019 | optimizely/optimizely-client-python | optimizely/client.py | Client.parse_response | def parse_response(resp):
""" Method to parse response from the Optimizely API and
return results as JSON. Errors are thrown for various
errors that the API can throw.
"""
if resp.status_code in [200, 201, 202]:
return resp.json()
elif resp.status_code == 204:
return None
elif resp.status_code == 400:
raise error.BadRequestError(resp.text)
elif resp.status_code == 401:
raise error.UnauthorizedError(resp.text)
elif resp.status_code == 403:
raise error.ForbiddenError(resp.text)
elif resp.status_code == 404:
raise error.NotFoundError(resp.text)
elif resp.status_code == 429:
raise error.TooManyRequestsError(resp.text)
elif resp.status_code == 503:
raise error.ServiceUnavailableError(resp.text)
else:
raise error.OptimizelyError(resp.text) | python | def parse_response(resp):
if resp.status_code in [200, 201, 202]:
return resp.json()
elif resp.status_code == 204:
return None
elif resp.status_code == 400:
raise error.BadRequestError(resp.text)
elif resp.status_code == 401:
raise error.UnauthorizedError(resp.text)
elif resp.status_code == 403:
raise error.ForbiddenError(resp.text)
elif resp.status_code == 404:
raise error.NotFoundError(resp.text)
elif resp.status_code == 429:
raise error.TooManyRequestsError(resp.text)
elif resp.status_code == 503:
raise error.ServiceUnavailableError(resp.text)
else:
raise error.OptimizelyError(resp.text) | [
"def",
"parse_response",
"(",
"resp",
")",
":",
"if",
"resp",
".",
"status_code",
"in",
"[",
"200",
",",
"201",
",",
"202",
"]",
":",
"return",
"resp",
".",
"json",
"(",
")",
"elif",
"resp",
".",
"status_code",
"==",
"204",
":",
"return",
"None",
"elif",
"resp",
".",
"status_code",
"==",
"400",
":",
"raise",
"error",
".",
"BadRequestError",
"(",
"resp",
".",
"text",
")",
"elif",
"resp",
".",
"status_code",
"==",
"401",
":",
"raise",
"error",
".",
"UnauthorizedError",
"(",
"resp",
".",
"text",
")",
"elif",
"resp",
".",
"status_code",
"==",
"403",
":",
"raise",
"error",
".",
"ForbiddenError",
"(",
"resp",
".",
"text",
")",
"elif",
"resp",
".",
"status_code",
"==",
"404",
":",
"raise",
"error",
".",
"NotFoundError",
"(",
"resp",
".",
"text",
")",
"elif",
"resp",
".",
"status_code",
"==",
"429",
":",
"raise",
"error",
".",
"TooManyRequestsError",
"(",
"resp",
".",
"text",
")",
"elif",
"resp",
".",
"status_code",
"==",
"503",
":",
"raise",
"error",
".",
"ServiceUnavailableError",
"(",
"resp",
".",
"text",
")",
"else",
":",
"raise",
"error",
".",
"OptimizelyError",
"(",
"resp",
".",
"text",
")"
] | Method to parse response from the Optimizely API and
return results as JSON. Errors are thrown for various
errors that the API can throw. | [
"Method",
"to",
"parse",
"response",
"from",
"the",
"Optimizely",
"API",
"and",
"return",
"results",
"as",
"JSON",
".",
"Errors",
"are",
"thrown",
"for",
"various",
"errors",
"that",
"the",
"API",
"can",
"throw",
"."
] | c4a121e8ac66e44f6ef4ad4959ef46ed3992708a | https://github.com/optimizely/optimizely-client-python/blob/c4a121e8ac66e44f6ef4ad4959ef46ed3992708a/optimizely/client.py#L77-L99 |
2,020 | sirrice/pygg | pygg/pygg.py | _to_r | def _to_r(o, as_data=False, level=0):
"""Helper function to convert python data structures to R equivalents
TODO: a single model for transforming to r to handle
* function args
* lists as function args
"""
if o is None:
return "NA"
if isinstance(o, basestring):
return o
if hasattr(o, "r"):
# bridge to @property r on GGStatement(s)
return o.r
elif isinstance(o, bool):
return "TRUE" if o else "FALSE"
elif isinstance(o, (list, tuple)):
inner = ",".join([_to_r(x, True, level+1) for x in o])
return "c({})".format(inner) if as_data else inner
elif isinstance(o, dict):
inner = ",".join(["{}={}".format(k, _to_r(v, True, level+1))
for k, v in sorted(o.iteritems(), key=lambda x: x[0])])
return "list({})".format(inner) if as_data else inner
return str(o) | python | def _to_r(o, as_data=False, level=0):
if o is None:
return "NA"
if isinstance(o, basestring):
return o
if hasattr(o, "r"):
# bridge to @property r on GGStatement(s)
return o.r
elif isinstance(o, bool):
return "TRUE" if o else "FALSE"
elif isinstance(o, (list, tuple)):
inner = ",".join([_to_r(x, True, level+1) for x in o])
return "c({})".format(inner) if as_data else inner
elif isinstance(o, dict):
inner = ",".join(["{}={}".format(k, _to_r(v, True, level+1))
for k, v in sorted(o.iteritems(), key=lambda x: x[0])])
return "list({})".format(inner) if as_data else inner
return str(o) | [
"def",
"_to_r",
"(",
"o",
",",
"as_data",
"=",
"False",
",",
"level",
"=",
"0",
")",
":",
"if",
"o",
"is",
"None",
":",
"return",
"\"NA\"",
"if",
"isinstance",
"(",
"o",
",",
"basestring",
")",
":",
"return",
"o",
"if",
"hasattr",
"(",
"o",
",",
"\"r\"",
")",
":",
"# bridge to @property r on GGStatement(s)",
"return",
"o",
".",
"r",
"elif",
"isinstance",
"(",
"o",
",",
"bool",
")",
":",
"return",
"\"TRUE\"",
"if",
"o",
"else",
"\"FALSE\"",
"elif",
"isinstance",
"(",
"o",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"inner",
"=",
"\",\"",
".",
"join",
"(",
"[",
"_to_r",
"(",
"x",
",",
"True",
",",
"level",
"+",
"1",
")",
"for",
"x",
"in",
"o",
"]",
")",
"return",
"\"c({})\"",
".",
"format",
"(",
"inner",
")",
"if",
"as_data",
"else",
"inner",
"elif",
"isinstance",
"(",
"o",
",",
"dict",
")",
":",
"inner",
"=",
"\",\"",
".",
"join",
"(",
"[",
"\"{}={}\"",
".",
"format",
"(",
"k",
",",
"_to_r",
"(",
"v",
",",
"True",
",",
"level",
"+",
"1",
")",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"o",
".",
"iteritems",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
"]",
")",
"return",
"\"list({})\"",
".",
"format",
"(",
"inner",
")",
"if",
"as_data",
"else",
"inner",
"return",
"str",
"(",
"o",
")"
] | Helper function to convert python data structures to R equivalents
TODO: a single model for transforming to r to handle
* function args
* lists as function args | [
"Helper",
"function",
"to",
"convert",
"python",
"data",
"structures",
"to",
"R",
"equivalents"
] | b36e19b3827e0a7d661de660b04d55a73f35896b | https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L32-L55 |
2,021 | sirrice/pygg | pygg/pygg.py | data_py | def data_py(o, *args, **kwargs):
"""converts python object into R Dataframe definition
converts following data structures:
row oriented list of dictionaries:
[ { 'x': 0, 'y': 1, ...}, ... ]
col oriented dictionary of lists
{ 'x': [0,1,2...], 'y': [...], ... }
@param o python object to convert
@param args argument list to pass to read.csv
@param kwargs keyword args to pass to read.csv
@return a tuple of the file containing the data and an
expression to define data.frame object and set it to variable "data"
data = read.csv(tmpfile, *args, **kwargs)
"""
if isinstance(o, basestring):
fname = o
else:
if not is_pandas_df(o):
# convert incoming data layout to pandas' DataFrame
o = pandas.DataFrame(o)
fname = tempfile.NamedTemporaryFile().name
o.to_csv(fname, sep=',', encoding='utf-8', index=False)
kwargs["sep"] = esc(',')
read_csv_stmt = GGStatement("read.csv", esc(fname), *args, **kwargs).r
return GGData("data = {}".format(read_csv_stmt), fname=fname) | python | def data_py(o, *args, **kwargs):
if isinstance(o, basestring):
fname = o
else:
if not is_pandas_df(o):
# convert incoming data layout to pandas' DataFrame
o = pandas.DataFrame(o)
fname = tempfile.NamedTemporaryFile().name
o.to_csv(fname, sep=',', encoding='utf-8', index=False)
kwargs["sep"] = esc(',')
read_csv_stmt = GGStatement("read.csv", esc(fname), *args, **kwargs).r
return GGData("data = {}".format(read_csv_stmt), fname=fname) | [
"def",
"data_py",
"(",
"o",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"basestring",
")",
":",
"fname",
"=",
"o",
"else",
":",
"if",
"not",
"is_pandas_df",
"(",
"o",
")",
":",
"# convert incoming data layout to pandas' DataFrame",
"o",
"=",
"pandas",
".",
"DataFrame",
"(",
"o",
")",
"fname",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
".",
"name",
"o",
".",
"to_csv",
"(",
"fname",
",",
"sep",
"=",
"','",
",",
"encoding",
"=",
"'utf-8'",
",",
"index",
"=",
"False",
")",
"kwargs",
"[",
"\"sep\"",
"]",
"=",
"esc",
"(",
"','",
")",
"read_csv_stmt",
"=",
"GGStatement",
"(",
"\"read.csv\"",
",",
"esc",
"(",
"fname",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"r",
"return",
"GGData",
"(",
"\"data = {}\"",
".",
"format",
"(",
"read_csv_stmt",
")",
",",
"fname",
"=",
"fname",
")"
] | converts python object into R Dataframe definition
converts following data structures:
row oriented list of dictionaries:
[ { 'x': 0, 'y': 1, ...}, ... ]
col oriented dictionary of lists
{ 'x': [0,1,2...], 'y': [...], ... }
@param o python object to convert
@param args argument list to pass to read.csv
@param kwargs keyword args to pass to read.csv
@return a tuple of the file containing the data and an
expression to define data.frame object and set it to variable "data"
data = read.csv(tmpfile, *args, **kwargs) | [
"converts",
"python",
"object",
"into",
"R",
"Dataframe",
"definition"
] | b36e19b3827e0a7d661de660b04d55a73f35896b | https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L176-L208 |
2,022 | sirrice/pygg | pygg/pygg.py | ggsave | def ggsave(name, plot, data=None, *args, **kwargs):
"""Save a GGStatements object to destination name
@param name output file name. if None, don't run R command
@param kwargs keyword args to pass to ggsave. The following are special
keywords for the python save method
data: a python data object (list, dict, DataFrame) used to populate
the `data` variable in R
libs: list of library names to load in addition to ggplot2
prefix: string containing R code to run before any ggplot commands (including data loading)
postfix: string containing R code to run after data is loaded (e.g., if you want to rename variable names)
quiet: if Truthy, don't print out R program string
"""
# constants
kwdefaults = {
'width': 10,
'height': 8,
'scale': 1
}
keys_to_rm = ["prefix", "quiet", "postfix", 'libs']
varname = 'p'
# process arguments
prefix = kwargs.get('prefix', '')
postfix = kwargs.get('postfix', '')
libs = kwargs.get('libs', [])
libs = '\n'.join(["library(%s)" % lib for lib in libs])
quiet = kwargs.get("quiet", False)
kwargs = {k: v for k, v in kwargs.iteritems()
if v is not None and k not in keys_to_rm}
kwdefaults.update(kwargs)
kwargs = kwdefaults
# figure out how to load data in the R environment
if data is None: data = plot.data
if data is None:
# Don't load anything, the data source is already present in R
data_src = ''
elif isinstance(data, basestring) and 'RPostgreSQL' in data:
# Hack to allow through data_sql results
data_src = data
elif isinstance(data, GGData):
data_src = str(data)
else:
# format the python data object
data_src = str(data_py(data))
prog = "%(header)s\n%(libs)s\n%(prefix)s\n%(data)s\n%(postfix)s\n%(varname)s = %(prog)s" % {
'header': "library(ggplot2)",
'libs': libs,
'data': data_src,
'prefix': prefix,
'postfix': postfix,
'varname': varname,
'prog': plot.r
}
if name:
stmt = GGStatement("ggsave", esc(name), varname, *args, **kwargs)
prog = "%s\n%s" % (prog, stmt.r)
if not quiet:
print prog
print
if name:
execute_r(prog, quiet)
return prog | python | def ggsave(name, plot, data=None, *args, **kwargs):
# constants
kwdefaults = {
'width': 10,
'height': 8,
'scale': 1
}
keys_to_rm = ["prefix", "quiet", "postfix", 'libs']
varname = 'p'
# process arguments
prefix = kwargs.get('prefix', '')
postfix = kwargs.get('postfix', '')
libs = kwargs.get('libs', [])
libs = '\n'.join(["library(%s)" % lib for lib in libs])
quiet = kwargs.get("quiet", False)
kwargs = {k: v for k, v in kwargs.iteritems()
if v is not None and k not in keys_to_rm}
kwdefaults.update(kwargs)
kwargs = kwdefaults
# figure out how to load data in the R environment
if data is None: data = plot.data
if data is None:
# Don't load anything, the data source is already present in R
data_src = ''
elif isinstance(data, basestring) and 'RPostgreSQL' in data:
# Hack to allow through data_sql results
data_src = data
elif isinstance(data, GGData):
data_src = str(data)
else:
# format the python data object
data_src = str(data_py(data))
prog = "%(header)s\n%(libs)s\n%(prefix)s\n%(data)s\n%(postfix)s\n%(varname)s = %(prog)s" % {
'header': "library(ggplot2)",
'libs': libs,
'data': data_src,
'prefix': prefix,
'postfix': postfix,
'varname': varname,
'prog': plot.r
}
if name:
stmt = GGStatement("ggsave", esc(name), varname, *args, **kwargs)
prog = "%s\n%s" % (prog, stmt.r)
if not quiet:
print prog
print
if name:
execute_r(prog, quiet)
return prog | [
"def",
"ggsave",
"(",
"name",
",",
"plot",
",",
"data",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# constants",
"kwdefaults",
"=",
"{",
"'width'",
":",
"10",
",",
"'height'",
":",
"8",
",",
"'scale'",
":",
"1",
"}",
"keys_to_rm",
"=",
"[",
"\"prefix\"",
",",
"\"quiet\"",
",",
"\"postfix\"",
",",
"'libs'",
"]",
"varname",
"=",
"'p'",
"# process arguments",
"prefix",
"=",
"kwargs",
".",
"get",
"(",
"'prefix'",
",",
"''",
")",
"postfix",
"=",
"kwargs",
".",
"get",
"(",
"'postfix'",
",",
"''",
")",
"libs",
"=",
"kwargs",
".",
"get",
"(",
"'libs'",
",",
"[",
"]",
")",
"libs",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"\"library(%s)\"",
"%",
"lib",
"for",
"lib",
"in",
"libs",
"]",
")",
"quiet",
"=",
"kwargs",
".",
"get",
"(",
"\"quiet\"",
",",
"False",
")",
"kwargs",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"and",
"k",
"not",
"in",
"keys_to_rm",
"}",
"kwdefaults",
".",
"update",
"(",
"kwargs",
")",
"kwargs",
"=",
"kwdefaults",
"# figure out how to load data in the R environment",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"plot",
".",
"data",
"if",
"data",
"is",
"None",
":",
"# Don't load anything, the data source is already present in R",
"data_src",
"=",
"''",
"elif",
"isinstance",
"(",
"data",
",",
"basestring",
")",
"and",
"'RPostgreSQL'",
"in",
"data",
":",
"# Hack to allow through data_sql results",
"data_src",
"=",
"data",
"elif",
"isinstance",
"(",
"data",
",",
"GGData",
")",
":",
"data_src",
"=",
"str",
"(",
"data",
")",
"else",
":",
"# format the python data object",
"data_src",
"=",
"str",
"(",
"data_py",
"(",
"data",
")",
")",
"prog",
"=",
"\"%(header)s\\n%(libs)s\\n%(prefix)s\\n%(data)s\\n%(postfix)s\\n%(varname)s = %(prog)s\"",
"%",
"{",
"'header'",
":",
"\"library(ggplot2)\"",
",",
"'libs'",
":",
"libs",
",",
"'data'",
":",
"data_src",
",",
"'prefix'",
":",
"prefix",
",",
"'postfix'",
":",
"postfix",
",",
"'varname'",
":",
"varname",
",",
"'prog'",
":",
"plot",
".",
"r",
"}",
"if",
"name",
":",
"stmt",
"=",
"GGStatement",
"(",
"\"ggsave\"",
",",
"esc",
"(",
"name",
")",
",",
"varname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"prog",
"=",
"\"%s\\n%s\"",
"%",
"(",
"prog",
",",
"stmt",
".",
"r",
")",
"if",
"not",
"quiet",
":",
"print",
"prog",
"print",
"if",
"name",
":",
"execute_r",
"(",
"prog",
",",
"quiet",
")",
"return",
"prog"
] | Save a GGStatements object to destination name
@param name output file name. if None, don't run R command
@param kwargs keyword args to pass to ggsave. The following are special
keywords for the python save method
data: a python data object (list, dict, DataFrame) used to populate
the `data` variable in R
libs: list of library names to load in addition to ggplot2
prefix: string containing R code to run before any ggplot commands (including data loading)
postfix: string containing R code to run after data is loaded (e.g., if you want to rename variable names)
quiet: if Truthy, don't print out R program string | [
"Save",
"a",
"GGStatements",
"object",
"to",
"destination",
"name"
] | b36e19b3827e0a7d661de660b04d55a73f35896b | https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L245-L315 |
2,023 | sirrice/pygg | pygg/pygg.py | gg_ipython | def gg_ipython(plot, data, width=IPYTHON_IMAGE_SIZE, height=None,
*args, **kwargs):
"""Render pygg in an IPython notebook
Allows one to say things like:
import pygg
p = pygg.ggplot('diamonds', pygg.aes(x='carat', y='price', color='clarity'))
p += pygg.geom_point(alpha=0.5, size = 2)
p += pygg.scale_x_log10(limits=[1, 2])
pygg.gg_ipython(p, data=None, quiet=True)
directly in an IPython notebook and see the resulting ggplot2 image
displayed inline. This function is print a warning if the IPython library
cannot be imported. The ggplot2 image is rendered as a PNG and not
as a vectorized graphics object right now.
Note that by default gg_ipython sets the output height and width to
IPYTHON_IMAGE_SIZE pixels as this is a reasonable default size for a
browser-based notebook. Height is by default None, indicating that height
should be set to the same value as width. It is possible to adjust
the aspect ratio of the output by providing non-None values for both
width and height
"""
try:
import IPython.display
tmp_image_filename = tempfile.NamedTemporaryFile(suffix='.jpg').name
# Quiet by default
kwargs['quiet'] = kwargs.get('quiet', True)
if width is None:
raise ValueError("Width cannot be None")
height = height or width
w_in, h_in = size_r_img_inches(width, height)
ggsave(name=tmp_image_filename, plot=plot, data=data,
dpi=600, width=w_in, height=h_in, units=esc('in'),
*args, **kwargs)
return IPython.display.Image(filename=tmp_image_filename,
width=width, height=height)
except ImportError:
print "Could't load IPython library; integration is disabled" | python | def gg_ipython(plot, data, width=IPYTHON_IMAGE_SIZE, height=None,
*args, **kwargs):
try:
import IPython.display
tmp_image_filename = tempfile.NamedTemporaryFile(suffix='.jpg').name
# Quiet by default
kwargs['quiet'] = kwargs.get('quiet', True)
if width is None:
raise ValueError("Width cannot be None")
height = height or width
w_in, h_in = size_r_img_inches(width, height)
ggsave(name=tmp_image_filename, plot=plot, data=data,
dpi=600, width=w_in, height=h_in, units=esc('in'),
*args, **kwargs)
return IPython.display.Image(filename=tmp_image_filename,
width=width, height=height)
except ImportError:
print "Could't load IPython library; integration is disabled" | [
"def",
"gg_ipython",
"(",
"plot",
",",
"data",
",",
"width",
"=",
"IPYTHON_IMAGE_SIZE",
",",
"height",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"import",
"IPython",
".",
"display",
"tmp_image_filename",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.jpg'",
")",
".",
"name",
"# Quiet by default",
"kwargs",
"[",
"'quiet'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'quiet'",
",",
"True",
")",
"if",
"width",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Width cannot be None\"",
")",
"height",
"=",
"height",
"or",
"width",
"w_in",
",",
"h_in",
"=",
"size_r_img_inches",
"(",
"width",
",",
"height",
")",
"ggsave",
"(",
"name",
"=",
"tmp_image_filename",
",",
"plot",
"=",
"plot",
",",
"data",
"=",
"data",
",",
"dpi",
"=",
"600",
",",
"width",
"=",
"w_in",
",",
"height",
"=",
"h_in",
",",
"units",
"=",
"esc",
"(",
"'in'",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"IPython",
".",
"display",
".",
"Image",
"(",
"filename",
"=",
"tmp_image_filename",
",",
"width",
"=",
"width",
",",
"height",
"=",
"height",
")",
"except",
"ImportError",
":",
"print",
"\"Could't load IPython library; integration is disabled\""
] | Render pygg in an IPython notebook
Allows one to say things like:
import pygg
p = pygg.ggplot('diamonds', pygg.aes(x='carat', y='price', color='clarity'))
p += pygg.geom_point(alpha=0.5, size = 2)
p += pygg.scale_x_log10(limits=[1, 2])
pygg.gg_ipython(p, data=None, quiet=True)
directly in an IPython notebook and see the resulting ggplot2 image
displayed inline. This function is print a warning if the IPython library
cannot be imported. The ggplot2 image is rendered as a PNG and not
as a vectorized graphics object right now.
Note that by default gg_ipython sets the output height and width to
IPYTHON_IMAGE_SIZE pixels as this is a reasonable default size for a
browser-based notebook. Height is by default None, indicating that height
should be set to the same value as width. It is possible to adjust
the aspect ratio of the output by providing non-None values for both
width and height | [
"Render",
"pygg",
"in",
"an",
"IPython",
"notebook"
] | b36e19b3827e0a7d661de660b04d55a73f35896b | https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L318-L359 |
2,024 | sirrice/pygg | pygg/pygg.py | size_r_img_inches | def size_r_img_inches(width, height):
"""Compute the width and height for an R image for display in IPython
Neight width nor height can be null but should be integer pixel values > 0.
Returns a tuple of (width, height) that should be used by ggsave in R to
produce an appropriately sized jpeg/png/pdf image with the right aspect
ratio. The returned values are in inches.
"""
# both width and height are given
aspect_ratio = height / (1.0 * width)
return R_IMAGE_SIZE, round(aspect_ratio * R_IMAGE_SIZE, 2) | python | def size_r_img_inches(width, height):
# both width and height are given
aspect_ratio = height / (1.0 * width)
return R_IMAGE_SIZE, round(aspect_ratio * R_IMAGE_SIZE, 2) | [
"def",
"size_r_img_inches",
"(",
"width",
",",
"height",
")",
":",
"# both width and height are given",
"aspect_ratio",
"=",
"height",
"/",
"(",
"1.0",
"*",
"width",
")",
"return",
"R_IMAGE_SIZE",
",",
"round",
"(",
"aspect_ratio",
"*",
"R_IMAGE_SIZE",
",",
"2",
")"
] | Compute the width and height for an R image for display in IPython
Neight width nor height can be null but should be integer pixel values > 0.
Returns a tuple of (width, height) that should be used by ggsave in R to
produce an appropriately sized jpeg/png/pdf image with the right aspect
ratio. The returned values are in inches. | [
"Compute",
"the",
"width",
"and",
"height",
"for",
"an",
"R",
"image",
"for",
"display",
"in",
"IPython"
] | b36e19b3827e0a7d661de660b04d55a73f35896b | https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L362-L374 |
2,025 | sirrice/pygg | pygg/pygg.py | execute_r | def execute_r(prog, quiet):
"""Run the R code prog an R subprocess
@raises ValueError if the subprocess exits with non-zero status
"""
FNULL = open(os.devnull, 'w') if quiet else None
try:
input_proc = subprocess.Popen(["echo", prog], stdout=subprocess.PIPE)
status = subprocess.call("R --no-save --quiet",
stdin=input_proc.stdout,
stdout=FNULL,
stderr=subprocess.STDOUT,
shell=True) # warning, this is a security problem
if status != 0:
raise ValueError("ggplot2 bridge failed for program: {}."
" Check for an error".format(prog))
finally:
if FNULL is not None:
FNULL.close() | python | def execute_r(prog, quiet):
FNULL = open(os.devnull, 'w') if quiet else None
try:
input_proc = subprocess.Popen(["echo", prog], stdout=subprocess.PIPE)
status = subprocess.call("R --no-save --quiet",
stdin=input_proc.stdout,
stdout=FNULL,
stderr=subprocess.STDOUT,
shell=True) # warning, this is a security problem
if status != 0:
raise ValueError("ggplot2 bridge failed for program: {}."
" Check for an error".format(prog))
finally:
if FNULL is not None:
FNULL.close() | [
"def",
"execute_r",
"(",
"prog",
",",
"quiet",
")",
":",
"FNULL",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"if",
"quiet",
"else",
"None",
"try",
":",
"input_proc",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"echo\"",
",",
"prog",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"status",
"=",
"subprocess",
".",
"call",
"(",
"\"R --no-save --quiet\"",
",",
"stdin",
"=",
"input_proc",
".",
"stdout",
",",
"stdout",
"=",
"FNULL",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"shell",
"=",
"True",
")",
"# warning, this is a security problem",
"if",
"status",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"ggplot2 bridge failed for program: {}.\"",
"\" Check for an error\"",
".",
"format",
"(",
"prog",
")",
")",
"finally",
":",
"if",
"FNULL",
"is",
"not",
"None",
":",
"FNULL",
".",
"close",
"(",
")"
] | Run the R code prog an R subprocess
@raises ValueError if the subprocess exits with non-zero status | [
"Run",
"the",
"R",
"code",
"prog",
"an",
"R",
"subprocess"
] | b36e19b3827e0a7d661de660b04d55a73f35896b | https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L377-L395 |
2,026 | sirrice/pygg | pygg/pygg.py | GGStatement.r | def r(self):
"""Convert this GGStatement into its R equivalent expression"""
r_args = [_to_r(self.args), _to_r(self.kwargs)]
# remove empty strings from the call args
r_args = ",".join([x for x in r_args if x != ""])
return "{}({})".format(self.name, r_args) | python | def r(self):
r_args = [_to_r(self.args), _to_r(self.kwargs)]
# remove empty strings from the call args
r_args = ",".join([x for x in r_args if x != ""])
return "{}({})".format(self.name, r_args) | [
"def",
"r",
"(",
"self",
")",
":",
"r_args",
"=",
"[",
"_to_r",
"(",
"self",
".",
"args",
")",
",",
"_to_r",
"(",
"self",
".",
"kwargs",
")",
"]",
"# remove empty strings from the call args",
"r_args",
"=",
"\",\"",
".",
"join",
"(",
"[",
"x",
"for",
"x",
"in",
"r_args",
"if",
"x",
"!=",
"\"\"",
"]",
")",
"return",
"\"{}({})\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"r_args",
")"
] | Convert this GGStatement into its R equivalent expression | [
"Convert",
"this",
"GGStatement",
"into",
"its",
"R",
"equivalent",
"expression"
] | b36e19b3827e0a7d661de660b04d55a73f35896b | https://github.com/sirrice/pygg/blob/b36e19b3827e0a7d661de660b04d55a73f35896b/pygg/pygg.py#L74-L79 |
2,027 | pygeobuf/pygeobuf | geobuf/scripts/cli.py | encode | def encode(precision, with_z):
"""Given GeoJSON on stdin, writes a geobuf file to stdout."""
logger = logging.getLogger('geobuf')
stdin = click.get_text_stream('stdin')
sink = click.get_binary_stream('stdout')
try:
data = json.load(stdin)
pbf = geobuf.encode(
data,
precision if precision >= 0 else 6,
3 if with_z else 2)
sink.write(pbf)
sys.exit(0)
except Exception:
logger.exception("Failed. Exception caught")
sys.exit(1) | python | def encode(precision, with_z):
logger = logging.getLogger('geobuf')
stdin = click.get_text_stream('stdin')
sink = click.get_binary_stream('stdout')
try:
data = json.load(stdin)
pbf = geobuf.encode(
data,
precision if precision >= 0 else 6,
3 if with_z else 2)
sink.write(pbf)
sys.exit(0)
except Exception:
logger.exception("Failed. Exception caught")
sys.exit(1) | [
"def",
"encode",
"(",
"precision",
",",
"with_z",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'geobuf'",
")",
"stdin",
"=",
"click",
".",
"get_text_stream",
"(",
"'stdin'",
")",
"sink",
"=",
"click",
".",
"get_binary_stream",
"(",
"'stdout'",
")",
"try",
":",
"data",
"=",
"json",
".",
"load",
"(",
"stdin",
")",
"pbf",
"=",
"geobuf",
".",
"encode",
"(",
"data",
",",
"precision",
"if",
"precision",
">=",
"0",
"else",
"6",
",",
"3",
"if",
"with_z",
"else",
"2",
")",
"sink",
".",
"write",
"(",
"pbf",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"except",
"Exception",
":",
"logger",
".",
"exception",
"(",
"\"Failed. Exception caught\"",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Given GeoJSON on stdin, writes a geobuf file to stdout. | [
"Given",
"GeoJSON",
"on",
"stdin",
"writes",
"a",
"geobuf",
"file",
"to",
"stdout",
"."
] | c9e055ab47532781626cfe2c931a8444820acf05 | https://github.com/pygeobuf/pygeobuf/blob/c9e055ab47532781626cfe2c931a8444820acf05/geobuf/scripts/cli.py#L46-L61 |
2,028 | pygeobuf/pygeobuf | geobuf/scripts/cli.py | decode | def decode():
"""Given a Geobuf byte string on stdin, write a GeoJSON feature
collection to stdout."""
logger = logging.getLogger('geobuf')
stdin = click.get_binary_stream('stdin')
sink = click.get_text_stream('stdout')
try:
pbf = stdin.read()
data = geobuf.decode(pbf)
json.dump(data, sink)
sys.exit(0)
except Exception:
logger.exception("Failed. Exception caught")
sys.exit(1) | python | def decode():
logger = logging.getLogger('geobuf')
stdin = click.get_binary_stream('stdin')
sink = click.get_text_stream('stdout')
try:
pbf = stdin.read()
data = geobuf.decode(pbf)
json.dump(data, sink)
sys.exit(0)
except Exception:
logger.exception("Failed. Exception caught")
sys.exit(1) | [
"def",
"decode",
"(",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'geobuf'",
")",
"stdin",
"=",
"click",
".",
"get_binary_stream",
"(",
"'stdin'",
")",
"sink",
"=",
"click",
".",
"get_text_stream",
"(",
"'stdout'",
")",
"try",
":",
"pbf",
"=",
"stdin",
".",
"read",
"(",
")",
"data",
"=",
"geobuf",
".",
"decode",
"(",
"pbf",
")",
"json",
".",
"dump",
"(",
"data",
",",
"sink",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"except",
"Exception",
":",
"logger",
".",
"exception",
"(",
"\"Failed. Exception caught\"",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Given a Geobuf byte string on stdin, write a GeoJSON feature
collection to stdout. | [
"Given",
"a",
"Geobuf",
"byte",
"string",
"on",
"stdin",
"write",
"a",
"GeoJSON",
"feature",
"collection",
"to",
"stdout",
"."
] | c9e055ab47532781626cfe2c931a8444820acf05 | https://github.com/pygeobuf/pygeobuf/blob/c9e055ab47532781626cfe2c931a8444820acf05/geobuf/scripts/cli.py#L65-L78 |
2,029 | tammoippen/geohash-hilbert | geohash_hilbert/_int2str.py | encode_int | def encode_int(code, bits_per_char=6):
"""Encode int into a string preserving order
It is using 2, 4 or 6 bits per coding character (default 6).
Parameters:
code: int Positive integer.
bits_per_char: int The number of bits per coding character.
Returns:
str: the encoded integer
"""
if code < 0:
raise ValueError('Only positive ints are allowed!')
if bits_per_char == 6:
return _encode_int64(code)
if bits_per_char == 4:
return _encode_int16(code)
if bits_per_char == 2:
return _encode_int4(code)
raise ValueError('`bits_per_char` must be in {6, 4, 2}') | python | def encode_int(code, bits_per_char=6):
if code < 0:
raise ValueError('Only positive ints are allowed!')
if bits_per_char == 6:
return _encode_int64(code)
if bits_per_char == 4:
return _encode_int16(code)
if bits_per_char == 2:
return _encode_int4(code)
raise ValueError('`bits_per_char` must be in {6, 4, 2}') | [
"def",
"encode_int",
"(",
"code",
",",
"bits_per_char",
"=",
"6",
")",
":",
"if",
"code",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Only positive ints are allowed!'",
")",
"if",
"bits_per_char",
"==",
"6",
":",
"return",
"_encode_int64",
"(",
"code",
")",
"if",
"bits_per_char",
"==",
"4",
":",
"return",
"_encode_int16",
"(",
"code",
")",
"if",
"bits_per_char",
"==",
"2",
":",
"return",
"_encode_int4",
"(",
"code",
")",
"raise",
"ValueError",
"(",
"'`bits_per_char` must be in {6, 4, 2}'",
")"
] | Encode int into a string preserving order
It is using 2, 4 or 6 bits per coding character (default 6).
Parameters:
code: int Positive integer.
bits_per_char: int The number of bits per coding character.
Returns:
str: the encoded integer | [
"Encode",
"int",
"into",
"a",
"string",
"preserving",
"order"
] | b74f0fc1bff0234d8ff367e4129c3324676b0b36 | https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_int2str.py#L27-L49 |
2,030 | tammoippen/geohash-hilbert | geohash_hilbert/_hilbert.py | _coord2int | def _coord2int(lng, lat, dim):
"""Convert lon, lat values into a dim x dim-grid coordinate system.
Parameters:
lng: float Longitude value of coordinate (-180.0, 180.0); corresponds to X axis
lat: float Latitude value of coordinate (-90.0, 90.0); corresponds to Y axis
dim: int Number of coding points each x, y value can take.
Corresponds to 2^level of the hilbert curve.
Returns:
Tuple[int, int]:
Lower left corner of corresponding dim x dim-grid box
x x value of point [0, dim); corresponds to longitude
y y value of point [0, dim); corresponds to latitude
"""
assert dim >= 1
lat_y = (lat + _LAT_INTERVAL[1]) / 180.0 * dim # [0 ... dim)
lng_x = (lng + _LNG_INTERVAL[1]) / 360.0 * dim # [0 ... dim)
return min(dim - 1, int(floor(lng_x))), min(dim - 1, int(floor(lat_y))) | python | def _coord2int(lng, lat, dim):
assert dim >= 1
lat_y = (lat + _LAT_INTERVAL[1]) / 180.0 * dim # [0 ... dim)
lng_x = (lng + _LNG_INTERVAL[1]) / 360.0 * dim # [0 ... dim)
return min(dim - 1, int(floor(lng_x))), min(dim - 1, int(floor(lat_y))) | [
"def",
"_coord2int",
"(",
"lng",
",",
"lat",
",",
"dim",
")",
":",
"assert",
"dim",
">=",
"1",
"lat_y",
"=",
"(",
"lat",
"+",
"_LAT_INTERVAL",
"[",
"1",
"]",
")",
"/",
"180.0",
"*",
"dim",
"# [0 ... dim)",
"lng_x",
"=",
"(",
"lng",
"+",
"_LNG_INTERVAL",
"[",
"1",
"]",
")",
"/",
"360.0",
"*",
"dim",
"# [0 ... dim)",
"return",
"min",
"(",
"dim",
"-",
"1",
",",
"int",
"(",
"floor",
"(",
"lng_x",
")",
")",
")",
",",
"min",
"(",
"dim",
"-",
"1",
",",
"int",
"(",
"floor",
"(",
"lat_y",
")",
")",
")"
] | Convert lon, lat values into a dim x dim-grid coordinate system.
Parameters:
lng: float Longitude value of coordinate (-180.0, 180.0); corresponds to X axis
lat: float Latitude value of coordinate (-90.0, 90.0); corresponds to Y axis
dim: int Number of coding points each x, y value can take.
Corresponds to 2^level of the hilbert curve.
Returns:
Tuple[int, int]:
Lower left corner of corresponding dim x dim-grid box
x x value of point [0, dim); corresponds to longitude
y y value of point [0, dim); corresponds to latitude | [
"Convert",
"lon",
"lat",
"values",
"into",
"a",
"dim",
"x",
"dim",
"-",
"grid",
"coordinate",
"system",
"."
] | b74f0fc1bff0234d8ff367e4129c3324676b0b36 | https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L157-L177 |
2,031 | tammoippen/geohash-hilbert | geohash_hilbert/_hilbert.py | _int2coord | def _int2coord(x, y, dim):
"""Convert x, y values in dim x dim-grid coordinate system into lng, lat values.
Parameters:
x: int x value of point [0, dim); corresponds to longitude
y: int y value of point [0, dim); corresponds to latitude
dim: int Number of coding points each x, y value can take.
Corresponds to 2^level of the hilbert curve.
Returns:
Tuple[float, float]: (lng, lat)
lng longitude value of coordinate [-180.0, 180.0]; corresponds to X axis
lat latitude value of coordinate [-90.0, 90.0]; corresponds to Y axis
"""
assert dim >= 1
assert x < dim
assert y < dim
lng = x / dim * 360 - 180
lat = y / dim * 180 - 90
return lng, lat | python | def _int2coord(x, y, dim):
assert dim >= 1
assert x < dim
assert y < dim
lng = x / dim * 360 - 180
lat = y / dim * 180 - 90
return lng, lat | [
"def",
"_int2coord",
"(",
"x",
",",
"y",
",",
"dim",
")",
":",
"assert",
"dim",
">=",
"1",
"assert",
"x",
"<",
"dim",
"assert",
"y",
"<",
"dim",
"lng",
"=",
"x",
"/",
"dim",
"*",
"360",
"-",
"180",
"lat",
"=",
"y",
"/",
"dim",
"*",
"180",
"-",
"90",
"return",
"lng",
",",
"lat"
] | Convert x, y values in dim x dim-grid coordinate system into lng, lat values.
Parameters:
x: int x value of point [0, dim); corresponds to longitude
y: int y value of point [0, dim); corresponds to latitude
dim: int Number of coding points each x, y value can take.
Corresponds to 2^level of the hilbert curve.
Returns:
Tuple[float, float]: (lng, lat)
lng longitude value of coordinate [-180.0, 180.0]; corresponds to X axis
lat latitude value of coordinate [-90.0, 90.0]; corresponds to Y axis | [
"Convert",
"x",
"y",
"values",
"in",
"dim",
"x",
"dim",
"-",
"grid",
"coordinate",
"system",
"into",
"lng",
"lat",
"values",
"."
] | b74f0fc1bff0234d8ff367e4129c3324676b0b36 | https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L180-L201 |
2,032 | tammoippen/geohash-hilbert | geohash_hilbert/_hilbert.py | _rotate | def _rotate(n, x, y, rx, ry):
"""Rotate and flip a quadrant appropriately
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
"""
if ry == 0:
if rx == 1:
x = n - 1 - x
y = n - 1 - y
return y, x
return x, y | python | def _rotate(n, x, y, rx, ry):
if ry == 0:
if rx == 1:
x = n - 1 - x
y = n - 1 - y
return y, x
return x, y | [
"def",
"_rotate",
"(",
"n",
",",
"x",
",",
"y",
",",
"rx",
",",
"ry",
")",
":",
"if",
"ry",
"==",
"0",
":",
"if",
"rx",
"==",
"1",
":",
"x",
"=",
"n",
"-",
"1",
"-",
"x",
"y",
"=",
"n",
"-",
"1",
"-",
"y",
"return",
"y",
",",
"x",
"return",
"x",
",",
"y"
] | Rotate and flip a quadrant appropriately
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 | [
"Rotate",
"and",
"flip",
"a",
"quadrant",
"appropriately"
] | b74f0fc1bff0234d8ff367e4129c3324676b0b36 | https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L263-L275 |
2,033 | tammoippen/geohash-hilbert | geohash_hilbert/_utils.py | neighbours | def neighbours(code, bits_per_char=6):
"""Get the neighbouring geohashes for `code`.
Look for the north, north-east, east, south-east, south, south-west, west,
north-west neighbours. If you are at the east/west edge of the grid
(lng ∈ (-180, 180)), then it wraps around the globe and gets the corresponding
neighbor.
Parameters:
code: str The geohash at the center.
bits_per_char: int The number of bits per coding character.
Returns:
dict: geohashes in the neighborhood of `code`. Possible keys are 'north',
'north-east', 'east', 'south-east', 'south', 'south-west',
'west', 'north-west'. If the input code covers the north pole, then
keys 'north', 'north-east', and 'north-west' are not present, and if
the input code covers the south pole then keys 'south', 'south-west',
and 'south-east' are not present.
"""
lng, lat, lng_err, lat_err = decode_exactly(code, bits_per_char)
precision = len(code)
north = lat + 2 * lat_err
south = lat - 2 * lat_err
east = lng + 2 * lng_err
if east > 180:
east -= 360
west = lng - 2 * lng_err
if west < -180:
west += 360
neighbours_dict = {
'east': encode(east, lat, precision, bits_per_char), # noqa: E241
'west': encode(west, lat, precision, bits_per_char), # noqa: E241
}
if north <= 90: # input cell not already at the north pole
neighbours_dict.update({
'north': encode(lng, north, precision, bits_per_char), # noqa: E241
'north-east': encode(east, north, precision, bits_per_char), # noqa: E241
'north-west': encode(west, north, precision, bits_per_char), # noqa: E241
})
if south >= -90: # input cell not already at the south pole
neighbours_dict.update({
'south': encode(lng, south, precision, bits_per_char), # noqa: E241
'south-east': encode(east, south, precision, bits_per_char), # noqa: E241
'south-west': encode(west, south, precision, bits_per_char), # noqa: E241
})
return neighbours_dict | python | def neighbours(code, bits_per_char=6):
lng, lat, lng_err, lat_err = decode_exactly(code, bits_per_char)
precision = len(code)
north = lat + 2 * lat_err
south = lat - 2 * lat_err
east = lng + 2 * lng_err
if east > 180:
east -= 360
west = lng - 2 * lng_err
if west < -180:
west += 360
neighbours_dict = {
'east': encode(east, lat, precision, bits_per_char), # noqa: E241
'west': encode(west, lat, precision, bits_per_char), # noqa: E241
}
if north <= 90: # input cell not already at the north pole
neighbours_dict.update({
'north': encode(lng, north, precision, bits_per_char), # noqa: E241
'north-east': encode(east, north, precision, bits_per_char), # noqa: E241
'north-west': encode(west, north, precision, bits_per_char), # noqa: E241
})
if south >= -90: # input cell not already at the south pole
neighbours_dict.update({
'south': encode(lng, south, precision, bits_per_char), # noqa: E241
'south-east': encode(east, south, precision, bits_per_char), # noqa: E241
'south-west': encode(west, south, precision, bits_per_char), # noqa: E241
})
return neighbours_dict | [
"def",
"neighbours",
"(",
"code",
",",
"bits_per_char",
"=",
"6",
")",
":",
"lng",
",",
"lat",
",",
"lng_err",
",",
"lat_err",
"=",
"decode_exactly",
"(",
"code",
",",
"bits_per_char",
")",
"precision",
"=",
"len",
"(",
"code",
")",
"north",
"=",
"lat",
"+",
"2",
"*",
"lat_err",
"south",
"=",
"lat",
"-",
"2",
"*",
"lat_err",
"east",
"=",
"lng",
"+",
"2",
"*",
"lng_err",
"if",
"east",
">",
"180",
":",
"east",
"-=",
"360",
"west",
"=",
"lng",
"-",
"2",
"*",
"lng_err",
"if",
"west",
"<",
"-",
"180",
":",
"west",
"+=",
"360",
"neighbours_dict",
"=",
"{",
"'east'",
":",
"encode",
"(",
"east",
",",
"lat",
",",
"precision",
",",
"bits_per_char",
")",
",",
"# noqa: E241",
"'west'",
":",
"encode",
"(",
"west",
",",
"lat",
",",
"precision",
",",
"bits_per_char",
")",
",",
"# noqa: E241",
"}",
"if",
"north",
"<=",
"90",
":",
"# input cell not already at the north pole",
"neighbours_dict",
".",
"update",
"(",
"{",
"'north'",
":",
"encode",
"(",
"lng",
",",
"north",
",",
"precision",
",",
"bits_per_char",
")",
",",
"# noqa: E241",
"'north-east'",
":",
"encode",
"(",
"east",
",",
"north",
",",
"precision",
",",
"bits_per_char",
")",
",",
"# noqa: E241",
"'north-west'",
":",
"encode",
"(",
"west",
",",
"north",
",",
"precision",
",",
"bits_per_char",
")",
",",
"# noqa: E241",
"}",
")",
"if",
"south",
">=",
"-",
"90",
":",
"# input cell not already at the south pole",
"neighbours_dict",
".",
"update",
"(",
"{",
"'south'",
":",
"encode",
"(",
"lng",
",",
"south",
",",
"precision",
",",
"bits_per_char",
")",
",",
"# noqa: E241",
"'south-east'",
":",
"encode",
"(",
"east",
",",
"south",
",",
"precision",
",",
"bits_per_char",
")",
",",
"# noqa: E241",
"'south-west'",
":",
"encode",
"(",
"west",
",",
"south",
",",
"precision",
",",
"bits_per_char",
")",
",",
"# noqa: E241",
"}",
")",
"return",
"neighbours_dict"
] | Get the neighbouring geohashes for `code`.
Look for the north, north-east, east, south-east, south, south-west, west,
north-west neighbours. If you are at the east/west edge of the grid
(lng ∈ (-180, 180)), then it wraps around the globe and gets the corresponding
neighbor.
Parameters:
code: str The geohash at the center.
bits_per_char: int The number of bits per coding character.
Returns:
dict: geohashes in the neighborhood of `code`. Possible keys are 'north',
'north-east', 'east', 'south-east', 'south', 'south-west',
'west', 'north-west'. If the input code covers the north pole, then
keys 'north', 'north-east', and 'north-west' are not present, and if
the input code covers the south pole then keys 'south', 'south-west',
and 'south-east' are not present. | [
"Get",
"the",
"neighbouring",
"geohashes",
"for",
"code",
"."
] | b74f0fc1bff0234d8ff367e4129c3324676b0b36 | https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_utils.py#L30-L84 |
2,034 | cocagne/txdbus | txdbus/objects.py | isSignatureValid | def isSignatureValid(expected, received):
"""
Verifies that the received signature matches the expected value
"""
if expected:
if not received or expected != received:
return False
else:
if received:
return False
return True | python | def isSignatureValid(expected, received):
if expected:
if not received or expected != received:
return False
else:
if received:
return False
return True | [
"def",
"isSignatureValid",
"(",
"expected",
",",
"received",
")",
":",
"if",
"expected",
":",
"if",
"not",
"received",
"or",
"expected",
"!=",
"received",
":",
"return",
"False",
"else",
":",
"if",
"received",
":",
"return",
"False",
"return",
"True"
] | Verifies that the received signature matches the expected value | [
"Verifies",
"that",
"the",
"received",
"signature",
"matches",
"the",
"expected",
"value"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L17-L27 |
2,035 | cocagne/txdbus | txdbus/objects.py | RemoteDBusObject.notifyOnDisconnect | def notifyOnDisconnect(self, callback):
"""
Registers a callback that will be called when the DBus connection
underlying the remote object is lost
@type callback: Callable object accepting a L{RemoteDBusObject} and
L{twisted.python.failure.Failure}
@param callback: Function that will be called when the connection to
the DBus session is lost. Arguments are the
L{RemoteDBusObject} instance and reason for the
disconnect (the same value passed to
L{twisted.internet.protocol.Protocol.connectionLost})
"""
if self._disconnectCBs is None:
self._disconnectCBs = []
self._disconnectCBs.append(callback) | python | def notifyOnDisconnect(self, callback):
if self._disconnectCBs is None:
self._disconnectCBs = []
self._disconnectCBs.append(callback) | [
"def",
"notifyOnDisconnect",
"(",
"self",
",",
"callback",
")",
":",
"if",
"self",
".",
"_disconnectCBs",
"is",
"None",
":",
"self",
".",
"_disconnectCBs",
"=",
"[",
"]",
"self",
".",
"_disconnectCBs",
".",
"append",
"(",
"callback",
")"
] | Registers a callback that will be called when the DBus connection
underlying the remote object is lost
@type callback: Callable object accepting a L{RemoteDBusObject} and
L{twisted.python.failure.Failure}
@param callback: Function that will be called when the connection to
the DBus session is lost. Arguments are the
L{RemoteDBusObject} instance and reason for the
disconnect (the same value passed to
L{twisted.internet.protocol.Protocol.connectionLost}) | [
"Registers",
"a",
"callback",
"that",
"will",
"be",
"called",
"when",
"the",
"DBus",
"connection",
"underlying",
"the",
"remote",
"object",
"is",
"lost"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L112-L127 |
2,036 | cocagne/txdbus | txdbus/objects.py | RemoteDBusObject.notifyOnSignal | def notifyOnSignal(self, signalName, callback, interface=None):
"""
Informs the DBus daemon of the process's interest in the specified
signal and registers the callback function to be called when the
signal arrives. Multiple callbacks may be registered.
@type signalName: C{string}
@param signalName: Name of the signal to register the callback for
@type callback: Callable object
@param callback: Callback to be called on signal arrival. The callback
will be passed signals arguments as positional function arguments.
@type interface: C{string}
@param interface: Optional DBus interface emitting the signal. This is
only needed if more than one interface shares a signal with the
same name
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to an integer rule_id that may be passed to
cancelSignalNotification to prevent the delivery of future signals
to the callback
"""
iface = None
signal = None
for i in self.interfaces:
if interface and not i.name == interface:
continue
if signalName in i.signals:
signal = i.signals[signalName]
iface = i
break
def callback_caller(sig_msg):
if isSignatureValid(signal.sig, sig_msg.signature):
if sig_msg.body:
callback(*sig_msg.body)
else:
callback()
if iface is None:
raise AttributeError(
'Requested signal "%s" is not a member of any of the '
'supported interfaces' % (signalName,),
)
d = self.objHandler.conn.addMatch(
callback_caller,
mtype='signal',
path=self.objectPath,
member=signalName,
interface=iface.name,
)
def on_ok(rule_id):
if self._signalRules is None:
self._signalRules = set()
self._signalRules.add(rule_id)
return rule_id
d.addCallback(on_ok)
return d | python | def notifyOnSignal(self, signalName, callback, interface=None):
iface = None
signal = None
for i in self.interfaces:
if interface and not i.name == interface:
continue
if signalName in i.signals:
signal = i.signals[signalName]
iface = i
break
def callback_caller(sig_msg):
if isSignatureValid(signal.sig, sig_msg.signature):
if sig_msg.body:
callback(*sig_msg.body)
else:
callback()
if iface is None:
raise AttributeError(
'Requested signal "%s" is not a member of any of the '
'supported interfaces' % (signalName,),
)
d = self.objHandler.conn.addMatch(
callback_caller,
mtype='signal',
path=self.objectPath,
member=signalName,
interface=iface.name,
)
def on_ok(rule_id):
if self._signalRules is None:
self._signalRules = set()
self._signalRules.add(rule_id)
return rule_id
d.addCallback(on_ok)
return d | [
"def",
"notifyOnSignal",
"(",
"self",
",",
"signalName",
",",
"callback",
",",
"interface",
"=",
"None",
")",
":",
"iface",
"=",
"None",
"signal",
"=",
"None",
"for",
"i",
"in",
"self",
".",
"interfaces",
":",
"if",
"interface",
"and",
"not",
"i",
".",
"name",
"==",
"interface",
":",
"continue",
"if",
"signalName",
"in",
"i",
".",
"signals",
":",
"signal",
"=",
"i",
".",
"signals",
"[",
"signalName",
"]",
"iface",
"=",
"i",
"break",
"def",
"callback_caller",
"(",
"sig_msg",
")",
":",
"if",
"isSignatureValid",
"(",
"signal",
".",
"sig",
",",
"sig_msg",
".",
"signature",
")",
":",
"if",
"sig_msg",
".",
"body",
":",
"callback",
"(",
"*",
"sig_msg",
".",
"body",
")",
"else",
":",
"callback",
"(",
")",
"if",
"iface",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"'Requested signal \"%s\" is not a member of any of the '",
"'supported interfaces'",
"%",
"(",
"signalName",
",",
")",
",",
")",
"d",
"=",
"self",
".",
"objHandler",
".",
"conn",
".",
"addMatch",
"(",
"callback_caller",
",",
"mtype",
"=",
"'signal'",
",",
"path",
"=",
"self",
".",
"objectPath",
",",
"member",
"=",
"signalName",
",",
"interface",
"=",
"iface",
".",
"name",
",",
")",
"def",
"on_ok",
"(",
"rule_id",
")",
":",
"if",
"self",
".",
"_signalRules",
"is",
"None",
":",
"self",
".",
"_signalRules",
"=",
"set",
"(",
")",
"self",
".",
"_signalRules",
".",
"add",
"(",
"rule_id",
")",
"return",
"rule_id",
"d",
".",
"addCallback",
"(",
"on_ok",
")",
"return",
"d"
] | Informs the DBus daemon of the process's interest in the specified
signal and registers the callback function to be called when the
signal arrives. Multiple callbacks may be registered.
@type signalName: C{string}
@param signalName: Name of the signal to register the callback for
@type callback: Callable object
@param callback: Callback to be called on signal arrival. The callback
will be passed signals arguments as positional function arguments.
@type interface: C{string}
@param interface: Optional DBus interface emitting the signal. This is
only needed if more than one interface shares a signal with the
same name
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to an integer rule_id that may be passed to
cancelSignalNotification to prevent the delivery of future signals
to the callback | [
"Informs",
"the",
"DBus",
"daemon",
"of",
"the",
"process",
"s",
"interest",
"in",
"the",
"specified",
"signal",
"and",
"registers",
"the",
"callback",
"function",
"to",
"be",
"called",
"when",
"the",
"signal",
"arrives",
".",
"Multiple",
"callbacks",
"may",
"be",
"registered",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L144-L211 |
2,037 | cocagne/txdbus | txdbus/objects.py | RemoteDBusObject.cancelSignalNotification | def cancelSignalNotification(self, rule_id):
"""
Cancels a callback previously registered with notifyOnSignal
"""
if self._signalRules and rule_id in self._signalRules:
self.objHandler.conn.delMatch(rule_id)
self._signalRules.remove(rule_id) | python | def cancelSignalNotification(self, rule_id):
if self._signalRules and rule_id in self._signalRules:
self.objHandler.conn.delMatch(rule_id)
self._signalRules.remove(rule_id) | [
"def",
"cancelSignalNotification",
"(",
"self",
",",
"rule_id",
")",
":",
"if",
"self",
".",
"_signalRules",
"and",
"rule_id",
"in",
"self",
".",
"_signalRules",
":",
"self",
".",
"objHandler",
".",
"conn",
".",
"delMatch",
"(",
"rule_id",
")",
"self",
".",
"_signalRules",
".",
"remove",
"(",
"rule_id",
")"
] | Cancels a callback previously registered with notifyOnSignal | [
"Cancels",
"a",
"callback",
"previously",
"registered",
"with",
"notifyOnSignal"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L213-L219 |
2,038 | cocagne/txdbus | txdbus/objects.py | RemoteDBusObject.callRemote | def callRemote(self, methodName, *args, **kwargs):
"""
Calls the remote method and returns a Deferred instance to the result.
DBus does not support passing keyword arguments over the wire. The
keyword arguments accepted by this method alter the behavior of the
remote call as described in the kwargs prameter description.
@type methodName: C{string}
@param methodName: Name of the method to call
@param args: Positional arguments to be passed to the remote method
@param kwargs: Three keyword parameters may be passed to alter the
behavior of the remote method call. If \"expectReply=False\" is
supplied, the returned Deferred will be immediately called back
with the value None. If \"autoStart=False\" is supplied the DBus
daemon will not attempt to auto-start a service to fulfill the call
if the service is not yet running (defaults to True). If
\"timeout=VALUE\" is supplied, the returned Deferred will be
errbacked with a L{error.TimeOut} instance if the remote call does
not return before the timeout elapses. If \"interface\" is
specified, the remote call use the method of the named interface.
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to the result of the remote call
"""
expectReply = kwargs.get('expectReply', True)
autoStart = kwargs.get('autoStart', True)
timeout = kwargs.get('timeout', None)
interface = kwargs.get('interface', None)
m = None
for i in self.interfaces:
if interface and not interface == i.name:
continue
m = i.methods.get(methodName, None)
if m:
break
if m is None:
raise AttributeError(
'Requested method "%s" is not a member of any of the '
'supported interfaces' % (methodName,),
)
if len(args) != m.nargs:
raise TypeError(
'%s.%s takes %d arguments (%d given)' %
(i.name, methodName, m.nargs, len(args)),
)
return self.objHandler.conn.callRemote(
self.objectPath, methodName,
interface=i.name,
destination=self.busName,
signature=m.sigIn,
body=args,
expectReply=expectReply,
autoStart=autoStart,
timeout=timeout,
returnSignature=m.sigOut,
) | python | def callRemote(self, methodName, *args, **kwargs):
expectReply = kwargs.get('expectReply', True)
autoStart = kwargs.get('autoStart', True)
timeout = kwargs.get('timeout', None)
interface = kwargs.get('interface', None)
m = None
for i in self.interfaces:
if interface and not interface == i.name:
continue
m = i.methods.get(methodName, None)
if m:
break
if m is None:
raise AttributeError(
'Requested method "%s" is not a member of any of the '
'supported interfaces' % (methodName,),
)
if len(args) != m.nargs:
raise TypeError(
'%s.%s takes %d arguments (%d given)' %
(i.name, methodName, m.nargs, len(args)),
)
return self.objHandler.conn.callRemote(
self.objectPath, methodName,
interface=i.name,
destination=self.busName,
signature=m.sigIn,
body=args,
expectReply=expectReply,
autoStart=autoStart,
timeout=timeout,
returnSignature=m.sigOut,
) | [
"def",
"callRemote",
"(",
"self",
",",
"methodName",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"expectReply",
"=",
"kwargs",
".",
"get",
"(",
"'expectReply'",
",",
"True",
")",
"autoStart",
"=",
"kwargs",
".",
"get",
"(",
"'autoStart'",
",",
"True",
")",
"timeout",
"=",
"kwargs",
".",
"get",
"(",
"'timeout'",
",",
"None",
")",
"interface",
"=",
"kwargs",
".",
"get",
"(",
"'interface'",
",",
"None",
")",
"m",
"=",
"None",
"for",
"i",
"in",
"self",
".",
"interfaces",
":",
"if",
"interface",
"and",
"not",
"interface",
"==",
"i",
".",
"name",
":",
"continue",
"m",
"=",
"i",
".",
"methods",
".",
"get",
"(",
"methodName",
",",
"None",
")",
"if",
"m",
":",
"break",
"if",
"m",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"'Requested method \"%s\" is not a member of any of the '",
"'supported interfaces'",
"%",
"(",
"methodName",
",",
")",
",",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"m",
".",
"nargs",
":",
"raise",
"TypeError",
"(",
"'%s.%s takes %d arguments (%d given)'",
"%",
"(",
"i",
".",
"name",
",",
"methodName",
",",
"m",
".",
"nargs",
",",
"len",
"(",
"args",
")",
")",
",",
")",
"return",
"self",
".",
"objHandler",
".",
"conn",
".",
"callRemote",
"(",
"self",
".",
"objectPath",
",",
"methodName",
",",
"interface",
"=",
"i",
".",
"name",
",",
"destination",
"=",
"self",
".",
"busName",
",",
"signature",
"=",
"m",
".",
"sigIn",
",",
"body",
"=",
"args",
",",
"expectReply",
"=",
"expectReply",
",",
"autoStart",
"=",
"autoStart",
",",
"timeout",
"=",
"timeout",
",",
"returnSignature",
"=",
"m",
".",
"sigOut",
",",
")"
] | Calls the remote method and returns a Deferred instance to the result.
DBus does not support passing keyword arguments over the wire. The
keyword arguments accepted by this method alter the behavior of the
remote call as described in the kwargs prameter description.
@type methodName: C{string}
@param methodName: Name of the method to call
@param args: Positional arguments to be passed to the remote method
@param kwargs: Three keyword parameters may be passed to alter the
behavior of the remote method call. If \"expectReply=False\" is
supplied, the returned Deferred will be immediately called back
with the value None. If \"autoStart=False\" is supplied the DBus
daemon will not attempt to auto-start a service to fulfill the call
if the service is not yet running (defaults to True). If
\"timeout=VALUE\" is supplied, the returned Deferred will be
errbacked with a L{error.TimeOut} instance if the remote call does
not return before the timeout elapses. If \"interface\" is
specified, the remote call use the method of the named interface.
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to the result of the remote call | [
"Calls",
"the",
"remote",
"method",
"and",
"returns",
"a",
"Deferred",
"instance",
"to",
"the",
"result",
".",
"DBus",
"does",
"not",
"support",
"passing",
"keyword",
"arguments",
"over",
"the",
"wire",
".",
"The",
"keyword",
"arguments",
"accepted",
"by",
"this",
"method",
"alter",
"the",
"behavior",
"of",
"the",
"remote",
"call",
"as",
"described",
"in",
"the",
"kwargs",
"prameter",
"description",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L221-L283 |
2,039 | cocagne/txdbus | txdbus/objects.py | DBusObjectHandler.connectionLost | def connectionLost(self, reason):
"""
Called by the DBus Connection object when the connection is lost.
@type reason: L{twistd.python.failure.Failure}
@param reason: The value passed to the associated connection's
connectionLost method.
"""
for wref in self._weakProxies.valuerefs():
p = wref()
if p is not None:
p.connectionLost(reason) | python | def connectionLost(self, reason):
for wref in self._weakProxies.valuerefs():
p = wref()
if p is not None:
p.connectionLost(reason) | [
"def",
"connectionLost",
"(",
"self",
",",
"reason",
")",
":",
"for",
"wref",
"in",
"self",
".",
"_weakProxies",
".",
"valuerefs",
"(",
")",
":",
"p",
"=",
"wref",
"(",
")",
"if",
"p",
"is",
"not",
"None",
":",
"p",
".",
"connectionLost",
"(",
"reason",
")"
] | Called by the DBus Connection object when the connection is lost.
@type reason: L{twistd.python.failure.Failure}
@param reason: The value passed to the associated connection's
connectionLost method. | [
"Called",
"by",
"the",
"DBus",
"Connection",
"object",
"when",
"the",
"connection",
"is",
"lost",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L649-L660 |
2,040 | cocagne/txdbus | txdbus/objects.py | DBusObjectHandler.exportObject | def exportObject(self, dbusObject):
"""
Makes the specified object available over DBus
@type dbusObject: an object implementing the L{IDBusObject} interface
@param dbusObject: The object to export over DBus
"""
o = IDBusObject(dbusObject)
self.exports[o.getObjectPath()] = o
o.setObjectHandler(self)
i = {}
for iface in o.getInterfaces():
i[iface.name] = o.getAllProperties(iface.name)
msig = message.SignalMessage(
o.getObjectPath(),
'InterfacesAdded',
'org.freedesktop.DBus.ObjectManager',
signature='sa{sa{sv}}',
body=[o.getObjectPath(), i],
)
self.conn.sendMessage(msig) | python | def exportObject(self, dbusObject):
o = IDBusObject(dbusObject)
self.exports[o.getObjectPath()] = o
o.setObjectHandler(self)
i = {}
for iface in o.getInterfaces():
i[iface.name] = o.getAllProperties(iface.name)
msig = message.SignalMessage(
o.getObjectPath(),
'InterfacesAdded',
'org.freedesktop.DBus.ObjectManager',
signature='sa{sa{sv}}',
body=[o.getObjectPath(), i],
)
self.conn.sendMessage(msig) | [
"def",
"exportObject",
"(",
"self",
",",
"dbusObject",
")",
":",
"o",
"=",
"IDBusObject",
"(",
"dbusObject",
")",
"self",
".",
"exports",
"[",
"o",
".",
"getObjectPath",
"(",
")",
"]",
"=",
"o",
"o",
".",
"setObjectHandler",
"(",
"self",
")",
"i",
"=",
"{",
"}",
"for",
"iface",
"in",
"o",
".",
"getInterfaces",
"(",
")",
":",
"i",
"[",
"iface",
".",
"name",
"]",
"=",
"o",
".",
"getAllProperties",
"(",
"iface",
".",
"name",
")",
"msig",
"=",
"message",
".",
"SignalMessage",
"(",
"o",
".",
"getObjectPath",
"(",
")",
",",
"'InterfacesAdded'",
",",
"'org.freedesktop.DBus.ObjectManager'",
",",
"signature",
"=",
"'sa{sa{sv}}'",
",",
"body",
"=",
"[",
"o",
".",
"getObjectPath",
"(",
")",
",",
"i",
"]",
",",
")",
"self",
".",
"conn",
".",
"sendMessage",
"(",
"msig",
")"
] | Makes the specified object available over DBus
@type dbusObject: an object implementing the L{IDBusObject} interface
@param dbusObject: The object to export over DBus | [
"Makes",
"the",
"specified",
"object",
"available",
"over",
"DBus"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L662-L685 |
2,041 | cocagne/txdbus | txdbus/objects.py | DBusObjectHandler.getManagedObjects | def getManagedObjects(self, objectPath):
"""
Returns a Python dictionary containing the reply content for
org.freedesktop.DBus.ObjectManager.GetManagedObjects
"""
d = {}
for p in sorted(self.exports.keys()):
if not p.startswith(objectPath) or p == objectPath:
continue
o = self.exports[p]
i = {}
d[p] = i
for iface in o.getInterfaces():
i[iface.name] = o.getAllProperties(iface.name)
return d | python | def getManagedObjects(self, objectPath):
d = {}
for p in sorted(self.exports.keys()):
if not p.startswith(objectPath) or p == objectPath:
continue
o = self.exports[p]
i = {}
d[p] = i
for iface in o.getInterfaces():
i[iface.name] = o.getAllProperties(iface.name)
return d | [
"def",
"getManagedObjects",
"(",
"self",
",",
"objectPath",
")",
":",
"d",
"=",
"{",
"}",
"for",
"p",
"in",
"sorted",
"(",
"self",
".",
"exports",
".",
"keys",
"(",
")",
")",
":",
"if",
"not",
"p",
".",
"startswith",
"(",
"objectPath",
")",
"or",
"p",
"==",
"objectPath",
":",
"continue",
"o",
"=",
"self",
".",
"exports",
"[",
"p",
"]",
"i",
"=",
"{",
"}",
"d",
"[",
"p",
"]",
"=",
"i",
"for",
"iface",
"in",
"o",
".",
"getInterfaces",
"(",
")",
":",
"i",
"[",
"iface",
".",
"name",
"]",
"=",
"o",
".",
"getAllProperties",
"(",
"iface",
".",
"name",
")",
"return",
"d"
] | Returns a Python dictionary containing the reply content for
org.freedesktop.DBus.ObjectManager.GetManagedObjects | [
"Returns",
"a",
"Python",
"dictionary",
"containing",
"the",
"reply",
"content",
"for",
"org",
".",
"freedesktop",
".",
"DBus",
".",
"ObjectManager",
".",
"GetManagedObjects"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L708-L724 |
2,042 | cocagne/txdbus | txdbus/objects.py | DBusObjectHandler._send_err | def _send_err(self, msg, errName, errMsg):
"""
Helper method for sending error messages
"""
r = message.ErrorMessage(
errName,
msg.serial,
body=[errMsg],
signature='s',
destination=msg.sender,
)
self.conn.sendMessage(r) | python | def _send_err(self, msg, errName, errMsg):
r = message.ErrorMessage(
errName,
msg.serial,
body=[errMsg],
signature='s',
destination=msg.sender,
)
self.conn.sendMessage(r) | [
"def",
"_send_err",
"(",
"self",
",",
"msg",
",",
"errName",
",",
"errMsg",
")",
":",
"r",
"=",
"message",
".",
"ErrorMessage",
"(",
"errName",
",",
"msg",
".",
"serial",
",",
"body",
"=",
"[",
"errMsg",
"]",
",",
"signature",
"=",
"'s'",
",",
"destination",
"=",
"msg",
".",
"sender",
",",
")",
"self",
".",
"conn",
".",
"sendMessage",
"(",
"r",
")"
] | Helper method for sending error messages | [
"Helper",
"method",
"for",
"sending",
"error",
"messages"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/objects.py#L726-L738 |
2,043 | cocagne/txdbus | txdbus/client.py | DBusClientConnection._cbGotHello | def _cbGotHello(self, busName):
"""
Called in reply to the initial Hello remote method invocation
"""
self.busName = busName
# print 'Connection Bus Name = ', self.busName
self.factory._ok(self) | python | def _cbGotHello(self, busName):
self.busName = busName
# print 'Connection Bus Name = ', self.busName
self.factory._ok(self) | [
"def",
"_cbGotHello",
"(",
"self",
",",
"busName",
")",
":",
"self",
".",
"busName",
"=",
"busName",
"# print 'Connection Bus Name = ', self.busName",
"self",
".",
"factory",
".",
"_ok",
"(",
"self",
")"
] | Called in reply to the initial Hello remote method invocation | [
"Called",
"in",
"reply",
"to",
"the",
"initial",
"Hello",
"remote",
"method",
"invocation"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L81-L89 |
2,044 | cocagne/txdbus | txdbus/client.py | DBusClientConnection.connectionLost | def connectionLost(self, reason):
"""
Called when the transport loses connection to the bus
"""
if self.busName is None:
return
for cb in self._dcCallbacks:
cb(self, reason)
for d, timeout in self._pendingCalls.values():
if timeout:
timeout.cancel()
d.errback(reason)
self._pendingCalls = {}
self.objHandler.connectionLost(reason) | python | def connectionLost(self, reason):
if self.busName is None:
return
for cb in self._dcCallbacks:
cb(self, reason)
for d, timeout in self._pendingCalls.values():
if timeout:
timeout.cancel()
d.errback(reason)
self._pendingCalls = {}
self.objHandler.connectionLost(reason) | [
"def",
"connectionLost",
"(",
"self",
",",
"reason",
")",
":",
"if",
"self",
".",
"busName",
"is",
"None",
":",
"return",
"for",
"cb",
"in",
"self",
".",
"_dcCallbacks",
":",
"cb",
"(",
"self",
",",
"reason",
")",
"for",
"d",
",",
"timeout",
"in",
"self",
".",
"_pendingCalls",
".",
"values",
"(",
")",
":",
"if",
"timeout",
":",
"timeout",
".",
"cancel",
"(",
")",
"d",
".",
"errback",
"(",
"reason",
")",
"self",
".",
"_pendingCalls",
"=",
"{",
"}",
"self",
".",
"objHandler",
".",
"connectionLost",
"(",
"reason",
")"
] | Called when the transport loses connection to the bus | [
"Called",
"when",
"the",
"transport",
"loses",
"connection",
"to",
"the",
"bus"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L97-L113 |
2,045 | cocagne/txdbus | txdbus/client.py | DBusClientConnection.delMatch | def delMatch(self, rule_id):
"""
Removes a message matching rule previously registered with addMatch
"""
rule = self.match_rules[rule_id]
d = self.callRemote(
'/org/freedesktop/DBus',
'RemoveMatch',
interface='org.freedesktop.DBus',
destination='org.freedesktop.DBus',
body=[rule],
signature='s',
)
def ok(_):
del self.match_rules[rule_id]
self.router.delMatch(rule_id)
d.addCallback(ok)
return d | python | def delMatch(self, rule_id):
rule = self.match_rules[rule_id]
d = self.callRemote(
'/org/freedesktop/DBus',
'RemoveMatch',
interface='org.freedesktop.DBus',
destination='org.freedesktop.DBus',
body=[rule],
signature='s',
)
def ok(_):
del self.match_rules[rule_id]
self.router.delMatch(rule_id)
d.addCallback(ok)
return d | [
"def",
"delMatch",
"(",
"self",
",",
"rule_id",
")",
":",
"rule",
"=",
"self",
".",
"match_rules",
"[",
"rule_id",
"]",
"d",
"=",
"self",
".",
"callRemote",
"(",
"'/org/freedesktop/DBus'",
",",
"'RemoveMatch'",
",",
"interface",
"=",
"'org.freedesktop.DBus'",
",",
"destination",
"=",
"'org.freedesktop.DBus'",
",",
"body",
"=",
"[",
"rule",
"]",
",",
"signature",
"=",
"'s'",
",",
")",
"def",
"ok",
"(",
"_",
")",
":",
"del",
"self",
".",
"match_rules",
"[",
"rule_id",
"]",
"self",
".",
"router",
".",
"delMatch",
"(",
"rule_id",
")",
"d",
".",
"addCallback",
"(",
"ok",
")",
"return",
"d"
] | Removes a message matching rule previously registered with addMatch | [
"Removes",
"a",
"message",
"matching",
"rule",
"previously",
"registered",
"with",
"addMatch"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L180-L201 |
2,046 | cocagne/txdbus | txdbus/client.py | DBusClientConnection.addMatch | def addMatch(self, callback, mtype=None, sender=None, interface=None,
member=None, path=None, path_namespace=None, destination=None,
arg=None, arg_path=None, arg0namespace=None):
"""
Creates a message matching rule, associates it with the specified
callback function, and sends the match rule to the DBus daemon.
The arguments to this function are exactly follow the DBus
specification. Refer to the \"Message Bus Message Routing\" section of
the DBus specification for details.
@rtype: C{int}
@returns: a L{Deferred} to an integer id that may be used to unregister
the match rule
"""
l = []
def add(k, v):
if v is not None:
l.append("%s='%s'" % (k, v))
add('type', mtype)
add('sender', sender)
add('interface', interface)
add('member', member)
add('path', path)
add('path_namespace', path_namespace)
add('destination', destination)
if arg:
for idx, v in arg:
add('arg%d' % (idx,), v)
if arg_path:
for idx, v in arg_path:
add('arg%dpath' % (idx,), v)
add('arg0namespace', arg0namespace)
rule = ','.join(l)
d = self.callRemote(
'/org/freedesktop/DBus',
'AddMatch',
interface='org.freedesktop.DBus',
destination='org.freedesktop.DBus',
body=[rule],
signature='s',
)
def ok(_):
rule_id = self.router.addMatch(
callback,
mtype,
sender,
interface,
member,
path,
path_namespace,
destination,
arg,
arg_path,
arg0namespace,
)
self.match_rules[rule_id] = rule
return rule_id
d.addCallbacks(ok)
return d | python | def addMatch(self, callback, mtype=None, sender=None, interface=None,
member=None, path=None, path_namespace=None, destination=None,
arg=None, arg_path=None, arg0namespace=None):
l = []
def add(k, v):
if v is not None:
l.append("%s='%s'" % (k, v))
add('type', mtype)
add('sender', sender)
add('interface', interface)
add('member', member)
add('path', path)
add('path_namespace', path_namespace)
add('destination', destination)
if arg:
for idx, v in arg:
add('arg%d' % (idx,), v)
if arg_path:
for idx, v in arg_path:
add('arg%dpath' % (idx,), v)
add('arg0namespace', arg0namespace)
rule = ','.join(l)
d = self.callRemote(
'/org/freedesktop/DBus',
'AddMatch',
interface='org.freedesktop.DBus',
destination='org.freedesktop.DBus',
body=[rule],
signature='s',
)
def ok(_):
rule_id = self.router.addMatch(
callback,
mtype,
sender,
interface,
member,
path,
path_namespace,
destination,
arg,
arg_path,
arg0namespace,
)
self.match_rules[rule_id] = rule
return rule_id
d.addCallbacks(ok)
return d | [
"def",
"addMatch",
"(",
"self",
",",
"callback",
",",
"mtype",
"=",
"None",
",",
"sender",
"=",
"None",
",",
"interface",
"=",
"None",
",",
"member",
"=",
"None",
",",
"path",
"=",
"None",
",",
"path_namespace",
"=",
"None",
",",
"destination",
"=",
"None",
",",
"arg",
"=",
"None",
",",
"arg_path",
"=",
"None",
",",
"arg0namespace",
"=",
"None",
")",
":",
"l",
"=",
"[",
"]",
"def",
"add",
"(",
"k",
",",
"v",
")",
":",
"if",
"v",
"is",
"not",
"None",
":",
"l",
".",
"append",
"(",
"\"%s='%s'\"",
"%",
"(",
"k",
",",
"v",
")",
")",
"add",
"(",
"'type'",
",",
"mtype",
")",
"add",
"(",
"'sender'",
",",
"sender",
")",
"add",
"(",
"'interface'",
",",
"interface",
")",
"add",
"(",
"'member'",
",",
"member",
")",
"add",
"(",
"'path'",
",",
"path",
")",
"add",
"(",
"'path_namespace'",
",",
"path_namespace",
")",
"add",
"(",
"'destination'",
",",
"destination",
")",
"if",
"arg",
":",
"for",
"idx",
",",
"v",
"in",
"arg",
":",
"add",
"(",
"'arg%d'",
"%",
"(",
"idx",
",",
")",
",",
"v",
")",
"if",
"arg_path",
":",
"for",
"idx",
",",
"v",
"in",
"arg_path",
":",
"add",
"(",
"'arg%dpath'",
"%",
"(",
"idx",
",",
")",
",",
"v",
")",
"add",
"(",
"'arg0namespace'",
",",
"arg0namespace",
")",
"rule",
"=",
"','",
".",
"join",
"(",
"l",
")",
"d",
"=",
"self",
".",
"callRemote",
"(",
"'/org/freedesktop/DBus'",
",",
"'AddMatch'",
",",
"interface",
"=",
"'org.freedesktop.DBus'",
",",
"destination",
"=",
"'org.freedesktop.DBus'",
",",
"body",
"=",
"[",
"rule",
"]",
",",
"signature",
"=",
"'s'",
",",
")",
"def",
"ok",
"(",
"_",
")",
":",
"rule_id",
"=",
"self",
".",
"router",
".",
"addMatch",
"(",
"callback",
",",
"mtype",
",",
"sender",
",",
"interface",
",",
"member",
",",
"path",
",",
"path_namespace",
",",
"destination",
",",
"arg",
",",
"arg_path",
",",
"arg0namespace",
",",
")",
"self",
".",
"match_rules",
"[",
"rule_id",
"]",
"=",
"rule",
"return",
"rule_id",
"d",
".",
"addCallbacks",
"(",
"ok",
")",
"return",
"d"
] | Creates a message matching rule, associates it with the specified
callback function, and sends the match rule to the DBus daemon.
The arguments to this function are exactly follow the DBus
specification. Refer to the \"Message Bus Message Routing\" section of
the DBus specification for details.
@rtype: C{int}
@returns: a L{Deferred} to an integer id that may be used to unregister
the match rule | [
"Creates",
"a",
"message",
"matching",
"rule",
"associates",
"it",
"with",
"the",
"specified",
"callback",
"function",
"and",
"sends",
"the",
"match",
"rule",
"to",
"the",
"DBus",
"daemon",
".",
"The",
"arguments",
"to",
"this",
"function",
"are",
"exactly",
"follow",
"the",
"DBus",
"specification",
".",
"Refer",
"to",
"the",
"\\",
"Message",
"Bus",
"Message",
"Routing",
"\\",
"section",
"of",
"the",
"DBus",
"specification",
"for",
"details",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L203-L272 |
2,047 | cocagne/txdbus | txdbus/client.py | DBusClientConnection.getNameOwner | def getNameOwner(self, busName):
"""
Calls org.freedesktop.DBus.GetNameOwner
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to the unique connection name owning the bus name
"""
d = self.callRemote(
'/org/freedesktop/DBus',
'GetNameOwner',
interface='org.freedesktop.DBus',
signature='s',
body=[busName],
destination='org.freedesktop.DBus',
)
return d | python | def getNameOwner(self, busName):
d = self.callRemote(
'/org/freedesktop/DBus',
'GetNameOwner',
interface='org.freedesktop.DBus',
signature='s',
body=[busName],
destination='org.freedesktop.DBus',
)
return d | [
"def",
"getNameOwner",
"(",
"self",
",",
"busName",
")",
":",
"d",
"=",
"self",
".",
"callRemote",
"(",
"'/org/freedesktop/DBus'",
",",
"'GetNameOwner'",
",",
"interface",
"=",
"'org.freedesktop.DBus'",
",",
"signature",
"=",
"'s'",
",",
"body",
"=",
"[",
"busName",
"]",
",",
"destination",
"=",
"'org.freedesktop.DBus'",
",",
")",
"return",
"d"
] | Calls org.freedesktop.DBus.GetNameOwner
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to the unique connection name owning the bus name | [
"Calls",
"org",
".",
"freedesktop",
".",
"DBus",
".",
"GetNameOwner"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L274-L288 |
2,048 | cocagne/txdbus | txdbus/client.py | DBusClientConnection.requestBusName | def requestBusName(self, newName,
allowReplacement=False,
replaceExisting=False,
doNotQueue=True,
errbackUnlessAcquired=True):
"""
Calls org.freedesktop.DBus.RequestName to request that the specified
bus name be associated with the connection.
@type newName: C{string}
@param newName: Bus name to acquire
@type allowReplacement: C{bool}
@param allowReplacement: If True (defaults to False) and another
application later requests this same name, the new requester will
be given the name and this connection will lose ownership.
@type replaceExisting: C{bool}
@param replaceExisting: If True (defaults to False) and another
application owns the name but specified allowReplacement at the
time of the name acquisition, this connection will assume ownership
of the bus name.
@type doNotQueue: C{bool}
@param doNotQueue: If True (defaults to True) the name request will
fail if the name is currently in use. If False, the request will
cause this connection to be queued for ownership of the requested
name
@type errbackUnlessAcquired: C{bool}
@param errbackUnlessAcquired: If True (defaults to True) an
L{twisted.python.failure.Failure} will be returned if the name is
not acquired.
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to
"""
flags = 0
if allowReplacement:
flags |= 0x1
if replaceExisting:
flags |= 0x2
if doNotQueue:
flags |= 0x4
d = self.callRemote(
'/org/freedesktop/DBus',
'RequestName',
interface='org.freedesktop.DBus',
signature='su',
body=[newName, flags],
destination='org.freedesktop.DBus',
)
def on_result(r):
if errbackUnlessAcquired and not (
r == NAME_ACQUIRED or r == NAME_ALREADY_OWNER):
raise error.FailedToAcquireName(newName, r)
return r
d.addCallback(on_result)
return d | python | def requestBusName(self, newName,
allowReplacement=False,
replaceExisting=False,
doNotQueue=True,
errbackUnlessAcquired=True):
flags = 0
if allowReplacement:
flags |= 0x1
if replaceExisting:
flags |= 0x2
if doNotQueue:
flags |= 0x4
d = self.callRemote(
'/org/freedesktop/DBus',
'RequestName',
interface='org.freedesktop.DBus',
signature='su',
body=[newName, flags],
destination='org.freedesktop.DBus',
)
def on_result(r):
if errbackUnlessAcquired and not (
r == NAME_ACQUIRED or r == NAME_ALREADY_OWNER):
raise error.FailedToAcquireName(newName, r)
return r
d.addCallback(on_result)
return d | [
"def",
"requestBusName",
"(",
"self",
",",
"newName",
",",
"allowReplacement",
"=",
"False",
",",
"replaceExisting",
"=",
"False",
",",
"doNotQueue",
"=",
"True",
",",
"errbackUnlessAcquired",
"=",
"True",
")",
":",
"flags",
"=",
"0",
"if",
"allowReplacement",
":",
"flags",
"|=",
"0x1",
"if",
"replaceExisting",
":",
"flags",
"|=",
"0x2",
"if",
"doNotQueue",
":",
"flags",
"|=",
"0x4",
"d",
"=",
"self",
".",
"callRemote",
"(",
"'/org/freedesktop/DBus'",
",",
"'RequestName'",
",",
"interface",
"=",
"'org.freedesktop.DBus'",
",",
"signature",
"=",
"'su'",
",",
"body",
"=",
"[",
"newName",
",",
"flags",
"]",
",",
"destination",
"=",
"'org.freedesktop.DBus'",
",",
")",
"def",
"on_result",
"(",
"r",
")",
":",
"if",
"errbackUnlessAcquired",
"and",
"not",
"(",
"r",
"==",
"NAME_ACQUIRED",
"or",
"r",
"==",
"NAME_ALREADY_OWNER",
")",
":",
"raise",
"error",
".",
"FailedToAcquireName",
"(",
"newName",
",",
"r",
")",
"return",
"r",
"d",
".",
"addCallback",
"(",
"on_result",
")",
"return",
"d"
] | Calls org.freedesktop.DBus.RequestName to request that the specified
bus name be associated with the connection.
@type newName: C{string}
@param newName: Bus name to acquire
@type allowReplacement: C{bool}
@param allowReplacement: If True (defaults to False) and another
application later requests this same name, the new requester will
be given the name and this connection will lose ownership.
@type replaceExisting: C{bool}
@param replaceExisting: If True (defaults to False) and another
application owns the name but specified allowReplacement at the
time of the name acquisition, this connection will assume ownership
of the bus name.
@type doNotQueue: C{bool}
@param doNotQueue: If True (defaults to True) the name request will
fail if the name is currently in use. If False, the request will
cause this connection to be queued for ownership of the requested
name
@type errbackUnlessAcquired: C{bool}
@param errbackUnlessAcquired: If True (defaults to True) an
L{twisted.python.failure.Failure} will be returned if the name is
not acquired.
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to | [
"Calls",
"org",
".",
"freedesktop",
".",
"DBus",
".",
"RequestName",
"to",
"request",
"that",
"the",
"specified",
"bus",
"name",
"be",
"associated",
"with",
"the",
"connection",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L342-L404 |
2,049 | cocagne/txdbus | txdbus/client.py | DBusClientConnection.introspectRemoteObject | def introspectRemoteObject(self, busName, objectPath,
replaceKnownInterfaces=False):
"""
Calls org.freedesktop.DBus.Introspectable.Introspect
@type busName: C{string}
@param busName: Name of the bus containing the object
@type objectPath: C{string}
@param objectPath: Object Path to introspect
@type replaceKnownInterfaces: C{bool}
@param replaceKnownInterfaces: If True (defaults to False), the content
of the introspected XML will override any pre-existing definitions
of the contained interfaces.
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to a list of L{interface.DBusInterface} instances
created from the content of the introspected XML description of the
object's interface.
"""
d = self.callRemote(
objectPath,
'Introspect',
interface='org.freedesktop.DBus.Introspectable',
destination=busName,
)
def ok(xml_str):
return introspection.getInterfacesFromXML(
xml_str,
replaceKnownInterfaces
)
def err(e):
raise error.IntrospectionFailed(
'Introspection Failed: ' + e.getErrorMessage()
)
d.addCallbacks(ok, err)
return d | python | def introspectRemoteObject(self, busName, objectPath,
replaceKnownInterfaces=False):
d = self.callRemote(
objectPath,
'Introspect',
interface='org.freedesktop.DBus.Introspectable',
destination=busName,
)
def ok(xml_str):
return introspection.getInterfacesFromXML(
xml_str,
replaceKnownInterfaces
)
def err(e):
raise error.IntrospectionFailed(
'Introspection Failed: ' + e.getErrorMessage()
)
d.addCallbacks(ok, err)
return d | [
"def",
"introspectRemoteObject",
"(",
"self",
",",
"busName",
",",
"objectPath",
",",
"replaceKnownInterfaces",
"=",
"False",
")",
":",
"d",
"=",
"self",
".",
"callRemote",
"(",
"objectPath",
",",
"'Introspect'",
",",
"interface",
"=",
"'org.freedesktop.DBus.Introspectable'",
",",
"destination",
"=",
"busName",
",",
")",
"def",
"ok",
"(",
"xml_str",
")",
":",
"return",
"introspection",
".",
"getInterfacesFromXML",
"(",
"xml_str",
",",
"replaceKnownInterfaces",
")",
"def",
"err",
"(",
"e",
")",
":",
"raise",
"error",
".",
"IntrospectionFailed",
"(",
"'Introspection Failed: '",
"+",
"e",
".",
"getErrorMessage",
"(",
")",
")",
"d",
".",
"addCallbacks",
"(",
"ok",
",",
"err",
")",
"return",
"d"
] | Calls org.freedesktop.DBus.Introspectable.Introspect
@type busName: C{string}
@param busName: Name of the bus containing the object
@type objectPath: C{string}
@param objectPath: Object Path to introspect
@type replaceKnownInterfaces: C{bool}
@param replaceKnownInterfaces: If True (defaults to False), the content
of the introspected XML will override any pre-existing definitions
of the contained interfaces.
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to a list of L{interface.DBusInterface} instances
created from the content of the introspected XML description of the
object's interface. | [
"Calls",
"org",
".",
"freedesktop",
".",
"DBus",
".",
"Introspectable",
".",
"Introspect"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L406-L447 |
2,050 | cocagne/txdbus | txdbus/client.py | DBusClientConnection._cbCvtReply | def _cbCvtReply(self, msg, returnSignature):
"""
Converts a remote method call reply message into an appropriate
callback
value.
"""
if msg is None:
return None
if returnSignature != _NO_CHECK_RETURN:
if not returnSignature:
if msg.signature:
raise error.RemoteError(
'Unexpected return value signature')
else:
if not msg.signature or msg.signature != returnSignature:
msg = 'Expected "%s". Received "%s"' % (
str(returnSignature), str(msg.signature))
raise error.RemoteError(
'Unexpected return value signature: %s' %
(msg,))
if msg.body is None or len(msg.body) == 0:
return None
# if not (
# isinstance(msg.body[0], six.string_types) and
# msg.body[0].startswith('<!D')
# ):
# print('RET SIG', msg.signature, 'BODY:', msg.body)
if len(msg.body) == 1 and not msg.signature[0] == '(':
return msg.body[0]
else:
return msg.body | python | def _cbCvtReply(self, msg, returnSignature):
if msg is None:
return None
if returnSignature != _NO_CHECK_RETURN:
if not returnSignature:
if msg.signature:
raise error.RemoteError(
'Unexpected return value signature')
else:
if not msg.signature or msg.signature != returnSignature:
msg = 'Expected "%s". Received "%s"' % (
str(returnSignature), str(msg.signature))
raise error.RemoteError(
'Unexpected return value signature: %s' %
(msg,))
if msg.body is None or len(msg.body) == 0:
return None
# if not (
# isinstance(msg.body[0], six.string_types) and
# msg.body[0].startswith('<!D')
# ):
# print('RET SIG', msg.signature, 'BODY:', msg.body)
if len(msg.body) == 1 and not msg.signature[0] == '(':
return msg.body[0]
else:
return msg.body | [
"def",
"_cbCvtReply",
"(",
"self",
",",
"msg",
",",
"returnSignature",
")",
":",
"if",
"msg",
"is",
"None",
":",
"return",
"None",
"if",
"returnSignature",
"!=",
"_NO_CHECK_RETURN",
":",
"if",
"not",
"returnSignature",
":",
"if",
"msg",
".",
"signature",
":",
"raise",
"error",
".",
"RemoteError",
"(",
"'Unexpected return value signature'",
")",
"else",
":",
"if",
"not",
"msg",
".",
"signature",
"or",
"msg",
".",
"signature",
"!=",
"returnSignature",
":",
"msg",
"=",
"'Expected \"%s\". Received \"%s\"'",
"%",
"(",
"str",
"(",
"returnSignature",
")",
",",
"str",
"(",
"msg",
".",
"signature",
")",
")",
"raise",
"error",
".",
"RemoteError",
"(",
"'Unexpected return value signature: %s'",
"%",
"(",
"msg",
",",
")",
")",
"if",
"msg",
".",
"body",
"is",
"None",
"or",
"len",
"(",
"msg",
".",
"body",
")",
"==",
"0",
":",
"return",
"None",
"# if not (",
"# isinstance(msg.body[0], six.string_types) and",
"# msg.body[0].startswith('<!D')",
"# ):",
"# print('RET SIG', msg.signature, 'BODY:', msg.body)",
"if",
"len",
"(",
"msg",
".",
"body",
")",
"==",
"1",
"and",
"not",
"msg",
".",
"signature",
"[",
"0",
"]",
"==",
"'('",
":",
"return",
"msg",
".",
"body",
"[",
"0",
"]",
"else",
":",
"return",
"msg",
".",
"body"
] | Converts a remote method call reply message into an appropriate
callback
value. | [
"Converts",
"a",
"remote",
"method",
"call",
"reply",
"message",
"into",
"an",
"appropriate",
"callback",
"value",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L449-L482 |
2,051 | cocagne/txdbus | txdbus/client.py | DBusClientConnection.callRemote | def callRemote(self, objectPath, methodName,
interface=None,
destination=None,
signature=None,
body=None,
expectReply=True,
autoStart=True,
timeout=None,
returnSignature=_NO_CHECK_RETURN):
"""
Calls a method on a remote DBus object and returns a deferred to the
result.
@type objectPath: C{string}
@param objectPath: Path of the remote object
@type methodName: C{string}
@param methodName: Name of the method to call
@type interface: None or C{string}
@param interface: If specified, this specifies the interface containing
the desired method
@type destination: None or C{string}
@param destination: If specified, this specifies the bus name
containing the remote object
@type signature: None or C{string}
@param signature: If specified, this specifies the DBus signature of
the body of the DBus MethodCall message. This string must be a
valid Signature string as defined by the DBus specification. If
arguments are supplied to the method call, this parameter must be
provided.
@type body: C{list}
@param body: A C{list} of Python objects to encode. The list content
must match the content of the signature parameter
@type expectReply: C{bool}
@param expectReply: If True (defaults to True) the returned deferred
will be called back with the eventual result of the remote call. If
False, the deferred will be immediately called back with None.
@type autoStart: C{bool}
@param autoStart: If True (defaults to True) DBus will attempt to
automatically start a service to handle the method call if a
service matching the target object is registered but not yet
started.
@type timeout: None or C{float}
@param timeout: If specified and the remote call does not return a
value before the timeout expires, the returned Deferred will be
errbacked with a L{error.TimeOut} instance.
@type returnSignature: C{string}
@param returnSignature: If specified, the return values will be
validated against the signature string. If the returned values do
not mactch, the returned Deferred witl be errbacked with a
L{error.RemoteError} instance.
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to the result. If expectReply is False, the
deferred will be immediately called back with None.
"""
try:
mcall = message.MethodCallMessage(
objectPath,
methodName,
interface=interface,
destination=destination,
signature=signature,
body=body,
expectReply=expectReply,
autoStart=autoStart,
oobFDs=self._toBeSentFDs,
)
d = self.callRemoteMessage(mcall, timeout)
d.addCallback(self._cbCvtReply, returnSignature)
return d
except Exception:
return defer.fail() | python | def callRemote(self, objectPath, methodName,
interface=None,
destination=None,
signature=None,
body=None,
expectReply=True,
autoStart=True,
timeout=None,
returnSignature=_NO_CHECK_RETURN):
try:
mcall = message.MethodCallMessage(
objectPath,
methodName,
interface=interface,
destination=destination,
signature=signature,
body=body,
expectReply=expectReply,
autoStart=autoStart,
oobFDs=self._toBeSentFDs,
)
d = self.callRemoteMessage(mcall, timeout)
d.addCallback(self._cbCvtReply, returnSignature)
return d
except Exception:
return defer.fail() | [
"def",
"callRemote",
"(",
"self",
",",
"objectPath",
",",
"methodName",
",",
"interface",
"=",
"None",
",",
"destination",
"=",
"None",
",",
"signature",
"=",
"None",
",",
"body",
"=",
"None",
",",
"expectReply",
"=",
"True",
",",
"autoStart",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"returnSignature",
"=",
"_NO_CHECK_RETURN",
")",
":",
"try",
":",
"mcall",
"=",
"message",
".",
"MethodCallMessage",
"(",
"objectPath",
",",
"methodName",
",",
"interface",
"=",
"interface",
",",
"destination",
"=",
"destination",
",",
"signature",
"=",
"signature",
",",
"body",
"=",
"body",
",",
"expectReply",
"=",
"expectReply",
",",
"autoStart",
"=",
"autoStart",
",",
"oobFDs",
"=",
"self",
".",
"_toBeSentFDs",
",",
")",
"d",
"=",
"self",
".",
"callRemoteMessage",
"(",
"mcall",
",",
"timeout",
")",
"d",
".",
"addCallback",
"(",
"self",
".",
"_cbCvtReply",
",",
"returnSignature",
")",
"return",
"d",
"except",
"Exception",
":",
"return",
"defer",
".",
"fail",
"(",
")"
] | Calls a method on a remote DBus object and returns a deferred to the
result.
@type objectPath: C{string}
@param objectPath: Path of the remote object
@type methodName: C{string}
@param methodName: Name of the method to call
@type interface: None or C{string}
@param interface: If specified, this specifies the interface containing
the desired method
@type destination: None or C{string}
@param destination: If specified, this specifies the bus name
containing the remote object
@type signature: None or C{string}
@param signature: If specified, this specifies the DBus signature of
the body of the DBus MethodCall message. This string must be a
valid Signature string as defined by the DBus specification. If
arguments are supplied to the method call, this parameter must be
provided.
@type body: C{list}
@param body: A C{list} of Python objects to encode. The list content
must match the content of the signature parameter
@type expectReply: C{bool}
@param expectReply: If True (defaults to True) the returned deferred
will be called back with the eventual result of the remote call. If
False, the deferred will be immediately called back with None.
@type autoStart: C{bool}
@param autoStart: If True (defaults to True) DBus will attempt to
automatically start a service to handle the method call if a
service matching the target object is registered but not yet
started.
@type timeout: None or C{float}
@param timeout: If specified and the remote call does not return a
value before the timeout expires, the returned Deferred will be
errbacked with a L{error.TimeOut} instance.
@type returnSignature: C{string}
@param returnSignature: If specified, the return values will be
validated against the signature string. If the returned values do
not mactch, the returned Deferred witl be errbacked with a
L{error.RemoteError} instance.
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to the result. If expectReply is False, the
deferred will be immediately called back with None. | [
"Calls",
"a",
"method",
"on",
"a",
"remote",
"DBus",
"object",
"and",
"returns",
"a",
"deferred",
"to",
"the",
"result",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L484-L568 |
2,052 | cocagne/txdbus | txdbus/client.py | DBusClientConnection._onMethodTimeout | def _onMethodTimeout(self, serial, d):
"""
Called when a remote method invocation timeout occurs
"""
del self._pendingCalls[serial]
d.errback(error.TimeOut('Method call timed out')) | python | def _onMethodTimeout(self, serial, d):
del self._pendingCalls[serial]
d.errback(error.TimeOut('Method call timed out')) | [
"def",
"_onMethodTimeout",
"(",
"self",
",",
"serial",
",",
"d",
")",
":",
"del",
"self",
".",
"_pendingCalls",
"[",
"serial",
"]",
"d",
".",
"errback",
"(",
"error",
".",
"TimeOut",
"(",
"'Method call timed out'",
")",
")"
] | Called when a remote method invocation timeout occurs | [
"Called",
"when",
"a",
"remote",
"method",
"invocation",
"timeout",
"occurs"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L570-L575 |
2,053 | cocagne/txdbus | txdbus/client.py | DBusClientConnection.methodReturnReceived | def methodReturnReceived(self, mret):
"""
Called when a method return message is received
"""
d, timeout = self._pendingCalls.get(mret.reply_serial, (None, None))
if timeout:
timeout.cancel()
if d:
del self._pendingCalls[mret.reply_serial]
d.callback(mret) | python | def methodReturnReceived(self, mret):
d, timeout = self._pendingCalls.get(mret.reply_serial, (None, None))
if timeout:
timeout.cancel()
if d:
del self._pendingCalls[mret.reply_serial]
d.callback(mret) | [
"def",
"methodReturnReceived",
"(",
"self",
",",
"mret",
")",
":",
"d",
",",
"timeout",
"=",
"self",
".",
"_pendingCalls",
".",
"get",
"(",
"mret",
".",
"reply_serial",
",",
"(",
"None",
",",
"None",
")",
")",
"if",
"timeout",
":",
"timeout",
".",
"cancel",
"(",
")",
"if",
"d",
":",
"del",
"self",
".",
"_pendingCalls",
"[",
"mret",
".",
"reply_serial",
"]",
"d",
".",
"callback",
"(",
"mret",
")"
] | Called when a method return message is received | [
"Called",
"when",
"a",
"method",
"return",
"message",
"is",
"received"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L609-L618 |
2,054 | cocagne/txdbus | txdbus/client.py | DBusClientConnection.errorReceived | def errorReceived(self, merr):
"""
Called when an error message is received
"""
d, timeout = self._pendingCalls.get(merr.reply_serial, (None, None))
if timeout:
timeout.cancel()
if d:
del self._pendingCalls[merr.reply_serial]
e = error.RemoteError(merr.error_name)
e.message = ''
e.values = []
if merr.body:
if isinstance(merr.body[0], six.string_types):
e.message = merr.body[0]
e.values = merr.body
d.errback(e) | python | def errorReceived(self, merr):
d, timeout = self._pendingCalls.get(merr.reply_serial, (None, None))
if timeout:
timeout.cancel()
if d:
del self._pendingCalls[merr.reply_serial]
e = error.RemoteError(merr.error_name)
e.message = ''
e.values = []
if merr.body:
if isinstance(merr.body[0], six.string_types):
e.message = merr.body[0]
e.values = merr.body
d.errback(e) | [
"def",
"errorReceived",
"(",
"self",
",",
"merr",
")",
":",
"d",
",",
"timeout",
"=",
"self",
".",
"_pendingCalls",
".",
"get",
"(",
"merr",
".",
"reply_serial",
",",
"(",
"None",
",",
"None",
")",
")",
"if",
"timeout",
":",
"timeout",
".",
"cancel",
"(",
")",
"if",
"d",
":",
"del",
"self",
".",
"_pendingCalls",
"[",
"merr",
".",
"reply_serial",
"]",
"e",
"=",
"error",
".",
"RemoteError",
"(",
"merr",
".",
"error_name",
")",
"e",
".",
"message",
"=",
"''",
"e",
".",
"values",
"=",
"[",
"]",
"if",
"merr",
".",
"body",
":",
"if",
"isinstance",
"(",
"merr",
".",
"body",
"[",
"0",
"]",
",",
"six",
".",
"string_types",
")",
":",
"e",
".",
"message",
"=",
"merr",
".",
"body",
"[",
"0",
"]",
"e",
".",
"values",
"=",
"merr",
".",
"body",
"d",
".",
"errback",
"(",
"e",
")"
] | Called when an error message is received | [
"Called",
"when",
"an",
"error",
"message",
"is",
"received"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/client.py#L620-L636 |
2,055 | cocagne/txdbus | txdbus/endpoints.py | getDBusEnvEndpoints | def getDBusEnvEndpoints(reactor, client=True):
"""
Creates endpoints from the DBUS_SESSION_BUS_ADDRESS environment variable
@rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint}
@returns: A list of endpoint instances
"""
env = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None)
if env is None:
raise Exception('DBus Session environment variable not set')
return getDBusEndpoints(reactor, env, client) | python | def getDBusEnvEndpoints(reactor, client=True):
env = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None)
if env is None:
raise Exception('DBus Session environment variable not set')
return getDBusEndpoints(reactor, env, client) | [
"def",
"getDBusEnvEndpoints",
"(",
"reactor",
",",
"client",
"=",
"True",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DBUS_SESSION_BUS_ADDRESS'",
",",
"None",
")",
"if",
"env",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'DBus Session environment variable not set'",
")",
"return",
"getDBusEndpoints",
"(",
"reactor",
",",
"env",
",",
"client",
")"
] | Creates endpoints from the DBUS_SESSION_BUS_ADDRESS environment variable
@rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint}
@returns: A list of endpoint instances | [
"Creates",
"endpoints",
"from",
"the",
"DBUS_SESSION_BUS_ADDRESS",
"environment",
"variable"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/endpoints.py#L16-L27 |
2,056 | cocagne/txdbus | txdbus/endpoints.py | getDBusEndpoints | def getDBusEndpoints(reactor, busAddress, client=True):
"""
Creates DBus endpoints.
@param busAddress: 'session', 'system', or a valid bus address as defined
by the DBus specification. If 'session' (the default) or 'system' is
supplied, the contents of the DBUS_SESSION_BUS_ADDRESS or
DBUS_SYSTEM_BUS_ADDRESS environment variables will be used for the bus
address, respectively. If DBUS_SYSTEM_BUS_ADDRESS is not set, the
well-known address unix:path=/var/run/dbus/system_bus_socket will be
used.
@type busAddress: C{string}
@rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint}
@returns: A list of endpoint instances
"""
if busAddress == 'session':
addrString = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None)
if addrString is None:
raise Exception('DBus Session environment variable not set')
elif busAddress == 'system':
addrString = os.environ.get(
'DBUS_SYSTEM_BUS_ADDRESS',
'unix:path=/var/run/dbus/system_bus_socket',
)
else:
addrString = busAddress
# XXX Add documentation about extra key=value parameters in address string
# such as nonce-tcp vs tcp which use same endpoint class
epl = []
for ep_addr in addrString.split(';'):
d = {}
kind = None
ep = None
for c in ep_addr.split(','):
if c.startswith('unix:'):
kind = 'unix'
c = c[5:]
elif c.startswith('tcp:'):
kind = 'tcp'
c = c[4:]
elif c.startswith('nonce-tcp:'):
kind = 'tcp'
c = c[10:]
d['nonce-tcp'] = True
elif c.startswith('launchd:'):
kind = 'launchd'
c = c[7:]
if '=' in c:
k, v = c.split('=')
d[k] = v
if kind == 'unix':
if 'path' in d:
path = d['path']
elif 'tmpdir' in d:
path = d['tmpdir'] + '/dbus-' + str(os.getpid())
elif 'abstract' in d:
path = '\0' + d['abstract']
if client:
ep = UNIXClientEndpoint(reactor, path=path)
else:
ep = UNIXServerEndpoint(reactor, address=path)
elif kind == 'tcp':
if client:
ep = TCP4ClientEndpoint(reactor, d['host'], int(d['port']))
else:
ep = TCP4ServerEndpoint(reactor, int(
d['port']), interface=d['host'])
if ep:
ep.dbus_args = d
epl.append(ep)
return epl | python | def getDBusEndpoints(reactor, busAddress, client=True):
if busAddress == 'session':
addrString = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None)
if addrString is None:
raise Exception('DBus Session environment variable not set')
elif busAddress == 'system':
addrString = os.environ.get(
'DBUS_SYSTEM_BUS_ADDRESS',
'unix:path=/var/run/dbus/system_bus_socket',
)
else:
addrString = busAddress
# XXX Add documentation about extra key=value parameters in address string
# such as nonce-tcp vs tcp which use same endpoint class
epl = []
for ep_addr in addrString.split(';'):
d = {}
kind = None
ep = None
for c in ep_addr.split(','):
if c.startswith('unix:'):
kind = 'unix'
c = c[5:]
elif c.startswith('tcp:'):
kind = 'tcp'
c = c[4:]
elif c.startswith('nonce-tcp:'):
kind = 'tcp'
c = c[10:]
d['nonce-tcp'] = True
elif c.startswith('launchd:'):
kind = 'launchd'
c = c[7:]
if '=' in c:
k, v = c.split('=')
d[k] = v
if kind == 'unix':
if 'path' in d:
path = d['path']
elif 'tmpdir' in d:
path = d['tmpdir'] + '/dbus-' + str(os.getpid())
elif 'abstract' in d:
path = '\0' + d['abstract']
if client:
ep = UNIXClientEndpoint(reactor, path=path)
else:
ep = UNIXServerEndpoint(reactor, address=path)
elif kind == 'tcp':
if client:
ep = TCP4ClientEndpoint(reactor, d['host'], int(d['port']))
else:
ep = TCP4ServerEndpoint(reactor, int(
d['port']), interface=d['host'])
if ep:
ep.dbus_args = d
epl.append(ep)
return epl | [
"def",
"getDBusEndpoints",
"(",
"reactor",
",",
"busAddress",
",",
"client",
"=",
"True",
")",
":",
"if",
"busAddress",
"==",
"'session'",
":",
"addrString",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DBUS_SESSION_BUS_ADDRESS'",
",",
"None",
")",
"if",
"addrString",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'DBus Session environment variable not set'",
")",
"elif",
"busAddress",
"==",
"'system'",
":",
"addrString",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DBUS_SYSTEM_BUS_ADDRESS'",
",",
"'unix:path=/var/run/dbus/system_bus_socket'",
",",
")",
"else",
":",
"addrString",
"=",
"busAddress",
"# XXX Add documentation about extra key=value parameters in address string",
"# such as nonce-tcp vs tcp which use same endpoint class",
"epl",
"=",
"[",
"]",
"for",
"ep_addr",
"in",
"addrString",
".",
"split",
"(",
"';'",
")",
":",
"d",
"=",
"{",
"}",
"kind",
"=",
"None",
"ep",
"=",
"None",
"for",
"c",
"in",
"ep_addr",
".",
"split",
"(",
"','",
")",
":",
"if",
"c",
".",
"startswith",
"(",
"'unix:'",
")",
":",
"kind",
"=",
"'unix'",
"c",
"=",
"c",
"[",
"5",
":",
"]",
"elif",
"c",
".",
"startswith",
"(",
"'tcp:'",
")",
":",
"kind",
"=",
"'tcp'",
"c",
"=",
"c",
"[",
"4",
":",
"]",
"elif",
"c",
".",
"startswith",
"(",
"'nonce-tcp:'",
")",
":",
"kind",
"=",
"'tcp'",
"c",
"=",
"c",
"[",
"10",
":",
"]",
"d",
"[",
"'nonce-tcp'",
"]",
"=",
"True",
"elif",
"c",
".",
"startswith",
"(",
"'launchd:'",
")",
":",
"kind",
"=",
"'launchd'",
"c",
"=",
"c",
"[",
"7",
":",
"]",
"if",
"'='",
"in",
"c",
":",
"k",
",",
"v",
"=",
"c",
".",
"split",
"(",
"'='",
")",
"d",
"[",
"k",
"]",
"=",
"v",
"if",
"kind",
"==",
"'unix'",
":",
"if",
"'path'",
"in",
"d",
":",
"path",
"=",
"d",
"[",
"'path'",
"]",
"elif",
"'tmpdir'",
"in",
"d",
":",
"path",
"=",
"d",
"[",
"'tmpdir'",
"]",
"+",
"'/dbus-'",
"+",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
"elif",
"'abstract'",
"in",
"d",
":",
"path",
"=",
"'\\0'",
"+",
"d",
"[",
"'abstract'",
"]",
"if",
"client",
":",
"ep",
"=",
"UNIXClientEndpoint",
"(",
"reactor",
",",
"path",
"=",
"path",
")",
"else",
":",
"ep",
"=",
"UNIXServerEndpoint",
"(",
"reactor",
",",
"address",
"=",
"path",
")",
"elif",
"kind",
"==",
"'tcp'",
":",
"if",
"client",
":",
"ep",
"=",
"TCP4ClientEndpoint",
"(",
"reactor",
",",
"d",
"[",
"'host'",
"]",
",",
"int",
"(",
"d",
"[",
"'port'",
"]",
")",
")",
"else",
":",
"ep",
"=",
"TCP4ServerEndpoint",
"(",
"reactor",
",",
"int",
"(",
"d",
"[",
"'port'",
"]",
")",
",",
"interface",
"=",
"d",
"[",
"'host'",
"]",
")",
"if",
"ep",
":",
"ep",
".",
"dbus_args",
"=",
"d",
"epl",
".",
"append",
"(",
"ep",
")",
"return",
"epl"
] | Creates DBus endpoints.
@param busAddress: 'session', 'system', or a valid bus address as defined
by the DBus specification. If 'session' (the default) or 'system' is
supplied, the contents of the DBUS_SESSION_BUS_ADDRESS or
DBUS_SYSTEM_BUS_ADDRESS environment variables will be used for the bus
address, respectively. If DBUS_SYSTEM_BUS_ADDRESS is not set, the
well-known address unix:path=/var/run/dbus/system_bus_socket will be
used.
@type busAddress: C{string}
@rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint}
@returns: A list of endpoint instances | [
"Creates",
"DBus",
"endpoints",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/endpoints.py#L30-L113 |
2,057 | cocagne/txdbus | doc/examples/fd_server.py | FDObject.dbus_lenFD | def dbus_lenFD(self, fd):
"""
Returns the byte count after reading till EOF.
"""
f = os.fdopen(fd, 'rb')
result = len(f.read())
f.close()
return result | python | def dbus_lenFD(self, fd):
f = os.fdopen(fd, 'rb')
result = len(f.read())
f.close()
return result | [
"def",
"dbus_lenFD",
"(",
"self",
",",
"fd",
")",
":",
"f",
"=",
"os",
".",
"fdopen",
"(",
"fd",
",",
"'rb'",
")",
"result",
"=",
"len",
"(",
"f",
".",
"read",
"(",
")",
")",
"f",
".",
"close",
"(",
")",
"return",
"result"
] | Returns the byte count after reading till EOF. | [
"Returns",
"the",
"byte",
"count",
"after",
"reading",
"till",
"EOF",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/doc/examples/fd_server.py#L46-L53 |
2,058 | cocagne/txdbus | doc/examples/fd_server.py | FDObject.dbus_readBytesFD | def dbus_readBytesFD(self, fd, byte_count):
"""
Reads byte_count bytes from fd and returns them.
"""
f = os.fdopen(fd, 'rb')
result = f.read(byte_count)
f.close()
return bytearray(result) | python | def dbus_readBytesFD(self, fd, byte_count):
f = os.fdopen(fd, 'rb')
result = f.read(byte_count)
f.close()
return bytearray(result) | [
"def",
"dbus_readBytesFD",
"(",
"self",
",",
"fd",
",",
"byte_count",
")",
":",
"f",
"=",
"os",
".",
"fdopen",
"(",
"fd",
",",
"'rb'",
")",
"result",
"=",
"f",
".",
"read",
"(",
"byte_count",
")",
"f",
".",
"close",
"(",
")",
"return",
"bytearray",
"(",
"result",
")"
] | Reads byte_count bytes from fd and returns them. | [
"Reads",
"byte_count",
"bytes",
"from",
"fd",
"and",
"returns",
"them",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/doc/examples/fd_server.py#L56-L63 |
2,059 | cocagne/txdbus | doc/examples/fd_server.py | FDObject.dbus_readBytesTwoFDs | def dbus_readBytesTwoFDs(self, fd1, fd2, byte_count):
"""
Reads byte_count from fd1 and fd2. Returns concatenation.
"""
result = bytearray()
for fd in (fd1, fd2):
f = os.fdopen(fd, 'rb')
result.extend(f.read(byte_count))
f.close()
return result | python | def dbus_readBytesTwoFDs(self, fd1, fd2, byte_count):
result = bytearray()
for fd in (fd1, fd2):
f = os.fdopen(fd, 'rb')
result.extend(f.read(byte_count))
f.close()
return result | [
"def",
"dbus_readBytesTwoFDs",
"(",
"self",
",",
"fd1",
",",
"fd2",
",",
"byte_count",
")",
":",
"result",
"=",
"bytearray",
"(",
")",
"for",
"fd",
"in",
"(",
"fd1",
",",
"fd2",
")",
":",
"f",
"=",
"os",
".",
"fdopen",
"(",
"fd",
",",
"'rb'",
")",
"result",
".",
"extend",
"(",
"f",
".",
"read",
"(",
"byte_count",
")",
")",
"f",
".",
"close",
"(",
")",
"return",
"result"
] | Reads byte_count from fd1 and fd2. Returns concatenation. | [
"Reads",
"byte_count",
"from",
"fd1",
"and",
"fd2",
".",
"Returns",
"concatenation",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/doc/examples/fd_server.py#L66-L75 |
2,060 | cocagne/txdbus | txdbus/introspection.py | generateIntrospectionXML | def generateIntrospectionXML(objectPath, exportedObjects):
"""
Generates the introspection XML for an object path or partial object path
that matches exported objects.
This allows for browsing the exported objects with tools such as d-feet.
@rtype: C{string}
"""
l = [_dtd_decl]
l.append('<node name="%s">' % (objectPath,))
obj = exportedObjects.get(objectPath, None)
if obj is not None:
for i in obj.getInterfaces():
l.append(i.introspectionXml)
l.append(_intro)
# make sure objectPath ends with '/' to only get partial matches based on
# the full path, not a part of a subpath
if not objectPath.endswith('/'):
objectPath += '/'
matches = []
for path in exportedObjects.keys():
if path.startswith(objectPath):
path = path[len(objectPath):].partition('/')[0]
if path not in matches:
matches.append(path)
if obj is None and not matches:
return None
for m in matches:
l.append('<node name="%s"/>' % m)
l.append('</node>')
return '\n'.join(l) | python | def generateIntrospectionXML(objectPath, exportedObjects):
l = [_dtd_decl]
l.append('<node name="%s">' % (objectPath,))
obj = exportedObjects.get(objectPath, None)
if obj is not None:
for i in obj.getInterfaces():
l.append(i.introspectionXml)
l.append(_intro)
# make sure objectPath ends with '/' to only get partial matches based on
# the full path, not a part of a subpath
if not objectPath.endswith('/'):
objectPath += '/'
matches = []
for path in exportedObjects.keys():
if path.startswith(objectPath):
path = path[len(objectPath):].partition('/')[0]
if path not in matches:
matches.append(path)
if obj is None and not matches:
return None
for m in matches:
l.append('<node name="%s"/>' % m)
l.append('</node>')
return '\n'.join(l) | [
"def",
"generateIntrospectionXML",
"(",
"objectPath",
",",
"exportedObjects",
")",
":",
"l",
"=",
"[",
"_dtd_decl",
"]",
"l",
".",
"append",
"(",
"'<node name=\"%s\">'",
"%",
"(",
"objectPath",
",",
")",
")",
"obj",
"=",
"exportedObjects",
".",
"get",
"(",
"objectPath",
",",
"None",
")",
"if",
"obj",
"is",
"not",
"None",
":",
"for",
"i",
"in",
"obj",
".",
"getInterfaces",
"(",
")",
":",
"l",
".",
"append",
"(",
"i",
".",
"introspectionXml",
")",
"l",
".",
"append",
"(",
"_intro",
")",
"# make sure objectPath ends with '/' to only get partial matches based on",
"# the full path, not a part of a subpath",
"if",
"not",
"objectPath",
".",
"endswith",
"(",
"'/'",
")",
":",
"objectPath",
"+=",
"'/'",
"matches",
"=",
"[",
"]",
"for",
"path",
"in",
"exportedObjects",
".",
"keys",
"(",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"objectPath",
")",
":",
"path",
"=",
"path",
"[",
"len",
"(",
"objectPath",
")",
":",
"]",
".",
"partition",
"(",
"'/'",
")",
"[",
"0",
"]",
"if",
"path",
"not",
"in",
"matches",
":",
"matches",
".",
"append",
"(",
"path",
")",
"if",
"obj",
"is",
"None",
"and",
"not",
"matches",
":",
"return",
"None",
"for",
"m",
"in",
"matches",
":",
"l",
".",
"append",
"(",
"'<node name=\"%s\"/>'",
"%",
"m",
")",
"l",
".",
"append",
"(",
"'</node>'",
")",
"return",
"'\\n'",
".",
"join",
"(",
"l",
")"
] | Generates the introspection XML for an object path or partial object path
that matches exported objects.
This allows for browsing the exported objects with tools such as d-feet.
@rtype: C{string} | [
"Generates",
"the",
"introspection",
"XML",
"for",
"an",
"object",
"path",
"or",
"partial",
"object",
"path",
"that",
"matches",
"exported",
"objects",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/introspection.py#L34-L70 |
2,061 | cocagne/txdbus | txdbus/bus.py | Bus.clientConnected | def clientConnected(self, proto):
"""
Called when a client connects to the bus. This method assigns the
new connection a unique bus name.
"""
proto.uniqueName = ':1.%d' % (self.next_id,)
self.next_id += 1
self.clients[proto.uniqueName] = proto | python | def clientConnected(self, proto):
proto.uniqueName = ':1.%d' % (self.next_id,)
self.next_id += 1
self.clients[proto.uniqueName] = proto | [
"def",
"clientConnected",
"(",
"self",
",",
"proto",
")",
":",
"proto",
".",
"uniqueName",
"=",
"':1.%d'",
"%",
"(",
"self",
".",
"next_id",
",",
")",
"self",
".",
"next_id",
"+=",
"1",
"self",
".",
"clients",
"[",
"proto",
".",
"uniqueName",
"]",
"=",
"proto"
] | Called when a client connects to the bus. This method assigns the
new connection a unique bus name. | [
"Called",
"when",
"a",
"client",
"connects",
"to",
"the",
"bus",
".",
"This",
"method",
"assigns",
"the",
"new",
"connection",
"a",
"unique",
"bus",
"name",
"."
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/bus.py#L174-L181 |
2,062 | cocagne/txdbus | txdbus/bus.py | Bus.clientDisconnected | def clientDisconnected(self, proto):
"""
Called when a client disconnects from the bus
"""
for rule_id in proto.matchRules:
self.router.delMatch(rule_id)
for busName in proto.busNames.keys():
self.dbus_ReleaseName(busName, proto.uniqueName)
if proto.uniqueName:
del self.clients[proto.uniqueName] | python | def clientDisconnected(self, proto):
for rule_id in proto.matchRules:
self.router.delMatch(rule_id)
for busName in proto.busNames.keys():
self.dbus_ReleaseName(busName, proto.uniqueName)
if proto.uniqueName:
del self.clients[proto.uniqueName] | [
"def",
"clientDisconnected",
"(",
"self",
",",
"proto",
")",
":",
"for",
"rule_id",
"in",
"proto",
".",
"matchRules",
":",
"self",
".",
"router",
".",
"delMatch",
"(",
"rule_id",
")",
"for",
"busName",
"in",
"proto",
".",
"busNames",
".",
"keys",
"(",
")",
":",
"self",
".",
"dbus_ReleaseName",
"(",
"busName",
",",
"proto",
".",
"uniqueName",
")",
"if",
"proto",
".",
"uniqueName",
":",
"del",
"self",
".",
"clients",
"[",
"proto",
".",
"uniqueName",
"]"
] | Called when a client disconnects from the bus | [
"Called",
"when",
"a",
"client",
"disconnects",
"from",
"the",
"bus"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/bus.py#L183-L194 |
2,063 | cocagne/txdbus | txdbus/bus.py | Bus.sendMessage | def sendMessage(self, msg):
"""
Sends the supplied message to the correct destination. The
@type msg: L{message.DBusMessage}
@param msg: The 'destination' field of the message must be set for
method calls and returns
"""
if msg._messageType in (1, 2):
assert msg.destination, 'Failed to specify a message destination'
if msg.destination is not None:
if msg.destination[0] == ':':
p = self.clients.get(msg.destination, None)
else:
p = self.busNames.get(msg.destination, None)
if p:
p = p[0]
# print 'SND: ', msg._messageType, ' to ', p.uniqueName, 'serial',
# msg.serial,
if p:
p.sendMessage(msg)
else:
log.msg(
'Invalid bus name in msg.destination: '
+ msg.destination
)
else:
self.router.routeMessage(msg) | python | def sendMessage(self, msg):
if msg._messageType in (1, 2):
assert msg.destination, 'Failed to specify a message destination'
if msg.destination is not None:
if msg.destination[0] == ':':
p = self.clients.get(msg.destination, None)
else:
p = self.busNames.get(msg.destination, None)
if p:
p = p[0]
# print 'SND: ', msg._messageType, ' to ', p.uniqueName, 'serial',
# msg.serial,
if p:
p.sendMessage(msg)
else:
log.msg(
'Invalid bus name in msg.destination: '
+ msg.destination
)
else:
self.router.routeMessage(msg) | [
"def",
"sendMessage",
"(",
"self",
",",
"msg",
")",
":",
"if",
"msg",
".",
"_messageType",
"in",
"(",
"1",
",",
"2",
")",
":",
"assert",
"msg",
".",
"destination",
",",
"'Failed to specify a message destination'",
"if",
"msg",
".",
"destination",
"is",
"not",
"None",
":",
"if",
"msg",
".",
"destination",
"[",
"0",
"]",
"==",
"':'",
":",
"p",
"=",
"self",
".",
"clients",
".",
"get",
"(",
"msg",
".",
"destination",
",",
"None",
")",
"else",
":",
"p",
"=",
"self",
".",
"busNames",
".",
"get",
"(",
"msg",
".",
"destination",
",",
"None",
")",
"if",
"p",
":",
"p",
"=",
"p",
"[",
"0",
"]",
"# print 'SND: ', msg._messageType, ' to ', p.uniqueName, 'serial',",
"# msg.serial,",
"if",
"p",
":",
"p",
".",
"sendMessage",
"(",
"msg",
")",
"else",
":",
"log",
".",
"msg",
"(",
"'Invalid bus name in msg.destination: '",
"+",
"msg",
".",
"destination",
")",
"else",
":",
"self",
".",
"router",
".",
"routeMessage",
"(",
"msg",
")"
] | Sends the supplied message to the correct destination. The
@type msg: L{message.DBusMessage}
@param msg: The 'destination' field of the message must be set for
method calls and returns | [
"Sends",
"the",
"supplied",
"message",
"to",
"the",
"correct",
"destination",
".",
"The"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/bus.py#L196-L225 |
2,064 | cocagne/txdbus | txdbus/bus.py | Bus.sendSignal | def sendSignal(self, p, member, signature=None, body=None,
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus'):
"""
Sends a signal to a specific connection
@type p: L{BusProtocol}
@param p: L{BusProtocol} instance to send a signal to
@type member: C{string}
@param member: Name of the signal to send
@type path: C{string}
@param path: Path of the object emitting the signal. Defaults to
'org/freedesktop/DBus'
@type interface: C{string}
@param interface: If specified, this specifies the interface containing
the desired method. Defaults to 'org.freedesktop.DBus'
@type body: None or C{list}
@param body: If supplied, this is a list of signal arguments. The
contents of the list must match the signature.
@type signature: None or C{string}
@param signature: If specified, this specifies the DBus signature of
the body of the DBus Signal message. This string must be a valid
Signature string as defined by the DBus specification. If the body
argumnent is supplied, this parameter must be provided.
"""
if not isinstance(body, (list, tuple)):
body = [body]
s = message.SignalMessage(path, member, interface,
p.uniqueName, signature, body)
p.sendMessage(s) | python | def sendSignal(self, p, member, signature=None, body=None,
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus'):
if not isinstance(body, (list, tuple)):
body = [body]
s = message.SignalMessage(path, member, interface,
p.uniqueName, signature, body)
p.sendMessage(s) | [
"def",
"sendSignal",
"(",
"self",
",",
"p",
",",
"member",
",",
"signature",
"=",
"None",
",",
"body",
"=",
"None",
",",
"path",
"=",
"'/org/freedesktop/DBus'",
",",
"interface",
"=",
"'org.freedesktop.DBus'",
")",
":",
"if",
"not",
"isinstance",
"(",
"body",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"body",
"=",
"[",
"body",
"]",
"s",
"=",
"message",
".",
"SignalMessage",
"(",
"path",
",",
"member",
",",
"interface",
",",
"p",
".",
"uniqueName",
",",
"signature",
",",
"body",
")",
"p",
".",
"sendMessage",
"(",
"s",
")"
] | Sends a signal to a specific connection
@type p: L{BusProtocol}
@param p: L{BusProtocol} instance to send a signal to
@type member: C{string}
@param member: Name of the signal to send
@type path: C{string}
@param path: Path of the object emitting the signal. Defaults to
'org/freedesktop/DBus'
@type interface: C{string}
@param interface: If specified, this specifies the interface containing
the desired method. Defaults to 'org.freedesktop.DBus'
@type body: None or C{list}
@param body: If supplied, this is a list of signal arguments. The
contents of the list must match the signature.
@type signature: None or C{string}
@param signature: If specified, this specifies the DBus signature of
the body of the DBus Signal message. This string must be a valid
Signature string as defined by the DBus specification. If the body
argumnent is supplied, this parameter must be provided. | [
"Sends",
"a",
"signal",
"to",
"a",
"specific",
"connection"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/bus.py#L277-L312 |
2,065 | cocagne/txdbus | txdbus/bus.py | Bus.broadcastSignal | def broadcastSignal(self, member, signature=None, body=None,
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus'):
"""
Sends a signal to all connections with registered interest
@type member: C{string}
@param member: Name of the signal to send
@type path: C{string}
@param path: Path of the object emitting the signal. Defaults to
'org/freedesktop/DBus'
@type interface: C{string}
@param interface: If specified, this specifies the interface containing
the desired method. Defaults to 'org.freedesktop.DBus'
@type body: None or C{list}
@param body: If supplied, this is a list of signal arguments. The
contents of the list must match the signature.
@type signature: None or C{string}
@param signature: If specified, this specifies the DBus signature of
the body of the DBus Signal message. This string must be a valid
Signature string as defined by the DBus specification. If the body
argumnent is supplied , this parameter must be provided.
"""
if not isinstance(body, (list, tuple)):
body = [body]
s = message.SignalMessage(path, member, interface,
None, signature, body)
self.router.routeMessage(s) | python | def broadcastSignal(self, member, signature=None, body=None,
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus'):
if not isinstance(body, (list, tuple)):
body = [body]
s = message.SignalMessage(path, member, interface,
None, signature, body)
self.router.routeMessage(s) | [
"def",
"broadcastSignal",
"(",
"self",
",",
"member",
",",
"signature",
"=",
"None",
",",
"body",
"=",
"None",
",",
"path",
"=",
"'/org/freedesktop/DBus'",
",",
"interface",
"=",
"'org.freedesktop.DBus'",
")",
":",
"if",
"not",
"isinstance",
"(",
"body",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"body",
"=",
"[",
"body",
"]",
"s",
"=",
"message",
".",
"SignalMessage",
"(",
"path",
",",
"member",
",",
"interface",
",",
"None",
",",
"signature",
",",
"body",
")",
"self",
".",
"router",
".",
"routeMessage",
"(",
"s",
")"
] | Sends a signal to all connections with registered interest
@type member: C{string}
@param member: Name of the signal to send
@type path: C{string}
@param path: Path of the object emitting the signal. Defaults to
'org/freedesktop/DBus'
@type interface: C{string}
@param interface: If specified, this specifies the interface containing
the desired method. Defaults to 'org.freedesktop.DBus'
@type body: None or C{list}
@param body: If supplied, this is a list of signal arguments. The
contents of the list must match the signature.
@type signature: None or C{string}
@param signature: If specified, this specifies the DBus signature of
the body of the DBus Signal message. This string must be a valid
Signature string as defined by the DBus specification. If the body
argumnent is supplied , this parameter must be provided. | [
"Sends",
"a",
"signal",
"to",
"all",
"connections",
"with",
"registered",
"interest"
] | eb424918764b7b93eecd2a4e2e5c2d0b2944407b | https://github.com/cocagne/txdbus/blob/eb424918764b7b93eecd2a4e2e5c2d0b2944407b/txdbus/bus.py#L314-L346 |
2,066 | tonyo/pyope | pyope/ope.py | OPE.encrypt | def encrypt(self, plaintext):
"""Encrypt the given plaintext value"""
if not isinstance(plaintext, int):
raise ValueError('Plaintext must be an integer value')
if not self.in_range.contains(plaintext):
raise OutOfRangeError('Plaintext is not within the input range')
return self.encrypt_recursive(plaintext, self.in_range, self.out_range) | python | def encrypt(self, plaintext):
if not isinstance(plaintext, int):
raise ValueError('Plaintext must be an integer value')
if not self.in_range.contains(plaintext):
raise OutOfRangeError('Plaintext is not within the input range')
return self.encrypt_recursive(plaintext, self.in_range, self.out_range) | [
"def",
"encrypt",
"(",
"self",
",",
"plaintext",
")",
":",
"if",
"not",
"isinstance",
"(",
"plaintext",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"'Plaintext must be an integer value'",
")",
"if",
"not",
"self",
".",
"in_range",
".",
"contains",
"(",
"plaintext",
")",
":",
"raise",
"OutOfRangeError",
"(",
"'Plaintext is not within the input range'",
")",
"return",
"self",
".",
"encrypt_recursive",
"(",
"plaintext",
",",
"self",
".",
"in_range",
",",
"self",
".",
"out_range",
")"
] | Encrypt the given plaintext value | [
"Encrypt",
"the",
"given",
"plaintext",
"value"
] | 1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e | https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/ope.py#L100-L106 |
2,067 | tonyo/pyope | pyope/ope.py | OPE.decrypt | def decrypt(self, ciphertext):
"""Decrypt the given ciphertext value"""
if not isinstance(ciphertext, int):
raise ValueError('Ciphertext must be an integer value')
if not self.out_range.contains(ciphertext):
raise OutOfRangeError('Ciphertext is not within the output range')
return self.decrypt_recursive(ciphertext, self.in_range, self.out_range) | python | def decrypt(self, ciphertext):
if not isinstance(ciphertext, int):
raise ValueError('Ciphertext must be an integer value')
if not self.out_range.contains(ciphertext):
raise OutOfRangeError('Ciphertext is not within the output range')
return self.decrypt_recursive(ciphertext, self.in_range, self.out_range) | [
"def",
"decrypt",
"(",
"self",
",",
"ciphertext",
")",
":",
"if",
"not",
"isinstance",
"(",
"ciphertext",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"'Ciphertext must be an integer value'",
")",
"if",
"not",
"self",
".",
"out_range",
".",
"contains",
"(",
"ciphertext",
")",
":",
"raise",
"OutOfRangeError",
"(",
"'Ciphertext is not within the output range'",
")",
"return",
"self",
".",
"decrypt_recursive",
"(",
"ciphertext",
",",
"self",
".",
"in_range",
",",
"self",
".",
"out_range",
")"
] | Decrypt the given ciphertext value | [
"Decrypt",
"the",
"given",
"ciphertext",
"value"
] | 1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e | https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/ope.py#L130-L136 |
2,068 | tonyo/pyope | pyope/ope.py | OPE.tape_gen | def tape_gen(self, data):
"""Return a bit string, generated from the given data string"""
# FIXME
data = str(data).encode()
# Derive a key from data
hmac_obj = hmac.HMAC(self.key, digestmod=hashlib.sha256)
hmac_obj.update(data)
assert hmac_obj.digest_size == 32
digest = hmac_obj.digest()
# Use AES in the CTR mode to generate a pseudo-random bit string
aes_algo = algorithms.AES(digest)
aes_cipher = Cipher(aes_algo, mode=CTR(b'\x00' * 16), backend=default_backend())
encryptor = aes_cipher.encryptor()
while True:
encrypted_bytes = encryptor.update(b'\x00' * 16)
# Convert the data to a list of bits
bits = util.str_to_bitstring(encrypted_bytes)
for bit in bits:
yield bit | python | def tape_gen(self, data):
# FIXME
data = str(data).encode()
# Derive a key from data
hmac_obj = hmac.HMAC(self.key, digestmod=hashlib.sha256)
hmac_obj.update(data)
assert hmac_obj.digest_size == 32
digest = hmac_obj.digest()
# Use AES in the CTR mode to generate a pseudo-random bit string
aes_algo = algorithms.AES(digest)
aes_cipher = Cipher(aes_algo, mode=CTR(b'\x00' * 16), backend=default_backend())
encryptor = aes_cipher.encryptor()
while True:
encrypted_bytes = encryptor.update(b'\x00' * 16)
# Convert the data to a list of bits
bits = util.str_to_bitstring(encrypted_bytes)
for bit in bits:
yield bit | [
"def",
"tape_gen",
"(",
"self",
",",
"data",
")",
":",
"# FIXME",
"data",
"=",
"str",
"(",
"data",
")",
".",
"encode",
"(",
")",
"# Derive a key from data",
"hmac_obj",
"=",
"hmac",
".",
"HMAC",
"(",
"self",
".",
"key",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
")",
"hmac_obj",
".",
"update",
"(",
"data",
")",
"assert",
"hmac_obj",
".",
"digest_size",
"==",
"32",
"digest",
"=",
"hmac_obj",
".",
"digest",
"(",
")",
"# Use AES in the CTR mode to generate a pseudo-random bit string",
"aes_algo",
"=",
"algorithms",
".",
"AES",
"(",
"digest",
")",
"aes_cipher",
"=",
"Cipher",
"(",
"aes_algo",
",",
"mode",
"=",
"CTR",
"(",
"b'\\x00'",
"*",
"16",
")",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"encryptor",
"=",
"aes_cipher",
".",
"encryptor",
"(",
")",
"while",
"True",
":",
"encrypted_bytes",
"=",
"encryptor",
".",
"update",
"(",
"b'\\x00'",
"*",
"16",
")",
"# Convert the data to a list of bits",
"bits",
"=",
"util",
".",
"str_to_bitstring",
"(",
"encrypted_bytes",
")",
"for",
"bit",
"in",
"bits",
":",
"yield",
"bit"
] | Return a bit string, generated from the given data string | [
"Return",
"a",
"bit",
"string",
"generated",
"from",
"the",
"given",
"data",
"string"
] | 1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e | https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/ope.py#L164-L186 |
2,069 | tonyo/pyope | pyope/ope.py | OPE.generate_key | def generate_key(block_size=32):
"""Generate random key for ope cipher.
Parameters
----------
block_size : int, optional
Length of random bytes.
Returns
-------
random_key : str
A random key for encryption.
Notes:
------
Implementation follows https://github.com/pyca/cryptography
"""
random_seq = os.urandom(block_size)
random_key = base64.b64encode(random_seq)
return random_key | python | def generate_key(block_size=32):
random_seq = os.urandom(block_size)
random_key = base64.b64encode(random_seq)
return random_key | [
"def",
"generate_key",
"(",
"block_size",
"=",
"32",
")",
":",
"random_seq",
"=",
"os",
".",
"urandom",
"(",
"block_size",
")",
"random_key",
"=",
"base64",
".",
"b64encode",
"(",
"random_seq",
")",
"return",
"random_key"
] | Generate random key for ope cipher.
Parameters
----------
block_size : int, optional
Length of random bytes.
Returns
-------
random_key : str
A random key for encryption.
Notes:
------
Implementation follows https://github.com/pyca/cryptography | [
"Generate",
"random",
"key",
"for",
"ope",
"cipher",
"."
] | 1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e | https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/ope.py#L189-L208 |
2,070 | tonyo/pyope | pyope/util.py | byte_to_bitstring | def byte_to_bitstring(byte):
"""Convert one byte to a list of bits"""
assert 0 <= byte <= 0xff
bits = [int(x) for x in list(bin(byte + 0x100)[3:])]
return bits | python | def byte_to_bitstring(byte):
assert 0 <= byte <= 0xff
bits = [int(x) for x in list(bin(byte + 0x100)[3:])]
return bits | [
"def",
"byte_to_bitstring",
"(",
"byte",
")",
":",
"assert",
"0",
"<=",
"byte",
"<=",
"0xff",
"bits",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"list",
"(",
"bin",
"(",
"byte",
"+",
"0x100",
")",
"[",
"3",
":",
"]",
")",
"]",
"return",
"bits"
] | Convert one byte to a list of bits | [
"Convert",
"one",
"byte",
"to",
"a",
"list",
"of",
"bits"
] | 1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e | https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/util.py#L3-L7 |
2,071 | tonyo/pyope | pyope/util.py | str_to_bitstring | def str_to_bitstring(data):
"""Convert a string to a list of bits"""
assert isinstance(data, bytes), "Data must be an instance of bytes"
byte_list = data_to_byte_list(data)
bit_list = [bit for data_byte in byte_list for bit in byte_to_bitstring(data_byte)]
return bit_list | python | def str_to_bitstring(data):
assert isinstance(data, bytes), "Data must be an instance of bytes"
byte_list = data_to_byte_list(data)
bit_list = [bit for data_byte in byte_list for bit in byte_to_bitstring(data_byte)]
return bit_list | [
"def",
"str_to_bitstring",
"(",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
",",
"\"Data must be an instance of bytes\"",
"byte_list",
"=",
"data_to_byte_list",
"(",
"data",
")",
"bit_list",
"=",
"[",
"bit",
"for",
"data_byte",
"in",
"byte_list",
"for",
"bit",
"in",
"byte_to_bitstring",
"(",
"data_byte",
")",
"]",
"return",
"bit_list"
] | Convert a string to a list of bits | [
"Convert",
"a",
"string",
"to",
"a",
"list",
"of",
"bits"
] | 1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e | https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/util.py#L18-L23 |
2,072 | tonyo/pyope | pyope/stat.py | sample_hgd | def sample_hgd(in_range, out_range, nsample, seed_coins):
"""Get a sample from the hypergeometric distribution, using the provided bit list as a source of randomness"""
in_size = in_range.size()
out_size = out_range.size()
assert in_size > 0 and out_size > 0
assert in_size <= out_size
assert out_range.contains(nsample)
# 1-based index of nsample in out_range
nsample_index = nsample - out_range.start + 1
if in_size == out_size:
# Input and output domains have equal size
return in_range.start + nsample_index - 1
in_sample_num = HGD.rhyper(nsample_index, in_size, out_size - in_size, seed_coins)
if in_sample_num == 0:
return in_range.start
else:
in_sample = in_range.start + in_sample_num - 1
assert in_range.contains(in_sample)
return in_sample | python | def sample_hgd(in_range, out_range, nsample, seed_coins):
in_size = in_range.size()
out_size = out_range.size()
assert in_size > 0 and out_size > 0
assert in_size <= out_size
assert out_range.contains(nsample)
# 1-based index of nsample in out_range
nsample_index = nsample - out_range.start + 1
if in_size == out_size:
# Input and output domains have equal size
return in_range.start + nsample_index - 1
in_sample_num = HGD.rhyper(nsample_index, in_size, out_size - in_size, seed_coins)
if in_sample_num == 0:
return in_range.start
else:
in_sample = in_range.start + in_sample_num - 1
assert in_range.contains(in_sample)
return in_sample | [
"def",
"sample_hgd",
"(",
"in_range",
",",
"out_range",
",",
"nsample",
",",
"seed_coins",
")",
":",
"in_size",
"=",
"in_range",
".",
"size",
"(",
")",
"out_size",
"=",
"out_range",
".",
"size",
"(",
")",
"assert",
"in_size",
">",
"0",
"and",
"out_size",
">",
"0",
"assert",
"in_size",
"<=",
"out_size",
"assert",
"out_range",
".",
"contains",
"(",
"nsample",
")",
"# 1-based index of nsample in out_range",
"nsample_index",
"=",
"nsample",
"-",
"out_range",
".",
"start",
"+",
"1",
"if",
"in_size",
"==",
"out_size",
":",
"# Input and output domains have equal size",
"return",
"in_range",
".",
"start",
"+",
"nsample_index",
"-",
"1",
"in_sample_num",
"=",
"HGD",
".",
"rhyper",
"(",
"nsample_index",
",",
"in_size",
",",
"out_size",
"-",
"in_size",
",",
"seed_coins",
")",
"if",
"in_sample_num",
"==",
"0",
":",
"return",
"in_range",
".",
"start",
"else",
":",
"in_sample",
"=",
"in_range",
".",
"start",
"+",
"in_sample_num",
"-",
"1",
"assert",
"in_range",
".",
"contains",
"(",
"in_sample",
")",
"return",
"in_sample"
] | Get a sample from the hypergeometric distribution, using the provided bit list as a source of randomness | [
"Get",
"a",
"sample",
"from",
"the",
"hypergeometric",
"distribution",
"using",
"the",
"provided",
"bit",
"list",
"as",
"a",
"source",
"of",
"randomness"
] | 1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e | https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/stat.py#L5-L25 |
2,073 | tonyo/pyope | pyope/stat.py | sample_uniform | def sample_uniform(in_range, seed_coins):
"""Uniformly select a number from the range using the bit list as a source of randomness"""
if isinstance(seed_coins, list):
seed_coins.append(None)
seed_coins = iter(seed_coins)
cur_range = in_range.copy()
assert cur_range.size() != 0
while cur_range.size() > 1:
mid = (cur_range.start + cur_range.end) // 2
bit = next(seed_coins)
if bit == 0:
cur_range.end = mid
elif bit == 1:
cur_range.start = mid + 1
elif bit is None:
raise NotEnoughCoinsError()
else:
raise InvalidCoinError()
assert cur_range.size() == 1
return cur_range.start | python | def sample_uniform(in_range, seed_coins):
if isinstance(seed_coins, list):
seed_coins.append(None)
seed_coins = iter(seed_coins)
cur_range = in_range.copy()
assert cur_range.size() != 0
while cur_range.size() > 1:
mid = (cur_range.start + cur_range.end) // 2
bit = next(seed_coins)
if bit == 0:
cur_range.end = mid
elif bit == 1:
cur_range.start = mid + 1
elif bit is None:
raise NotEnoughCoinsError()
else:
raise InvalidCoinError()
assert cur_range.size() == 1
return cur_range.start | [
"def",
"sample_uniform",
"(",
"in_range",
",",
"seed_coins",
")",
":",
"if",
"isinstance",
"(",
"seed_coins",
",",
"list",
")",
":",
"seed_coins",
".",
"append",
"(",
"None",
")",
"seed_coins",
"=",
"iter",
"(",
"seed_coins",
")",
"cur_range",
"=",
"in_range",
".",
"copy",
"(",
")",
"assert",
"cur_range",
".",
"size",
"(",
")",
"!=",
"0",
"while",
"cur_range",
".",
"size",
"(",
")",
">",
"1",
":",
"mid",
"=",
"(",
"cur_range",
".",
"start",
"+",
"cur_range",
".",
"end",
")",
"//",
"2",
"bit",
"=",
"next",
"(",
"seed_coins",
")",
"if",
"bit",
"==",
"0",
":",
"cur_range",
".",
"end",
"=",
"mid",
"elif",
"bit",
"==",
"1",
":",
"cur_range",
".",
"start",
"=",
"mid",
"+",
"1",
"elif",
"bit",
"is",
"None",
":",
"raise",
"NotEnoughCoinsError",
"(",
")",
"else",
":",
"raise",
"InvalidCoinError",
"(",
")",
"assert",
"cur_range",
".",
"size",
"(",
")",
"==",
"1",
"return",
"cur_range",
".",
"start"
] | Uniformly select a number from the range using the bit list as a source of randomness | [
"Uniformly",
"select",
"a",
"number",
"from",
"the",
"range",
"using",
"the",
"bit",
"list",
"as",
"a",
"source",
"of",
"randomness"
] | 1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e | https://github.com/tonyo/pyope/blob/1e9f9f15cd4b989d1bf3c607270bf6a8ae808b1e/pyope/stat.py#L28-L47 |
2,074 | dustin/twitty-twister | twittytwister/twitter.py | __downloadPage | def __downloadPage(factory, *args, **kwargs):
"""Start a HTTP download, returning a HTTPDownloader object"""
# The Twisted API is weird:
# 1) web.client.downloadPage() doesn't give us the HTTP headers
# 2) there is no method that simply accepts a URL and gives you back
# a HTTPDownloader object
#TODO: convert getPage() usage to something similar, too
downloader = factory(*args, **kwargs)
if downloader.scheme == 'https':
from twisted.internet import ssl
contextFactory = ssl.ClientContextFactory()
reactor.connectSSL(downloader.host, downloader.port,
downloader, contextFactory)
else:
reactor.connectTCP(downloader.host, downloader.port,
downloader)
return downloader | python | def __downloadPage(factory, *args, **kwargs):
# The Twisted API is weird:
# 1) web.client.downloadPage() doesn't give us the HTTP headers
# 2) there is no method that simply accepts a URL and gives you back
# a HTTPDownloader object
#TODO: convert getPage() usage to something similar, too
downloader = factory(*args, **kwargs)
if downloader.scheme == 'https':
from twisted.internet import ssl
contextFactory = ssl.ClientContextFactory()
reactor.connectSSL(downloader.host, downloader.port,
downloader, contextFactory)
else:
reactor.connectTCP(downloader.host, downloader.port,
downloader)
return downloader | [
"def",
"__downloadPage",
"(",
"factory",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# The Twisted API is weird:",
"# 1) web.client.downloadPage() doesn't give us the HTTP headers",
"# 2) there is no method that simply accepts a URL and gives you back",
"# a HTTPDownloader object",
"#TODO: convert getPage() usage to something similar, too",
"downloader",
"=",
"factory",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"downloader",
".",
"scheme",
"==",
"'https'",
":",
"from",
"twisted",
".",
"internet",
"import",
"ssl",
"contextFactory",
"=",
"ssl",
".",
"ClientContextFactory",
"(",
")",
"reactor",
".",
"connectSSL",
"(",
"downloader",
".",
"host",
",",
"downloader",
".",
"port",
",",
"downloader",
",",
"contextFactory",
")",
"else",
":",
"reactor",
".",
"connectTCP",
"(",
"downloader",
".",
"host",
",",
"downloader",
".",
"port",
",",
"downloader",
")",
"return",
"downloader"
] | Start a HTTP download, returning a HTTPDownloader object | [
"Start",
"a",
"HTTP",
"download",
"returning",
"a",
"HTTPDownloader",
"object"
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L76-L95 |
2,075 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.__clientDefer | def __clientDefer(self, c):
"""Return a deferred for a HTTP client, after handling incoming headers"""
def handle_headers(r):
self.gotHeaders(c.response_headers)
return r
return c.deferred.addBoth(handle_headers) | python | def __clientDefer(self, c):
def handle_headers(r):
self.gotHeaders(c.response_headers)
return r
return c.deferred.addBoth(handle_headers) | [
"def",
"__clientDefer",
"(",
"self",
",",
"c",
")",
":",
"def",
"handle_headers",
"(",
"r",
")",
":",
"self",
".",
"gotHeaders",
"(",
"c",
".",
"response_headers",
")",
"return",
"r",
"return",
"c",
".",
"deferred",
".",
"addBoth",
"(",
"handle_headers",
")"
] | Return a deferred for a HTTP client, after handling incoming headers | [
"Return",
"a",
"deferred",
"for",
"a",
"HTTP",
"client",
"after",
"handling",
"incoming",
"headers"
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L231-L237 |
2,076 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.verify_credentials | def verify_credentials(self, delegate=None):
"Verify a user's credentials."
parser = txml.Users(delegate)
return self.__downloadPage('/account/verify_credentials.xml', parser) | python | def verify_credentials(self, delegate=None):
"Verify a user's credentials."
parser = txml.Users(delegate)
return self.__downloadPage('/account/verify_credentials.xml', parser) | [
"def",
"verify_credentials",
"(",
"self",
",",
"delegate",
"=",
"None",
")",
":",
"parser",
"=",
"txml",
".",
"Users",
"(",
"delegate",
")",
"return",
"self",
".",
"__downloadPage",
"(",
"'/account/verify_credentials.xml'",
",",
"parser",
")"
] | Verify a user's credentials. | [
"Verify",
"a",
"user",
"s",
"credentials",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L304-L307 |
2,077 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.update | def update(self, status, source=None, params={}):
"Update your status. Returns the ID of the new post."
params = params.copy()
params['status'] = status
if source:
params['source'] = source
return self.__parsed_post(self.__post('/statuses/update.xml', params),
txml.parseUpdateResponse) | python | def update(self, status, source=None, params={}):
"Update your status. Returns the ID of the new post."
params = params.copy()
params['status'] = status
if source:
params['source'] = source
return self.__parsed_post(self.__post('/statuses/update.xml', params),
txml.parseUpdateResponse) | [
"def",
"update",
"(",
"self",
",",
"status",
",",
"source",
"=",
"None",
",",
"params",
"=",
"{",
"}",
")",
":",
"params",
"=",
"params",
".",
"copy",
"(",
")",
"params",
"[",
"'status'",
"]",
"=",
"status",
"if",
"source",
":",
"params",
"[",
"'source'",
"]",
"=",
"source",
"return",
"self",
".",
"__parsed_post",
"(",
"self",
".",
"__post",
"(",
"'/statuses/update.xml'",
",",
"params",
")",
",",
"txml",
".",
"parseUpdateResponse",
")"
] | Update your status. Returns the ID of the new post. | [
"Update",
"your",
"status",
".",
"Returns",
"the",
"ID",
"of",
"the",
"new",
"post",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L315-L322 |
2,078 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.retweet | def retweet(self, id, delegate):
"""Retweet a post
Returns the retweet status info back to the given delegate
"""
parser = txml.Statuses(delegate)
return self.__postPage('/statuses/retweet/%s.xml' % (id), parser) | python | def retweet(self, id, delegate):
parser = txml.Statuses(delegate)
return self.__postPage('/statuses/retweet/%s.xml' % (id), parser) | [
"def",
"retweet",
"(",
"self",
",",
"id",
",",
"delegate",
")",
":",
"parser",
"=",
"txml",
".",
"Statuses",
"(",
"delegate",
")",
"return",
"self",
".",
"__postPage",
"(",
"'/statuses/retweet/%s.xml'",
"%",
"(",
"id",
")",
",",
"parser",
")"
] | Retweet a post
Returns the retweet status info back to the given delegate | [
"Retweet",
"a",
"post"
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L324-L330 |
2,079 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.user_timeline | def user_timeline(self, delegate, user=None, params={}, extra_args=None):
"""Get the most recent updates for a user.
If no user is specified, the statuses for the authenticating user are
returned.
See search for example of how results are returned."""
if user:
params['id'] = user
return self.__get('/statuses/user_timeline.xml', delegate, params,
txml.Statuses, extra_args=extra_args) | python | def user_timeline(self, delegate, user=None, params={}, extra_args=None):
if user:
params['id'] = user
return self.__get('/statuses/user_timeline.xml', delegate, params,
txml.Statuses, extra_args=extra_args) | [
"def",
"user_timeline",
"(",
"self",
",",
"delegate",
",",
"user",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"extra_args",
"=",
"None",
")",
":",
"if",
"user",
":",
"params",
"[",
"'id'",
"]",
"=",
"user",
"return",
"self",
".",
"__get",
"(",
"'/statuses/user_timeline.xml'",
",",
"delegate",
",",
"params",
",",
"txml",
".",
"Statuses",
",",
"extra_args",
"=",
"extra_args",
")"
] | Get the most recent updates for a user.
If no user is specified, the statuses for the authenticating user are
returned.
See search for example of how results are returned. | [
"Get",
"the",
"most",
"recent",
"updates",
"for",
"a",
"user",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L350-L360 |
2,080 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.public_timeline | def public_timeline(self, delegate, params={}, extra_args=None):
"Get the most recent public timeline."
return self.__get('/statuses/public_timeline.atom', delegate, params,
extra_args=extra_args) | python | def public_timeline(self, delegate, params={}, extra_args=None):
"Get the most recent public timeline."
return self.__get('/statuses/public_timeline.atom', delegate, params,
extra_args=extra_args) | [
"def",
"public_timeline",
"(",
"self",
",",
"delegate",
",",
"params",
"=",
"{",
"}",
",",
"extra_args",
"=",
"None",
")",
":",
"return",
"self",
".",
"__get",
"(",
"'/statuses/public_timeline.atom'",
",",
"delegate",
",",
"params",
",",
"extra_args",
"=",
"extra_args",
")"
] | Get the most recent public timeline. | [
"Get",
"the",
"most",
"recent",
"public",
"timeline",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L367-L371 |
2,081 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.direct_messages | def direct_messages(self, delegate, params={}, extra_args=None):
"""Get direct messages for the authenticating user.
Search results are returned one message at a time a DirectMessage
objects"""
return self.__get('/direct_messages.xml', delegate, params,
txml.Direct, extra_args=extra_args) | python | def direct_messages(self, delegate, params={}, extra_args=None):
return self.__get('/direct_messages.xml', delegate, params,
txml.Direct, extra_args=extra_args) | [
"def",
"direct_messages",
"(",
"self",
",",
"delegate",
",",
"params",
"=",
"{",
"}",
",",
"extra_args",
"=",
"None",
")",
":",
"return",
"self",
".",
"__get",
"(",
"'/direct_messages.xml'",
",",
"delegate",
",",
"params",
",",
"txml",
".",
"Direct",
",",
"extra_args",
"=",
"extra_args",
")"
] | Get direct messages for the authenticating user.
Search results are returned one message at a time a DirectMessage
objects | [
"Get",
"direct",
"messages",
"for",
"the",
"authenticating",
"user",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L373-L379 |
2,082 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.send_direct_message | def send_direct_message(self, text, user=None, delegate=None, screen_name=None, user_id=None, params={}):
"""Send a direct message
"""
params = params.copy()
if user is not None:
params['user'] = user
if user_id is not None:
params['user_id'] = user_id
if screen_name is not None:
params['screen_name'] = screen_name
params['text'] = text
parser = txml.Direct(delegate)
return self.__postPage('/direct_messages/new.xml', parser, params) | python | def send_direct_message(self, text, user=None, delegate=None, screen_name=None, user_id=None, params={}):
params = params.copy()
if user is not None:
params['user'] = user
if user_id is not None:
params['user_id'] = user_id
if screen_name is not None:
params['screen_name'] = screen_name
params['text'] = text
parser = txml.Direct(delegate)
return self.__postPage('/direct_messages/new.xml', parser, params) | [
"def",
"send_direct_message",
"(",
"self",
",",
"text",
",",
"user",
"=",
"None",
",",
"delegate",
"=",
"None",
",",
"screen_name",
"=",
"None",
",",
"user_id",
"=",
"None",
",",
"params",
"=",
"{",
"}",
")",
":",
"params",
"=",
"params",
".",
"copy",
"(",
")",
"if",
"user",
"is",
"not",
"None",
":",
"params",
"[",
"'user'",
"]",
"=",
"user",
"if",
"user_id",
"is",
"not",
"None",
":",
"params",
"[",
"'user_id'",
"]",
"=",
"user_id",
"if",
"screen_name",
"is",
"not",
"None",
":",
"params",
"[",
"'screen_name'",
"]",
"=",
"screen_name",
"params",
"[",
"'text'",
"]",
"=",
"text",
"parser",
"=",
"txml",
".",
"Direct",
"(",
"delegate",
")",
"return",
"self",
".",
"__postPage",
"(",
"'/direct_messages/new.xml'",
",",
"parser",
",",
"params",
")"
] | Send a direct message | [
"Send",
"a",
"direct",
"message"
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L381-L393 |
2,083 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.replies | def replies(self, delegate, params={}, extra_args=None):
"""Get the most recent replies for the authenticating user.
See search for example of how results are returned."""
return self.__get('/statuses/replies.atom', delegate, params,
extra_args=extra_args) | python | def replies(self, delegate, params={}, extra_args=None):
return self.__get('/statuses/replies.atom', delegate, params,
extra_args=extra_args) | [
"def",
"replies",
"(",
"self",
",",
"delegate",
",",
"params",
"=",
"{",
"}",
",",
"extra_args",
"=",
"None",
")",
":",
"return",
"self",
".",
"__get",
"(",
"'/statuses/replies.atom'",
",",
"delegate",
",",
"params",
",",
"extra_args",
"=",
"extra_args",
")"
] | Get the most recent replies for the authenticating user.
See search for example of how results are returned. | [
"Get",
"the",
"most",
"recent",
"replies",
"for",
"the",
"authenticating",
"user",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L395-L400 |
2,084 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.follow_user | def follow_user(self, user, delegate):
"""Follow the given user.
Returns the user info back to the given delegate
"""
parser = txml.Users(delegate)
return self.__postPage('/friendships/create/%s.xml' % (user), parser) | python | def follow_user(self, user, delegate):
parser = txml.Users(delegate)
return self.__postPage('/friendships/create/%s.xml' % (user), parser) | [
"def",
"follow_user",
"(",
"self",
",",
"user",
",",
"delegate",
")",
":",
"parser",
"=",
"txml",
".",
"Users",
"(",
"delegate",
")",
"return",
"self",
".",
"__postPage",
"(",
"'/friendships/create/%s.xml'",
"%",
"(",
"user",
")",
",",
"parser",
")"
] | Follow the given user.
Returns the user info back to the given delegate | [
"Follow",
"the",
"given",
"user",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L414-L420 |
2,085 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.unfollow_user | def unfollow_user(self, user, delegate):
"""Unfollow the given user.
Returns the user info back to the given delegate
"""
parser = txml.Users(delegate)
return self.__postPage('/friendships/destroy/%s.xml' % (user), parser) | python | def unfollow_user(self, user, delegate):
parser = txml.Users(delegate)
return self.__postPage('/friendships/destroy/%s.xml' % (user), parser) | [
"def",
"unfollow_user",
"(",
"self",
",",
"user",
",",
"delegate",
")",
":",
"parser",
"=",
"txml",
".",
"Users",
"(",
"delegate",
")",
"return",
"self",
".",
"__postPage",
"(",
"'/friendships/destroy/%s.xml'",
"%",
"(",
"user",
")",
",",
"parser",
")"
] | Unfollow the given user.
Returns the user info back to the given delegate | [
"Unfollow",
"the",
"given",
"user",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L422-L428 |
2,086 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.list_friends | def list_friends(self, delegate, user=None, params={}, extra_args=None, page_delegate=None):
"""Get the list of friends for a user.
Calls the delegate with each user object found."""
if user:
url = '/statuses/friends/' + user + '.xml'
else:
url = '/statuses/friends.xml'
return self.__get_maybe_paging(url, delegate, params, txml.PagedUserList, extra_args, page_delegate) | python | def list_friends(self, delegate, user=None, params={}, extra_args=None, page_delegate=None):
if user:
url = '/statuses/friends/' + user + '.xml'
else:
url = '/statuses/friends.xml'
return self.__get_maybe_paging(url, delegate, params, txml.PagedUserList, extra_args, page_delegate) | [
"def",
"list_friends",
"(",
"self",
",",
"delegate",
",",
"user",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"extra_args",
"=",
"None",
",",
"page_delegate",
"=",
"None",
")",
":",
"if",
"user",
":",
"url",
"=",
"'/statuses/friends/'",
"+",
"user",
"+",
"'.xml'",
"else",
":",
"url",
"=",
"'/statuses/friends.xml'",
"return",
"self",
".",
"__get_maybe_paging",
"(",
"url",
",",
"delegate",
",",
"params",
",",
"txml",
".",
"PagedUserList",
",",
"extra_args",
",",
"page_delegate",
")"
] | Get the list of friends for a user.
Calls the delegate with each user object found. | [
"Get",
"the",
"list",
"of",
"friends",
"for",
"a",
"user",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L457-L466 |
2,087 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.show_user | def show_user(self, user):
"""Get the info for a specific user.
Returns a delegate that will receive the user in a callback."""
url = '/users/show/%s.xml' % (user)
d = defer.Deferred()
self.__downloadPage(url, txml.Users(lambda u: d.callback(u))) \
.addErrback(lambda e: d.errback(e))
return d | python | def show_user(self, user):
url = '/users/show/%s.xml' % (user)
d = defer.Deferred()
self.__downloadPage(url, txml.Users(lambda u: d.callback(u))) \
.addErrback(lambda e: d.errback(e))
return d | [
"def",
"show_user",
"(",
"self",
",",
"user",
")",
":",
"url",
"=",
"'/users/show/%s.xml'",
"%",
"(",
"user",
")",
"d",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"__downloadPage",
"(",
"url",
",",
"txml",
".",
"Users",
"(",
"lambda",
"u",
":",
"d",
".",
"callback",
"(",
"u",
")",
")",
")",
".",
"addErrback",
"(",
"lambda",
"e",
":",
"d",
".",
"errback",
"(",
"e",
")",
")",
"return",
"d"
] | Get the info for a specific user.
Returns a delegate that will receive the user in a callback. | [
"Get",
"the",
"info",
"for",
"a",
"specific",
"user",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L488-L499 |
2,088 | dustin/twitty-twister | twittytwister/twitter.py | Twitter.search | def search(self, query, delegate, args=None, extra_args=None):
"""Perform a search query.
Results are given one at a time to the delegate. An example delegate
may look like this:
def exampleDelegate(entry):
print entry.title"""
if args is None:
args = {}
args['q'] = query
return self.__doDownloadPage(self.search_url + '?' + self._urlencode(args),
txml.Feed(delegate, extra_args), agent=self.agent) | python | def search(self, query, delegate, args=None, extra_args=None):
if args is None:
args = {}
args['q'] = query
return self.__doDownloadPage(self.search_url + '?' + self._urlencode(args),
txml.Feed(delegate, extra_args), agent=self.agent) | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"delegate",
",",
"args",
"=",
"None",
",",
"extra_args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"{",
"}",
"args",
"[",
"'q'",
"]",
"=",
"query",
"return",
"self",
".",
"__doDownloadPage",
"(",
"self",
".",
"search_url",
"+",
"'?'",
"+",
"self",
".",
"_urlencode",
"(",
"args",
")",
",",
"txml",
".",
"Feed",
"(",
"delegate",
",",
"extra_args",
")",
",",
"agent",
"=",
"self",
".",
"agent",
")"
] | Perform a search query.
Results are given one at a time to the delegate. An example delegate
may look like this:
def exampleDelegate(entry):
print entry.title | [
"Perform",
"a",
"search",
"query",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L501-L513 |
2,089 | dustin/twitty-twister | twittytwister/twitter.py | TwitterMonitor.startService | def startService(self):
"""
Start the service.
This causes a transition to the C{'idle'} state, and then calls
L{connect} to attempt an initial conection.
"""
service.Service.startService(self)
self._toState('idle')
try:
self.connect()
except NoConsumerError:
pass | python | def startService(self):
service.Service.startService(self)
self._toState('idle')
try:
self.connect()
except NoConsumerError:
pass | [
"def",
"startService",
"(",
"self",
")",
":",
"service",
".",
"Service",
".",
"startService",
"(",
"self",
")",
"self",
".",
"_toState",
"(",
"'idle'",
")",
"try",
":",
"self",
".",
"connect",
"(",
")",
"except",
"NoConsumerError",
":",
"pass"
] | Start the service.
This causes a transition to the C{'idle'} state, and then calls
L{connect} to attempt an initial conection. | [
"Start",
"the",
"service",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L880-L893 |
2,090 | dustin/twitty-twister | twittytwister/twitter.py | TwitterMonitor.connect | def connect(self, forceReconnect=False):
"""
Check current conditions and initiate connection if possible.
This is called to check preconditions for starting a new connection,
and initating the connection itself.
If the service is not running, this will do nothing.
@param forceReconnect: Drop an existing connection to reconnnect.
@type forceReconnect: C{False}
@raises L{ConnectError}: When a connection (attempt) is already in
progress, unless C{forceReconnect} is set.
@raises L{NoConsumerError}: When there is no consumer for incoming
tweets. No further connection attempts will be made, unless L{connect}
is called again.
"""
if self._state == 'stopped':
raise Error("This service is not running. Not connecting.")
if self._state == 'connected':
if forceReconnect:
self._toState('disconnecting')
return True
else:
raise ConnectError("Already connected.")
elif self._state == 'aborting':
raise ConnectError("Aborting connection in progress.")
elif self._state == 'disconnecting':
raise ConnectError("Disconnect in progress.")
elif self._state == 'connecting':
if forceReconnect:
self._toState('aborting')
return True
else:
raise ConnectError("Connect in progress.")
if self.delegate is None:
if self._state != 'idle':
self._toState('idle')
raise NoConsumerError()
if self._state == 'waiting':
if self._reconnectDelayedCall.called:
self._reconnectDelayedCall = None
pass
else:
self._reconnectDelayedCall.reset(0)
return True
self._toState('connecting')
return True | python | def connect(self, forceReconnect=False):
if self._state == 'stopped':
raise Error("This service is not running. Not connecting.")
if self._state == 'connected':
if forceReconnect:
self._toState('disconnecting')
return True
else:
raise ConnectError("Already connected.")
elif self._state == 'aborting':
raise ConnectError("Aborting connection in progress.")
elif self._state == 'disconnecting':
raise ConnectError("Disconnect in progress.")
elif self._state == 'connecting':
if forceReconnect:
self._toState('aborting')
return True
else:
raise ConnectError("Connect in progress.")
if self.delegate is None:
if self._state != 'idle':
self._toState('idle')
raise NoConsumerError()
if self._state == 'waiting':
if self._reconnectDelayedCall.called:
self._reconnectDelayedCall = None
pass
else:
self._reconnectDelayedCall.reset(0)
return True
self._toState('connecting')
return True | [
"def",
"connect",
"(",
"self",
",",
"forceReconnect",
"=",
"False",
")",
":",
"if",
"self",
".",
"_state",
"==",
"'stopped'",
":",
"raise",
"Error",
"(",
"\"This service is not running. Not connecting.\"",
")",
"if",
"self",
".",
"_state",
"==",
"'connected'",
":",
"if",
"forceReconnect",
":",
"self",
".",
"_toState",
"(",
"'disconnecting'",
")",
"return",
"True",
"else",
":",
"raise",
"ConnectError",
"(",
"\"Already connected.\"",
")",
"elif",
"self",
".",
"_state",
"==",
"'aborting'",
":",
"raise",
"ConnectError",
"(",
"\"Aborting connection in progress.\"",
")",
"elif",
"self",
".",
"_state",
"==",
"'disconnecting'",
":",
"raise",
"ConnectError",
"(",
"\"Disconnect in progress.\"",
")",
"elif",
"self",
".",
"_state",
"==",
"'connecting'",
":",
"if",
"forceReconnect",
":",
"self",
".",
"_toState",
"(",
"'aborting'",
")",
"return",
"True",
"else",
":",
"raise",
"ConnectError",
"(",
"\"Connect in progress.\"",
")",
"if",
"self",
".",
"delegate",
"is",
"None",
":",
"if",
"self",
".",
"_state",
"!=",
"'idle'",
":",
"self",
".",
"_toState",
"(",
"'idle'",
")",
"raise",
"NoConsumerError",
"(",
")",
"if",
"self",
".",
"_state",
"==",
"'waiting'",
":",
"if",
"self",
".",
"_reconnectDelayedCall",
".",
"called",
":",
"self",
".",
"_reconnectDelayedCall",
"=",
"None",
"pass",
"else",
":",
"self",
".",
"_reconnectDelayedCall",
".",
"reset",
"(",
"0",
")",
"return",
"True",
"self",
".",
"_toState",
"(",
"'connecting'",
")",
"return",
"True"
] | Check current conditions and initiate connection if possible.
This is called to check preconditions for starting a new connection,
and initating the connection itself.
If the service is not running, this will do nothing.
@param forceReconnect: Drop an existing connection to reconnnect.
@type forceReconnect: C{False}
@raises L{ConnectError}: When a connection (attempt) is already in
progress, unless C{forceReconnect} is set.
@raises L{NoConsumerError}: When there is no consumer for incoming
tweets. No further connection attempts will be made, unless L{connect}
is called again. | [
"Check",
"current",
"conditions",
"and",
"initiate",
"connection",
"if",
"possible",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L906-L958 |
2,091 | dustin/twitty-twister | twittytwister/twitter.py | TwitterMonitor.makeConnection | def makeConnection(self, protocol):
"""
Called when the connection has been established.
This method is called when an HTTP 200 response has been received,
with the protocol that decodes the individual Twitter stream elements.
That protocol will call the consumer for all Twitter entries received.
The protocol, stored in L{protocol}, has a deferred that fires when
the connection is closed, causing a transition to the
C{'disconnected'} state.
@param protocol: The Twitter stream protocol.
@type protocol: L{TwitterStream}
"""
self._errorState = None
def cb(result):
self.protocol = None
if self._state == 'stopped':
# Don't transition to any other state. We are stopped.
pass
else:
if isinstance(result, failure.Failure):
reason = result
else:
reason = None
self._toState('disconnected', reason)
self.protocol = protocol
d = protocol.deferred
d.addBoth(cb) | python | def makeConnection(self, protocol):
self._errorState = None
def cb(result):
self.protocol = None
if self._state == 'stopped':
# Don't transition to any other state. We are stopped.
pass
else:
if isinstance(result, failure.Failure):
reason = result
else:
reason = None
self._toState('disconnected', reason)
self.protocol = protocol
d = protocol.deferred
d.addBoth(cb) | [
"def",
"makeConnection",
"(",
"self",
",",
"protocol",
")",
":",
"self",
".",
"_errorState",
"=",
"None",
"def",
"cb",
"(",
"result",
")",
":",
"self",
".",
"protocol",
"=",
"None",
"if",
"self",
".",
"_state",
"==",
"'stopped'",
":",
"# Don't transition to any other state. We are stopped.",
"pass",
"else",
":",
"if",
"isinstance",
"(",
"result",
",",
"failure",
".",
"Failure",
")",
":",
"reason",
"=",
"result",
"else",
":",
"reason",
"=",
"None",
"self",
".",
"_toState",
"(",
"'disconnected'",
",",
"reason",
")",
"self",
".",
"protocol",
"=",
"protocol",
"d",
"=",
"protocol",
".",
"deferred",
"d",
".",
"addBoth",
"(",
"cb",
")"
] | Called when the connection has been established.
This method is called when an HTTP 200 response has been received,
with the protocol that decodes the individual Twitter stream elements.
That protocol will call the consumer for all Twitter entries received.
The protocol, stored in L{protocol}, has a deferred that fires when
the connection is closed, causing a transition to the
C{'disconnected'} state.
@param protocol: The Twitter stream protocol.
@type protocol: L{TwitterStream} | [
"Called",
"when",
"the",
"connection",
"has",
"been",
"established",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L969-L1000 |
2,092 | dustin/twitty-twister | twittytwister/twitter.py | TwitterMonitor._reconnect | def _reconnect(self, errorState):
"""
Attempt to reconnect.
If the current back-off delay is 0, L{connect} is called. Otherwise,
it will cause a transition to the C{'waiting'} state, ultimately
causing a call to L{connect} when the delay expires.
"""
def connect():
if self.noisy:
log.msg("Reconnecting now.")
self.connect()
backOff = self.backOffs[errorState]
if self._errorState != errorState or self._delay is None:
self._errorState = errorState
self._delay = backOff['initial']
else:
self._delay = min(backOff['max'], self._delay * backOff['factor'])
if self._delay == 0:
connect()
else:
self._reconnectDelayedCall = self.reactor.callLater(self._delay,
connect)
self._toState('waiting') | python | def _reconnect(self, errorState):
def connect():
if self.noisy:
log.msg("Reconnecting now.")
self.connect()
backOff = self.backOffs[errorState]
if self._errorState != errorState or self._delay is None:
self._errorState = errorState
self._delay = backOff['initial']
else:
self._delay = min(backOff['max'], self._delay * backOff['factor'])
if self._delay == 0:
connect()
else:
self._reconnectDelayedCall = self.reactor.callLater(self._delay,
connect)
self._toState('waiting') | [
"def",
"_reconnect",
"(",
"self",
",",
"errorState",
")",
":",
"def",
"connect",
"(",
")",
":",
"if",
"self",
".",
"noisy",
":",
"log",
".",
"msg",
"(",
"\"Reconnecting now.\"",
")",
"self",
".",
"connect",
"(",
")",
"backOff",
"=",
"self",
".",
"backOffs",
"[",
"errorState",
"]",
"if",
"self",
".",
"_errorState",
"!=",
"errorState",
"or",
"self",
".",
"_delay",
"is",
"None",
":",
"self",
".",
"_errorState",
"=",
"errorState",
"self",
".",
"_delay",
"=",
"backOff",
"[",
"'initial'",
"]",
"else",
":",
"self",
".",
"_delay",
"=",
"min",
"(",
"backOff",
"[",
"'max'",
"]",
",",
"self",
".",
"_delay",
"*",
"backOff",
"[",
"'factor'",
"]",
")",
"if",
"self",
".",
"_delay",
"==",
"0",
":",
"connect",
"(",
")",
"else",
":",
"self",
".",
"_reconnectDelayedCall",
"=",
"self",
".",
"reactor",
".",
"callLater",
"(",
"self",
".",
"_delay",
",",
"connect",
")",
"self",
".",
"_toState",
"(",
"'waiting'",
")"
] | Attempt to reconnect.
If the current back-off delay is 0, L{connect} is called. Otherwise,
it will cause a transition to the C{'waiting'} state, ultimately
causing a call to L{connect} when the delay expires. | [
"Attempt",
"to",
"reconnect",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L1003-L1029 |
2,093 | dustin/twitty-twister | twittytwister/twitter.py | TwitterMonitor._toState | def _toState(self, state, *args, **kwargs):
"""
Transition to the next state.
@param state: Name of the next state.
"""
try:
method = getattr(self, '_state_%s' % state)
except AttributeError:
raise ValueError("No such state %r" % state)
log.msg("%s: to state %r" % (self.__class__.__name__, state))
self._state = state
method(*args, **kwargs) | python | def _toState(self, state, *args, **kwargs):
try:
method = getattr(self, '_state_%s' % state)
except AttributeError:
raise ValueError("No such state %r" % state)
log.msg("%s: to state %r" % (self.__class__.__name__, state))
self._state = state
method(*args, **kwargs) | [
"def",
"_toState",
"(",
"self",
",",
"state",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"'_state_%s'",
"%",
"state",
")",
"except",
"AttributeError",
":",
"raise",
"ValueError",
"(",
"\"No such state %r\"",
"%",
"state",
")",
"log",
".",
"msg",
"(",
"\"%s: to state %r\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"state",
")",
")",
"self",
".",
"_state",
"=",
"state",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Transition to the next state.
@param state: Name of the next state. | [
"Transition",
"to",
"the",
"next",
"state",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L1032-L1045 |
2,094 | dustin/twitty-twister | twittytwister/twitter.py | TwitterMonitor._state_stopped | def _state_stopped(self):
"""
The service is not running.
This is the initial state, and the state after L{stopService} was
called. To get out of this state, call L{startService}. If there is a
current connection, we disconnect.
"""
if self._reconnectDelayedCall:
self._reconnectDelayedCall.cancel()
self._reconnectDelayedCall = None
self.loseConnection() | python | def _state_stopped(self):
if self._reconnectDelayedCall:
self._reconnectDelayedCall.cancel()
self._reconnectDelayedCall = None
self.loseConnection() | [
"def",
"_state_stopped",
"(",
"self",
")",
":",
"if",
"self",
".",
"_reconnectDelayedCall",
":",
"self",
".",
"_reconnectDelayedCall",
".",
"cancel",
"(",
")",
"self",
".",
"_reconnectDelayedCall",
"=",
"None",
"self",
".",
"loseConnection",
"(",
")"
] | The service is not running.
This is the initial state, and the state after L{stopService} was
called. To get out of this state, call L{startService}. If there is a
current connection, we disconnect. | [
"The",
"service",
"is",
"not",
"running",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L1048-L1059 |
2,095 | dustin/twitty-twister | twittytwister/twitter.py | TwitterMonitor._state_connecting | def _state_connecting(self):
"""
A connection is being started.
A succesful attempt results in the state C{'connected'} when the
first response from Twitter has been received. Transitioning
to the state C{'aborting'} will cause an immediate disconnect instead,
by transitioning to C{'disconnecting'}.
Errors will cause a transition to the C{'error'} state.
"""
def responseReceived(protocol):
self.makeConnection(protocol)
if self._state == 'aborting':
self._toState('disconnecting')
else:
self._toState('connected')
def trapError(failure):
self._toState('error', failure)
def onEntry(entry):
if self.delegate:
try:
self.delegate(entry)
except:
log.err()
else:
pass
d = self.api(onEntry, self.args)
d.addCallback(responseReceived)
d.addErrback(trapError) | python | def _state_connecting(self):
def responseReceived(protocol):
self.makeConnection(protocol)
if self._state == 'aborting':
self._toState('disconnecting')
else:
self._toState('connected')
def trapError(failure):
self._toState('error', failure)
def onEntry(entry):
if self.delegate:
try:
self.delegate(entry)
except:
log.err()
else:
pass
d = self.api(onEntry, self.args)
d.addCallback(responseReceived)
d.addErrback(trapError) | [
"def",
"_state_connecting",
"(",
"self",
")",
":",
"def",
"responseReceived",
"(",
"protocol",
")",
":",
"self",
".",
"makeConnection",
"(",
"protocol",
")",
"if",
"self",
".",
"_state",
"==",
"'aborting'",
":",
"self",
".",
"_toState",
"(",
"'disconnecting'",
")",
"else",
":",
"self",
".",
"_toState",
"(",
"'connected'",
")",
"def",
"trapError",
"(",
"failure",
")",
":",
"self",
".",
"_toState",
"(",
"'error'",
",",
"failure",
")",
"def",
"onEntry",
"(",
"entry",
")",
":",
"if",
"self",
".",
"delegate",
":",
"try",
":",
"self",
".",
"delegate",
"(",
"entry",
")",
"except",
":",
"log",
".",
"err",
"(",
")",
"else",
":",
"pass",
"d",
"=",
"self",
".",
"api",
"(",
"onEntry",
",",
"self",
".",
"args",
")",
"d",
".",
"addCallback",
"(",
"responseReceived",
")",
"d",
".",
"addErrback",
"(",
"trapError",
")"
] | A connection is being started.
A succesful attempt results in the state C{'connected'} when the
first response from Twitter has been received. Transitioning
to the state C{'aborting'} will cause an immediate disconnect instead,
by transitioning to C{'disconnecting'}.
Errors will cause a transition to the C{'error'} state. | [
"A",
"connection",
"is",
"being",
"started",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L1081-L1114 |
2,096 | dustin/twitty-twister | twittytwister/twitter.py | TwitterMonitor._state_error | def _state_error(self, reason):
"""
The connection attempt resulted in an error.
Attempt a reconnect with a back-off algorithm.
"""
log.err(reason)
def matchException(failure):
for errorState, backOff in self.backOffs.iteritems():
if 'errorTypes' not in backOff:
continue
if failure.check(*backOff['errorTypes']):
return errorState
return 'other'
errorState = matchException(reason)
self._reconnect(errorState) | python | def _state_error(self, reason):
log.err(reason)
def matchException(failure):
for errorState, backOff in self.backOffs.iteritems():
if 'errorTypes' not in backOff:
continue
if failure.check(*backOff['errorTypes']):
return errorState
return 'other'
errorState = matchException(reason)
self._reconnect(errorState) | [
"def",
"_state_error",
"(",
"self",
",",
"reason",
")",
":",
"log",
".",
"err",
"(",
"reason",
")",
"def",
"matchException",
"(",
"failure",
")",
":",
"for",
"errorState",
",",
"backOff",
"in",
"self",
".",
"backOffs",
".",
"iteritems",
"(",
")",
":",
"if",
"'errorTypes'",
"not",
"in",
"backOff",
":",
"continue",
"if",
"failure",
".",
"check",
"(",
"*",
"backOff",
"[",
"'errorTypes'",
"]",
")",
":",
"return",
"errorState",
"return",
"'other'",
"errorState",
"=",
"matchException",
"(",
"reason",
")",
"self",
".",
"_reconnect",
"(",
"errorState",
")"
] | The connection attempt resulted in an error.
Attempt a reconnect with a back-off algorithm. | [
"The",
"connection",
"attempt",
"resulted",
"in",
"an",
"error",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L1168-L1186 |
2,097 | dustin/twitty-twister | twittytwister/streaming.py | LengthDelimitedStream.lineReceived | def lineReceived(self, line):
"""
Called when a line is received.
We expect a length in bytes or an empty line for keep-alive. If
we got a length, switch to raw mode to receive that amount of bytes.
"""
if line and line.isdigit():
self._expectedLength = int(line)
self._rawBuffer = []
self._rawBufferLength = 0
self.setRawMode()
else:
self.keepAliveReceived() | python | def lineReceived(self, line):
if line and line.isdigit():
self._expectedLength = int(line)
self._rawBuffer = []
self._rawBufferLength = 0
self.setRawMode()
else:
self.keepAliveReceived() | [
"def",
"lineReceived",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
"and",
"line",
".",
"isdigit",
"(",
")",
":",
"self",
".",
"_expectedLength",
"=",
"int",
"(",
"line",
")",
"self",
".",
"_rawBuffer",
"=",
"[",
"]",
"self",
".",
"_rawBufferLength",
"=",
"0",
"self",
".",
"setRawMode",
"(",
")",
"else",
":",
"self",
".",
"keepAliveReceived",
"(",
")"
] | Called when a line is received.
We expect a length in bytes or an empty line for keep-alive. If
we got a length, switch to raw mode to receive that amount of bytes. | [
"Called",
"when",
"a",
"line",
"is",
"received",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/streaming.py#L35-L48 |
2,098 | dustin/twitty-twister | twittytwister/streaming.py | LengthDelimitedStream.rawDataReceived | def rawDataReceived(self, data):
"""
Called when raw data is received.
Fill the raw buffer C{_rawBuffer} until we have received at least
C{_expectedLength} bytes. Call C{datagramReceived} with the received
byte string of the expected size. Then switch back to line mode with
the remainder of the buffer.
"""
self._rawBuffer.append(data)
self._rawBufferLength += len(data)
if self._rawBufferLength >= self._expectedLength:
receivedData = ''.join(self._rawBuffer)
expectedData = receivedData[:self._expectedLength]
extraData = receivedData[self._expectedLength:]
self._rawBuffer = None
self._rawBufferLength = None
self._expectedLength = None
self.datagramReceived(expectedData)
self.setLineMode(extraData) | python | def rawDataReceived(self, data):
self._rawBuffer.append(data)
self._rawBufferLength += len(data)
if self._rawBufferLength >= self._expectedLength:
receivedData = ''.join(self._rawBuffer)
expectedData = receivedData[:self._expectedLength]
extraData = receivedData[self._expectedLength:]
self._rawBuffer = None
self._rawBufferLength = None
self._expectedLength = None
self.datagramReceived(expectedData)
self.setLineMode(extraData) | [
"def",
"rawDataReceived",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_rawBuffer",
".",
"append",
"(",
"data",
")",
"self",
".",
"_rawBufferLength",
"+=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"_rawBufferLength",
">=",
"self",
".",
"_expectedLength",
":",
"receivedData",
"=",
"''",
".",
"join",
"(",
"self",
".",
"_rawBuffer",
")",
"expectedData",
"=",
"receivedData",
"[",
":",
"self",
".",
"_expectedLength",
"]",
"extraData",
"=",
"receivedData",
"[",
"self",
".",
"_expectedLength",
":",
"]",
"self",
".",
"_rawBuffer",
"=",
"None",
"self",
".",
"_rawBufferLength",
"=",
"None",
"self",
".",
"_expectedLength",
"=",
"None",
"self",
".",
"datagramReceived",
"(",
"expectedData",
")",
"self",
".",
"setLineMode",
"(",
"extraData",
")"
] | Called when raw data is received.
Fill the raw buffer C{_rawBuffer} until we have received at least
C{_expectedLength} bytes. Call C{datagramReceived} with the received
byte string of the expected size. Then switch back to line mode with
the remainder of the buffer. | [
"Called",
"when",
"raw",
"data",
"is",
"received",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/streaming.py#L51-L73 |
2,099 | dustin/twitty-twister | twittytwister/streaming.py | TwitterObject.fromDict | def fromDict(cls, data):
"""
Fill this objects attributes from a dict for known properties.
"""
obj = cls()
obj.raw = data
for name, value in data.iteritems():
if cls.SIMPLE_PROPS and name in cls.SIMPLE_PROPS:
setattr(obj, name, value)
elif cls.COMPLEX_PROPS and name in cls.COMPLEX_PROPS:
value = cls.COMPLEX_PROPS[name].fromDict(value)
setattr(obj, name, value)
elif cls.LIST_PROPS and name in cls.LIST_PROPS:
value = [cls.LIST_PROPS[name].fromDict(item)
for item in value]
setattr(obj, name, value)
return obj | python | def fromDict(cls, data):
obj = cls()
obj.raw = data
for name, value in data.iteritems():
if cls.SIMPLE_PROPS and name in cls.SIMPLE_PROPS:
setattr(obj, name, value)
elif cls.COMPLEX_PROPS and name in cls.COMPLEX_PROPS:
value = cls.COMPLEX_PROPS[name].fromDict(value)
setattr(obj, name, value)
elif cls.LIST_PROPS and name in cls.LIST_PROPS:
value = [cls.LIST_PROPS[name].fromDict(item)
for item in value]
setattr(obj, name, value)
return obj | [
"def",
"fromDict",
"(",
"cls",
",",
"data",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"obj",
".",
"raw",
"=",
"data",
"for",
"name",
",",
"value",
"in",
"data",
".",
"iteritems",
"(",
")",
":",
"if",
"cls",
".",
"SIMPLE_PROPS",
"and",
"name",
"in",
"cls",
".",
"SIMPLE_PROPS",
":",
"setattr",
"(",
"obj",
",",
"name",
",",
"value",
")",
"elif",
"cls",
".",
"COMPLEX_PROPS",
"and",
"name",
"in",
"cls",
".",
"COMPLEX_PROPS",
":",
"value",
"=",
"cls",
".",
"COMPLEX_PROPS",
"[",
"name",
"]",
".",
"fromDict",
"(",
"value",
")",
"setattr",
"(",
"obj",
",",
"name",
",",
"value",
")",
"elif",
"cls",
".",
"LIST_PROPS",
"and",
"name",
"in",
"cls",
".",
"LIST_PROPS",
":",
"value",
"=",
"[",
"cls",
".",
"LIST_PROPS",
"[",
"name",
"]",
".",
"fromDict",
"(",
"item",
")",
"for",
"item",
"in",
"value",
"]",
"setattr",
"(",
"obj",
",",
"name",
",",
"value",
")",
"return",
"obj"
] | Fill this objects attributes from a dict for known properties. | [
"Fill",
"this",
"objects",
"attributes",
"from",
"a",
"dict",
"for",
"known",
"properties",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/streaming.py#L102-L119 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.