repo
stringclasses 679
values | path
stringlengths 6
122
| func_name
stringlengths 2
76
| original_string
stringlengths 87
70.9k
| language
stringclasses 1
value | code
stringlengths 87
70.9k
| code_tokens
sequencelengths 20
6.91k
| docstring
stringlengths 1
21.7k
| docstring_tokens
sequencelengths 1
1.6k
| sha
stringclasses 679
values | url
stringlengths 92
213
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
cltrudeau/django-flowr | flowr/models.py | Node.descendents_root | def descendents_root(self):
"""Returns a list of descendents of this node, if the root node is in
the list (due to a cycle) it will be included but will not pass
through it.
"""
visited = set([])
self._depth_descend(self, visited, True)
try:
visited.remove(self)
except KeyError:
# we weren't descendent of ourself, that's ok
pass
return list(visited) | python | def descendents_root(self):
"""Returns a list of descendents of this node, if the root node is in
the list (due to a cycle) it will be included but will not pass
through it.
"""
visited = set([])
self._depth_descend(self, visited, True)
try:
visited.remove(self)
except KeyError:
# we weren't descendent of ourself, that's ok
pass
return list(visited) | [
"def",
"descendents_root",
"(",
"self",
")",
":",
"visited",
"=",
"set",
"(",
"[",
"]",
")",
"self",
".",
"_depth_descend",
"(",
"self",
",",
"visited",
",",
"True",
")",
"try",
":",
"visited",
".",
"remove",
"(",
"self",
")",
"except",
"KeyError",
":",
"# we weren't descendent of ourself, that's ok",
"pass",
"return",
"list",
"(",
"visited",
")"
] | Returns a list of descendents of this node, if the root node is in
the list (due to a cycle) it will be included but will not pass
through it. | [
"Returns",
"a",
"list",
"of",
"descendents",
"of",
"this",
"node",
"if",
"the",
"root",
"node",
"is",
"in",
"the",
"list",
"(",
"due",
"to",
"a",
"cycle",
")",
"it",
"will",
"be",
"included",
"but",
"will",
"not",
"pass",
"through",
"it",
"."
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L275-L288 | valid |
cltrudeau/django-flowr | flowr/models.py | Node.can_remove | def can_remove(self):
"""Returns True if it is legal to remove this node and still leave the
graph as a single connected entity, not splitting it into a forest.
Only nodes with no children or those who cause a cycle can be deleted.
"""
if self.children.count() == 0:
return True
ancestors = set(self.ancestors_root())
children = set(self.children.all())
return children.issubset(ancestors) | python | def can_remove(self):
"""Returns True if it is legal to remove this node and still leave the
graph as a single connected entity, not splitting it into a forest.
Only nodes with no children or those who cause a cycle can be deleted.
"""
if self.children.count() == 0:
return True
ancestors = set(self.ancestors_root())
children = set(self.children.all())
return children.issubset(ancestors) | [
"def",
"can_remove",
"(",
"self",
")",
":",
"if",
"self",
".",
"children",
".",
"count",
"(",
")",
"==",
"0",
":",
"return",
"True",
"ancestors",
"=",
"set",
"(",
"self",
".",
"ancestors_root",
"(",
")",
")",
"children",
"=",
"set",
"(",
"self",
".",
"children",
".",
"all",
"(",
")",
")",
"return",
"children",
".",
"issubset",
"(",
"ancestors",
")"
] | Returns True if it is legal to remove this node and still leave the
graph as a single connected entity, not splitting it into a forest.
Only nodes with no children or those who cause a cycle can be deleted. | [
"Returns",
"True",
"if",
"it",
"is",
"legal",
"to",
"remove",
"this",
"node",
"and",
"still",
"leave",
"the",
"graph",
"as",
"a",
"single",
"connected",
"entity",
"not",
"splitting",
"it",
"into",
"a",
"forest",
".",
"Only",
"nodes",
"with",
"no",
"children",
"or",
"those",
"who",
"cause",
"a",
"cycle",
"can",
"be",
"deleted",
"."
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L290-L300 | valid |
cltrudeau/django-flowr | flowr/models.py | Node.remove | def remove(self):
"""Removes the node from the graph. Note this does not remove the
associated data object. See :func:`Node.can_remove` for limitations
on what can be deleted.
:returns:
:class:`BaseNodeData` subclass associated with the deleted Node
:raises AttributeError:
if called on a ``Node`` that cannot be deleted
"""
if not self.can_remove():
raise AttributeError('this node cannot be deleted')
data = self.data
self.parents.remove(self)
self.delete()
return data | python | def remove(self):
"""Removes the node from the graph. Note this does not remove the
associated data object. See :func:`Node.can_remove` for limitations
on what can be deleted.
:returns:
:class:`BaseNodeData` subclass associated with the deleted Node
:raises AttributeError:
if called on a ``Node`` that cannot be deleted
"""
if not self.can_remove():
raise AttributeError('this node cannot be deleted')
data = self.data
self.parents.remove(self)
self.delete()
return data | [
"def",
"remove",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"can_remove",
"(",
")",
":",
"raise",
"AttributeError",
"(",
"'this node cannot be deleted'",
")",
"data",
"=",
"self",
".",
"data",
"self",
".",
"parents",
".",
"remove",
"(",
"self",
")",
"self",
".",
"delete",
"(",
")",
"return",
"data"
] | Removes the node from the graph. Note this does not remove the
associated data object. See :func:`Node.can_remove` for limitations
on what can be deleted.
:returns:
:class:`BaseNodeData` subclass associated with the deleted Node
:raises AttributeError:
if called on a ``Node`` that cannot be deleted | [
"Removes",
"the",
"node",
"from",
"the",
"graph",
".",
"Note",
"this",
"does",
"not",
"remove",
"the",
"associated",
"data",
"object",
".",
"See",
":",
"func",
":",
"Node",
".",
"can_remove",
"for",
"limitations",
"on",
"what",
"can",
"be",
"deleted",
"."
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L302-L319 | valid |
cltrudeau/django-flowr | flowr/models.py | Node.prune | def prune(self):
"""Removes the node and all descendents without looping back past the
root. Note this does not remove the associated data objects.
:returns:
list of :class:`BaseDataNode` subclassers associated with the
removed ``Node`` objects.
"""
targets = self.descendents_root()
try:
targets.remove(self.graph.root)
except ValueError:
# root wasn't in the target list, no problem
pass
results = [n.data for n in targets]
results.append(self.data)
for node in targets:
node.delete()
for parent in self.parents.all():
parent.children.remove(self)
self.delete()
return results | python | def prune(self):
"""Removes the node and all descendents without looping back past the
root. Note this does not remove the associated data objects.
:returns:
list of :class:`BaseDataNode` subclassers associated with the
removed ``Node`` objects.
"""
targets = self.descendents_root()
try:
targets.remove(self.graph.root)
except ValueError:
# root wasn't in the target list, no problem
pass
results = [n.data for n in targets]
results.append(self.data)
for node in targets:
node.delete()
for parent in self.parents.all():
parent.children.remove(self)
self.delete()
return results | [
"def",
"prune",
"(",
"self",
")",
":",
"targets",
"=",
"self",
".",
"descendents_root",
"(",
")",
"try",
":",
"targets",
".",
"remove",
"(",
"self",
".",
"graph",
".",
"root",
")",
"except",
"ValueError",
":",
"# root wasn't in the target list, no problem",
"pass",
"results",
"=",
"[",
"n",
".",
"data",
"for",
"n",
"in",
"targets",
"]",
"results",
".",
"append",
"(",
"self",
".",
"data",
")",
"for",
"node",
"in",
"targets",
":",
"node",
".",
"delete",
"(",
")",
"for",
"parent",
"in",
"self",
".",
"parents",
".",
"all",
"(",
")",
":",
"parent",
".",
"children",
".",
"remove",
"(",
"self",
")",
"self",
".",
"delete",
"(",
")",
"return",
"results"
] | Removes the node and all descendents without looping back past the
root. Note this does not remove the associated data objects.
:returns:
list of :class:`BaseDataNode` subclassers associated with the
removed ``Node`` objects. | [
"Removes",
"the",
"node",
"and",
"all",
"descendents",
"without",
"looping",
"back",
"past",
"the",
"root",
".",
"Note",
"this",
"does",
"not",
"remove",
"the",
"associated",
"data",
"objects",
"."
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L321-L345 | valid |
cltrudeau/django-flowr | flowr/models.py | Node.prune_list | def prune_list(self):
"""Returns a list of nodes that would be removed if prune were called
on this element.
"""
targets = self.descendents_root()
try:
targets.remove(self.graph.root)
except ValueError:
# root wasn't in the target list, no problem
pass
targets.append(self)
return targets | python | def prune_list(self):
"""Returns a list of nodes that would be removed if prune were called
on this element.
"""
targets = self.descendents_root()
try:
targets.remove(self.graph.root)
except ValueError:
# root wasn't in the target list, no problem
pass
targets.append(self)
return targets | [
"def",
"prune_list",
"(",
"self",
")",
":",
"targets",
"=",
"self",
".",
"descendents_root",
"(",
")",
"try",
":",
"targets",
".",
"remove",
"(",
"self",
".",
"graph",
".",
"root",
")",
"except",
"ValueError",
":",
"# root wasn't in the target list, no problem",
"pass",
"targets",
".",
"append",
"(",
"self",
")",
"return",
"targets"
] | Returns a list of nodes that would be removed if prune were called
on this element. | [
"Returns",
"a",
"list",
"of",
"nodes",
"that",
"would",
"be",
"removed",
"if",
"prune",
"were",
"called",
"on",
"this",
"element",
"."
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L347-L359 | valid |
cltrudeau/django-flowr | flowr/models.py | FlowNodeData._child_allowed | def _child_allowed(self, child_rule):
"""Called to verify that the given rule can become a child of the
current node.
:raises AttributeError:
if the child is not allowed
"""
num_kids = self.node.children.count()
num_kids_allowed = len(self.rule.children)
if not self.rule.multiple_paths:
num_kids_allowed = 1
if num_kids >= num_kids_allowed:
raise AttributeError('Rule %s only allows %s children' % (
self.rule_name, self.num_kids_allowed))
# verify not a duplicate
for node in self.node.children.all():
if node.data.rule_label == child_rule.class_label:
raise AttributeError('Child rule already exists')
# check if the given rule is allowed as a child
if child_rule not in self.rule.children:
raise AttributeError('Rule %s is not a valid child of Rule %s' % (
child_rule.__name__, self.rule_name)) | python | def _child_allowed(self, child_rule):
"""Called to verify that the given rule can become a child of the
current node.
:raises AttributeError:
if the child is not allowed
"""
num_kids = self.node.children.count()
num_kids_allowed = len(self.rule.children)
if not self.rule.multiple_paths:
num_kids_allowed = 1
if num_kids >= num_kids_allowed:
raise AttributeError('Rule %s only allows %s children' % (
self.rule_name, self.num_kids_allowed))
# verify not a duplicate
for node in self.node.children.all():
if node.data.rule_label == child_rule.class_label:
raise AttributeError('Child rule already exists')
# check if the given rule is allowed as a child
if child_rule not in self.rule.children:
raise AttributeError('Rule %s is not a valid child of Rule %s' % (
child_rule.__name__, self.rule_name)) | [
"def",
"_child_allowed",
"(",
"self",
",",
"child_rule",
")",
":",
"num_kids",
"=",
"self",
".",
"node",
".",
"children",
".",
"count",
"(",
")",
"num_kids_allowed",
"=",
"len",
"(",
"self",
".",
"rule",
".",
"children",
")",
"if",
"not",
"self",
".",
"rule",
".",
"multiple_paths",
":",
"num_kids_allowed",
"=",
"1",
"if",
"num_kids",
">=",
"num_kids_allowed",
":",
"raise",
"AttributeError",
"(",
"'Rule %s only allows %s children'",
"%",
"(",
"self",
".",
"rule_name",
",",
"self",
".",
"num_kids_allowed",
")",
")",
"# verify not a duplicate",
"for",
"node",
"in",
"self",
".",
"node",
".",
"children",
".",
"all",
"(",
")",
":",
"if",
"node",
".",
"data",
".",
"rule_label",
"==",
"child_rule",
".",
"class_label",
":",
"raise",
"AttributeError",
"(",
"'Child rule already exists'",
")",
"# check if the given rule is allowed as a child",
"if",
"child_rule",
"not",
"in",
"self",
".",
"rule",
".",
"children",
":",
"raise",
"AttributeError",
"(",
"'Rule %s is not a valid child of Rule %s'",
"%",
"(",
"child_rule",
".",
"__name__",
",",
"self",
".",
"rule_name",
")",
")"
] | Called to verify that the given rule can become a child of the
current node.
:raises AttributeError:
if the child is not allowed | [
"Called",
"to",
"verify",
"that",
"the",
"given",
"rule",
"can",
"become",
"a",
"child",
"of",
"the",
"current",
"node",
"."
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L540-L564 | valid |
cltrudeau/django-flowr | flowr/models.py | FlowNodeData.add_child_rule | def add_child_rule(self, child_rule):
"""Add a child path in the :class:`Flow` graph using the given
:class:`Rule` subclass. This will create a new child :class:`Node` in
the associated :class:`Flow` object's state graph with a new
:class:`FlowNodeData` instance attached.
The :class:`Rule` must be allowed at this stage of the flow according
to the hierarchy of rules.
:param child_rule:
:class:`Rule` class to add to the flow as a child of :class:`Node`
that this object owns
:returns:
``FlowNodeData`` that was added
"""
self._child_allowed(child_rule)
child_node = self.node.add_child(rule_label=child_rule.class_label)
return child_node.data | python | def add_child_rule(self, child_rule):
"""Add a child path in the :class:`Flow` graph using the given
:class:`Rule` subclass. This will create a new child :class:`Node` in
the associated :class:`Flow` object's state graph with a new
:class:`FlowNodeData` instance attached.
The :class:`Rule` must be allowed at this stage of the flow according
to the hierarchy of rules.
:param child_rule:
:class:`Rule` class to add to the flow as a child of :class:`Node`
that this object owns
:returns:
``FlowNodeData`` that was added
"""
self._child_allowed(child_rule)
child_node = self.node.add_child(rule_label=child_rule.class_label)
return child_node.data | [
"def",
"add_child_rule",
"(",
"self",
",",
"child_rule",
")",
":",
"self",
".",
"_child_allowed",
"(",
"child_rule",
")",
"child_node",
"=",
"self",
".",
"node",
".",
"add_child",
"(",
"rule_label",
"=",
"child_rule",
".",
"class_label",
")",
"return",
"child_node",
".",
"data"
] | Add a child path in the :class:`Flow` graph using the given
:class:`Rule` subclass. This will create a new child :class:`Node` in
the associated :class:`Flow` object's state graph with a new
:class:`FlowNodeData` instance attached.
The :class:`Rule` must be allowed at this stage of the flow according
to the hierarchy of rules.
:param child_rule:
:class:`Rule` class to add to the flow as a child of :class:`Node`
that this object owns
:returns:
``FlowNodeData`` that was added | [
"Add",
"a",
"child",
"path",
"in",
"the",
":",
"class",
":",
"Flow",
"graph",
"using",
"the",
"given",
":",
"class",
":",
"Rule",
"subclass",
".",
"This",
"will",
"create",
"a",
"new",
"child",
":",
"class",
":",
"Node",
"in",
"the",
"associated",
":",
"class",
":",
"Flow",
"object",
"s",
"state",
"graph",
"with",
"a",
"new",
":",
"class",
":",
"FlowNodeData",
"instance",
"attached",
".",
"The",
":",
"class",
":",
"Rule",
"must",
"be",
"allowed",
"at",
"this",
"stage",
"of",
"the",
"flow",
"according",
"to",
"the",
"hierarchy",
"of",
"rules",
"."
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L566-L583 | valid |
cltrudeau/django-flowr | flowr/models.py | FlowNodeData.connect_child | def connect_child(self, child_node):
"""Adds a connection to an existing rule in the :class`Flow` graph.
The given :class`Rule` subclass must be allowed to be connected at
this stage of the flow according to the hierarchy of rules.
:param child_node:
``FlowNodeData`` to attach as a child
"""
self._child_allowed(child_node.rule)
self.node.connect_child(child_node.node) | python | def connect_child(self, child_node):
"""Adds a connection to an existing rule in the :class`Flow` graph.
The given :class`Rule` subclass must be allowed to be connected at
this stage of the flow according to the hierarchy of rules.
:param child_node:
``FlowNodeData`` to attach as a child
"""
self._child_allowed(child_node.rule)
self.node.connect_child(child_node.node) | [
"def",
"connect_child",
"(",
"self",
",",
"child_node",
")",
":",
"self",
".",
"_child_allowed",
"(",
"child_node",
".",
"rule",
")",
"self",
".",
"node",
".",
"connect_child",
"(",
"child_node",
".",
"node",
")"
] | Adds a connection to an existing rule in the :class`Flow` graph.
The given :class`Rule` subclass must be allowed to be connected at
this stage of the flow according to the hierarchy of rules.
:param child_node:
``FlowNodeData`` to attach as a child | [
"Adds",
"a",
"connection",
"to",
"an",
"existing",
"rule",
"in",
"the",
":",
"class",
"Flow",
"graph",
".",
"The",
"given",
":",
"class",
"Rule",
"subclass",
"must",
"be",
"allowed",
"to",
"be",
"connected",
"at",
"this",
"stage",
"of",
"the",
"flow",
"according",
"to",
"the",
"hierarchy",
"of",
"rules",
"."
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L585-L594 | valid |
cltrudeau/django-flowr | flowr/models.py | Flow.in_use | def in_use(self):
"""Returns True if there is a :class:`State` object that uses this
``Flow``"""
state = State.objects.filter(flow=self).first()
return bool(state) | python | def in_use(self):
"""Returns True if there is a :class:`State` object that uses this
``Flow``"""
state = State.objects.filter(flow=self).first()
return bool(state) | [
"def",
"in_use",
"(",
"self",
")",
":",
"state",
"=",
"State",
".",
"objects",
".",
"filter",
"(",
"flow",
"=",
"self",
")",
".",
"first",
"(",
")",
"return",
"bool",
"(",
"state",
")"
] | Returns True if there is a :class:`State` object that uses this
``Flow`` | [
"Returns",
"True",
"if",
"there",
"is",
"a",
":",
"class",
":",
"State",
"object",
"that",
"uses",
"this",
"Flow"
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L613-L617 | valid |
cltrudeau/django-flowr | flowr/models.py | State.start | def start(self, flow):
"""Factory method for a running state based on a flow. Creates and
returns a ``State`` object and calls the associated
:func:`Rule.on_enter` method.
:param flow:
:class:`Flow` which defines this state machine
:returns:
newly created instance
"""
state = State.objects.create(flow=flow,
current_node=flow.state_graph.root)
flow.state_graph.root.data.rule.on_enter(state)
return state | python | def start(self, flow):
"""Factory method for a running state based on a flow. Creates and
returns a ``State`` object and calls the associated
:func:`Rule.on_enter` method.
:param flow:
:class:`Flow` which defines this state machine
:returns:
newly created instance
"""
state = State.objects.create(flow=flow,
current_node=flow.state_graph.root)
flow.state_graph.root.data.rule.on_enter(state)
return state | [
"def",
"start",
"(",
"self",
",",
"flow",
")",
":",
"state",
"=",
"State",
".",
"objects",
".",
"create",
"(",
"flow",
"=",
"flow",
",",
"current_node",
"=",
"flow",
".",
"state_graph",
".",
"root",
")",
"flow",
".",
"state_graph",
".",
"root",
".",
"data",
".",
"rule",
".",
"on_enter",
"(",
"state",
")",
"return",
"state"
] | Factory method for a running state based on a flow. Creates and
returns a ``State`` object and calls the associated
:func:`Rule.on_enter` method.
:param flow:
:class:`Flow` which defines this state machine
:returns:
newly created instance | [
"Factory",
"method",
"for",
"a",
"running",
"state",
"based",
"on",
"a",
"flow",
".",
"Creates",
"and",
"returns",
"a",
"State",
"object",
"and",
"calls",
"the",
"associated",
":",
"func",
":",
"Rule",
".",
"on_enter",
"method",
"."
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L638-L651 | valid |
cltrudeau/django-flowr | flowr/models.py | State.next_state | def next_state(self, rule=None):
"""Proceeds to the next step in the flow. Calls the associated
:func:`Rule.on_leave` method for the for the current rule and the
:func:`Rule.on_enter` for the rule being entered. If the current step
in the flow is multipath then a valid :class:`Rule` subclass must be
passed into this call.
If there is only one possible path in the flow and a :class:`Rule` is
given it will be ignored.
:param rule:
if the current :class:`Rule` in the :class:`Flow` is multipath
then the next :class:`Rule` in the flow must be provided.
"""
num_kids = self.current_node.children.count()
next_node = None
if num_kids == 0:
raise AttributeError('No next state in this Flow id=%s' % (
self.flow.id))
elif num_kids == 1:
next_node = self.current_node.children.first()
else:
if not rule:
raise AttributeError(('Current Rule %s is multipath but no '
'choice was passed in') % self.current_node.data.rule_name)
for node in self.current_node.children.all():
if node.data.rule_label == rule.class_label:
next_node = node
break
if not next_node:
raise AttributeError(('Current Rule %s is multipath and the '
'Rule choice passed in was not in the Flow') % (
self.current_node.data.rule_name))
self.current_node.data.rule.on_leave(self)
next_node.data.rule.on_enter(self)
self.current_node = next_node
self.save() | python | def next_state(self, rule=None):
"""Proceeds to the next step in the flow. Calls the associated
:func:`Rule.on_leave` method for the for the current rule and the
:func:`Rule.on_enter` for the rule being entered. If the current step
in the flow is multipath then a valid :class:`Rule` subclass must be
passed into this call.
If there is only one possible path in the flow and a :class:`Rule` is
given it will be ignored.
:param rule:
if the current :class:`Rule` in the :class:`Flow` is multipath
then the next :class:`Rule` in the flow must be provided.
"""
num_kids = self.current_node.children.count()
next_node = None
if num_kids == 0:
raise AttributeError('No next state in this Flow id=%s' % (
self.flow.id))
elif num_kids == 1:
next_node = self.current_node.children.first()
else:
if not rule:
raise AttributeError(('Current Rule %s is multipath but no '
'choice was passed in') % self.current_node.data.rule_name)
for node in self.current_node.children.all():
if node.data.rule_label == rule.class_label:
next_node = node
break
if not next_node:
raise AttributeError(('Current Rule %s is multipath and the '
'Rule choice passed in was not in the Flow') % (
self.current_node.data.rule_name))
self.current_node.data.rule.on_leave(self)
next_node.data.rule.on_enter(self)
self.current_node = next_node
self.save() | [
"def",
"next_state",
"(",
"self",
",",
"rule",
"=",
"None",
")",
":",
"num_kids",
"=",
"self",
".",
"current_node",
".",
"children",
".",
"count",
"(",
")",
"next_node",
"=",
"None",
"if",
"num_kids",
"==",
"0",
":",
"raise",
"AttributeError",
"(",
"'No next state in this Flow id=%s'",
"%",
"(",
"self",
".",
"flow",
".",
"id",
")",
")",
"elif",
"num_kids",
"==",
"1",
":",
"next_node",
"=",
"self",
".",
"current_node",
".",
"children",
".",
"first",
"(",
")",
"else",
":",
"if",
"not",
"rule",
":",
"raise",
"AttributeError",
"(",
"(",
"'Current Rule %s is multipath but no '",
"'choice was passed in'",
")",
"%",
"self",
".",
"current_node",
".",
"data",
".",
"rule_name",
")",
"for",
"node",
"in",
"self",
".",
"current_node",
".",
"children",
".",
"all",
"(",
")",
":",
"if",
"node",
".",
"data",
".",
"rule_label",
"==",
"rule",
".",
"class_label",
":",
"next_node",
"=",
"node",
"break",
"if",
"not",
"next_node",
":",
"raise",
"AttributeError",
"(",
"(",
"'Current Rule %s is multipath and the '",
"'Rule choice passed in was not in the Flow'",
")",
"%",
"(",
"self",
".",
"current_node",
".",
"data",
".",
"rule_name",
")",
")",
"self",
".",
"current_node",
".",
"data",
".",
"rule",
".",
"on_leave",
"(",
"self",
")",
"next_node",
".",
"data",
".",
"rule",
".",
"on_enter",
"(",
"self",
")",
"self",
".",
"current_node",
"=",
"next_node",
"self",
".",
"save",
"(",
")"
] | Proceeds to the next step in the flow. Calls the associated
:func:`Rule.on_leave` method for the for the current rule and the
:func:`Rule.on_enter` for the rule being entered. If the current step
in the flow is multipath then a valid :class:`Rule` subclass must be
passed into this call.
If there is only one possible path in the flow and a :class:`Rule` is
given it will be ignored.
:param rule:
if the current :class:`Rule` in the :class:`Flow` is multipath
then the next :class:`Rule` in the flow must be provided. | [
"Proceeds",
"to",
"the",
"next",
"step",
"in",
"the",
"flow",
".",
"Calls",
"the",
"associated",
":",
"func",
":",
"Rule",
".",
"on_leave",
"method",
"for",
"the",
"for",
"the",
"current",
"rule",
"and",
"the",
":",
"func",
":",
"Rule",
".",
"on_enter",
"for",
"the",
"rule",
"being",
"entered",
".",
"If",
"the",
"current",
"step",
"in",
"the",
"flow",
"is",
"multipath",
"then",
"a",
"valid",
":",
"class",
":",
"Rule",
"subclass",
"must",
"be",
"passed",
"into",
"this",
"call",
"."
] | d077b90376ede33721db55ff29e08b8a16ed17ae | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L657-L696 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/locations.py | Locations.get_location | def get_location(self, location_id):
"""
Returns location data.
http://dev.wheniwork.com/#get-existing-location
"""
url = "/2/locations/%s" % location_id
return self.location_from_json(self._get_resource(url)["location"]) | python | def get_location(self, location_id):
"""
Returns location data.
http://dev.wheniwork.com/#get-existing-location
"""
url = "/2/locations/%s" % location_id
return self.location_from_json(self._get_resource(url)["location"]) | [
"def",
"get_location",
"(",
"self",
",",
"location_id",
")",
":",
"url",
"=",
"\"/2/locations/%s\"",
"%",
"location_id",
"return",
"self",
".",
"location_from_json",
"(",
"self",
".",
"_get_resource",
"(",
"url",
")",
"[",
"\"location\"",
"]",
")"
] | Returns location data.
http://dev.wheniwork.com/#get-existing-location | [
"Returns",
"location",
"data",
"."
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/locations.py#L6-L14 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/locations.py | Locations.get_locations | def get_locations(self):
"""
Returns a list of locations.
http://dev.wheniwork.com/#listing-locations
"""
url = "/2/locations"
data = self._get_resource(url)
locations = []
for entry in data['locations']:
locations.append(self.location_from_json(entry))
return locations | python | def get_locations(self):
"""
Returns a list of locations.
http://dev.wheniwork.com/#listing-locations
"""
url = "/2/locations"
data = self._get_resource(url)
locations = []
for entry in data['locations']:
locations.append(self.location_from_json(entry))
return locations | [
"def",
"get_locations",
"(",
"self",
")",
":",
"url",
"=",
"\"/2/locations\"",
"data",
"=",
"self",
".",
"_get_resource",
"(",
"url",
")",
"locations",
"=",
"[",
"]",
"for",
"entry",
"in",
"data",
"[",
"'locations'",
"]",
":",
"locations",
".",
"append",
"(",
"self",
".",
"location_from_json",
"(",
"entry",
")",
")",
"return",
"locations"
] | Returns a list of locations.
http://dev.wheniwork.com/#listing-locations | [
"Returns",
"a",
"list",
"of",
"locations",
"."
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/locations.py#L16-L29 | valid |
joelfrederico/SciSalt | scisalt/scipy/LinLsqFit_mod.py | LinLsqFit.X | def X(self):
"""
The :math:`X` weighted properly by the errors from *y_error*
"""
if self._X is None:
X = _copy.deepcopy(self.X_unweighted)
# print 'X shape is {}'.format(X.shape)
for i, el in enumerate(X):
X[i, :] = el/self.y_error[i]
# print 'New X shape is {}'.format(X.shape)
self._X = X
return self._X | python | def X(self):
"""
The :math:`X` weighted properly by the errors from *y_error*
"""
if self._X is None:
X = _copy.deepcopy(self.X_unweighted)
# print 'X shape is {}'.format(X.shape)
for i, el in enumerate(X):
X[i, :] = el/self.y_error[i]
# print 'New X shape is {}'.format(X.shape)
self._X = X
return self._X | [
"def",
"X",
"(",
"self",
")",
":",
"if",
"self",
".",
"_X",
"is",
"None",
":",
"X",
"=",
"_copy",
".",
"deepcopy",
"(",
"self",
".",
"X_unweighted",
")",
"# print 'X shape is {}'.format(X.shape)",
"for",
"i",
",",
"el",
"in",
"enumerate",
"(",
"X",
")",
":",
"X",
"[",
"i",
",",
":",
"]",
"=",
"el",
"/",
"self",
".",
"y_error",
"[",
"i",
"]",
"# print 'New X shape is {}'.format(X.shape)",
"self",
".",
"_X",
"=",
"X",
"return",
"self",
".",
"_X"
] | The :math:`X` weighted properly by the errors from *y_error* | [
"The",
":",
"math",
":",
"X",
"weighted",
"properly",
"by",
"the",
"errors",
"from",
"*",
"y_error",
"*"
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L91-L102 | valid |
joelfrederico/SciSalt | scisalt/scipy/LinLsqFit_mod.py | LinLsqFit.y | def y(self):
"""
The :math:`X` weighted properly by the errors from *y_error*
"""
if self._y is None:
self._y = self.y_unweighted/self.y_error
return self._y | python | def y(self):
"""
The :math:`X` weighted properly by the errors from *y_error*
"""
if self._y is None:
self._y = self.y_unweighted/self.y_error
return self._y | [
"def",
"y",
"(",
"self",
")",
":",
"if",
"self",
".",
"_y",
"is",
"None",
":",
"self",
".",
"_y",
"=",
"self",
".",
"y_unweighted",
"/",
"self",
".",
"y_error",
"return",
"self",
".",
"_y"
] | The :math:`X` weighted properly by the errors from *y_error* | [
"The",
":",
"math",
":",
"X",
"weighted",
"properly",
"by",
"the",
"errors",
"from",
"*",
"y_error",
"*"
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L108-L114 | valid |
joelfrederico/SciSalt | scisalt/scipy/LinLsqFit_mod.py | LinLsqFit.y_fit | def y_fit(self):
"""
Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i`
"""
if self._y_fit is None:
self._y_fit = _np.dot(self.X_unweighted, self.beta)
return self._y_fit | python | def y_fit(self):
"""
Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i`
"""
if self._y_fit is None:
self._y_fit = _np.dot(self.X_unweighted, self.beta)
return self._y_fit | [
"def",
"y_fit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_y_fit",
"is",
"None",
":",
"self",
".",
"_y_fit",
"=",
"_np",
".",
"dot",
"(",
"self",
".",
"X_unweighted",
",",
"self",
".",
"beta",
")",
"return",
"self",
".",
"_y_fit"
] | Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i` | [
"Using",
"the",
"result",
"of",
"the",
"linear",
"least",
"squares",
"the",
"result",
"of",
":",
"math",
":",
"X_",
"{",
"ij",
"}",
"\\\\",
"beta_i"
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L120-L126 | valid |
joelfrederico/SciSalt | scisalt/scipy/LinLsqFit_mod.py | LinLsqFit.beta | def beta(self):
"""
The result :math:`\\beta` of the linear least squares
"""
if self._beta is None:
# This is the linear least squares matrix formalism
self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y)
return self._beta | python | def beta(self):
"""
The result :math:`\\beta` of the linear least squares
"""
if self._beta is None:
# This is the linear least squares matrix formalism
self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y)
return self._beta | [
"def",
"beta",
"(",
"self",
")",
":",
"if",
"self",
".",
"_beta",
"is",
"None",
":",
"# This is the linear least squares matrix formalism",
"self",
".",
"_beta",
"=",
"_np",
".",
"dot",
"(",
"_np",
".",
"linalg",
".",
"pinv",
"(",
"self",
".",
"X",
")",
",",
"self",
".",
"y",
")",
"return",
"self",
".",
"_beta"
] | The result :math:`\\beta` of the linear least squares | [
"The",
"result",
":",
"math",
":",
"\\\\",
"beta",
"of",
"the",
"linear",
"least",
"squares"
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L132-L139 | valid |
joelfrederico/SciSalt | scisalt/scipy/LinLsqFit_mod.py | LinLsqFit.covar | def covar(self):
"""
The covariance matrix for the result :math:`\\beta`
"""
if self._covar is None:
self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X))
return self._covar | python | def covar(self):
"""
The covariance matrix for the result :math:`\\beta`
"""
if self._covar is None:
self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X))
return self._covar | [
"def",
"covar",
"(",
"self",
")",
":",
"if",
"self",
".",
"_covar",
"is",
"None",
":",
"self",
".",
"_covar",
"=",
"_np",
".",
"linalg",
".",
"inv",
"(",
"_np",
".",
"dot",
"(",
"_np",
".",
"transpose",
"(",
"self",
".",
"X",
")",
",",
"self",
".",
"X",
")",
")",
"return",
"self",
".",
"_covar"
] | The covariance matrix for the result :math:`\\beta` | [
"The",
"covariance",
"matrix",
"for",
"the",
"result",
":",
"math",
":",
"\\\\",
"beta"
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L145-L151 | valid |
joelfrederico/SciSalt | scisalt/scipy/LinLsqFit_mod.py | LinLsqFit.chisq_red | def chisq_red(self):
"""
The reduced chi-square of the linear least squares
"""
if self._chisq_red is None:
self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False)
return self._chisq_red | python | def chisq_red(self):
"""
The reduced chi-square of the linear least squares
"""
if self._chisq_red is None:
self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False)
return self._chisq_red | [
"def",
"chisq_red",
"(",
"self",
")",
":",
"if",
"self",
".",
"_chisq_red",
"is",
"None",
":",
"self",
".",
"_chisq_red",
"=",
"chisquare",
"(",
"self",
".",
"y_unweighted",
".",
"transpose",
"(",
")",
",",
"_np",
".",
"dot",
"(",
"self",
".",
"X_unweighted",
",",
"self",
".",
"beta",
")",
",",
"self",
".",
"y_error",
",",
"ddof",
"=",
"3",
",",
"verbose",
"=",
"False",
")",
"return",
"self",
".",
"_chisq_red"
] | The reduced chi-square of the linear least squares | [
"The",
"reduced",
"chi",
"-",
"square",
"of",
"the",
"linear",
"least",
"squares"
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L157-L163 | valid |
mvexel/maproulette-api-wrapper | maproulette/task.py | MapRouletteTask.create | def create(self, server):
"""Create the task on the server"""
if len(self.geometries) == 0:
raise Exception('no geometries')
return server.post(
'task_admin',
self.as_payload(),
replacements={
'slug': self.__challenge__.slug,
'identifier': self.identifier}) | python | def create(self, server):
"""Create the task on the server"""
if len(self.geometries) == 0:
raise Exception('no geometries')
return server.post(
'task_admin',
self.as_payload(),
replacements={
'slug': self.__challenge__.slug,
'identifier': self.identifier}) | [
"def",
"create",
"(",
"self",
",",
"server",
")",
":",
"if",
"len",
"(",
"self",
".",
"geometries",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"'no geometries'",
")",
"return",
"server",
".",
"post",
"(",
"'task_admin'",
",",
"self",
".",
"as_payload",
"(",
")",
",",
"replacements",
"=",
"{",
"'slug'",
":",
"self",
".",
"__challenge__",
".",
"slug",
",",
"'identifier'",
":",
"self",
".",
"identifier",
"}",
")"
] | Create the task on the server | [
"Create",
"the",
"task",
"on",
"the",
"server"
] | 835278111afefed2beecf9716a033529304c548f | https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/task.py#L45-L54 | valid |
mvexel/maproulette-api-wrapper | maproulette/task.py | MapRouletteTask.update | def update(self, server):
"""Update existing task on the server"""
return server.put(
'task_admin',
self.as_payload(),
replacements={
'slug': self.__challenge__.slug,
'identifier': self.identifier}) | python | def update(self, server):
"""Update existing task on the server"""
return server.put(
'task_admin',
self.as_payload(),
replacements={
'slug': self.__challenge__.slug,
'identifier': self.identifier}) | [
"def",
"update",
"(",
"self",
",",
"server",
")",
":",
"return",
"server",
".",
"put",
"(",
"'task_admin'",
",",
"self",
".",
"as_payload",
"(",
")",
",",
"replacements",
"=",
"{",
"'slug'",
":",
"self",
".",
"__challenge__",
".",
"slug",
",",
"'identifier'",
":",
"self",
".",
"identifier",
"}",
")"
] | Update existing task on the server | [
"Update",
"existing",
"task",
"on",
"the",
"server"
] | 835278111afefed2beecf9716a033529304c548f | https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/task.py#L56-L63 | valid |
mvexel/maproulette-api-wrapper | maproulette/task.py | MapRouletteTask.from_server | def from_server(cls, server, slug, identifier):
"""Retrieve a task from the server"""
task = server.get(
'task',
replacements={
'slug': slug,
'identifier': identifier})
return cls(**task) | python | def from_server(cls, server, slug, identifier):
"""Retrieve a task from the server"""
task = server.get(
'task',
replacements={
'slug': slug,
'identifier': identifier})
return cls(**task) | [
"def",
"from_server",
"(",
"cls",
",",
"server",
",",
"slug",
",",
"identifier",
")",
":",
"task",
"=",
"server",
".",
"get",
"(",
"'task'",
",",
"replacements",
"=",
"{",
"'slug'",
":",
"slug",
",",
"'identifier'",
":",
"identifier",
"}",
")",
"return",
"cls",
"(",
"*",
"*",
"task",
")"
] | Retrieve a task from the server | [
"Retrieve",
"a",
"task",
"from",
"the",
"server"
] | 835278111afefed2beecf9716a033529304c548f | https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/task.py#L92-L99 | valid |
minttu/tmc.py | tmc/coloring.py | formatter | def formatter(color, s):
""" Formats a string with color """
if no_coloring:
return s
return "{begin}{s}{reset}".format(begin=color, s=s, reset=Colors.RESET) | python | def formatter(color, s):
""" Formats a string with color """
if no_coloring:
return s
return "{begin}{s}{reset}".format(begin=color, s=s, reset=Colors.RESET) | [
"def",
"formatter",
"(",
"color",
",",
"s",
")",
":",
"if",
"no_coloring",
":",
"return",
"s",
"return",
"\"{begin}{s}{reset}\"",
".",
"format",
"(",
"begin",
"=",
"color",
",",
"s",
"=",
"s",
",",
"reset",
"=",
"Colors",
".",
"RESET",
")"
] | Formats a string with color | [
"Formats",
"a",
"string",
"with",
"color"
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/coloring.py#L42-L46 | valid |
frascoweb/frasco-models | frasco_models/backends/mongoengine.py | Document.reload | def reload(self, *fields, **kwargs):
"""Reloads all attributes from the database.
:param fields: (optional) args list of fields to reload
:param max_depth: (optional) depth of dereferencing to follow
.. versionadded:: 0.1.2
.. versionchanged:: 0.6 Now chainable
.. versionchanged:: 0.9 Can provide specific fields to reload
"""
max_depth = 1
if fields and isinstance(fields[0], int):
max_depth = fields[0]
fields = fields[1:]
elif "max_depth" in kwargs:
max_depth = kwargs["max_depth"]
if not self.pk:
raise self.DoesNotExist("Document does not exist")
obj = self._qs.read_preference(ReadPreference.PRIMARY).filter(
**self._object_key).only(*fields).limit(1
).select_related(max_depth=max_depth)
if obj:
obj = obj[0]
else:
raise self.DoesNotExist("Document does not exist")
for field in self._fields_ordered:
if not fields or field in fields:
try:
setattr(self, field, self._reload(field, obj[field]))
except KeyError:
# If field is removed from the database while the object
# is in memory, a reload would cause a KeyError
# i.e. obj.update(unset__field=1) followed by obj.reload()
delattr(self, field)
# BUG FIX BY US HERE:
if not fields:
self._changed_fields = obj._changed_fields
else:
for field in fields:
field = self._db_field_map.get(field, field)
if field in self._changed_fields:
self._changed_fields.remove(field)
self._created = False
return self | python | def reload(self, *fields, **kwargs):
"""Reloads all attributes from the database.
:param fields: (optional) args list of fields to reload
:param max_depth: (optional) depth of dereferencing to follow
.. versionadded:: 0.1.2
.. versionchanged:: 0.6 Now chainable
.. versionchanged:: 0.9 Can provide specific fields to reload
"""
max_depth = 1
if fields and isinstance(fields[0], int):
max_depth = fields[0]
fields = fields[1:]
elif "max_depth" in kwargs:
max_depth = kwargs["max_depth"]
if not self.pk:
raise self.DoesNotExist("Document does not exist")
obj = self._qs.read_preference(ReadPreference.PRIMARY).filter(
**self._object_key).only(*fields).limit(1
).select_related(max_depth=max_depth)
if obj:
obj = obj[0]
else:
raise self.DoesNotExist("Document does not exist")
for field in self._fields_ordered:
if not fields or field in fields:
try:
setattr(self, field, self._reload(field, obj[field]))
except KeyError:
# If field is removed from the database while the object
# is in memory, a reload would cause a KeyError
# i.e. obj.update(unset__field=1) followed by obj.reload()
delattr(self, field)
# BUG FIX BY US HERE:
if not fields:
self._changed_fields = obj._changed_fields
else:
for field in fields:
field = self._db_field_map.get(field, field)
if field in self._changed_fields:
self._changed_fields.remove(field)
self._created = False
return self | [
"def",
"reload",
"(",
"self",
",",
"*",
"fields",
",",
"*",
"*",
"kwargs",
")",
":",
"max_depth",
"=",
"1",
"if",
"fields",
"and",
"isinstance",
"(",
"fields",
"[",
"0",
"]",
",",
"int",
")",
":",
"max_depth",
"=",
"fields",
"[",
"0",
"]",
"fields",
"=",
"fields",
"[",
"1",
":",
"]",
"elif",
"\"max_depth\"",
"in",
"kwargs",
":",
"max_depth",
"=",
"kwargs",
"[",
"\"max_depth\"",
"]",
"if",
"not",
"self",
".",
"pk",
":",
"raise",
"self",
".",
"DoesNotExist",
"(",
"\"Document does not exist\"",
")",
"obj",
"=",
"self",
".",
"_qs",
".",
"read_preference",
"(",
"ReadPreference",
".",
"PRIMARY",
")",
".",
"filter",
"(",
"*",
"*",
"self",
".",
"_object_key",
")",
".",
"only",
"(",
"*",
"fields",
")",
".",
"limit",
"(",
"1",
")",
".",
"select_related",
"(",
"max_depth",
"=",
"max_depth",
")",
"if",
"obj",
":",
"obj",
"=",
"obj",
"[",
"0",
"]",
"else",
":",
"raise",
"self",
".",
"DoesNotExist",
"(",
"\"Document does not exist\"",
")",
"for",
"field",
"in",
"self",
".",
"_fields_ordered",
":",
"if",
"not",
"fields",
"or",
"field",
"in",
"fields",
":",
"try",
":",
"setattr",
"(",
"self",
",",
"field",
",",
"self",
".",
"_reload",
"(",
"field",
",",
"obj",
"[",
"field",
"]",
")",
")",
"except",
"KeyError",
":",
"# If field is removed from the database while the object",
"# is in memory, a reload would cause a KeyError",
"# i.e. obj.update(unset__field=1) followed by obj.reload()",
"delattr",
"(",
"self",
",",
"field",
")",
"# BUG FIX BY US HERE:",
"if",
"not",
"fields",
":",
"self",
".",
"_changed_fields",
"=",
"obj",
".",
"_changed_fields",
"else",
":",
"for",
"field",
"in",
"fields",
":",
"field",
"=",
"self",
".",
"_db_field_map",
".",
"get",
"(",
"field",
",",
"field",
")",
"if",
"field",
"in",
"self",
".",
"_changed_fields",
":",
"self",
".",
"_changed_fields",
".",
"remove",
"(",
"field",
")",
"self",
".",
"_created",
"=",
"False",
"return",
"self"
] | Reloads all attributes from the database.
:param fields: (optional) args list of fields to reload
:param max_depth: (optional) depth of dereferencing to follow
.. versionadded:: 0.1.2
.. versionchanged:: 0.6 Now chainable
.. versionchanged:: 0.9 Can provide specific fields to reload | [
"Reloads",
"all",
"attributes",
"from",
"the",
"database",
".",
":",
"param",
"fields",
":",
"(",
"optional",
")",
"args",
"list",
"of",
"fields",
"to",
"reload",
":",
"param",
"max_depth",
":",
"(",
"optional",
")",
"depth",
"of",
"dereferencing",
"to",
"follow",
"..",
"versionadded",
"::",
"0",
".",
"1",
".",
"2",
"..",
"versionchanged",
"::",
"0",
".",
"6",
"Now",
"chainable",
"..",
"versionchanged",
"::",
"0",
".",
"9",
"Can",
"provide",
"specific",
"fields",
"to",
"reload"
] | f7c1e14424cadf3dc07c2bd81cc32b0fd046ccba | https://github.com/frascoweb/frasco-models/blob/f7c1e14424cadf3dc07c2bd81cc32b0fd046ccba/frasco_models/backends/mongoengine.py#L45-L90 | valid |
joelfrederico/SciSalt | scisalt/imageprocess/pdf2png.py | pdf2png | def pdf2png(file_in, file_out):
"""
Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.)
Parameters
----------
file_in : str
The path to the pdf file to be converted.
file_out : str
The path to the png file to be written.
"""
command = 'convert -display 37.5 {} -resize 600 -append {}'.format(file_in, file_out)
_subprocess.call(_shlex.split(command)) | python | def pdf2png(file_in, file_out):
"""
Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.)
Parameters
----------
file_in : str
The path to the pdf file to be converted.
file_out : str
The path to the png file to be written.
"""
command = 'convert -display 37.5 {} -resize 600 -append {}'.format(file_in, file_out)
_subprocess.call(_shlex.split(command)) | [
"def",
"pdf2png",
"(",
"file_in",
",",
"file_out",
")",
":",
"command",
"=",
"'convert -display 37.5 {} -resize 600 -append {}'",
".",
"format",
"(",
"file_in",
",",
"file_out",
")",
"_subprocess",
".",
"call",
"(",
"_shlex",
".",
"split",
"(",
"command",
")",
")"
] | Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.)
Parameters
----------
file_in : str
The path to the pdf file to be converted.
file_out : str
The path to the png file to be written. | [
"Uses",
"ImageMagick",
"<http",
":",
"//",
"www",
".",
"imagemagick",
".",
"org",
"/",
">",
"_",
"to",
"convert",
"an",
"input",
"*",
"file_in",
"*",
"pdf",
"to",
"a",
"*",
"file_out",
"*",
"png",
".",
"(",
"Untested",
"with",
"other",
"formats",
".",
")"
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/imageprocess/pdf2png.py#L6-L19 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/users.py | Users.get_user | def get_user(self, user_id):
"""
Returns user profile data.
http://dev.wheniwork.com/#get-existing-user
"""
url = "/2/users/%s" % user_id
return self.user_from_json(self._get_resource(url)["user"]) | python | def get_user(self, user_id):
"""
Returns user profile data.
http://dev.wheniwork.com/#get-existing-user
"""
url = "/2/users/%s" % user_id
return self.user_from_json(self._get_resource(url)["user"]) | [
"def",
"get_user",
"(",
"self",
",",
"user_id",
")",
":",
"url",
"=",
"\"/2/users/%s\"",
"%",
"user_id",
"return",
"self",
".",
"user_from_json",
"(",
"self",
".",
"_get_resource",
"(",
"url",
")",
"[",
"\"user\"",
"]",
")"
] | Returns user profile data.
http://dev.wheniwork.com/#get-existing-user | [
"Returns",
"user",
"profile",
"data",
"."
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/users.py#L8-L16 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/users.py | Users.get_users | def get_users(self, params={}):
"""
Returns a list of users.
http://dev.wheniwork.com/#listing-users
"""
param_list = [(k, params[k]) for k in sorted(params)]
url = "/2/users/?%s" % urlencode(param_list)
data = self._get_resource(url)
users = []
for entry in data["users"]:
users.append(self.user_from_json(entry))
return users | python | def get_users(self, params={}):
"""
Returns a list of users.
http://dev.wheniwork.com/#listing-users
"""
param_list = [(k, params[k]) for k in sorted(params)]
url = "/2/users/?%s" % urlencode(param_list)
data = self._get_resource(url)
users = []
for entry in data["users"]:
users.append(self.user_from_json(entry))
return users | [
"def",
"get_users",
"(",
"self",
",",
"params",
"=",
"{",
"}",
")",
":",
"param_list",
"=",
"[",
"(",
"k",
",",
"params",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"sorted",
"(",
"params",
")",
"]",
"url",
"=",
"\"/2/users/?%s\"",
"%",
"urlencode",
"(",
"param_list",
")",
"data",
"=",
"self",
".",
"_get_resource",
"(",
"url",
")",
"users",
"=",
"[",
"]",
"for",
"entry",
"in",
"data",
"[",
"\"users\"",
"]",
":",
"users",
".",
"append",
"(",
"self",
".",
"user_from_json",
"(",
"entry",
")",
")",
"return",
"users"
] | Returns a list of users.
http://dev.wheniwork.com/#listing-users | [
"Returns",
"a",
"list",
"of",
"users",
"."
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/users.py#L18-L32 | valid |
eykd/paved | paved/util.py | _setVirtualEnv | def _setVirtualEnv():
"""Attempt to set the virtualenv activate command, if it hasn't been specified.
"""
try:
activate = options.virtualenv.activate_cmd
except AttributeError:
activate = None
if activate is None:
virtualenv = path(os.environ.get('VIRTUAL_ENV', ''))
if not virtualenv:
virtualenv = options.paved.cwd
else:
virtualenv = path(virtualenv)
activate = virtualenv / 'bin' / 'activate'
if activate.exists():
info('Using default virtualenv at %s' % activate)
options.setdotted('virtualenv.activate_cmd', 'source %s' % activate) | python | def _setVirtualEnv():
"""Attempt to set the virtualenv activate command, if it hasn't been specified.
"""
try:
activate = options.virtualenv.activate_cmd
except AttributeError:
activate = None
if activate is None:
virtualenv = path(os.environ.get('VIRTUAL_ENV', ''))
if not virtualenv:
virtualenv = options.paved.cwd
else:
virtualenv = path(virtualenv)
activate = virtualenv / 'bin' / 'activate'
if activate.exists():
info('Using default virtualenv at %s' % activate)
options.setdotted('virtualenv.activate_cmd', 'source %s' % activate) | [
"def",
"_setVirtualEnv",
"(",
")",
":",
"try",
":",
"activate",
"=",
"options",
".",
"virtualenv",
".",
"activate_cmd",
"except",
"AttributeError",
":",
"activate",
"=",
"None",
"if",
"activate",
"is",
"None",
":",
"virtualenv",
"=",
"path",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'VIRTUAL_ENV'",
",",
"''",
")",
")",
"if",
"not",
"virtualenv",
":",
"virtualenv",
"=",
"options",
".",
"paved",
".",
"cwd",
"else",
":",
"virtualenv",
"=",
"path",
"(",
"virtualenv",
")",
"activate",
"=",
"virtualenv",
"/",
"'bin'",
"/",
"'activate'",
"if",
"activate",
".",
"exists",
"(",
")",
":",
"info",
"(",
"'Using default virtualenv at %s'",
"%",
"activate",
")",
"options",
".",
"setdotted",
"(",
"'virtualenv.activate_cmd'",
",",
"'source %s'",
"%",
"activate",
")"
] | Attempt to set the virtualenv activate command, if it hasn't been specified. | [
"Attempt",
"to",
"set",
"the",
"virtualenv",
"activate",
"command",
"if",
"it",
"hasn",
"t",
"been",
"specified",
"."
] | f04f8a4248c571f3d5ce882b325884a3e5d80203 | https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L14-L33 | valid |
eykd/paved | paved/util.py | shv | def shv(command, capture=False, ignore_error=False, cwd=None):
"""Run the given command inside the virtual environment, if available:
"""
_setVirtualEnv()
try:
command = "%s; %s" % (options.virtualenv.activate_cmd, command)
except AttributeError:
pass
return bash(command, capture=capture, ignore_error=ignore_error, cwd=cwd) | python | def shv(command, capture=False, ignore_error=False, cwd=None):
"""Run the given command inside the virtual environment, if available:
"""
_setVirtualEnv()
try:
command = "%s; %s" % (options.virtualenv.activate_cmd, command)
except AttributeError:
pass
return bash(command, capture=capture, ignore_error=ignore_error, cwd=cwd) | [
"def",
"shv",
"(",
"command",
",",
"capture",
"=",
"False",
",",
"ignore_error",
"=",
"False",
",",
"cwd",
"=",
"None",
")",
":",
"_setVirtualEnv",
"(",
")",
"try",
":",
"command",
"=",
"\"%s; %s\"",
"%",
"(",
"options",
".",
"virtualenv",
".",
"activate_cmd",
",",
"command",
")",
"except",
"AttributeError",
":",
"pass",
"return",
"bash",
"(",
"command",
",",
"capture",
"=",
"capture",
",",
"ignore_error",
"=",
"ignore_error",
",",
"cwd",
"=",
"cwd",
")"
] | Run the given command inside the virtual environment, if available: | [
"Run",
"the",
"given",
"command",
"inside",
"the",
"virtual",
"environment",
"if",
"available",
":"
] | f04f8a4248c571f3d5ce882b325884a3e5d80203 | https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L85-L93 | valid |
eykd/paved | paved/util.py | update | def update(dst, src):
"""Recursively update the destination dict-like object with the source dict-like object.
Useful for merging options and Bunches together!
Based on:
http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1
"""
stack = [(dst, src)]
def isdict(o):
return hasattr(o, 'keys')
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if isdict(current_src[key]) and isdict(current_dst[key]):
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst | python | def update(dst, src):
"""Recursively update the destination dict-like object with the source dict-like object.
Useful for merging options and Bunches together!
Based on:
http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1
"""
stack = [(dst, src)]
def isdict(o):
return hasattr(o, 'keys')
while stack:
current_dst, current_src = stack.pop()
for key in current_src:
if key not in current_dst:
current_dst[key] = current_src[key]
else:
if isdict(current_src[key]) and isdict(current_dst[key]):
stack.append((current_dst[key], current_src[key]))
else:
current_dst[key] = current_src[key]
return dst | [
"def",
"update",
"(",
"dst",
",",
"src",
")",
":",
"stack",
"=",
"[",
"(",
"dst",
",",
"src",
")",
"]",
"def",
"isdict",
"(",
"o",
")",
":",
"return",
"hasattr",
"(",
"o",
",",
"'keys'",
")",
"while",
"stack",
":",
"current_dst",
",",
"current_src",
"=",
"stack",
".",
"pop",
"(",
")",
"for",
"key",
"in",
"current_src",
":",
"if",
"key",
"not",
"in",
"current_dst",
":",
"current_dst",
"[",
"key",
"]",
"=",
"current_src",
"[",
"key",
"]",
"else",
":",
"if",
"isdict",
"(",
"current_src",
"[",
"key",
"]",
")",
"and",
"isdict",
"(",
"current_dst",
"[",
"key",
"]",
")",
":",
"stack",
".",
"append",
"(",
"(",
"current_dst",
"[",
"key",
"]",
",",
"current_src",
"[",
"key",
"]",
")",
")",
"else",
":",
"current_dst",
"[",
"key",
"]",
"=",
"current_src",
"[",
"key",
"]",
"return",
"dst"
] | Recursively update the destination dict-like object with the source dict-like object.
Useful for merging options and Bunches together!
Based on:
http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1 | [
"Recursively",
"update",
"the",
"destination",
"dict",
"-",
"like",
"object",
"with",
"the",
"source",
"dict",
"-",
"like",
"object",
"."
] | f04f8a4248c571f3d5ce882b325884a3e5d80203 | https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L96-L119 | valid |
eykd/paved | paved/util.py | pip_install | def pip_install(*args):
"""Send the given arguments to `pip install`.
"""
download_cache = ('--download-cache=%s ' % options.paved.pip.download_cache) if options.paved.pip.download_cache else ''
shv('pip install %s%s' % (download_cache, ' '.join(args))) | python | def pip_install(*args):
"""Send the given arguments to `pip install`.
"""
download_cache = ('--download-cache=%s ' % options.paved.pip.download_cache) if options.paved.pip.download_cache else ''
shv('pip install %s%s' % (download_cache, ' '.join(args))) | [
"def",
"pip_install",
"(",
"*",
"args",
")",
":",
"download_cache",
"=",
"(",
"'--download-cache=%s '",
"%",
"options",
".",
"paved",
".",
"pip",
".",
"download_cache",
")",
"if",
"options",
".",
"paved",
".",
"pip",
".",
"download_cache",
"else",
"''",
"shv",
"(",
"'pip install %s%s'",
"%",
"(",
"download_cache",
",",
"' '",
".",
"join",
"(",
"args",
")",
")",
")"
] | Send the given arguments to `pip install`. | [
"Send",
"the",
"given",
"arguments",
"to",
"pip",
"install",
"."
] | f04f8a4248c571f3d5ce882b325884a3e5d80203 | https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L132-L136 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/__init__.py | WhenIWork._get_resource | def _get_resource(self, url, data_key=None):
"""
When I Work GET method. Return representation of the requested
resource.
"""
headers = {"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().getURL(url, headers)
if response.status != 200:
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | python | def _get_resource(self, url, data_key=None):
"""
When I Work GET method. Return representation of the requested
resource.
"""
headers = {"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().getURL(url, headers)
if response.status != 200:
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | [
"def",
"_get_resource",
"(",
"self",
",",
"url",
",",
"data_key",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"\"Accept\"",
":",
"\"application/json\"",
"}",
"if",
"self",
".",
"token",
":",
"headers",
"[",
"\"W-Token\"",
"]",
"=",
"\"%s\"",
"%",
"self",
".",
"token",
"response",
"=",
"WhenIWork_DAO",
"(",
")",
".",
"getURL",
"(",
"url",
",",
"headers",
")",
"if",
"response",
".",
"status",
"!=",
"200",
":",
"raise",
"DataFailureException",
"(",
"url",
",",
"response",
".",
"status",
",",
"response",
".",
"data",
")",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"data",
")"
] | When I Work GET method. Return representation of the requested
resource. | [
"When",
"I",
"Work",
"GET",
"method",
".",
"Return",
"representation",
"of",
"the",
"requested",
"resource",
"."
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L26-L39 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/__init__.py | WhenIWork._put_resource | def _put_resource(self, url, body):
"""
When I Work PUT method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().putURL(url, headers, json.dumps(body))
if not (response.status == 200 or response.status == 201 or
response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | python | def _put_resource(self, url, body):
"""
When I Work PUT method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().putURL(url, headers, json.dumps(body))
if not (response.status == 200 or response.status == 201 or
response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | [
"def",
"_put_resource",
"(",
"self",
",",
"url",
",",
"body",
")",
":",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/json\"",
",",
"\"Accept\"",
":",
"\"application/json\"",
"}",
"if",
"self",
".",
"token",
":",
"headers",
"[",
"\"W-Token\"",
"]",
"=",
"\"%s\"",
"%",
"self",
".",
"token",
"response",
"=",
"WhenIWork_DAO",
"(",
")",
".",
"putURL",
"(",
"url",
",",
"headers",
",",
"json",
".",
"dumps",
"(",
"body",
")",
")",
"if",
"not",
"(",
"response",
".",
"status",
"==",
"200",
"or",
"response",
".",
"status",
"==",
"201",
"or",
"response",
".",
"status",
"==",
"204",
")",
":",
"raise",
"DataFailureException",
"(",
"url",
",",
"response",
".",
"status",
",",
"response",
".",
"data",
")",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"data",
")"
] | When I Work PUT method. | [
"When",
"I",
"Work",
"PUT",
"method",
"."
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L41-L55 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/__init__.py | WhenIWork._post_resource | def _post_resource(self, url, body):
"""
When I Work POST method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().postURL(url, headers, json.dumps(body))
if not (response.status == 200 or response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | python | def _post_resource(self, url, body):
"""
When I Work POST method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().postURL(url, headers, json.dumps(body))
if not (response.status == 200 or response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | [
"def",
"_post_resource",
"(",
"self",
",",
"url",
",",
"body",
")",
":",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/json\"",
",",
"\"Accept\"",
":",
"\"application/json\"",
"}",
"if",
"self",
".",
"token",
":",
"headers",
"[",
"\"W-Token\"",
"]",
"=",
"\"%s\"",
"%",
"self",
".",
"token",
"response",
"=",
"WhenIWork_DAO",
"(",
")",
".",
"postURL",
"(",
"url",
",",
"headers",
",",
"json",
".",
"dumps",
"(",
"body",
")",
")",
"if",
"not",
"(",
"response",
".",
"status",
"==",
"200",
"or",
"response",
".",
"status",
"==",
"204",
")",
":",
"raise",
"DataFailureException",
"(",
"url",
",",
"response",
".",
"status",
",",
"response",
".",
"data",
")",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"data",
")"
] | When I Work POST method. | [
"When",
"I",
"Work",
"POST",
"method",
"."
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L57-L70 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/__init__.py | WhenIWork._delete_resource | def _delete_resource(self, url):
"""
When I Work DELETE method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().deleteURL(url, headers)
if not (response.status == 200 or response.status == 201 or
response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | python | def _delete_resource(self, url):
"""
When I Work DELETE method.
"""
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().deleteURL(url, headers)
if not (response.status == 200 or response.status == 201 or
response.status == 204):
raise DataFailureException(url, response.status, response.data)
return json.loads(response.data) | [
"def",
"_delete_resource",
"(",
"self",
",",
"url",
")",
":",
"headers",
"=",
"{",
"\"Content-Type\"",
":",
"\"application/json\"",
",",
"\"Accept\"",
":",
"\"application/json\"",
"}",
"if",
"self",
".",
"token",
":",
"headers",
"[",
"\"W-Token\"",
"]",
"=",
"\"%s\"",
"%",
"self",
".",
"token",
"response",
"=",
"WhenIWork_DAO",
"(",
")",
".",
"deleteURL",
"(",
"url",
",",
"headers",
")",
"if",
"not",
"(",
"response",
".",
"status",
"==",
"200",
"or",
"response",
".",
"status",
"==",
"201",
"or",
"response",
".",
"status",
"==",
"204",
")",
":",
"raise",
"DataFailureException",
"(",
"url",
",",
"response",
".",
"status",
",",
"response",
".",
"data",
")",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"data",
")"
] | When I Work DELETE method. | [
"When",
"I",
"Work",
"DELETE",
"method",
"."
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L72-L86 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/shifts.py | Shifts.get_shifts | def get_shifts(self, params={}):
"""
List shifts
http://dev.wheniwork.com/#listing-shifts
"""
param_list = [(k, params[k]) for k in sorted(params)]
url = "/2/shifts/?%s" % urlencode(param_list)
data = self._get_resource(url)
shifts = []
locations = {}
sites = {}
positions = {}
users = {}
for entry in data.get("locations", []):
location = Locations.location_from_json(entry)
locations[location.location_id] = location
for entry in data.get("sites", []):
site = Sites.site_from_json(entry)
sites[site.site_id] = site
for entry in data.get("positions", []):
position = Positions.position_from_json(entry)
positions[position.position_id] = position
for entry in data.get("users", []):
user = Users.user_from_json(entry)
users[user.user_id] = user
for entry in data["shifts"]:
shift = self.shift_from_json(entry)
shifts.append(shift)
for shift in shifts:
shift.location = locations.get(shift.location_id, None)
shift.site = sites.get(shift.site_id, None)
shift.position = positions.get(shift.position_id, None)
shift.user = users.get(shift.user_id, None)
return shifts | python | def get_shifts(self, params={}):
"""
List shifts
http://dev.wheniwork.com/#listing-shifts
"""
param_list = [(k, params[k]) for k in sorted(params)]
url = "/2/shifts/?%s" % urlencode(param_list)
data = self._get_resource(url)
shifts = []
locations = {}
sites = {}
positions = {}
users = {}
for entry in data.get("locations", []):
location = Locations.location_from_json(entry)
locations[location.location_id] = location
for entry in data.get("sites", []):
site = Sites.site_from_json(entry)
sites[site.site_id] = site
for entry in data.get("positions", []):
position = Positions.position_from_json(entry)
positions[position.position_id] = position
for entry in data.get("users", []):
user = Users.user_from_json(entry)
users[user.user_id] = user
for entry in data["shifts"]:
shift = self.shift_from_json(entry)
shifts.append(shift)
for shift in shifts:
shift.location = locations.get(shift.location_id, None)
shift.site = sites.get(shift.site_id, None)
shift.position = positions.get(shift.position_id, None)
shift.user = users.get(shift.user_id, None)
return shifts | [
"def",
"get_shifts",
"(",
"self",
",",
"params",
"=",
"{",
"}",
")",
":",
"param_list",
"=",
"[",
"(",
"k",
",",
"params",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"sorted",
"(",
"params",
")",
"]",
"url",
"=",
"\"/2/shifts/?%s\"",
"%",
"urlencode",
"(",
"param_list",
")",
"data",
"=",
"self",
".",
"_get_resource",
"(",
"url",
")",
"shifts",
"=",
"[",
"]",
"locations",
"=",
"{",
"}",
"sites",
"=",
"{",
"}",
"positions",
"=",
"{",
"}",
"users",
"=",
"{",
"}",
"for",
"entry",
"in",
"data",
".",
"get",
"(",
"\"locations\"",
",",
"[",
"]",
")",
":",
"location",
"=",
"Locations",
".",
"location_from_json",
"(",
"entry",
")",
"locations",
"[",
"location",
".",
"location_id",
"]",
"=",
"location",
"for",
"entry",
"in",
"data",
".",
"get",
"(",
"\"sites\"",
",",
"[",
"]",
")",
":",
"site",
"=",
"Sites",
".",
"site_from_json",
"(",
"entry",
")",
"sites",
"[",
"site",
".",
"site_id",
"]",
"=",
"site",
"for",
"entry",
"in",
"data",
".",
"get",
"(",
"\"positions\"",
",",
"[",
"]",
")",
":",
"position",
"=",
"Positions",
".",
"position_from_json",
"(",
"entry",
")",
"positions",
"[",
"position",
".",
"position_id",
"]",
"=",
"position",
"for",
"entry",
"in",
"data",
".",
"get",
"(",
"\"users\"",
",",
"[",
"]",
")",
":",
"user",
"=",
"Users",
".",
"user_from_json",
"(",
"entry",
")",
"users",
"[",
"user",
".",
"user_id",
"]",
"=",
"user",
"for",
"entry",
"in",
"data",
"[",
"\"shifts\"",
"]",
":",
"shift",
"=",
"self",
".",
"shift_from_json",
"(",
"entry",
")",
"shifts",
".",
"append",
"(",
"shift",
")",
"for",
"shift",
"in",
"shifts",
":",
"shift",
".",
"location",
"=",
"locations",
".",
"get",
"(",
"shift",
".",
"location_id",
",",
"None",
")",
"shift",
".",
"site",
"=",
"sites",
".",
"get",
"(",
"shift",
".",
"site_id",
",",
"None",
")",
"shift",
".",
"position",
"=",
"positions",
".",
"get",
"(",
"shift",
".",
"position_id",
",",
"None",
")",
"shift",
".",
"user",
"=",
"users",
".",
"get",
"(",
"shift",
".",
"user_id",
",",
"None",
")",
"return",
"shifts"
] | List shifts
http://dev.wheniwork.com/#listing-shifts | [
"List",
"shifts"
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/shifts.py#L13-L50 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/shifts.py | Shifts.create_shift | def create_shift(self, params={}):
"""
Creates a shift
http://dev.wheniwork.com/#create/update-shift
"""
url = "/2/shifts/"
body = params
data = self._post_resource(url, body)
shift = self.shift_from_json(data["shift"])
return shift | python | def create_shift(self, params={}):
"""
Creates a shift
http://dev.wheniwork.com/#create/update-shift
"""
url = "/2/shifts/"
body = params
data = self._post_resource(url, body)
shift = self.shift_from_json(data["shift"])
return shift | [
"def",
"create_shift",
"(",
"self",
",",
"params",
"=",
"{",
"}",
")",
":",
"url",
"=",
"\"/2/shifts/\"",
"body",
"=",
"params",
"data",
"=",
"self",
".",
"_post_resource",
"(",
"url",
",",
"body",
")",
"shift",
"=",
"self",
".",
"shift_from_json",
"(",
"data",
"[",
"\"shift\"",
"]",
")",
"return",
"shift"
] | Creates a shift
http://dev.wheniwork.com/#create/update-shift | [
"Creates",
"a",
"shift"
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/shifts.py#L52-L64 | valid |
uw-it-cte/uw-restclients-wheniwork | uw_wheniwork/shifts.py | Shifts.delete_shifts | def delete_shifts(self, shifts):
"""
Delete existing shifts.
http://dev.wheniwork.com/#delete-shift
"""
url = "/2/shifts/?%s" % urlencode(
{'ids': ",".join(str(s) for s in shifts)})
data = self._delete_resource(url)
return data | python | def delete_shifts(self, shifts):
"""
Delete existing shifts.
http://dev.wheniwork.com/#delete-shift
"""
url = "/2/shifts/?%s" % urlencode(
{'ids': ",".join(str(s) for s in shifts)})
data = self._delete_resource(url)
return data | [
"def",
"delete_shifts",
"(",
"self",
",",
"shifts",
")",
":",
"url",
"=",
"\"/2/shifts/?%s\"",
"%",
"urlencode",
"(",
"{",
"'ids'",
":",
"\",\"",
".",
"join",
"(",
"str",
"(",
"s",
")",
"for",
"s",
"in",
"shifts",
")",
"}",
")",
"data",
"=",
"self",
".",
"_delete_resource",
"(",
"url",
")",
"return",
"data"
] | Delete existing shifts.
http://dev.wheniwork.com/#delete-shift | [
"Delete",
"existing",
"shifts",
"."
] | 0d3ca09d5bbe808fec12e5f943596570d33a1731 | https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/shifts.py#L66-L77 | valid |
tBaxter/tango-happenings | build/lib/happenings/models.py | EventManager.delete_past_events | def delete_past_events(self):
"""
Removes old events. This is provided largely as a convenience for maintenance
purposes (daily_cleanup). if an Event has passed by more than X days
as defined by Lapsed and has no related special events it will be deleted
to free up the event name and remove clutter.
For best results, set this up to run regularly as a cron job.
"""
lapsed = datetime.datetime.now() - datetime.timedelta(days=90)
for event in self.filter(start_date__lte=lapsed, featured=0, recap=''):
event.delete() | python | def delete_past_events(self):
"""
Removes old events. This is provided largely as a convenience for maintenance
purposes (daily_cleanup). if an Event has passed by more than X days
as defined by Lapsed and has no related special events it will be deleted
to free up the event name and remove clutter.
For best results, set this up to run regularly as a cron job.
"""
lapsed = datetime.datetime.now() - datetime.timedelta(days=90)
for event in self.filter(start_date__lte=lapsed, featured=0, recap=''):
event.delete() | [
"def",
"delete_past_events",
"(",
"self",
")",
":",
"lapsed",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"90",
")",
"for",
"event",
"in",
"self",
".",
"filter",
"(",
"start_date__lte",
"=",
"lapsed",
",",
"featured",
"=",
"0",
",",
"recap",
"=",
"''",
")",
":",
"event",
".",
"delete",
"(",
")"
] | Removes old events. This is provided largely as a convenience for maintenance
purposes (daily_cleanup). if an Event has passed by more than X days
as defined by Lapsed and has no related special events it will be deleted
to free up the event name and remove clutter.
For best results, set this up to run regularly as a cron job. | [
"Removes",
"old",
"events",
".",
"This",
"is",
"provided",
"largely",
"as",
"a",
"convenience",
"for",
"maintenance",
"purposes",
"(",
"daily_cleanup",
")",
".",
"if",
"an",
"Event",
"has",
"passed",
"by",
"more",
"than",
"X",
"days",
"as",
"defined",
"by",
"Lapsed",
"and",
"has",
"no",
"related",
"special",
"events",
"it",
"will",
"be",
"deleted",
"to",
"free",
"up",
"the",
"event",
"name",
"and",
"remove",
"clutter",
".",
"For",
"best",
"results",
"set",
"this",
"up",
"to",
"run",
"regularly",
"as",
"a",
"cron",
"job",
"."
] | cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2 | https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L56-L66 | valid |
tBaxter/tango-happenings | build/lib/happenings/models.py | Event.recently_ended | def recently_ended(self):
"""
Determines if event ended recently (within 5 days).
Useful for attending list.
"""
if self.ended():
end_date = self.end_date if self.end_date else self.start_date
if end_date >= offset.date():
return True | python | def recently_ended(self):
"""
Determines if event ended recently (within 5 days).
Useful for attending list.
"""
if self.ended():
end_date = self.end_date if self.end_date else self.start_date
if end_date >= offset.date():
return True | [
"def",
"recently_ended",
"(",
"self",
")",
":",
"if",
"self",
".",
"ended",
"(",
")",
":",
"end_date",
"=",
"self",
".",
"end_date",
"if",
"self",
".",
"end_date",
"else",
"self",
".",
"start_date",
"if",
"end_date",
">=",
"offset",
".",
"date",
"(",
")",
":",
"return",
"True"
] | Determines if event ended recently (within 5 days).
Useful for attending list. | [
"Determines",
"if",
"event",
"ended",
"recently",
"(",
"within",
"5",
"days",
")",
".",
"Useful",
"for",
"attending",
"list",
"."
] | cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2 | https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L159-L167 | valid |
tBaxter/tango-happenings | build/lib/happenings/models.py | Event.all_comments | def all_comments(self):
"""
Returns combined list of event and update comments.
"""
ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='event')
update_ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='update')
update_ids = self.update_set.values_list('id', flat=True)
return Comment.objects.filter(
Q(content_type=ctype.id, object_pk=self.id) |
Q(content_type=update_ctype.id, object_pk__in=update_ids)
) | python | def all_comments(self):
"""
Returns combined list of event and update comments.
"""
ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='event')
update_ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='update')
update_ids = self.update_set.values_list('id', flat=True)
return Comment.objects.filter(
Q(content_type=ctype.id, object_pk=self.id) |
Q(content_type=update_ctype.id, object_pk__in=update_ids)
) | [
"def",
"all_comments",
"(",
"self",
")",
":",
"ctype",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label__exact",
"=",
"\"happenings\"",
",",
"model__exact",
"=",
"'event'",
")",
"update_ctype",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label__exact",
"=",
"\"happenings\"",
",",
"model__exact",
"=",
"'update'",
")",
"update_ids",
"=",
"self",
".",
"update_set",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
"return",
"Comment",
".",
"objects",
".",
"filter",
"(",
"Q",
"(",
"content_type",
"=",
"ctype",
".",
"id",
",",
"object_pk",
"=",
"self",
".",
"id",
")",
"|",
"Q",
"(",
"content_type",
"=",
"update_ctype",
".",
"id",
",",
"object_pk__in",
"=",
"update_ids",
")",
")"
] | Returns combined list of event and update comments. | [
"Returns",
"combined",
"list",
"of",
"event",
"and",
"update",
"comments",
"."
] | cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2 | https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L186-L197 | valid |
tBaxter/tango-happenings | build/lib/happenings/models.py | Event.get_all_images | def get_all_images(self):
"""
Returns chained list of event and update images.
"""
self_imgs = self.image_set.all()
update_ids = self.update_set.values_list('id', flat=True)
u_images = UpdateImage.objects.filter(update__id__in=update_ids)
return list(chain(self_imgs, u_images)) | python | def get_all_images(self):
"""
Returns chained list of event and update images.
"""
self_imgs = self.image_set.all()
update_ids = self.update_set.values_list('id', flat=True)
u_images = UpdateImage.objects.filter(update__id__in=update_ids)
return list(chain(self_imgs, u_images)) | [
"def",
"get_all_images",
"(",
"self",
")",
":",
"self_imgs",
"=",
"self",
".",
"image_set",
".",
"all",
"(",
")",
"update_ids",
"=",
"self",
".",
"update_set",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
"u_images",
"=",
"UpdateImage",
".",
"objects",
".",
"filter",
"(",
"update__id__in",
"=",
"update_ids",
")",
"return",
"list",
"(",
"chain",
"(",
"self_imgs",
",",
"u_images",
")",
")"
] | Returns chained list of event and update images. | [
"Returns",
"chained",
"list",
"of",
"event",
"and",
"update",
"images",
"."
] | cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2 | https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L217-L225 | valid |
tBaxter/tango-happenings | build/lib/happenings/models.py | Event.get_all_images_count | def get_all_images_count(self):
"""
Gets count of all images from both event and updates.
"""
self_imgs = self.image_set.count()
update_ids = self.update_set.values_list('id', flat=True)
u_images = UpdateImage.objects.filter(update__id__in=update_ids).count()
count = self_imgs + u_images
return count | python | def get_all_images_count(self):
"""
Gets count of all images from both event and updates.
"""
self_imgs = self.image_set.count()
update_ids = self.update_set.values_list('id', flat=True)
u_images = UpdateImage.objects.filter(update__id__in=update_ids).count()
count = self_imgs + u_images
return count | [
"def",
"get_all_images_count",
"(",
"self",
")",
":",
"self_imgs",
"=",
"self",
".",
"image_set",
".",
"count",
"(",
")",
"update_ids",
"=",
"self",
".",
"update_set",
".",
"values_list",
"(",
"'id'",
",",
"flat",
"=",
"True",
")",
"u_images",
"=",
"UpdateImage",
".",
"objects",
".",
"filter",
"(",
"update__id__in",
"=",
"update_ids",
")",
".",
"count",
"(",
")",
"count",
"=",
"self_imgs",
"+",
"u_images",
"return",
"count"
] | Gets count of all images from both event and updates. | [
"Gets",
"count",
"of",
"all",
"images",
"from",
"both",
"event",
"and",
"updates",
"."
] | cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2 | https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L227-L236 | valid |
tBaxter/tango-happenings | build/lib/happenings/models.py | Event.get_top_assets | def get_top_assets(self):
"""
Gets images and videos to populate top assets.
Map is built separately.
"""
images = self.get_all_images()[0:14]
video = []
if supports_video:
video = self.eventvideo_set.all()[0:10]
return list(chain(images, video))[0:15] | python | def get_top_assets(self):
"""
Gets images and videos to populate top assets.
Map is built separately.
"""
images = self.get_all_images()[0:14]
video = []
if supports_video:
video = self.eventvideo_set.all()[0:10]
return list(chain(images, video))[0:15] | [
"def",
"get_top_assets",
"(",
"self",
")",
":",
"images",
"=",
"self",
".",
"get_all_images",
"(",
")",
"[",
"0",
":",
"14",
"]",
"video",
"=",
"[",
"]",
"if",
"supports_video",
":",
"video",
"=",
"self",
".",
"eventvideo_set",
".",
"all",
"(",
")",
"[",
"0",
":",
"10",
"]",
"return",
"list",
"(",
"chain",
"(",
"images",
",",
"video",
")",
")",
"[",
"0",
":",
"15",
"]"
] | Gets images and videos to populate top assets.
Map is built separately. | [
"Gets",
"images",
"and",
"videos",
"to",
"populate",
"top",
"assets",
"."
] | cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2 | https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L238-L249 | valid |
joelfrederico/SciSalt | scisalt/matplotlib/plot_featured.py | plot_featured | def plot_featured(*args, **kwargs):
"""
Wrapper for matplotlib.pyplot.plot() / errorbar().
Takes options:
* 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here.
* 'fig': figure to use.
* 'figlabel': figure label.
* 'legend': legend location.
* 'toplabel': top label of plot.
* 'xlabel': x-label of plot.
* 'ylabel': y-label of plot.
"""
# Strip off options specific to plot_featured
toplabel = kwargs.pop('toplabel', None)
xlabel = kwargs.pop('xlabel', None)
ylabel = kwargs.pop('ylabel', None)
legend = kwargs.pop('legend', None)
error = kwargs.pop('error', None)
# save = kwargs.pop('save', False)
figlabel = kwargs.pop('figlabel', None)
fig = kwargs.pop('fig', None)
if figlabel is not None:
fig = _figure(figlabel)
elif fig is None:
try:
fig = _plt.gcf()
except:
fig = _plt.fig()
# Pass everything else to plot
if error is None:
_plt.plot(*args, **kwargs)
else:
_plt.errorbar(*args, **kwargs)
# Format plot as desired
_addlabel(toplabel, xlabel, ylabel, fig=fig)
if legend is not None:
_plt.legend(legend)
return fig | python | def plot_featured(*args, **kwargs):
"""
Wrapper for matplotlib.pyplot.plot() / errorbar().
Takes options:
* 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here.
* 'fig': figure to use.
* 'figlabel': figure label.
* 'legend': legend location.
* 'toplabel': top label of plot.
* 'xlabel': x-label of plot.
* 'ylabel': y-label of plot.
"""
# Strip off options specific to plot_featured
toplabel = kwargs.pop('toplabel', None)
xlabel = kwargs.pop('xlabel', None)
ylabel = kwargs.pop('ylabel', None)
legend = kwargs.pop('legend', None)
error = kwargs.pop('error', None)
# save = kwargs.pop('save', False)
figlabel = kwargs.pop('figlabel', None)
fig = kwargs.pop('fig', None)
if figlabel is not None:
fig = _figure(figlabel)
elif fig is None:
try:
fig = _plt.gcf()
except:
fig = _plt.fig()
# Pass everything else to plot
if error is None:
_plt.plot(*args, **kwargs)
else:
_plt.errorbar(*args, **kwargs)
# Format plot as desired
_addlabel(toplabel, xlabel, ylabel, fig=fig)
if legend is not None:
_plt.legend(legend)
return fig | [
"def",
"plot_featured",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Strip off options specific to plot_featured",
"toplabel",
"=",
"kwargs",
".",
"pop",
"(",
"'toplabel'",
",",
"None",
")",
"xlabel",
"=",
"kwargs",
".",
"pop",
"(",
"'xlabel'",
",",
"None",
")",
"ylabel",
"=",
"kwargs",
".",
"pop",
"(",
"'ylabel'",
",",
"None",
")",
"legend",
"=",
"kwargs",
".",
"pop",
"(",
"'legend'",
",",
"None",
")",
"error",
"=",
"kwargs",
".",
"pop",
"(",
"'error'",
",",
"None",
")",
"# save = kwargs.pop('save', False)",
"figlabel",
"=",
"kwargs",
".",
"pop",
"(",
"'figlabel'",
",",
"None",
")",
"fig",
"=",
"kwargs",
".",
"pop",
"(",
"'fig'",
",",
"None",
")",
"if",
"figlabel",
"is",
"not",
"None",
":",
"fig",
"=",
"_figure",
"(",
"figlabel",
")",
"elif",
"fig",
"is",
"None",
":",
"try",
":",
"fig",
"=",
"_plt",
".",
"gcf",
"(",
")",
"except",
":",
"fig",
"=",
"_plt",
".",
"fig",
"(",
")",
"# Pass everything else to plot",
"if",
"error",
"is",
"None",
":",
"_plt",
".",
"plot",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"_plt",
".",
"errorbar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Format plot as desired",
"_addlabel",
"(",
"toplabel",
",",
"xlabel",
",",
"ylabel",
",",
"fig",
"=",
"fig",
")",
"if",
"legend",
"is",
"not",
"None",
":",
"_plt",
".",
"legend",
"(",
"legend",
")",
"return",
"fig"
] | Wrapper for matplotlib.pyplot.plot() / errorbar().
Takes options:
* 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here.
* 'fig': figure to use.
* 'figlabel': figure label.
* 'legend': legend location.
* 'toplabel': top label of plot.
* 'xlabel': x-label of plot.
* 'ylabel': y-label of plot. | [
"Wrapper",
"for",
"matplotlib",
".",
"pyplot",
".",
"plot",
"()",
"/",
"errorbar",
"()",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/plot_featured.py#L11-L55 | valid |
minttu/tmc.py | tmc/ui/spinner.py | Spinner.decorate | def decorate(msg="", waitmsg="Please wait"):
"""
Decorated methods progress will be displayed to the user as a spinner.
Mostly for slower functions that do some network IO.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
spin = Spinner(msg=msg, waitmsg=waitmsg)
spin.start()
a = None
try:
a = func(*args, **kwargs)
except Exception as e:
spin.msg = "Something went wrong: "
spin.stop_spinning()
spin.join()
raise e
spin.stop_spinning()
spin.join()
return a
return wrapper
return decorator | python | def decorate(msg="", waitmsg="Please wait"):
"""
Decorated methods progress will be displayed to the user as a spinner.
Mostly for slower functions that do some network IO.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
spin = Spinner(msg=msg, waitmsg=waitmsg)
spin.start()
a = None
try:
a = func(*args, **kwargs)
except Exception as e:
spin.msg = "Something went wrong: "
spin.stop_spinning()
spin.join()
raise e
spin.stop_spinning()
spin.join()
return a
return wrapper
return decorator | [
"def",
"decorate",
"(",
"msg",
"=",
"\"\"",
",",
"waitmsg",
"=",
"\"Please wait\"",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"spin",
"=",
"Spinner",
"(",
"msg",
"=",
"msg",
",",
"waitmsg",
"=",
"waitmsg",
")",
"spin",
".",
"start",
"(",
")",
"a",
"=",
"None",
"try",
":",
"a",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"spin",
".",
"msg",
"=",
"\"Something went wrong: \"",
"spin",
".",
"stop_spinning",
"(",
")",
"spin",
".",
"join",
"(",
")",
"raise",
"e",
"spin",
".",
"stop_spinning",
"(",
")",
"spin",
".",
"join",
"(",
")",
"return",
"a",
"return",
"wrapper",
"return",
"decorator"
] | Decorated methods progress will be displayed to the user as a spinner.
Mostly for slower functions that do some network IO. | [
"Decorated",
"methods",
"progress",
"will",
"be",
"displayed",
"to",
"the",
"user",
"as",
"a",
"spinner",
".",
"Mostly",
"for",
"slower",
"functions",
"that",
"do",
"some",
"network",
"IO",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/ui/spinner.py#L54-L78 | valid |
minttu/tmc.py | tmc/ui/menu.py | Menu.launch | def launch(title, items, selected=None):
"""
Launches a new menu. Wraps curses nicely so exceptions won't screw with
the terminal too much.
"""
resp = {"code": -1, "done": False}
curses.wrapper(Menu, title, items, selected, resp)
return resp | python | def launch(title, items, selected=None):
"""
Launches a new menu. Wraps curses nicely so exceptions won't screw with
the terminal too much.
"""
resp = {"code": -1, "done": False}
curses.wrapper(Menu, title, items, selected, resp)
return resp | [
"def",
"launch",
"(",
"title",
",",
"items",
",",
"selected",
"=",
"None",
")",
":",
"resp",
"=",
"{",
"\"code\"",
":",
"-",
"1",
",",
"\"done\"",
":",
"False",
"}",
"curses",
".",
"wrapper",
"(",
"Menu",
",",
"title",
",",
"items",
",",
"selected",
",",
"resp",
")",
"return",
"resp"
] | Launches a new menu. Wraps curses nicely so exceptions won't screw with
the terminal too much. | [
"Launches",
"a",
"new",
"menu",
".",
"Wraps",
"curses",
"nicely",
"so",
"exceptions",
"won",
"t",
"screw",
"with",
"the",
"terminal",
"too",
"much",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/ui/menu.py#L122-L129 | valid |
joelfrederico/SciSalt | scisalt/PWFA/ions.py | Ions.q | def q(self, x, q0):
"""
Numerically solved trajectory function for initial conditons :math:`q(0) = q_0` and :math:`q'(0) = 0`.
"""
y1_0 = q0
y0_0 = 0
y0 = [y0_0, y1_0]
y = _sp.integrate.odeint(self._func, y0, x, Dfun=self._gradient, rtol=self.rtol, atol=self.atol)
return y[:, 1] | python | def q(self, x, q0):
"""
Numerically solved trajectory function for initial conditons :math:`q(0) = q_0` and :math:`q'(0) = 0`.
"""
y1_0 = q0
y0_0 = 0
y0 = [y0_0, y1_0]
y = _sp.integrate.odeint(self._func, y0, x, Dfun=self._gradient, rtol=self.rtol, atol=self.atol)
return y[:, 1] | [
"def",
"q",
"(",
"self",
",",
"x",
",",
"q0",
")",
":",
"y1_0",
"=",
"q0",
"y0_0",
"=",
"0",
"y0",
"=",
"[",
"y0_0",
",",
"y1_0",
"]",
"y",
"=",
"_sp",
".",
"integrate",
".",
"odeint",
"(",
"self",
".",
"_func",
",",
"y0",
",",
"x",
",",
"Dfun",
"=",
"self",
".",
"_gradient",
",",
"rtol",
"=",
"self",
".",
"rtol",
",",
"atol",
"=",
"self",
".",
"atol",
")",
"return",
"y",
"[",
":",
",",
"1",
"]"
] | Numerically solved trajectory function for initial conditons :math:`q(0) = q_0` and :math:`q'(0) = 0`. | [
"Numerically",
"solved",
"trajectory",
"function",
"for",
"initial",
"conditons",
":",
"math",
":",
"q",
"(",
"0",
")",
"=",
"q_0",
"and",
":",
"math",
":",
"q",
"(",
"0",
")",
"=",
"0",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/ions.py#L93-L103 | valid |
cltrudeau/django-awl | awl/rankedmodel/models.py | RankedModel.save | def save(self, *args, **kwargs):
"""Overridden method that handles that re-ranking of objects and the
integrity of the ``rank`` field.
:param rerank:
Added parameter, if True will rerank other objects based on the
change in this save. Defaults to True.
"""
rerank = kwargs.pop('rerank', True)
if rerank:
if not self.id:
self._process_new_rank_obj()
elif self.rank == self._rank_at_load:
# nothing changed
pass
else:
self._process_moved_rank_obj()
super(RankedModel, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""Overridden method that handles that re-ranking of objects and the
integrity of the ``rank`` field.
:param rerank:
Added parameter, if True will rerank other objects based on the
change in this save. Defaults to True.
"""
rerank = kwargs.pop('rerank', True)
if rerank:
if not self.id:
self._process_new_rank_obj()
elif self.rank == self._rank_at_load:
# nothing changed
pass
else:
self._process_moved_rank_obj()
super(RankedModel, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"rerank",
"=",
"kwargs",
".",
"pop",
"(",
"'rerank'",
",",
"True",
")",
"if",
"rerank",
":",
"if",
"not",
"self",
".",
"id",
":",
"self",
".",
"_process_new_rank_obj",
"(",
")",
"elif",
"self",
".",
"rank",
"==",
"self",
".",
"_rank_at_load",
":",
"# nothing changed",
"pass",
"else",
":",
"self",
".",
"_process_moved_rank_obj",
"(",
")",
"super",
"(",
"RankedModel",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Overridden method that handles that re-ranking of objects and the
integrity of the ``rank`` field.
:param rerank:
Added parameter, if True will rerank other objects based on the
change in this save. Defaults to True. | [
"Overridden",
"method",
"that",
"handles",
"that",
"re",
"-",
"ranking",
"of",
"objects",
"and",
"the",
"integrity",
"of",
"the",
"rank",
"field",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/rankedmodel/models.py#L113-L131 | valid |
cltrudeau/django-awl | awl/rankedmodel/models.py | RankedModel.repack | def repack(self):
"""Removes any blank ranks in the order."""
items = self.grouped_filter().order_by('rank').select_for_update()
for count, item in enumerate(items):
item.rank = count + 1
item.save(rerank=False) | python | def repack(self):
"""Removes any blank ranks in the order."""
items = self.grouped_filter().order_by('rank').select_for_update()
for count, item in enumerate(items):
item.rank = count + 1
item.save(rerank=False) | [
"def",
"repack",
"(",
"self",
")",
":",
"items",
"=",
"self",
".",
"grouped_filter",
"(",
")",
".",
"order_by",
"(",
"'rank'",
")",
".",
"select_for_update",
"(",
")",
"for",
"count",
",",
"item",
"in",
"enumerate",
"(",
"items",
")",
":",
"item",
".",
"rank",
"=",
"count",
"+",
"1",
"item",
".",
"save",
"(",
"rerank",
"=",
"False",
")"
] | Removes any blank ranks in the order. | [
"Removes",
"any",
"blank",
"ranks",
"in",
"the",
"order",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/rankedmodel/models.py#L153-L158 | valid |
cltrudeau/django-awl | awl/utils.py | refetch_for_update | def refetch_for_update(obj):
"""Queries the database for the same object that is passed in, refetching
its contents and runs ``select_for_update()`` to lock the corresponding
row until the next commit.
:param obj:
Object to refetch
:returns:
Refreshed version of the object
"""
return obj.__class__.objects.select_for_update().get(id=obj.id) | python | def refetch_for_update(obj):
"""Queries the database for the same object that is passed in, refetching
its contents and runs ``select_for_update()`` to lock the corresponding
row until the next commit.
:param obj:
Object to refetch
:returns:
Refreshed version of the object
"""
return obj.__class__.objects.select_for_update().get(id=obj.id) | [
"def",
"refetch_for_update",
"(",
"obj",
")",
":",
"return",
"obj",
".",
"__class__",
".",
"objects",
".",
"select_for_update",
"(",
")",
".",
"get",
"(",
"id",
"=",
"obj",
".",
"id",
")"
] | Queries the database for the same object that is passed in, refetching
its contents and runs ``select_for_update()`` to lock the corresponding
row until the next commit.
:param obj:
Object to refetch
:returns:
Refreshed version of the object | [
"Queries",
"the",
"database",
"for",
"the",
"same",
"object",
"that",
"is",
"passed",
"in",
"refetching",
"its",
"contents",
"and",
"runs",
"select_for_update",
"()",
"to",
"lock",
"the",
"corresponding",
"row",
"until",
"the",
"next",
"commit",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/utils.py#L46-L56 | valid |
cltrudeau/django-awl | awl/utils.py | get_field_names | def get_field_names(obj, ignore_auto=True, ignore_relations=True,
exclude=[]):
"""Returns the field names of a Django model object.
:param obj: the Django model class or object instance to get the fields
from
:param ignore_auto: ignore any fields of type AutoField. Defaults to True
:param ignore_relations: ignore any fields that involve relations such as
the ForeignKey or ManyToManyField
:param exclude: exclude anything in this list from the results
:returns: generator of found field names
"""
from django.db.models import (AutoField, ForeignKey, ManyToManyField,
ManyToOneRel, OneToOneField, OneToOneRel)
for field in obj._meta.get_fields():
if ignore_auto and isinstance(field, AutoField):
continue
if ignore_relations and (isinstance(field, ForeignKey) or
isinstance(field, ManyToManyField) or
isinstance(field, ManyToOneRel) or
isinstance(field, OneToOneRel) or
isinstance(field, OneToOneField)):
# optimization is killing coverage measure, have to put no-op that
# does something
a = 1; a
continue
if field.name in exclude:
continue
yield field.name | python | def get_field_names(obj, ignore_auto=True, ignore_relations=True,
exclude=[]):
"""Returns the field names of a Django model object.
:param obj: the Django model class or object instance to get the fields
from
:param ignore_auto: ignore any fields of type AutoField. Defaults to True
:param ignore_relations: ignore any fields that involve relations such as
the ForeignKey or ManyToManyField
:param exclude: exclude anything in this list from the results
:returns: generator of found field names
"""
from django.db.models import (AutoField, ForeignKey, ManyToManyField,
ManyToOneRel, OneToOneField, OneToOneRel)
for field in obj._meta.get_fields():
if ignore_auto and isinstance(field, AutoField):
continue
if ignore_relations and (isinstance(field, ForeignKey) or
isinstance(field, ManyToManyField) or
isinstance(field, ManyToOneRel) or
isinstance(field, OneToOneRel) or
isinstance(field, OneToOneField)):
# optimization is killing coverage measure, have to put no-op that
# does something
a = 1; a
continue
if field.name in exclude:
continue
yield field.name | [
"def",
"get_field_names",
"(",
"obj",
",",
"ignore_auto",
"=",
"True",
",",
"ignore_relations",
"=",
"True",
",",
"exclude",
"=",
"[",
"]",
")",
":",
"from",
"django",
".",
"db",
".",
"models",
"import",
"(",
"AutoField",
",",
"ForeignKey",
",",
"ManyToManyField",
",",
"ManyToOneRel",
",",
"OneToOneField",
",",
"OneToOneRel",
")",
"for",
"field",
"in",
"obj",
".",
"_meta",
".",
"get_fields",
"(",
")",
":",
"if",
"ignore_auto",
"and",
"isinstance",
"(",
"field",
",",
"AutoField",
")",
":",
"continue",
"if",
"ignore_relations",
"and",
"(",
"isinstance",
"(",
"field",
",",
"ForeignKey",
")",
"or",
"isinstance",
"(",
"field",
",",
"ManyToManyField",
")",
"or",
"isinstance",
"(",
"field",
",",
"ManyToOneRel",
")",
"or",
"isinstance",
"(",
"field",
",",
"OneToOneRel",
")",
"or",
"isinstance",
"(",
"field",
",",
"OneToOneField",
")",
")",
":",
"# optimization is killing coverage measure, have to put no-op that",
"# does something",
"a",
"=",
"1",
"a",
"continue",
"if",
"field",
".",
"name",
"in",
"exclude",
":",
"continue",
"yield",
"field",
".",
"name"
] | Returns the field names of a Django model object.
:param obj: the Django model class or object instance to get the fields
from
:param ignore_auto: ignore any fields of type AutoField. Defaults to True
:param ignore_relations: ignore any fields that involve relations such as
the ForeignKey or ManyToManyField
:param exclude: exclude anything in this list from the results
:returns: generator of found field names | [
"Returns",
"the",
"field",
"names",
"of",
"a",
"Django",
"model",
"object",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/utils.py#L59-L93 | valid |
cltrudeau/django-awl | awl/utils.py | get_obj_attr | def get_obj_attr(obj, attr):
"""Works like getattr() but supports django's double underscore object
dereference notation.
Example usage:
.. code-block:: python
>>> get_obj_attr(book, 'writer__age')
42
>>> get_obj_attr(book, 'publisher__address')
<Address object at 105a79ac8>
:param obj:
Object to start the derference from
:param attr:
String name of attribute to return
:returns:
Derferenced object
:raises:
AttributeError in the attribute in question does not exist
"""
# handle '__' referencing like in QuerySets
fields = attr.split('__')
field_obj = getattr(obj, fields[0])
for field in fields[1:]:
# keep going down the reference tree
field_obj = getattr(field_obj, field)
return field_obj | python | def get_obj_attr(obj, attr):
"""Works like getattr() but supports django's double underscore object
dereference notation.
Example usage:
.. code-block:: python
>>> get_obj_attr(book, 'writer__age')
42
>>> get_obj_attr(book, 'publisher__address')
<Address object at 105a79ac8>
:param obj:
Object to start the derference from
:param attr:
String name of attribute to return
:returns:
Derferenced object
:raises:
AttributeError in the attribute in question does not exist
"""
# handle '__' referencing like in QuerySets
fields = attr.split('__')
field_obj = getattr(obj, fields[0])
for field in fields[1:]:
# keep going down the reference tree
field_obj = getattr(field_obj, field)
return field_obj | [
"def",
"get_obj_attr",
"(",
"obj",
",",
"attr",
")",
":",
"# handle '__' referencing like in QuerySets",
"fields",
"=",
"attr",
".",
"split",
"(",
"'__'",
")",
"field_obj",
"=",
"getattr",
"(",
"obj",
",",
"fields",
"[",
"0",
"]",
")",
"for",
"field",
"in",
"fields",
"[",
"1",
":",
"]",
":",
"# keep going down the reference tree",
"field_obj",
"=",
"getattr",
"(",
"field_obj",
",",
"field",
")",
"return",
"field_obj"
] | Works like getattr() but supports django's double underscore object
dereference notation.
Example usage:
.. code-block:: python
>>> get_obj_attr(book, 'writer__age')
42
>>> get_obj_attr(book, 'publisher__address')
<Address object at 105a79ac8>
:param obj:
Object to start the derference from
:param attr:
String name of attribute to return
:returns:
Derferenced object
:raises:
AttributeError in the attribute in question does not exist | [
"Works",
"like",
"getattr",
"()",
"but",
"supports",
"django",
"s",
"double",
"underscore",
"object",
"dereference",
"notation",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/utils.py#L96-L129 | valid |
cltrudeau/django-awl | awl/utils.py | URLTree.as_list | def as_list(self):
"""Returns a list of strings describing the full paths and patterns
along with the name of the urls. Example:
.. code-block::python
>>> u = URLTree()
>>> u.as_list()
[
'admin/',
'admin/$, name=index',
'admin/login/$, name=login',
]
"""
result = []
for child in self.children:
self._depth_traversal(child, result)
return result | python | def as_list(self):
"""Returns a list of strings describing the full paths and patterns
along with the name of the urls. Example:
.. code-block::python
>>> u = URLTree()
>>> u.as_list()
[
'admin/',
'admin/$, name=index',
'admin/login/$, name=login',
]
"""
result = []
for child in self.children:
self._depth_traversal(child, result)
return result | [
"def",
"as_list",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"child",
"in",
"self",
".",
"children",
":",
"self",
".",
"_depth_traversal",
"(",
"child",
",",
"result",
")",
"return",
"result"
] | Returns a list of strings describing the full paths and patterns
along with the name of the urls. Example:
.. code-block::python
>>> u = URLTree()
>>> u.as_list()
[
'admin/',
'admin/$, name=index',
'admin/login/$, name=login',
] | [
"Returns",
"a",
"list",
"of",
"strings",
"describing",
"the",
"full",
"paths",
"and",
"patterns",
"along",
"with",
"the",
"name",
"of",
"the",
"urls",
".",
"Example",
":"
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/utils.py#L178-L195 | valid |
geoneric/starling | starling/flask/error_handler/error_code.py | register | def register(
app):
"""
Register all HTTP error code error handlers
Currently, errors are handled by the JSON error handler.
"""
# Pick a handler based on the requested format. Currently we assume the
# caller wants JSON.
error_handler = json.http_exception_error_handler
@app.errorhandler(400)
def handle_bad_request(
exception):
return error_handler(exception)
@app.errorhandler(404)
def handle_not_found(
exception):
return error_handler(exception)
@app.errorhandler(405)
def handle_method_not_allowed(
exception):
return error_handler(exception)
@app.errorhandler(422)
def handle_unprocessable_entity(
exception):
return error_handler(exception)
@app.errorhandler(500)
def handle_internal_server_error(
exception):
return error_handler(exception) | python | def register(
app):
"""
Register all HTTP error code error handlers
Currently, errors are handled by the JSON error handler.
"""
# Pick a handler based on the requested format. Currently we assume the
# caller wants JSON.
error_handler = json.http_exception_error_handler
@app.errorhandler(400)
def handle_bad_request(
exception):
return error_handler(exception)
@app.errorhandler(404)
def handle_not_found(
exception):
return error_handler(exception)
@app.errorhandler(405)
def handle_method_not_allowed(
exception):
return error_handler(exception)
@app.errorhandler(422)
def handle_unprocessable_entity(
exception):
return error_handler(exception)
@app.errorhandler(500)
def handle_internal_server_error(
exception):
return error_handler(exception) | [
"def",
"register",
"(",
"app",
")",
":",
"# Pick a handler based on the requested format. Currently we assume the",
"# caller wants JSON.",
"error_handler",
"=",
"json",
".",
"http_exception_error_handler",
"@",
"app",
".",
"errorhandler",
"(",
"400",
")",
"def",
"handle_bad_request",
"(",
"exception",
")",
":",
"return",
"error_handler",
"(",
"exception",
")",
"@",
"app",
".",
"errorhandler",
"(",
"404",
")",
"def",
"handle_not_found",
"(",
"exception",
")",
":",
"return",
"error_handler",
"(",
"exception",
")",
"@",
"app",
".",
"errorhandler",
"(",
"405",
")",
"def",
"handle_method_not_allowed",
"(",
"exception",
")",
":",
"return",
"error_handler",
"(",
"exception",
")",
"@",
"app",
".",
"errorhandler",
"(",
"422",
")",
"def",
"handle_unprocessable_entity",
"(",
"exception",
")",
":",
"return",
"error_handler",
"(",
"exception",
")",
"@",
"app",
".",
"errorhandler",
"(",
"500",
")",
"def",
"handle_internal_server_error",
"(",
"exception",
")",
":",
"return",
"error_handler",
"(",
"exception",
")"
] | Register all HTTP error code error handlers
Currently, errors are handled by the JSON error handler. | [
"Register",
"all",
"HTTP",
"error",
"code",
"error",
"handlers"
] | a8e1324c4d6e8b063a0d353bcd03bb8e57edd888 | https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/flask/error_handler/error_code.py#L7-L47 | valid |
joelfrederico/SciSalt | scisalt/matplotlib/plot.py | plot | def plot(*args, ax=None, **kwargs):
"""
Plots but automatically resizes x axis.
.. versionadded:: 1.4
Parameters
----------
args
Passed on to :meth:`matplotlib.axis.Axis.plot`.
ax : :class:`matplotlib.axis.Axis`, optional
The axis to plot to.
kwargs
Passed on to :meth:`matplotlib.axis.Axis.plot`.
"""
if ax is None:
fig, ax = _setup_axes()
pl = ax.plot(*args, **kwargs)
if _np.shape(args)[0] > 1:
if type(args[1]) is not str:
min_x = min(args[0])
max_x = max(args[0])
ax.set_xlim((min_x, max_x))
return pl | python | def plot(*args, ax=None, **kwargs):
"""
Plots but automatically resizes x axis.
.. versionadded:: 1.4
Parameters
----------
args
Passed on to :meth:`matplotlib.axis.Axis.plot`.
ax : :class:`matplotlib.axis.Axis`, optional
The axis to plot to.
kwargs
Passed on to :meth:`matplotlib.axis.Axis.plot`.
"""
if ax is None:
fig, ax = _setup_axes()
pl = ax.plot(*args, **kwargs)
if _np.shape(args)[0] > 1:
if type(args[1]) is not str:
min_x = min(args[0])
max_x = max(args[0])
ax.set_xlim((min_x, max_x))
return pl | [
"def",
"plot",
"(",
"*",
"args",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"_setup_axes",
"(",
")",
"pl",
"=",
"ax",
".",
"plot",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"_np",
".",
"shape",
"(",
"args",
")",
"[",
"0",
"]",
">",
"1",
":",
"if",
"type",
"(",
"args",
"[",
"1",
"]",
")",
"is",
"not",
"str",
":",
"min_x",
"=",
"min",
"(",
"args",
"[",
"0",
"]",
")",
"max_x",
"=",
"max",
"(",
"args",
"[",
"0",
"]",
")",
"ax",
".",
"set_xlim",
"(",
"(",
"min_x",
",",
"max_x",
")",
")",
"return",
"pl"
] | Plots but automatically resizes x axis.
.. versionadded:: 1.4
Parameters
----------
args
Passed on to :meth:`matplotlib.axis.Axis.plot`.
ax : :class:`matplotlib.axis.Axis`, optional
The axis to plot to.
kwargs
Passed on to :meth:`matplotlib.axis.Axis.plot`. | [
"Plots",
"but",
"automatically",
"resizes",
"x",
"axis",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/plot.py#L10-L37 | valid |
joelfrederico/SciSalt | scisalt/numpy/linspacestep.py | linspacestep | def linspacestep(start, stop, step=1):
"""
Create a vector of values over an interval with a specified step size.
Parameters
----------
start : float
The beginning of the interval.
stop : float
The end of the interval.
step : float
The step size.
Returns
-------
vector : :class:`numpy.ndarray`
The vector of values.
"""
# Find an integer number of steps
numsteps = _np.int((stop-start)/step)
# Do a linspace over the new range
# that has the correct endpoint
return _np.linspace(start, start+step*numsteps, numsteps+1) | python | def linspacestep(start, stop, step=1):
"""
Create a vector of values over an interval with a specified step size.
Parameters
----------
start : float
The beginning of the interval.
stop : float
The end of the interval.
step : float
The step size.
Returns
-------
vector : :class:`numpy.ndarray`
The vector of values.
"""
# Find an integer number of steps
numsteps = _np.int((stop-start)/step)
# Do a linspace over the new range
# that has the correct endpoint
return _np.linspace(start, start+step*numsteps, numsteps+1) | [
"def",
"linspacestep",
"(",
"start",
",",
"stop",
",",
"step",
"=",
"1",
")",
":",
"# Find an integer number of steps",
"numsteps",
"=",
"_np",
".",
"int",
"(",
"(",
"stop",
"-",
"start",
")",
"/",
"step",
")",
"# Do a linspace over the new range",
"# that has the correct endpoint",
"return",
"_np",
".",
"linspace",
"(",
"start",
",",
"start",
"+",
"step",
"*",
"numsteps",
",",
"numsteps",
"+",
"1",
")"
] | Create a vector of values over an interval with a specified step size.
Parameters
----------
start : float
The beginning of the interval.
stop : float
The end of the interval.
step : float
The step size.
Returns
-------
vector : :class:`numpy.ndarray`
The vector of values. | [
"Create",
"a",
"vector",
"of",
"values",
"over",
"an",
"interval",
"with",
"a",
"specified",
"step",
"size",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/numpy/linspacestep.py#L7-L31 | valid |
joelfrederico/SciSalt | scisalt/logging/mylogger.py | mylogger | def mylogger(name=None, filename=None, indent_offset=7, level=_logging.DEBUG, stream_level=_logging.WARN, file_level=_logging.INFO):
"""
Sets up logging to *filename*.debug.log, *filename*.log, and the terminal. *indent_offset* attempts to line up the lowest indent level to 0. Custom levels:
* *level*: Parent logging level.
* *stream_level*: Logging level for console stream.
* *file_level*: Logging level for general file log.
"""
if name is not None:
logger = _logging.getLogger(name)
else:
logger = _logging.getLogger()
logger.setLevel(level)
fmtr = IndentFormatter(indent_offset=indent_offset)
fmtr_msgonly = IndentFormatter('%(funcName)s:%(lineno)d: %(message)s')
ch = _logging.StreamHandler()
ch.setLevel(stream_level)
ch.setFormatter(fmtr_msgonly)
logger.addHandler(ch)
if filename is not None:
debugh = _logging.FileHandler(filename='{}_debug.log'.format(filename), mode='w')
debugh.setLevel(_logging.DEBUG)
debugh.setFormatter(fmtr_msgonly)
logger.addHandler(debugh)
fh = _logging.FileHandler(filename='{}.log'.format(filename), mode='w')
fh.setLevel(file_level)
fh.setFormatter(fmtr)
logger.addHandler(fh)
return logger | python | def mylogger(name=None, filename=None, indent_offset=7, level=_logging.DEBUG, stream_level=_logging.WARN, file_level=_logging.INFO):
"""
Sets up logging to *filename*.debug.log, *filename*.log, and the terminal. *indent_offset* attempts to line up the lowest indent level to 0. Custom levels:
* *level*: Parent logging level.
* *stream_level*: Logging level for console stream.
* *file_level*: Logging level for general file log.
"""
if name is not None:
logger = _logging.getLogger(name)
else:
logger = _logging.getLogger()
logger.setLevel(level)
fmtr = IndentFormatter(indent_offset=indent_offset)
fmtr_msgonly = IndentFormatter('%(funcName)s:%(lineno)d: %(message)s')
ch = _logging.StreamHandler()
ch.setLevel(stream_level)
ch.setFormatter(fmtr_msgonly)
logger.addHandler(ch)
if filename is not None:
debugh = _logging.FileHandler(filename='{}_debug.log'.format(filename), mode='w')
debugh.setLevel(_logging.DEBUG)
debugh.setFormatter(fmtr_msgonly)
logger.addHandler(debugh)
fh = _logging.FileHandler(filename='{}.log'.format(filename), mode='w')
fh.setLevel(file_level)
fh.setFormatter(fmtr)
logger.addHandler(fh)
return logger | [
"def",
"mylogger",
"(",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"indent_offset",
"=",
"7",
",",
"level",
"=",
"_logging",
".",
"DEBUG",
",",
"stream_level",
"=",
"_logging",
".",
"WARN",
",",
"file_level",
"=",
"_logging",
".",
"INFO",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"logger",
"=",
"_logging",
".",
"getLogger",
"(",
"name",
")",
"else",
":",
"logger",
"=",
"_logging",
".",
"getLogger",
"(",
")",
"logger",
".",
"setLevel",
"(",
"level",
")",
"fmtr",
"=",
"IndentFormatter",
"(",
"indent_offset",
"=",
"indent_offset",
")",
"fmtr_msgonly",
"=",
"IndentFormatter",
"(",
"'%(funcName)s:%(lineno)d: %(message)s'",
")",
"ch",
"=",
"_logging",
".",
"StreamHandler",
"(",
")",
"ch",
".",
"setLevel",
"(",
"stream_level",
")",
"ch",
".",
"setFormatter",
"(",
"fmtr_msgonly",
")",
"logger",
".",
"addHandler",
"(",
"ch",
")",
"if",
"filename",
"is",
"not",
"None",
":",
"debugh",
"=",
"_logging",
".",
"FileHandler",
"(",
"filename",
"=",
"'{}_debug.log'",
".",
"format",
"(",
"filename",
")",
",",
"mode",
"=",
"'w'",
")",
"debugh",
".",
"setLevel",
"(",
"_logging",
".",
"DEBUG",
")",
"debugh",
".",
"setFormatter",
"(",
"fmtr_msgonly",
")",
"logger",
".",
"addHandler",
"(",
"debugh",
")",
"fh",
"=",
"_logging",
".",
"FileHandler",
"(",
"filename",
"=",
"'{}.log'",
".",
"format",
"(",
"filename",
")",
",",
"mode",
"=",
"'w'",
")",
"fh",
".",
"setLevel",
"(",
"file_level",
")",
"fh",
".",
"setFormatter",
"(",
"fmtr",
")",
"logger",
".",
"addHandler",
"(",
"fh",
")",
"return",
"logger"
] | Sets up logging to *filename*.debug.log, *filename*.log, and the terminal. *indent_offset* attempts to line up the lowest indent level to 0. Custom levels:
* *level*: Parent logging level.
* *stream_level*: Logging level for console stream.
* *file_level*: Logging level for general file log. | [
"Sets",
"up",
"logging",
"to",
"*",
"filename",
"*",
".",
"debug",
".",
"log",
"*",
"filename",
"*",
".",
"log",
"and",
"the",
"terminal",
".",
"*",
"indent_offset",
"*",
"attempts",
"to",
"line",
"up",
"the",
"lowest",
"indent",
"level",
"to",
"0",
".",
"Custom",
"levels",
":"
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/logging/mylogger.py#L6-L40 | valid |
minttu/tmc.py | tmc/__main__.py | selected_course | def selected_course(func):
"""
Passes the selected course as the first argument to func.
"""
@wraps(func)
def inner(*args, **kwargs):
course = Course.get_selected()
return func(course, *args, **kwargs)
return inner | python | def selected_course(func):
"""
Passes the selected course as the first argument to func.
"""
@wraps(func)
def inner(*args, **kwargs):
course = Course.get_selected()
return func(course, *args, **kwargs)
return inner | [
"def",
"selected_course",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"course",
"=",
"Course",
".",
"get_selected",
"(",
")",
"return",
"func",
"(",
"course",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"inner"
] | Passes the selected course as the first argument to func. | [
"Passes",
"the",
"selected",
"course",
"as",
"the",
"first",
"argument",
"to",
"func",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L38-L46 | valid |
minttu/tmc.py | tmc/__main__.py | selected_exercise | def selected_exercise(func):
"""
Passes the selected exercise as the first argument to func.
"""
@wraps(func)
def inner(*args, **kwargs):
exercise = Exercise.get_selected()
return func(exercise, *args, **kwargs)
return inner | python | def selected_exercise(func):
"""
Passes the selected exercise as the first argument to func.
"""
@wraps(func)
def inner(*args, **kwargs):
exercise = Exercise.get_selected()
return func(exercise, *args, **kwargs)
return inner | [
"def",
"selected_exercise",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"exercise",
"=",
"Exercise",
".",
"get_selected",
"(",
")",
"return",
"func",
"(",
"exercise",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"inner"
] | Passes the selected exercise as the first argument to func. | [
"Passes",
"the",
"selected",
"exercise",
"as",
"the",
"first",
"argument",
"to",
"func",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L49-L57 | valid |
minttu/tmc.py | tmc/__main__.py | false_exit | def false_exit(func):
"""
If func returns False the program exits immediately.
"""
@wraps(func)
def inner(*args, **kwargs):
ret = func(*args, **kwargs)
if ret is False:
if "TMC_TESTING" in os.environ:
raise TMCExit()
else:
sys.exit(-1)
return ret
return inner | python | def false_exit(func):
"""
If func returns False the program exits immediately.
"""
@wraps(func)
def inner(*args, **kwargs):
ret = func(*args, **kwargs)
if ret is False:
if "TMC_TESTING" in os.environ:
raise TMCExit()
else:
sys.exit(-1)
return ret
return inner | [
"def",
"false_exit",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"ret",
"is",
"False",
":",
"if",
"\"TMC_TESTING\"",
"in",
"os",
".",
"environ",
":",
"raise",
"TMCExit",
"(",
")",
"else",
":",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"return",
"ret",
"return",
"inner"
] | If func returns False the program exits immediately. | [
"If",
"func",
"returns",
"False",
"the",
"program",
"exits",
"immediately",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L60-L73 | valid |
minttu/tmc.py | tmc/__main__.py | configure | def configure(server=None, username=None, password=None, tid=None, auto=False):
"""
Configure tmc.py to use your account.
"""
if not server and not username and not password and not tid:
if Config.has():
if not yn_prompt("Override old configuration", False):
return False
reset_db()
if not server:
while True:
server = input("Server url [https://tmc.mooc.fi/mooc/]: ").strip()
if len(server) == 0:
server = "https://tmc.mooc.fi/mooc/"
if not server.endswith('/'):
server += '/'
if not (server.startswith("http://")
or server.startswith("https://")):
ret = custom_prompt(
"Server should start with http:// or https://\n" +
"R: Retry, H: Assume http://, S: Assume https://",
["r", "h", "s"], "r")
if ret == "r":
continue
# Strip previous schema
if "://" in server:
server = server.split("://")[1]
if ret == "h":
server = "http://" + server
elif ret == "s":
server = "https://" + server
break
print("Using URL: '{0}'".format(server))
while True:
if not username:
username = input("Username: ")
if not password:
password = getpass("Password: ")
# wow, such security
token = b64encode(
bytes("{0}:{1}".format(username, password), encoding='utf-8')
).decode("utf-8")
try:
api.configure(url=server, token=token, test=True)
except APIError as e:
print(e)
if auto is False and yn_prompt("Retry authentication"):
username = password = None
continue
return False
break
if tid:
select(course=True, tid=tid, auto=auto)
else:
select(course=True) | python | def configure(server=None, username=None, password=None, tid=None, auto=False):
"""
Configure tmc.py to use your account.
"""
if not server and not username and not password and not tid:
if Config.has():
if not yn_prompt("Override old configuration", False):
return False
reset_db()
if not server:
while True:
server = input("Server url [https://tmc.mooc.fi/mooc/]: ").strip()
if len(server) == 0:
server = "https://tmc.mooc.fi/mooc/"
if not server.endswith('/'):
server += '/'
if not (server.startswith("http://")
or server.startswith("https://")):
ret = custom_prompt(
"Server should start with http:// or https://\n" +
"R: Retry, H: Assume http://, S: Assume https://",
["r", "h", "s"], "r")
if ret == "r":
continue
# Strip previous schema
if "://" in server:
server = server.split("://")[1]
if ret == "h":
server = "http://" + server
elif ret == "s":
server = "https://" + server
break
print("Using URL: '{0}'".format(server))
while True:
if not username:
username = input("Username: ")
if not password:
password = getpass("Password: ")
# wow, such security
token = b64encode(
bytes("{0}:{1}".format(username, password), encoding='utf-8')
).decode("utf-8")
try:
api.configure(url=server, token=token, test=True)
except APIError as e:
print(e)
if auto is False and yn_prompt("Retry authentication"):
username = password = None
continue
return False
break
if tid:
select(course=True, tid=tid, auto=auto)
else:
select(course=True) | [
"def",
"configure",
"(",
"server",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"tid",
"=",
"None",
",",
"auto",
"=",
"False",
")",
":",
"if",
"not",
"server",
"and",
"not",
"username",
"and",
"not",
"password",
"and",
"not",
"tid",
":",
"if",
"Config",
".",
"has",
"(",
")",
":",
"if",
"not",
"yn_prompt",
"(",
"\"Override old configuration\"",
",",
"False",
")",
":",
"return",
"False",
"reset_db",
"(",
")",
"if",
"not",
"server",
":",
"while",
"True",
":",
"server",
"=",
"input",
"(",
"\"Server url [https://tmc.mooc.fi/mooc/]: \"",
")",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"server",
")",
"==",
"0",
":",
"server",
"=",
"\"https://tmc.mooc.fi/mooc/\"",
"if",
"not",
"server",
".",
"endswith",
"(",
"'/'",
")",
":",
"server",
"+=",
"'/'",
"if",
"not",
"(",
"server",
".",
"startswith",
"(",
"\"http://\"",
")",
"or",
"server",
".",
"startswith",
"(",
"\"https://\"",
")",
")",
":",
"ret",
"=",
"custom_prompt",
"(",
"\"Server should start with http:// or https://\\n\"",
"+",
"\"R: Retry, H: Assume http://, S: Assume https://\"",
",",
"[",
"\"r\"",
",",
"\"h\"",
",",
"\"s\"",
"]",
",",
"\"r\"",
")",
"if",
"ret",
"==",
"\"r\"",
":",
"continue",
"# Strip previous schema",
"if",
"\"://\"",
"in",
"server",
":",
"server",
"=",
"server",
".",
"split",
"(",
"\"://\"",
")",
"[",
"1",
"]",
"if",
"ret",
"==",
"\"h\"",
":",
"server",
"=",
"\"http://\"",
"+",
"server",
"elif",
"ret",
"==",
"\"s\"",
":",
"server",
"=",
"\"https://\"",
"+",
"server",
"break",
"print",
"(",
"\"Using URL: '{0}'\"",
".",
"format",
"(",
"server",
")",
")",
"while",
"True",
":",
"if",
"not",
"username",
":",
"username",
"=",
"input",
"(",
"\"Username: \"",
")",
"if",
"not",
"password",
":",
"password",
"=",
"getpass",
"(",
"\"Password: \"",
")",
"# wow, such security",
"token",
"=",
"b64encode",
"(",
"bytes",
"(",
"\"{0}:{1}\"",
".",
"format",
"(",
"username",
",",
"password",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"try",
":",
"api",
".",
"configure",
"(",
"url",
"=",
"server",
",",
"token",
"=",
"token",
",",
"test",
"=",
"True",
")",
"except",
"APIError",
"as",
"e",
":",
"print",
"(",
"e",
")",
"if",
"auto",
"is",
"False",
"and",
"yn_prompt",
"(",
"\"Retry authentication\"",
")",
":",
"username",
"=",
"password",
"=",
"None",
"continue",
"return",
"False",
"break",
"if",
"tid",
":",
"select",
"(",
"course",
"=",
"True",
",",
"tid",
"=",
"tid",
",",
"auto",
"=",
"auto",
")",
"else",
":",
"select",
"(",
"course",
"=",
"True",
")"
] | Configure tmc.py to use your account. | [
"Configure",
"tmc",
".",
"py",
"to",
"use",
"your",
"account",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L104-L160 | valid |
minttu/tmc.py | tmc/__main__.py | download | def download(course, tid=None, dl_all=False, force=False, upgradejava=False,
update=False):
"""
Download the exercises from the server.
"""
def dl(id):
download_exercise(Exercise.get(Exercise.tid == id),
force=force,
update_java=upgradejava,
update=update)
if dl_all:
for exercise in list(course.exercises):
dl(exercise.tid)
elif tid is not None:
dl(int(tid))
else:
for exercise in list(course.exercises):
if not exercise.is_completed:
dl(exercise.tid)
else:
exercise.update_downloaded() | python | def download(course, tid=None, dl_all=False, force=False, upgradejava=False,
update=False):
"""
Download the exercises from the server.
"""
def dl(id):
download_exercise(Exercise.get(Exercise.tid == id),
force=force,
update_java=upgradejava,
update=update)
if dl_all:
for exercise in list(course.exercises):
dl(exercise.tid)
elif tid is not None:
dl(int(tid))
else:
for exercise in list(course.exercises):
if not exercise.is_completed:
dl(exercise.tid)
else:
exercise.update_downloaded() | [
"def",
"download",
"(",
"course",
",",
"tid",
"=",
"None",
",",
"dl_all",
"=",
"False",
",",
"force",
"=",
"False",
",",
"upgradejava",
"=",
"False",
",",
"update",
"=",
"False",
")",
":",
"def",
"dl",
"(",
"id",
")",
":",
"download_exercise",
"(",
"Exercise",
".",
"get",
"(",
"Exercise",
".",
"tid",
"==",
"id",
")",
",",
"force",
"=",
"force",
",",
"update_java",
"=",
"upgradejava",
",",
"update",
"=",
"update",
")",
"if",
"dl_all",
":",
"for",
"exercise",
"in",
"list",
"(",
"course",
".",
"exercises",
")",
":",
"dl",
"(",
"exercise",
".",
"tid",
")",
"elif",
"tid",
"is",
"not",
"None",
":",
"dl",
"(",
"int",
"(",
"tid",
")",
")",
"else",
":",
"for",
"exercise",
"in",
"list",
"(",
"course",
".",
"exercises",
")",
":",
"if",
"not",
"exercise",
".",
"is_completed",
":",
"dl",
"(",
"exercise",
".",
"tid",
")",
"else",
":",
"exercise",
".",
"update_downloaded",
"(",
")"
] | Download the exercises from the server. | [
"Download",
"the",
"exercises",
"from",
"the",
"server",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L183-L205 | valid |
minttu/tmc.py | tmc/__main__.py | skip | def skip(course, num=1):
"""
Go to the next exercise.
"""
sel = None
try:
sel = Exercise.get_selected()
if sel.course.tid != course.tid:
sel = None
except NoExerciseSelected:
pass
if sel is None:
sel = course.exercises.first()
else:
try:
sel = Exercise.get(Exercise.id == sel.id + num)
except peewee.DoesNotExist:
print("There are no more exercises in this course.")
return False
sel.set_select()
list_all(single=sel) | python | def skip(course, num=1):
"""
Go to the next exercise.
"""
sel = None
try:
sel = Exercise.get_selected()
if sel.course.tid != course.tid:
sel = None
except NoExerciseSelected:
pass
if sel is None:
sel = course.exercises.first()
else:
try:
sel = Exercise.get(Exercise.id == sel.id + num)
except peewee.DoesNotExist:
print("There are no more exercises in this course.")
return False
sel.set_select()
list_all(single=sel) | [
"def",
"skip",
"(",
"course",
",",
"num",
"=",
"1",
")",
":",
"sel",
"=",
"None",
"try",
":",
"sel",
"=",
"Exercise",
".",
"get_selected",
"(",
")",
"if",
"sel",
".",
"course",
".",
"tid",
"!=",
"course",
".",
"tid",
":",
"sel",
"=",
"None",
"except",
"NoExerciseSelected",
":",
"pass",
"if",
"sel",
"is",
"None",
":",
"sel",
"=",
"course",
".",
"exercises",
".",
"first",
"(",
")",
"else",
":",
"try",
":",
"sel",
"=",
"Exercise",
".",
"get",
"(",
"Exercise",
".",
"id",
"==",
"sel",
".",
"id",
"+",
"num",
")",
"except",
"peewee",
".",
"DoesNotExist",
":",
"print",
"(",
"\"There are no more exercises in this course.\"",
")",
"return",
"False",
"sel",
".",
"set_select",
"(",
")",
"list_all",
"(",
"single",
"=",
"sel",
")"
] | Go to the next exercise. | [
"Go",
"to",
"the",
"next",
"exercise",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L211-L233 | valid |
minttu/tmc.py | tmc/__main__.py | run | def run(exercise, command):
"""
Spawns a process with `command path-of-exercise`
"""
Popen(['nohup', command, exercise.path()], stdout=DEVNULL, stderr=DEVNULL) | python | def run(exercise, command):
"""
Spawns a process with `command path-of-exercise`
"""
Popen(['nohup', command, exercise.path()], stdout=DEVNULL, stderr=DEVNULL) | [
"def",
"run",
"(",
"exercise",
",",
"command",
")",
":",
"Popen",
"(",
"[",
"'nohup'",
",",
"command",
",",
"exercise",
".",
"path",
"(",
")",
"]",
",",
"stdout",
"=",
"DEVNULL",
",",
"stderr",
"=",
"DEVNULL",
")"
] | Spawns a process with `command path-of-exercise` | [
"Spawns",
"a",
"process",
"with",
"command",
"path",
"-",
"of",
"-",
"exercise"
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L255-L259 | valid |
minttu/tmc.py | tmc/__main__.py | select | def select(course=False, tid=None, auto=False):
"""
Select a course or an exercise.
"""
if course:
update(course=True)
course = None
try:
course = Course.get_selected()
except NoCourseSelected:
pass
ret = {}
if not tid:
ret = Menu.launch("Select a course",
Course.select().execute(),
course)
else:
ret["item"] = Course.get(Course.tid == tid)
if "item" in ret:
ret["item"].set_select()
update()
if ret["item"].path == "":
select_a_path(auto=auto)
# Selects the first exercise in this course
skip()
return
else:
print("You can select the course with `tmc select --course`")
return
else:
selected = None
try:
selected = Exercise.get_selected()
except NoExerciseSelected:
pass
ret = {}
if not tid:
ret = Menu.launch("Select an exercise",
Course.get_selected().exercises,
selected)
else:
ret["item"] = Exercise.byid(tid)
if "item" in ret:
ret["item"].set_select()
print("Selected {}".format(ret["item"])) | python | def select(course=False, tid=None, auto=False):
"""
Select a course or an exercise.
"""
if course:
update(course=True)
course = None
try:
course = Course.get_selected()
except NoCourseSelected:
pass
ret = {}
if not tid:
ret = Menu.launch("Select a course",
Course.select().execute(),
course)
else:
ret["item"] = Course.get(Course.tid == tid)
if "item" in ret:
ret["item"].set_select()
update()
if ret["item"].path == "":
select_a_path(auto=auto)
# Selects the first exercise in this course
skip()
return
else:
print("You can select the course with `tmc select --course`")
return
else:
selected = None
try:
selected = Exercise.get_selected()
except NoExerciseSelected:
pass
ret = {}
if not tid:
ret = Menu.launch("Select an exercise",
Course.get_selected().exercises,
selected)
else:
ret["item"] = Exercise.byid(tid)
if "item" in ret:
ret["item"].set_select()
print("Selected {}".format(ret["item"])) | [
"def",
"select",
"(",
"course",
"=",
"False",
",",
"tid",
"=",
"None",
",",
"auto",
"=",
"False",
")",
":",
"if",
"course",
":",
"update",
"(",
"course",
"=",
"True",
")",
"course",
"=",
"None",
"try",
":",
"course",
"=",
"Course",
".",
"get_selected",
"(",
")",
"except",
"NoCourseSelected",
":",
"pass",
"ret",
"=",
"{",
"}",
"if",
"not",
"tid",
":",
"ret",
"=",
"Menu",
".",
"launch",
"(",
"\"Select a course\"",
",",
"Course",
".",
"select",
"(",
")",
".",
"execute",
"(",
")",
",",
"course",
")",
"else",
":",
"ret",
"[",
"\"item\"",
"]",
"=",
"Course",
".",
"get",
"(",
"Course",
".",
"tid",
"==",
"tid",
")",
"if",
"\"item\"",
"in",
"ret",
":",
"ret",
"[",
"\"item\"",
"]",
".",
"set_select",
"(",
")",
"update",
"(",
")",
"if",
"ret",
"[",
"\"item\"",
"]",
".",
"path",
"==",
"\"\"",
":",
"select_a_path",
"(",
"auto",
"=",
"auto",
")",
"# Selects the first exercise in this course",
"skip",
"(",
")",
"return",
"else",
":",
"print",
"(",
"\"You can select the course with `tmc select --course`\"",
")",
"return",
"else",
":",
"selected",
"=",
"None",
"try",
":",
"selected",
"=",
"Exercise",
".",
"get_selected",
"(",
")",
"except",
"NoExerciseSelected",
":",
"pass",
"ret",
"=",
"{",
"}",
"if",
"not",
"tid",
":",
"ret",
"=",
"Menu",
".",
"launch",
"(",
"\"Select an exercise\"",
",",
"Course",
".",
"get_selected",
"(",
")",
".",
"exercises",
",",
"selected",
")",
"else",
":",
"ret",
"[",
"\"item\"",
"]",
"=",
"Exercise",
".",
"byid",
"(",
"tid",
")",
"if",
"\"item\"",
"in",
"ret",
":",
"ret",
"[",
"\"item\"",
"]",
".",
"set_select",
"(",
")",
"print",
"(",
"\"Selected {}\"",
".",
"format",
"(",
"ret",
"[",
"\"item\"",
"]",
")",
")"
] | Select a course or an exercise. | [
"Select",
"a",
"course",
"or",
"an",
"exercise",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L266-L312 | valid |
minttu/tmc.py | tmc/__main__.py | submit | def submit(course, tid=None, pastebin=False, review=False):
"""
Submit the selected exercise to the server.
"""
if tid is not None:
return submit_exercise(Exercise.byid(tid),
pastebin=pastebin,
request_review=review)
else:
sel = Exercise.get_selected()
if not sel:
raise NoExerciseSelected()
return submit_exercise(sel, pastebin=pastebin, request_review=review) | python | def submit(course, tid=None, pastebin=False, review=False):
"""
Submit the selected exercise to the server.
"""
if tid is not None:
return submit_exercise(Exercise.byid(tid),
pastebin=pastebin,
request_review=review)
else:
sel = Exercise.get_selected()
if not sel:
raise NoExerciseSelected()
return submit_exercise(sel, pastebin=pastebin, request_review=review) | [
"def",
"submit",
"(",
"course",
",",
"tid",
"=",
"None",
",",
"pastebin",
"=",
"False",
",",
"review",
"=",
"False",
")",
":",
"if",
"tid",
"is",
"not",
"None",
":",
"return",
"submit_exercise",
"(",
"Exercise",
".",
"byid",
"(",
"tid",
")",
",",
"pastebin",
"=",
"pastebin",
",",
"request_review",
"=",
"review",
")",
"else",
":",
"sel",
"=",
"Exercise",
".",
"get_selected",
"(",
")",
"if",
"not",
"sel",
":",
"raise",
"NoExerciseSelected",
"(",
")",
"return",
"submit_exercise",
"(",
"sel",
",",
"pastebin",
"=",
"pastebin",
",",
"request_review",
"=",
"review",
")"
] | Submit the selected exercise to the server. | [
"Submit",
"the",
"selected",
"exercise",
"to",
"the",
"server",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L323-L335 | valid |
minttu/tmc.py | tmc/__main__.py | paste | def paste(tid=None, review=False):
"""
Sends the selected exercise to the TMC pastebin.
"""
submit(pastebin=True, tid=tid, review=False) | python | def paste(tid=None, review=False):
"""
Sends the selected exercise to the TMC pastebin.
"""
submit(pastebin=True, tid=tid, review=False) | [
"def",
"paste",
"(",
"tid",
"=",
"None",
",",
"review",
"=",
"False",
")",
":",
"submit",
"(",
"pastebin",
"=",
"True",
",",
"tid",
"=",
"tid",
",",
"review",
"=",
"False",
")"
] | Sends the selected exercise to the TMC pastebin. | [
"Sends",
"the",
"selected",
"exercise",
"to",
"the",
"TMC",
"pastebin",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L342-L346 | valid |
minttu/tmc.py | tmc/__main__.py | list_all | def list_all(course, single=None):
"""
Lists all of the exercises in the current course.
"""
def bs(val):
return "●" if val else " "
def bc(val):
return as_success("✔") if val else as_error("✘")
def format_line(exercise):
return "{0} │ {1} │ {2} │ {3} │ {4}".format(exercise.tid,
bs(exercise.is_selected),
bc(exercise.is_downloaded),
bc(exercise.is_completed),
exercise.menuname())
print("ID{0}│ S │ D │ C │ Name".format(
(len(str(course.exercises[0].tid)) - 1) * " "
))
if single:
print(format_line(single))
return
for exercise in course.exercises:
# ToDo: use a pager
print(format_line(exercise)) | python | def list_all(course, single=None):
"""
Lists all of the exercises in the current course.
"""
def bs(val):
return "●" if val else " "
def bc(val):
return as_success("✔") if val else as_error("✘")
def format_line(exercise):
return "{0} │ {1} │ {2} │ {3} │ {4}".format(exercise.tid,
bs(exercise.is_selected),
bc(exercise.is_downloaded),
bc(exercise.is_completed),
exercise.menuname())
print("ID{0}│ S │ D │ C │ Name".format(
(len(str(course.exercises[0].tid)) - 1) * " "
))
if single:
print(format_line(single))
return
for exercise in course.exercises:
# ToDo: use a pager
print(format_line(exercise)) | [
"def",
"list_all",
"(",
"course",
",",
"single",
"=",
"None",
")",
":",
"def",
"bs",
"(",
"val",
")",
":",
"return",
"\"●\" i",
" v",
"l e",
"se \"",
"\"",
"def",
"bc",
"(",
"val",
")",
":",
"return",
"as_success",
"(",
"\"✔\") ",
"i",
" v",
"l e",
"se a",
"_error(\"",
"✘",
"\")",
"",
"def",
"format_line",
"(",
"exercise",
")",
":",
"return",
"\"{0} │ {1} │ {2} │ {3} │ {4}\".format(",
"e",
"xercis",
"e",
".tid,",
"",
"",
"",
"bs",
"(",
"exercise",
".",
"is_selected",
")",
",",
"bc",
"(",
"exercise",
".",
"is_downloaded",
")",
",",
"bc",
"(",
"exercise",
".",
"is_completed",
")",
",",
"exercise",
".",
"menuname",
"(",
")",
")",
"print",
"(",
"\"ID{0}│ S │ D │ C │ Name\".format(",
"",
"",
"",
"(",
"len",
"(",
"str",
"(",
"course",
".",
"exercises",
"[",
"0",
"]",
".",
"tid",
")",
")",
"-",
"1",
")",
"*",
"\" \"",
")",
")",
"if",
"single",
":",
"print",
"(",
"format_line",
"(",
"single",
")",
")",
"return",
"for",
"exercise",
"in",
"course",
".",
"exercises",
":",
"# ToDo: use a pager",
"print",
"(",
"format_line",
"(",
"exercise",
")",
")"
] | Lists all of the exercises in the current course. | [
"Lists",
"all",
"of",
"the",
"exercises",
"in",
"the",
"current",
"course",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L372-L398 | valid |
minttu/tmc.py | tmc/__main__.py | update | def update(course=False):
"""
Update the data of courses and or exercises from server.
"""
if course:
with Spinner.context(msg="Updated course metadata.",
waitmsg="Updating course metadata."):
for course in api.get_courses():
old = None
try:
old = Course.get(Course.tid == course["id"])
except peewee.DoesNotExist:
old = None
if old:
old.details_url = course["details_url"]
old.save()
continue
Course.create(tid=course["id"], name=course["name"],
details_url=course["details_url"])
else:
selected = Course.get_selected()
# with Spinner.context(msg="Updated exercise metadata.",
# waitmsg="Updating exercise metadata."):
print("Updating exercise data.")
for exercise in api.get_exercises(selected):
old = None
try:
old = Exercise.byid(exercise["id"])
except peewee.DoesNotExist:
old = None
if old is not None:
old.name = exercise["name"]
old.course = selected.id
old.is_attempted = exercise["attempted"]
old.is_completed = exercise["completed"]
old.deadline = exercise.get("deadline")
old.is_downloaded = os.path.isdir(old.path())
old.return_url = exercise["return_url"]
old.zip_url = exercise["zip_url"]
old.submissions_url = exercise["exercise_submissions_url"]
old.save()
download_exercise(old, update=True)
else:
ex = Exercise.create(tid=exercise["id"],
name=exercise["name"],
course=selected.id,
is_attempted=exercise["attempted"],
is_completed=exercise["completed"],
deadline=exercise.get("deadline"),
return_url=exercise["return_url"],
zip_url=exercise["zip_url"],
submissions_url=exercise[("exercise_"
"submissions_"
"url")])
ex.is_downloaded = os.path.isdir(ex.path())
ex.save() | python | def update(course=False):
"""
Update the data of courses and or exercises from server.
"""
if course:
with Spinner.context(msg="Updated course metadata.",
waitmsg="Updating course metadata."):
for course in api.get_courses():
old = None
try:
old = Course.get(Course.tid == course["id"])
except peewee.DoesNotExist:
old = None
if old:
old.details_url = course["details_url"]
old.save()
continue
Course.create(tid=course["id"], name=course["name"],
details_url=course["details_url"])
else:
selected = Course.get_selected()
# with Spinner.context(msg="Updated exercise metadata.",
# waitmsg="Updating exercise metadata."):
print("Updating exercise data.")
for exercise in api.get_exercises(selected):
old = None
try:
old = Exercise.byid(exercise["id"])
except peewee.DoesNotExist:
old = None
if old is not None:
old.name = exercise["name"]
old.course = selected.id
old.is_attempted = exercise["attempted"]
old.is_completed = exercise["completed"]
old.deadline = exercise.get("deadline")
old.is_downloaded = os.path.isdir(old.path())
old.return_url = exercise["return_url"]
old.zip_url = exercise["zip_url"]
old.submissions_url = exercise["exercise_submissions_url"]
old.save()
download_exercise(old, update=True)
else:
ex = Exercise.create(tid=exercise["id"],
name=exercise["name"],
course=selected.id,
is_attempted=exercise["attempted"],
is_completed=exercise["completed"],
deadline=exercise.get("deadline"),
return_url=exercise["return_url"],
zip_url=exercise["zip_url"],
submissions_url=exercise[("exercise_"
"submissions_"
"url")])
ex.is_downloaded = os.path.isdir(ex.path())
ex.save() | [
"def",
"update",
"(",
"course",
"=",
"False",
")",
":",
"if",
"course",
":",
"with",
"Spinner",
".",
"context",
"(",
"msg",
"=",
"\"Updated course metadata.\"",
",",
"waitmsg",
"=",
"\"Updating course metadata.\"",
")",
":",
"for",
"course",
"in",
"api",
".",
"get_courses",
"(",
")",
":",
"old",
"=",
"None",
"try",
":",
"old",
"=",
"Course",
".",
"get",
"(",
"Course",
".",
"tid",
"==",
"course",
"[",
"\"id\"",
"]",
")",
"except",
"peewee",
".",
"DoesNotExist",
":",
"old",
"=",
"None",
"if",
"old",
":",
"old",
".",
"details_url",
"=",
"course",
"[",
"\"details_url\"",
"]",
"old",
".",
"save",
"(",
")",
"continue",
"Course",
".",
"create",
"(",
"tid",
"=",
"course",
"[",
"\"id\"",
"]",
",",
"name",
"=",
"course",
"[",
"\"name\"",
"]",
",",
"details_url",
"=",
"course",
"[",
"\"details_url\"",
"]",
")",
"else",
":",
"selected",
"=",
"Course",
".",
"get_selected",
"(",
")",
"# with Spinner.context(msg=\"Updated exercise metadata.\",",
"# waitmsg=\"Updating exercise metadata.\"):",
"print",
"(",
"\"Updating exercise data.\"",
")",
"for",
"exercise",
"in",
"api",
".",
"get_exercises",
"(",
"selected",
")",
":",
"old",
"=",
"None",
"try",
":",
"old",
"=",
"Exercise",
".",
"byid",
"(",
"exercise",
"[",
"\"id\"",
"]",
")",
"except",
"peewee",
".",
"DoesNotExist",
":",
"old",
"=",
"None",
"if",
"old",
"is",
"not",
"None",
":",
"old",
".",
"name",
"=",
"exercise",
"[",
"\"name\"",
"]",
"old",
".",
"course",
"=",
"selected",
".",
"id",
"old",
".",
"is_attempted",
"=",
"exercise",
"[",
"\"attempted\"",
"]",
"old",
".",
"is_completed",
"=",
"exercise",
"[",
"\"completed\"",
"]",
"old",
".",
"deadline",
"=",
"exercise",
".",
"get",
"(",
"\"deadline\"",
")",
"old",
".",
"is_downloaded",
"=",
"os",
".",
"path",
".",
"isdir",
"(",
"old",
".",
"path",
"(",
")",
")",
"old",
".",
"return_url",
"=",
"exercise",
"[",
"\"return_url\"",
"]",
"old",
".",
"zip_url",
"=",
"exercise",
"[",
"\"zip_url\"",
"]",
"old",
".",
"submissions_url",
"=",
"exercise",
"[",
"\"exercise_submissions_url\"",
"]",
"old",
".",
"save",
"(",
")",
"download_exercise",
"(",
"old",
",",
"update",
"=",
"True",
")",
"else",
":",
"ex",
"=",
"Exercise",
".",
"create",
"(",
"tid",
"=",
"exercise",
"[",
"\"id\"",
"]",
",",
"name",
"=",
"exercise",
"[",
"\"name\"",
"]",
",",
"course",
"=",
"selected",
".",
"id",
",",
"is_attempted",
"=",
"exercise",
"[",
"\"attempted\"",
"]",
",",
"is_completed",
"=",
"exercise",
"[",
"\"completed\"",
"]",
",",
"deadline",
"=",
"exercise",
".",
"get",
"(",
"\"deadline\"",
")",
",",
"return_url",
"=",
"exercise",
"[",
"\"return_url\"",
"]",
",",
"zip_url",
"=",
"exercise",
"[",
"\"zip_url\"",
"]",
",",
"submissions_url",
"=",
"exercise",
"[",
"(",
"\"exercise_\"",
"\"submissions_\"",
"\"url\"",
")",
"]",
")",
"ex",
".",
"is_downloaded",
"=",
"os",
".",
"path",
".",
"isdir",
"(",
"ex",
".",
"path",
"(",
")",
")",
"ex",
".",
"save",
"(",
")"
] | Update the data of courses and or exercises from server. | [
"Update",
"the",
"data",
"of",
"courses",
"and",
"or",
"exercises",
"from",
"server",
"."
] | 212cfe1791a4aab4783f99b665cc32da6437f419 | https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/__main__.py#L403-L459 | valid |
TaurusOlson/incisive | incisive/core.py | determine_type | def determine_type(x):
"""Determine the type of x"""
types = (int, float, str)
_type = filter(lambda a: is_type(a, x), types)[0]
return _type(x) | python | def determine_type(x):
"""Determine the type of x"""
types = (int, float, str)
_type = filter(lambda a: is_type(a, x), types)[0]
return _type(x) | [
"def",
"determine_type",
"(",
"x",
")",
":",
"types",
"=",
"(",
"int",
",",
"float",
",",
"str",
")",
"_type",
"=",
"filter",
"(",
"lambda",
"a",
":",
"is_type",
"(",
"a",
",",
"x",
")",
",",
"types",
")",
"[",
"0",
"]",
"return",
"_type",
"(",
"x",
")"
] | Determine the type of x | [
"Determine",
"the",
"type",
"of",
"x"
] | 25bb9f53495985c1416c82e26f54158df4050cb0 | https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L21-L25 | valid |
TaurusOlson/incisive | incisive/core.py | dmap | def dmap(fn, record):
"""map for a directory"""
values = (fn(v) for k, v in record.items())
return dict(itertools.izip(record, values)) | python | def dmap(fn, record):
"""map for a directory"""
values = (fn(v) for k, v in record.items())
return dict(itertools.izip(record, values)) | [
"def",
"dmap",
"(",
"fn",
",",
"record",
")",
":",
"values",
"=",
"(",
"fn",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"record",
".",
"items",
"(",
")",
")",
"return",
"dict",
"(",
"itertools",
".",
"izip",
"(",
"record",
",",
"values",
")",
")"
] | map for a directory | [
"map",
"for",
"a",
"directory"
] | 25bb9f53495985c1416c82e26f54158df4050cb0 | https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L28-L31 | valid |
TaurusOlson/incisive | incisive/core.py | apply_types | def apply_types(use_types, guess_type, line):
"""Apply the types on the elements of the line"""
new_line = {}
for k, v in line.items():
if use_types.has_key(k):
new_line[k] = force_type(use_types[k], v)
elif guess_type:
new_line[k] = determine_type(v)
else:
new_line[k] = v
return new_line | python | def apply_types(use_types, guess_type, line):
"""Apply the types on the elements of the line"""
new_line = {}
for k, v in line.items():
if use_types.has_key(k):
new_line[k] = force_type(use_types[k], v)
elif guess_type:
new_line[k] = determine_type(v)
else:
new_line[k] = v
return new_line | [
"def",
"apply_types",
"(",
"use_types",
",",
"guess_type",
",",
"line",
")",
":",
"new_line",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"line",
".",
"items",
"(",
")",
":",
"if",
"use_types",
".",
"has_key",
"(",
"k",
")",
":",
"new_line",
"[",
"k",
"]",
"=",
"force_type",
"(",
"use_types",
"[",
"k",
"]",
",",
"v",
")",
"elif",
"guess_type",
":",
"new_line",
"[",
"k",
"]",
"=",
"determine_type",
"(",
"v",
")",
"else",
":",
"new_line",
"[",
"k",
"]",
"=",
"v",
"return",
"new_line"
] | Apply the types on the elements of the line | [
"Apply",
"the",
"types",
"on",
"the",
"elements",
"of",
"the",
"line"
] | 25bb9f53495985c1416c82e26f54158df4050cb0 | https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L41-L51 | valid |
TaurusOlson/incisive | incisive/core.py | read_csv | def read_csv(filename, delimiter=",", skip=0, guess_type=True, has_header=True, use_types={}):
"""Read a CSV file
Usage
-----
>>> data = read_csv(filename, delimiter=delimiter, skip=skip,
guess_type=guess_type, has_header=True, use_types={})
# Use specific types
>>> types = {"sepal.length": int, "petal.width": float}
>>> data = read_csv(filename, guess_type=guess_type, use_types=types)
keywords
:has_header:
Determine whether the file has a header or not
"""
with open(filename, 'r') as f:
# Skip the n first lines
if has_header:
header = f.readline().strip().split(delimiter)
else:
header = None
for i in range(skip):
f.readline()
for line in csv.DictReader(f, delimiter=delimiter, fieldnames=header):
if use_types:
yield apply_types(use_types, guess_type, line)
elif guess_type:
yield dmap(determine_type, line)
else:
yield line | python | def read_csv(filename, delimiter=",", skip=0, guess_type=True, has_header=True, use_types={}):
"""Read a CSV file
Usage
-----
>>> data = read_csv(filename, delimiter=delimiter, skip=skip,
guess_type=guess_type, has_header=True, use_types={})
# Use specific types
>>> types = {"sepal.length": int, "petal.width": float}
>>> data = read_csv(filename, guess_type=guess_type, use_types=types)
keywords
:has_header:
Determine whether the file has a header or not
"""
with open(filename, 'r') as f:
# Skip the n first lines
if has_header:
header = f.readline().strip().split(delimiter)
else:
header = None
for i in range(skip):
f.readline()
for line in csv.DictReader(f, delimiter=delimiter, fieldnames=header):
if use_types:
yield apply_types(use_types, guess_type, line)
elif guess_type:
yield dmap(determine_type, line)
else:
yield line | [
"def",
"read_csv",
"(",
"filename",
",",
"delimiter",
"=",
"\",\"",
",",
"skip",
"=",
"0",
",",
"guess_type",
"=",
"True",
",",
"has_header",
"=",
"True",
",",
"use_types",
"=",
"{",
"}",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"# Skip the n first lines",
"if",
"has_header",
":",
"header",
"=",
"f",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
"delimiter",
")",
"else",
":",
"header",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"skip",
")",
":",
"f",
".",
"readline",
"(",
")",
"for",
"line",
"in",
"csv",
".",
"DictReader",
"(",
"f",
",",
"delimiter",
"=",
"delimiter",
",",
"fieldnames",
"=",
"header",
")",
":",
"if",
"use_types",
":",
"yield",
"apply_types",
"(",
"use_types",
",",
"guess_type",
",",
"line",
")",
"elif",
"guess_type",
":",
"yield",
"dmap",
"(",
"determine_type",
",",
"line",
")",
"else",
":",
"yield",
"line"
] | Read a CSV file
Usage
-----
>>> data = read_csv(filename, delimiter=delimiter, skip=skip,
guess_type=guess_type, has_header=True, use_types={})
# Use specific types
>>> types = {"sepal.length": int, "petal.width": float}
>>> data = read_csv(filename, guess_type=guess_type, use_types=types)
keywords
:has_header:
Determine whether the file has a header or not | [
"Read",
"a",
"CSV",
"file",
"Usage",
"-----",
">>>",
"data",
"=",
"read_csv",
"(",
"filename",
"delimiter",
"=",
"delimiter",
"skip",
"=",
"skip",
"guess_type",
"=",
"guess_type",
"has_header",
"=",
"True",
"use_types",
"=",
"{}",
")"
] | 25bb9f53495985c1416c82e26f54158df4050cb0 | https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L55-L88 | valid |
TaurusOlson/incisive | incisive/core.py | write_csv | def write_csv(filename, header, data=None, rows=None, mode="w"):
"""Write the data to the specified filename
Usage
-----
>>> write_csv(filename, header, data, mode=mode)
Parameters
----------
filename : str
The name of the file
header : list of strings
The names of the columns (or fields):
(fieldname1, fieldname2, ...)
data : list of dictionaries (optional)
[
{fieldname1: a1, fieldname2: a2},
{fieldname1: b1, fieldname2: b2},
...
]
rows : list of lists (optional)
[
(a1, a2),
(b1, b2),
...
]
mode : str (optional)
"w": write the data to the file by overwriting it
"a": write the data to the file by appending them
Returns
-------
None. A CSV file is written.
"""
if data == rows == None:
msg = "You must specify either data or rows"
raise ValueError(msg)
elif data != None and rows != None:
msg = "You must specify either data or rows. Not both"
raise ValueError(msg)
data_header = dict((x, x) for x in header)
with open(filename, mode) as f:
if data:
writer = csv.DictWriter(f, fieldnames=header)
if mode == "w":
writer.writerow(data_header)
writer.writerows(data)
elif rows:
writer = csv.writer(f)
if mode == "w":
writer.writerow(header)
writer.writerows(rows)
print "Saved %s." % filename | python | def write_csv(filename, header, data=None, rows=None, mode="w"):
"""Write the data to the specified filename
Usage
-----
>>> write_csv(filename, header, data, mode=mode)
Parameters
----------
filename : str
The name of the file
header : list of strings
The names of the columns (or fields):
(fieldname1, fieldname2, ...)
data : list of dictionaries (optional)
[
{fieldname1: a1, fieldname2: a2},
{fieldname1: b1, fieldname2: b2},
...
]
rows : list of lists (optional)
[
(a1, a2),
(b1, b2),
...
]
mode : str (optional)
"w": write the data to the file by overwriting it
"a": write the data to the file by appending them
Returns
-------
None. A CSV file is written.
"""
if data == rows == None:
msg = "You must specify either data or rows"
raise ValueError(msg)
elif data != None and rows != None:
msg = "You must specify either data or rows. Not both"
raise ValueError(msg)
data_header = dict((x, x) for x in header)
with open(filename, mode) as f:
if data:
writer = csv.DictWriter(f, fieldnames=header)
if mode == "w":
writer.writerow(data_header)
writer.writerows(data)
elif rows:
writer = csv.writer(f)
if mode == "w":
writer.writerow(header)
writer.writerows(rows)
print "Saved %s." % filename | [
"def",
"write_csv",
"(",
"filename",
",",
"header",
",",
"data",
"=",
"None",
",",
"rows",
"=",
"None",
",",
"mode",
"=",
"\"w\"",
")",
":",
"if",
"data",
"==",
"rows",
"==",
"None",
":",
"msg",
"=",
"\"You must specify either data or rows\"",
"raise",
"ValueError",
"(",
"msg",
")",
"elif",
"data",
"!=",
"None",
"and",
"rows",
"!=",
"None",
":",
"msg",
"=",
"\"You must specify either data or rows. Not both\"",
"raise",
"ValueError",
"(",
"msg",
")",
"data_header",
"=",
"dict",
"(",
"(",
"x",
",",
"x",
")",
"for",
"x",
"in",
"header",
")",
"with",
"open",
"(",
"filename",
",",
"mode",
")",
"as",
"f",
":",
"if",
"data",
":",
"writer",
"=",
"csv",
".",
"DictWriter",
"(",
"f",
",",
"fieldnames",
"=",
"header",
")",
"if",
"mode",
"==",
"\"w\"",
":",
"writer",
".",
"writerow",
"(",
"data_header",
")",
"writer",
".",
"writerows",
"(",
"data",
")",
"elif",
"rows",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"f",
")",
"if",
"mode",
"==",
"\"w\"",
":",
"writer",
".",
"writerow",
"(",
"header",
")",
"writer",
".",
"writerows",
"(",
"rows",
")",
"print",
"\"Saved %s.\"",
"%",
"filename"
] | Write the data to the specified filename
Usage
-----
>>> write_csv(filename, header, data, mode=mode)
Parameters
----------
filename : str
The name of the file
header : list of strings
The names of the columns (or fields):
(fieldname1, fieldname2, ...)
data : list of dictionaries (optional)
[
{fieldname1: a1, fieldname2: a2},
{fieldname1: b1, fieldname2: b2},
...
]
rows : list of lists (optional)
[
(a1, a2),
(b1, b2),
...
]
mode : str (optional)
"w": write the data to the file by overwriting it
"a": write the data to the file by appending them
Returns
-------
None. A CSV file is written. | [
"Write",
"the",
"data",
"to",
"the",
"specified",
"filename",
"Usage",
"-----",
">>>",
"write_csv",
"(",
"filename",
"header",
"data",
"mode",
"=",
"mode",
")"
] | 25bb9f53495985c1416c82e26f54158df4050cb0 | https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L91-L152 | valid |
TaurusOlson/incisive | incisive/core.py | format_to_csv | def format_to_csv(filename, skiprows=0, delimiter=""):
"""Convert a file to a .csv file"""
if not delimiter:
delimiter = "\t"
input_file = open(filename, "r")
if skiprows:
[input_file.readline() for _ in range(skiprows)]
new_filename = os.path.splitext(filename)[0] + ".csv"
output_file = open(new_filename, "w")
header = input_file.readline().split()
reader = csv.DictReader(input_file, fieldnames=header, delimiter=delimiter)
writer = csv.DictWriter(output_file, fieldnames=header, delimiter=",")
# Write header
writer.writerow(dict((x, x) for x in header))
# Write rows
for line in reader:
if None in line: del line[None]
writer.writerow(line)
input_file.close()
output_file.close()
print "Saved %s." % new_filename | python | def format_to_csv(filename, skiprows=0, delimiter=""):
"""Convert a file to a .csv file"""
if not delimiter:
delimiter = "\t"
input_file = open(filename, "r")
if skiprows:
[input_file.readline() for _ in range(skiprows)]
new_filename = os.path.splitext(filename)[0] + ".csv"
output_file = open(new_filename, "w")
header = input_file.readline().split()
reader = csv.DictReader(input_file, fieldnames=header, delimiter=delimiter)
writer = csv.DictWriter(output_file, fieldnames=header, delimiter=",")
# Write header
writer.writerow(dict((x, x) for x in header))
# Write rows
for line in reader:
if None in line: del line[None]
writer.writerow(line)
input_file.close()
output_file.close()
print "Saved %s." % new_filename | [
"def",
"format_to_csv",
"(",
"filename",
",",
"skiprows",
"=",
"0",
",",
"delimiter",
"=",
"\"\"",
")",
":",
"if",
"not",
"delimiter",
":",
"delimiter",
"=",
"\"\\t\"",
"input_file",
"=",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"if",
"skiprows",
":",
"[",
"input_file",
".",
"readline",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"skiprows",
")",
"]",
"new_filename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]",
"+",
"\".csv\"",
"output_file",
"=",
"open",
"(",
"new_filename",
",",
"\"w\"",
")",
"header",
"=",
"input_file",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
"reader",
"=",
"csv",
".",
"DictReader",
"(",
"input_file",
",",
"fieldnames",
"=",
"header",
",",
"delimiter",
"=",
"delimiter",
")",
"writer",
"=",
"csv",
".",
"DictWriter",
"(",
"output_file",
",",
"fieldnames",
"=",
"header",
",",
"delimiter",
"=",
"\",\"",
")",
"# Write header",
"writer",
".",
"writerow",
"(",
"dict",
"(",
"(",
"x",
",",
"x",
")",
"for",
"x",
"in",
"header",
")",
")",
"# Write rows",
"for",
"line",
"in",
"reader",
":",
"if",
"None",
"in",
"line",
":",
"del",
"line",
"[",
"None",
"]",
"writer",
".",
"writerow",
"(",
"line",
")",
"input_file",
".",
"close",
"(",
")",
"output_file",
".",
"close",
"(",
")",
"print",
"\"Saved %s.\"",
"%",
"new_filename"
] | Convert a file to a .csv file | [
"Convert",
"a",
"file",
"to",
"a",
".",
"csv",
"file"
] | 25bb9f53495985c1416c82e26f54158df4050cb0 | https://github.com/TaurusOlson/incisive/blob/25bb9f53495985c1416c82e26f54158df4050cb0/incisive/core.py#L155-L182 | valid |
joelfrederico/SciSalt | scisalt/matplotlib/savefig.py | savefig | def savefig(filename, path="figs", fig=None, ext='eps', verbose=False, **kwargs):
"""
Save the figure *fig* (optional, if not specified, latest figure in focus) to *filename* in the path *path* with extension *ext*.
*\*\*kwargs* is passed to :meth:`matplotlib.figure.Figure.savefig`.
"""
filename = os.path.join(path, filename)
final_filename = '{}.{}'.format(filename, ext).replace(" ", "").replace("\n", "")
final_filename = os.path.abspath(final_filename)
final_path = os.path.dirname(final_filename)
if not os.path.exists(final_path):
os.makedirs(final_path)
if verbose:
print('Saving file: {}'.format(final_filename))
if fig is not None:
fig.savefig(final_filename, bbox_inches='tight', **kwargs)
else:
plt.savefig(final_filename, bbox_inches='tight', **kwargs) | python | def savefig(filename, path="figs", fig=None, ext='eps', verbose=False, **kwargs):
"""
Save the figure *fig* (optional, if not specified, latest figure in focus) to *filename* in the path *path* with extension *ext*.
*\*\*kwargs* is passed to :meth:`matplotlib.figure.Figure.savefig`.
"""
filename = os.path.join(path, filename)
final_filename = '{}.{}'.format(filename, ext).replace(" ", "").replace("\n", "")
final_filename = os.path.abspath(final_filename)
final_path = os.path.dirname(final_filename)
if not os.path.exists(final_path):
os.makedirs(final_path)
if verbose:
print('Saving file: {}'.format(final_filename))
if fig is not None:
fig.savefig(final_filename, bbox_inches='tight', **kwargs)
else:
plt.savefig(final_filename, bbox_inches='tight', **kwargs) | [
"def",
"savefig",
"(",
"filename",
",",
"path",
"=",
"\"figs\"",
",",
"fig",
"=",
"None",
",",
"ext",
"=",
"'eps'",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"final_filename",
"=",
"'{}.{}'",
".",
"format",
"(",
"filename",
",",
"ext",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
"final_filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"final_filename",
")",
"final_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"final_filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"final_path",
")",
":",
"os",
".",
"makedirs",
"(",
"final_path",
")",
"if",
"verbose",
":",
"print",
"(",
"'Saving file: {}'",
".",
"format",
"(",
"final_filename",
")",
")",
"if",
"fig",
"is",
"not",
"None",
":",
"fig",
".",
"savefig",
"(",
"final_filename",
",",
"bbox_inches",
"=",
"'tight'",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"plt",
".",
"savefig",
"(",
"final_filename",
",",
"bbox_inches",
"=",
"'tight'",
",",
"*",
"*",
"kwargs",
")"
] | Save the figure *fig* (optional, if not specified, latest figure in focus) to *filename* in the path *path* with extension *ext*.
*\*\*kwargs* is passed to :meth:`matplotlib.figure.Figure.savefig`. | [
"Save",
"the",
"figure",
"*",
"fig",
"*",
"(",
"optional",
"if",
"not",
"specified",
"latest",
"figure",
"in",
"focus",
")",
"to",
"*",
"filename",
"*",
"in",
"the",
"path",
"*",
"path",
"*",
"with",
"extension",
"*",
"ext",
"*",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/savefig.py#L12-L32 | valid |
cltrudeau/django-awl | awl/admintools.py | admin_obj_link | def admin_obj_link(obj, display=''):
"""Returns a link to the django admin change list with a filter set to
only the object given.
:param obj:
Object to create the admin change list display link for
:param display:
Text to display in the link. Defaults to string call of the object
:returns:
Text containing HTML for a link
"""
# get the url for the change list for this object
url = reverse('admin:%s_%s_changelist' % (obj._meta.app_label,
obj._meta.model_name))
url += '?id__exact=%s' % obj.id
text = str(obj)
if display:
text = display
return format_html('<a href="{}">{}</a>', url, text) | python | def admin_obj_link(obj, display=''):
"""Returns a link to the django admin change list with a filter set to
only the object given.
:param obj:
Object to create the admin change list display link for
:param display:
Text to display in the link. Defaults to string call of the object
:returns:
Text containing HTML for a link
"""
# get the url for the change list for this object
url = reverse('admin:%s_%s_changelist' % (obj._meta.app_label,
obj._meta.model_name))
url += '?id__exact=%s' % obj.id
text = str(obj)
if display:
text = display
return format_html('<a href="{}">{}</a>', url, text) | [
"def",
"admin_obj_link",
"(",
"obj",
",",
"display",
"=",
"''",
")",
":",
"# get the url for the change list for this object",
"url",
"=",
"reverse",
"(",
"'admin:%s_%s_changelist'",
"%",
"(",
"obj",
".",
"_meta",
".",
"app_label",
",",
"obj",
".",
"_meta",
".",
"model_name",
")",
")",
"url",
"+=",
"'?id__exact=%s'",
"%",
"obj",
".",
"id",
"text",
"=",
"str",
"(",
"obj",
")",
"if",
"display",
":",
"text",
"=",
"display",
"return",
"format_html",
"(",
"'<a href=\"{}\">{}</a>'",
",",
"url",
",",
"text",
")"
] | Returns a link to the django admin change list with a filter set to
only the object given.
:param obj:
Object to create the admin change list display link for
:param display:
Text to display in the link. Defaults to string call of the object
:returns:
Text containing HTML for a link | [
"Returns",
"a",
"link",
"to",
"the",
"django",
"admin",
"change",
"list",
"with",
"a",
"filter",
"set",
"to",
"only",
"the",
"object",
"given",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L12-L32 | valid |
cltrudeau/django-awl | awl/admintools.py | admin_obj_attr | def admin_obj_attr(obj, attr):
"""A safe version of :func:``utils.get_obj_attr`` that returns and empty
string in the case of an exception or an empty object
"""
try:
field_obj = get_obj_attr(obj, attr)
if not field_obj:
return ''
except AttributeError:
return ''
return field_obj | python | def admin_obj_attr(obj, attr):
"""A safe version of :func:``utils.get_obj_attr`` that returns and empty
string in the case of an exception or an empty object
"""
try:
field_obj = get_obj_attr(obj, attr)
if not field_obj:
return ''
except AttributeError:
return ''
return field_obj | [
"def",
"admin_obj_attr",
"(",
"obj",
",",
"attr",
")",
":",
"try",
":",
"field_obj",
"=",
"get_obj_attr",
"(",
"obj",
",",
"attr",
")",
"if",
"not",
"field_obj",
":",
"return",
"''",
"except",
"AttributeError",
":",
"return",
"''",
"return",
"field_obj"
] | A safe version of :func:``utils.get_obj_attr`` that returns and empty
string in the case of an exception or an empty object | [
"A",
"safe",
"version",
"of",
":",
"func",
":",
"utils",
".",
"get_obj_attr",
"that",
"returns",
"and",
"empty",
"string",
"in",
"the",
"case",
"of",
"an",
"exception",
"or",
"an",
"empty",
"object"
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L35-L46 | valid |
cltrudeau/django-awl | awl/admintools.py | _obj_display | def _obj_display(obj, display=''):
"""Returns string representation of an object, either the default or based
on the display template passed in.
"""
result = ''
if not display:
result = str(obj)
else:
template = Template(display)
context = Context({'obj':obj})
result = template.render(context)
return result | python | def _obj_display(obj, display=''):
"""Returns string representation of an object, either the default or based
on the display template passed in.
"""
result = ''
if not display:
result = str(obj)
else:
template = Template(display)
context = Context({'obj':obj})
result = template.render(context)
return result | [
"def",
"_obj_display",
"(",
"obj",
",",
"display",
"=",
"''",
")",
":",
"result",
"=",
"''",
"if",
"not",
"display",
":",
"result",
"=",
"str",
"(",
"obj",
")",
"else",
":",
"template",
"=",
"Template",
"(",
"display",
")",
"context",
"=",
"Context",
"(",
"{",
"'obj'",
":",
"obj",
"}",
")",
"result",
"=",
"template",
".",
"render",
"(",
"context",
")",
"return",
"result"
] | Returns string representation of an object, either the default or based
on the display template passed in. | [
"Returns",
"string",
"representation",
"of",
"an",
"object",
"either",
"the",
"default",
"or",
"based",
"on",
"the",
"display",
"template",
"passed",
"in",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L49-L61 | valid |
cltrudeau/django-awl | awl/admintools.py | make_admin_obj_mixin | def make_admin_obj_mixin(name):
"""This method dynamically creates a mixin to be used with your
:class:`ModelAdmin` classes. The mixin provides utility methods that can
be referenced in side of the admin object's ``list_display`` and other
similar attributes.
:param name:
Each usage of the mixin must be given a unique name for the mixin class
being created
:returns:
Dynamically created mixin class
The created class supports the following methods:
.. code-block:: python
add_obj_ref(funcname, attr, [title, display])
Django admin ``list_display`` does not support the double underscore
semantics of object references. This method adds a function to the mixin
that returns the ``str(obj)`` value from object relations.
:param funcname:
Name of the function to be added to the mixin. In the admin class
object that includes the mixin, this name is used in the
``list_display`` tuple.
:param attr:
Name of the attribute to dereference from the corresponding object,
i.e. what will be dereferenced. This name supports double underscore
object link referencing for ``models.ForeignKey`` members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text in the column. If not given it defaults
to the string representation of the object for the row: ``str(obj)`` .
This parameter supports django templating, the context for which
contains a dictionary key named "obj" with the value being the object
for the row.
.. code-block:: python
add_obj_link(funcname, attr, [title, display])
This method adds a function to the mixin that returns a link to a django
admin change list page for the member attribute of the object being
displayed.
:param funcname:
Name of the function to be added to the mixin. In the admin class
object that includes the mixin, this name is used in the
``list_display`` tuple.
:param attr:
Name of the attribute to dereference from the corresponding object,
i.e. what will be lined to. This name supports double underscore
object link referencing for ``models.ForeignKey`` members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not given it
defaults to the string representation of the object for the row:
``str(obj)`` . This parameter supports django templating, the context
for which contains a dictionary key named "obj" with the value being
the object for the row.
Example usage:
.. code-block:: python
# ---- models.py file ----
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
.. code-block:: python
# ---- admin.py file ----
@admin.register(Author)
class Author(admin.ModelAdmin):
list_display = ('name', )
mixin = make_admin_obj_mixin('BookMixin')
mixin.add_obj_link('show_author', 'Author', 'Our Authors',
'{{obj.name}} (id={{obj.id}})')
@admin.register(Book)
class BookAdmin(admin.ModelAdmin, mixin):
list_display = ('name', 'show_author')
A sample django admin page for "Book" would have the table:
+---------------------------------+------------------------+
| Name | Our Authors |
+=================================+========================+
| Hitchhikers Guide To The Galaxy | *Douglas Adams (id=1)* |
+---------------------------------+------------------------+
| War and Peace | *Tolstoy (id=2)* |
+---------------------------------+------------------------+
| Dirk Gently | *Douglas Adams (id=1)* |
+---------------------------------+------------------------+
Each of the *items* in the "Our Authors" column would be a link to the
django admin change list for the "Author" object with a filter set to show
just the object that was clicked. For example, if you clicked "Douglas
Adams (id=1)" you would be taken to the Author change list page filtered
just for Douglas Adams books.
The ``add_obj_ref`` method is similar to the above, but instead of showing
links, it just shows text and so can be used for view-only attributes of
dereferenced objects.
"""
@classmethod
def add_obj_link(cls, funcname, attr, title='', display=''):
if not title:
title = attr.capitalize()
# python scoping is a bit weird with default values, if it isn't
# referenced the inner function won't see it, so assign it for use
_display = display
def _link(self, obj):
field_obj = admin_obj_attr(obj, attr)
if not field_obj:
return ''
text = _obj_display(field_obj, _display)
return admin_obj_link(field_obj, text)
_link.short_description = title
_link.allow_tags = True
_link.admin_order_field = attr
setattr(cls, funcname, _link)
@classmethod
def add_obj_ref(cls, funcname, attr, title='', display=''):
if not title:
title = attr.capitalize()
# python scoping is a bit weird with default values, if it isn't
# referenced the inner function won't see it, so assign it for use
_display = display
def _ref(self, obj):
field_obj = admin_obj_attr(obj, attr)
if not field_obj:
return ''
return _obj_display(field_obj, _display)
_ref.short_description = title
_ref.allow_tags = True
_ref.admin_order_field = attr
setattr(cls, funcname, _ref)
klass = type(name, (), {})
klass.add_obj_link = add_obj_link
klass.add_obj_ref = add_obj_ref
return klass | python | def make_admin_obj_mixin(name):
"""This method dynamically creates a mixin to be used with your
:class:`ModelAdmin` classes. The mixin provides utility methods that can
be referenced in side of the admin object's ``list_display`` and other
similar attributes.
:param name:
Each usage of the mixin must be given a unique name for the mixin class
being created
:returns:
Dynamically created mixin class
The created class supports the following methods:
.. code-block:: python
add_obj_ref(funcname, attr, [title, display])
Django admin ``list_display`` does not support the double underscore
semantics of object references. This method adds a function to the mixin
that returns the ``str(obj)`` value from object relations.
:param funcname:
Name of the function to be added to the mixin. In the admin class
object that includes the mixin, this name is used in the
``list_display`` tuple.
:param attr:
Name of the attribute to dereference from the corresponding object,
i.e. what will be dereferenced. This name supports double underscore
object link referencing for ``models.ForeignKey`` members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text in the column. If not given it defaults
to the string representation of the object for the row: ``str(obj)`` .
This parameter supports django templating, the context for which
contains a dictionary key named "obj" with the value being the object
for the row.
.. code-block:: python
add_obj_link(funcname, attr, [title, display])
This method adds a function to the mixin that returns a link to a django
admin change list page for the member attribute of the object being
displayed.
:param funcname:
Name of the function to be added to the mixin. In the admin class
object that includes the mixin, this name is used in the
``list_display`` tuple.
:param attr:
Name of the attribute to dereference from the corresponding object,
i.e. what will be lined to. This name supports double underscore
object link referencing for ``models.ForeignKey`` members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not given it
defaults to the string representation of the object for the row:
``str(obj)`` . This parameter supports django templating, the context
for which contains a dictionary key named "obj" with the value being
the object for the row.
Example usage:
.. code-block:: python
# ---- models.py file ----
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
.. code-block:: python
# ---- admin.py file ----
@admin.register(Author)
class Author(admin.ModelAdmin):
list_display = ('name', )
mixin = make_admin_obj_mixin('BookMixin')
mixin.add_obj_link('show_author', 'Author', 'Our Authors',
'{{obj.name}} (id={{obj.id}})')
@admin.register(Book)
class BookAdmin(admin.ModelAdmin, mixin):
list_display = ('name', 'show_author')
A sample django admin page for "Book" would have the table:
+---------------------------------+------------------------+
| Name | Our Authors |
+=================================+========================+
| Hitchhikers Guide To The Galaxy | *Douglas Adams (id=1)* |
+---------------------------------+------------------------+
| War and Peace | *Tolstoy (id=2)* |
+---------------------------------+------------------------+
| Dirk Gently | *Douglas Adams (id=1)* |
+---------------------------------+------------------------+
Each of the *items* in the "Our Authors" column would be a link to the
django admin change list for the "Author" object with a filter set to show
just the object that was clicked. For example, if you clicked "Douglas
Adams (id=1)" you would be taken to the Author change list page filtered
just for Douglas Adams books.
The ``add_obj_ref`` method is similar to the above, but instead of showing
links, it just shows text and so can be used for view-only attributes of
dereferenced objects.
"""
@classmethod
def add_obj_link(cls, funcname, attr, title='', display=''):
if not title:
title = attr.capitalize()
# python scoping is a bit weird with default values, if it isn't
# referenced the inner function won't see it, so assign it for use
_display = display
def _link(self, obj):
field_obj = admin_obj_attr(obj, attr)
if not field_obj:
return ''
text = _obj_display(field_obj, _display)
return admin_obj_link(field_obj, text)
_link.short_description = title
_link.allow_tags = True
_link.admin_order_field = attr
setattr(cls, funcname, _link)
@classmethod
def add_obj_ref(cls, funcname, attr, title='', display=''):
if not title:
title = attr.capitalize()
# python scoping is a bit weird with default values, if it isn't
# referenced the inner function won't see it, so assign it for use
_display = display
def _ref(self, obj):
field_obj = admin_obj_attr(obj, attr)
if not field_obj:
return ''
return _obj_display(field_obj, _display)
_ref.short_description = title
_ref.allow_tags = True
_ref.admin_order_field = attr
setattr(cls, funcname, _ref)
klass = type(name, (), {})
klass.add_obj_link = add_obj_link
klass.add_obj_ref = add_obj_ref
return klass | [
"def",
"make_admin_obj_mixin",
"(",
"name",
")",
":",
"@",
"classmethod",
"def",
"add_obj_link",
"(",
"cls",
",",
"funcname",
",",
"attr",
",",
"title",
"=",
"''",
",",
"display",
"=",
"''",
")",
":",
"if",
"not",
"title",
":",
"title",
"=",
"attr",
".",
"capitalize",
"(",
")",
"# python scoping is a bit weird with default values, if it isn't",
"# referenced the inner function won't see it, so assign it for use",
"_display",
"=",
"display",
"def",
"_link",
"(",
"self",
",",
"obj",
")",
":",
"field_obj",
"=",
"admin_obj_attr",
"(",
"obj",
",",
"attr",
")",
"if",
"not",
"field_obj",
":",
"return",
"''",
"text",
"=",
"_obj_display",
"(",
"field_obj",
",",
"_display",
")",
"return",
"admin_obj_link",
"(",
"field_obj",
",",
"text",
")",
"_link",
".",
"short_description",
"=",
"title",
"_link",
".",
"allow_tags",
"=",
"True",
"_link",
".",
"admin_order_field",
"=",
"attr",
"setattr",
"(",
"cls",
",",
"funcname",
",",
"_link",
")",
"@",
"classmethod",
"def",
"add_obj_ref",
"(",
"cls",
",",
"funcname",
",",
"attr",
",",
"title",
"=",
"''",
",",
"display",
"=",
"''",
")",
":",
"if",
"not",
"title",
":",
"title",
"=",
"attr",
".",
"capitalize",
"(",
")",
"# python scoping is a bit weird with default values, if it isn't",
"# referenced the inner function won't see it, so assign it for use",
"_display",
"=",
"display",
"def",
"_ref",
"(",
"self",
",",
"obj",
")",
":",
"field_obj",
"=",
"admin_obj_attr",
"(",
"obj",
",",
"attr",
")",
"if",
"not",
"field_obj",
":",
"return",
"''",
"return",
"_obj_display",
"(",
"field_obj",
",",
"_display",
")",
"_ref",
".",
"short_description",
"=",
"title",
"_ref",
".",
"allow_tags",
"=",
"True",
"_ref",
".",
"admin_order_field",
"=",
"attr",
"setattr",
"(",
"cls",
",",
"funcname",
",",
"_ref",
")",
"klass",
"=",
"type",
"(",
"name",
",",
"(",
")",
",",
"{",
"}",
")",
"klass",
".",
"add_obj_link",
"=",
"add_obj_link",
"klass",
".",
"add_obj_ref",
"=",
"add_obj_ref",
"return",
"klass"
] | This method dynamically creates a mixin to be used with your
:class:`ModelAdmin` classes. The mixin provides utility methods that can
be referenced in side of the admin object's ``list_display`` and other
similar attributes.
:param name:
Each usage of the mixin must be given a unique name for the mixin class
being created
:returns:
Dynamically created mixin class
The created class supports the following methods:
.. code-block:: python
add_obj_ref(funcname, attr, [title, display])
Django admin ``list_display`` does not support the double underscore
semantics of object references. This method adds a function to the mixin
that returns the ``str(obj)`` value from object relations.
:param funcname:
Name of the function to be added to the mixin. In the admin class
object that includes the mixin, this name is used in the
``list_display`` tuple.
:param attr:
Name of the attribute to dereference from the corresponding object,
i.e. what will be dereferenced. This name supports double underscore
object link referencing for ``models.ForeignKey`` members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text in the column. If not given it defaults
to the string representation of the object for the row: ``str(obj)`` .
This parameter supports django templating, the context for which
contains a dictionary key named "obj" with the value being the object
for the row.
.. code-block:: python
add_obj_link(funcname, attr, [title, display])
This method adds a function to the mixin that returns a link to a django
admin change list page for the member attribute of the object being
displayed.
:param funcname:
Name of the function to be added to the mixin. In the admin class
object that includes the mixin, this name is used in the
``list_display`` tuple.
:param attr:
Name of the attribute to dereference from the corresponding object,
i.e. what will be lined to. This name supports double underscore
object link referencing for ``models.ForeignKey`` members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not given it
defaults to the string representation of the object for the row:
``str(obj)`` . This parameter supports django templating, the context
for which contains a dictionary key named "obj" with the value being
the object for the row.
Example usage:
.. code-block:: python
# ---- models.py file ----
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
.. code-block:: python
# ---- admin.py file ----
@admin.register(Author)
class Author(admin.ModelAdmin):
list_display = ('name', )
mixin = make_admin_obj_mixin('BookMixin')
mixin.add_obj_link('show_author', 'Author', 'Our Authors',
'{{obj.name}} (id={{obj.id}})')
@admin.register(Book)
class BookAdmin(admin.ModelAdmin, mixin):
list_display = ('name', 'show_author')
A sample django admin page for "Book" would have the table:
+---------------------------------+------------------------+
| Name | Our Authors |
+=================================+========================+
| Hitchhikers Guide To The Galaxy | *Douglas Adams (id=1)* |
+---------------------------------+------------------------+
| War and Peace | *Tolstoy (id=2)* |
+---------------------------------+------------------------+
| Dirk Gently | *Douglas Adams (id=1)* |
+---------------------------------+------------------------+
Each of the *items* in the "Our Authors" column would be a link to the
django admin change list for the "Author" object with a filter set to show
just the object that was clicked. For example, if you clicked "Douglas
Adams (id=1)" you would be taken to the Author change list page filtered
just for Douglas Adams books.
The ``add_obj_ref`` method is similar to the above, but instead of showing
links, it just shows text and so can be used for view-only attributes of
dereferenced objects. | [
"This",
"method",
"dynamically",
"creates",
"a",
"mixin",
"to",
"be",
"used",
"with",
"your",
":",
"class",
":",
"ModelAdmin",
"classes",
".",
"The",
"mixin",
"provides",
"utility",
"methods",
"that",
"can",
"be",
"referenced",
"in",
"side",
"of",
"the",
"admin",
"object",
"s",
"list_display",
"and",
"other",
"similar",
"attributes",
".",
":",
"param",
"name",
":",
"Each",
"usage",
"of",
"the",
"mixin",
"must",
"be",
"given",
"a",
"unique",
"name",
"for",
"the",
"mixin",
"class",
"being",
"created",
":",
"returns",
":",
"Dynamically",
"created",
"mixin",
"class"
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L64-L232 | valid |
cltrudeau/django-awl | awl/admintools.py | fancy_modeladmin | def fancy_modeladmin(*args):
"""Returns a new copy of a :class:`FancyModelAdmin` class (a class, not
an instance!). This can then be inherited from when declaring a model
admin class. The :class:`FancyModelAdmin` class has additional methods
for managing the ``list_display`` attribute.
:param ``*args``: [optional] any arguments given will be added to the
``list_display`` property using regular django ``list_display``
functionality.
This function is meant as a replacement for :func:`make_admin_obj_mixin`,
it does everything the old one does with fewer bookkeeping needs for the
user as well as adding functionality.
Example usage:
.. code-block:: python
# ---- models.py file ----
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
.. code-block:: python
# ---- admin.py file ----
@admin.register(Author)
class Author(admin.ModelAdmin):
list_display = ('name', )
base = fany_list_display_modeladmin()
base.add_displays('id', 'name')
base.add_obj_link('author', 'Our Authors',
'{{obj.name}} (id={{obj.id}})')
@admin.register(Book)
class BookAdmin(base):
list_display = ('name', 'show_author')
A sample django admin page for "Book" would have the table:
+----+---------------------------------+------------------------+
| ID | Name | Our Authors |
+====+=================================+========================+
| 1 | Hitchhikers Guide To The Galaxy | *Douglas Adams (id=1)* |
+----+---------------------------------+------------------------+
| 2 | War and Peace | *Tolstoy (id=2)* |
+----+---------------------------------+------------------------+
| 3 | Dirk Gently | *Douglas Adams (id=1)* |
+----+---------------------------------+------------------------+
See :class:`FancyModelAdmin` for a full list of functionality
provided by the returned base class.
"""
global klass_count
klass_count += 1
name = 'DynamicAdminClass%d' % klass_count
# clone the admin class
klass = type(name, (FancyModelAdmin,), {})
klass.list_display = []
if len(args) > 0:
klass.add_displays(*args)
return klass | python | def fancy_modeladmin(*args):
"""Returns a new copy of a :class:`FancyModelAdmin` class (a class, not
an instance!). This can then be inherited from when declaring a model
admin class. The :class:`FancyModelAdmin` class has additional methods
for managing the ``list_display`` attribute.
:param ``*args``: [optional] any arguments given will be added to the
``list_display`` property using regular django ``list_display``
functionality.
This function is meant as a replacement for :func:`make_admin_obj_mixin`,
it does everything the old one does with fewer bookkeeping needs for the
user as well as adding functionality.
Example usage:
.. code-block:: python
# ---- models.py file ----
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
.. code-block:: python
# ---- admin.py file ----
@admin.register(Author)
class Author(admin.ModelAdmin):
list_display = ('name', )
base = fany_list_display_modeladmin()
base.add_displays('id', 'name')
base.add_obj_link('author', 'Our Authors',
'{{obj.name}} (id={{obj.id}})')
@admin.register(Book)
class BookAdmin(base):
list_display = ('name', 'show_author')
A sample django admin page for "Book" would have the table:
+----+---------------------------------+------------------------+
| ID | Name | Our Authors |
+====+=================================+========================+
| 1 | Hitchhikers Guide To The Galaxy | *Douglas Adams (id=1)* |
+----+---------------------------------+------------------------+
| 2 | War and Peace | *Tolstoy (id=2)* |
+----+---------------------------------+------------------------+
| 3 | Dirk Gently | *Douglas Adams (id=1)* |
+----+---------------------------------+------------------------+
See :class:`FancyModelAdmin` for a full list of functionality
provided by the returned base class.
"""
global klass_count
klass_count += 1
name = 'DynamicAdminClass%d' % klass_count
# clone the admin class
klass = type(name, (FancyModelAdmin,), {})
klass.list_display = []
if len(args) > 0:
klass.add_displays(*args)
return klass | [
"def",
"fancy_modeladmin",
"(",
"*",
"args",
")",
":",
"global",
"klass_count",
"klass_count",
"+=",
"1",
"name",
"=",
"'DynamicAdminClass%d'",
"%",
"klass_count",
"# clone the admin class",
"klass",
"=",
"type",
"(",
"name",
",",
"(",
"FancyModelAdmin",
",",
")",
",",
"{",
"}",
")",
"klass",
".",
"list_display",
"=",
"[",
"]",
"if",
"len",
"(",
"args",
")",
">",
"0",
":",
"klass",
".",
"add_displays",
"(",
"*",
"args",
")",
"return",
"klass"
] | Returns a new copy of a :class:`FancyModelAdmin` class (a class, not
an instance!). This can then be inherited from when declaring a model
admin class. The :class:`FancyModelAdmin` class has additional methods
for managing the ``list_display`` attribute.
:param ``*args``: [optional] any arguments given will be added to the
``list_display`` property using regular django ``list_display``
functionality.
This function is meant as a replacement for :func:`make_admin_obj_mixin`,
it does everything the old one does with fewer bookkeeping needs for the
user as well as adding functionality.
Example usage:
.. code-block:: python
# ---- models.py file ----
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
.. code-block:: python
# ---- admin.py file ----
@admin.register(Author)
class Author(admin.ModelAdmin):
list_display = ('name', )
base = fany_list_display_modeladmin()
base.add_displays('id', 'name')
base.add_obj_link('author', 'Our Authors',
'{{obj.name}} (id={{obj.id}})')
@admin.register(Book)
class BookAdmin(base):
list_display = ('name', 'show_author')
A sample django admin page for "Book" would have the table:
+----+---------------------------------+------------------------+
| ID | Name | Our Authors |
+====+=================================+========================+
| 1 | Hitchhikers Guide To The Galaxy | *Douglas Adams (id=1)* |
+----+---------------------------------+------------------------+
| 2 | War and Peace | *Tolstoy (id=2)* |
+----+---------------------------------+------------------------+
| 3 | Dirk Gently | *Douglas Adams (id=1)* |
+----+---------------------------------+------------------------+
See :class:`FancyModelAdmin` for a full list of functionality
provided by the returned base class. | [
"Returns",
"a",
"new",
"copy",
"of",
"a",
":",
"class",
":",
"FancyModelAdmin",
"class",
"(",
"a",
"class",
"not",
"an",
"instance!",
")",
".",
"This",
"can",
"then",
"be",
"inherited",
"from",
"when",
"declaring",
"a",
"model",
"admin",
"class",
".",
"The",
":",
"class",
":",
"FancyModelAdmin",
"class",
"has",
"additional",
"methods",
"for",
"managing",
"the",
"list_display",
"attribute",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L439-L512 | valid |
cltrudeau/django-awl | awl/admintools.py | FancyModelAdmin.add_display | def add_display(cls, attr, title=''):
"""Adds a ``list_display`` property without any extra wrappers,
similar to :func:`add_displays`, but can also change the title.
:param attr:
Name of the attribute to add to the display
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
"""
global klass_count
klass_count += 1
fn_name = 'dyn_fn_%d' % klass_count
cls.list_display.append(fn_name)
if not title:
title = attr.capitalize()
def _ref(self, obj):
# use the django mechanism for field value lookup
_, _, value = lookup_field(attr, obj, cls)
return value
_ref.short_description = title
_ref.allow_tags = True
_ref.admin_order_field = attr
setattr(cls, fn_name, _ref) | python | def add_display(cls, attr, title=''):
"""Adds a ``list_display`` property without any extra wrappers,
similar to :func:`add_displays`, but can also change the title.
:param attr:
Name of the attribute to add to the display
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
"""
global klass_count
klass_count += 1
fn_name = 'dyn_fn_%d' % klass_count
cls.list_display.append(fn_name)
if not title:
title = attr.capitalize()
def _ref(self, obj):
# use the django mechanism for field value lookup
_, _, value = lookup_field(attr, obj, cls)
return value
_ref.short_description = title
_ref.allow_tags = True
_ref.admin_order_field = attr
setattr(cls, fn_name, _ref) | [
"def",
"add_display",
"(",
"cls",
",",
"attr",
",",
"title",
"=",
"''",
")",
":",
"global",
"klass_count",
"klass_count",
"+=",
"1",
"fn_name",
"=",
"'dyn_fn_%d'",
"%",
"klass_count",
"cls",
".",
"list_display",
".",
"append",
"(",
"fn_name",
")",
"if",
"not",
"title",
":",
"title",
"=",
"attr",
".",
"capitalize",
"(",
")",
"def",
"_ref",
"(",
"self",
",",
"obj",
")",
":",
"# use the django mechanism for field value lookup",
"_",
",",
"_",
",",
"value",
"=",
"lookup_field",
"(",
"attr",
",",
"obj",
",",
"cls",
")",
"return",
"value",
"_ref",
".",
"short_description",
"=",
"title",
"_ref",
".",
"allow_tags",
"=",
"True",
"_ref",
".",
"admin_order_field",
"=",
"attr",
"setattr",
"(",
"cls",
",",
"fn_name",
",",
"_ref",
")"
] | Adds a ``list_display`` property without any extra wrappers,
similar to :func:`add_displays`, but can also change the title.
:param attr:
Name of the attribute to add to the display
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr`` | [
"Adds",
"a",
"list_display",
"property",
"without",
"any",
"extra",
"wrappers",
"similar",
"to",
":",
"func",
":",
"add_displays",
"but",
"can",
"also",
"change",
"the",
"title",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L256-L283 | valid |
cltrudeau/django-awl | awl/admintools.py | FancyModelAdmin.add_link | def add_link(cls, attr, title='', display=''):
"""Adds a ``list_display`` attribute that appears as a link to the
django admin change page for the type of object being shown. Supports
double underscore attribute name dereferencing.
:param attr:
Name of the attribute to dereference from the corresponding
object, i.e. what will be lined to. This name supports double
underscore object link referencing for ``models.ForeignKey``
members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not
given it defaults to the string representation of the object for
the row: ``str(obj)`` . This parameter supports django
templating, the context for which contains a dictionary key named
"obj" with the value being the object for the row.
Example usage:
.. code-block:: python
# ---- admin.py file ----
base = fancy_modeladmin('id')
base.add_link('author', 'Our Authors',
'{{obj.name}} (id={{obj.id}})')
@admin.register(Book)
class BookAdmin(base):
pass
The django admin change page for the Book class would have a column
for "id" and another titled "Our Authors". The "Our Authors" column
would have a link for each Author object referenced by "book.author".
The link would go to the Author django admin change listing. The
display of the link would be the name of the author with the id in
brakcets, e.g. "Douglas Adams (id=42)"
"""
global klass_count
klass_count += 1
fn_name = 'dyn_fn_%d' % klass_count
cls.list_display.append(fn_name)
if not title:
title = attr.capitalize()
# python scoping is a bit weird with default values, if it isn't
# referenced the inner function won't see it, so assign it for use
_display = display
def _link(self, obj):
field_obj = admin_obj_attr(obj, attr)
if not field_obj:
return ''
text = _obj_display(field_obj, _display)
return admin_obj_link(field_obj, text)
_link.short_description = title
_link.allow_tags = True
_link.admin_order_field = attr
setattr(cls, fn_name, _link) | python | def add_link(cls, attr, title='', display=''):
"""Adds a ``list_display`` attribute that appears as a link to the
django admin change page for the type of object being shown. Supports
double underscore attribute name dereferencing.
:param attr:
Name of the attribute to dereference from the corresponding
object, i.e. what will be lined to. This name supports double
underscore object link referencing for ``models.ForeignKey``
members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not
given it defaults to the string representation of the object for
the row: ``str(obj)`` . This parameter supports django
templating, the context for which contains a dictionary key named
"obj" with the value being the object for the row.
Example usage:
.. code-block:: python
# ---- admin.py file ----
base = fancy_modeladmin('id')
base.add_link('author', 'Our Authors',
'{{obj.name}} (id={{obj.id}})')
@admin.register(Book)
class BookAdmin(base):
pass
The django admin change page for the Book class would have a column
for "id" and another titled "Our Authors". The "Our Authors" column
would have a link for each Author object referenced by "book.author".
The link would go to the Author django admin change listing. The
display of the link would be the name of the author with the id in
brakcets, e.g. "Douglas Adams (id=42)"
"""
global klass_count
klass_count += 1
fn_name = 'dyn_fn_%d' % klass_count
cls.list_display.append(fn_name)
if not title:
title = attr.capitalize()
# python scoping is a bit weird with default values, if it isn't
# referenced the inner function won't see it, so assign it for use
_display = display
def _link(self, obj):
field_obj = admin_obj_attr(obj, attr)
if not field_obj:
return ''
text = _obj_display(field_obj, _display)
return admin_obj_link(field_obj, text)
_link.short_description = title
_link.allow_tags = True
_link.admin_order_field = attr
setattr(cls, fn_name, _link) | [
"def",
"add_link",
"(",
"cls",
",",
"attr",
",",
"title",
"=",
"''",
",",
"display",
"=",
"''",
")",
":",
"global",
"klass_count",
"klass_count",
"+=",
"1",
"fn_name",
"=",
"'dyn_fn_%d'",
"%",
"klass_count",
"cls",
".",
"list_display",
".",
"append",
"(",
"fn_name",
")",
"if",
"not",
"title",
":",
"title",
"=",
"attr",
".",
"capitalize",
"(",
")",
"# python scoping is a bit weird with default values, if it isn't",
"# referenced the inner function won't see it, so assign it for use",
"_display",
"=",
"display",
"def",
"_link",
"(",
"self",
",",
"obj",
")",
":",
"field_obj",
"=",
"admin_obj_attr",
"(",
"obj",
",",
"attr",
")",
"if",
"not",
"field_obj",
":",
"return",
"''",
"text",
"=",
"_obj_display",
"(",
"field_obj",
",",
"_display",
")",
"return",
"admin_obj_link",
"(",
"field_obj",
",",
"text",
")",
"_link",
".",
"short_description",
"=",
"title",
"_link",
".",
"allow_tags",
"=",
"True",
"_link",
".",
"admin_order_field",
"=",
"attr",
"setattr",
"(",
"cls",
",",
"fn_name",
",",
"_link",
")"
] | Adds a ``list_display`` attribute that appears as a link to the
django admin change page for the type of object being shown. Supports
double underscore attribute name dereferencing.
:param attr:
Name of the attribute to dereference from the corresponding
object, i.e. what will be lined to. This name supports double
underscore object link referencing for ``models.ForeignKey``
members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not
given it defaults to the string representation of the object for
the row: ``str(obj)`` . This parameter supports django
templating, the context for which contains a dictionary key named
"obj" with the value being the object for the row.
Example usage:
.. code-block:: python
# ---- admin.py file ----
base = fancy_modeladmin('id')
base.add_link('author', 'Our Authors',
'{{obj.name}} (id={{obj.id}})')
@admin.register(Book)
class BookAdmin(base):
pass
The django admin change page for the Book class would have a column
for "id" and another titled "Our Authors". The "Our Authors" column
would have a link for each Author object referenced by "book.author".
The link would go to the Author django admin change listing. The
display of the link would be the name of the author with the id in
brakcets, e.g. "Douglas Adams (id=42)" | [
"Adds",
"a",
"list_display",
"attribute",
"that",
"appears",
"as",
"a",
"link",
"to",
"the",
"django",
"admin",
"change",
"page",
"for",
"the",
"type",
"of",
"object",
"being",
"shown",
".",
"Supports",
"double",
"underscore",
"attribute",
"name",
"dereferencing",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L286-L352 | valid |
cltrudeau/django-awl | awl/admintools.py | FancyModelAdmin.add_object | def add_object(cls, attr, title='', display=''):
"""Adds a ``list_display`` attribute showing an object. Supports
double underscore attribute name dereferencing.
:param attr:
Name of the attribute to dereference from the corresponding
object, i.e. what will be lined to. This name supports double
underscore object link referencing for ``models.ForeignKey``
members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not
given it defaults to the string representation of the object for
the row: ``str(obj)``. This parameter supports django templating,
the context for which contains a dictionary key named "obj" with
the value being the object for the row.
"""
global klass_count
klass_count += 1
fn_name = 'dyn_fn_%d' % klass_count
cls.list_display.append(fn_name)
if not title:
title = attr.capitalize()
# python scoping is a bit weird with default values, if it isn't
# referenced the inner function won't see it, so assign it for use
_display = display
def _ref(self, obj):
field_obj = admin_obj_attr(obj, attr)
if not field_obj:
return ''
return _obj_display(field_obj, _display)
_ref.short_description = title
_ref.allow_tags = True
_ref.admin_order_field = attr
setattr(cls, fn_name, _ref) | python | def add_object(cls, attr, title='', display=''):
"""Adds a ``list_display`` attribute showing an object. Supports
double underscore attribute name dereferencing.
:param attr:
Name of the attribute to dereference from the corresponding
object, i.e. what will be lined to. This name supports double
underscore object link referencing for ``models.ForeignKey``
members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not
given it defaults to the string representation of the object for
the row: ``str(obj)``. This parameter supports django templating,
the context for which contains a dictionary key named "obj" with
the value being the object for the row.
"""
global klass_count
klass_count += 1
fn_name = 'dyn_fn_%d' % klass_count
cls.list_display.append(fn_name)
if not title:
title = attr.capitalize()
# python scoping is a bit weird with default values, if it isn't
# referenced the inner function won't see it, so assign it for use
_display = display
def _ref(self, obj):
field_obj = admin_obj_attr(obj, attr)
if not field_obj:
return ''
return _obj_display(field_obj, _display)
_ref.short_description = title
_ref.allow_tags = True
_ref.admin_order_field = attr
setattr(cls, fn_name, _ref) | [
"def",
"add_object",
"(",
"cls",
",",
"attr",
",",
"title",
"=",
"''",
",",
"display",
"=",
"''",
")",
":",
"global",
"klass_count",
"klass_count",
"+=",
"1",
"fn_name",
"=",
"'dyn_fn_%d'",
"%",
"klass_count",
"cls",
".",
"list_display",
".",
"append",
"(",
"fn_name",
")",
"if",
"not",
"title",
":",
"title",
"=",
"attr",
".",
"capitalize",
"(",
")",
"# python scoping is a bit weird with default values, if it isn't",
"# referenced the inner function won't see it, so assign it for use",
"_display",
"=",
"display",
"def",
"_ref",
"(",
"self",
",",
"obj",
")",
":",
"field_obj",
"=",
"admin_obj_attr",
"(",
"obj",
",",
"attr",
")",
"if",
"not",
"field_obj",
":",
"return",
"''",
"return",
"_obj_display",
"(",
"field_obj",
",",
"_display",
")",
"_ref",
".",
"short_description",
"=",
"title",
"_ref",
".",
"allow_tags",
"=",
"True",
"_ref",
".",
"admin_order_field",
"=",
"attr",
"setattr",
"(",
"cls",
",",
"fn_name",
",",
"_ref",
")"
] | Adds a ``list_display`` attribute showing an object. Supports
double underscore attribute name dereferencing.
:param attr:
Name of the attribute to dereference from the corresponding
object, i.e. what will be lined to. This name supports double
underscore object link referencing for ``models.ForeignKey``
members.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``attr``
:param display:
What to display as the text for the link being shown. If not
given it defaults to the string representation of the object for
the row: ``str(obj)``. This parameter supports django templating,
the context for which contains a dictionary key named "obj" with
the value being the object for the row. | [
"Adds",
"a",
"list_display",
"attribute",
"showing",
"an",
"object",
".",
"Supports",
"double",
"underscore",
"attribute",
"name",
"dereferencing",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L355-L398 | valid |
cltrudeau/django-awl | awl/admintools.py | FancyModelAdmin.add_formatted_field | def add_formatted_field(cls, field, format_string, title=''):
"""Adds a ``list_display`` attribute showing a field in the object
using a python %formatted string.
:param field:
Name of the field in the object.
:param format_string:
A old-style (to remain python 2.x compatible) % string formatter
with a single variable reference. The named ``field`` attribute
will be passed to the formatter using the "%" operator.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``field``
"""
global klass_count
klass_count += 1
fn_name = 'dyn_fn_%d' % klass_count
cls.list_display.append(fn_name)
if not title:
title = field.capitalize()
# python scoping is a bit weird with default values, if it isn't
# referenced the inner function won't see it, so assign it for use
_format_string = format_string
def _ref(self, obj):
return _format_string % getattr(obj, field)
_ref.short_description = title
_ref.allow_tags = True
_ref.admin_order_field = field
setattr(cls, fn_name, _ref) | python | def add_formatted_field(cls, field, format_string, title=''):
"""Adds a ``list_display`` attribute showing a field in the object
using a python %formatted string.
:param field:
Name of the field in the object.
:param format_string:
A old-style (to remain python 2.x compatible) % string formatter
with a single variable reference. The named ``field`` attribute
will be passed to the formatter using the "%" operator.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``field``
"""
global klass_count
klass_count += 1
fn_name = 'dyn_fn_%d' % klass_count
cls.list_display.append(fn_name)
if not title:
title = field.capitalize()
# python scoping is a bit weird with default values, if it isn't
# referenced the inner function won't see it, so assign it for use
_format_string = format_string
def _ref(self, obj):
return _format_string % getattr(obj, field)
_ref.short_description = title
_ref.allow_tags = True
_ref.admin_order_field = field
setattr(cls, fn_name, _ref) | [
"def",
"add_formatted_field",
"(",
"cls",
",",
"field",
",",
"format_string",
",",
"title",
"=",
"''",
")",
":",
"global",
"klass_count",
"klass_count",
"+=",
"1",
"fn_name",
"=",
"'dyn_fn_%d'",
"%",
"klass_count",
"cls",
".",
"list_display",
".",
"append",
"(",
"fn_name",
")",
"if",
"not",
"title",
":",
"title",
"=",
"field",
".",
"capitalize",
"(",
")",
"# python scoping is a bit weird with default values, if it isn't",
"# referenced the inner function won't see it, so assign it for use",
"_format_string",
"=",
"format_string",
"def",
"_ref",
"(",
"self",
",",
"obj",
")",
":",
"return",
"_format_string",
"%",
"getattr",
"(",
"obj",
",",
"field",
")",
"_ref",
".",
"short_description",
"=",
"title",
"_ref",
".",
"allow_tags",
"=",
"True",
"_ref",
".",
"admin_order_field",
"=",
"field",
"setattr",
"(",
"cls",
",",
"fn_name",
",",
"_ref",
")"
] | Adds a ``list_display`` attribute showing a field in the object
using a python %formatted string.
:param field:
Name of the field in the object.
:param format_string:
A old-style (to remain python 2.x compatible) % string formatter
with a single variable reference. The named ``field`` attribute
will be passed to the formatter using the "%" operator.
:param title:
Title for the column of the django admin table. If not given it
defaults to a capitalized version of ``field`` | [
"Adds",
"a",
"list_display",
"attribute",
"showing",
"a",
"field",
"in",
"the",
"object",
"using",
"a",
"python",
"%formatted",
"string",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/admintools.py#L401-L435 | valid |
cltrudeau/django-awl | awl/decorators.py | post_required | def post_required(method_or_options=[]):
"""View decorator that enforces that the method was called using POST.
This decorator can be called with or without parameters. As it is
expected to wrap a view, the first argument of the method being wrapped is
expected to be a ``request`` object.
.. code-block:: python
@post_required
def some_view(request):
pass
@post_required(['firstname', 'lastname'])
def some_view(request):
pass
The optional parameter contains a single list which specifies the names of
the expected fields in the POST dictionary. The list is not exclusive,
you can pass in fields that are not checked by the decorator.
:param options:
List of the names of expected POST keys.
"""
def decorator(method):
# handle wrapping or wrapping with arguments; if no arguments (and no
# calling parenthesis) then method_or_options will be a list,
# otherwise it will be the wrapped function
expected_fields = []
if not callable(method_or_options):
# not callable means wrapping with arguments
expected_fields = method_or_options
@wraps(method)
def wrapper(*args, **kwargs):
request = args[0]
if request.method != 'POST':
logger.error('POST required for this url')
raise Http404('only POST allowed for this url')
missing = []
for field in expected_fields:
if field not in request.POST:
missing.append(field)
if missing:
s = 'Expected fields missing in POST: %s' % missing
logger.error(s)
raise Http404(s)
# everything verified, run the view
return method(*args, **kwargs)
return wrapper
if callable(method_or_options):
# callable means decorated method without options, call our decorator
return decorator(method_or_options)
return decorator | python | def post_required(method_or_options=[]):
"""View decorator that enforces that the method was called using POST.
This decorator can be called with or without parameters. As it is
expected to wrap a view, the first argument of the method being wrapped is
expected to be a ``request`` object.
.. code-block:: python
@post_required
def some_view(request):
pass
@post_required(['firstname', 'lastname'])
def some_view(request):
pass
The optional parameter contains a single list which specifies the names of
the expected fields in the POST dictionary. The list is not exclusive,
you can pass in fields that are not checked by the decorator.
:param options:
List of the names of expected POST keys.
"""
def decorator(method):
# handle wrapping or wrapping with arguments; if no arguments (and no
# calling parenthesis) then method_or_options will be a list,
# otherwise it will be the wrapped function
expected_fields = []
if not callable(method_or_options):
# not callable means wrapping with arguments
expected_fields = method_or_options
@wraps(method)
def wrapper(*args, **kwargs):
request = args[0]
if request.method != 'POST':
logger.error('POST required for this url')
raise Http404('only POST allowed for this url')
missing = []
for field in expected_fields:
if field not in request.POST:
missing.append(field)
if missing:
s = 'Expected fields missing in POST: %s' % missing
logger.error(s)
raise Http404(s)
# everything verified, run the view
return method(*args, **kwargs)
return wrapper
if callable(method_or_options):
# callable means decorated method without options, call our decorator
return decorator(method_or_options)
return decorator | [
"def",
"post_required",
"(",
"method_or_options",
"=",
"[",
"]",
")",
":",
"def",
"decorator",
"(",
"method",
")",
":",
"# handle wrapping or wrapping with arguments; if no arguments (and no",
"# calling parenthesis) then method_or_options will be a list,",
"# otherwise it will be the wrapped function",
"expected_fields",
"=",
"[",
"]",
"if",
"not",
"callable",
"(",
"method_or_options",
")",
":",
"# not callable means wrapping with arguments",
"expected_fields",
"=",
"method_or_options",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"args",
"[",
"0",
"]",
"if",
"request",
".",
"method",
"!=",
"'POST'",
":",
"logger",
".",
"error",
"(",
"'POST required for this url'",
")",
"raise",
"Http404",
"(",
"'only POST allowed for this url'",
")",
"missing",
"=",
"[",
"]",
"for",
"field",
"in",
"expected_fields",
":",
"if",
"field",
"not",
"in",
"request",
".",
"POST",
":",
"missing",
".",
"append",
"(",
"field",
")",
"if",
"missing",
":",
"s",
"=",
"'Expected fields missing in POST: %s'",
"%",
"missing",
"logger",
".",
"error",
"(",
"s",
")",
"raise",
"Http404",
"(",
"s",
")",
"# everything verified, run the view",
"return",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper",
"if",
"callable",
"(",
"method_or_options",
")",
":",
"# callable means decorated method without options, call our decorator ",
"return",
"decorator",
"(",
"method_or_options",
")",
"return",
"decorator"
] | View decorator that enforces that the method was called using POST.
This decorator can be called with or without parameters. As it is
expected to wrap a view, the first argument of the method being wrapped is
expected to be a ``request`` object.
.. code-block:: python
@post_required
def some_view(request):
pass
@post_required(['firstname', 'lastname'])
def some_view(request):
pass
The optional parameter contains a single list which specifies the names of
the expected fields in the POST dictionary. The list is not exclusive,
you can pass in fields that are not checked by the decorator.
:param options:
List of the names of expected POST keys. | [
"View",
"decorator",
"that",
"enforces",
"that",
"the",
"method",
"was",
"called",
"using",
"POST",
".",
"This",
"decorator",
"can",
"be",
"called",
"with",
"or",
"without",
"parameters",
".",
"As",
"it",
"is",
"expected",
"to",
"wrap",
"a",
"view",
"the",
"first",
"argument",
"of",
"the",
"method",
"being",
"wrapped",
"is",
"expected",
"to",
"be",
"a",
"request",
"object",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/decorators.py#L13-L70 | valid |
cltrudeau/django-awl | awl/decorators.py | json_post_required | def json_post_required(*decorator_args):
"""View decorator that enforces that the method was called using POST and
contains a field containing a JSON dictionary. This method should
only be used to wrap views and assumes the first argument of the method
being wrapped is a ``request`` object.
.. code-block:: python
@json_post_required('data', 'json_data')
def some_view(request):
username = request.json_data['username']
:param field:
The name of the POST field that contains a JSON dictionary
:param request_name:
[optional] Name of the parameter on the request to put the
deserialized JSON data. If not given the field name is used
"""
def decorator(method):
@wraps(method)
def wrapper(*args, **kwargs):
field = decorator_args[0]
if len(decorator_args) == 2:
request_name = decorator_args[1]
else:
request_name = field
request = args[0]
if request.method != 'POST':
logger.error('POST required for this url')
raise Http404('only POST allowed for this url')
if field not in request.POST:
s = 'Expected field named %s in POST' % field
logger.error(s)
raise Http404(s)
# deserialize the JSON and put it in the request
setattr(request, request_name, json.loads(request.POST[field]))
# everything verified, run the view
return method(*args, **kwargs)
return wrapper
return decorator | python | def json_post_required(*decorator_args):
"""View decorator that enforces that the method was called using POST and
contains a field containing a JSON dictionary. This method should
only be used to wrap views and assumes the first argument of the method
being wrapped is a ``request`` object.
.. code-block:: python
@json_post_required('data', 'json_data')
def some_view(request):
username = request.json_data['username']
:param field:
The name of the POST field that contains a JSON dictionary
:param request_name:
[optional] Name of the parameter on the request to put the
deserialized JSON data. If not given the field name is used
"""
def decorator(method):
@wraps(method)
def wrapper(*args, **kwargs):
field = decorator_args[0]
if len(decorator_args) == 2:
request_name = decorator_args[1]
else:
request_name = field
request = args[0]
if request.method != 'POST':
logger.error('POST required for this url')
raise Http404('only POST allowed for this url')
if field not in request.POST:
s = 'Expected field named %s in POST' % field
logger.error(s)
raise Http404(s)
# deserialize the JSON and put it in the request
setattr(request, request_name, json.loads(request.POST[field]))
# everything verified, run the view
return method(*args, **kwargs)
return wrapper
return decorator | [
"def",
"json_post_required",
"(",
"*",
"decorator_args",
")",
":",
"def",
"decorator",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"field",
"=",
"decorator_args",
"[",
"0",
"]",
"if",
"len",
"(",
"decorator_args",
")",
"==",
"2",
":",
"request_name",
"=",
"decorator_args",
"[",
"1",
"]",
"else",
":",
"request_name",
"=",
"field",
"request",
"=",
"args",
"[",
"0",
"]",
"if",
"request",
".",
"method",
"!=",
"'POST'",
":",
"logger",
".",
"error",
"(",
"'POST required for this url'",
")",
"raise",
"Http404",
"(",
"'only POST allowed for this url'",
")",
"if",
"field",
"not",
"in",
"request",
".",
"POST",
":",
"s",
"=",
"'Expected field named %s in POST'",
"%",
"field",
"logger",
".",
"error",
"(",
"s",
")",
"raise",
"Http404",
"(",
"s",
")",
"# deserialize the JSON and put it in the request",
"setattr",
"(",
"request",
",",
"request_name",
",",
"json",
".",
"loads",
"(",
"request",
".",
"POST",
"[",
"field",
"]",
")",
")",
"# everything verified, run the view",
"return",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper",
"return",
"decorator"
] | View decorator that enforces that the method was called using POST and
contains a field containing a JSON dictionary. This method should
only be used to wrap views and assumes the first argument of the method
being wrapped is a ``request`` object.
.. code-block:: python
@json_post_required('data', 'json_data')
def some_view(request):
username = request.json_data['username']
:param field:
The name of the POST field that contains a JSON dictionary
:param request_name:
[optional] Name of the parameter on the request to put the
deserialized JSON data. If not given the field name is used | [
"View",
"decorator",
"that",
"enforces",
"that",
"the",
"method",
"was",
"called",
"using",
"POST",
"and",
"contains",
"a",
"field",
"containing",
"a",
"JSON",
"dictionary",
".",
"This",
"method",
"should",
"only",
"be",
"used",
"to",
"wrap",
"views",
"and",
"assumes",
"the",
"first",
"argument",
"of",
"the",
"method",
"being",
"wrapped",
"is",
"a",
"request",
"object",
"."
] | 70d469ef9a161c1170b53aa017cf02d7c15eb90c | https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/decorators.py#L73-L117 | valid |
joelfrederico/SciSalt | scisalt/matplotlib/hist.py | hist | def hist(x, bins=10, labels=None, aspect="auto", plot=True, ax=None, range=None):
"""
Creates a histogram of data *x* with a *bins*, *labels* = :code:`[title, xlabel, ylabel]`.
"""
h, edge = _np.histogram(x, bins=bins, range=range)
mids = edge + (edge[1]-edge[0])/2
mids = mids[:-1]
if plot:
if ax is None:
_plt.hist(x, bins=bins, range=range)
else:
ax.hist(x, bins=bins, range=range)
if labels is not None:
_addlabel(labels[0], labels[1], labels[2])
return h, mids | python | def hist(x, bins=10, labels=None, aspect="auto", plot=True, ax=None, range=None):
"""
Creates a histogram of data *x* with a *bins*, *labels* = :code:`[title, xlabel, ylabel]`.
"""
h, edge = _np.histogram(x, bins=bins, range=range)
mids = edge + (edge[1]-edge[0])/2
mids = mids[:-1]
if plot:
if ax is None:
_plt.hist(x, bins=bins, range=range)
else:
ax.hist(x, bins=bins, range=range)
if labels is not None:
_addlabel(labels[0], labels[1], labels[2])
return h, mids | [
"def",
"hist",
"(",
"x",
",",
"bins",
"=",
"10",
",",
"labels",
"=",
"None",
",",
"aspect",
"=",
"\"auto\"",
",",
"plot",
"=",
"True",
",",
"ax",
"=",
"None",
",",
"range",
"=",
"None",
")",
":",
"h",
",",
"edge",
"=",
"_np",
".",
"histogram",
"(",
"x",
",",
"bins",
"=",
"bins",
",",
"range",
"=",
"range",
")",
"mids",
"=",
"edge",
"+",
"(",
"edge",
"[",
"1",
"]",
"-",
"edge",
"[",
"0",
"]",
")",
"/",
"2",
"mids",
"=",
"mids",
"[",
":",
"-",
"1",
"]",
"if",
"plot",
":",
"if",
"ax",
"is",
"None",
":",
"_plt",
".",
"hist",
"(",
"x",
",",
"bins",
"=",
"bins",
",",
"range",
"=",
"range",
")",
"else",
":",
"ax",
".",
"hist",
"(",
"x",
",",
"bins",
"=",
"bins",
",",
"range",
"=",
"range",
")",
"if",
"labels",
"is",
"not",
"None",
":",
"_addlabel",
"(",
"labels",
"[",
"0",
"]",
",",
"labels",
"[",
"1",
"]",
",",
"labels",
"[",
"2",
"]",
")",
"return",
"h",
",",
"mids"
] | Creates a histogram of data *x* with a *bins*, *labels* = :code:`[title, xlabel, ylabel]`. | [
"Creates",
"a",
"histogram",
"of",
"data",
"*",
"x",
"*",
"with",
"a",
"*",
"bins",
"*",
"*",
"labels",
"*",
"=",
":",
"code",
":",
"[",
"title",
"xlabel",
"ylabel",
"]",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/hist.py#L10-L29 | valid |
joelfrederico/SciSalt | scisalt/PWFA/match.py | Match.sigma | def sigma(self):
"""
Spot size of matched beam :math:`\\left( \\frac{2 E \\varepsilon_0 }{ n_p e^2 } \\right)^{1/4} \\sqrt{\\epsilon}`
"""
return _np.power(2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.plasma.n_p * _np.power(_spc.elementary_charge, 2)) , 0.25) * _np.sqrt(self.emit) | python | def sigma(self):
"""
Spot size of matched beam :math:`\\left( \\frac{2 E \\varepsilon_0 }{ n_p e^2 } \\right)^{1/4} \\sqrt{\\epsilon}`
"""
return _np.power(2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.plasma.n_p * _np.power(_spc.elementary_charge, 2)) , 0.25) * _np.sqrt(self.emit) | [
"def",
"sigma",
"(",
"self",
")",
":",
"return",
"_np",
".",
"power",
"(",
"2",
"*",
"_sltr",
".",
"GeV2joule",
"(",
"self",
".",
"E",
")",
"*",
"_spc",
".",
"epsilon_0",
"/",
"(",
"self",
".",
"plasma",
".",
"n_p",
"*",
"_np",
".",
"power",
"(",
"_spc",
".",
"elementary_charge",
",",
"2",
")",
")",
",",
"0.25",
")",
"*",
"_np",
".",
"sqrt",
"(",
"self",
".",
"emit",
")"
] | Spot size of matched beam :math:`\\left( \\frac{2 E \\varepsilon_0 }{ n_p e^2 } \\right)^{1/4} \\sqrt{\\epsilon}` | [
"Spot",
"size",
"of",
"matched",
"beam",
":",
"math",
":",
"\\\\",
"left",
"(",
"\\\\",
"frac",
"{",
"2",
"E",
"\\\\",
"varepsilon_0",
"}",
"{",
"n_p",
"e^2",
"}",
"\\\\",
"right",
")",
"^",
"{",
"1",
"/",
"4",
"}",
"\\\\",
"sqrt",
"{",
"\\\\",
"epsilon",
"}"
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/match.py#L53-L57 | valid |
joelfrederico/SciSalt | scisalt/PWFA/match.py | Match.sigma_prime | def sigma_prime(self):
"""
Divergence of matched beam
"""
return _np.sqrt(self.emit/self.beta(self.E)) | python | def sigma_prime(self):
"""
Divergence of matched beam
"""
return _np.sqrt(self.emit/self.beta(self.E)) | [
"def",
"sigma_prime",
"(",
"self",
")",
":",
"return",
"_np",
".",
"sqrt",
"(",
"self",
".",
"emit",
"/",
"self",
".",
"beta",
"(",
"self",
".",
"E",
")",
")"
] | Divergence of matched beam | [
"Divergence",
"of",
"matched",
"beam"
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/match.py#L67-L71 | valid |
joelfrederico/SciSalt | scisalt/PWFA/match.py | MatchPlasma.n_p | def n_p(self):
"""
The plasma density in SI units.
"""
return 2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.beta*_spc.elementary_charge)**2 | python | def n_p(self):
"""
The plasma density in SI units.
"""
return 2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.beta*_spc.elementary_charge)**2 | [
"def",
"n_p",
"(",
"self",
")",
":",
"return",
"2",
"*",
"_sltr",
".",
"GeV2joule",
"(",
"self",
".",
"E",
")",
"*",
"_spc",
".",
"epsilon_0",
"/",
"(",
"self",
".",
"beta",
"*",
"_spc",
".",
"elementary_charge",
")",
"**",
"2"
] | The plasma density in SI units. | [
"The",
"plasma",
"density",
"in",
"SI",
"units",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/match.py#L127-L131 | valid |
joelfrederico/SciSalt | scisalt/PWFA/match.py | MatchPlasma.plasma | def plasma(self, species=_pt.hydrogen):
"""
The matched :class:`Plasma`.
"""
return _Plasma(self.n_p, species=species) | python | def plasma(self, species=_pt.hydrogen):
"""
The matched :class:`Plasma`.
"""
return _Plasma(self.n_p, species=species) | [
"def",
"plasma",
"(",
"self",
",",
"species",
"=",
"_pt",
".",
"hydrogen",
")",
":",
"return",
"_Plasma",
"(",
"self",
".",
"n_p",
",",
"species",
"=",
"species",
")"
] | The matched :class:`Plasma`. | [
"The",
"matched",
":",
"class",
":",
"Plasma",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/match.py#L141-L145 | valid |
ewilazarus/yld | yld/__main__.py | main | def main(target, label):
"""
Semver tag triggered deployment helper
"""
check_environment(target, label)
click.secho('Fetching tags from the upstream ...')
handler = TagHandler(git.list_tags())
print_information(handler, label)
tag = handler.yield_tag(target, label)
confirm(tag) | python | def main(target, label):
"""
Semver tag triggered deployment helper
"""
check_environment(target, label)
click.secho('Fetching tags from the upstream ...')
handler = TagHandler(git.list_tags())
print_information(handler, label)
tag = handler.yield_tag(target, label)
confirm(tag) | [
"def",
"main",
"(",
"target",
",",
"label",
")",
":",
"check_environment",
"(",
"target",
",",
"label",
")",
"click",
".",
"secho",
"(",
"'Fetching tags from the upstream ...'",
")",
"handler",
"=",
"TagHandler",
"(",
"git",
".",
"list_tags",
"(",
")",
")",
"print_information",
"(",
"handler",
",",
"label",
")",
"tag",
"=",
"handler",
".",
"yield_tag",
"(",
"target",
",",
"label",
")",
"confirm",
"(",
"tag",
")"
] | Semver tag triggered deployment helper | [
"Semver",
"tag",
"triggered",
"deployment",
"helper"
] | 157e474d1055f14ffdfd7e99da6c77d5f17d4307 | https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/__main__.py#L26-L38 | valid |
ewilazarus/yld | yld/__main__.py | check_environment | def check_environment(target, label):
"""
Performs some environment checks prior to the program's execution
"""
if not git.exists():
click.secho('You must have git installed to use yld.', fg='red')
sys.exit(1)
if not os.path.isdir('.git'):
click.secho('You must cd into a git repository to use yld.', fg='red')
sys.exit(1)
if not git.is_committed():
click.secho('You must commit or stash your work before proceeding.',
fg='red')
sys.exit(1)
if target is None and label is None:
click.secho('You must specify either a target or a label.', fg='red')
sys.exit(1) | python | def check_environment(target, label):
"""
Performs some environment checks prior to the program's execution
"""
if not git.exists():
click.secho('You must have git installed to use yld.', fg='red')
sys.exit(1)
if not os.path.isdir('.git'):
click.secho('You must cd into a git repository to use yld.', fg='red')
sys.exit(1)
if not git.is_committed():
click.secho('You must commit or stash your work before proceeding.',
fg='red')
sys.exit(1)
if target is None and label is None:
click.secho('You must specify either a target or a label.', fg='red')
sys.exit(1) | [
"def",
"check_environment",
"(",
"target",
",",
"label",
")",
":",
"if",
"not",
"git",
".",
"exists",
"(",
")",
":",
"click",
".",
"secho",
"(",
"'You must have git installed to use yld.'",
",",
"fg",
"=",
"'red'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"'.git'",
")",
":",
"click",
".",
"secho",
"(",
"'You must cd into a git repository to use yld.'",
",",
"fg",
"=",
"'red'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"not",
"git",
".",
"is_committed",
"(",
")",
":",
"click",
".",
"secho",
"(",
"'You must commit or stash your work before proceeding.'",
",",
"fg",
"=",
"'red'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"target",
"is",
"None",
"and",
"label",
"is",
"None",
":",
"click",
".",
"secho",
"(",
"'You must specify either a target or a label.'",
",",
"fg",
"=",
"'red'",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Performs some environment checks prior to the program's execution | [
"Performs",
"some",
"environment",
"checks",
"prior",
"to",
"the",
"program",
"s",
"execution"
] | 157e474d1055f14ffdfd7e99da6c77d5f17d4307 | https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/__main__.py#L41-L60 | valid |
ewilazarus/yld | yld/__main__.py | print_information | def print_information(handler, label):
"""
Prints latest tag's information
"""
click.echo('=> Latest stable: {tag}'.format(
tag=click.style(str(handler.latest_stable or 'N/A'), fg='yellow' if
handler.latest_stable else 'magenta')
))
if label is not None:
latest_revision = handler.latest_revision(label)
click.echo('=> Latest relative revision ({label}): {tag}'.format(
label=click.style(label, fg='blue'),
tag=click.style(str(latest_revision or 'N/A'),
fg='yellow' if latest_revision else 'magenta')
)) | python | def print_information(handler, label):
"""
Prints latest tag's information
"""
click.echo('=> Latest stable: {tag}'.format(
tag=click.style(str(handler.latest_stable or 'N/A'), fg='yellow' if
handler.latest_stable else 'magenta')
))
if label is not None:
latest_revision = handler.latest_revision(label)
click.echo('=> Latest relative revision ({label}): {tag}'.format(
label=click.style(label, fg='blue'),
tag=click.style(str(latest_revision or 'N/A'),
fg='yellow' if latest_revision else 'magenta')
)) | [
"def",
"print_information",
"(",
"handler",
",",
"label",
")",
":",
"click",
".",
"echo",
"(",
"'=> Latest stable: {tag}'",
".",
"format",
"(",
"tag",
"=",
"click",
".",
"style",
"(",
"str",
"(",
"handler",
".",
"latest_stable",
"or",
"'N/A'",
")",
",",
"fg",
"=",
"'yellow'",
"if",
"handler",
".",
"latest_stable",
"else",
"'magenta'",
")",
")",
")",
"if",
"label",
"is",
"not",
"None",
":",
"latest_revision",
"=",
"handler",
".",
"latest_revision",
"(",
"label",
")",
"click",
".",
"echo",
"(",
"'=> Latest relative revision ({label}): {tag}'",
".",
"format",
"(",
"label",
"=",
"click",
".",
"style",
"(",
"label",
",",
"fg",
"=",
"'blue'",
")",
",",
"tag",
"=",
"click",
".",
"style",
"(",
"str",
"(",
"latest_revision",
"or",
"'N/A'",
")",
",",
"fg",
"=",
"'yellow'",
"if",
"latest_revision",
"else",
"'magenta'",
")",
")",
")"
] | Prints latest tag's information | [
"Prints",
"latest",
"tag",
"s",
"information"
] | 157e474d1055f14ffdfd7e99da6c77d5f17d4307 | https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/__main__.py#L63-L78 | valid |
ewilazarus/yld | yld/__main__.py | confirm | def confirm(tag):
"""
Prompts user before proceeding
"""
click.echo()
if click.confirm('Do you want to create the tag {tag}?'.format(
tag=click.style(str(tag), fg='yellow')),
default=True, abort=True):
git.create_tag(tag)
if click.confirm(
'Do you want to push the tag {tag} into the upstream?'.format(
tag=click.style(str(tag), fg='yellow')),
default=True):
git.push_tag(tag)
click.echo('Done!')
else:
git.delete_tag(tag)
click.echo('Aborted!') | python | def confirm(tag):
"""
Prompts user before proceeding
"""
click.echo()
if click.confirm('Do you want to create the tag {tag}?'.format(
tag=click.style(str(tag), fg='yellow')),
default=True, abort=True):
git.create_tag(tag)
if click.confirm(
'Do you want to push the tag {tag} into the upstream?'.format(
tag=click.style(str(tag), fg='yellow')),
default=True):
git.push_tag(tag)
click.echo('Done!')
else:
git.delete_tag(tag)
click.echo('Aborted!') | [
"def",
"confirm",
"(",
"tag",
")",
":",
"click",
".",
"echo",
"(",
")",
"if",
"click",
".",
"confirm",
"(",
"'Do you want to create the tag {tag}?'",
".",
"format",
"(",
"tag",
"=",
"click",
".",
"style",
"(",
"str",
"(",
"tag",
")",
",",
"fg",
"=",
"'yellow'",
")",
")",
",",
"default",
"=",
"True",
",",
"abort",
"=",
"True",
")",
":",
"git",
".",
"create_tag",
"(",
"tag",
")",
"if",
"click",
".",
"confirm",
"(",
"'Do you want to push the tag {tag} into the upstream?'",
".",
"format",
"(",
"tag",
"=",
"click",
".",
"style",
"(",
"str",
"(",
"tag",
")",
",",
"fg",
"=",
"'yellow'",
")",
")",
",",
"default",
"=",
"True",
")",
":",
"git",
".",
"push_tag",
"(",
"tag",
")",
"click",
".",
"echo",
"(",
"'Done!'",
")",
"else",
":",
"git",
".",
"delete_tag",
"(",
"tag",
")",
"click",
".",
"echo",
"(",
"'Aborted!'",
")"
] | Prompts user before proceeding | [
"Prompts",
"user",
"before",
"proceeding"
] | 157e474d1055f14ffdfd7e99da6c77d5f17d4307 | https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/__main__.py#L81-L99 | valid |
joelfrederico/SciSalt | scisalt/matplotlib/imshow.py | imshow | def imshow(X, ax=None, add_cbar=True, rescale_fig=True, **kwargs):
"""
Plots an array *X* such that the first coordinate is the *x* coordinate and the second coordinate is the *y* coordinate, with the origin at the bottom left corner.
Optional argument *ax* allows an existing axes to be used.
*\*\*kwargs* are passed on to :meth:`matplotlib.axes.Axes.imshow`.
.. versionadded:: 1.3
Returns
-------
fig, ax, im :
if axes aren't specified.
im :
if axes are specified.
"""
return _plot_array(X, plottype=_IMSHOW, ax=ax, add_cbar=add_cbar, rescale_fig=rescale_fig, **kwargs) | python | def imshow(X, ax=None, add_cbar=True, rescale_fig=True, **kwargs):
"""
Plots an array *X* such that the first coordinate is the *x* coordinate and the second coordinate is the *y* coordinate, with the origin at the bottom left corner.
Optional argument *ax* allows an existing axes to be used.
*\*\*kwargs* are passed on to :meth:`matplotlib.axes.Axes.imshow`.
.. versionadded:: 1.3
Returns
-------
fig, ax, im :
if axes aren't specified.
im :
if axes are specified.
"""
return _plot_array(X, plottype=_IMSHOW, ax=ax, add_cbar=add_cbar, rescale_fig=rescale_fig, **kwargs) | [
"def",
"imshow",
"(",
"X",
",",
"ax",
"=",
"None",
",",
"add_cbar",
"=",
"True",
",",
"rescale_fig",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_plot_array",
"(",
"X",
",",
"plottype",
"=",
"_IMSHOW",
",",
"ax",
"=",
"ax",
",",
"add_cbar",
"=",
"add_cbar",
",",
"rescale_fig",
"=",
"rescale_fig",
",",
"*",
"*",
"kwargs",
")"
] | Plots an array *X* such that the first coordinate is the *x* coordinate and the second coordinate is the *y* coordinate, with the origin at the bottom left corner.
Optional argument *ax* allows an existing axes to be used.
*\*\*kwargs* are passed on to :meth:`matplotlib.axes.Axes.imshow`.
.. versionadded:: 1.3
Returns
-------
fig, ax, im :
if axes aren't specified.
im :
if axes are specified. | [
"Plots",
"an",
"array",
"*",
"X",
"*",
"such",
"that",
"the",
"first",
"coordinate",
"is",
"the",
"*",
"x",
"*",
"coordinate",
"and",
"the",
"second",
"coordinate",
"is",
"the",
"*",
"y",
"*",
"coordinate",
"with",
"the",
"origin",
"at",
"the",
"bottom",
"left",
"corner",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/imshow.py#L28-L45 | valid |
joelfrederico/SciSalt | scisalt/matplotlib/imshow.py | scaled_figsize | def scaled_figsize(X, figsize=None, h_pad=None, v_pad=None):
"""
Given an array *X*, determine a good size for the figure to be by shrinking it to fit within *figsize*. If not specified, shrinks to fit the figsize specified by the current :attr:`matplotlib.rcParams`.
.. versionadded:: 1.3
"""
if figsize is None:
figsize = _mpl.rcParams['figure.figsize']
# ======================================
# Find the height and width
# ======================================
width, height = _np.shape(X)
ratio = width / height
# ======================================
# Find how to rescale the figure
# ======================================
if ratio > figsize[0]/figsize[1]:
figsize[1] = figsize[0] / ratio
else:
figsize[0] = figsize[1] * ratio
return figsize | python | def scaled_figsize(X, figsize=None, h_pad=None, v_pad=None):
"""
Given an array *X*, determine a good size for the figure to be by shrinking it to fit within *figsize*. If not specified, shrinks to fit the figsize specified by the current :attr:`matplotlib.rcParams`.
.. versionadded:: 1.3
"""
if figsize is None:
figsize = _mpl.rcParams['figure.figsize']
# ======================================
# Find the height and width
# ======================================
width, height = _np.shape(X)
ratio = width / height
# ======================================
# Find how to rescale the figure
# ======================================
if ratio > figsize[0]/figsize[1]:
figsize[1] = figsize[0] / ratio
else:
figsize[0] = figsize[1] * ratio
return figsize | [
"def",
"scaled_figsize",
"(",
"X",
",",
"figsize",
"=",
"None",
",",
"h_pad",
"=",
"None",
",",
"v_pad",
"=",
"None",
")",
":",
"if",
"figsize",
"is",
"None",
":",
"figsize",
"=",
"_mpl",
".",
"rcParams",
"[",
"'figure.figsize'",
"]",
"# ======================================",
"# Find the height and width",
"# ======================================",
"width",
",",
"height",
"=",
"_np",
".",
"shape",
"(",
"X",
")",
"ratio",
"=",
"width",
"/",
"height",
"# ======================================",
"# Find how to rescale the figure",
"# ======================================",
"if",
"ratio",
">",
"figsize",
"[",
"0",
"]",
"/",
"figsize",
"[",
"1",
"]",
":",
"figsize",
"[",
"1",
"]",
"=",
"figsize",
"[",
"0",
"]",
"/",
"ratio",
"else",
":",
"figsize",
"[",
"0",
"]",
"=",
"figsize",
"[",
"1",
"]",
"*",
"ratio",
"return",
"figsize"
] | Given an array *X*, determine a good size for the figure to be by shrinking it to fit within *figsize*. If not specified, shrinks to fit the figsize specified by the current :attr:`matplotlib.rcParams`.
.. versionadded:: 1.3 | [
"Given",
"an",
"array",
"*",
"X",
"*",
"determine",
"a",
"good",
"size",
"for",
"the",
"figure",
"to",
"be",
"by",
"shrinking",
"it",
"to",
"fit",
"within",
"*",
"figsize",
"*",
".",
"If",
"not",
"specified",
"shrinks",
"to",
"fit",
"the",
"figsize",
"specified",
"by",
"the",
"current",
":",
"attr",
":",
"matplotlib",
".",
"rcParams",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/imshow.py#L132-L156 | valid |
joelfrederico/SciSalt | scisalt/h5/h5.py | get | def get(f, key, default=None):
"""
Gets an array from datasets.
.. versionadded:: 1.4
"""
if key in f.keys():
val = f[key].value
if default is None:
return val
else:
if _np.shape(val) == _np.shape(default):
return val
return default | python | def get(f, key, default=None):
"""
Gets an array from datasets.
.. versionadded:: 1.4
"""
if key in f.keys():
val = f[key].value
if default is None:
return val
else:
if _np.shape(val) == _np.shape(default):
return val
return default | [
"def",
"get",
"(",
"f",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"in",
"f",
".",
"keys",
"(",
")",
":",
"val",
"=",
"f",
"[",
"key",
"]",
".",
"value",
"if",
"default",
"is",
"None",
":",
"return",
"val",
"else",
":",
"if",
"_np",
".",
"shape",
"(",
"val",
")",
"==",
"_np",
".",
"shape",
"(",
"default",
")",
":",
"return",
"val",
"return",
"default"
] | Gets an array from datasets.
.. versionadded:: 1.4 | [
"Gets",
"an",
"array",
"from",
"datasets",
"."
] | 7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f | https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/h5/h5.py#L28-L44 | valid |