id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
247,100 |
openpermissions/perch
|
perch/model.py
|
SubResource._save
|
def _save(self):
"""Save the sub-resource within the parent resource"""
yield self.validate()
try:
self._parent = yield self.parent_resource.get(self.parent_id)
except couch.NotFound:
msg = '{}_id {} not found'.format(
self.parent_resource.resource_type,
self.parent_id)
raise exceptions.ValidationError(msg)
yield self._parent.save_subresource(self)
|
python
|
def _save(self):
"""Save the sub-resource within the parent resource"""
yield self.validate()
try:
self._parent = yield self.parent_resource.get(self.parent_id)
except couch.NotFound:
msg = '{}_id {} not found'.format(
self.parent_resource.resource_type,
self.parent_id)
raise exceptions.ValidationError(msg)
yield self._parent.save_subresource(self)
|
[
"def",
"_save",
"(",
"self",
")",
":",
"yield",
"self",
".",
"validate",
"(",
")",
"try",
":",
"self",
".",
"_parent",
"=",
"yield",
"self",
".",
"parent_resource",
".",
"get",
"(",
"self",
".",
"parent_id",
")",
"except",
"couch",
".",
"NotFound",
":",
"msg",
"=",
"'{}_id {} not found'",
".",
"format",
"(",
"self",
".",
"parent_resource",
".",
"resource_type",
",",
"self",
".",
"parent_id",
")",
"raise",
"exceptions",
".",
"ValidationError",
"(",
"msg",
")",
"yield",
"self",
".",
"_parent",
".",
"save_subresource",
"(",
"self",
")"
] |
Save the sub-resource within the parent resource
|
[
"Save",
"the",
"sub",
"-",
"resource",
"within",
"the",
"parent",
"resource"
] |
36d78994133918f3c52c187f19e50132960a0156
|
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/model.py#L552-L564
|
247,101 |
openpermissions/perch
|
perch/model.py
|
SubResource.delete
|
def delete(self, user):
"""Delete a sub-resource"""
if user:
can_delete = yield self.can_delete(user)
else:
can_delete = False
if not can_delete:
raise exceptions.Unauthorized('User may not delete the resource')
try:
parent = yield self.get_parent()
except couch.NotFound:
msg = '{}_id {} not found'.format(
self.parent_resource.resource_type,
self.parent_id)
raise exceptions.ValidationError(msg)
yield parent.delete_subresource(self)
|
python
|
def delete(self, user):
"""Delete a sub-resource"""
if user:
can_delete = yield self.can_delete(user)
else:
can_delete = False
if not can_delete:
raise exceptions.Unauthorized('User may not delete the resource')
try:
parent = yield self.get_parent()
except couch.NotFound:
msg = '{}_id {} not found'.format(
self.parent_resource.resource_type,
self.parent_id)
raise exceptions.ValidationError(msg)
yield parent.delete_subresource(self)
|
[
"def",
"delete",
"(",
"self",
",",
"user",
")",
":",
"if",
"user",
":",
"can_delete",
"=",
"yield",
"self",
".",
"can_delete",
"(",
"user",
")",
"else",
":",
"can_delete",
"=",
"False",
"if",
"not",
"can_delete",
":",
"raise",
"exceptions",
".",
"Unauthorized",
"(",
"'User may not delete the resource'",
")",
"try",
":",
"parent",
"=",
"yield",
"self",
".",
"get_parent",
"(",
")",
"except",
"couch",
".",
"NotFound",
":",
"msg",
"=",
"'{}_id {} not found'",
".",
"format",
"(",
"self",
".",
"parent_resource",
".",
"resource_type",
",",
"self",
".",
"parent_id",
")",
"raise",
"exceptions",
".",
"ValidationError",
"(",
"msg",
")",
"yield",
"parent",
".",
"delete_subresource",
"(",
"self",
")"
] |
Delete a sub-resource
|
[
"Delete",
"a",
"sub",
"-",
"resource"
] |
36d78994133918f3c52c187f19e50132960a0156
|
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/model.py#L609-L627
|
247,102 |
openpermissions/perch
|
perch/model.py
|
SubResource.state
|
def state(self):
"""
Get the SubResource state
If the parents state has a higher priority, then it overrides the
SubResource state
..note:: This assumes that self.parent is populated
"""
state = self._resource.get('state', self.default_state)
if state not in State:
state = getattr(State, state)
if not self.parent:
raise Exception('Unable to check the parent state')
parent_state = self.parent.state
return max([state, parent_state], key=attrgetter('value'))
|
python
|
def state(self):
"""
Get the SubResource state
If the parents state has a higher priority, then it overrides the
SubResource state
..note:: This assumes that self.parent is populated
"""
state = self._resource.get('state', self.default_state)
if state not in State:
state = getattr(State, state)
if not self.parent:
raise Exception('Unable to check the parent state')
parent_state = self.parent.state
return max([state, parent_state], key=attrgetter('value'))
|
[
"def",
"state",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"_resource",
".",
"get",
"(",
"'state'",
",",
"self",
".",
"default_state",
")",
"if",
"state",
"not",
"in",
"State",
":",
"state",
"=",
"getattr",
"(",
"State",
",",
"state",
")",
"if",
"not",
"self",
".",
"parent",
":",
"raise",
"Exception",
"(",
"'Unable to check the parent state'",
")",
"parent_state",
"=",
"self",
".",
"parent",
".",
"state",
"return",
"max",
"(",
"[",
"state",
",",
"parent_state",
"]",
",",
"key",
"=",
"attrgetter",
"(",
"'value'",
")",
")"
] |
Get the SubResource state
If the parents state has a higher priority, then it overrides the
SubResource state
..note:: This assumes that self.parent is populated
|
[
"Get",
"the",
"SubResource",
"state"
] |
36d78994133918f3c52c187f19e50132960a0156
|
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/model.py#L630-L648
|
247,103 |
ktdreyer/txproductpages
|
txproductpages/release.py
|
Release.schedule_tasks
|
def schedule_tasks(self):
"""
Get all the tasks for a release.
:param release_id: int, release id number.
:returns: deferred that when fired returns a list of Munch (dict-like)
objects representing all tasks.
"""
url = 'api/v6/releases/%d/schedule-tasks' % self.id
tasks = yield self.connection._get(url)
defer.returnValue(munchify(tasks))
|
python
|
def schedule_tasks(self):
"""
Get all the tasks for a release.
:param release_id: int, release id number.
:returns: deferred that when fired returns a list of Munch (dict-like)
objects representing all tasks.
"""
url = 'api/v6/releases/%d/schedule-tasks' % self.id
tasks = yield self.connection._get(url)
defer.returnValue(munchify(tasks))
|
[
"def",
"schedule_tasks",
"(",
"self",
")",
":",
"url",
"=",
"'api/v6/releases/%d/schedule-tasks'",
"%",
"self",
".",
"id",
"tasks",
"=",
"yield",
"self",
".",
"connection",
".",
"_get",
"(",
"url",
")",
"defer",
".",
"returnValue",
"(",
"munchify",
"(",
"tasks",
")",
")"
] |
Get all the tasks for a release.
:param release_id: int, release id number.
:returns: deferred that when fired returns a list of Munch (dict-like)
objects representing all tasks.
|
[
"Get",
"all",
"the",
"tasks",
"for",
"a",
"release",
"."
] |
96c85c498c0eef1d37cddb031db32e8b885fcbd9
|
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/release.py#L11-L21
|
247,104 |
ktdreyer/txproductpages
|
txproductpages/release.py
|
Release.task_date
|
def task_date(self, task_re):
""" Get a datetime.date object for the last task that matches a regex.
:param task_re: regex, eg re.compile('Development Freeze').
See txproductpages.milestones for some useful regex
constants to pass in here.
:returns: deferred that when fired returns a datetime.date object
:raises: TaskNotFoundException if no tasks matched.
"""
tasks = yield self.schedule_tasks()
task_date = None
for task in tasks:
if task_re.match(task['name']):
(y, m, d) = task['date_finish'].split('-')
task_date = date(int(y), int(m), int(d))
if task_date:
defer.returnValue(task_date)
raise TaskNotFoundException()
|
python
|
def task_date(self, task_re):
""" Get a datetime.date object for the last task that matches a regex.
:param task_re: regex, eg re.compile('Development Freeze').
See txproductpages.milestones for some useful regex
constants to pass in here.
:returns: deferred that when fired returns a datetime.date object
:raises: TaskNotFoundException if no tasks matched.
"""
tasks = yield self.schedule_tasks()
task_date = None
for task in tasks:
if task_re.match(task['name']):
(y, m, d) = task['date_finish'].split('-')
task_date = date(int(y), int(m), int(d))
if task_date:
defer.returnValue(task_date)
raise TaskNotFoundException()
|
[
"def",
"task_date",
"(",
"self",
",",
"task_re",
")",
":",
"tasks",
"=",
"yield",
"self",
".",
"schedule_tasks",
"(",
")",
"task_date",
"=",
"None",
"for",
"task",
"in",
"tasks",
":",
"if",
"task_re",
".",
"match",
"(",
"task",
"[",
"'name'",
"]",
")",
":",
"(",
"y",
",",
"m",
",",
"d",
")",
"=",
"task",
"[",
"'date_finish'",
"]",
".",
"split",
"(",
"'-'",
")",
"task_date",
"=",
"date",
"(",
"int",
"(",
"y",
")",
",",
"int",
"(",
"m",
")",
",",
"int",
"(",
"d",
")",
")",
"if",
"task_date",
":",
"defer",
".",
"returnValue",
"(",
"task_date",
")",
"raise",
"TaskNotFoundException",
"(",
")"
] |
Get a datetime.date object for the last task that matches a regex.
:param task_re: regex, eg re.compile('Development Freeze').
See txproductpages.milestones for some useful regex
constants to pass in here.
:returns: deferred that when fired returns a datetime.date object
:raises: TaskNotFoundException if no tasks matched.
|
[
"Get",
"a",
"datetime",
".",
"date",
"object",
"for",
"the",
"last",
"task",
"that",
"matches",
"a",
"regex",
"."
] |
96c85c498c0eef1d37cddb031db32e8b885fcbd9
|
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/release.py#L24-L41
|
247,105 |
chrisnorman7/confmanager
|
confmanager/confframe.py
|
ConfFrame.apply
|
def apply(self, event = None):
"""Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config."""
for section in self.config.sections():
# Run through the sections to check all the option values:
for option, o in self.config.config[section].items():
# Check the actual values against the validators and complain if necessary:
if not o['include']:
continue # This value is hidden, so there's no control for it.
control = self._controls[section][option] # Get the actual control for GetValue
try:
value = type(o['value'])(control.GetValue()) # Try and convert the value
except ValueError as msg:
self.displayError(section, option, str(msg)) # Woops, something went wrong
return False # Tells self.onOk not to close the window
problem = None # Set up the problem variable.
try:
problem = o['validate'](value) # See if it passes the test
except Exception as e:
problem = str(e) # The lambda raised an exception.
if problem:
self.displayError(section, option, problem) # It didn't
return False # Tells self.onOk not to close the window
self.config.set(section, option, value) # All clear
return True
|
python
|
def apply(self, event = None):
"""Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config."""
for section in self.config.sections():
# Run through the sections to check all the option values:
for option, o in self.config.config[section].items():
# Check the actual values against the validators and complain if necessary:
if not o['include']:
continue # This value is hidden, so there's no control for it.
control = self._controls[section][option] # Get the actual control for GetValue
try:
value = type(o['value'])(control.GetValue()) # Try and convert the value
except ValueError as msg:
self.displayError(section, option, str(msg)) # Woops, something went wrong
return False # Tells self.onOk not to close the window
problem = None # Set up the problem variable.
try:
problem = o['validate'](value) # See if it passes the test
except Exception as e:
problem = str(e) # The lambda raised an exception.
if problem:
self.displayError(section, option, problem) # It didn't
return False # Tells self.onOk not to close the window
self.config.set(section, option, value) # All clear
return True
|
[
"def",
"apply",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"for",
"section",
"in",
"self",
".",
"config",
".",
"sections",
"(",
")",
":",
"# Run through the sections to check all the option values:\r",
"for",
"option",
",",
"o",
"in",
"self",
".",
"config",
".",
"config",
"[",
"section",
"]",
".",
"items",
"(",
")",
":",
"# Check the actual values against the validators and complain if necessary:\r",
"if",
"not",
"o",
"[",
"'include'",
"]",
":",
"continue",
"# This value is hidden, so there's no control for it.\r",
"control",
"=",
"self",
".",
"_controls",
"[",
"section",
"]",
"[",
"option",
"]",
"# Get the actual control for GetValue\r",
"try",
":",
"value",
"=",
"type",
"(",
"o",
"[",
"'value'",
"]",
")",
"(",
"control",
".",
"GetValue",
"(",
")",
")",
"# Try and convert the value\r",
"except",
"ValueError",
"as",
"msg",
":",
"self",
".",
"displayError",
"(",
"section",
",",
"option",
",",
"str",
"(",
"msg",
")",
")",
"# Woops, something went wrong\r",
"return",
"False",
"# Tells self.onOk not to close the window\r",
"problem",
"=",
"None",
"# Set up the problem variable.\r",
"try",
":",
"problem",
"=",
"o",
"[",
"'validate'",
"]",
"(",
"value",
")",
"# See if it passes the test\r",
"except",
"Exception",
"as",
"e",
":",
"problem",
"=",
"str",
"(",
"e",
")",
"# The lambda raised an exception.\r",
"if",
"problem",
":",
"self",
".",
"displayError",
"(",
"section",
",",
"option",
",",
"problem",
")",
"# It didn't\r",
"return",
"False",
"# Tells self.onOk not to close the window\r",
"self",
".",
"config",
".",
"set",
"(",
"section",
",",
"option",
",",
"value",
")",
"# All clear\r",
"return",
"True"
] |
Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config.
|
[
"Before",
"self",
".",
"onOk",
"closes",
"the",
"window",
"it",
"calls",
"this",
"function",
"to",
"sync",
"the",
"config",
"changes",
"from",
"the",
"GUI",
"back",
"to",
"self",
".",
"config",
"."
] |
54a3ce0b596f9da32ae82fd4ff4cb46bb1cf23b1
|
https://github.com/chrisnorman7/confmanager/blob/54a3ce0b596f9da32ae82fd4ff4cb46bb1cf23b1/confmanager/confframe.py#L55-L78
|
247,106 |
jwkvam/piecharts
|
piecharts/__init__.py
|
_detect_notebook
|
def _detect_notebook():
"""
This isn't 100% correct but seems good enough
Returns
-------
bool
True if it detects this is a notebook, otherwise False.
"""
try:
from IPython import get_ipython
from ipykernel import zmqshell
except ImportError:
return False
kernel = get_ipython()
return isinstance(kernel, zmqshell.ZMQInteractiveShell)
|
python
|
def _detect_notebook():
"""
This isn't 100% correct but seems good enough
Returns
-------
bool
True if it detects this is a notebook, otherwise False.
"""
try:
from IPython import get_ipython
from ipykernel import zmqshell
except ImportError:
return False
kernel = get_ipython()
return isinstance(kernel, zmqshell.ZMQInteractiveShell)
|
[
"def",
"_detect_notebook",
"(",
")",
":",
"try",
":",
"from",
"IPython",
"import",
"get_ipython",
"from",
"ipykernel",
"import",
"zmqshell",
"except",
"ImportError",
":",
"return",
"False",
"kernel",
"=",
"get_ipython",
"(",
")",
"return",
"isinstance",
"(",
"kernel",
",",
"zmqshell",
".",
"ZMQInteractiveShell",
")"
] |
This isn't 100% correct but seems good enough
Returns
-------
bool
True if it detects this is a notebook, otherwise False.
|
[
"This",
"isn",
"t",
"100%",
"correct",
"but",
"seems",
"good",
"enough"
] |
b6cd6102c01f0761c991adb2ba949128aebeb818
|
https://github.com/jwkvam/piecharts/blob/b6cd6102c01f0761c991adb2ba949128aebeb818/piecharts/__init__.py#L41-L56
|
247,107 |
jwkvam/piecharts
|
piecharts/__init__.py
|
Chart.xlim
|
def xlim(self, low, high):
"""Set xaxis limits
Parameters
----------
low : number
high : number
Returns
-------
Chart
"""
self.chart['xAxis'][0]['min'] = low
self.chart['xAxis'][0]['max'] = high
return self
|
python
|
def xlim(self, low, high):
"""Set xaxis limits
Parameters
----------
low : number
high : number
Returns
-------
Chart
"""
self.chart['xAxis'][0]['min'] = low
self.chart['xAxis'][0]['max'] = high
return self
|
[
"def",
"xlim",
"(",
"self",
",",
"low",
",",
"high",
")",
":",
"self",
".",
"chart",
"[",
"'xAxis'",
"]",
"[",
"0",
"]",
"[",
"'min'",
"]",
"=",
"low",
"self",
".",
"chart",
"[",
"'xAxis'",
"]",
"[",
"0",
"]",
"[",
"'max'",
"]",
"=",
"high",
"return",
"self"
] |
Set xaxis limits
Parameters
----------
low : number
high : number
Returns
-------
Chart
|
[
"Set",
"xaxis",
"limits"
] |
b6cd6102c01f0761c991adb2ba949128aebeb818
|
https://github.com/jwkvam/piecharts/blob/b6cd6102c01f0761c991adb2ba949128aebeb818/piecharts/__init__.py#L372-L387
|
247,108 |
jwkvam/piecharts
|
piecharts/__init__.py
|
Chart.ylim
|
def ylim(self, low, high):
"""Set yaxis limits
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
"""
self.chart['yAxis'][0]['min'] = low
self.chart['yAxis'][0]['max'] = high
return self
|
python
|
def ylim(self, low, high):
"""Set yaxis limits
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
"""
self.chart['yAxis'][0]['min'] = low
self.chart['yAxis'][0]['max'] = high
return self
|
[
"def",
"ylim",
"(",
"self",
",",
"low",
",",
"high",
")",
":",
"self",
".",
"chart",
"[",
"'yAxis'",
"]",
"[",
"0",
"]",
"[",
"'min'",
"]",
"=",
"low",
"self",
".",
"chart",
"[",
"'yAxis'",
"]",
"[",
"0",
"]",
"[",
"'max'",
"]",
"=",
"high",
"return",
"self"
] |
Set yaxis limits
Parameters
----------
low : number
high : number
index : int, optional
Returns
-------
Chart
|
[
"Set",
"yaxis",
"limits"
] |
b6cd6102c01f0761c991adb2ba949128aebeb818
|
https://github.com/jwkvam/piecharts/blob/b6cd6102c01f0761c991adb2ba949128aebeb818/piecharts/__init__.py#L389-L405
|
247,109 |
treycucco/bidon
|
bidon/util/transform.py
|
get_val
|
def get_val(source, extract=None, transform=None):
"""Extract a value from a source, transform and return it."""
if extract is None:
raw_value = source
else:
raw_value = extract(source)
if transform is None:
return raw_value
else:
return transform(raw_value)
|
python
|
def get_val(source, extract=None, transform=None):
"""Extract a value from a source, transform and return it."""
if extract is None:
raw_value = source
else:
raw_value = extract(source)
if transform is None:
return raw_value
else:
return transform(raw_value)
|
[
"def",
"get_val",
"(",
"source",
",",
"extract",
"=",
"None",
",",
"transform",
"=",
"None",
")",
":",
"if",
"extract",
"is",
"None",
":",
"raw_value",
"=",
"source",
"else",
":",
"raw_value",
"=",
"extract",
"(",
"source",
")",
"if",
"transform",
"is",
"None",
":",
"return",
"raw_value",
"else",
":",
"return",
"transform",
"(",
"raw_value",
")"
] |
Extract a value from a source, transform and return it.
|
[
"Extract",
"a",
"value",
"from",
"a",
"source",
"transform",
"and",
"return",
"it",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L10-L20
|
247,110 |
treycucco/bidon
|
bidon/util/transform.py
|
get_obj
|
def get_obj(source, extract=None, child_transform=None, transform=None):
"""Maps an object based on a key->extractor child_transform dict."""
if extract is None:
obj = source
else:
obj = extract(source)
if child_transform is None:
data = obj
else:
data = dict()
for k, v in child_transform.items():
try:
data[k] = v(obj)
except Exception as ex:
raise Exception("An error occurred with child {0}".format(k)) from ex
if transform is None:
return data
else:
return transform(data)
|
python
|
def get_obj(source, extract=None, child_transform=None, transform=None):
"""Maps an object based on a key->extractor child_transform dict."""
if extract is None:
obj = source
else:
obj = extract(source)
if child_transform is None:
data = obj
else:
data = dict()
for k, v in child_transform.items():
try:
data[k] = v(obj)
except Exception as ex:
raise Exception("An error occurred with child {0}".format(k)) from ex
if transform is None:
return data
else:
return transform(data)
|
[
"def",
"get_obj",
"(",
"source",
",",
"extract",
"=",
"None",
",",
"child_transform",
"=",
"None",
",",
"transform",
"=",
"None",
")",
":",
"if",
"extract",
"is",
"None",
":",
"obj",
"=",
"source",
"else",
":",
"obj",
"=",
"extract",
"(",
"source",
")",
"if",
"child_transform",
"is",
"None",
":",
"data",
"=",
"obj",
"else",
":",
"data",
"=",
"dict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"child_transform",
".",
"items",
"(",
")",
":",
"try",
":",
"data",
"[",
"k",
"]",
"=",
"v",
"(",
"obj",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"Exception",
"(",
"\"An error occurred with child {0}\"",
".",
"format",
"(",
"k",
")",
")",
"from",
"ex",
"if",
"transform",
"is",
"None",
":",
"return",
"data",
"else",
":",
"return",
"transform",
"(",
"data",
")"
] |
Maps an object based on a key->extractor child_transform dict.
|
[
"Maps",
"an",
"object",
"based",
"on",
"a",
"key",
"-",
">",
"extractor",
"child_transform",
"dict",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L23-L43
|
247,111 |
treycucco/bidon
|
bidon/util/transform.py
|
get_lst
|
def get_lst(source, extract=None, transform=None):
"""Extract a list from a source, transform each item, and return the result."""
if extract is None:
raw_list = source
else:
raw_list = extract(source)
if transform is None:
return raw_list
else:
tlist = []
for idx, item in enumerate(raw_list):
try:
tlist.append(transform(item))
except Exception as ex:
raise Exception("An error occurred with item #{0}".format(idx)) from ex
return tlist
|
python
|
def get_lst(source, extract=None, transform=None):
"""Extract a list from a source, transform each item, and return the result."""
if extract is None:
raw_list = source
else:
raw_list = extract(source)
if transform is None:
return raw_list
else:
tlist = []
for idx, item in enumerate(raw_list):
try:
tlist.append(transform(item))
except Exception as ex:
raise Exception("An error occurred with item #{0}".format(idx)) from ex
return tlist
|
[
"def",
"get_lst",
"(",
"source",
",",
"extract",
"=",
"None",
",",
"transform",
"=",
"None",
")",
":",
"if",
"extract",
"is",
"None",
":",
"raw_list",
"=",
"source",
"else",
":",
"raw_list",
"=",
"extract",
"(",
"source",
")",
"if",
"transform",
"is",
"None",
":",
"return",
"raw_list",
"else",
":",
"tlist",
"=",
"[",
"]",
"for",
"idx",
",",
"item",
"in",
"enumerate",
"(",
"raw_list",
")",
":",
"try",
":",
"tlist",
".",
"append",
"(",
"transform",
"(",
"item",
")",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"Exception",
"(",
"\"An error occurred with item #{0}\"",
".",
"format",
"(",
"idx",
")",
")",
"from",
"ex",
"return",
"tlist"
] |
Extract a list from a source, transform each item, and return the result.
|
[
"Extract",
"a",
"list",
"from",
"a",
"source",
"transform",
"each",
"item",
"and",
"return",
"the",
"result",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L46-L62
|
247,112 |
treycucco/bidon
|
bidon/util/transform.py
|
get_composition
|
def get_composition(source, *fxns):
"""Compose several extractors together, on a source."""
val = source
for fxn in fxns:
val = fxn(val)
return val
|
python
|
def get_composition(source, *fxns):
"""Compose several extractors together, on a source."""
val = source
for fxn in fxns:
val = fxn(val)
return val
|
[
"def",
"get_composition",
"(",
"source",
",",
"*",
"fxns",
")",
":",
"val",
"=",
"source",
"for",
"fxn",
"in",
"fxns",
":",
"val",
"=",
"fxn",
"(",
"val",
")",
"return",
"val"
] |
Compose several extractors together, on a source.
|
[
"Compose",
"several",
"extractors",
"together",
"on",
"a",
"source",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L65-L70
|
247,113 |
treycucco/bidon
|
bidon/util/transform.py
|
get_flattened
|
def get_flattened(dct, names, path_joiner="_"):
"""Flatten a child dicts, whose resulting keys are joined by path_joiner.
E.G. { "valuation": { "currency": "USD", "amount": "100" } } ->
{ "valuation_currency": "USD", "valuation_amount": "100" }
"""
new_dct = dict()
for key, val in dct.items():
if key in names:
child = {path_joiner.join(k): v for k, v in flatten_dict(val, (key, ))}
new_dct.update(child)
else:
new_dct[key] = dct[key]
return new_dct
|
python
|
def get_flattened(dct, names, path_joiner="_"):
"""Flatten a child dicts, whose resulting keys are joined by path_joiner.
E.G. { "valuation": { "currency": "USD", "amount": "100" } } ->
{ "valuation_currency": "USD", "valuation_amount": "100" }
"""
new_dct = dict()
for key, val in dct.items():
if key in names:
child = {path_joiner.join(k): v for k, v in flatten_dict(val, (key, ))}
new_dct.update(child)
else:
new_dct[key] = dct[key]
return new_dct
|
[
"def",
"get_flattened",
"(",
"dct",
",",
"names",
",",
"path_joiner",
"=",
"\"_\"",
")",
":",
"new_dct",
"=",
"dict",
"(",
")",
"for",
"key",
",",
"val",
"in",
"dct",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"names",
":",
"child",
"=",
"{",
"path_joiner",
".",
"join",
"(",
"k",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"flatten_dict",
"(",
"val",
",",
"(",
"key",
",",
")",
")",
"}",
"new_dct",
".",
"update",
"(",
"child",
")",
"else",
":",
"new_dct",
"[",
"key",
"]",
"=",
"dct",
"[",
"key",
"]",
"return",
"new_dct"
] |
Flatten a child dicts, whose resulting keys are joined by path_joiner.
E.G. { "valuation": { "currency": "USD", "amount": "100" } } ->
{ "valuation_currency": "USD", "valuation_amount": "100" }
|
[
"Flatten",
"a",
"child",
"dicts",
"whose",
"resulting",
"keys",
"are",
"joined",
"by",
"path_joiner",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L73-L86
|
247,114 |
treycucco/bidon
|
bidon/util/transform.py
|
get_hoisted
|
def get_hoisted(dct, child_name):
"""Pulls all of a child's keys up to the parent, with the names unchanged."""
child = dct[child_name]
del dct[child_name]
dct.update(child)
return dct
|
python
|
def get_hoisted(dct, child_name):
"""Pulls all of a child's keys up to the parent, with the names unchanged."""
child = dct[child_name]
del dct[child_name]
dct.update(child)
return dct
|
[
"def",
"get_hoisted",
"(",
"dct",
",",
"child_name",
")",
":",
"child",
"=",
"dct",
"[",
"child_name",
"]",
"del",
"dct",
"[",
"child_name",
"]",
"dct",
".",
"update",
"(",
"child",
")",
"return",
"dct"
] |
Pulls all of a child's keys up to the parent, with the names unchanged.
|
[
"Pulls",
"all",
"of",
"a",
"child",
"s",
"keys",
"up",
"to",
"the",
"parent",
"with",
"the",
"names",
"unchanged",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L89-L94
|
247,115 |
treycucco/bidon
|
bidon/util/transform.py
|
obj
|
def obj(extract=None, child_transform=None, transform=None):
"""Returns a partial of get_obj that only needs a source argument."""
return lambda source: get_obj(source, extract, child_transform, transform)
|
python
|
def obj(extract=None, child_transform=None, transform=None):
"""Returns a partial of get_obj that only needs a source argument."""
return lambda source: get_obj(source, extract, child_transform, transform)
|
[
"def",
"obj",
"(",
"extract",
"=",
"None",
",",
"child_transform",
"=",
"None",
",",
"transform",
"=",
"None",
")",
":",
"return",
"lambda",
"source",
":",
"get_obj",
"(",
"source",
",",
"extract",
",",
"child_transform",
",",
"transform",
")"
] |
Returns a partial of get_obj that only needs a source argument.
|
[
"Returns",
"a",
"partial",
"of",
"get_obj",
"that",
"only",
"needs",
"a",
"source",
"argument",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L102-L104
|
247,116 |
treycucco/bidon
|
bidon/util/transform.py
|
get_xml_attr
|
def get_xml_attr(source, name, path=None):
"""Get the XML attribute with name from source. If path is not Mone, it will instead get the
XML attribute with name from the child indicated by path.
"""
if path is None:
return source.attrib[name]
else:
return get_xml_attr(get_xml_child(source, path), name)
|
python
|
def get_xml_attr(source, name, path=None):
"""Get the XML attribute with name from source. If path is not Mone, it will instead get the
XML attribute with name from the child indicated by path.
"""
if path is None:
return source.attrib[name]
else:
return get_xml_attr(get_xml_child(source, path), name)
|
[
"def",
"get_xml_attr",
"(",
"source",
",",
"name",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"source",
".",
"attrib",
"[",
"name",
"]",
"else",
":",
"return",
"get_xml_attr",
"(",
"get_xml_child",
"(",
"source",
",",
"path",
")",
",",
"name",
")"
] |
Get the XML attribute with name from source. If path is not Mone, it will instead get the
XML attribute with name from the child indicated by path.
|
[
"Get",
"the",
"XML",
"attribute",
"with",
"name",
"from",
"source",
".",
"If",
"path",
"is",
"not",
"Mone",
"it",
"will",
"instead",
"get",
"the",
"XML",
"attribute",
"with",
"name",
"from",
"the",
"child",
"indicated",
"by",
"path",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L127-L134
|
247,117 |
treycucco/bidon
|
bidon/util/transform.py
|
get_xml_text
|
def get_xml_text(source, path=None):
"""Get the text of the XML node. If path is not None, it will get the text of the descendant of
source indicated by path.
"""
if path is None:
return source.text
else:
return get_xml_text(get_xml_child(source, path))
|
python
|
def get_xml_text(source, path=None):
"""Get the text of the XML node. If path is not None, it will get the text of the descendant of
source indicated by path.
"""
if path is None:
return source.text
else:
return get_xml_text(get_xml_child(source, path))
|
[
"def",
"get_xml_text",
"(",
"source",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"source",
".",
"text",
"else",
":",
"return",
"get_xml_text",
"(",
"get_xml_child",
"(",
"source",
",",
"path",
")",
")"
] |
Get the text of the XML node. If path is not None, it will get the text of the descendant of
source indicated by path.
|
[
"Get",
"the",
"text",
"of",
"the",
"XML",
"node",
".",
"If",
"path",
"is",
"not",
"None",
"it",
"will",
"get",
"the",
"text",
"of",
"the",
"descendant",
"of",
"source",
"indicated",
"by",
"path",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L137-L144
|
247,118 |
treycucco/bidon
|
bidon/util/transform.py
|
get_xml_child
|
def get_xml_child(source, path):
"""Get the first descendant of source identified by path.
Path must be either a an xpath string, or a 2-tuple of (xpath, namespace_dict).
"""
if isinstance(path, (tuple, list)):
return source.find(*path)
else:
return source.find(path)
|
python
|
def get_xml_child(source, path):
"""Get the first descendant of source identified by path.
Path must be either a an xpath string, or a 2-tuple of (xpath, namespace_dict).
"""
if isinstance(path, (tuple, list)):
return source.find(*path)
else:
return source.find(path)
|
[
"def",
"get_xml_child",
"(",
"source",
",",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"source",
".",
"find",
"(",
"*",
"path",
")",
"else",
":",
"return",
"source",
".",
"find",
"(",
"path",
")"
] |
Get the first descendant of source identified by path.
Path must be either a an xpath string, or a 2-tuple of (xpath, namespace_dict).
|
[
"Get",
"the",
"first",
"descendant",
"of",
"source",
"identified",
"by",
"path",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L147-L155
|
247,119 |
treycucco/bidon
|
bidon/util/transform.py
|
get_xml_children
|
def get_xml_children(source, path):
"""Get all the descendants of source identified by path.
Path must be either a an xpath string, or a 2-tuple of (xpath, namespace_dict).
"""
if isinstance(path, (tuple, list)):
return source.findall(*path)
else:
return source.findall(path)
|
python
|
def get_xml_children(source, path):
"""Get all the descendants of source identified by path.
Path must be either a an xpath string, or a 2-tuple of (xpath, namespace_dict).
"""
if isinstance(path, (tuple, list)):
return source.findall(*path)
else:
return source.findall(path)
|
[
"def",
"get_xml_children",
"(",
"source",
",",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"source",
".",
"findall",
"(",
"*",
"path",
")",
"else",
":",
"return",
"source",
".",
"findall",
"(",
"path",
")"
] |
Get all the descendants of source identified by path.
Path must be either a an xpath string, or a 2-tuple of (xpath, namespace_dict).
|
[
"Get",
"all",
"the",
"descendants",
"of",
"source",
"identified",
"by",
"path",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L158-L166
|
247,120 |
treycucco/bidon
|
bidon/util/transform.py
|
get_json_val
|
def get_json_val(source, path, *, ignore_bad_path=False):
"""Get the nested value identified by the json path, rooted at source."""
try:
return JP.find(source, path)
except JP.JSONPathError as ex:
if ignore_bad_path:
return None
else:
raise
|
python
|
def get_json_val(source, path, *, ignore_bad_path=False):
"""Get the nested value identified by the json path, rooted at source."""
try:
return JP.find(source, path)
except JP.JSONPathError as ex:
if ignore_bad_path:
return None
else:
raise
|
[
"def",
"get_json_val",
"(",
"source",
",",
"path",
",",
"*",
",",
"ignore_bad_path",
"=",
"False",
")",
":",
"try",
":",
"return",
"JP",
".",
"find",
"(",
"source",
",",
"path",
")",
"except",
"JP",
".",
"JSONPathError",
"as",
"ex",
":",
"if",
"ignore_bad_path",
":",
"return",
"None",
"else",
":",
"raise"
] |
Get the nested value identified by the json path, rooted at source.
|
[
"Get",
"the",
"nested",
"value",
"identified",
"by",
"the",
"json",
"path",
"rooted",
"at",
"source",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L189-L197
|
247,121 |
treycucco/bidon
|
bidon/util/transform.py
|
json_val
|
def json_val(path, *, ignore_bad_path=False):
"""Returns a partial of get_json_val that only needs a source argument."""
return lambda source: get_json_val(source, path, ignore_bad_path=ignore_bad_path)
|
python
|
def json_val(path, *, ignore_bad_path=False):
"""Returns a partial of get_json_val that only needs a source argument."""
return lambda source: get_json_val(source, path, ignore_bad_path=ignore_bad_path)
|
[
"def",
"json_val",
"(",
"path",
",",
"*",
",",
"ignore_bad_path",
"=",
"False",
")",
":",
"return",
"lambda",
"source",
":",
"get_json_val",
"(",
"source",
",",
"path",
",",
"ignore_bad_path",
"=",
"ignore_bad_path",
")"
] |
Returns a partial of get_json_val that only needs a source argument.
|
[
"Returns",
"a",
"partial",
"of",
"get_json_val",
"that",
"only",
"needs",
"a",
"source",
"argument",
"."
] |
d9f24596841d0e69e8ac70a1d1a1deecea95e340
|
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/util/transform.py#L205-L207
|
247,122 |
KnowledgeLinks/rdfframework
|
rdfframework/rml/rmlmanager.py
|
RmlManager.register_defs
|
def register_defs(self, def_list, **kwargs):
"""
Registers a list of Rml defintions objects
Args:
-----
def_list: list of objects defining the rml definitons
"""
for item in def_list:
if isinstance(item, tuple):
self.register_rml_def(*item, **kwargs)
elif isinstance(item, dict):
cp_kwargs = kwargs.copy()
item.update(kwargs)
self.register_rml_def(**item)
|
python
|
def register_defs(self, def_list, **kwargs):
"""
Registers a list of Rml defintions objects
Args:
-----
def_list: list of objects defining the rml definitons
"""
for item in def_list:
if isinstance(item, tuple):
self.register_rml_def(*item, **kwargs)
elif isinstance(item, dict):
cp_kwargs = kwargs.copy()
item.update(kwargs)
self.register_rml_def(**item)
|
[
"def",
"register_defs",
"(",
"self",
",",
"def_list",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"item",
"in",
"def_list",
":",
"if",
"isinstance",
"(",
"item",
",",
"tuple",
")",
":",
"self",
".",
"register_rml_def",
"(",
"*",
"item",
",",
"*",
"*",
"kwargs",
")",
"elif",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"cp_kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"item",
".",
"update",
"(",
"kwargs",
")",
"self",
".",
"register_rml_def",
"(",
"*",
"*",
"item",
")"
] |
Registers a list of Rml defintions objects
Args:
-----
def_list: list of objects defining the rml definitons
|
[
"Registers",
"a",
"list",
"of",
"Rml",
"defintions",
"objects"
] |
9ec32dcc4bed51650a4b392cc5c15100fef7923a
|
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/rmlmanager.py#L43-L57
|
247,123 |
KnowledgeLinks/rdfframework
|
rdfframework/rml/rmlmanager.py
|
RmlManager.register_rml_def
|
def register_rml_def(self,
location_type,
location,
filename=None,
**kwargs):
"""
Registers the rml file locations for easy access
Args:
-----
location_type: ['package_all',
'package_file',
'directory',
'filepath']
location: The correlated location string based on the location_type
filename: Optional, associated with 'package_file' location_type
kwargs:
-------
include_subfolders: Boolean
"""
if location_type == 'directory':
self.register_directory(location, **kwargs)
elif location_type == 'filepath':
if not os.path.exists(location):
raise OSError("File not found", location)
if os.path.isfile(location):
self.register_rml(location)
elif filename:
new_loc = os.path.join(location, filename)
if not os.path.exists(new_loc):
raise OSError("File not found", new_loc)
elif os.path.isfile(new_loc):
self.register_rml(new_loc)
else:
raise OSError("File not found", location)
elif location_type.startswith('package'):
pkg_path = \
importlib.util.find_spec(\
location).submodule_search_locations[0]
if location_type.endswith('_all'):
self.register_directory(pkg_path, **kwargs)
elif location_type.endswith('_file'):
filepath = os.path.join(pkg_path, filename)
self.register_rml(filepath, **kwargs)
else:
raise NotImplementedError
|
python
|
def register_rml_def(self,
location_type,
location,
filename=None,
**kwargs):
"""
Registers the rml file locations for easy access
Args:
-----
location_type: ['package_all',
'package_file',
'directory',
'filepath']
location: The correlated location string based on the location_type
filename: Optional, associated with 'package_file' location_type
kwargs:
-------
include_subfolders: Boolean
"""
if location_type == 'directory':
self.register_directory(location, **kwargs)
elif location_type == 'filepath':
if not os.path.exists(location):
raise OSError("File not found", location)
if os.path.isfile(location):
self.register_rml(location)
elif filename:
new_loc = os.path.join(location, filename)
if not os.path.exists(new_loc):
raise OSError("File not found", new_loc)
elif os.path.isfile(new_loc):
self.register_rml(new_loc)
else:
raise OSError("File not found", location)
elif location_type.startswith('package'):
pkg_path = \
importlib.util.find_spec(\
location).submodule_search_locations[0]
if location_type.endswith('_all'):
self.register_directory(pkg_path, **kwargs)
elif location_type.endswith('_file'):
filepath = os.path.join(pkg_path, filename)
self.register_rml(filepath, **kwargs)
else:
raise NotImplementedError
|
[
"def",
"register_rml_def",
"(",
"self",
",",
"location_type",
",",
"location",
",",
"filename",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"location_type",
"==",
"'directory'",
":",
"self",
".",
"register_directory",
"(",
"location",
",",
"*",
"*",
"kwargs",
")",
"elif",
"location_type",
"==",
"'filepath'",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"raise",
"OSError",
"(",
"\"File not found\"",
",",
"location",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"location",
")",
":",
"self",
".",
"register_rml",
"(",
"location",
")",
"elif",
"filename",
":",
"new_loc",
"=",
"os",
".",
"path",
".",
"join",
"(",
"location",
",",
"filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"new_loc",
")",
":",
"raise",
"OSError",
"(",
"\"File not found\"",
",",
"new_loc",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"new_loc",
")",
":",
"self",
".",
"register_rml",
"(",
"new_loc",
")",
"else",
":",
"raise",
"OSError",
"(",
"\"File not found\"",
",",
"location",
")",
"elif",
"location_type",
".",
"startswith",
"(",
"'package'",
")",
":",
"pkg_path",
"=",
"importlib",
".",
"util",
".",
"find_spec",
"(",
"location",
")",
".",
"submodule_search_locations",
"[",
"0",
"]",
"if",
"location_type",
".",
"endswith",
"(",
"'_all'",
")",
":",
"self",
".",
"register_directory",
"(",
"pkg_path",
",",
"*",
"*",
"kwargs",
")",
"elif",
"location_type",
".",
"endswith",
"(",
"'_file'",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pkg_path",
",",
"filename",
")",
"self",
".",
"register_rml",
"(",
"filepath",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"raise",
"NotImplementedError"
] |
Registers the rml file locations for easy access
Args:
-----
location_type: ['package_all',
'package_file',
'directory',
'filepath']
location: The correlated location string based on the location_type
filename: Optional, associated with 'package_file' location_type
kwargs:
-------
include_subfolders: Boolean
|
[
"Registers",
"the",
"rml",
"file",
"locations",
"for",
"easy",
"access"
] |
9ec32dcc4bed51650a4b392cc5c15100fef7923a
|
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/rmlmanager.py#L59-L105
|
247,124 |
KnowledgeLinks/rdfframework
|
rdfframework/rml/rmlmanager.py
|
RmlManager.register_rml
|
def register_rml(self, filepath, **kwargs):
"""
Registers the filepath for an rml mapping
Args:
-----
filepath: the path the rml file
"""
name = os.path.split(filepath)[-1]
if name in self.rml_maps and self.rml_maps[name] != filepath:
raise Exception("RML name already registered. Filenames must be "
"unique.",
(self.rml_maps[name], filepath))
self.rml_maps[name] = filepath
|
python
|
def register_rml(self, filepath, **kwargs):
"""
Registers the filepath for an rml mapping
Args:
-----
filepath: the path the rml file
"""
name = os.path.split(filepath)[-1]
if name in self.rml_maps and self.rml_maps[name] != filepath:
raise Exception("RML name already registered. Filenames must be "
"unique.",
(self.rml_maps[name], filepath))
self.rml_maps[name] = filepath
|
[
"def",
"register_rml",
"(",
"self",
",",
"filepath",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filepath",
")",
"[",
"-",
"1",
"]",
"if",
"name",
"in",
"self",
".",
"rml_maps",
"and",
"self",
".",
"rml_maps",
"[",
"name",
"]",
"!=",
"filepath",
":",
"raise",
"Exception",
"(",
"\"RML name already registered. Filenames must be \"",
"\"unique.\"",
",",
"(",
"self",
".",
"rml_maps",
"[",
"name",
"]",
",",
"filepath",
")",
")",
"self",
".",
"rml_maps",
"[",
"name",
"]",
"=",
"filepath"
] |
Registers the filepath for an rml mapping
Args:
-----
filepath: the path the rml file
|
[
"Registers",
"the",
"filepath",
"for",
"an",
"rml",
"mapping"
] |
9ec32dcc4bed51650a4b392cc5c15100fef7923a
|
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/rmlmanager.py#L107-L120
|
247,125 |
KnowledgeLinks/rdfframework
|
rdfframework/rml/rmlmanager.py
|
RmlManager.register_directory
|
def register_directory(self, dirpath, **kwargs):
"""
Registers all of the files in the the directory path
"""
kwargs['file_extensions'] = kwargs.get("file_extensions",
self.rdf_formats)
files = list_files(file_directory=dirpath, **kwargs)
for fileinfo in files:
self.register_rml(fileinfo[-1], **kwargs)
|
python
|
def register_directory(self, dirpath, **kwargs):
"""
Registers all of the files in the the directory path
"""
kwargs['file_extensions'] = kwargs.get("file_extensions",
self.rdf_formats)
files = list_files(file_directory=dirpath, **kwargs)
for fileinfo in files:
self.register_rml(fileinfo[-1], **kwargs)
|
[
"def",
"register_directory",
"(",
"self",
",",
"dirpath",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'file_extensions'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"\"file_extensions\"",
",",
"self",
".",
"rdf_formats",
")",
"files",
"=",
"list_files",
"(",
"file_directory",
"=",
"dirpath",
",",
"*",
"*",
"kwargs",
")",
"for",
"fileinfo",
"in",
"files",
":",
"self",
".",
"register_rml",
"(",
"fileinfo",
"[",
"-",
"1",
"]",
",",
"*",
"*",
"kwargs",
")"
] |
Registers all of the files in the the directory path
|
[
"Registers",
"all",
"of",
"the",
"files",
"in",
"the",
"the",
"directory",
"path"
] |
9ec32dcc4bed51650a4b392cc5c15100fef7923a
|
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/rmlmanager.py#L122-L131
|
247,126 |
KnowledgeLinks/rdfframework
|
rdfframework/rml/rmlmanager.py
|
RmlManager.make_processor
|
def make_processor(self, name, mappings, processor_type, **kwargs):
"""
Instantiates a RmlProcessor and registers it in the manager
Args:
-----
name: the name to register the processor
mappings: the list RML mapping definitions to use
processor_type: the name of the RML processor to use
"""
from .processor import Processor
if self.processors.get(name):
raise LookupError("processor has already been created")
if isinstance(mappings, list):
mappings = [self.get_rml(item) for item in mappings]
else:
mappings = [self.get_rml(mappings)]
self.processors[name] = Processor[processor_type](mappings, **kwargs)
self.processors[name].name = name
return self.processors[name]
|
python
|
def make_processor(self, name, mappings, processor_type, **kwargs):
"""
Instantiates a RmlProcessor and registers it in the manager
Args:
-----
name: the name to register the processor
mappings: the list RML mapping definitions to use
processor_type: the name of the RML processor to use
"""
from .processor import Processor
if self.processors.get(name):
raise LookupError("processor has already been created")
if isinstance(mappings, list):
mappings = [self.get_rml(item) for item in mappings]
else:
mappings = [self.get_rml(mappings)]
self.processors[name] = Processor[processor_type](mappings, **kwargs)
self.processors[name].name = name
return self.processors[name]
|
[
"def",
"make_processor",
"(",
"self",
",",
"name",
",",
"mappings",
",",
"processor_type",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"processor",
"import",
"Processor",
"if",
"self",
".",
"processors",
".",
"get",
"(",
"name",
")",
":",
"raise",
"LookupError",
"(",
"\"processor has already been created\"",
")",
"if",
"isinstance",
"(",
"mappings",
",",
"list",
")",
":",
"mappings",
"=",
"[",
"self",
".",
"get_rml",
"(",
"item",
")",
"for",
"item",
"in",
"mappings",
"]",
"else",
":",
"mappings",
"=",
"[",
"self",
".",
"get_rml",
"(",
"mappings",
")",
"]",
"self",
".",
"processors",
"[",
"name",
"]",
"=",
"Processor",
"[",
"processor_type",
"]",
"(",
"mappings",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"processors",
"[",
"name",
"]",
".",
"name",
"=",
"name",
"return",
"self",
".",
"processors",
"[",
"name",
"]"
] |
Instantiates a RmlProcessor and registers it in the manager
Args:
-----
name: the name to register the processor
mappings: the list RML mapping definitions to use
processor_type: the name of the RML processor to use
|
[
"Instantiates",
"a",
"RmlProcessor",
"and",
"registers",
"it",
"in",
"the",
"manager"
] |
9ec32dcc4bed51650a4b392cc5c15100fef7923a
|
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/rmlmanager.py#L133-L152
|
247,127 |
KnowledgeLinks/rdfframework
|
rdfframework/rml/rmlmanager.py
|
RmlManager.get_processor
|
def get_processor(self,
name,
mappings=None,
processor_type=None,
**kwargs):
"""
Returns the specified RML Processor
"""
try:
return self.processors[name]
except KeyError:
return self.make_processor(name,
mappings,
processor_type,
**kwargs)
|
python
|
def get_processor(self,
name,
mappings=None,
processor_type=None,
**kwargs):
"""
Returns the specified RML Processor
"""
try:
return self.processors[name]
except KeyError:
return self.make_processor(name,
mappings,
processor_type,
**kwargs)
|
[
"def",
"get_processor",
"(",
"self",
",",
"name",
",",
"mappings",
"=",
"None",
",",
"processor_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"self",
".",
"processors",
"[",
"name",
"]",
"except",
"KeyError",
":",
"return",
"self",
".",
"make_processor",
"(",
"name",
",",
"mappings",
",",
"processor_type",
",",
"*",
"*",
"kwargs",
")"
] |
Returns the specified RML Processor
|
[
"Returns",
"the",
"specified",
"RML",
"Processor"
] |
9ec32dcc4bed51650a4b392cc5c15100fef7923a
|
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/rmlmanager.py#L154-L168
|
247,128 |
KnowledgeLinks/rdfframework
|
rdfframework/rml/rmlmanager.py
|
RmlManager.get_rml
|
def get_rml(self, rml_name, rtn_format="filepath"):
""" returns the rml mapping filepath
rml_name(str): Name of the rml mapping to retrieve
rtn_format: ['filepath', 'data']
"""
try:
rml_path = self.rml_maps[rml_name]
except KeyError:
if rml_name in self.rml_maps.values() or os.path.exists(rml_name):
rml_path = rml_name
else:
raise LookupError("rml_name '%s' is not registered" % rml_name)
if rtn_format == "data":
with open(rml_path, "rb") as fo:
return fo.read()
return rml_path
|
python
|
def get_rml(self, rml_name, rtn_format="filepath"):
""" returns the rml mapping filepath
rml_name(str): Name of the rml mapping to retrieve
rtn_format: ['filepath', 'data']
"""
try:
rml_path = self.rml_maps[rml_name]
except KeyError:
if rml_name in self.rml_maps.values() or os.path.exists(rml_name):
rml_path = rml_name
else:
raise LookupError("rml_name '%s' is not registered" % rml_name)
if rtn_format == "data":
with open(rml_path, "rb") as fo:
return fo.read()
return rml_path
|
[
"def",
"get_rml",
"(",
"self",
",",
"rml_name",
",",
"rtn_format",
"=",
"\"filepath\"",
")",
":",
"try",
":",
"rml_path",
"=",
"self",
".",
"rml_maps",
"[",
"rml_name",
"]",
"except",
"KeyError",
":",
"if",
"rml_name",
"in",
"self",
".",
"rml_maps",
".",
"values",
"(",
")",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"rml_name",
")",
":",
"rml_path",
"=",
"rml_name",
"else",
":",
"raise",
"LookupError",
"(",
"\"rml_name '%s' is not registered\"",
"%",
"rml_name",
")",
"if",
"rtn_format",
"==",
"\"data\"",
":",
"with",
"open",
"(",
"rml_path",
",",
"\"rb\"",
")",
"as",
"fo",
":",
"return",
"fo",
".",
"read",
"(",
")",
"return",
"rml_path"
] |
returns the rml mapping filepath
rml_name(str): Name of the rml mapping to retrieve
rtn_format: ['filepath', 'data']
|
[
"returns",
"the",
"rml",
"mapping",
"filepath"
] |
9ec32dcc4bed51650a4b392cc5c15100fef7923a
|
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rml/rmlmanager.py#L193-L210
|
247,129 |
tlevine/vlermv
|
vlermv/_abstract.py
|
AbstractVlermv.filename
|
def filename(self, index):
'''
Get the absolute filename corresponding to a key; run the
key_transformer on the key and do a few other small things.
:raises TypeError: if the key_transformer returns something other than
a :py:class:`tuple` of :py:class:`strings <str>`
:raises KeyError: if the key_transformer returns an empty path
:returns: the filename
:rtype: str
'''
subpath = self.key_transformer.to_path(index)
if not isinstance(subpath, tuple):
msg = 'subpath is a %s, but it should be a tuple.'
raise TypeError(msg % type(subpath).__name__)
elif len(subpath) == 0:
raise KeyError('You specified an empty key.')
elif not all(isinstance(x, str) for x in subpath):
msg = 'Elements of subpath should all be str; here is subpath:\n%s' % repr(subpath)
raise TypeError(msg)
return os.path.join(self.base_directory, *safe_path(subpath)) + self.extension
|
python
|
def filename(self, index):
'''
Get the absolute filename corresponding to a key; run the
key_transformer on the key and do a few other small things.
:raises TypeError: if the key_transformer returns something other than
a :py:class:`tuple` of :py:class:`strings <str>`
:raises KeyError: if the key_transformer returns an empty path
:returns: the filename
:rtype: str
'''
subpath = self.key_transformer.to_path(index)
if not isinstance(subpath, tuple):
msg = 'subpath is a %s, but it should be a tuple.'
raise TypeError(msg % type(subpath).__name__)
elif len(subpath) == 0:
raise KeyError('You specified an empty key.')
elif not all(isinstance(x, str) for x in subpath):
msg = 'Elements of subpath should all be str; here is subpath:\n%s' % repr(subpath)
raise TypeError(msg)
return os.path.join(self.base_directory, *safe_path(subpath)) + self.extension
|
[
"def",
"filename",
"(",
"self",
",",
"index",
")",
":",
"subpath",
"=",
"self",
".",
"key_transformer",
".",
"to_path",
"(",
"index",
")",
"if",
"not",
"isinstance",
"(",
"subpath",
",",
"tuple",
")",
":",
"msg",
"=",
"'subpath is a %s, but it should be a tuple.'",
"raise",
"TypeError",
"(",
"msg",
"%",
"type",
"(",
"subpath",
")",
".",
"__name__",
")",
"elif",
"len",
"(",
"subpath",
")",
"==",
"0",
":",
"raise",
"KeyError",
"(",
"'You specified an empty key.'",
")",
"elif",
"not",
"all",
"(",
"isinstance",
"(",
"x",
",",
"str",
")",
"for",
"x",
"in",
"subpath",
")",
":",
"msg",
"=",
"'Elements of subpath should all be str; here is subpath:\\n%s'",
"%",
"repr",
"(",
"subpath",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"base_directory",
",",
"*",
"safe_path",
"(",
"subpath",
")",
")",
"+",
"self",
".",
"extension"
] |
Get the absolute filename corresponding to a key; run the
key_transformer on the key and do a few other small things.
:raises TypeError: if the key_transformer returns something other than
a :py:class:`tuple` of :py:class:`strings <str>`
:raises KeyError: if the key_transformer returns an empty path
:returns: the filename
:rtype: str
|
[
"Get",
"the",
"absolute",
"filename",
"corresponding",
"to",
"a",
"key",
";",
"run",
"the",
"key_transformer",
"on",
"the",
"key",
"and",
"do",
"a",
"few",
"other",
"small",
"things",
"."
] |
0b332ea1c20e4065b30f5e3ec0c1d0fffbce6b20
|
https://github.com/tlevine/vlermv/blob/0b332ea1c20e4065b30f5e3ec0c1d0fffbce6b20/vlermv/_abstract.py#L147-L167
|
247,130 |
tlevine/vlermv
|
vlermv/_abstract.py
|
AbstractVlermv.from_filename
|
def from_filename(self, filename):
'''
Convert an absolute filename into key.
'''
i = len(self.base_directory)
if filename[:i] != self.base_directory:
raise ValueError('Filename needs to start with "%s";\nyou passed "%s".' % (self.base_directory, filename))
if filename.endswith(self.extension):
if len(self.extension) > 0:
j = -len(self.extension)
else:
j = None
return self.key_transformer.from_path(tuple(filename[i:j].strip('/').split('/')))
|
python
|
def from_filename(self, filename):
'''
Convert an absolute filename into key.
'''
i = len(self.base_directory)
if filename[:i] != self.base_directory:
raise ValueError('Filename needs to start with "%s";\nyou passed "%s".' % (self.base_directory, filename))
if filename.endswith(self.extension):
if len(self.extension) > 0:
j = -len(self.extension)
else:
j = None
return self.key_transformer.from_path(tuple(filename[i:j].strip('/').split('/')))
|
[
"def",
"from_filename",
"(",
"self",
",",
"filename",
")",
":",
"i",
"=",
"len",
"(",
"self",
".",
"base_directory",
")",
"if",
"filename",
"[",
":",
"i",
"]",
"!=",
"self",
".",
"base_directory",
":",
"raise",
"ValueError",
"(",
"'Filename needs to start with \"%s\";\\nyou passed \"%s\".'",
"%",
"(",
"self",
".",
"base_directory",
",",
"filename",
")",
")",
"if",
"filename",
".",
"endswith",
"(",
"self",
".",
"extension",
")",
":",
"if",
"len",
"(",
"self",
".",
"extension",
")",
">",
"0",
":",
"j",
"=",
"-",
"len",
"(",
"self",
".",
"extension",
")",
"else",
":",
"j",
"=",
"None",
"return",
"self",
".",
"key_transformer",
".",
"from_path",
"(",
"tuple",
"(",
"filename",
"[",
"i",
":",
"j",
"]",
".",
"strip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
")",
")"
] |
Convert an absolute filename into key.
|
[
"Convert",
"an",
"absolute",
"filename",
"into",
"key",
"."
] |
0b332ea1c20e4065b30f5e3ec0c1d0fffbce6b20
|
https://github.com/tlevine/vlermv/blob/0b332ea1c20e4065b30f5e3ec0c1d0fffbce6b20/vlermv/_abstract.py#L169-L182
|
247,131 |
untwisted/quickirc
|
quickirc.py
|
Irc.main
|
def main(self, spin, data):
"""
The function which uses irc rfc regex to extract
the basic arguments from the msg.
"""
data = data.decode(self.encoding)
field = re.match(RFC_REG, data)
if not field:
return
prefix = self.extract_prefix(field.group('prefix'))
command = field.group('command').upper()
args = self.extract_args(field.group('arguments'))
spawn(spin, command, *(prefix + args))
|
python
|
def main(self, spin, data):
"""
The function which uses irc rfc regex to extract
the basic arguments from the msg.
"""
data = data.decode(self.encoding)
field = re.match(RFC_REG, data)
if not field:
return
prefix = self.extract_prefix(field.group('prefix'))
command = field.group('command').upper()
args = self.extract_args(field.group('arguments'))
spawn(spin, command, *(prefix + args))
|
[
"def",
"main",
"(",
"self",
",",
"spin",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"field",
"=",
"re",
".",
"match",
"(",
"RFC_REG",
",",
"data",
")",
"if",
"not",
"field",
":",
"return",
"prefix",
"=",
"self",
".",
"extract_prefix",
"(",
"field",
".",
"group",
"(",
"'prefix'",
")",
")",
"command",
"=",
"field",
".",
"group",
"(",
"'command'",
")",
".",
"upper",
"(",
")",
"args",
"=",
"self",
".",
"extract_args",
"(",
"field",
".",
"group",
"(",
"'arguments'",
")",
")",
"spawn",
"(",
"spin",
",",
"command",
",",
"*",
"(",
"prefix",
"+",
"args",
")",
")"
] |
The function which uses irc rfc regex to extract
the basic arguments from the msg.
|
[
"The",
"function",
"which",
"uses",
"irc",
"rfc",
"regex",
"to",
"extract",
"the",
"basic",
"arguments",
"from",
"the",
"msg",
"."
] |
4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99
|
https://github.com/untwisted/quickirc/blob/4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99/quickirc.py#L135-L149
|
247,132 |
untwisted/quickirc
|
quickirc.py
|
Irc.extract_prefix
|
def extract_prefix(self, prefix):
"""
It extracts an irc msg prefix chunk
"""
field = re.match(PREFIX_REG, prefix if prefix else '')
return (prefix,) if not field else field.group(1, 2, 3)
|
python
|
def extract_prefix(self, prefix):
"""
It extracts an irc msg prefix chunk
"""
field = re.match(PREFIX_REG, prefix if prefix else '')
return (prefix,) if not field else field.group(1, 2, 3)
|
[
"def",
"extract_prefix",
"(",
"self",
",",
"prefix",
")",
":",
"field",
"=",
"re",
".",
"match",
"(",
"PREFIX_REG",
",",
"prefix",
"if",
"prefix",
"else",
"''",
")",
"return",
"(",
"prefix",
",",
")",
"if",
"not",
"field",
"else",
"field",
".",
"group",
"(",
"1",
",",
"2",
",",
"3",
")"
] |
It extracts an irc msg prefix chunk
|
[
"It",
"extracts",
"an",
"irc",
"msg",
"prefix",
"chunk"
] |
4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99
|
https://github.com/untwisted/quickirc/blob/4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99/quickirc.py#L151-L158
|
247,133 |
untwisted/quickirc
|
quickirc.py
|
Irc.extract_args
|
def extract_args(self, data):
"""
It extracts irc msg arguments.
"""
args = []
data = data.strip(' ')
if ':' in data:
lhs, rhs = data.split(':', 1)
if lhs: args.extend(lhs.rstrip(' ').split(' '))
args.append(rhs)
else:
args.extend(data.split(' '))
return tuple(args)
|
python
|
def extract_args(self, data):
"""
It extracts irc msg arguments.
"""
args = []
data = data.strip(' ')
if ':' in data:
lhs, rhs = data.split(':', 1)
if lhs: args.extend(lhs.rstrip(' ').split(' '))
args.append(rhs)
else:
args.extend(data.split(' '))
return tuple(args)
|
[
"def",
"extract_args",
"(",
"self",
",",
"data",
")",
":",
"args",
"=",
"[",
"]",
"data",
"=",
"data",
".",
"strip",
"(",
"' '",
")",
"if",
"':'",
"in",
"data",
":",
"lhs",
",",
"rhs",
"=",
"data",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"lhs",
":",
"args",
".",
"extend",
"(",
"lhs",
".",
"rstrip",
"(",
"' '",
")",
".",
"split",
"(",
"' '",
")",
")",
"args",
".",
"append",
"(",
"rhs",
")",
"else",
":",
"args",
".",
"extend",
"(",
"data",
".",
"split",
"(",
"' '",
")",
")",
"return",
"tuple",
"(",
"args",
")"
] |
It extracts irc msg arguments.
|
[
"It",
"extracts",
"irc",
"msg",
"arguments",
"."
] |
4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99
|
https://github.com/untwisted/quickirc/blob/4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99/quickirc.py#L160-L172
|
247,134 |
untwisted/quickirc
|
quickirc.py
|
CTCP.extract_ctcp
|
def extract_ctcp(self, spin, nick, user, host, target, msg):
"""
it is used to extract ctcp requests into pieces.
"""
# The ctcp delimiter token.
DELIM = '\001'
if not msg.startswith(DELIM) or not msg.endswith(DELIM):
return
ctcp_args = msg.strip(DELIM).split(' ')
spawn(spin, ctcp_args[0], (nick, user, host, target, msg), *ctcp_args[1:])
|
python
|
def extract_ctcp(self, spin, nick, user, host, target, msg):
"""
it is used to extract ctcp requests into pieces.
"""
# The ctcp delimiter token.
DELIM = '\001'
if not msg.startswith(DELIM) or not msg.endswith(DELIM):
return
ctcp_args = msg.strip(DELIM).split(' ')
spawn(spin, ctcp_args[0], (nick, user, host, target, msg), *ctcp_args[1:])
|
[
"def",
"extract_ctcp",
"(",
"self",
",",
"spin",
",",
"nick",
",",
"user",
",",
"host",
",",
"target",
",",
"msg",
")",
":",
"# The ctcp delimiter token.",
"DELIM",
"=",
"'\\001'",
"if",
"not",
"msg",
".",
"startswith",
"(",
"DELIM",
")",
"or",
"not",
"msg",
".",
"endswith",
"(",
"DELIM",
")",
":",
"return",
"ctcp_args",
"=",
"msg",
".",
"strip",
"(",
"DELIM",
")",
".",
"split",
"(",
"' '",
")",
"spawn",
"(",
"spin",
",",
"ctcp_args",
"[",
"0",
"]",
",",
"(",
"nick",
",",
"user",
",",
"host",
",",
"target",
",",
"msg",
")",
",",
"*",
"ctcp_args",
"[",
"1",
":",
"]",
")"
] |
it is used to extract ctcp requests into pieces.
|
[
"it",
"is",
"used",
"to",
"extract",
"ctcp",
"requests",
"into",
"pieces",
"."
] |
4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99
|
https://github.com/untwisted/quickirc/blob/4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99/quickirc.py#L184-L197
|
247,135 |
untwisted/quickirc
|
quickirc.py
|
CTCP.patch
|
def patch(self, spin, header, *args):
"""
It spawns DCC TYPE as event.
"""
spawn(spin, 'DCC %s' % args[0], header, *args[1:])
|
python
|
def patch(self, spin, header, *args):
"""
It spawns DCC TYPE as event.
"""
spawn(spin, 'DCC %s' % args[0], header, *args[1:])
|
[
"def",
"patch",
"(",
"self",
",",
"spin",
",",
"header",
",",
"*",
"args",
")",
":",
"spawn",
"(",
"spin",
",",
"'DCC %s'",
"%",
"args",
"[",
"0",
"]",
",",
"header",
",",
"*",
"args",
"[",
"1",
":",
"]",
")"
] |
It spawns DCC TYPE as event.
|
[
"It",
"spawns",
"DCC",
"TYPE",
"as",
"event",
"."
] |
4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99
|
https://github.com/untwisted/quickirc/blob/4e92ffd45eef03eee2ba0b659b19b4f40a2dbf99/quickirc.py#L199-L204
|
247,136 |
fopina/tgbotplug
|
tgbot/tgbot.py
|
TGBot.print_commands
|
def print_commands(self, out=sys.stdout):
'''
utility method to print commands
and descriptions for @BotFather
'''
cmds = self.list_commands()
for ck in cmds:
if ck.printable:
out.write('%s\n' % ck)
|
python
|
def print_commands(self, out=sys.stdout):
'''
utility method to print commands
and descriptions for @BotFather
'''
cmds = self.list_commands()
for ck in cmds:
if ck.printable:
out.write('%s\n' % ck)
|
[
"def",
"print_commands",
"(",
"self",
",",
"out",
"=",
"sys",
".",
"stdout",
")",
":",
"cmds",
"=",
"self",
".",
"list_commands",
"(",
")",
"for",
"ck",
"in",
"cmds",
":",
"if",
"ck",
".",
"printable",
":",
"out",
".",
"write",
"(",
"'%s\\n'",
"%",
"ck",
")"
] |
utility method to print commands
and descriptions for @BotFather
|
[
"utility",
"method",
"to",
"print",
"commands",
"and",
"descriptions",
"for"
] |
c115733b03f2e23ddcdecfce588d1a6a1e5bde91
|
https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/tgbot.py#L161-L169
|
247,137 |
udoprog/mimeprovider
|
mimeprovider/client/requests.py
|
RequestsClient.request
|
def request(self, method, uri, **kw):
"""
The money maker.
"""
expect = kw.pop("expect", [])
mime_body = kw.pop("mime_body", None)
headers = kw.pop("headers", {})
data = kw.pop("data", None)
if mime_body:
mimevalues = self.mimeobjects.get(mime_body.__class__)
if not mimevalues:
raise ClientException(
("Cannot handle object of type "
"{0!r}").format(mime_body.__class__))
mapping = mimevalues[0]
document_type, mimetype, validator = mapping
data = document_type.render(validator, mime_body)
headers["Content-Type"] = mimetype
if uri[0] != '/':
uri = '/' + uri
url = "{self.scheme}://{self.host}{uri}".format(self=self, uri=uri)
response = self.session.request(
method, url,
headers=headers,
data=data,
**kw)
content_type = response.headers.get("Content-Type")
if content_type is None or not response.content:
return response, None
mimetype, opts = werkzeug.http.parse_options_header(content_type)
if mimetype not in self.mimetypes:
raise ClientException(
"Cannot handle response type: {0}".format(mimetype))
document_type, document_class, validator = self.mimetypes.get(mimetype)
if expect and document_class not in expect:
raise ClientException(
"Unexpected response type: {0}".format(mimetype))
try:
obj = document_type.parse(validator,
document_class,
response.content)
except MimeValidationError as e:
raise ClientException(
"Response format invalid: {0}".format(str(e)))
except:
log.error(
"Failed to parse content of type: {0}".format(mimetype),
exc_info=sys.exc_info())
raise ClientException(
"Failed to parse content of type: {0}".format(mimetype))
return response, obj
|
python
|
def request(self, method, uri, **kw):
"""
The money maker.
"""
expect = kw.pop("expect", [])
mime_body = kw.pop("mime_body", None)
headers = kw.pop("headers", {})
data = kw.pop("data", None)
if mime_body:
mimevalues = self.mimeobjects.get(mime_body.__class__)
if not mimevalues:
raise ClientException(
("Cannot handle object of type "
"{0!r}").format(mime_body.__class__))
mapping = mimevalues[0]
document_type, mimetype, validator = mapping
data = document_type.render(validator, mime_body)
headers["Content-Type"] = mimetype
if uri[0] != '/':
uri = '/' + uri
url = "{self.scheme}://{self.host}{uri}".format(self=self, uri=uri)
response = self.session.request(
method, url,
headers=headers,
data=data,
**kw)
content_type = response.headers.get("Content-Type")
if content_type is None or not response.content:
return response, None
mimetype, opts = werkzeug.http.parse_options_header(content_type)
if mimetype not in self.mimetypes:
raise ClientException(
"Cannot handle response type: {0}".format(mimetype))
document_type, document_class, validator = self.mimetypes.get(mimetype)
if expect and document_class not in expect:
raise ClientException(
"Unexpected response type: {0}".format(mimetype))
try:
obj = document_type.parse(validator,
document_class,
response.content)
except MimeValidationError as e:
raise ClientException(
"Response format invalid: {0}".format(str(e)))
except:
log.error(
"Failed to parse content of type: {0}".format(mimetype),
exc_info=sys.exc_info())
raise ClientException(
"Failed to parse content of type: {0}".format(mimetype))
return response, obj
|
[
"def",
"request",
"(",
"self",
",",
"method",
",",
"uri",
",",
"*",
"*",
"kw",
")",
":",
"expect",
"=",
"kw",
".",
"pop",
"(",
"\"expect\"",
",",
"[",
"]",
")",
"mime_body",
"=",
"kw",
".",
"pop",
"(",
"\"mime_body\"",
",",
"None",
")",
"headers",
"=",
"kw",
".",
"pop",
"(",
"\"headers\"",
",",
"{",
"}",
")",
"data",
"=",
"kw",
".",
"pop",
"(",
"\"data\"",
",",
"None",
")",
"if",
"mime_body",
":",
"mimevalues",
"=",
"self",
".",
"mimeobjects",
".",
"get",
"(",
"mime_body",
".",
"__class__",
")",
"if",
"not",
"mimevalues",
":",
"raise",
"ClientException",
"(",
"(",
"\"Cannot handle object of type \"",
"\"{0!r}\"",
")",
".",
"format",
"(",
"mime_body",
".",
"__class__",
")",
")",
"mapping",
"=",
"mimevalues",
"[",
"0",
"]",
"document_type",
",",
"mimetype",
",",
"validator",
"=",
"mapping",
"data",
"=",
"document_type",
".",
"render",
"(",
"validator",
",",
"mime_body",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"mimetype",
"if",
"uri",
"[",
"0",
"]",
"!=",
"'/'",
":",
"uri",
"=",
"'/'",
"+",
"uri",
"url",
"=",
"\"{self.scheme}://{self.host}{uri}\"",
".",
"format",
"(",
"self",
"=",
"self",
",",
"uri",
"=",
"uri",
")",
"response",
"=",
"self",
".",
"session",
".",
"request",
"(",
"method",
",",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"data",
",",
"*",
"*",
"kw",
")",
"content_type",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"\"Content-Type\"",
")",
"if",
"content_type",
"is",
"None",
"or",
"not",
"response",
".",
"content",
":",
"return",
"response",
",",
"None",
"mimetype",
",",
"opts",
"=",
"werkzeug",
".",
"http",
".",
"parse_options_header",
"(",
"content_type",
")",
"if",
"mimetype",
"not",
"in",
"self",
".",
"mimetypes",
":",
"raise",
"ClientException",
"(",
"\"Cannot handle response type: {0}\"",
".",
"format",
"(",
"mimetype",
")",
")",
"document_type",
",",
"document_class",
",",
"validator",
"=",
"self",
".",
"mimetypes",
".",
"get",
"(",
"mimetype",
")",
"if",
"expect",
"and",
"document_class",
"not",
"in",
"expect",
":",
"raise",
"ClientException",
"(",
"\"Unexpected response type: {0}\"",
".",
"format",
"(",
"mimetype",
")",
")",
"try",
":",
"obj",
"=",
"document_type",
".",
"parse",
"(",
"validator",
",",
"document_class",
",",
"response",
".",
"content",
")",
"except",
"MimeValidationError",
"as",
"e",
":",
"raise",
"ClientException",
"(",
"\"Response format invalid: {0}\"",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")",
"except",
":",
"log",
".",
"error",
"(",
"\"Failed to parse content of type: {0}\"",
".",
"format",
"(",
"mimetype",
")",
",",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
")",
"raise",
"ClientException",
"(",
"\"Failed to parse content of type: {0}\"",
".",
"format",
"(",
"mimetype",
")",
")",
"return",
"response",
",",
"obj"
] |
The money maker.
|
[
"The",
"money",
"maker",
"."
] |
5acd61eb0ef813b4a2eb6bbe75d07af1e11847a4
|
https://github.com/udoprog/mimeprovider/blob/5acd61eb0ef813b4a2eb6bbe75d07af1e11847a4/mimeprovider/client/requests.py#L56-L123
|
247,138 |
onenameio/onename-python
|
onename/client.py
|
OnenameClient.update_user
|
def update_user(self, username, profile, owner_privkey):
"""
Update profile_hash on blockchain
"""
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'profile': profile,
'owner_pubkey': owner_pubkey
}
resp = self._post_request(url, payload)
try:
unsigned_tx = resp['unsigned_tx']
except:
return resp
dht_resp = write_dht_profile(profile)
dht_resp = dht_resp[0]
if not dht_resp['status'] == 'success':
return {"error": "DHT write failed"}
# sign all unsigned inputs
signed_tx = sign_all_unsigned_inputs(owner_privkey, unsigned_tx)
return self.broadcast_transaction(signed_tx)
|
python
|
def update_user(self, username, profile, owner_privkey):
"""
Update profile_hash on blockchain
"""
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'profile': profile,
'owner_pubkey': owner_pubkey
}
resp = self._post_request(url, payload)
try:
unsigned_tx = resp['unsigned_tx']
except:
return resp
dht_resp = write_dht_profile(profile)
dht_resp = dht_resp[0]
if not dht_resp['status'] == 'success':
return {"error": "DHT write failed"}
# sign all unsigned inputs
signed_tx = sign_all_unsigned_inputs(owner_privkey, unsigned_tx)
return self.broadcast_transaction(signed_tx)
|
[
"def",
"update_user",
"(",
"self",
",",
"username",
",",
"profile",
",",
"owner_privkey",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"/users/\"",
"+",
"username",
"+",
"\"/update\"",
"owner_pubkey",
"=",
"get_pubkey_from_privkey",
"(",
"owner_privkey",
")",
"payload",
"=",
"{",
"'profile'",
":",
"profile",
",",
"'owner_pubkey'",
":",
"owner_pubkey",
"}",
"resp",
"=",
"self",
".",
"_post_request",
"(",
"url",
",",
"payload",
")",
"try",
":",
"unsigned_tx",
"=",
"resp",
"[",
"'unsigned_tx'",
"]",
"except",
":",
"return",
"resp",
"dht_resp",
"=",
"write_dht_profile",
"(",
"profile",
")",
"dht_resp",
"=",
"dht_resp",
"[",
"0",
"]",
"if",
"not",
"dht_resp",
"[",
"'status'",
"]",
"==",
"'success'",
":",
"return",
"{",
"\"error\"",
":",
"\"DHT write failed\"",
"}",
"# sign all unsigned inputs",
"signed_tx",
"=",
"sign_all_unsigned_inputs",
"(",
"owner_privkey",
",",
"unsigned_tx",
")",
"return",
"self",
".",
"broadcast_transaction",
"(",
"signed_tx",
")"
] |
Update profile_hash on blockchain
|
[
"Update",
"profile_hash",
"on",
"blockchain"
] |
74c583282f18ad9582c6b57b826126d045321494
|
https://github.com/onenameio/onename-python/blob/74c583282f18ad9582c6b57b826126d045321494/onename/client.py#L142-L172
|
247,139 |
onenameio/onename-python
|
onename/client.py
|
OnenameClient.transfer_user
|
def transfer_user(self, username, transfer_address, owner_privkey):
"""
Transfer name on blockchain
"""
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'transfer_address': transfer_address,
'owner_pubkey': owner_pubkey
}
resp = self._post_request(url, payload)
try:
unsigned_tx = resp['unsigned_tx']
except:
return resp
# sign all unsigned inputs
signed_tx = sign_all_unsigned_inputs(owner_privkey, unsigned_tx)
return self.broadcast_transaction(signed_tx)
|
python
|
def transfer_user(self, username, transfer_address, owner_privkey):
"""
Transfer name on blockchain
"""
url = self.base_url + "/users/" + username + "/update"
owner_pubkey = get_pubkey_from_privkey(owner_privkey)
payload = {
'transfer_address': transfer_address,
'owner_pubkey': owner_pubkey
}
resp = self._post_request(url, payload)
try:
unsigned_tx = resp['unsigned_tx']
except:
return resp
# sign all unsigned inputs
signed_tx = sign_all_unsigned_inputs(owner_privkey, unsigned_tx)
return self.broadcast_transaction(signed_tx)
|
[
"def",
"transfer_user",
"(",
"self",
",",
"username",
",",
"transfer_address",
",",
"owner_privkey",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"/users/\"",
"+",
"username",
"+",
"\"/update\"",
"owner_pubkey",
"=",
"get_pubkey_from_privkey",
"(",
"owner_privkey",
")",
"payload",
"=",
"{",
"'transfer_address'",
":",
"transfer_address",
",",
"'owner_pubkey'",
":",
"owner_pubkey",
"}",
"resp",
"=",
"self",
".",
"_post_request",
"(",
"url",
",",
"payload",
")",
"try",
":",
"unsigned_tx",
"=",
"resp",
"[",
"'unsigned_tx'",
"]",
"except",
":",
"return",
"resp",
"# sign all unsigned inputs",
"signed_tx",
"=",
"sign_all_unsigned_inputs",
"(",
"owner_privkey",
",",
"unsigned_tx",
")",
"return",
"self",
".",
"broadcast_transaction",
"(",
"signed_tx",
")"
] |
Transfer name on blockchain
|
[
"Transfer",
"name",
"on",
"blockchain"
] |
74c583282f18ad9582c6b57b826126d045321494
|
https://github.com/onenameio/onename-python/blob/74c583282f18ad9582c6b57b826126d045321494/onename/client.py#L174-L198
|
247,140 |
kervi/kervi-core
|
kervi/controllers/__init__.py
|
Controller.create
|
def create(controller_id, name):
"""Turn class into a kervi controller"""
def _decorator(cls):
class _ControllerClass(cls, Controller):
def __init__(self):
Controller.__init__(self, controller_id, name)
for key in cls.__dict__.keys():
prop = cls.__dict__[key]
if isinstance(prop, KerviValue):
if prop.is_input:
self.inputs._add_internal(key, prop)
else:
self.outputs._add_internal(key, prop)
cls.__init__(self)
return _ControllerClass
return _decorator
|
python
|
def create(controller_id, name):
"""Turn class into a kervi controller"""
def _decorator(cls):
class _ControllerClass(cls, Controller):
def __init__(self):
Controller.__init__(self, controller_id, name)
for key in cls.__dict__.keys():
prop = cls.__dict__[key]
if isinstance(prop, KerviValue):
if prop.is_input:
self.inputs._add_internal(key, prop)
else:
self.outputs._add_internal(key, prop)
cls.__init__(self)
return _ControllerClass
return _decorator
|
[
"def",
"create",
"(",
"controller_id",
",",
"name",
")",
":",
"def",
"_decorator",
"(",
"cls",
")",
":",
"class",
"_ControllerClass",
"(",
"cls",
",",
"Controller",
")",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"Controller",
".",
"__init__",
"(",
"self",
",",
"controller_id",
",",
"name",
")",
"for",
"key",
"in",
"cls",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"prop",
"=",
"cls",
".",
"__dict__",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"prop",
",",
"KerviValue",
")",
":",
"if",
"prop",
".",
"is_input",
":",
"self",
".",
"inputs",
".",
"_add_internal",
"(",
"key",
",",
"prop",
")",
"else",
":",
"self",
".",
"outputs",
".",
"_add_internal",
"(",
"key",
",",
"prop",
")",
"cls",
".",
"__init__",
"(",
"self",
")",
"return",
"_ControllerClass",
"return",
"_decorator"
] |
Turn class into a kervi controller
|
[
"Turn",
"class",
"into",
"a",
"kervi",
"controller"
] |
3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23
|
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/controllers/__init__.py#L205-L220
|
247,141 |
kervi/kervi-core
|
kervi/controllers/__init__.py
|
Controller.input
|
def input(input_id, name, value_class=NumberValue):
"""Add input to controller"""
def _init():
return value_class(
name,
input_id=input_id,
is_input=True,
index=-1
)
def _decorator(cls):
setattr(cls, input_id, _init())
return cls
return _decorator
|
python
|
def input(input_id, name, value_class=NumberValue):
"""Add input to controller"""
def _init():
return value_class(
name,
input_id=input_id,
is_input=True,
index=-1
)
def _decorator(cls):
setattr(cls, input_id, _init())
return cls
return _decorator
|
[
"def",
"input",
"(",
"input_id",
",",
"name",
",",
"value_class",
"=",
"NumberValue",
")",
":",
"def",
"_init",
"(",
")",
":",
"return",
"value_class",
"(",
"name",
",",
"input_id",
"=",
"input_id",
",",
"is_input",
"=",
"True",
",",
"index",
"=",
"-",
"1",
")",
"def",
"_decorator",
"(",
"cls",
")",
":",
"setattr",
"(",
"cls",
",",
"input_id",
",",
"_init",
"(",
")",
")",
"return",
"cls",
"return",
"_decorator"
] |
Add input to controller
|
[
"Add",
"input",
"to",
"controller"
] |
3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23
|
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/controllers/__init__.py#L223-L235
|
247,142 |
kervi/kervi-core
|
kervi/controllers/__init__.py
|
Controller.output
|
def output(output_id, name, value_class=NumberValue):
"""Add output to controller"""
def _init():
return value_class(
name,
input_id=output_id,
is_input=False,
index=-1
)
def _decorator(cls):
setattr(cls, output_id, _init())
return cls
return _decorator
|
python
|
def output(output_id, name, value_class=NumberValue):
"""Add output to controller"""
def _init():
return value_class(
name,
input_id=output_id,
is_input=False,
index=-1
)
def _decorator(cls):
setattr(cls, output_id, _init())
return cls
return _decorator
|
[
"def",
"output",
"(",
"output_id",
",",
"name",
",",
"value_class",
"=",
"NumberValue",
")",
":",
"def",
"_init",
"(",
")",
":",
"return",
"value_class",
"(",
"name",
",",
"input_id",
"=",
"output_id",
",",
"is_input",
"=",
"False",
",",
"index",
"=",
"-",
"1",
")",
"def",
"_decorator",
"(",
"cls",
")",
":",
"setattr",
"(",
"cls",
",",
"output_id",
",",
"_init",
"(",
")",
")",
"return",
"cls",
"return",
"_decorator"
] |
Add output to controller
|
[
"Add",
"output",
"to",
"controller"
] |
3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23
|
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/controllers/__init__.py#L238-L250
|
247,143 |
b3j0f/utils
|
b3j0f/utils/ut.py
|
_subset
|
def _subset(subset, superset):
"""True if subset is a subset of superset.
:param dict subset: subset to compare.
:param dict superset: superset to compare.
:return: True iif all pairs (key, value) of subset are in superset.
:rtype: bool
"""
result = True
for k in subset:
result = k in superset and subset[k] == superset[k]
if not result:
break
return result
|
python
|
def _subset(subset, superset):
"""True if subset is a subset of superset.
:param dict subset: subset to compare.
:param dict superset: superset to compare.
:return: True iif all pairs (key, value) of subset are in superset.
:rtype: bool
"""
result = True
for k in subset:
result = k in superset and subset[k] == superset[k]
if not result:
break
return result
|
[
"def",
"_subset",
"(",
"subset",
",",
"superset",
")",
":",
"result",
"=",
"True",
"for",
"k",
"in",
"subset",
":",
"result",
"=",
"k",
"in",
"superset",
"and",
"subset",
"[",
"k",
"]",
"==",
"superset",
"[",
"k",
"]",
"if",
"not",
"result",
":",
"break",
"return",
"result"
] |
True if subset is a subset of superset.
:param dict subset: subset to compare.
:param dict superset: superset to compare.
:return: True iif all pairs (key, value) of subset are in superset.
:rtype: bool
|
[
"True",
"if",
"subset",
"is",
"a",
"subset",
"of",
"superset",
"."
] |
793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff
|
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/ut.py#L40-L54
|
247,144 |
alexhayes/django-toolkit
|
django_toolkit/templatetags/buttons.py
|
button_with_image
|
def button_with_image(size='medium', icon=None, text=None, title=None, button=False,
name=None, target=False, disabled=False, extra_css=None, modal=None,
data_target='#modal', viewname=None, next=None, extra_href=False, href=False,
fancyajax=False, viewargs=[], **kwargs):
"""
Output a button using Bingo's button html.
@param size: The size that refers to the icon css class.
@param icon: A css class that refers to an icon - for example 'send_mail'
@param text: Text to display on the button
@param title: Title parameter for the button or if button=False the data-tip for an a tag.
@param button: If true a button tag will be returned.
@param name: A name for the button
@param target: A target for the a tag
@param disabled: If true, css class 'disabled' will be added to the container div.
@param extra_css: A string of extra css classes.
@param model: If True the class 'model' is placed on the a tag.
@param viewname: The django viewname as defined in a urls.py file.
@param **kwargs: Remaining keyword args are supplied to django.core.urlresolvers.reverse
@param next: If specified ?next=[NEXT] will be appended to any generated link.
@return string
"""
html = '<div class="button-std'
if disabled:
html += ' disabled'
html += '">'
if button:
html += '<button type="submit" name="%s" value="%s" class="%s">' % (name, title, icon)
if icon:
html += '<span class="icon-%s icon-%s-%s"></span>' % (size, size, icon)
html += '<span>%s</span></button>' % (title)
else:
html += '<a class="%s' % (icon)
if fancyajax:
html += ' fancybox fancybox.ajax'
if extra_css:
html += ' %s' % (extra_css)
html += '"'
if modal:
html += ' role="button" data-toggle="modal" data-remoteinbody="false"'
if data_target:
html += ' data-target="#modal"'
if fancyajax:
html += ' data-spinner-append="1"'
if viewname:
html += ' href="%s' % (reverse(viewname, args=viewargs, kwargs=kwargs))
elif href:
html += ' href="%s' % (href)
if viewname or href:
if next:
if next.startswith('/'):
html += '?next=%s' % next
else:
html += '?next=%s' % reverse(next)
if extra_href:
html += extra_href
html += '"'
if not title and text:
title = text
if title:
html += ' data-tip="%s"' % (title)
if target:
html += ' target="%s"' % (target)
html += '>'
if icon:
html += '<span class="icon-%s icon-%s-%s"></span>' % (size, size, icon)
if text:
html += '<span class="title">%s</span>' % (text)
html += '</a></div>'
return html
|
python
|
def button_with_image(size='medium', icon=None, text=None, title=None, button=False,
name=None, target=False, disabled=False, extra_css=None, modal=None,
data_target='#modal', viewname=None, next=None, extra_href=False, href=False,
fancyajax=False, viewargs=[], **kwargs):
"""
Output a button using Bingo's button html.
@param size: The size that refers to the icon css class.
@param icon: A css class that refers to an icon - for example 'send_mail'
@param text: Text to display on the button
@param title: Title parameter for the button or if button=False the data-tip for an a tag.
@param button: If true a button tag will be returned.
@param name: A name for the button
@param target: A target for the a tag
@param disabled: If true, css class 'disabled' will be added to the container div.
@param extra_css: A string of extra css classes.
@param model: If True the class 'model' is placed on the a tag.
@param viewname: The django viewname as defined in a urls.py file.
@param **kwargs: Remaining keyword args are supplied to django.core.urlresolvers.reverse
@param next: If specified ?next=[NEXT] will be appended to any generated link.
@return string
"""
html = '<div class="button-std'
if disabled:
html += ' disabled'
html += '">'
if button:
html += '<button type="submit" name="%s" value="%s" class="%s">' % (name, title, icon)
if icon:
html += '<span class="icon-%s icon-%s-%s"></span>' % (size, size, icon)
html += '<span>%s</span></button>' % (title)
else:
html += '<a class="%s' % (icon)
if fancyajax:
html += ' fancybox fancybox.ajax'
if extra_css:
html += ' %s' % (extra_css)
html += '"'
if modal:
html += ' role="button" data-toggle="modal" data-remoteinbody="false"'
if data_target:
html += ' data-target="#modal"'
if fancyajax:
html += ' data-spinner-append="1"'
if viewname:
html += ' href="%s' % (reverse(viewname, args=viewargs, kwargs=kwargs))
elif href:
html += ' href="%s' % (href)
if viewname or href:
if next:
if next.startswith('/'):
html += '?next=%s' % next
else:
html += '?next=%s' % reverse(next)
if extra_href:
html += extra_href
html += '"'
if not title and text:
title = text
if title:
html += ' data-tip="%s"' % (title)
if target:
html += ' target="%s"' % (target)
html += '>'
if icon:
html += '<span class="icon-%s icon-%s-%s"></span>' % (size, size, icon)
if text:
html += '<span class="title">%s</span>' % (text)
html += '</a></div>'
return html
|
[
"def",
"button_with_image",
"(",
"size",
"=",
"'medium'",
",",
"icon",
"=",
"None",
",",
"text",
"=",
"None",
",",
"title",
"=",
"None",
",",
"button",
"=",
"False",
",",
"name",
"=",
"None",
",",
"target",
"=",
"False",
",",
"disabled",
"=",
"False",
",",
"extra_css",
"=",
"None",
",",
"modal",
"=",
"None",
",",
"data_target",
"=",
"'#modal'",
",",
"viewname",
"=",
"None",
",",
"next",
"=",
"None",
",",
"extra_href",
"=",
"False",
",",
"href",
"=",
"False",
",",
"fancyajax",
"=",
"False",
",",
"viewargs",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"html",
"=",
"'<div class=\"button-std'",
"if",
"disabled",
":",
"html",
"+=",
"' disabled'",
"html",
"+=",
"'\">'",
"if",
"button",
":",
"html",
"+=",
"'<button type=\"submit\" name=\"%s\" value=\"%s\" class=\"%s\">'",
"%",
"(",
"name",
",",
"title",
",",
"icon",
")",
"if",
"icon",
":",
"html",
"+=",
"'<span class=\"icon-%s icon-%s-%s\"></span>'",
"%",
"(",
"size",
",",
"size",
",",
"icon",
")",
"html",
"+=",
"'<span>%s</span></button>'",
"%",
"(",
"title",
")",
"else",
":",
"html",
"+=",
"'<a class=\"%s'",
"%",
"(",
"icon",
")",
"if",
"fancyajax",
":",
"html",
"+=",
"' fancybox fancybox.ajax'",
"if",
"extra_css",
":",
"html",
"+=",
"' %s'",
"%",
"(",
"extra_css",
")",
"html",
"+=",
"'\"'",
"if",
"modal",
":",
"html",
"+=",
"' role=\"button\" data-toggle=\"modal\" data-remoteinbody=\"false\"'",
"if",
"data_target",
":",
"html",
"+=",
"' data-target=\"#modal\"'",
"if",
"fancyajax",
":",
"html",
"+=",
"' data-spinner-append=\"1\"'",
"if",
"viewname",
":",
"html",
"+=",
"' href=\"%s'",
"%",
"(",
"reverse",
"(",
"viewname",
",",
"args",
"=",
"viewargs",
",",
"kwargs",
"=",
"kwargs",
")",
")",
"elif",
"href",
":",
"html",
"+=",
"' href=\"%s'",
"%",
"(",
"href",
")",
"if",
"viewname",
"or",
"href",
":",
"if",
"next",
":",
"if",
"next",
".",
"startswith",
"(",
"'/'",
")",
":",
"html",
"+=",
"'?next=%s'",
"%",
"next",
"else",
":",
"html",
"+=",
"'?next=%s'",
"%",
"reverse",
"(",
"next",
")",
"if",
"extra_href",
":",
"html",
"+=",
"extra_href",
"html",
"+=",
"'\"'",
"if",
"not",
"title",
"and",
"text",
":",
"title",
"=",
"text",
"if",
"title",
":",
"html",
"+=",
"' data-tip=\"%s\"'",
"%",
"(",
"title",
")",
"if",
"target",
":",
"html",
"+=",
"' target=\"%s\"'",
"%",
"(",
"target",
")",
"html",
"+=",
"'>'",
"if",
"icon",
":",
"html",
"+=",
"'<span class=\"icon-%s icon-%s-%s\"></span>'",
"%",
"(",
"size",
",",
"size",
",",
"icon",
")",
"if",
"text",
":",
"html",
"+=",
"'<span class=\"title\">%s</span>'",
"%",
"(",
"text",
")",
"html",
"+=",
"'</a></div>'",
"return",
"html"
] |
Output a button using Bingo's button html.
@param size: The size that refers to the icon css class.
@param icon: A css class that refers to an icon - for example 'send_mail'
@param text: Text to display on the button
@param title: Title parameter for the button or if button=False the data-tip for an a tag.
@param button: If true a button tag will be returned.
@param name: A name for the button
@param target: A target for the a tag
@param disabled: If true, css class 'disabled' will be added to the container div.
@param extra_css: A string of extra css classes.
@param model: If True the class 'model' is placed on the a tag.
@param viewname: The django viewname as defined in a urls.py file.
@param **kwargs: Remaining keyword args are supplied to django.core.urlresolvers.reverse
@param next: If specified ?next=[NEXT] will be appended to any generated link.
@return string
|
[
"Output",
"a",
"button",
"using",
"Bingo",
"s",
"button",
"html",
"."
] |
b64106392fad596defc915b8235fe6e1d0013b5b
|
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/templatetags/buttons.py#L7-L83
|
247,145 |
rmed/dev-init
|
dev_init/dev_init.py
|
init_parser
|
def init_parser():
""" Initialize the arguments parser. """
parser = argparse.ArgumentParser(
description="Automated development environment initialization")
parser.add_argument('--version', action='version',
version='%(prog)s ' + __version__)
subparsers = parser.add_subparsers(title="commands")
# List command
parser_list = subparsers.add_parser("list",
help="list all the available environment types")
# New command
parser_new = subparsers.add_parser("new",
help="define a new environment type")
parser_new.add_argument("environment", help="name for the environment")
# Remove command
parser_remove = subparsers.add_parser("remove",
help="remove an environment type from the configuration file")
parser_remove.add_argument("environment", help="name of the environment")
# Show command
parser_show = subparsers.add_parser("show",
help="show the commands performed for a specific environment")
parser_show.add_argument("environment", help="name of the environment")
# Start command
parser_start = subparsers.add_parser("start",
help="start a new environment")
parser_start.add_argument("environment", help="name of the environment")
parser_start.add_argument("path", nargs="?",
help="path in which to initialize the environment")
return parser
|
python
|
def init_parser():
""" Initialize the arguments parser. """
parser = argparse.ArgumentParser(
description="Automated development environment initialization")
parser.add_argument('--version', action='version',
version='%(prog)s ' + __version__)
subparsers = parser.add_subparsers(title="commands")
# List command
parser_list = subparsers.add_parser("list",
help="list all the available environment types")
# New command
parser_new = subparsers.add_parser("new",
help="define a new environment type")
parser_new.add_argument("environment", help="name for the environment")
# Remove command
parser_remove = subparsers.add_parser("remove",
help="remove an environment type from the configuration file")
parser_remove.add_argument("environment", help="name of the environment")
# Show command
parser_show = subparsers.add_parser("show",
help="show the commands performed for a specific environment")
parser_show.add_argument("environment", help="name of the environment")
# Start command
parser_start = subparsers.add_parser("start",
help="start a new environment")
parser_start.add_argument("environment", help="name of the environment")
parser_start.add_argument("path", nargs="?",
help="path in which to initialize the environment")
return parser
|
[
"def",
"init_parser",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Automated development environment initialization\"",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"'%(prog)s '",
"+",
"__version__",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"title",
"=",
"\"commands\"",
")",
"# List command",
"parser_list",
"=",
"subparsers",
".",
"add_parser",
"(",
"\"list\"",
",",
"help",
"=",
"\"list all the available environment types\"",
")",
"# New command",
"parser_new",
"=",
"subparsers",
".",
"add_parser",
"(",
"\"new\"",
",",
"help",
"=",
"\"define a new environment type\"",
")",
"parser_new",
".",
"add_argument",
"(",
"\"environment\"",
",",
"help",
"=",
"\"name for the environment\"",
")",
"# Remove command",
"parser_remove",
"=",
"subparsers",
".",
"add_parser",
"(",
"\"remove\"",
",",
"help",
"=",
"\"remove an environment type from the configuration file\"",
")",
"parser_remove",
".",
"add_argument",
"(",
"\"environment\"",
",",
"help",
"=",
"\"name of the environment\"",
")",
"# Show command",
"parser_show",
"=",
"subparsers",
".",
"add_parser",
"(",
"\"show\"",
",",
"help",
"=",
"\"show the commands performed for a specific environment\"",
")",
"parser_show",
".",
"add_argument",
"(",
"\"environment\"",
",",
"help",
"=",
"\"name of the environment\"",
")",
"# Start command",
"parser_start",
"=",
"subparsers",
".",
"add_parser",
"(",
"\"start\"",
",",
"help",
"=",
"\"start a new environment\"",
")",
"parser_start",
".",
"add_argument",
"(",
"\"environment\"",
",",
"help",
"=",
"\"name of the environment\"",
")",
"parser_start",
".",
"add_argument",
"(",
"\"path\"",
",",
"nargs",
"=",
"\"?\"",
",",
"help",
"=",
"\"path in which to initialize the environment\"",
")",
"return",
"parser"
] |
Initialize the arguments parser.
|
[
"Initialize",
"the",
"arguments",
"parser",
"."
] |
afc5da13002e563324c6291dede0bf2e0f58171f
|
https://github.com/rmed/dev-init/blob/afc5da13002e563324c6291dede0bf2e0f58171f/dev_init/dev_init.py#L39-L75
|
247,146 |
rmed/dev-init
|
dev_init/dev_init.py
|
new_env
|
def new_env(environment):
""" Create a new environment in the configuration and ask the
user for the commands for this specific environment.
"""
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
if environment in parser.sections():
print("Environment '%s' already exists" % environment)
return
print("Please introduce (in order) the commands for '%s'\n" % environment)
print("Press RETURN to end command and RETURN with empty line to finish\n")
commands = []
cmd = ""
while True:
try:
cmd = raw_input("> ")
if not cmd:
break
commands.append(cmd)
except KeyboardInterrupt:
return
parser.add_section(environment)
parser.set(environment, "cmd", "\n".join(commands))
write_config(parser)
print("Added environment '%s'" % environment)
|
python
|
def new_env(environment):
""" Create a new environment in the configuration and ask the
user for the commands for this specific environment.
"""
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
if environment in parser.sections():
print("Environment '%s' already exists" % environment)
return
print("Please introduce (in order) the commands for '%s'\n" % environment)
print("Press RETURN to end command and RETURN with empty line to finish\n")
commands = []
cmd = ""
while True:
try:
cmd = raw_input("> ")
if not cmd:
break
commands.append(cmd)
except KeyboardInterrupt:
return
parser.add_section(environment)
parser.set(environment, "cmd", "\n".join(commands))
write_config(parser)
print("Added environment '%s'" % environment)
|
[
"def",
"new_env",
"(",
"environment",
")",
":",
"if",
"not",
"environment",
":",
"print",
"(",
"\"You need to supply an environment name\"",
")",
"return",
"parser",
"=",
"read_config",
"(",
")",
"if",
"environment",
"in",
"parser",
".",
"sections",
"(",
")",
":",
"print",
"(",
"\"Environment '%s' already exists\"",
"%",
"environment",
")",
"return",
"print",
"(",
"\"Please introduce (in order) the commands for '%s'\\n\"",
"%",
"environment",
")",
"print",
"(",
"\"Press RETURN to end command and RETURN with empty line to finish\\n\"",
")",
"commands",
"=",
"[",
"]",
"cmd",
"=",
"\"\"",
"while",
"True",
":",
"try",
":",
"cmd",
"=",
"raw_input",
"(",
"\"> \"",
")",
"if",
"not",
"cmd",
":",
"break",
"commands",
".",
"append",
"(",
"cmd",
")",
"except",
"KeyboardInterrupt",
":",
"return",
"parser",
".",
"add_section",
"(",
"environment",
")",
"parser",
".",
"set",
"(",
"environment",
",",
"\"cmd\"",
",",
"\"\\n\"",
".",
"join",
"(",
"commands",
")",
")",
"write_config",
"(",
"parser",
")",
"print",
"(",
"\"Added environment '%s'\"",
"%",
"environment",
")"
] |
Create a new environment in the configuration and ask the
user for the commands for this specific environment.
|
[
"Create",
"a",
"new",
"environment",
"in",
"the",
"configuration",
"and",
"ask",
"the",
"user",
"for",
"the",
"commands",
"for",
"this",
"specific",
"environment",
"."
] |
afc5da13002e563324c6291dede0bf2e0f58171f
|
https://github.com/rmed/dev-init/blob/afc5da13002e563324c6291dede0bf2e0f58171f/dev_init/dev_init.py#L84-L121
|
247,147 |
rmed/dev-init
|
dev_init/dev_init.py
|
remove_env
|
def remove_env(environment):
""" Remove an environment from the configuration. """
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
if not parser.remove_section(environment):
print("Unknown environment type '%s'" % environment)
return
write_config(parser)
print("Removed environment '%s'" % environment)
|
python
|
def remove_env(environment):
""" Remove an environment from the configuration. """
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
if not parser.remove_section(environment):
print("Unknown environment type '%s'" % environment)
return
write_config(parser)
print("Removed environment '%s'" % environment)
|
[
"def",
"remove_env",
"(",
"environment",
")",
":",
"if",
"not",
"environment",
":",
"print",
"(",
"\"You need to supply an environment name\"",
")",
"return",
"parser",
"=",
"read_config",
"(",
")",
"if",
"not",
"parser",
".",
"remove_section",
"(",
"environment",
")",
":",
"print",
"(",
"\"Unknown environment type '%s'\"",
"%",
"environment",
")",
"return",
"write_config",
"(",
"parser",
")",
"print",
"(",
"\"Removed environment '%s'\"",
"%",
"environment",
")"
] |
Remove an environment from the configuration.
|
[
"Remove",
"an",
"environment",
"from",
"the",
"configuration",
"."
] |
afc5da13002e563324c6291dede0bf2e0f58171f
|
https://github.com/rmed/dev-init/blob/afc5da13002e563324c6291dede0bf2e0f58171f/dev_init/dev_init.py#L123-L137
|
247,148 |
rmed/dev-init
|
dev_init/dev_init.py
|
show_env
|
def show_env(environment):
""" Show the commands for a given environment. """
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
try:
commands = parser.get(environment, "cmd").split("\n")
except KeyError:
print("Unknown environment type '%s'" % environment)
return
print("Environment: %s\n" % environment)
for cmd in commands:
print(cmd)
|
python
|
def show_env(environment):
""" Show the commands for a given environment. """
if not environment:
print("You need to supply an environment name")
return
parser = read_config()
try:
commands = parser.get(environment, "cmd").split("\n")
except KeyError:
print("Unknown environment type '%s'" % environment)
return
print("Environment: %s\n" % environment)
for cmd in commands:
print(cmd)
|
[
"def",
"show_env",
"(",
"environment",
")",
":",
"if",
"not",
"environment",
":",
"print",
"(",
"\"You need to supply an environment name\"",
")",
"return",
"parser",
"=",
"read_config",
"(",
")",
"try",
":",
"commands",
"=",
"parser",
".",
"get",
"(",
"environment",
",",
"\"cmd\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"except",
"KeyError",
":",
"print",
"(",
"\"Unknown environment type '%s'\"",
"%",
"environment",
")",
"return",
"print",
"(",
"\"Environment: %s\\n\"",
"%",
"environment",
")",
"for",
"cmd",
"in",
"commands",
":",
"print",
"(",
"cmd",
")"
] |
Show the commands for a given environment.
|
[
"Show",
"the",
"commands",
"for",
"a",
"given",
"environment",
"."
] |
afc5da13002e563324c6291dede0bf2e0f58171f
|
https://github.com/rmed/dev-init/blob/afc5da13002e563324c6291dede0bf2e0f58171f/dev_init/dev_init.py#L139-L157
|
247,149 |
rmed/dev-init
|
dev_init/dev_init.py
|
start_env
|
def start_env(environment, path):
""" Initialize a new environment in specified directory.
If path does not exist, will try to create the directory structure
recursively.
If the path is not provided, will use current working directory.
"""
parser = read_config()
if environment not in parser.sections():
print("Unknown environment type '%s'" % environment)
return
if path and not os.path.isdir(path):
try:
os.makedirs(path)
except os.error:
print("Could not create directory structure")
return
init_path = path if path else os.getcwd()
commands = parser.get(environment, "cmd").split("\n")
print("Working in directory: " + init_path)
for cmd in commands:
proc = subprocess.Popen(cmd , cwd=init_path, shell=True)
proc.wait()
print("Initialized '%s' environment" % environment)
|
python
|
def start_env(environment, path):
""" Initialize a new environment in specified directory.
If path does not exist, will try to create the directory structure
recursively.
If the path is not provided, will use current working directory.
"""
parser = read_config()
if environment not in parser.sections():
print("Unknown environment type '%s'" % environment)
return
if path and not os.path.isdir(path):
try:
os.makedirs(path)
except os.error:
print("Could not create directory structure")
return
init_path = path if path else os.getcwd()
commands = parser.get(environment, "cmd").split("\n")
print("Working in directory: " + init_path)
for cmd in commands:
proc = subprocess.Popen(cmd , cwd=init_path, shell=True)
proc.wait()
print("Initialized '%s' environment" % environment)
|
[
"def",
"start_env",
"(",
"environment",
",",
"path",
")",
":",
"parser",
"=",
"read_config",
"(",
")",
"if",
"environment",
"not",
"in",
"parser",
".",
"sections",
"(",
")",
":",
"print",
"(",
"\"Unknown environment type '%s'\"",
"%",
"environment",
")",
"return",
"if",
"path",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"os",
".",
"error",
":",
"print",
"(",
"\"Could not create directory structure\"",
")",
"return",
"init_path",
"=",
"path",
"if",
"path",
"else",
"os",
".",
"getcwd",
"(",
")",
"commands",
"=",
"parser",
".",
"get",
"(",
"environment",
",",
"\"cmd\"",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"print",
"(",
"\"Working in directory: \"",
"+",
"init_path",
")",
"for",
"cmd",
"in",
"commands",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"cwd",
"=",
"init_path",
",",
"shell",
"=",
"True",
")",
"proc",
".",
"wait",
"(",
")",
"print",
"(",
"\"Initialized '%s' environment\"",
"%",
"environment",
")"
] |
Initialize a new environment in specified directory.
If path does not exist, will try to create the directory structure
recursively.
If the path is not provided, will use current working directory.
|
[
"Initialize",
"a",
"new",
"environment",
"in",
"specified",
"directory",
"."
] |
afc5da13002e563324c6291dede0bf2e0f58171f
|
https://github.com/rmed/dev-init/blob/afc5da13002e563324c6291dede0bf2e0f58171f/dev_init/dev_init.py#L159-L190
|
247,150 |
rmed/dev-init
|
dev_init/dev_init.py
|
read_config
|
def read_config():
""" Read the configuration file and parse the different environments.
Returns: ConfigParser object
"""
if not os.path.isfile(CONFIG):
with open(CONFIG, "w"):
pass
parser = ConfigParser()
parser.read(CONFIG)
return parser
|
python
|
def read_config():
""" Read the configuration file and parse the different environments.
Returns: ConfigParser object
"""
if not os.path.isfile(CONFIG):
with open(CONFIG, "w"):
pass
parser = ConfigParser()
parser.read(CONFIG)
return parser
|
[
"def",
"read_config",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"CONFIG",
")",
":",
"with",
"open",
"(",
"CONFIG",
",",
"\"w\"",
")",
":",
"pass",
"parser",
"=",
"ConfigParser",
"(",
")",
"parser",
".",
"read",
"(",
"CONFIG",
")",
"return",
"parser"
] |
Read the configuration file and parse the different environments.
Returns: ConfigParser object
|
[
"Read",
"the",
"configuration",
"file",
"and",
"parse",
"the",
"different",
"environments",
"."
] |
afc5da13002e563324c6291dede0bf2e0f58171f
|
https://github.com/rmed/dev-init/blob/afc5da13002e563324c6291dede0bf2e0f58171f/dev_init/dev_init.py#L192-L204
|
247,151 |
rmed/dev-init
|
dev_init/dev_init.py
|
parse_action
|
def parse_action(action, parsed):
""" Parse the action to execute. """
if action == "list":
list_env()
elif action == "new":
new_env(parsed.environment)
elif action == "remove":
remove_env(parsed.environment)
elif action == "show":
show_env(parsed.environment)
elif action == "start":
start_env(parsed.environment, parsed.path)
|
python
|
def parse_action(action, parsed):
""" Parse the action to execute. """
if action == "list":
list_env()
elif action == "new":
new_env(parsed.environment)
elif action == "remove":
remove_env(parsed.environment)
elif action == "show":
show_env(parsed.environment)
elif action == "start":
start_env(parsed.environment, parsed.path)
|
[
"def",
"parse_action",
"(",
"action",
",",
"parsed",
")",
":",
"if",
"action",
"==",
"\"list\"",
":",
"list_env",
"(",
")",
"elif",
"action",
"==",
"\"new\"",
":",
"new_env",
"(",
"parsed",
".",
"environment",
")",
"elif",
"action",
"==",
"\"remove\"",
":",
"remove_env",
"(",
"parsed",
".",
"environment",
")",
"elif",
"action",
"==",
"\"show\"",
":",
"show_env",
"(",
"parsed",
".",
"environment",
")",
"elif",
"action",
"==",
"\"start\"",
":",
"start_env",
"(",
"parsed",
".",
"environment",
",",
"parsed",
".",
"path",
")"
] |
Parse the action to execute.
|
[
"Parse",
"the",
"action",
"to",
"execute",
"."
] |
afc5da13002e563324c6291dede0bf2e0f58171f
|
https://github.com/rmed/dev-init/blob/afc5da13002e563324c6291dede0bf2e0f58171f/dev_init/dev_init.py#L211-L226
|
247,152 |
edeposit/edeposit.amqp.pdfgen
|
src/edeposit/amqp/pdfgen/translator.py
|
gen_pdf
|
def gen_pdf(rst_content, style_text, header=None, footer=FOOTER):
"""
Create PDF file from `rst_content` using `style_text` as style.
Optinally, add `header` or `footer`.
Args:
rst_content (str): Content of the PDF file in restructured text markup.
style_text (str): Style for the :mod:`rst2pdf` module.
header (str, default None): Header which will be rendered to each page.
footer (str, default FOOTER): Footer, which will be rendered to each
page. See :attr:`FOOTER` for details.
Returns:
obj: StringIO file instance containing PDF file.
"""
out_file_obj = StringIO()
with NamedTemporaryFile() as f:
f.write(style_text)
f.flush()
pdf = _init_pdf(f.name, header, footer)
# create PDF
pdf.createPdf(text=rst_content, output=out_file_obj, compressed=True)
# rewind file pointer to begin
out_file_obj.seek(0)
return out_file_obj
|
python
|
def gen_pdf(rst_content, style_text, header=None, footer=FOOTER):
"""
Create PDF file from `rst_content` using `style_text` as style.
Optinally, add `header` or `footer`.
Args:
rst_content (str): Content of the PDF file in restructured text markup.
style_text (str): Style for the :mod:`rst2pdf` module.
header (str, default None): Header which will be rendered to each page.
footer (str, default FOOTER): Footer, which will be rendered to each
page. See :attr:`FOOTER` for details.
Returns:
obj: StringIO file instance containing PDF file.
"""
out_file_obj = StringIO()
with NamedTemporaryFile() as f:
f.write(style_text)
f.flush()
pdf = _init_pdf(f.name, header, footer)
# create PDF
pdf.createPdf(text=rst_content, output=out_file_obj, compressed=True)
# rewind file pointer to begin
out_file_obj.seek(0)
return out_file_obj
|
[
"def",
"gen_pdf",
"(",
"rst_content",
",",
"style_text",
",",
"header",
"=",
"None",
",",
"footer",
"=",
"FOOTER",
")",
":",
"out_file_obj",
"=",
"StringIO",
"(",
")",
"with",
"NamedTemporaryFile",
"(",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"style_text",
")",
"f",
".",
"flush",
"(",
")",
"pdf",
"=",
"_init_pdf",
"(",
"f",
".",
"name",
",",
"header",
",",
"footer",
")",
"# create PDF",
"pdf",
".",
"createPdf",
"(",
"text",
"=",
"rst_content",
",",
"output",
"=",
"out_file_obj",
",",
"compressed",
"=",
"True",
")",
"# rewind file pointer to begin",
"out_file_obj",
".",
"seek",
"(",
"0",
")",
"return",
"out_file_obj"
] |
Create PDF file from `rst_content` using `style_text` as style.
Optinally, add `header` or `footer`.
Args:
rst_content (str): Content of the PDF file in restructured text markup.
style_text (str): Style for the :mod:`rst2pdf` module.
header (str, default None): Header which will be rendered to each page.
footer (str, default FOOTER): Footer, which will be rendered to each
page. See :attr:`FOOTER` for details.
Returns:
obj: StringIO file instance containing PDF file.
|
[
"Create",
"PDF",
"file",
"from",
"rst_content",
"using",
"style_text",
"as",
"style",
"."
] |
1022d6d01196f4928d664a71e49273c2d8c67e63
|
https://github.com/edeposit/edeposit.amqp.pdfgen/blob/1022d6d01196f4928d664a71e49273c2d8c67e63/src/edeposit/amqp/pdfgen/translator.py#L49-L79
|
247,153 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
define_parameters
|
def define_parameters(**parameters):
"""Get a list of parameters to pass to AWS boto call."""
params = []
for key, value in parameters.items():
param = dict(ParameterKey=key, ParameterValue=value)
params.append(param)
return params
|
python
|
def define_parameters(**parameters):
"""Get a list of parameters to pass to AWS boto call."""
params = []
for key, value in parameters.items():
param = dict(ParameterKey=key, ParameterValue=value)
params.append(param)
return params
|
[
"def",
"define_parameters",
"(",
"*",
"*",
"parameters",
")",
":",
"params",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"parameters",
".",
"items",
"(",
")",
":",
"param",
"=",
"dict",
"(",
"ParameterKey",
"=",
"key",
",",
"ParameterValue",
"=",
"value",
")",
"params",
".",
"append",
"(",
"param",
")",
"return",
"params"
] |
Get a list of parameters to pass to AWS boto call.
|
[
"Get",
"a",
"list",
"of",
"parameters",
"to",
"pass",
"to",
"AWS",
"boto",
"call",
"."
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L75-L81
|
247,154 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
AwsEKS.create
|
def create(self):
"""Deploy a cluster on Amazon's EKS Service configured
for Jupyterhub Deployments.
"""
steps = [
(self.create_role, (), {}),
(self.create_vpc, (), {}),
(self.create_cluster, (), {}),
(self.create_node_group, (), {}),
(self.create_spot_nodes, (), {}),
(self.create_utilities, (), {}),
]
# Execute creation.
for step in tqdm.tqdm(steps, ncols=70):
method, args, kwargs = step
method(*args, **kwargs)
|
python
|
def create(self):
"""Deploy a cluster on Amazon's EKS Service configured
for Jupyterhub Deployments.
"""
steps = [
(self.create_role, (), {}),
(self.create_vpc, (), {}),
(self.create_cluster, (), {}),
(self.create_node_group, (), {}),
(self.create_spot_nodes, (), {}),
(self.create_utilities, (), {}),
]
# Execute creation.
for step in tqdm.tqdm(steps, ncols=70):
method, args, kwargs = step
method(*args, **kwargs)
|
[
"def",
"create",
"(",
"self",
")",
":",
"steps",
"=",
"[",
"(",
"self",
".",
"create_role",
",",
"(",
")",
",",
"{",
"}",
")",
",",
"(",
"self",
".",
"create_vpc",
",",
"(",
")",
",",
"{",
"}",
")",
",",
"(",
"self",
".",
"create_cluster",
",",
"(",
")",
",",
"{",
"}",
")",
",",
"(",
"self",
".",
"create_node_group",
",",
"(",
")",
",",
"{",
"}",
")",
",",
"(",
"self",
".",
"create_spot_nodes",
",",
"(",
")",
",",
"{",
"}",
")",
",",
"(",
"self",
".",
"create_utilities",
",",
"(",
")",
",",
"{",
"}",
")",
",",
"]",
"# Execute creation.",
"for",
"step",
"in",
"tqdm",
".",
"tqdm",
"(",
"steps",
",",
"ncols",
"=",
"70",
")",
":",
"method",
",",
"args",
",",
"kwargs",
"=",
"step",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Deploy a cluster on Amazon's EKS Service configured
for Jupyterhub Deployments.
|
[
"Deploy",
"a",
"cluster",
"on",
"Amazon",
"s",
"EKS",
"Service",
"configured",
"for",
"Jupyterhub",
"Deployments",
"."
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L238-L253
|
247,155 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
AwsEKS.delete
|
def delete(self):
"""Delete a running cluster."""
stacks = [
self.utilities_name,
self.spot_nodes_name,
self.node_group_name,
self.cluster_name,
self.vpc_name,
self.role_name
]
# Execute creation.
for stack in tqdm.tqdm(stacks, ncols=70):
self.delete_stack(stack)
|
python
|
def delete(self):
"""Delete a running cluster."""
stacks = [
self.utilities_name,
self.spot_nodes_name,
self.node_group_name,
self.cluster_name,
self.vpc_name,
self.role_name
]
# Execute creation.
for stack in tqdm.tqdm(stacks, ncols=70):
self.delete_stack(stack)
|
[
"def",
"delete",
"(",
"self",
")",
":",
"stacks",
"=",
"[",
"self",
".",
"utilities_name",
",",
"self",
".",
"spot_nodes_name",
",",
"self",
".",
"node_group_name",
",",
"self",
".",
"cluster_name",
",",
"self",
".",
"vpc_name",
",",
"self",
".",
"role_name",
"]",
"# Execute creation.",
"for",
"stack",
"in",
"tqdm",
".",
"tqdm",
"(",
"stacks",
",",
"ncols",
"=",
"70",
")",
":",
"self",
".",
"delete_stack",
"(",
"stack",
")"
] |
Delete a running cluster.
|
[
"Delete",
"a",
"running",
"cluster",
"."
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L255-L267
|
247,156 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
AwsEKS.get_template
|
def get_template(self, template_name, **parameters):
"""Pull templates from the AWS templates folder"""
template_path = pathlib.Path(self.template_dir).joinpath(template_name)
return get_template(template_path, **parameters)
|
python
|
def get_template(self, template_name, **parameters):
"""Pull templates from the AWS templates folder"""
template_path = pathlib.Path(self.template_dir).joinpath(template_name)
return get_template(template_path, **parameters)
|
[
"def",
"get_template",
"(",
"self",
",",
"template_name",
",",
"*",
"*",
"parameters",
")",
":",
"template_path",
"=",
"pathlib",
".",
"Path",
"(",
"self",
".",
"template_dir",
")",
".",
"joinpath",
"(",
"template_name",
")",
"return",
"get_template",
"(",
"template_path",
",",
"*",
"*",
"parameters",
")"
] |
Pull templates from the AWS templates folder
|
[
"Pull",
"templates",
"from",
"the",
"AWS",
"templates",
"folder"
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L285-L288
|
247,157 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
AwsEKS.delete_stack
|
def delete_stack(self, stack_name):
"""Teardown a stack."""
get_stack(stack_name)
CLIENT.delete_stack(
StackName=stack_name
)
DELETE_WAITER.wait(StackName=stack_name)
|
python
|
def delete_stack(self, stack_name):
"""Teardown a stack."""
get_stack(stack_name)
CLIENT.delete_stack(
StackName=stack_name
)
DELETE_WAITER.wait(StackName=stack_name)
|
[
"def",
"delete_stack",
"(",
"self",
",",
"stack_name",
")",
":",
"get_stack",
"(",
"stack_name",
")",
"CLIENT",
".",
"delete_stack",
"(",
"StackName",
"=",
"stack_name",
")",
"DELETE_WAITER",
".",
"wait",
"(",
"StackName",
"=",
"stack_name",
")"
] |
Teardown a stack.
|
[
"Teardown",
"a",
"stack",
"."
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L290-L296
|
247,158 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
AwsEKS.create_stack
|
def create_stack(
self,
stack_name,
stack_template_name,
parameters=None,
capabilities=None
):
"""Create a stack using Amazon's Cloud formation"""
# Build template_path
stack_template_path = pathlib.Path(
self.template_dir).joinpath(stack_template_name)
# Create stack
create_stack(
stack_name,
stack_template_path,
parameters=parameters,
capabilities=capabilities
)
|
python
|
def create_stack(
self,
stack_name,
stack_template_name,
parameters=None,
capabilities=None
):
"""Create a stack using Amazon's Cloud formation"""
# Build template_path
stack_template_path = pathlib.Path(
self.template_dir).joinpath(stack_template_name)
# Create stack
create_stack(
stack_name,
stack_template_path,
parameters=parameters,
capabilities=capabilities
)
|
[
"def",
"create_stack",
"(",
"self",
",",
"stack_name",
",",
"stack_template_name",
",",
"parameters",
"=",
"None",
",",
"capabilities",
"=",
"None",
")",
":",
"# Build template_path",
"stack_template_path",
"=",
"pathlib",
".",
"Path",
"(",
"self",
".",
"template_dir",
")",
".",
"joinpath",
"(",
"stack_template_name",
")",
"# Create stack",
"create_stack",
"(",
"stack_name",
",",
"stack_template_path",
",",
"parameters",
"=",
"parameters",
",",
"capabilities",
"=",
"capabilities",
")"
] |
Create a stack using Amazon's Cloud formation
|
[
"Create",
"a",
"stack",
"using",
"Amazon",
"s",
"Cloud",
"formation"
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L298-L316
|
247,159 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
AwsEKS.create_vpc
|
def create_vpc(self):
"""Create a virtual private cloud on Amazon's Web services configured
for deploying JupyterHubs.
"""
self.create_stack(
self.vpc_name,
'amazon-eks-vpc.yaml',
parameters=define_parameters(
VpcBlock="10.42.0.0/16",
Subnet01Block="10.42.1.0/24",
Subnet02Block="10.42.2.0/24",
Subnet03Block="10.42.3.0/24"
)
)
|
python
|
def create_vpc(self):
"""Create a virtual private cloud on Amazon's Web services configured
for deploying JupyterHubs.
"""
self.create_stack(
self.vpc_name,
'amazon-eks-vpc.yaml',
parameters=define_parameters(
VpcBlock="10.42.0.0/16",
Subnet01Block="10.42.1.0/24",
Subnet02Block="10.42.2.0/24",
Subnet03Block="10.42.3.0/24"
)
)
|
[
"def",
"create_vpc",
"(",
"self",
")",
":",
"self",
".",
"create_stack",
"(",
"self",
".",
"vpc_name",
",",
"'amazon-eks-vpc.yaml'",
",",
"parameters",
"=",
"define_parameters",
"(",
"VpcBlock",
"=",
"\"10.42.0.0/16\"",
",",
"Subnet01Block",
"=",
"\"10.42.1.0/24\"",
",",
"Subnet02Block",
"=",
"\"10.42.2.0/24\"",
",",
"Subnet03Block",
"=",
"\"10.42.3.0/24\"",
")",
")"
] |
Create a virtual private cloud on Amazon's Web services configured
for deploying JupyterHubs.
|
[
"Create",
"a",
"virtual",
"private",
"cloud",
"on",
"Amazon",
"s",
"Web",
"services",
"configured",
"for",
"deploying",
"JupyterHubs",
"."
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L328-L341
|
247,160 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
AwsEKS.create_cluster
|
def create_cluster(self):
"""Creates a cluster on Amazon EKS .
"""
self.create_stack(
self.cluster_name,
'amazon-eks-cluster.yaml',
parameters=define_parameters(
ClusterName=self.cluster_name,
ControlPlaneSecurityGroup=self.security_groups,
Subnets=self.subnet_ids
)
)
|
python
|
def create_cluster(self):
"""Creates a cluster on Amazon EKS .
"""
self.create_stack(
self.cluster_name,
'amazon-eks-cluster.yaml',
parameters=define_parameters(
ClusterName=self.cluster_name,
ControlPlaneSecurityGroup=self.security_groups,
Subnets=self.subnet_ids
)
)
|
[
"def",
"create_cluster",
"(",
"self",
")",
":",
"self",
".",
"create_stack",
"(",
"self",
".",
"cluster_name",
",",
"'amazon-eks-cluster.yaml'",
",",
"parameters",
"=",
"define_parameters",
"(",
"ClusterName",
"=",
"self",
".",
"cluster_name",
",",
"ControlPlaneSecurityGroup",
"=",
"self",
".",
"security_groups",
",",
"Subnets",
"=",
"self",
".",
"subnet_ids",
")",
")"
] |
Creates a cluster on Amazon EKS .
|
[
"Creates",
"a",
"cluster",
"on",
"Amazon",
"EKS",
"."
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L343-L354
|
247,161 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
AwsEKS.create_node_group
|
def create_node_group(self):
"""Create on-demand node group on Amazon EKS.
"""
self.create_stack(
self.node_group_name,
'amazon-eks-nodegroup.yaml',
capabilities=['CAPABILITY_IAM'],
parameters=define_parameters(
ClusterName=self.cluster_name,
ClusterControlPlaneSecurityGroup=self.security_groups,
Subnets=self.subnet_ids,
VpcId=self.vpc_ids,
KeyName=self.ssh_key_name,
NodeAutoScalingGroupMaxSize="1",
NodeVolumeSize="100",
NodeImageId="ami-0a54c984b9f908c81",
NodeGroupName=f"{self.name} OnDemand Nodes"
)
)
|
python
|
def create_node_group(self):
"""Create on-demand node group on Amazon EKS.
"""
self.create_stack(
self.node_group_name,
'amazon-eks-nodegroup.yaml',
capabilities=['CAPABILITY_IAM'],
parameters=define_parameters(
ClusterName=self.cluster_name,
ClusterControlPlaneSecurityGroup=self.security_groups,
Subnets=self.subnet_ids,
VpcId=self.vpc_ids,
KeyName=self.ssh_key_name,
NodeAutoScalingGroupMaxSize="1",
NodeVolumeSize="100",
NodeImageId="ami-0a54c984b9f908c81",
NodeGroupName=f"{self.name} OnDemand Nodes"
)
)
|
[
"def",
"create_node_group",
"(",
"self",
")",
":",
"self",
".",
"create_stack",
"(",
"self",
".",
"node_group_name",
",",
"'amazon-eks-nodegroup.yaml'",
",",
"capabilities",
"=",
"[",
"'CAPABILITY_IAM'",
"]",
",",
"parameters",
"=",
"define_parameters",
"(",
"ClusterName",
"=",
"self",
".",
"cluster_name",
",",
"ClusterControlPlaneSecurityGroup",
"=",
"self",
".",
"security_groups",
",",
"Subnets",
"=",
"self",
".",
"subnet_ids",
",",
"VpcId",
"=",
"self",
".",
"vpc_ids",
",",
"KeyName",
"=",
"self",
".",
"ssh_key_name",
",",
"NodeAutoScalingGroupMaxSize",
"=",
"\"1\"",
",",
"NodeVolumeSize",
"=",
"\"100\"",
",",
"NodeImageId",
"=",
"\"ami-0a54c984b9f908c81\"",
",",
"NodeGroupName",
"=",
"f\"{self.name} OnDemand Nodes\"",
")",
")"
] |
Create on-demand node group on Amazon EKS.
|
[
"Create",
"on",
"-",
"demand",
"node",
"group",
"on",
"Amazon",
"EKS",
"."
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L356-L374
|
247,162 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
AwsEKS.create_spot_nodes
|
def create_spot_nodes(self):
"""Create spot nodes.
"""
self.create_stack(
self.spot_nodes_name,
'amazon-spot-nodes.yaml',
parameters=define_parameters(
ClusterName=self.cluster_name,
Subnets=self.subnet_ids,
NodeInstanceProfile=self.node_instance_profile,
NodeInstanceRole=self.node_instance_role,
NodeSecurityGroup=self.node_security_group,
)
)
|
python
|
def create_spot_nodes(self):
"""Create spot nodes.
"""
self.create_stack(
self.spot_nodes_name,
'amazon-spot-nodes.yaml',
parameters=define_parameters(
ClusterName=self.cluster_name,
Subnets=self.subnet_ids,
NodeInstanceProfile=self.node_instance_profile,
NodeInstanceRole=self.node_instance_role,
NodeSecurityGroup=self.node_security_group,
)
)
|
[
"def",
"create_spot_nodes",
"(",
"self",
")",
":",
"self",
".",
"create_stack",
"(",
"self",
".",
"spot_nodes_name",
",",
"'amazon-spot-nodes.yaml'",
",",
"parameters",
"=",
"define_parameters",
"(",
"ClusterName",
"=",
"self",
".",
"cluster_name",
",",
"Subnets",
"=",
"self",
".",
"subnet_ids",
",",
"NodeInstanceProfile",
"=",
"self",
".",
"node_instance_profile",
",",
"NodeInstanceRole",
"=",
"self",
".",
"node_instance_role",
",",
"NodeSecurityGroup",
"=",
"self",
".",
"node_security_group",
",",
")",
")"
] |
Create spot nodes.
|
[
"Create",
"spot",
"nodes",
"."
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L376-L390
|
247,163 |
townsenddw/jhubctl
|
jhubctl/clusters/providers/aws/aws.py
|
AwsEKS.create_utilities
|
def create_utilities(self):
"""Create utitilies stack.
"""
self.create_stack(
self.utilities_name,
'amazon-utilities.yaml',
parameters=define_parameters(
Subnets=self.subnet_ids,
NodeSecurityGroup=self.node_security_group
)
)
|
python
|
def create_utilities(self):
"""Create utitilies stack.
"""
self.create_stack(
self.utilities_name,
'amazon-utilities.yaml',
parameters=define_parameters(
Subnets=self.subnet_ids,
NodeSecurityGroup=self.node_security_group
)
)
|
[
"def",
"create_utilities",
"(",
"self",
")",
":",
"self",
".",
"create_stack",
"(",
"self",
".",
"utilities_name",
",",
"'amazon-utilities.yaml'",
",",
"parameters",
"=",
"define_parameters",
"(",
"Subnets",
"=",
"self",
".",
"subnet_ids",
",",
"NodeSecurityGroup",
"=",
"self",
".",
"node_security_group",
")",
")"
] |
Create utitilies stack.
|
[
"Create",
"utitilies",
"stack",
"."
] |
c8c20f86a16e9d01dd90e4607d81423417cc773b
|
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/clusters/providers/aws/aws.py#L392-L402
|
247,164 |
klen/muffin-debugtoolbar
|
muffin_debugtoolbar/plugin.py
|
debugtoolbar_middleware_factory
|
def debugtoolbar_middleware_factory(app, handler):
"""Setup Debug middleware."""
dbtb = app.ps.debugtoolbar
@asyncio.coroutine
def debugtoolbar_middleware(request):
"""Integrate to application."""
# Check for debugtoolbar is enabled for the request
if not dbtb.cfg.enabled or any(map(request.path.startswith, dbtb.cfg.exclude)):
return (yield from handler(request))
remote_host, remote_port = request.transport.get_extra_info('peername')
for host in dbtb.cfg.hosts:
if ip.ip_address(remote_host) in ip.ip_network(host):
break
else:
return (yield from handler(request))
# Initialize a debugstate for the request
state = DebugState(app, request)
dbtb.history[state.id] = state
context_switcher = state.wrap_handler(handler)
# Make response
try:
response = yield from context_switcher(handler(request))
state.status = response.status
except HTTPException as exc:
response = exc
state.status = response.status
except Exception as exc:
# Store traceback for unhandled exception
state.status = 500
if not dbtb.cfg.intercept_exc:
raise
tb = get_traceback(
info=sys.exc_info(), skip=1, show_hidden_frames=False,
ignore_system_exceptions=True, exc=exc)
dbtb.exceptions[tb.id] = request['pdbt_tb'] = tb
for frame in tb.frames:
dbtb.frames[id(frame)] = frame
response = Response(text=tb.render_full(request), content_type='text/html')
# Intercept http redirect codes and display an html page with a link to the target.
if dbtb.cfg.intercept_redirects and response.status in REDIRECT_CODES \
and 'Location' in response.headers:
response = yield from app.ps.jinja2.render(
'debugtoolbar/redirect.html', response=response)
response = Response(text=response, content_type='text/html')
yield from state.process_response(response)
if isinstance(response, Response) and response.content_type == 'text/html' and \
RE_BODY.search(response.body):
return (yield from dbtb.inject(state, response))
return response
return debugtoolbar_middleware
|
python
|
def debugtoolbar_middleware_factory(app, handler):
"""Setup Debug middleware."""
dbtb = app.ps.debugtoolbar
@asyncio.coroutine
def debugtoolbar_middleware(request):
"""Integrate to application."""
# Check for debugtoolbar is enabled for the request
if not dbtb.cfg.enabled or any(map(request.path.startswith, dbtb.cfg.exclude)):
return (yield from handler(request))
remote_host, remote_port = request.transport.get_extra_info('peername')
for host in dbtb.cfg.hosts:
if ip.ip_address(remote_host) in ip.ip_network(host):
break
else:
return (yield from handler(request))
# Initialize a debugstate for the request
state = DebugState(app, request)
dbtb.history[state.id] = state
context_switcher = state.wrap_handler(handler)
# Make response
try:
response = yield from context_switcher(handler(request))
state.status = response.status
except HTTPException as exc:
response = exc
state.status = response.status
except Exception as exc:
# Store traceback for unhandled exception
state.status = 500
if not dbtb.cfg.intercept_exc:
raise
tb = get_traceback(
info=sys.exc_info(), skip=1, show_hidden_frames=False,
ignore_system_exceptions=True, exc=exc)
dbtb.exceptions[tb.id] = request['pdbt_tb'] = tb
for frame in tb.frames:
dbtb.frames[id(frame)] = frame
response = Response(text=tb.render_full(request), content_type='text/html')
# Intercept http redirect codes and display an html page with a link to the target.
if dbtb.cfg.intercept_redirects and response.status in REDIRECT_CODES \
and 'Location' in response.headers:
response = yield from app.ps.jinja2.render(
'debugtoolbar/redirect.html', response=response)
response = Response(text=response, content_type='text/html')
yield from state.process_response(response)
if isinstance(response, Response) and response.content_type == 'text/html' and \
RE_BODY.search(response.body):
return (yield from dbtb.inject(state, response))
return response
return debugtoolbar_middleware
|
[
"def",
"debugtoolbar_middleware_factory",
"(",
"app",
",",
"handler",
")",
":",
"dbtb",
"=",
"app",
".",
"ps",
".",
"debugtoolbar",
"@",
"asyncio",
".",
"coroutine",
"def",
"debugtoolbar_middleware",
"(",
"request",
")",
":",
"\"\"\"Integrate to application.\"\"\"",
"# Check for debugtoolbar is enabled for the request",
"if",
"not",
"dbtb",
".",
"cfg",
".",
"enabled",
"or",
"any",
"(",
"map",
"(",
"request",
".",
"path",
".",
"startswith",
",",
"dbtb",
".",
"cfg",
".",
"exclude",
")",
")",
":",
"return",
"(",
"yield",
"from",
"handler",
"(",
"request",
")",
")",
"remote_host",
",",
"remote_port",
"=",
"request",
".",
"transport",
".",
"get_extra_info",
"(",
"'peername'",
")",
"for",
"host",
"in",
"dbtb",
".",
"cfg",
".",
"hosts",
":",
"if",
"ip",
".",
"ip_address",
"(",
"remote_host",
")",
"in",
"ip",
".",
"ip_network",
"(",
"host",
")",
":",
"break",
"else",
":",
"return",
"(",
"yield",
"from",
"handler",
"(",
"request",
")",
")",
"# Initialize a debugstate for the request",
"state",
"=",
"DebugState",
"(",
"app",
",",
"request",
")",
"dbtb",
".",
"history",
"[",
"state",
".",
"id",
"]",
"=",
"state",
"context_switcher",
"=",
"state",
".",
"wrap_handler",
"(",
"handler",
")",
"# Make response",
"try",
":",
"response",
"=",
"yield",
"from",
"context_switcher",
"(",
"handler",
"(",
"request",
")",
")",
"state",
".",
"status",
"=",
"response",
".",
"status",
"except",
"HTTPException",
"as",
"exc",
":",
"response",
"=",
"exc",
"state",
".",
"status",
"=",
"response",
".",
"status",
"except",
"Exception",
"as",
"exc",
":",
"# Store traceback for unhandled exception",
"state",
".",
"status",
"=",
"500",
"if",
"not",
"dbtb",
".",
"cfg",
".",
"intercept_exc",
":",
"raise",
"tb",
"=",
"get_traceback",
"(",
"info",
"=",
"sys",
".",
"exc_info",
"(",
")",
",",
"skip",
"=",
"1",
",",
"show_hidden_frames",
"=",
"False",
",",
"ignore_system_exceptions",
"=",
"True",
",",
"exc",
"=",
"exc",
")",
"dbtb",
".",
"exceptions",
"[",
"tb",
".",
"id",
"]",
"=",
"request",
"[",
"'pdbt_tb'",
"]",
"=",
"tb",
"for",
"frame",
"in",
"tb",
".",
"frames",
":",
"dbtb",
".",
"frames",
"[",
"id",
"(",
"frame",
")",
"]",
"=",
"frame",
"response",
"=",
"Response",
"(",
"text",
"=",
"tb",
".",
"render_full",
"(",
"request",
")",
",",
"content_type",
"=",
"'text/html'",
")",
"# Intercept http redirect codes and display an html page with a link to the target.",
"if",
"dbtb",
".",
"cfg",
".",
"intercept_redirects",
"and",
"response",
".",
"status",
"in",
"REDIRECT_CODES",
"and",
"'Location'",
"in",
"response",
".",
"headers",
":",
"response",
"=",
"yield",
"from",
"app",
".",
"ps",
".",
"jinja2",
".",
"render",
"(",
"'debugtoolbar/redirect.html'",
",",
"response",
"=",
"response",
")",
"response",
"=",
"Response",
"(",
"text",
"=",
"response",
",",
"content_type",
"=",
"'text/html'",
")",
"yield",
"from",
"state",
".",
"process_response",
"(",
"response",
")",
"if",
"isinstance",
"(",
"response",
",",
"Response",
")",
"and",
"response",
".",
"content_type",
"==",
"'text/html'",
"and",
"RE_BODY",
".",
"search",
"(",
"response",
".",
"body",
")",
":",
"return",
"(",
"yield",
"from",
"dbtb",
".",
"inject",
"(",
"state",
",",
"response",
")",
")",
"return",
"response",
"return",
"debugtoolbar_middleware"
] |
Setup Debug middleware.
|
[
"Setup",
"Debug",
"middleware",
"."
] |
b650b35fbe2035888f6bba5dac3073ef01c94dc6
|
https://github.com/klen/muffin-debugtoolbar/blob/b650b35fbe2035888f6bba5dac3073ef01c94dc6/muffin_debugtoolbar/plugin.py#L28-L89
|
247,165 |
klen/muffin-debugtoolbar
|
muffin_debugtoolbar/plugin.py
|
Plugin.setup
|
def setup(self, app):
"""Setup the plugin and prepare application."""
super(Plugin, self).setup(app)
if 'jinja2' not in app.plugins:
raise PluginException('The plugin requires Muffin-Jinja2 plugin installed.')
self.cfg.prefix = self.cfg.prefix.rstrip('/') + '/'
self.cfg.exclude.append(self.cfg.prefix)
# Setup debugtoolbar templates
app.ps.jinja2.cfg.template_folders.append(op.join(PLUGIN_ROOT, 'templates'))
self.cfg.panels += list(self.cfg.additional_panels)
panels_ = []
for panel in self.cfg.panels:
if isinstance(panel, str):
mod, _, panel = panel.partition(':')
mod = importlib.import_module(mod)
panel = eval(panel or 'DebugPanel', mod.__dict__)
panels_.append(panel)
self.cfg.panels = panels_
# Setup debugtoolbar static files
app.router.register_route(StaticRoute(
'debugtoolbar.static',
self.cfg.prefix + 'static/',
op.join(PLUGIN_ROOT, 'static')))
app.register(self.cfg.prefix + 'sse', name='debugtoolbar.sse')(self.sse)
app.register(
self.cfg.prefix + 'exception', name='debugtoolbar.exception')(self.exception)
app.register(
self.cfg.prefix + 'execute', name='debugtoolbar.execute')(self.execute)
app.register(
self.cfg.prefix + 'source', name='debugtoolbar.source')(self.source)
app.register(
self.cfg.prefix.rstrip('/'),
self.cfg.prefix,
self.cfg.prefix + '{request_id}', name='debugtoolbar.request')(self.view)
app['debugtoolbar'] = {}
app['debugtoolbar']['pdbt_token'] = uuid.uuid4().hex
self.history = app['debugtoolbar']['history'] = utils.History(50)
self.exceptions = app['debugtoolbar']['exceptions'] = utils.History(50)
self.frames = app['debugtoolbar']['frames'] = utils.History(100)
|
python
|
def setup(self, app):
"""Setup the plugin and prepare application."""
super(Plugin, self).setup(app)
if 'jinja2' not in app.plugins:
raise PluginException('The plugin requires Muffin-Jinja2 plugin installed.')
self.cfg.prefix = self.cfg.prefix.rstrip('/') + '/'
self.cfg.exclude.append(self.cfg.prefix)
# Setup debugtoolbar templates
app.ps.jinja2.cfg.template_folders.append(op.join(PLUGIN_ROOT, 'templates'))
self.cfg.panels += list(self.cfg.additional_panels)
panels_ = []
for panel in self.cfg.panels:
if isinstance(panel, str):
mod, _, panel = panel.partition(':')
mod = importlib.import_module(mod)
panel = eval(panel or 'DebugPanel', mod.__dict__)
panels_.append(panel)
self.cfg.panels = panels_
# Setup debugtoolbar static files
app.router.register_route(StaticRoute(
'debugtoolbar.static',
self.cfg.prefix + 'static/',
op.join(PLUGIN_ROOT, 'static')))
app.register(self.cfg.prefix + 'sse', name='debugtoolbar.sse')(self.sse)
app.register(
self.cfg.prefix + 'exception', name='debugtoolbar.exception')(self.exception)
app.register(
self.cfg.prefix + 'execute', name='debugtoolbar.execute')(self.execute)
app.register(
self.cfg.prefix + 'source', name='debugtoolbar.source')(self.source)
app.register(
self.cfg.prefix.rstrip('/'),
self.cfg.prefix,
self.cfg.prefix + '{request_id}', name='debugtoolbar.request')(self.view)
app['debugtoolbar'] = {}
app['debugtoolbar']['pdbt_token'] = uuid.uuid4().hex
self.history = app['debugtoolbar']['history'] = utils.History(50)
self.exceptions = app['debugtoolbar']['exceptions'] = utils.History(50)
self.frames = app['debugtoolbar']['frames'] = utils.History(100)
|
[
"def",
"setup",
"(",
"self",
",",
"app",
")",
":",
"super",
"(",
"Plugin",
",",
"self",
")",
".",
"setup",
"(",
"app",
")",
"if",
"'jinja2'",
"not",
"in",
"app",
".",
"plugins",
":",
"raise",
"PluginException",
"(",
"'The plugin requires Muffin-Jinja2 plugin installed.'",
")",
"self",
".",
"cfg",
".",
"prefix",
"=",
"self",
".",
"cfg",
".",
"prefix",
".",
"rstrip",
"(",
"'/'",
")",
"+",
"'/'",
"self",
".",
"cfg",
".",
"exclude",
".",
"append",
"(",
"self",
".",
"cfg",
".",
"prefix",
")",
"# Setup debugtoolbar templates",
"app",
".",
"ps",
".",
"jinja2",
".",
"cfg",
".",
"template_folders",
".",
"append",
"(",
"op",
".",
"join",
"(",
"PLUGIN_ROOT",
",",
"'templates'",
")",
")",
"self",
".",
"cfg",
".",
"panels",
"+=",
"list",
"(",
"self",
".",
"cfg",
".",
"additional_panels",
")",
"panels_",
"=",
"[",
"]",
"for",
"panel",
"in",
"self",
".",
"cfg",
".",
"panels",
":",
"if",
"isinstance",
"(",
"panel",
",",
"str",
")",
":",
"mod",
",",
"_",
",",
"panel",
"=",
"panel",
".",
"partition",
"(",
"':'",
")",
"mod",
"=",
"importlib",
".",
"import_module",
"(",
"mod",
")",
"panel",
"=",
"eval",
"(",
"panel",
"or",
"'DebugPanel'",
",",
"mod",
".",
"__dict__",
")",
"panels_",
".",
"append",
"(",
"panel",
")",
"self",
".",
"cfg",
".",
"panels",
"=",
"panels_",
"# Setup debugtoolbar static files",
"app",
".",
"router",
".",
"register_route",
"(",
"StaticRoute",
"(",
"'debugtoolbar.static'",
",",
"self",
".",
"cfg",
".",
"prefix",
"+",
"'static/'",
",",
"op",
".",
"join",
"(",
"PLUGIN_ROOT",
",",
"'static'",
")",
")",
")",
"app",
".",
"register",
"(",
"self",
".",
"cfg",
".",
"prefix",
"+",
"'sse'",
",",
"name",
"=",
"'debugtoolbar.sse'",
")",
"(",
"self",
".",
"sse",
")",
"app",
".",
"register",
"(",
"self",
".",
"cfg",
".",
"prefix",
"+",
"'exception'",
",",
"name",
"=",
"'debugtoolbar.exception'",
")",
"(",
"self",
".",
"exception",
")",
"app",
".",
"register",
"(",
"self",
".",
"cfg",
".",
"prefix",
"+",
"'execute'",
",",
"name",
"=",
"'debugtoolbar.execute'",
")",
"(",
"self",
".",
"execute",
")",
"app",
".",
"register",
"(",
"self",
".",
"cfg",
".",
"prefix",
"+",
"'source'",
",",
"name",
"=",
"'debugtoolbar.source'",
")",
"(",
"self",
".",
"source",
")",
"app",
".",
"register",
"(",
"self",
".",
"cfg",
".",
"prefix",
".",
"rstrip",
"(",
"'/'",
")",
",",
"self",
".",
"cfg",
".",
"prefix",
",",
"self",
".",
"cfg",
".",
"prefix",
"+",
"'{request_id}'",
",",
"name",
"=",
"'debugtoolbar.request'",
")",
"(",
"self",
".",
"view",
")",
"app",
"[",
"'debugtoolbar'",
"]",
"=",
"{",
"}",
"app",
"[",
"'debugtoolbar'",
"]",
"[",
"'pdbt_token'",
"]",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"self",
".",
"history",
"=",
"app",
"[",
"'debugtoolbar'",
"]",
"[",
"'history'",
"]",
"=",
"utils",
".",
"History",
"(",
"50",
")",
"self",
".",
"exceptions",
"=",
"app",
"[",
"'debugtoolbar'",
"]",
"[",
"'exceptions'",
"]",
"=",
"utils",
".",
"History",
"(",
"50",
")",
"self",
".",
"frames",
"=",
"app",
"[",
"'debugtoolbar'",
"]",
"[",
"'frames'",
"]",
"=",
"utils",
".",
"History",
"(",
"100",
")"
] |
Setup the plugin and prepare application.
|
[
"Setup",
"the",
"plugin",
"and",
"prepare",
"application",
"."
] |
b650b35fbe2035888f6bba5dac3073ef01c94dc6
|
https://github.com/klen/muffin-debugtoolbar/blob/b650b35fbe2035888f6bba5dac3073ef01c94dc6/muffin_debugtoolbar/plugin.py#L119-L164
|
247,166 |
klen/muffin-debugtoolbar
|
muffin_debugtoolbar/plugin.py
|
Plugin.inject
|
def inject(self, state, response):
""" Inject Debug Toolbar code to response body. """
html = yield from self.app.ps.jinja2.render(
'debugtoolbar/inject.html',
static_path=self.cfg.prefix + 'static',
toolbar_url=self.cfg.prefix + state.id,
)
html = html.encode(state.request.charset or 'utf-8')
response.body = RE_BODY.sub(html + b'</body>', response.body)
return response
|
python
|
def inject(self, state, response):
""" Inject Debug Toolbar code to response body. """
html = yield from self.app.ps.jinja2.render(
'debugtoolbar/inject.html',
static_path=self.cfg.prefix + 'static',
toolbar_url=self.cfg.prefix + state.id,
)
html = html.encode(state.request.charset or 'utf-8')
response.body = RE_BODY.sub(html + b'</body>', response.body)
return response
|
[
"def",
"inject",
"(",
"self",
",",
"state",
",",
"response",
")",
":",
"html",
"=",
"yield",
"from",
"self",
".",
"app",
".",
"ps",
".",
"jinja2",
".",
"render",
"(",
"'debugtoolbar/inject.html'",
",",
"static_path",
"=",
"self",
".",
"cfg",
".",
"prefix",
"+",
"'static'",
",",
"toolbar_url",
"=",
"self",
".",
"cfg",
".",
"prefix",
"+",
"state",
".",
"id",
",",
")",
"html",
"=",
"html",
".",
"encode",
"(",
"state",
".",
"request",
".",
"charset",
"or",
"'utf-8'",
")",
"response",
".",
"body",
"=",
"RE_BODY",
".",
"sub",
"(",
"html",
"+",
"b'</body>'",
",",
"response",
".",
"body",
")",
"return",
"response"
] |
Inject Debug Toolbar code to response body.
|
[
"Inject",
"Debug",
"Toolbar",
"code",
"to",
"response",
"body",
"."
] |
b650b35fbe2035888f6bba5dac3073ef01c94dc6
|
https://github.com/klen/muffin-debugtoolbar/blob/b650b35fbe2035888f6bba5dac3073ef01c94dc6/muffin_debugtoolbar/plugin.py#L173-L182
|
247,167 |
klen/muffin-debugtoolbar
|
muffin_debugtoolbar/plugin.py
|
Plugin.view
|
def view(self, request):
""" Debug Toolbar. """
auth = yield from self.authorize(request)
if not auth:
raise HTTPForbidden()
request_id = request.match_info.get('request_id')
state = self.history.get(request_id, None)
response = yield from self.app.ps.jinja2.render(
'debugtoolbar/toolbar.html',
debugtoolbar=self,
state=state,
static_path=self.cfg.prefix + 'static',
panels=state and state.panels or [],
global_panels=self.global_panels,
request=state and state.request or None,
)
return Response(text=response, content_type='text/html')
|
python
|
def view(self, request):
""" Debug Toolbar. """
auth = yield from self.authorize(request)
if not auth:
raise HTTPForbidden()
request_id = request.match_info.get('request_id')
state = self.history.get(request_id, None)
response = yield from self.app.ps.jinja2.render(
'debugtoolbar/toolbar.html',
debugtoolbar=self,
state=state,
static_path=self.cfg.prefix + 'static',
panels=state and state.panels or [],
global_panels=self.global_panels,
request=state and state.request or None,
)
return Response(text=response, content_type='text/html')
|
[
"def",
"view",
"(",
"self",
",",
"request",
")",
":",
"auth",
"=",
"yield",
"from",
"self",
".",
"authorize",
"(",
"request",
")",
"if",
"not",
"auth",
":",
"raise",
"HTTPForbidden",
"(",
")",
"request_id",
"=",
"request",
".",
"match_info",
".",
"get",
"(",
"'request_id'",
")",
"state",
"=",
"self",
".",
"history",
".",
"get",
"(",
"request_id",
",",
"None",
")",
"response",
"=",
"yield",
"from",
"self",
".",
"app",
".",
"ps",
".",
"jinja2",
".",
"render",
"(",
"'debugtoolbar/toolbar.html'",
",",
"debugtoolbar",
"=",
"self",
",",
"state",
"=",
"state",
",",
"static_path",
"=",
"self",
".",
"cfg",
".",
"prefix",
"+",
"'static'",
",",
"panels",
"=",
"state",
"and",
"state",
".",
"panels",
"or",
"[",
"]",
",",
"global_panels",
"=",
"self",
".",
"global_panels",
",",
"request",
"=",
"state",
"and",
"state",
".",
"request",
"or",
"None",
",",
")",
"return",
"Response",
"(",
"text",
"=",
"response",
",",
"content_type",
"=",
"'text/html'",
")"
] |
Debug Toolbar.
|
[
"Debug",
"Toolbar",
"."
] |
b650b35fbe2035888f6bba5dac3073ef01c94dc6
|
https://github.com/klen/muffin-debugtoolbar/blob/b650b35fbe2035888f6bba5dac3073ef01c94dc6/muffin_debugtoolbar/plugin.py#L185-L203
|
247,168 |
qbicsoftware/mtb-parser-lib
|
mtbparser/snv_item.py
|
SNVItem._format_dict
|
def _format_dict(self, info_dict):
"""Replaces empty content with 'NA's"""
for key, value in info_dict.items():
if not value:
info_dict[key] = "NA"
return info_dict
|
python
|
def _format_dict(self, info_dict):
"""Replaces empty content with 'NA's"""
for key, value in info_dict.items():
if not value:
info_dict[key] = "NA"
return info_dict
|
[
"def",
"_format_dict",
"(",
"self",
",",
"info_dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"info_dict",
".",
"items",
"(",
")",
":",
"if",
"not",
"value",
":",
"info_dict",
"[",
"key",
"]",
"=",
"\"NA\"",
"return",
"info_dict"
] |
Replaces empty content with 'NA's
|
[
"Replaces",
"empty",
"content",
"with",
"NA",
"s"
] |
e8b96e34b27e457ea7def2927fe44017fa173ba7
|
https://github.com/qbicsoftware/mtb-parser-lib/blob/e8b96e34b27e457ea7def2927fe44017fa173ba7/mtbparser/snv_item.py#L6-L11
|
247,169 |
minhhoit/yacms
|
yacms/utils/email.py
|
split_addresses
|
def split_addresses(email_string_list):
"""
Converts a string containing comma separated email addresses
into a list of email addresses.
"""
return [f for f in [s.strip() for s in email_string_list.split(",")] if f]
|
python
|
def split_addresses(email_string_list):
"""
Converts a string containing comma separated email addresses
into a list of email addresses.
"""
return [f for f in [s.strip() for s in email_string_list.split(",")] if f]
|
[
"def",
"split_addresses",
"(",
"email_string_list",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"email_string_list",
".",
"split",
"(",
"\",\"",
")",
"]",
"if",
"f",
"]"
] |
Converts a string containing comma separated email addresses
into a list of email addresses.
|
[
"Converts",
"a",
"string",
"containing",
"comma",
"separated",
"email",
"addresses",
"into",
"a",
"list",
"of",
"email",
"addresses",
"."
] |
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
|
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L15-L20
|
247,170 |
minhhoit/yacms
|
yacms/utils/email.py
|
subject_template
|
def subject_template(template, context):
"""
Loads and renders an email subject template, returning the
subject string.
"""
subject = loader.get_template(template).render(Context(context))
return " ".join(subject.splitlines()).strip()
|
python
|
def subject_template(template, context):
"""
Loads and renders an email subject template, returning the
subject string.
"""
subject = loader.get_template(template).render(Context(context))
return " ".join(subject.splitlines()).strip()
|
[
"def",
"subject_template",
"(",
"template",
",",
"context",
")",
":",
"subject",
"=",
"loader",
".",
"get_template",
"(",
"template",
")",
".",
"render",
"(",
"Context",
"(",
"context",
")",
")",
"return",
"\" \"",
".",
"join",
"(",
"subject",
".",
"splitlines",
"(",
")",
")",
".",
"strip",
"(",
")"
] |
Loads and renders an email subject template, returning the
subject string.
|
[
"Loads",
"and",
"renders",
"an",
"email",
"subject",
"template",
"returning",
"the",
"subject",
"string",
"."
] |
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
|
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L23-L29
|
247,171 |
minhhoit/yacms
|
yacms/utils/email.py
|
send_verification_mail
|
def send_verification_mail(request, user, verification_type):
"""
Sends an email with a verification link to users when
``ACCOUNTS_VERIFICATION_REQUIRED`` is ```True`` and they're signing
up, or when they reset a lost password.
The ``verification_type`` arg is both the name of the urlpattern for
the verification link, as well as the names of the email templates
to use.
"""
verify_url = reverse(verification_type, kwargs={
"uidb36": int_to_base36(user.id),
"token": default_token_generator.make_token(user),
}) + "?next=" + (next_url(request) or "/")
context = {
"request": request,
"user": user,
"verify_url": verify_url,
}
subject_template_name = "email/%s_subject.txt" % verification_type
subject = subject_template(subject_template_name, context)
send_mail_template(subject, "email/%s" % verification_type,
settings.DEFAULT_FROM_EMAIL, user.email,
context=context)
|
python
|
def send_verification_mail(request, user, verification_type):
"""
Sends an email with a verification link to users when
``ACCOUNTS_VERIFICATION_REQUIRED`` is ```True`` and they're signing
up, or when they reset a lost password.
The ``verification_type`` arg is both the name of the urlpattern for
the verification link, as well as the names of the email templates
to use.
"""
verify_url = reverse(verification_type, kwargs={
"uidb36": int_to_base36(user.id),
"token": default_token_generator.make_token(user),
}) + "?next=" + (next_url(request) or "/")
context = {
"request": request,
"user": user,
"verify_url": verify_url,
}
subject_template_name = "email/%s_subject.txt" % verification_type
subject = subject_template(subject_template_name, context)
send_mail_template(subject, "email/%s" % verification_type,
settings.DEFAULT_FROM_EMAIL, user.email,
context=context)
|
[
"def",
"send_verification_mail",
"(",
"request",
",",
"user",
",",
"verification_type",
")",
":",
"verify_url",
"=",
"reverse",
"(",
"verification_type",
",",
"kwargs",
"=",
"{",
"\"uidb36\"",
":",
"int_to_base36",
"(",
"user",
".",
"id",
")",
",",
"\"token\"",
":",
"default_token_generator",
".",
"make_token",
"(",
"user",
")",
",",
"}",
")",
"+",
"\"?next=\"",
"+",
"(",
"next_url",
"(",
"request",
")",
"or",
"\"/\"",
")",
"context",
"=",
"{",
"\"request\"",
":",
"request",
",",
"\"user\"",
":",
"user",
",",
"\"verify_url\"",
":",
"verify_url",
",",
"}",
"subject_template_name",
"=",
"\"email/%s_subject.txt\"",
"%",
"verification_type",
"subject",
"=",
"subject_template",
"(",
"subject_template_name",
",",
"context",
")",
"send_mail_template",
"(",
"subject",
",",
"\"email/%s\"",
"%",
"verification_type",
",",
"settings",
".",
"DEFAULT_FROM_EMAIL",
",",
"user",
".",
"email",
",",
"context",
"=",
"context",
")"
] |
Sends an email with a verification link to users when
``ACCOUNTS_VERIFICATION_REQUIRED`` is ```True`` and they're signing
up, or when they reset a lost password.
The ``verification_type`` arg is both the name of the urlpattern for
the verification link, as well as the names of the email templates
to use.
|
[
"Sends",
"an",
"email",
"with",
"a",
"verification",
"link",
"to",
"users",
"when",
"ACCOUNTS_VERIFICATION_REQUIRED",
"is",
"True",
"and",
"they",
"re",
"signing",
"up",
"or",
"when",
"they",
"reset",
"a",
"lost",
"password",
".",
"The",
"verification_type",
"arg",
"is",
"both",
"the",
"name",
"of",
"the",
"urlpattern",
"for",
"the",
"verification",
"link",
"as",
"well",
"as",
"the",
"names",
"of",
"the",
"email",
"templates",
"to",
"use",
"."
] |
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
|
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L69-L91
|
247,172 |
minhhoit/yacms
|
yacms/utils/email.py
|
send_approve_mail
|
def send_approve_mail(request, user):
"""
Sends an email to staff in listed in the setting
``ACCOUNTS_APPROVAL_EMAILS``, when a new user signs up and the
``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``.
"""
approval_emails = split_addresses(settings.ACCOUNTS_APPROVAL_EMAILS)
if not approval_emails:
return
context = {
"request": request,
"user": user,
"change_url": admin_url(user.__class__, "change", user.id),
}
subject = subject_template("email/account_approve_subject.txt", context)
send_mail_template(subject, "email/account_approve",
settings.DEFAULT_FROM_EMAIL, approval_emails,
context=context)
|
python
|
def send_approve_mail(request, user):
"""
Sends an email to staff in listed in the setting
``ACCOUNTS_APPROVAL_EMAILS``, when a new user signs up and the
``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``.
"""
approval_emails = split_addresses(settings.ACCOUNTS_APPROVAL_EMAILS)
if not approval_emails:
return
context = {
"request": request,
"user": user,
"change_url": admin_url(user.__class__, "change", user.id),
}
subject = subject_template("email/account_approve_subject.txt", context)
send_mail_template(subject, "email/account_approve",
settings.DEFAULT_FROM_EMAIL, approval_emails,
context=context)
|
[
"def",
"send_approve_mail",
"(",
"request",
",",
"user",
")",
":",
"approval_emails",
"=",
"split_addresses",
"(",
"settings",
".",
"ACCOUNTS_APPROVAL_EMAILS",
")",
"if",
"not",
"approval_emails",
":",
"return",
"context",
"=",
"{",
"\"request\"",
":",
"request",
",",
"\"user\"",
":",
"user",
",",
"\"change_url\"",
":",
"admin_url",
"(",
"user",
".",
"__class__",
",",
"\"change\"",
",",
"user",
".",
"id",
")",
",",
"}",
"subject",
"=",
"subject_template",
"(",
"\"email/account_approve_subject.txt\"",
",",
"context",
")",
"send_mail_template",
"(",
"subject",
",",
"\"email/account_approve\"",
",",
"settings",
".",
"DEFAULT_FROM_EMAIL",
",",
"approval_emails",
",",
"context",
"=",
"context",
")"
] |
Sends an email to staff in listed in the setting
``ACCOUNTS_APPROVAL_EMAILS``, when a new user signs up and the
``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``.
|
[
"Sends",
"an",
"email",
"to",
"staff",
"in",
"listed",
"in",
"the",
"setting",
"ACCOUNTS_APPROVAL_EMAILS",
"when",
"a",
"new",
"user",
"signs",
"up",
"and",
"the",
"ACCOUNTS_APPROVAL_REQUIRED",
"setting",
"is",
"True",
"."
] |
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
|
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L94-L111
|
247,173 |
minhhoit/yacms
|
yacms/utils/email.py
|
send_approved_mail
|
def send_approved_mail(request, user):
"""
Sends an email to a user once their ``is_active`` status goes from
``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_REQUIRED``
setting is ``True``.
"""
context = {"request": request, "user": user}
subject = subject_template("email/account_approved_subject.txt", context)
send_mail_template(subject, "email/account_approved",
settings.DEFAULT_FROM_EMAIL, user.email,
context=context)
|
python
|
def send_approved_mail(request, user):
"""
Sends an email to a user once their ``is_active`` status goes from
``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_REQUIRED``
setting is ``True``.
"""
context = {"request": request, "user": user}
subject = subject_template("email/account_approved_subject.txt", context)
send_mail_template(subject, "email/account_approved",
settings.DEFAULT_FROM_EMAIL, user.email,
context=context)
|
[
"def",
"send_approved_mail",
"(",
"request",
",",
"user",
")",
":",
"context",
"=",
"{",
"\"request\"",
":",
"request",
",",
"\"user\"",
":",
"user",
"}",
"subject",
"=",
"subject_template",
"(",
"\"email/account_approved_subject.txt\"",
",",
"context",
")",
"send_mail_template",
"(",
"subject",
",",
"\"email/account_approved\"",
",",
"settings",
".",
"DEFAULT_FROM_EMAIL",
",",
"user",
".",
"email",
",",
"context",
"=",
"context",
")"
] |
Sends an email to a user once their ``is_active`` status goes from
``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_REQUIRED``
setting is ``True``.
|
[
"Sends",
"an",
"email",
"to",
"a",
"user",
"once",
"their",
"is_active",
"status",
"goes",
"from",
"False",
"to",
"True",
"when",
"the",
"ACCOUNTS_APPROVAL_REQUIRED",
"setting",
"is",
"True",
"."
] |
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
|
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/email.py#L114-L124
|
247,174 |
OpenGov/python_data_wrap
|
datawrap/external/xmlparse.py
|
Worksheet.GetColumnNumber
|
def GetColumnNumber (self, columnName):
"""returns the column number for a given column heading name, 0 if not found"""
for row in range(1, self.maxRow + 1):
for column in range(1, self.maxColumn + 1):
if self.GetCellValue(column, row, "") == columnName:
return column
return 0
|
python
|
def GetColumnNumber (self, columnName):
"""returns the column number for a given column heading name, 0 if not found"""
for row in range(1, self.maxRow + 1):
for column in range(1, self.maxColumn + 1):
if self.GetCellValue(column, row, "") == columnName:
return column
return 0
|
[
"def",
"GetColumnNumber",
"(",
"self",
",",
"columnName",
")",
":",
"for",
"row",
"in",
"range",
"(",
"1",
",",
"self",
".",
"maxRow",
"+",
"1",
")",
":",
"for",
"column",
"in",
"range",
"(",
"1",
",",
"self",
".",
"maxColumn",
"+",
"1",
")",
":",
"if",
"self",
".",
"GetCellValue",
"(",
"column",
",",
"row",
",",
"\"\"",
")",
"==",
"columnName",
":",
"return",
"column",
"return",
"0"
] |
returns the column number for a given column heading name, 0 if not found
|
[
"returns",
"the",
"column",
"number",
"for",
"a",
"given",
"column",
"heading",
"name",
"0",
"if",
"not",
"found"
] |
7de38bb30d7a500adc336a4a7999528d753e5600
|
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L341-L347
|
247,175 |
OpenGov/python_data_wrap
|
datawrap/external/xmlparse.py
|
Worksheet.DumpAsCSV
|
def DumpAsCSV (self, separator=",", file=sys.stdout):
"""dump as a comma separated value file"""
for row in range(1, self.maxRow + 1):
sep = ""
for column in range(1, self.maxColumn + 1):
file.write("%s\"%s\"" % (sep, self.GetCellValue(column, row, "")))
sep = separator
file.write("\n")
|
python
|
def DumpAsCSV (self, separator=",", file=sys.stdout):
"""dump as a comma separated value file"""
for row in range(1, self.maxRow + 1):
sep = ""
for column in range(1, self.maxColumn + 1):
file.write("%s\"%s\"" % (sep, self.GetCellValue(column, row, "")))
sep = separator
file.write("\n")
|
[
"def",
"DumpAsCSV",
"(",
"self",
",",
"separator",
"=",
"\",\"",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"row",
"in",
"range",
"(",
"1",
",",
"self",
".",
"maxRow",
"+",
"1",
")",
":",
"sep",
"=",
"\"\"",
"for",
"column",
"in",
"range",
"(",
"1",
",",
"self",
".",
"maxColumn",
"+",
"1",
")",
":",
"file",
".",
"write",
"(",
"\"%s\\\"%s\\\"\"",
"%",
"(",
"sep",
",",
"self",
".",
"GetCellValue",
"(",
"column",
",",
"row",
",",
"\"\"",
")",
")",
")",
"sep",
"=",
"separator",
"file",
".",
"write",
"(",
"\"\\n\"",
")"
] |
dump as a comma separated value file
|
[
"dump",
"as",
"a",
"comma",
"separated",
"value",
"file"
] |
7de38bb30d7a500adc336a4a7999528d753e5600
|
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L349-L356
|
247,176 |
OpenGov/python_data_wrap
|
datawrap/external/xmlparse.py
|
ExcelFile.GetWorksheet
|
def GetWorksheet(self, nameOrNumber):
"""get a sheet by number"""
if isinstance(nameOrNumber, int):
return self.worksheets[nameOrNumber]
else:
return self.worksheetsByName[nameOrNumber]
|
python
|
def GetWorksheet(self, nameOrNumber):
"""get a sheet by number"""
if isinstance(nameOrNumber, int):
return self.worksheets[nameOrNumber]
else:
return self.worksheetsByName[nameOrNumber]
|
[
"def",
"GetWorksheet",
"(",
"self",
",",
"nameOrNumber",
")",
":",
"if",
"isinstance",
"(",
"nameOrNumber",
",",
"int",
")",
":",
"return",
"self",
".",
"worksheets",
"[",
"nameOrNumber",
"]",
"else",
":",
"return",
"self",
".",
"worksheetsByName",
"[",
"nameOrNumber",
"]"
] |
get a sheet by number
|
[
"get",
"a",
"sheet",
"by",
"number"
] |
7de38bb30d7a500adc336a4a7999528d753e5600
|
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L399-L404
|
247,177 |
OpenGov/python_data_wrap
|
datawrap/external/xmlparse.py
|
ExcelToSparseArrayHandler.startElement
|
def startElement (self, name, attrs):
'''if there's a start method for this element, call it
'''
func = getattr(self, 'start_' + name, None)
if func:
func(attrs)
|
python
|
def startElement (self, name, attrs):
'''if there's a start method for this element, call it
'''
func = getattr(self, 'start_' + name, None)
if func:
func(attrs)
|
[
"def",
"startElement",
"(",
"self",
",",
"name",
",",
"attrs",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"'start_'",
"+",
"name",
",",
"None",
")",
"if",
"func",
":",
"func",
"(",
"attrs",
")"
] |
if there's a start method for this element, call it
|
[
"if",
"there",
"s",
"a",
"start",
"method",
"for",
"this",
"element",
"call",
"it"
] |
7de38bb30d7a500adc336a4a7999528d753e5600
|
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/external/xmlparse.py#L521-L526
|
247,178 |
heikomuller/sco-engine
|
scoengine/reqbuf_worker.py
|
handle_request
|
def handle_request(request):
"""Convert a model run request from the buffer into a message in a RabbitMQ
queue.
Parameters
----------
request : dict
Buffer entry containing 'connector' and 'request' field
"""
connector = request['connector']
hostname = connector['host']
port = connector['port']
virtual_host = connector['virtualHost']
queue = connector['queue']
user = connector['user']
password = connector['password']
# Establish connection with RabbitMQ server
logging.info('Connect : [HOST=' + hostname + ', QUEUE=' + queue + ']')
done = False
attempts = 0
while not done and attempts < 100:
try:
credentials = pika.PlainCredentials(user, password)
con = pika.BlockingConnection(pika.ConnectionParameters(
host=hostname,
port=port,
virtual_host=virtual_host,
credentials=credentials
))
channel = con.channel()
channel.queue_declare(queue=queue, durable=True)
req = request['request']
logging.info('Run : [EXPERIMENT=' + req['experiment_id'] + ', RUN=' + req['run_id'] + ']')
channel.basic_publish(
exchange='',
routing_key=queue,
body=json.dumps(req),
properties=pika.BasicProperties(
delivery_mode = 2, # make message persistent
)
)
con.close()
done = True
except pika.exceptions.ConnectionClosed as ex:
attempts += 1
logging.exception(ex)
|
python
|
def handle_request(request):
"""Convert a model run request from the buffer into a message in a RabbitMQ
queue.
Parameters
----------
request : dict
Buffer entry containing 'connector' and 'request' field
"""
connector = request['connector']
hostname = connector['host']
port = connector['port']
virtual_host = connector['virtualHost']
queue = connector['queue']
user = connector['user']
password = connector['password']
# Establish connection with RabbitMQ server
logging.info('Connect : [HOST=' + hostname + ', QUEUE=' + queue + ']')
done = False
attempts = 0
while not done and attempts < 100:
try:
credentials = pika.PlainCredentials(user, password)
con = pika.BlockingConnection(pika.ConnectionParameters(
host=hostname,
port=port,
virtual_host=virtual_host,
credentials=credentials
))
channel = con.channel()
channel.queue_declare(queue=queue, durable=True)
req = request['request']
logging.info('Run : [EXPERIMENT=' + req['experiment_id'] + ', RUN=' + req['run_id'] + ']')
channel.basic_publish(
exchange='',
routing_key=queue,
body=json.dumps(req),
properties=pika.BasicProperties(
delivery_mode = 2, # make message persistent
)
)
con.close()
done = True
except pika.exceptions.ConnectionClosed as ex:
attempts += 1
logging.exception(ex)
|
[
"def",
"handle_request",
"(",
"request",
")",
":",
"connector",
"=",
"request",
"[",
"'connector'",
"]",
"hostname",
"=",
"connector",
"[",
"'host'",
"]",
"port",
"=",
"connector",
"[",
"'port'",
"]",
"virtual_host",
"=",
"connector",
"[",
"'virtualHost'",
"]",
"queue",
"=",
"connector",
"[",
"'queue'",
"]",
"user",
"=",
"connector",
"[",
"'user'",
"]",
"password",
"=",
"connector",
"[",
"'password'",
"]",
"# Establish connection with RabbitMQ server",
"logging",
".",
"info",
"(",
"'Connect : [HOST='",
"+",
"hostname",
"+",
"', QUEUE='",
"+",
"queue",
"+",
"']'",
")",
"done",
"=",
"False",
"attempts",
"=",
"0",
"while",
"not",
"done",
"and",
"attempts",
"<",
"100",
":",
"try",
":",
"credentials",
"=",
"pika",
".",
"PlainCredentials",
"(",
"user",
",",
"password",
")",
"con",
"=",
"pika",
".",
"BlockingConnection",
"(",
"pika",
".",
"ConnectionParameters",
"(",
"host",
"=",
"hostname",
",",
"port",
"=",
"port",
",",
"virtual_host",
"=",
"virtual_host",
",",
"credentials",
"=",
"credentials",
")",
")",
"channel",
"=",
"con",
".",
"channel",
"(",
")",
"channel",
".",
"queue_declare",
"(",
"queue",
"=",
"queue",
",",
"durable",
"=",
"True",
")",
"req",
"=",
"request",
"[",
"'request'",
"]",
"logging",
".",
"info",
"(",
"'Run : [EXPERIMENT='",
"+",
"req",
"[",
"'experiment_id'",
"]",
"+",
"', RUN='",
"+",
"req",
"[",
"'run_id'",
"]",
"+",
"']'",
")",
"channel",
".",
"basic_publish",
"(",
"exchange",
"=",
"''",
",",
"routing_key",
"=",
"queue",
",",
"body",
"=",
"json",
".",
"dumps",
"(",
"req",
")",
",",
"properties",
"=",
"pika",
".",
"BasicProperties",
"(",
"delivery_mode",
"=",
"2",
",",
"# make message persistent",
")",
")",
"con",
".",
"close",
"(",
")",
"done",
"=",
"True",
"except",
"pika",
".",
"exceptions",
".",
"ConnectionClosed",
"as",
"ex",
":",
"attempts",
"+=",
"1",
"logging",
".",
"exception",
"(",
"ex",
")"
] |
Convert a model run request from the buffer into a message in a RabbitMQ
queue.
Parameters
----------
request : dict
Buffer entry containing 'connector' and 'request' field
|
[
"Convert",
"a",
"model",
"run",
"request",
"from",
"the",
"buffer",
"into",
"a",
"message",
"in",
"a",
"RabbitMQ",
"queue",
"."
] |
3e7782d059ec808d930f0992794b6f5a8fd73c2c
|
https://github.com/heikomuller/sco-engine/blob/3e7782d059ec808d930f0992794b6f5a8fd73c2c/scoengine/reqbuf_worker.py#L19-L64
|
247,179 |
spookey/photon
|
photon/util/locations.py
|
get_locations
|
def get_locations():
'''
Compiles default locations
:returns:
A dictionary with folders as values:
* 'home_dir': Your home-directory (:file:`~`)
* 'call_dir': Where you called the first Python script from. (``argv[0]``)
* 'conf_dir': The :envvar:`XDG_CONFIG_HOME`-directory + \
``photon`` (:file:`~/.config/photon`)
* 'data_dir': The :envvar:`XDG_DATA_HOME`-directory + \
``photon`` (:file:`~/.local/share/photon`)
.. note::
* Both :func:`search_location` and :func:`make_locations` \
have the argument `locations`.
* |param_locations_none|
'''
home_dir = _path.expanduser('~')
conf_dir = _path.join(
_environ.get(
'XDG_CONFIG_HOME',
_path.join(home_dir, '.config')
),
IDENT
)
data_dir = _path.join(
_environ.get(
'XDG_DATA_HOME',
_path.join(home_dir, '.local', 'share')
),
IDENT
)
return {
'home_dir': home_dir,
'call_dir': _path.dirname(_path.abspath(_argv[0])),
'conf_dir': conf_dir,
'data_dir': data_dir
}
|
python
|
def get_locations():
'''
Compiles default locations
:returns:
A dictionary with folders as values:
* 'home_dir': Your home-directory (:file:`~`)
* 'call_dir': Where you called the first Python script from. (``argv[0]``)
* 'conf_dir': The :envvar:`XDG_CONFIG_HOME`-directory + \
``photon`` (:file:`~/.config/photon`)
* 'data_dir': The :envvar:`XDG_DATA_HOME`-directory + \
``photon`` (:file:`~/.local/share/photon`)
.. note::
* Both :func:`search_location` and :func:`make_locations` \
have the argument `locations`.
* |param_locations_none|
'''
home_dir = _path.expanduser('~')
conf_dir = _path.join(
_environ.get(
'XDG_CONFIG_HOME',
_path.join(home_dir, '.config')
),
IDENT
)
data_dir = _path.join(
_environ.get(
'XDG_DATA_HOME',
_path.join(home_dir, '.local', 'share')
),
IDENT
)
return {
'home_dir': home_dir,
'call_dir': _path.dirname(_path.abspath(_argv[0])),
'conf_dir': conf_dir,
'data_dir': data_dir
}
|
[
"def",
"get_locations",
"(",
")",
":",
"home_dir",
"=",
"_path",
".",
"expanduser",
"(",
"'~'",
")",
"conf_dir",
"=",
"_path",
".",
"join",
"(",
"_environ",
".",
"get",
"(",
"'XDG_CONFIG_HOME'",
",",
"_path",
".",
"join",
"(",
"home_dir",
",",
"'.config'",
")",
")",
",",
"IDENT",
")",
"data_dir",
"=",
"_path",
".",
"join",
"(",
"_environ",
".",
"get",
"(",
"'XDG_DATA_HOME'",
",",
"_path",
".",
"join",
"(",
"home_dir",
",",
"'.local'",
",",
"'share'",
")",
")",
",",
"IDENT",
")",
"return",
"{",
"'home_dir'",
":",
"home_dir",
",",
"'call_dir'",
":",
"_path",
".",
"dirname",
"(",
"_path",
".",
"abspath",
"(",
"_argv",
"[",
"0",
"]",
")",
")",
",",
"'conf_dir'",
":",
"conf_dir",
",",
"'data_dir'",
":",
"data_dir",
"}"
] |
Compiles default locations
:returns:
A dictionary with folders as values:
* 'home_dir': Your home-directory (:file:`~`)
* 'call_dir': Where you called the first Python script from. (``argv[0]``)
* 'conf_dir': The :envvar:`XDG_CONFIG_HOME`-directory + \
``photon`` (:file:`~/.config/photon`)
* 'data_dir': The :envvar:`XDG_DATA_HOME`-directory + \
``photon`` (:file:`~/.local/share/photon`)
.. note::
* Both :func:`search_location` and :func:`make_locations` \
have the argument `locations`.
* |param_locations_none|
|
[
"Compiles",
"default",
"locations"
] |
57212a26ce713ab7723910ee49e3d0ba1697799f
|
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/locations.py#L24-L70
|
247,180 |
spookey/photon
|
photon/util/locations.py
|
backup_location
|
def backup_location(src, loc=None):
'''
Writes Backups of locations
:param src:
The source file/folder to backup
:param loc:
The target folder to backup into
The backup will be called `src` + :func:`util.system.get_timestamp`.
* If `loc` left to none, the backup gets written in the same \
folder like `src` resides in
* Otherwise the specified path will be used.
'''
from photon.util.system import get_timestamp
src = _path.realpath(src)
if not loc or not loc.startswith(_sep):
loc = _path.dirname(src)
pth = _path.join(_path.basename(src), _path.realpath(loc))
out = '%s_backup_%s' % (_path.basename(src), get_timestamp())
change_location(src, search_location(out, create_in=pth))
|
python
|
def backup_location(src, loc=None):
'''
Writes Backups of locations
:param src:
The source file/folder to backup
:param loc:
The target folder to backup into
The backup will be called `src` + :func:`util.system.get_timestamp`.
* If `loc` left to none, the backup gets written in the same \
folder like `src` resides in
* Otherwise the specified path will be used.
'''
from photon.util.system import get_timestamp
src = _path.realpath(src)
if not loc or not loc.startswith(_sep):
loc = _path.dirname(src)
pth = _path.join(_path.basename(src), _path.realpath(loc))
out = '%s_backup_%s' % (_path.basename(src), get_timestamp())
change_location(src, search_location(out, create_in=pth))
|
[
"def",
"backup_location",
"(",
"src",
",",
"loc",
"=",
"None",
")",
":",
"from",
"photon",
".",
"util",
".",
"system",
"import",
"get_timestamp",
"src",
"=",
"_path",
".",
"realpath",
"(",
"src",
")",
"if",
"not",
"loc",
"or",
"not",
"loc",
".",
"startswith",
"(",
"_sep",
")",
":",
"loc",
"=",
"_path",
".",
"dirname",
"(",
"src",
")",
"pth",
"=",
"_path",
".",
"join",
"(",
"_path",
".",
"basename",
"(",
"src",
")",
",",
"_path",
".",
"realpath",
"(",
"loc",
")",
")",
"out",
"=",
"'%s_backup_%s'",
"%",
"(",
"_path",
".",
"basename",
"(",
"src",
")",
",",
"get_timestamp",
"(",
")",
")",
"change_location",
"(",
"src",
",",
"search_location",
"(",
"out",
",",
"create_in",
"=",
"pth",
")",
")"
] |
Writes Backups of locations
:param src:
The source file/folder to backup
:param loc:
The target folder to backup into
The backup will be called `src` + :func:`util.system.get_timestamp`.
* If `loc` left to none, the backup gets written in the same \
folder like `src` resides in
* Otherwise the specified path will be used.
|
[
"Writes",
"Backups",
"of",
"locations"
] |
57212a26ce713ab7723910ee49e3d0ba1697799f
|
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/locations.py#L220-L245
|
247,181 |
nir0s/serv
|
serv/serv.py
|
status
|
def status(name, init_system, verbose):
"""WIP! Try at your own expense
"""
try:
status = Serv(init_system, verbose=verbose).status(name)
except ServError as ex:
sys.exit(ex)
click.echo(json.dumps(status, indent=4, sort_keys=True))
|
python
|
def status(name, init_system, verbose):
"""WIP! Try at your own expense
"""
try:
status = Serv(init_system, verbose=verbose).status(name)
except ServError as ex:
sys.exit(ex)
click.echo(json.dumps(status, indent=4, sort_keys=True))
|
[
"def",
"status",
"(",
"name",
",",
"init_system",
",",
"verbose",
")",
":",
"try",
":",
"status",
"=",
"Serv",
"(",
"init_system",
",",
"verbose",
"=",
"verbose",
")",
".",
"status",
"(",
"name",
")",
"except",
"ServError",
"as",
"ex",
":",
"sys",
".",
"exit",
"(",
"ex",
")",
"click",
".",
"echo",
"(",
"json",
".",
"dumps",
"(",
"status",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
")"
] |
WIP! Try at your own expense
|
[
"WIP!",
"Try",
"at",
"your",
"own",
"expense"
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L432-L439
|
247,182 |
nir0s/serv
|
serv/serv.py
|
Serv._parse_service_env_vars
|
def _parse_service_env_vars(self, env_vars):
"""Return a dict based on `key=value` pair strings.
"""
env = {}
for var in env_vars:
# Yeah yeah.. it's less performant.. splitting twice.. who cares.
k, v = var.split('=')
env.update({k: v})
return env
|
python
|
def _parse_service_env_vars(self, env_vars):
"""Return a dict based on `key=value` pair strings.
"""
env = {}
for var in env_vars:
# Yeah yeah.. it's less performant.. splitting twice.. who cares.
k, v = var.split('=')
env.update({k: v})
return env
|
[
"def",
"_parse_service_env_vars",
"(",
"self",
",",
"env_vars",
")",
":",
"env",
"=",
"{",
"}",
"for",
"var",
"in",
"env_vars",
":",
"# Yeah yeah.. it's less performant.. splitting twice.. who cares.",
"k",
",",
"v",
"=",
"var",
".",
"split",
"(",
"'='",
")",
"env",
".",
"update",
"(",
"{",
"k",
":",
"v",
"}",
")",
"return",
"env"
] |
Return a dict based on `key=value` pair strings.
|
[
"Return",
"a",
"dict",
"based",
"on",
"key",
"=",
"value",
"pair",
"strings",
"."
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L71-L79
|
247,183 |
nir0s/serv
|
serv/serv.py
|
Serv._set_service_name_from_command
|
def _set_service_name_from_command(self, cmd):
"""Set the name of a service according to the command.
This is only relevant if the name wasn't explicitly provided.
Note that this is risky as it sets the name according to the
name of the file the command is using. If two services
use the same binary, even if their args are different, they
will be named the same.
"""
# TODO: Consider assign incremental integers to the name if a service
# with the same name already exists.
name = os.path.basename(cmd)
logger.info(
'Service name not supplied. Assigning name according to '
'executable: %s', name)
return name
|
python
|
def _set_service_name_from_command(self, cmd):
"""Set the name of a service according to the command.
This is only relevant if the name wasn't explicitly provided.
Note that this is risky as it sets the name according to the
name of the file the command is using. If two services
use the same binary, even if their args are different, they
will be named the same.
"""
# TODO: Consider assign incremental integers to the name if a service
# with the same name already exists.
name = os.path.basename(cmd)
logger.info(
'Service name not supplied. Assigning name according to '
'executable: %s', name)
return name
|
[
"def",
"_set_service_name_from_command",
"(",
"self",
",",
"cmd",
")",
":",
"# TODO: Consider assign incremental integers to the name if a service",
"# with the same name already exists.",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"cmd",
")",
"logger",
".",
"info",
"(",
"'Service name not supplied. Assigning name according to '",
"'executable: %s'",
",",
"name",
")",
"return",
"name"
] |
Set the name of a service according to the command.
This is only relevant if the name wasn't explicitly provided.
Note that this is risky as it sets the name according to the
name of the file the command is using. If two services
use the same binary, even if their args are different, they
will be named the same.
|
[
"Set",
"the",
"name",
"of",
"a",
"service",
"according",
"to",
"the",
"command",
"."
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L81-L96
|
247,184 |
nir0s/serv
|
serv/serv.py
|
Serv.generate
|
def generate(self,
cmd,
name='',
overwrite=False,
deploy=False,
start=False,
**params):
"""Generate service files and returns a list of the generated files.
It will generate configuration file(s) for the service and
deploy them to the tmp dir on your os.
If `deploy` is True, the service will be configured to run on the
current machine.
If `start` is True, the service will be started as well.
"""
# TODO: parsing env vars and setting the name should probably be under
# `base.py`.
name = name or self._set_service_name_from_command(cmd)
self.params.update(**params)
self.params.update(dict(
cmd=cmd,
name=name,
env=self._parse_service_env_vars(params.get('var', '')))
)
if 'var' in params:
self.params.pop('var')
init = self.implementation(logger=logger, **self.params)
logger.info(
'Generating %s files for service %s...',
self.init_system, name)
files = init.generate(overwrite=overwrite)
for f in files:
logger.info('Generated %s', f)
if deploy or start:
init.validate_platform()
logger.info('Deploying %s service %s...', self.init_system, name)
init.install()
if start:
logger.info(
'Starting %s service %s...',
self.init_system, name)
init.start()
logger.info('Service created')
return files
|
python
|
def generate(self,
cmd,
name='',
overwrite=False,
deploy=False,
start=False,
**params):
"""Generate service files and returns a list of the generated files.
It will generate configuration file(s) for the service and
deploy them to the tmp dir on your os.
If `deploy` is True, the service will be configured to run on the
current machine.
If `start` is True, the service will be started as well.
"""
# TODO: parsing env vars and setting the name should probably be under
# `base.py`.
name = name or self._set_service_name_from_command(cmd)
self.params.update(**params)
self.params.update(dict(
cmd=cmd,
name=name,
env=self._parse_service_env_vars(params.get('var', '')))
)
if 'var' in params:
self.params.pop('var')
init = self.implementation(logger=logger, **self.params)
logger.info(
'Generating %s files for service %s...',
self.init_system, name)
files = init.generate(overwrite=overwrite)
for f in files:
logger.info('Generated %s', f)
if deploy or start:
init.validate_platform()
logger.info('Deploying %s service %s...', self.init_system, name)
init.install()
if start:
logger.info(
'Starting %s service %s...',
self.init_system, name)
init.start()
logger.info('Service created')
return files
|
[
"def",
"generate",
"(",
"self",
",",
"cmd",
",",
"name",
"=",
"''",
",",
"overwrite",
"=",
"False",
",",
"deploy",
"=",
"False",
",",
"start",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"# TODO: parsing env vars and setting the name should probably be under",
"# `base.py`.",
"name",
"=",
"name",
"or",
"self",
".",
"_set_service_name_from_command",
"(",
"cmd",
")",
"self",
".",
"params",
".",
"update",
"(",
"*",
"*",
"params",
")",
"self",
".",
"params",
".",
"update",
"(",
"dict",
"(",
"cmd",
"=",
"cmd",
",",
"name",
"=",
"name",
",",
"env",
"=",
"self",
".",
"_parse_service_env_vars",
"(",
"params",
".",
"get",
"(",
"'var'",
",",
"''",
")",
")",
")",
")",
"if",
"'var'",
"in",
"params",
":",
"self",
".",
"params",
".",
"pop",
"(",
"'var'",
")",
"init",
"=",
"self",
".",
"implementation",
"(",
"logger",
"=",
"logger",
",",
"*",
"*",
"self",
".",
"params",
")",
"logger",
".",
"info",
"(",
"'Generating %s files for service %s...'",
",",
"self",
".",
"init_system",
",",
"name",
")",
"files",
"=",
"init",
".",
"generate",
"(",
"overwrite",
"=",
"overwrite",
")",
"for",
"f",
"in",
"files",
":",
"logger",
".",
"info",
"(",
"'Generated %s'",
",",
"f",
")",
"if",
"deploy",
"or",
"start",
":",
"init",
".",
"validate_platform",
"(",
")",
"logger",
".",
"info",
"(",
"'Deploying %s service %s...'",
",",
"self",
".",
"init_system",
",",
"name",
")",
"init",
".",
"install",
"(",
")",
"if",
"start",
":",
"logger",
".",
"info",
"(",
"'Starting %s service %s...'",
",",
"self",
".",
"init_system",
",",
"name",
")",
"init",
".",
"start",
"(",
")",
"logger",
".",
"info",
"(",
"'Service created'",
")",
"return",
"files"
] |
Generate service files and returns a list of the generated files.
It will generate configuration file(s) for the service and
deploy them to the tmp dir on your os.
If `deploy` is True, the service will be configured to run on the
current machine.
If `start` is True, the service will be started as well.
|
[
"Generate",
"service",
"files",
"and",
"returns",
"a",
"list",
"of",
"the",
"generated",
"files",
"."
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L98-L145
|
247,185 |
nir0s/serv
|
serv/serv.py
|
Serv.remove
|
def remove(self, name):
"""Remove a service completely.
It will try to stop the service and then uninstall it.
The implementation is, of course, system specific.
For instance, for upstart, it will `stop <name` and then
delete /etc/init/<name>.conf.
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Removing %s service %s...', self.init_system, name)
init.stop()
init.uninstall()
logger.info('Service removed')
|
python
|
def remove(self, name):
"""Remove a service completely.
It will try to stop the service and then uninstall it.
The implementation is, of course, system specific.
For instance, for upstart, it will `stop <name` and then
delete /etc/init/<name>.conf.
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Removing %s service %s...', self.init_system, name)
init.stop()
init.uninstall()
logger.info('Service removed')
|
[
"def",
"remove",
"(",
"self",
",",
"name",
")",
":",
"init",
"=",
"self",
".",
"_get_implementation",
"(",
"name",
")",
"self",
".",
"_assert_service_installed",
"(",
"init",
",",
"name",
")",
"logger",
".",
"info",
"(",
"'Removing %s service %s...'",
",",
"self",
".",
"init_system",
",",
"name",
")",
"init",
".",
"stop",
"(",
")",
"init",
".",
"uninstall",
"(",
")",
"logger",
".",
"info",
"(",
"'Service removed'",
")"
] |
Remove a service completely.
It will try to stop the service and then uninstall it.
The implementation is, of course, system specific.
For instance, for upstart, it will `stop <name` and then
delete /etc/init/<name>.conf.
|
[
"Remove",
"a",
"service",
"completely",
"."
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L147-L160
|
247,186 |
nir0s/serv
|
serv/serv.py
|
Serv.status
|
def status(self, name=''):
"""Return a list containing a single service's info if `name`
is supplied, else returns a list of all services' info.
"""
logger.warn(
'Note that `status` is currently not so robust and may break on '
'different systems')
init = self._get_implementation(name)
if name:
self._assert_service_installed(init, name)
logger.info('Retrieving status...')
return init.status(name)
|
python
|
def status(self, name=''):
"""Return a list containing a single service's info if `name`
is supplied, else returns a list of all services' info.
"""
logger.warn(
'Note that `status` is currently not so robust and may break on '
'different systems')
init = self._get_implementation(name)
if name:
self._assert_service_installed(init, name)
logger.info('Retrieving status...')
return init.status(name)
|
[
"def",
"status",
"(",
"self",
",",
"name",
"=",
"''",
")",
":",
"logger",
".",
"warn",
"(",
"'Note that `status` is currently not so robust and may break on '",
"'different systems'",
")",
"init",
"=",
"self",
".",
"_get_implementation",
"(",
"name",
")",
"if",
"name",
":",
"self",
".",
"_assert_service_installed",
"(",
"init",
",",
"name",
")",
"logger",
".",
"info",
"(",
"'Retrieving status...'",
")",
"return",
"init",
".",
"status",
"(",
"name",
")"
] |
Return a list containing a single service's info if `name`
is supplied, else returns a list of all services' info.
|
[
"Return",
"a",
"list",
"containing",
"a",
"single",
"service",
"s",
"info",
"if",
"name",
"is",
"supplied",
"else",
"returns",
"a",
"list",
"of",
"all",
"services",
"info",
"."
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L162-L173
|
247,187 |
nir0s/serv
|
serv/serv.py
|
Serv.stop
|
def stop(self, name):
"""Stop a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Stopping service: %s...', name)
init.stop()
|
python
|
def stop(self, name):
"""Stop a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Stopping service: %s...', name)
init.stop()
|
[
"def",
"stop",
"(",
"self",
",",
"name",
")",
":",
"init",
"=",
"self",
".",
"_get_implementation",
"(",
"name",
")",
"self",
".",
"_assert_service_installed",
"(",
"init",
",",
"name",
")",
"logger",
".",
"info",
"(",
"'Stopping service: %s...'",
",",
"name",
")",
"init",
".",
"stop",
"(",
")"
] |
Stop a service
|
[
"Stop",
"a",
"service"
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L175-L181
|
247,188 |
nir0s/serv
|
serv/serv.py
|
Serv.restart
|
def restart(self, name):
"""Restart a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Restarting service: %s...', name)
init.stop()
# Here we would use status to verify that the service stopped
# before restarting. If only status was stable. eh..
# The arbitrarity of this sleep time is making me sick...
time.sleep(3)
init.start()
|
python
|
def restart(self, name):
"""Restart a service
"""
init = self._get_implementation(name)
self._assert_service_installed(init, name)
logger.info('Restarting service: %s...', name)
init.stop()
# Here we would use status to verify that the service stopped
# before restarting. If only status was stable. eh..
# The arbitrarity of this sleep time is making me sick...
time.sleep(3)
init.start()
|
[
"def",
"restart",
"(",
"self",
",",
"name",
")",
":",
"init",
"=",
"self",
".",
"_get_implementation",
"(",
"name",
")",
"self",
".",
"_assert_service_installed",
"(",
"init",
",",
"name",
")",
"logger",
".",
"info",
"(",
"'Restarting service: %s...'",
",",
"name",
")",
"init",
".",
"stop",
"(",
")",
"# Here we would use status to verify that the service stopped",
"# before restarting. If only status was stable. eh..",
"# The arbitrarity of this sleep time is making me sick...",
"time",
".",
"sleep",
"(",
"3",
")",
"init",
".",
"start",
"(",
")"
] |
Restart a service
|
[
"Restart",
"a",
"service"
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L191-L202
|
247,189 |
nir0s/serv
|
serv/serv.py
|
Serv.lookup_init_systems
|
def lookup_init_systems(self):
"""Return the relevant init system and its version.
This will try to look at the mapping first. If the mapping
doesn't exist, it will try to identify it automatically.
Windows lookup is not supported and `nssm` is assumed.
"""
if utils.IS_WIN:
logger.debug(
'Lookup is not supported on Windows. Assuming nssm...')
return ['nssm']
if utils.IS_DARWIN:
logger.debug(
'Lookup is not supported on OS X, Assuming launchd...')
return ['launchd']
logger.debug('Looking up init method...')
return self._lookup_by_mapping() \
or self._init_sys_auto_lookup()
|
python
|
def lookup_init_systems(self):
"""Return the relevant init system and its version.
This will try to look at the mapping first. If the mapping
doesn't exist, it will try to identify it automatically.
Windows lookup is not supported and `nssm` is assumed.
"""
if utils.IS_WIN:
logger.debug(
'Lookup is not supported on Windows. Assuming nssm...')
return ['nssm']
if utils.IS_DARWIN:
logger.debug(
'Lookup is not supported on OS X, Assuming launchd...')
return ['launchd']
logger.debug('Looking up init method...')
return self._lookup_by_mapping() \
or self._init_sys_auto_lookup()
|
[
"def",
"lookup_init_systems",
"(",
"self",
")",
":",
"if",
"utils",
".",
"IS_WIN",
":",
"logger",
".",
"debug",
"(",
"'Lookup is not supported on Windows. Assuming nssm...'",
")",
"return",
"[",
"'nssm'",
"]",
"if",
"utils",
".",
"IS_DARWIN",
":",
"logger",
".",
"debug",
"(",
"'Lookup is not supported on OS X, Assuming launchd...'",
")",
"return",
"[",
"'launchd'",
"]",
"logger",
".",
"debug",
"(",
"'Looking up init method...'",
")",
"return",
"self",
".",
"_lookup_by_mapping",
"(",
")",
"or",
"self",
".",
"_init_sys_auto_lookup",
"(",
")"
] |
Return the relevant init system and its version.
This will try to look at the mapping first. If the mapping
doesn't exist, it will try to identify it automatically.
Windows lookup is not supported and `nssm` is assumed.
|
[
"Return",
"the",
"relevant",
"init",
"system",
"and",
"its",
"version",
"."
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L214-L233
|
247,190 |
nir0s/serv
|
serv/serv.py
|
Serv._init_sys_auto_lookup
|
def _init_sys_auto_lookup(self):
"""Return a list of tuples of available init systems on the
current machine.
Note that in some situations (Ubuntu 14.04 for instance) more than
one init system can be found.
"""
# TODO: Instead, check for executables for systemd and upstart
# systemctl for systemd and initctl for upstart.
# An alternative might be to check the second answer here:
# http://unix.stackexchange.com/questions/196166/how-to-find-out-if-a-system-uses-sysv-upstart-or-systemd-initsystem
# TODO: Move to each system's implementation
init_systems = []
if self._is_init_system_installed('/usr/lib/systemd'):
init_systems.append('systemd')
if self._is_init_system_installed('/usr/share/upstart'):
init_systems.append('upstart')
if self._is_init_system_installed('/etc/init.d'):
init_systems.append('sysv')
return init_systems
|
python
|
def _init_sys_auto_lookup(self):
"""Return a list of tuples of available init systems on the
current machine.
Note that in some situations (Ubuntu 14.04 for instance) more than
one init system can be found.
"""
# TODO: Instead, check for executables for systemd and upstart
# systemctl for systemd and initctl for upstart.
# An alternative might be to check the second answer here:
# http://unix.stackexchange.com/questions/196166/how-to-find-out-if-a-system-uses-sysv-upstart-or-systemd-initsystem
# TODO: Move to each system's implementation
init_systems = []
if self._is_init_system_installed('/usr/lib/systemd'):
init_systems.append('systemd')
if self._is_init_system_installed('/usr/share/upstart'):
init_systems.append('upstart')
if self._is_init_system_installed('/etc/init.d'):
init_systems.append('sysv')
return init_systems
|
[
"def",
"_init_sys_auto_lookup",
"(",
"self",
")",
":",
"# TODO: Instead, check for executables for systemd and upstart",
"# systemctl for systemd and initctl for upstart.",
"# An alternative might be to check the second answer here:",
"# http://unix.stackexchange.com/questions/196166/how-to-find-out-if-a-system-uses-sysv-upstart-or-systemd-initsystem",
"# TODO: Move to each system's implementation",
"init_systems",
"=",
"[",
"]",
"if",
"self",
".",
"_is_init_system_installed",
"(",
"'/usr/lib/systemd'",
")",
":",
"init_systems",
".",
"append",
"(",
"'systemd'",
")",
"if",
"self",
".",
"_is_init_system_installed",
"(",
"'/usr/share/upstart'",
")",
":",
"init_systems",
".",
"append",
"(",
"'upstart'",
")",
"if",
"self",
".",
"_is_init_system_installed",
"(",
"'/etc/init.d'",
")",
":",
"init_systems",
".",
"append",
"(",
"'sysv'",
")",
"return",
"init_systems"
] |
Return a list of tuples of available init systems on the
current machine.
Note that in some situations (Ubuntu 14.04 for instance) more than
one init system can be found.
|
[
"Return",
"a",
"list",
"of",
"tuples",
"of",
"available",
"init",
"systems",
"on",
"the",
"current",
"machine",
"."
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L238-L257
|
247,191 |
nir0s/serv
|
serv/serv.py
|
Serv._lookup_by_mapping
|
def _lookup_by_mapping():
"""Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux's version will most probably be "rolling" at
any given time, which means that the init system cannot be idenfied
by the version of the distro.
On top of trying to identify by the distro's ID, if /etc/os-release
contains an "ID_LIKE" field, it will be tried. That, again is true
for Arch where the distro's ID changes (Manjaro, Antergos, etc...)
But the "ID_LIKE" field is always (?) `arch`.
"""
like = distro.like().lower()
distribution_id = distro.id().lower()
version = distro.major_version()
if 'arch' in (distribution_id, like):
version = 'any'
init_sys = constants.DIST_TO_INITSYS.get(
distribution_id, constants.DIST_TO_INITSYS.get(like))
if init_sys:
system = init_sys.get(version)
return [system] if system else []
|
python
|
def _lookup_by_mapping():
"""Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux's version will most probably be "rolling" at
any given time, which means that the init system cannot be idenfied
by the version of the distro.
On top of trying to identify by the distro's ID, if /etc/os-release
contains an "ID_LIKE" field, it will be tried. That, again is true
for Arch where the distro's ID changes (Manjaro, Antergos, etc...)
But the "ID_LIKE" field is always (?) `arch`.
"""
like = distro.like().lower()
distribution_id = distro.id().lower()
version = distro.major_version()
if 'arch' in (distribution_id, like):
version = 'any'
init_sys = constants.DIST_TO_INITSYS.get(
distribution_id, constants.DIST_TO_INITSYS.get(like))
if init_sys:
system = init_sys.get(version)
return [system] if system else []
|
[
"def",
"_lookup_by_mapping",
"(",
")",
":",
"like",
"=",
"distro",
".",
"like",
"(",
")",
".",
"lower",
"(",
")",
"distribution_id",
"=",
"distro",
".",
"id",
"(",
")",
".",
"lower",
"(",
")",
"version",
"=",
"distro",
".",
"major_version",
"(",
")",
"if",
"'arch'",
"in",
"(",
"distribution_id",
",",
"like",
")",
":",
"version",
"=",
"'any'",
"init_sys",
"=",
"constants",
".",
"DIST_TO_INITSYS",
".",
"get",
"(",
"distribution_id",
",",
"constants",
".",
"DIST_TO_INITSYS",
".",
"get",
"(",
"like",
")",
")",
"if",
"init_sys",
":",
"system",
"=",
"init_sys",
".",
"get",
"(",
"version",
")",
"return",
"[",
"system",
"]",
"if",
"system",
"else",
"[",
"]"
] |
Return a the init system based on a constant mapping of
distribution+version to init system..
See constants.py for the mapping.
A failover of the version is proposed for when no version is supplied.
For instance, Arch Linux's version will most probably be "rolling" at
any given time, which means that the init system cannot be idenfied
by the version of the distro.
On top of trying to identify by the distro's ID, if /etc/os-release
contains an "ID_LIKE" field, it will be tried. That, again is true
for Arch where the distro's ID changes (Manjaro, Antergos, etc...)
But the "ID_LIKE" field is always (?) `arch`.
|
[
"Return",
"a",
"the",
"init",
"system",
"based",
"on",
"a",
"constant",
"mapping",
"of",
"distribution",
"+",
"version",
"to",
"init",
"system",
".."
] |
7af724ed49c0eb766c37c4b5287b043a8cf99e9c
|
https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/serv.py#L260-L284
|
247,192 |
doptio/heywood
|
src/heywood/watchdog.py
|
all_files
|
def all_files(file_or_directory):
'return all files under file_or_directory.'
if os.path.isdir(file_or_directory):
return [os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(file_or_directory)
for filename in filenames]
else:
return [file_or_directory]
|
python
|
def all_files(file_or_directory):
'return all files under file_or_directory.'
if os.path.isdir(file_or_directory):
return [os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(file_or_directory)
for filename in filenames]
else:
return [file_or_directory]
|
[
"def",
"all_files",
"(",
"file_or_directory",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"file_or_directory",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"filename",
")",
"for",
"dirname",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"file_or_directory",
")",
"for",
"filename",
"in",
"filenames",
"]",
"else",
":",
"return",
"[",
"file_or_directory",
"]"
] |
return all files under file_or_directory.
|
[
"return",
"all",
"files",
"under",
"file_or_directory",
"."
] |
40c2b1f28d43524a16b390fd3a4f6832f16fec41
|
https://github.com/doptio/heywood/blob/40c2b1f28d43524a16b390fd3a4f6832f16fec41/src/heywood/watchdog.py#L41-L48
|
247,193 |
knagra/farnsworth
|
base/views.py
|
add_context
|
def add_context(request):
""" Add variables to all dictionaries passed to templates. """
# Whether the user has president privileges
try:
PRESIDENT = Manager.objects.filter(
incumbent__user=request.user,
president=True,
).count() > 0
except TypeError:
PRESIDENT = False
# If the user is logged in as an anymous user
if request.user.username == ANONYMOUS_USERNAME:
request.session["ANONYMOUS_SESSION"] = True
ANONYMOUS_SESSION = request.session.get("ANONYMOUS_SESSION", False)
# A list with items of form (RequestType, number_of_open_requests)
request_types = list()
if request.user.is_authenticated():
for request_type in RequestType.objects.filter(enabled=True):
requests = Request.objects.filter(
request_type=request_type,
status=Request.OPEN,
)
if not request_type.managers.filter(incumbent__user=request.user):
requests = requests.exclude(
~Q(owner__user=request.user),
private=True,
)
request_types.append((request_type, requests.count()))
profile_requests_count = ProfileRequest.objects.all().count()
admin_unread_count = profile_requests_count
return {
"REQUEST_TYPES": request_types,
"HOUSE": settings.HOUSE_NAME,
"ANONYMOUS_USERNAME": ANONYMOUS_USERNAME,
"SHORT_HOUSE": settings.SHORT_HOUSE_NAME,
"ADMIN": settings.ADMINS[0],
"NUM_OF_PROFILE_REQUESTS": profile_requests_count,
"ADMIN_UNREAD_COUNT": admin_unread_count,
"ANONYMOUS_SESSION": ANONYMOUS_SESSION,
"PRESIDENT": PRESIDENT,
}
|
python
|
def add_context(request):
""" Add variables to all dictionaries passed to templates. """
# Whether the user has president privileges
try:
PRESIDENT = Manager.objects.filter(
incumbent__user=request.user,
president=True,
).count() > 0
except TypeError:
PRESIDENT = False
# If the user is logged in as an anymous user
if request.user.username == ANONYMOUS_USERNAME:
request.session["ANONYMOUS_SESSION"] = True
ANONYMOUS_SESSION = request.session.get("ANONYMOUS_SESSION", False)
# A list with items of form (RequestType, number_of_open_requests)
request_types = list()
if request.user.is_authenticated():
for request_type in RequestType.objects.filter(enabled=True):
requests = Request.objects.filter(
request_type=request_type,
status=Request.OPEN,
)
if not request_type.managers.filter(incumbent__user=request.user):
requests = requests.exclude(
~Q(owner__user=request.user),
private=True,
)
request_types.append((request_type, requests.count()))
profile_requests_count = ProfileRequest.objects.all().count()
admin_unread_count = profile_requests_count
return {
"REQUEST_TYPES": request_types,
"HOUSE": settings.HOUSE_NAME,
"ANONYMOUS_USERNAME": ANONYMOUS_USERNAME,
"SHORT_HOUSE": settings.SHORT_HOUSE_NAME,
"ADMIN": settings.ADMINS[0],
"NUM_OF_PROFILE_REQUESTS": profile_requests_count,
"ADMIN_UNREAD_COUNT": admin_unread_count,
"ANONYMOUS_SESSION": ANONYMOUS_SESSION,
"PRESIDENT": PRESIDENT,
}
|
[
"def",
"add_context",
"(",
"request",
")",
":",
"# Whether the user has president privileges",
"try",
":",
"PRESIDENT",
"=",
"Manager",
".",
"objects",
".",
"filter",
"(",
"incumbent__user",
"=",
"request",
".",
"user",
",",
"president",
"=",
"True",
",",
")",
".",
"count",
"(",
")",
">",
"0",
"except",
"TypeError",
":",
"PRESIDENT",
"=",
"False",
"# If the user is logged in as an anymous user",
"if",
"request",
".",
"user",
".",
"username",
"==",
"ANONYMOUS_USERNAME",
":",
"request",
".",
"session",
"[",
"\"ANONYMOUS_SESSION\"",
"]",
"=",
"True",
"ANONYMOUS_SESSION",
"=",
"request",
".",
"session",
".",
"get",
"(",
"\"ANONYMOUS_SESSION\"",
",",
"False",
")",
"# A list with items of form (RequestType, number_of_open_requests)",
"request_types",
"=",
"list",
"(",
")",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"for",
"request_type",
"in",
"RequestType",
".",
"objects",
".",
"filter",
"(",
"enabled",
"=",
"True",
")",
":",
"requests",
"=",
"Request",
".",
"objects",
".",
"filter",
"(",
"request_type",
"=",
"request_type",
",",
"status",
"=",
"Request",
".",
"OPEN",
",",
")",
"if",
"not",
"request_type",
".",
"managers",
".",
"filter",
"(",
"incumbent__user",
"=",
"request",
".",
"user",
")",
":",
"requests",
"=",
"requests",
".",
"exclude",
"(",
"~",
"Q",
"(",
"owner__user",
"=",
"request",
".",
"user",
")",
",",
"private",
"=",
"True",
",",
")",
"request_types",
".",
"append",
"(",
"(",
"request_type",
",",
"requests",
".",
"count",
"(",
")",
")",
")",
"profile_requests_count",
"=",
"ProfileRequest",
".",
"objects",
".",
"all",
"(",
")",
".",
"count",
"(",
")",
"admin_unread_count",
"=",
"profile_requests_count",
"return",
"{",
"\"REQUEST_TYPES\"",
":",
"request_types",
",",
"\"HOUSE\"",
":",
"settings",
".",
"HOUSE_NAME",
",",
"\"ANONYMOUS_USERNAME\"",
":",
"ANONYMOUS_USERNAME",
",",
"\"SHORT_HOUSE\"",
":",
"settings",
".",
"SHORT_HOUSE_NAME",
",",
"\"ADMIN\"",
":",
"settings",
".",
"ADMINS",
"[",
"0",
"]",
",",
"\"NUM_OF_PROFILE_REQUESTS\"",
":",
"profile_requests_count",
",",
"\"ADMIN_UNREAD_COUNT\"",
":",
"admin_unread_count",
",",
"\"ANONYMOUS_SESSION\"",
":",
"ANONYMOUS_SESSION",
",",
"\"PRESIDENT\"",
":",
"PRESIDENT",
",",
"}"
] |
Add variables to all dictionaries passed to templates.
|
[
"Add",
"variables",
"to",
"all",
"dictionaries",
"passed",
"to",
"templates",
"."
] |
1b6589f0d9fea154f0a1e2231ed906764ed26d26
|
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L54-L99
|
247,194 |
knagra/farnsworth
|
base/views.py
|
landing_view
|
def landing_view(request):
''' The external landing.'''
revision = None
can_edit = False
edit_url = None
if "farnswiki" in settings.INSTALLED_APPS:
from wiki.models import Page
from wiki.hooks import hookset
binder = settings.WIKI_BINDERS[0]
wiki = binder.lookup()
try:
if wiki:
page = wiki.pages.get(slug="landing")
else:
page = Page.objects.get(slug="landing")
except (Page.DoesNotExist, Page.MultipleObjectsReturned):
can_edit = hookset.can_create_page(wiki, request.user, slug="landing")
edit_url = binder.page_url(wiki, "landing")
else:
revision = page.revisions.latest()
can_edit = hookset.can_edit_page(page, request.user)
edit_url = page.get_edit_url()
return render_to_response('external.html', {
"page_name": "Landing",
"revision": revision,
"can_edit": can_edit,
"edit_url": edit_url,
}, context_instance=RequestContext(request))
|
python
|
def landing_view(request):
''' The external landing.'''
revision = None
can_edit = False
edit_url = None
if "farnswiki" in settings.INSTALLED_APPS:
from wiki.models import Page
from wiki.hooks import hookset
binder = settings.WIKI_BINDERS[0]
wiki = binder.lookup()
try:
if wiki:
page = wiki.pages.get(slug="landing")
else:
page = Page.objects.get(slug="landing")
except (Page.DoesNotExist, Page.MultipleObjectsReturned):
can_edit = hookset.can_create_page(wiki, request.user, slug="landing")
edit_url = binder.page_url(wiki, "landing")
else:
revision = page.revisions.latest()
can_edit = hookset.can_edit_page(page, request.user)
edit_url = page.get_edit_url()
return render_to_response('external.html', {
"page_name": "Landing",
"revision": revision,
"can_edit": can_edit,
"edit_url": edit_url,
}, context_instance=RequestContext(request))
|
[
"def",
"landing_view",
"(",
"request",
")",
":",
"revision",
"=",
"None",
"can_edit",
"=",
"False",
"edit_url",
"=",
"None",
"if",
"\"farnswiki\"",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"from",
"wiki",
".",
"models",
"import",
"Page",
"from",
"wiki",
".",
"hooks",
"import",
"hookset",
"binder",
"=",
"settings",
".",
"WIKI_BINDERS",
"[",
"0",
"]",
"wiki",
"=",
"binder",
".",
"lookup",
"(",
")",
"try",
":",
"if",
"wiki",
":",
"page",
"=",
"wiki",
".",
"pages",
".",
"get",
"(",
"slug",
"=",
"\"landing\"",
")",
"else",
":",
"page",
"=",
"Page",
".",
"objects",
".",
"get",
"(",
"slug",
"=",
"\"landing\"",
")",
"except",
"(",
"Page",
".",
"DoesNotExist",
",",
"Page",
".",
"MultipleObjectsReturned",
")",
":",
"can_edit",
"=",
"hookset",
".",
"can_create_page",
"(",
"wiki",
",",
"request",
".",
"user",
",",
"slug",
"=",
"\"landing\"",
")",
"edit_url",
"=",
"binder",
".",
"page_url",
"(",
"wiki",
",",
"\"landing\"",
")",
"else",
":",
"revision",
"=",
"page",
".",
"revisions",
".",
"latest",
"(",
")",
"can_edit",
"=",
"hookset",
".",
"can_edit_page",
"(",
"page",
",",
"request",
".",
"user",
")",
"edit_url",
"=",
"page",
".",
"get_edit_url",
"(",
")",
"return",
"render_to_response",
"(",
"'external.html'",
",",
"{",
"\"page_name\"",
":",
"\"Landing\"",
",",
"\"revision\"",
":",
"revision",
",",
"\"can_edit\"",
":",
"can_edit",
",",
"\"edit_url\"",
":",
"edit_url",
",",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
")"
] |
The external landing.
|
[
"The",
"external",
"landing",
"."
] |
1b6589f0d9fea154f0a1e2231ed906764ed26d26
|
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L101-L130
|
247,195 |
knagra/farnsworth
|
base/views.py
|
my_profile_view
|
def my_profile_view(request):
''' The view of the profile page. '''
page_name = "Profile Page"
if request.user.username == ANONYMOUS_USERNAME:
return red_home(request, MESSAGES['SPINELESS'])
userProfile = UserProfile.objects.get(user=request.user)
change_password_form = PasswordChangeForm(
request.user,
request.POST if "submit_password_form" in request.POST else None,
)
update_email_form = UpdateEmailForm(
request.POST if "submit_profile_form" in request.POST else None,
instance=request.user,
prefix="user",
)
update_profile_form = UpdateProfileForm(
request.POST if "submit_profile_form" in request.POST else None,
instance=userProfile,
prefix="profile",
)
if change_password_form.is_valid():
change_password_form.save()
messages.add_message(request, messages.SUCCESS,
"Your password was successfully changed.")
return HttpResponseRedirect(reverse('my_profile'))
if update_email_form.is_valid() and update_profile_form.is_valid():
update_email_form.save()
update_profile_form.save()
messages.add_message(request, messages.SUCCESS,
"Your profile has been successfully updated.")
return HttpResponseRedirect(reverse('my_profile'))
return render_to_response('my_profile.html', {
'page_name': page_name,
"update_email_form": update_email_form,
'update_profile_form': update_profile_form,
'change_password_form': change_password_form,
}, context_instance=RequestContext(request))
|
python
|
def my_profile_view(request):
''' The view of the profile page. '''
page_name = "Profile Page"
if request.user.username == ANONYMOUS_USERNAME:
return red_home(request, MESSAGES['SPINELESS'])
userProfile = UserProfile.objects.get(user=request.user)
change_password_form = PasswordChangeForm(
request.user,
request.POST if "submit_password_form" in request.POST else None,
)
update_email_form = UpdateEmailForm(
request.POST if "submit_profile_form" in request.POST else None,
instance=request.user,
prefix="user",
)
update_profile_form = UpdateProfileForm(
request.POST if "submit_profile_form" in request.POST else None,
instance=userProfile,
prefix="profile",
)
if change_password_form.is_valid():
change_password_form.save()
messages.add_message(request, messages.SUCCESS,
"Your password was successfully changed.")
return HttpResponseRedirect(reverse('my_profile'))
if update_email_form.is_valid() and update_profile_form.is_valid():
update_email_form.save()
update_profile_form.save()
messages.add_message(request, messages.SUCCESS,
"Your profile has been successfully updated.")
return HttpResponseRedirect(reverse('my_profile'))
return render_to_response('my_profile.html', {
'page_name': page_name,
"update_email_form": update_email_form,
'update_profile_form': update_profile_form,
'change_password_form': change_password_form,
}, context_instance=RequestContext(request))
|
[
"def",
"my_profile_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Profile Page\"",
"if",
"request",
".",
"user",
".",
"username",
"==",
"ANONYMOUS_USERNAME",
":",
"return",
"red_home",
"(",
"request",
",",
"MESSAGES",
"[",
"'SPINELESS'",
"]",
")",
"userProfile",
"=",
"UserProfile",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"request",
".",
"user",
")",
"change_password_form",
"=",
"PasswordChangeForm",
"(",
"request",
".",
"user",
",",
"request",
".",
"POST",
"if",
"\"submit_password_form\"",
"in",
"request",
".",
"POST",
"else",
"None",
",",
")",
"update_email_form",
"=",
"UpdateEmailForm",
"(",
"request",
".",
"POST",
"if",
"\"submit_profile_form\"",
"in",
"request",
".",
"POST",
"else",
"None",
",",
"instance",
"=",
"request",
".",
"user",
",",
"prefix",
"=",
"\"user\"",
",",
")",
"update_profile_form",
"=",
"UpdateProfileForm",
"(",
"request",
".",
"POST",
"if",
"\"submit_profile_form\"",
"in",
"request",
".",
"POST",
"else",
"None",
",",
"instance",
"=",
"userProfile",
",",
"prefix",
"=",
"\"profile\"",
",",
")",
"if",
"change_password_form",
".",
"is_valid",
"(",
")",
":",
"change_password_form",
".",
"save",
"(",
")",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"SUCCESS",
",",
"\"Your password was successfully changed.\"",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'my_profile'",
")",
")",
"if",
"update_email_form",
".",
"is_valid",
"(",
")",
"and",
"update_profile_form",
".",
"is_valid",
"(",
")",
":",
"update_email_form",
".",
"save",
"(",
")",
"update_profile_form",
".",
"save",
"(",
")",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"SUCCESS",
",",
"\"Your profile has been successfully updated.\"",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'my_profile'",
")",
")",
"return",
"render_to_response",
"(",
"'my_profile.html'",
",",
"{",
"'page_name'",
":",
"page_name",
",",
"\"update_email_form\"",
":",
"update_email_form",
",",
"'update_profile_form'",
":",
"update_profile_form",
",",
"'change_password_form'",
":",
"change_password_form",
",",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
")"
] |
The view of the profile page.
|
[
"The",
"view",
"of",
"the",
"profile",
"page",
"."
] |
1b6589f0d9fea154f0a1e2231ed906764ed26d26
|
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L305-L341
|
247,196 |
knagra/farnsworth
|
base/views.py
|
notifications_view
|
def notifications_view(request):
"""
Show a user their notifications.
"""
page_name = "Your Notifications"
# Copy the notifications so that they are still unread when we render the page
notifications = list(request.user.notifications.all())
request.user.notifications.mark_all_as_read()
return render_to_response("list_notifications.html", {
"page_name": page_name,
"notifications": notifications,
}, context_instance=RequestContext(request))
|
python
|
def notifications_view(request):
"""
Show a user their notifications.
"""
page_name = "Your Notifications"
# Copy the notifications so that they are still unread when we render the page
notifications = list(request.user.notifications.all())
request.user.notifications.mark_all_as_read()
return render_to_response("list_notifications.html", {
"page_name": page_name,
"notifications": notifications,
}, context_instance=RequestContext(request))
|
[
"def",
"notifications_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Your Notifications\"",
"# Copy the notifications so that they are still unread when we render the page",
"notifications",
"=",
"list",
"(",
"request",
".",
"user",
".",
"notifications",
".",
"all",
"(",
")",
")",
"request",
".",
"user",
".",
"notifications",
".",
"mark_all_as_read",
"(",
")",
"return",
"render_to_response",
"(",
"\"list_notifications.html\"",
",",
"{",
"\"page_name\"",
":",
"page_name",
",",
"\"notifications\"",
":",
"notifications",
",",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
")"
] |
Show a user their notifications.
|
[
"Show",
"a",
"user",
"their",
"notifications",
"."
] |
1b6589f0d9fea154f0a1e2231ed906764ed26d26
|
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L344-L355
|
247,197 |
knagra/farnsworth
|
base/views.py
|
login_view
|
def login_view(request):
''' The view of the login page. '''
ANONYMOUS_SESSION = request.session.get('ANONYMOUS_SESSION', False)
page_name = "Login Page"
redirect_to = request.GET.get('next', reverse('homepage'))
if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (ANONYMOUS_SESSION and request.user.username != ANONYMOUS_USERNAME):
return HttpResponseRedirect(redirect_to)
form = LoginForm(request.POST or None)
if form.is_valid():
user = form.save()
login(request, user)
if ANONYMOUS_SESSION:
request.session['ANONYMOUS_SESSION'] = True
return HttpResponseRedirect(redirect_to)
elif request.method == "POST":
reset_url = request.build_absolute_uri(reverse('reset_pw'))
messages.add_message(request, messages.INFO,
MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))
return render_to_response('login.html', {
'page_name': page_name,
'form': form,
'oauth_providers': _get_oauth_providers(),
'redirect_to': redirect_to,
}, context_instance=RequestContext(request))
|
python
|
def login_view(request):
''' The view of the login page. '''
ANONYMOUS_SESSION = request.session.get('ANONYMOUS_SESSION', False)
page_name = "Login Page"
redirect_to = request.GET.get('next', reverse('homepage'))
if (request.user.is_authenticated() and not ANONYMOUS_SESSION) or (ANONYMOUS_SESSION and request.user.username != ANONYMOUS_USERNAME):
return HttpResponseRedirect(redirect_to)
form = LoginForm(request.POST or None)
if form.is_valid():
user = form.save()
login(request, user)
if ANONYMOUS_SESSION:
request.session['ANONYMOUS_SESSION'] = True
return HttpResponseRedirect(redirect_to)
elif request.method == "POST":
reset_url = request.build_absolute_uri(reverse('reset_pw'))
messages.add_message(request, messages.INFO,
MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))
return render_to_response('login.html', {
'page_name': page_name,
'form': form,
'oauth_providers': _get_oauth_providers(),
'redirect_to': redirect_to,
}, context_instance=RequestContext(request))
|
[
"def",
"login_view",
"(",
"request",
")",
":",
"ANONYMOUS_SESSION",
"=",
"request",
".",
"session",
".",
"get",
"(",
"'ANONYMOUS_SESSION'",
",",
"False",
")",
"page_name",
"=",
"\"Login Page\"",
"redirect_to",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
",",
"reverse",
"(",
"'homepage'",
")",
")",
"if",
"(",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"and",
"not",
"ANONYMOUS_SESSION",
")",
"or",
"(",
"ANONYMOUS_SESSION",
"and",
"request",
".",
"user",
".",
"username",
"!=",
"ANONYMOUS_USERNAME",
")",
":",
"return",
"HttpResponseRedirect",
"(",
"redirect_to",
")",
"form",
"=",
"LoginForm",
"(",
"request",
".",
"POST",
"or",
"None",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"user",
"=",
"form",
".",
"save",
"(",
")",
"login",
"(",
"request",
",",
"user",
")",
"if",
"ANONYMOUS_SESSION",
":",
"request",
".",
"session",
"[",
"'ANONYMOUS_SESSION'",
"]",
"=",
"True",
"return",
"HttpResponseRedirect",
"(",
"redirect_to",
")",
"elif",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"reset_url",
"=",
"request",
".",
"build_absolute_uri",
"(",
"reverse",
"(",
"'reset_pw'",
")",
")",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"INFO",
",",
"MESSAGES",
"[",
"'RESET_MESSAGE'",
"]",
".",
"format",
"(",
"reset_url",
"=",
"reset_url",
")",
")",
"return",
"render_to_response",
"(",
"'login.html'",
",",
"{",
"'page_name'",
":",
"page_name",
",",
"'form'",
":",
"form",
",",
"'oauth_providers'",
":",
"_get_oauth_providers",
"(",
")",
",",
"'redirect_to'",
":",
"redirect_to",
",",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
")"
] |
The view of the login page.
|
[
"The",
"view",
"of",
"the",
"login",
"page",
"."
] |
1b6589f0d9fea154f0a1e2231ed906764ed26d26
|
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L357-L381
|
247,198 |
knagra/farnsworth
|
base/views.py
|
member_profile_view
|
def member_profile_view(request, targetUsername):
''' View a member's Profile. '''
if targetUsername == request.user.username and targetUsername != ANONYMOUS_USERNAME:
return HttpResponseRedirect(reverse('my_profile'))
page_name = "{0}'s Profile".format(targetUsername)
targetUser = get_object_or_404(User, username=targetUsername)
targetProfile = get_object_or_404(UserProfile, user=targetUser)
number_of_threads = Thread.objects.filter(owner=targetProfile).count()
number_of_messages = Message.objects.filter(owner=targetProfile).count()
number_of_requests = Request.objects.filter(owner=targetProfile).count()
rooms = Room.objects.filter(current_residents=targetProfile)
prev_rooms = PreviousResident.objects.filter(resident=targetProfile)
return render_to_response('member_profile.html', {
'page_name': page_name,
'targetUser': targetUser,
'targetProfile': targetProfile,
'number_of_threads': number_of_threads,
'number_of_messages': number_of_messages,
'number_of_requests': number_of_requests,
"rooms": rooms,
"prev_rooms": prev_rooms,
}, context_instance=RequestContext(request))
|
python
|
def member_profile_view(request, targetUsername):
''' View a member's Profile. '''
if targetUsername == request.user.username and targetUsername != ANONYMOUS_USERNAME:
return HttpResponseRedirect(reverse('my_profile'))
page_name = "{0}'s Profile".format(targetUsername)
targetUser = get_object_or_404(User, username=targetUsername)
targetProfile = get_object_or_404(UserProfile, user=targetUser)
number_of_threads = Thread.objects.filter(owner=targetProfile).count()
number_of_messages = Message.objects.filter(owner=targetProfile).count()
number_of_requests = Request.objects.filter(owner=targetProfile).count()
rooms = Room.objects.filter(current_residents=targetProfile)
prev_rooms = PreviousResident.objects.filter(resident=targetProfile)
return render_to_response('member_profile.html', {
'page_name': page_name,
'targetUser': targetUser,
'targetProfile': targetProfile,
'number_of_threads': number_of_threads,
'number_of_messages': number_of_messages,
'number_of_requests': number_of_requests,
"rooms": rooms,
"prev_rooms": prev_rooms,
}, context_instance=RequestContext(request))
|
[
"def",
"member_profile_view",
"(",
"request",
",",
"targetUsername",
")",
":",
"if",
"targetUsername",
"==",
"request",
".",
"user",
".",
"username",
"and",
"targetUsername",
"!=",
"ANONYMOUS_USERNAME",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'my_profile'",
")",
")",
"page_name",
"=",
"\"{0}'s Profile\"",
".",
"format",
"(",
"targetUsername",
")",
"targetUser",
"=",
"get_object_or_404",
"(",
"User",
",",
"username",
"=",
"targetUsername",
")",
"targetProfile",
"=",
"get_object_or_404",
"(",
"UserProfile",
",",
"user",
"=",
"targetUser",
")",
"number_of_threads",
"=",
"Thread",
".",
"objects",
".",
"filter",
"(",
"owner",
"=",
"targetProfile",
")",
".",
"count",
"(",
")",
"number_of_messages",
"=",
"Message",
".",
"objects",
".",
"filter",
"(",
"owner",
"=",
"targetProfile",
")",
".",
"count",
"(",
")",
"number_of_requests",
"=",
"Request",
".",
"objects",
".",
"filter",
"(",
"owner",
"=",
"targetProfile",
")",
".",
"count",
"(",
")",
"rooms",
"=",
"Room",
".",
"objects",
".",
"filter",
"(",
"current_residents",
"=",
"targetProfile",
")",
"prev_rooms",
"=",
"PreviousResident",
".",
"objects",
".",
"filter",
"(",
"resident",
"=",
"targetProfile",
")",
"return",
"render_to_response",
"(",
"'member_profile.html'",
",",
"{",
"'page_name'",
":",
"page_name",
",",
"'targetUser'",
":",
"targetUser",
",",
"'targetProfile'",
":",
"targetProfile",
",",
"'number_of_threads'",
":",
"number_of_threads",
",",
"'number_of_messages'",
":",
"number_of_messages",
",",
"'number_of_requests'",
":",
"number_of_requests",
",",
"\"rooms\"",
":",
"rooms",
",",
"\"prev_rooms\"",
":",
"prev_rooms",
",",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
")"
] |
View a member's Profile.
|
[
"View",
"a",
"member",
"s",
"Profile",
"."
] |
1b6589f0d9fea154f0a1e2231ed906764ed26d26
|
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L444-L465
|
247,199 |
knagra/farnsworth
|
base/views.py
|
request_profile_view
|
def request_profile_view(request):
''' The page to request a user profile on the site. '''
page_name = "Profile Request Page"
redirect_to = request.GET.get('next', reverse('homepage'))
if request.user.is_authenticated() and request.user.username != ANONYMOUS_USERNAME:
return HttpResponseRedirect(redirect_to)
form = ProfileRequestForm(
request.POST or None,
)
if form.is_valid():
username = form.cleaned_data['username']
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
if User.objects.filter(username=username).count():
reset_url = request.build_absolute_uri(reverse('reset_pw'))
form_add_error(form, 'username',
MESSAGES["USERNAME_TAKEN"].format(username=username))
messages.add_message(request, messages.INFO,
MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))
elif User.objects.filter(email=email).count():
reset_url = request.build_absolute_uri(reverse('reset_pw'))
messages.add_message(request, messages.INFO,
MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))
form_add_error(form, "email", MESSAGES["EMAIL_TAKEN"])
elif ProfileRequest.objects.filter(first_name=first_name, last_name=last_name).count():
form_add_error(
form, '__all__',
MESSAGES["PROFILE_TAKEN"].format(first_name=first_name,
last_name=last_name))
elif User.objects.filter(first_name=first_name, last_name=last_name).count():
reset_url = request.build_absolute_uri(reverse('reset_pw'))
messages.add_message(request, messages.INFO, MESSAGES['PROFILE_REQUEST_RESET'].format(reset_url=reset_url))
else:
form.save()
messages.add_message(request, messages.SUCCESS, MESSAGES['PROFILE_SUBMITTED'])
if settings.SEND_EMAILS and (email not in settings.EMAIL_BLACKLIST):
submission_subject = SUBMISSION_SUBJECT.format(house=settings.HOUSE_NAME)
submission_email = SUBMISSION_EMAIL.format(house=settings.HOUSE_NAME, full_name=first_name + " " + last_name, admin_name=settings.ADMINS[0][0],
admin_email=settings.ADMINS[0][1])
try:
send_mail(submission_subject, submission_email, settings.EMAIL_HOST_USER, [email], fail_silently=False)
# Add logging here
except SMTPException:
pass # Add logging here
return HttpResponseRedirect(redirect_to)
return render(request, 'request_profile.html', {
'form': form,
'page_name': page_name,
'oauth_providers': _get_oauth_providers(),
'redirect_to': redirect_to,
})
|
python
|
def request_profile_view(request):
''' The page to request a user profile on the site. '''
page_name = "Profile Request Page"
redirect_to = request.GET.get('next', reverse('homepage'))
if request.user.is_authenticated() and request.user.username != ANONYMOUS_USERNAME:
return HttpResponseRedirect(redirect_to)
form = ProfileRequestForm(
request.POST or None,
)
if form.is_valid():
username = form.cleaned_data['username']
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
if User.objects.filter(username=username).count():
reset_url = request.build_absolute_uri(reverse('reset_pw'))
form_add_error(form, 'username',
MESSAGES["USERNAME_TAKEN"].format(username=username))
messages.add_message(request, messages.INFO,
MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))
elif User.objects.filter(email=email).count():
reset_url = request.build_absolute_uri(reverse('reset_pw'))
messages.add_message(request, messages.INFO,
MESSAGES['RESET_MESSAGE'].format(reset_url=reset_url))
form_add_error(form, "email", MESSAGES["EMAIL_TAKEN"])
elif ProfileRequest.objects.filter(first_name=first_name, last_name=last_name).count():
form_add_error(
form, '__all__',
MESSAGES["PROFILE_TAKEN"].format(first_name=first_name,
last_name=last_name))
elif User.objects.filter(first_name=first_name, last_name=last_name).count():
reset_url = request.build_absolute_uri(reverse('reset_pw'))
messages.add_message(request, messages.INFO, MESSAGES['PROFILE_REQUEST_RESET'].format(reset_url=reset_url))
else:
form.save()
messages.add_message(request, messages.SUCCESS, MESSAGES['PROFILE_SUBMITTED'])
if settings.SEND_EMAILS and (email not in settings.EMAIL_BLACKLIST):
submission_subject = SUBMISSION_SUBJECT.format(house=settings.HOUSE_NAME)
submission_email = SUBMISSION_EMAIL.format(house=settings.HOUSE_NAME, full_name=first_name + " " + last_name, admin_name=settings.ADMINS[0][0],
admin_email=settings.ADMINS[0][1])
try:
send_mail(submission_subject, submission_email, settings.EMAIL_HOST_USER, [email], fail_silently=False)
# Add logging here
except SMTPException:
pass # Add logging here
return HttpResponseRedirect(redirect_to)
return render(request, 'request_profile.html', {
'form': form,
'page_name': page_name,
'oauth_providers': _get_oauth_providers(),
'redirect_to': redirect_to,
})
|
[
"def",
"request_profile_view",
"(",
"request",
")",
":",
"page_name",
"=",
"\"Profile Request Page\"",
"redirect_to",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
",",
"reverse",
"(",
"'homepage'",
")",
")",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"and",
"request",
".",
"user",
".",
"username",
"!=",
"ANONYMOUS_USERNAME",
":",
"return",
"HttpResponseRedirect",
"(",
"redirect_to",
")",
"form",
"=",
"ProfileRequestForm",
"(",
"request",
".",
"POST",
"or",
"None",
",",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"username",
"=",
"form",
".",
"cleaned_data",
"[",
"'username'",
"]",
"first_name",
"=",
"form",
".",
"cleaned_data",
"[",
"'first_name'",
"]",
"last_name",
"=",
"form",
".",
"cleaned_data",
"[",
"'last_name'",
"]",
"email",
"=",
"form",
".",
"cleaned_data",
"[",
"'email'",
"]",
"if",
"User",
".",
"objects",
".",
"filter",
"(",
"username",
"=",
"username",
")",
".",
"count",
"(",
")",
":",
"reset_url",
"=",
"request",
".",
"build_absolute_uri",
"(",
"reverse",
"(",
"'reset_pw'",
")",
")",
"form_add_error",
"(",
"form",
",",
"'username'",
",",
"MESSAGES",
"[",
"\"USERNAME_TAKEN\"",
"]",
".",
"format",
"(",
"username",
"=",
"username",
")",
")",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"INFO",
",",
"MESSAGES",
"[",
"'RESET_MESSAGE'",
"]",
".",
"format",
"(",
"reset_url",
"=",
"reset_url",
")",
")",
"elif",
"User",
".",
"objects",
".",
"filter",
"(",
"email",
"=",
"email",
")",
".",
"count",
"(",
")",
":",
"reset_url",
"=",
"request",
".",
"build_absolute_uri",
"(",
"reverse",
"(",
"'reset_pw'",
")",
")",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"INFO",
",",
"MESSAGES",
"[",
"'RESET_MESSAGE'",
"]",
".",
"format",
"(",
"reset_url",
"=",
"reset_url",
")",
")",
"form_add_error",
"(",
"form",
",",
"\"email\"",
",",
"MESSAGES",
"[",
"\"EMAIL_TAKEN\"",
"]",
")",
"elif",
"ProfileRequest",
".",
"objects",
".",
"filter",
"(",
"first_name",
"=",
"first_name",
",",
"last_name",
"=",
"last_name",
")",
".",
"count",
"(",
")",
":",
"form_add_error",
"(",
"form",
",",
"'__all__'",
",",
"MESSAGES",
"[",
"\"PROFILE_TAKEN\"",
"]",
".",
"format",
"(",
"first_name",
"=",
"first_name",
",",
"last_name",
"=",
"last_name",
")",
")",
"elif",
"User",
".",
"objects",
".",
"filter",
"(",
"first_name",
"=",
"first_name",
",",
"last_name",
"=",
"last_name",
")",
".",
"count",
"(",
")",
":",
"reset_url",
"=",
"request",
".",
"build_absolute_uri",
"(",
"reverse",
"(",
"'reset_pw'",
")",
")",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"INFO",
",",
"MESSAGES",
"[",
"'PROFILE_REQUEST_RESET'",
"]",
".",
"format",
"(",
"reset_url",
"=",
"reset_url",
")",
")",
"else",
":",
"form",
".",
"save",
"(",
")",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"SUCCESS",
",",
"MESSAGES",
"[",
"'PROFILE_SUBMITTED'",
"]",
")",
"if",
"settings",
".",
"SEND_EMAILS",
"and",
"(",
"email",
"not",
"in",
"settings",
".",
"EMAIL_BLACKLIST",
")",
":",
"submission_subject",
"=",
"SUBMISSION_SUBJECT",
".",
"format",
"(",
"house",
"=",
"settings",
".",
"HOUSE_NAME",
")",
"submission_email",
"=",
"SUBMISSION_EMAIL",
".",
"format",
"(",
"house",
"=",
"settings",
".",
"HOUSE_NAME",
",",
"full_name",
"=",
"first_name",
"+",
"\" \"",
"+",
"last_name",
",",
"admin_name",
"=",
"settings",
".",
"ADMINS",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"admin_email",
"=",
"settings",
".",
"ADMINS",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"try",
":",
"send_mail",
"(",
"submission_subject",
",",
"submission_email",
",",
"settings",
".",
"EMAIL_HOST_USER",
",",
"[",
"email",
"]",
",",
"fail_silently",
"=",
"False",
")",
"# Add logging here",
"except",
"SMTPException",
":",
"pass",
"# Add logging here",
"return",
"HttpResponseRedirect",
"(",
"redirect_to",
")",
"return",
"render",
"(",
"request",
",",
"'request_profile.html'",
",",
"{",
"'form'",
":",
"form",
",",
"'page_name'",
":",
"page_name",
",",
"'oauth_providers'",
":",
"_get_oauth_providers",
"(",
")",
",",
"'redirect_to'",
":",
"redirect_to",
",",
"}",
")"
] |
The page to request a user profile on the site.
|
[
"The",
"page",
"to",
"request",
"a",
"user",
"profile",
"on",
"the",
"site",
"."
] |
1b6589f0d9fea154f0a1e2231ed906764ed26d26
|
https://github.com/knagra/farnsworth/blob/1b6589f0d9fea154f0a1e2231ed906764ed26d26/base/views.py#L467-L518
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.