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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
9,300
|
libtcod/python-tcod
|
tcod/console.py
|
Console._init_setup_console_data
|
def _init_setup_console_data(self, order: str = "C") -> None:
"""Setup numpy arrays over libtcod data buffers."""
global _root_console
self._key_color = None
if self.console_c == ffi.NULL:
_root_console = self
self._console_data = lib.TCOD_ctx.root
else:
self._console_data = ffi.cast(
"struct TCOD_Console*", self.console_c
)
self._tiles = np.frombuffer(
ffi.buffer(self._console_data.tiles[0 : self.width * self.height]),
dtype=self.DTYPE,
).reshape((self.height, self.width))
self._order = tcod._internal.verify_order(order)
|
python
|
def _init_setup_console_data(self, order: str = "C") -> None:
"""Setup numpy arrays over libtcod data buffers."""
global _root_console
self._key_color = None
if self.console_c == ffi.NULL:
_root_console = self
self._console_data = lib.TCOD_ctx.root
else:
self._console_data = ffi.cast(
"struct TCOD_Console*", self.console_c
)
self._tiles = np.frombuffer(
ffi.buffer(self._console_data.tiles[0 : self.width * self.height]),
dtype=self.DTYPE,
).reshape((self.height, self.width))
self._order = tcod._internal.verify_order(order)
|
[
"def",
"_init_setup_console_data",
"(",
"self",
",",
"order",
":",
"str",
"=",
"\"C\"",
")",
"->",
"None",
":",
"global",
"_root_console",
"self",
".",
"_key_color",
"=",
"None",
"if",
"self",
".",
"console_c",
"==",
"ffi",
".",
"NULL",
":",
"_root_console",
"=",
"self",
"self",
".",
"_console_data",
"=",
"lib",
".",
"TCOD_ctx",
".",
"root",
"else",
":",
"self",
".",
"_console_data",
"=",
"ffi",
".",
"cast",
"(",
"\"struct TCOD_Console*\"",
",",
"self",
".",
"console_c",
")",
"self",
".",
"_tiles",
"=",
"np",
".",
"frombuffer",
"(",
"ffi",
".",
"buffer",
"(",
"self",
".",
"_console_data",
".",
"tiles",
"[",
"0",
":",
"self",
".",
"width",
"*",
"self",
".",
"height",
"]",
")",
",",
"dtype",
"=",
"self",
".",
"DTYPE",
",",
")",
".",
"reshape",
"(",
"(",
"self",
".",
"height",
",",
"self",
".",
"width",
")",
")",
"self",
".",
"_order",
"=",
"tcod",
".",
"_internal",
".",
"verify_order",
"(",
"order",
")"
] |
Setup numpy arrays over libtcod data buffers.
|
[
"Setup",
"numpy",
"arrays",
"over",
"libtcod",
"data",
"buffers",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L179-L196
|
9,301
|
libtcod/python-tcod
|
tcod/console.py
|
Console.tiles
|
def tiles(self) -> np.array:
"""An array of this consoles tile data.
This acts as a combination of the `ch`, `fg`, and `bg` attributes.
Colors include an alpha channel but how alpha works is currently
undefined.
Example::
>>> con = tcod.console.Console(10, 2, order="F")
>>> con.tiles[0, 0] = (
... ord("X"),
... (*tcod.white, 255),
... (*tcod.black, 255),
... )
>>> con.tiles[0, 0]
(88, [255, 255, 255, 255], [ 0, 0, 0, 255])
.. versionadded:: 10.0
"""
return self._tiles.T if self._order == "F" else self._tiles
|
python
|
def tiles(self) -> np.array:
"""An array of this consoles tile data.
This acts as a combination of the `ch`, `fg`, and `bg` attributes.
Colors include an alpha channel but how alpha works is currently
undefined.
Example::
>>> con = tcod.console.Console(10, 2, order="F")
>>> con.tiles[0, 0] = (
... ord("X"),
... (*tcod.white, 255),
... (*tcod.black, 255),
... )
>>> con.tiles[0, 0]
(88, [255, 255, 255, 255], [ 0, 0, 0, 255])
.. versionadded:: 10.0
"""
return self._tiles.T if self._order == "F" else self._tiles
|
[
"def",
"tiles",
"(",
"self",
")",
"->",
"np",
".",
"array",
":",
"return",
"self",
".",
"_tiles",
".",
"T",
"if",
"self",
".",
"_order",
"==",
"\"F\"",
"else",
"self",
".",
"_tiles"
] |
An array of this consoles tile data.
This acts as a combination of the `ch`, `fg`, and `bg` attributes.
Colors include an alpha channel but how alpha works is currently
undefined.
Example::
>>> con = tcod.console.Console(10, 2, order="F")
>>> con.tiles[0, 0] = (
... ord("X"),
... (*tcod.white, 255),
... (*tcod.black, 255),
... )
>>> con.tiles[0, 0]
(88, [255, 255, 255, 255], [ 0, 0, 0, 255])
.. versionadded:: 10.0
|
[
"An",
"array",
"of",
"this",
"consoles",
"tile",
"data",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L249-L268
|
9,302
|
libtcod/python-tcod
|
tcod/console.py
|
Console.__clear_warning
|
def __clear_warning(self, name: str, value: Tuple[int, int, int]) -> None:
"""Raise a warning for bad default values during calls to clear."""
warnings.warn(
"Clearing with the console default values is deprecated.\n"
"Add %s=%r to this call." % (name, value),
DeprecationWarning,
stacklevel=3,
)
|
python
|
def __clear_warning(self, name: str, value: Tuple[int, int, int]) -> None:
"""Raise a warning for bad default values during calls to clear."""
warnings.warn(
"Clearing with the console default values is deprecated.\n"
"Add %s=%r to this call." % (name, value),
DeprecationWarning,
stacklevel=3,
)
|
[
"def",
"__clear_warning",
"(",
"self",
",",
"name",
":",
"str",
",",
"value",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
")",
"->",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"Clearing with the console default values is deprecated.\\n\"",
"\"Add %s=%r to this call.\"",
"%",
"(",
"name",
",",
"value",
")",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"3",
",",
")"
] |
Raise a warning for bad default values during calls to clear.
|
[
"Raise",
"a",
"warning",
"for",
"bad",
"default",
"values",
"during",
"calls",
"to",
"clear",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L312-L319
|
9,303
|
libtcod/python-tcod
|
tcod/console.py
|
Console.__deprecate_defaults
|
def __deprecate_defaults(
self,
new_func: str,
bg_blend: Any,
alignment: Any = ...,
clear: Any = ...,
) -> None:
"""Return the parameters needed to recreate the current default state.
"""
if not __debug__:
return
fg = self.default_fg # type: Any
bg = self.default_bg # type: Any
if bg_blend == tcod.constants.BKGND_NONE:
bg = None
if bg_blend == tcod.constants.BKGND_DEFAULT:
bg_blend = self.default_bg_blend
else:
bg_blend = None
if bg_blend == tcod.constants.BKGND_NONE:
bg = None
bg_blend = None
if bg_blend == tcod.constants.BKGND_SET:
bg_blend = None
if alignment is None:
alignment = self.default_alignment
if alignment == tcod.constants.LEFT:
alignment = None
else:
alignment = None
if clear is not ...:
fg = None
params = []
if clear is True:
params.append('ch=ord(" ")')
if clear is False:
params.append("ch=0")
if fg is not None:
params.append("fg=%s" % (fg,))
if bg is not None:
params.append("bg=%s" % (bg,))
if bg_blend is not None:
params.append("bg_blend=%s" % (self.__BG_BLEND_LOOKUP[bg_blend],))
if alignment is not None:
params.append(
"alignment=%s" % (self.__ALIGNMENT_LOOKUP[alignment],)
)
param_str = ", ".join(params)
if not param_str:
param_str = "."
else:
param_str = " and add the following parameters:\n%s" % (param_str,)
warnings.warn(
"Console functions using default values have been deprecated.\n"
"Replace this method with `Console.%s`%s" % (new_func, param_str),
DeprecationWarning,
stacklevel=3,
)
|
python
|
def __deprecate_defaults(
self,
new_func: str,
bg_blend: Any,
alignment: Any = ...,
clear: Any = ...,
) -> None:
"""Return the parameters needed to recreate the current default state.
"""
if not __debug__:
return
fg = self.default_fg # type: Any
bg = self.default_bg # type: Any
if bg_blend == tcod.constants.BKGND_NONE:
bg = None
if bg_blend == tcod.constants.BKGND_DEFAULT:
bg_blend = self.default_bg_blend
else:
bg_blend = None
if bg_blend == tcod.constants.BKGND_NONE:
bg = None
bg_blend = None
if bg_blend == tcod.constants.BKGND_SET:
bg_blend = None
if alignment is None:
alignment = self.default_alignment
if alignment == tcod.constants.LEFT:
alignment = None
else:
alignment = None
if clear is not ...:
fg = None
params = []
if clear is True:
params.append('ch=ord(" ")')
if clear is False:
params.append("ch=0")
if fg is not None:
params.append("fg=%s" % (fg,))
if bg is not None:
params.append("bg=%s" % (bg,))
if bg_blend is not None:
params.append("bg_blend=%s" % (self.__BG_BLEND_LOOKUP[bg_blend],))
if alignment is not None:
params.append(
"alignment=%s" % (self.__ALIGNMENT_LOOKUP[alignment],)
)
param_str = ", ".join(params)
if not param_str:
param_str = "."
else:
param_str = " and add the following parameters:\n%s" % (param_str,)
warnings.warn(
"Console functions using default values have been deprecated.\n"
"Replace this method with `Console.%s`%s" % (new_func, param_str),
DeprecationWarning,
stacklevel=3,
)
|
[
"def",
"__deprecate_defaults",
"(",
"self",
",",
"new_func",
":",
"str",
",",
"bg_blend",
":",
"Any",
",",
"alignment",
":",
"Any",
"=",
"...",
",",
"clear",
":",
"Any",
"=",
"...",
",",
")",
"->",
"None",
":",
"if",
"not",
"__debug__",
":",
"return",
"fg",
"=",
"self",
".",
"default_fg",
"# type: Any",
"bg",
"=",
"self",
".",
"default_bg",
"# type: Any",
"if",
"bg_blend",
"==",
"tcod",
".",
"constants",
".",
"BKGND_NONE",
":",
"bg",
"=",
"None",
"if",
"bg_blend",
"==",
"tcod",
".",
"constants",
".",
"BKGND_DEFAULT",
":",
"bg_blend",
"=",
"self",
".",
"default_bg_blend",
"else",
":",
"bg_blend",
"=",
"None",
"if",
"bg_blend",
"==",
"tcod",
".",
"constants",
".",
"BKGND_NONE",
":",
"bg",
"=",
"None",
"bg_blend",
"=",
"None",
"if",
"bg_blend",
"==",
"tcod",
".",
"constants",
".",
"BKGND_SET",
":",
"bg_blend",
"=",
"None",
"if",
"alignment",
"is",
"None",
":",
"alignment",
"=",
"self",
".",
"default_alignment",
"if",
"alignment",
"==",
"tcod",
".",
"constants",
".",
"LEFT",
":",
"alignment",
"=",
"None",
"else",
":",
"alignment",
"=",
"None",
"if",
"clear",
"is",
"not",
"...",
":",
"fg",
"=",
"None",
"params",
"=",
"[",
"]",
"if",
"clear",
"is",
"True",
":",
"params",
".",
"append",
"(",
"'ch=ord(\" \")'",
")",
"if",
"clear",
"is",
"False",
":",
"params",
".",
"append",
"(",
"\"ch=0\"",
")",
"if",
"fg",
"is",
"not",
"None",
":",
"params",
".",
"append",
"(",
"\"fg=%s\"",
"%",
"(",
"fg",
",",
")",
")",
"if",
"bg",
"is",
"not",
"None",
":",
"params",
".",
"append",
"(",
"\"bg=%s\"",
"%",
"(",
"bg",
",",
")",
")",
"if",
"bg_blend",
"is",
"not",
"None",
":",
"params",
".",
"append",
"(",
"\"bg_blend=%s\"",
"%",
"(",
"self",
".",
"__BG_BLEND_LOOKUP",
"[",
"bg_blend",
"]",
",",
")",
")",
"if",
"alignment",
"is",
"not",
"None",
":",
"params",
".",
"append",
"(",
"\"alignment=%s\"",
"%",
"(",
"self",
".",
"__ALIGNMENT_LOOKUP",
"[",
"alignment",
"]",
",",
")",
")",
"param_str",
"=",
"\", \"",
".",
"join",
"(",
"params",
")",
"if",
"not",
"param_str",
":",
"param_str",
"=",
"\".\"",
"else",
":",
"param_str",
"=",
"\" and add the following parameters:\\n%s\"",
"%",
"(",
"param_str",
",",
")",
"warnings",
".",
"warn",
"(",
"\"Console functions using default values have been deprecated.\\n\"",
"\"Replace this method with `Console.%s`%s\"",
"%",
"(",
"new_func",
",",
"param_str",
")",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"3",
",",
")"
] |
Return the parameters needed to recreate the current default state.
|
[
"Return",
"the",
"parameters",
"needed",
"to",
"recreate",
"the",
"current",
"default",
"state",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L390-L448
|
9,304
|
libtcod/python-tcod
|
tcod/console.py
|
Console.get_height_rect
|
def get_height_rect(
self, x: int, y: int, width: int, height: int, string: str
) -> int:
"""Return the height of this text word-wrapped into this rectangle.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): Maximum width to render the text.
height (int): Maximum lines to render the text.
string (str): A Unicode string.
Returns:
int: The number of lines of text once word-wrapped.
"""
string_ = string.encode("utf-8")
return int(
lib.get_height_rect(
self.console_c, x, y, width, height, string_, len(string_)
)
)
|
python
|
def get_height_rect(
self, x: int, y: int, width: int, height: int, string: str
) -> int:
"""Return the height of this text word-wrapped into this rectangle.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): Maximum width to render the text.
height (int): Maximum lines to render the text.
string (str): A Unicode string.
Returns:
int: The number of lines of text once word-wrapped.
"""
string_ = string.encode("utf-8")
return int(
lib.get_height_rect(
self.console_c, x, y, width, height, string_, len(string_)
)
)
|
[
"def",
"get_height_rect",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"width",
":",
"int",
",",
"height",
":",
"int",
",",
"string",
":",
"str",
")",
"->",
"int",
":",
"string_",
"=",
"string",
".",
"encode",
"(",
"\"utf-8\"",
")",
"return",
"int",
"(",
"lib",
".",
"get_height_rect",
"(",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"string_",
",",
"len",
"(",
"string_",
")",
")",
")"
] |
Return the height of this text word-wrapped into this rectangle.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): Maximum width to render the text.
height (int): Maximum lines to render the text.
string (str): A Unicode string.
Returns:
int: The number of lines of text once word-wrapped.
|
[
"Return",
"the",
"height",
"of",
"this",
"text",
"word",
"-",
"wrapped",
"into",
"this",
"rectangle",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L529-L549
|
9,305
|
libtcod/python-tcod
|
tcod/console.py
|
Console.print_frame
|
def print_frame(
self,
x: int,
y: int,
width: int,
height: int,
string: str = "",
clear: bool = True,
bg_blend: int = tcod.constants.BKGND_DEFAULT,
) -> None:
"""Draw a framed rectangle with optional text.
This uses the default background color and blend mode to fill the
rectangle and the default foreground to draw the outline.
`string` will be printed on the inside of the rectangle, word-wrapped.
If `string` is empty then no title will be drawn.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): The width if the frame.
height (int): The height of the frame.
string (str): A Unicode string to print.
clear (bool): If True all text in the affected area will be
removed.
bg_blend (int): The background blending flag.
.. versionchanged:: 8.2
Now supports Unicode strings.
.. deprecated:: 8.5
Console methods which depend on console defaults have been
deprecated.
Use :any:`Console.draw_frame` instead, calling this function will
print a warning detailing which default values need to be made
explicit.
"""
self.__deprecate_defaults("draw_frame", bg_blend)
string = _fmt(string) if string else ffi.NULL
lib.TCOD_console_printf_frame(
self.console_c, x, y, width, height, clear, bg_blend, string
)
|
python
|
def print_frame(
self,
x: int,
y: int,
width: int,
height: int,
string: str = "",
clear: bool = True,
bg_blend: int = tcod.constants.BKGND_DEFAULT,
) -> None:
"""Draw a framed rectangle with optional text.
This uses the default background color and blend mode to fill the
rectangle and the default foreground to draw the outline.
`string` will be printed on the inside of the rectangle, word-wrapped.
If `string` is empty then no title will be drawn.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): The width if the frame.
height (int): The height of the frame.
string (str): A Unicode string to print.
clear (bool): If True all text in the affected area will be
removed.
bg_blend (int): The background blending flag.
.. versionchanged:: 8.2
Now supports Unicode strings.
.. deprecated:: 8.5
Console methods which depend on console defaults have been
deprecated.
Use :any:`Console.draw_frame` instead, calling this function will
print a warning detailing which default values need to be made
explicit.
"""
self.__deprecate_defaults("draw_frame", bg_blend)
string = _fmt(string) if string else ffi.NULL
lib.TCOD_console_printf_frame(
self.console_c, x, y, width, height, clear, bg_blend, string
)
|
[
"def",
"print_frame",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"width",
":",
"int",
",",
"height",
":",
"int",
",",
"string",
":",
"str",
"=",
"\"\"",
",",
"clear",
":",
"bool",
"=",
"True",
",",
"bg_blend",
":",
"int",
"=",
"tcod",
".",
"constants",
".",
"BKGND_DEFAULT",
",",
")",
"->",
"None",
":",
"self",
".",
"__deprecate_defaults",
"(",
"\"draw_frame\"",
",",
"bg_blend",
")",
"string",
"=",
"_fmt",
"(",
"string",
")",
"if",
"string",
"else",
"ffi",
".",
"NULL",
"lib",
".",
"TCOD_console_printf_frame",
"(",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"clear",
",",
"bg_blend",
",",
"string",
")"
] |
Draw a framed rectangle with optional text.
This uses the default background color and blend mode to fill the
rectangle and the default foreground to draw the outline.
`string` will be printed on the inside of the rectangle, word-wrapped.
If `string` is empty then no title will be drawn.
Args:
x (int): The x coordinate from the left.
y (int): The y coordinate from the top.
width (int): The width if the frame.
height (int): The height of the frame.
string (str): A Unicode string to print.
clear (bool): If True all text in the affected area will be
removed.
bg_blend (int): The background blending flag.
.. versionchanged:: 8.2
Now supports Unicode strings.
.. deprecated:: 8.5
Console methods which depend on console defaults have been
deprecated.
Use :any:`Console.draw_frame` instead, calling this function will
print a warning detailing which default values need to be made
explicit.
|
[
"Draw",
"a",
"framed",
"rectangle",
"with",
"optional",
"text",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L639-L681
|
9,306
|
libtcod/python-tcod
|
tcod/console.py
|
Console.blit
|
def blit(
self,
dest: "Console",
dest_x: int = 0,
dest_y: int = 0,
src_x: int = 0,
src_y: int = 0,
width: int = 0,
height: int = 0,
fg_alpha: float = 1.0,
bg_alpha: float = 1.0,
key_color: Optional[Tuple[int, int, int]] = None,
) -> None:
"""Blit from this console onto the ``dest`` console.
Args:
dest (Console): The destintaion console to blit onto.
dest_x (int): Leftmost coordinate of the destintaion console.
dest_y (int): Topmost coordinate of the destintaion console.
src_x (int): X coordinate from this console to blit, from the left.
src_y (int): Y coordinate from this console to blit, from the top.
width (int): The width of the region to blit.
If this is 0 the maximum possible width will be used.
height (int): The height of the region to blit.
If this is 0 the maximum possible height will be used.
fg_alpha (float): Foreground color alpha vaule.
bg_alpha (float): Background color alpha vaule.
key_color (Optional[Tuple[int, int, int]]):
None, or a (red, green, blue) tuple with values of 0-255.
.. versionchanged:: 4.0
Parameters were rearraged and made optional.
Previously they were:
`(x, y, width, height, dest, dest_x, dest_y, *)`
"""
# The old syntax is easy to detect and correct.
if hasattr(src_y, "console_c"):
(
src_x, # type: ignore
src_y,
width,
height,
dest, # type: ignore
dest_x,
dest_y,
) = (dest, dest_x, dest_y, src_x, src_y, width, height)
warnings.warn(
"Parameter names have been moved around, see documentation.",
DeprecationWarning,
stacklevel=2,
)
key_color = key_color or self._key_color
if key_color:
key_color = ffi.new("TCOD_color_t*", key_color)
lib.TCOD_console_blit_key_color(
self.console_c,
src_x,
src_y,
width,
height,
dest.console_c,
dest_x,
dest_y,
fg_alpha,
bg_alpha,
key_color,
)
else:
lib.TCOD_console_blit(
self.console_c,
src_x,
src_y,
width,
height,
dest.console_c,
dest_x,
dest_y,
fg_alpha,
bg_alpha,
)
|
python
|
def blit(
self,
dest: "Console",
dest_x: int = 0,
dest_y: int = 0,
src_x: int = 0,
src_y: int = 0,
width: int = 0,
height: int = 0,
fg_alpha: float = 1.0,
bg_alpha: float = 1.0,
key_color: Optional[Tuple[int, int, int]] = None,
) -> None:
"""Blit from this console onto the ``dest`` console.
Args:
dest (Console): The destintaion console to blit onto.
dest_x (int): Leftmost coordinate of the destintaion console.
dest_y (int): Topmost coordinate of the destintaion console.
src_x (int): X coordinate from this console to blit, from the left.
src_y (int): Y coordinate from this console to blit, from the top.
width (int): The width of the region to blit.
If this is 0 the maximum possible width will be used.
height (int): The height of the region to blit.
If this is 0 the maximum possible height will be used.
fg_alpha (float): Foreground color alpha vaule.
bg_alpha (float): Background color alpha vaule.
key_color (Optional[Tuple[int, int, int]]):
None, or a (red, green, blue) tuple with values of 0-255.
.. versionchanged:: 4.0
Parameters were rearraged and made optional.
Previously they were:
`(x, y, width, height, dest, dest_x, dest_y, *)`
"""
# The old syntax is easy to detect and correct.
if hasattr(src_y, "console_c"):
(
src_x, # type: ignore
src_y,
width,
height,
dest, # type: ignore
dest_x,
dest_y,
) = (dest, dest_x, dest_y, src_x, src_y, width, height)
warnings.warn(
"Parameter names have been moved around, see documentation.",
DeprecationWarning,
stacklevel=2,
)
key_color = key_color or self._key_color
if key_color:
key_color = ffi.new("TCOD_color_t*", key_color)
lib.TCOD_console_blit_key_color(
self.console_c,
src_x,
src_y,
width,
height,
dest.console_c,
dest_x,
dest_y,
fg_alpha,
bg_alpha,
key_color,
)
else:
lib.TCOD_console_blit(
self.console_c,
src_x,
src_y,
width,
height,
dest.console_c,
dest_x,
dest_y,
fg_alpha,
bg_alpha,
)
|
[
"def",
"blit",
"(",
"self",
",",
"dest",
":",
"\"Console\"",
",",
"dest_x",
":",
"int",
"=",
"0",
",",
"dest_y",
":",
"int",
"=",
"0",
",",
"src_x",
":",
"int",
"=",
"0",
",",
"src_y",
":",
"int",
"=",
"0",
",",
"width",
":",
"int",
"=",
"0",
",",
"height",
":",
"int",
"=",
"0",
",",
"fg_alpha",
":",
"float",
"=",
"1.0",
",",
"bg_alpha",
":",
"float",
"=",
"1.0",
",",
"key_color",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
"=",
"None",
",",
")",
"->",
"None",
":",
"# The old syntax is easy to detect and correct.",
"if",
"hasattr",
"(",
"src_y",
",",
"\"console_c\"",
")",
":",
"(",
"src_x",
",",
"# type: ignore",
"src_y",
",",
"width",
",",
"height",
",",
"dest",
",",
"# type: ignore",
"dest_x",
",",
"dest_y",
",",
")",
"=",
"(",
"dest",
",",
"dest_x",
",",
"dest_y",
",",
"src_x",
",",
"src_y",
",",
"width",
",",
"height",
")",
"warnings",
".",
"warn",
"(",
"\"Parameter names have been moved around, see documentation.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"key_color",
"=",
"key_color",
"or",
"self",
".",
"_key_color",
"if",
"key_color",
":",
"key_color",
"=",
"ffi",
".",
"new",
"(",
"\"TCOD_color_t*\"",
",",
"key_color",
")",
"lib",
".",
"TCOD_console_blit_key_color",
"(",
"self",
".",
"console_c",
",",
"src_x",
",",
"src_y",
",",
"width",
",",
"height",
",",
"dest",
".",
"console_c",
",",
"dest_x",
",",
"dest_y",
",",
"fg_alpha",
",",
"bg_alpha",
",",
"key_color",
",",
")",
"else",
":",
"lib",
".",
"TCOD_console_blit",
"(",
"self",
".",
"console_c",
",",
"src_x",
",",
"src_y",
",",
"width",
",",
"height",
",",
"dest",
".",
"console_c",
",",
"dest_x",
",",
"dest_y",
",",
"fg_alpha",
",",
"bg_alpha",
",",
")"
] |
Blit from this console onto the ``dest`` console.
Args:
dest (Console): The destintaion console to blit onto.
dest_x (int): Leftmost coordinate of the destintaion console.
dest_y (int): Topmost coordinate of the destintaion console.
src_x (int): X coordinate from this console to blit, from the left.
src_y (int): Y coordinate from this console to blit, from the top.
width (int): The width of the region to blit.
If this is 0 the maximum possible width will be used.
height (int): The height of the region to blit.
If this is 0 the maximum possible height will be used.
fg_alpha (float): Foreground color alpha vaule.
bg_alpha (float): Background color alpha vaule.
key_color (Optional[Tuple[int, int, int]]):
None, or a (red, green, blue) tuple with values of 0-255.
.. versionchanged:: 4.0
Parameters were rearraged and made optional.
Previously they were:
`(x, y, width, height, dest, dest_x, dest_y, *)`
|
[
"Blit",
"from",
"this",
"console",
"onto",
"the",
"dest",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L683-L766
|
9,307
|
libtcod/python-tcod
|
tcod/console.py
|
Console.print
|
def print(
self,
x: int,
y: int,
string: str,
fg: Optional[Tuple[int, int, int]] = None,
bg: Optional[Tuple[int, int, int]] = None,
bg_blend: int = tcod.constants.BKGND_SET,
alignment: int = tcod.constants.LEFT,
) -> None:
"""Print a string on a console with manual line breaks.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console. You can use negative numbers if you want to
start printing relative to the bottom-right corner, but this behavior
may change in future versions.
`string` is a Unicode string which may include color control
characters. Strings which are too long will be truncated until the
next newline character ``"\\n"``.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.
`bg_blend` is the blend type used by libtcod.
`alignment` can be `tcod.LEFT`, `tcod.CENTER`, or `tcod.RIGHT`.
.. versionadded:: 8.5
.. versionchanged:: 9.0
`fg` and `bg` now default to `None` instead of white-on-black.
"""
x, y = self._pythonic_index(x, y)
string_ = string.encode("utf-8") # type: bytes
lib.console_print(
self.console_c,
x,
y,
string_,
len(string_),
(fg,) if fg is not None else ffi.NULL,
(bg,) if bg is not None else ffi.NULL,
bg_blend,
alignment,
)
|
python
|
def print(
self,
x: int,
y: int,
string: str,
fg: Optional[Tuple[int, int, int]] = None,
bg: Optional[Tuple[int, int, int]] = None,
bg_blend: int = tcod.constants.BKGND_SET,
alignment: int = tcod.constants.LEFT,
) -> None:
"""Print a string on a console with manual line breaks.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console. You can use negative numbers if you want to
start printing relative to the bottom-right corner, but this behavior
may change in future versions.
`string` is a Unicode string which may include color control
characters. Strings which are too long will be truncated until the
next newline character ``"\\n"``.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.
`bg_blend` is the blend type used by libtcod.
`alignment` can be `tcod.LEFT`, `tcod.CENTER`, or `tcod.RIGHT`.
.. versionadded:: 8.5
.. versionchanged:: 9.0
`fg` and `bg` now default to `None` instead of white-on-black.
"""
x, y = self._pythonic_index(x, y)
string_ = string.encode("utf-8") # type: bytes
lib.console_print(
self.console_c,
x,
y,
string_,
len(string_),
(fg,) if fg is not None else ffi.NULL,
(bg,) if bg is not None else ffi.NULL,
bg_blend,
alignment,
)
|
[
"def",
"print",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"string",
":",
"str",
",",
"fg",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
"=",
"None",
",",
"bg",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
"=",
"None",
",",
"bg_blend",
":",
"int",
"=",
"tcod",
".",
"constants",
".",
"BKGND_SET",
",",
"alignment",
":",
"int",
"=",
"tcod",
".",
"constants",
".",
"LEFT",
",",
")",
"->",
"None",
":",
"x",
",",
"y",
"=",
"self",
".",
"_pythonic_index",
"(",
"x",
",",
"y",
")",
"string_",
"=",
"string",
".",
"encode",
"(",
"\"utf-8\"",
")",
"# type: bytes",
"lib",
".",
"console_print",
"(",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"string_",
",",
"len",
"(",
"string_",
")",
",",
"(",
"fg",
",",
")",
"if",
"fg",
"is",
"not",
"None",
"else",
"ffi",
".",
"NULL",
",",
"(",
"bg",
",",
")",
"if",
"bg",
"is",
"not",
"None",
"else",
"ffi",
".",
"NULL",
",",
"bg_blend",
",",
"alignment",
",",
")"
] |
Print a string on a console with manual line breaks.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console. You can use negative numbers if you want to
start printing relative to the bottom-right corner, but this behavior
may change in future versions.
`string` is a Unicode string which may include color control
characters. Strings which are too long will be truncated until the
next newline character ``"\\n"``.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.
`bg_blend` is the blend type used by libtcod.
`alignment` can be `tcod.LEFT`, `tcod.CENTER`, or `tcod.RIGHT`.
.. versionadded:: 8.5
.. versionchanged:: 9.0
`fg` and `bg` now default to `None` instead of white-on-black.
|
[
"Print",
"a",
"string",
"on",
"a",
"console",
"with",
"manual",
"line",
"breaks",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L874-L921
|
9,308
|
libtcod/python-tcod
|
tcod/console.py
|
Console.draw_frame
|
def draw_frame(
self,
x: int,
y: int,
width: int,
height: int,
title: str = "",
clear: bool = True,
fg: Optional[Tuple[int, int, int]] = None,
bg: Optional[Tuple[int, int, int]] = None,
bg_blend: int = tcod.constants.BKGND_SET,
) -> None:
"""Draw a framed rectangle with an optional title.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console. You can use negative numbers if you want to
start printing relative to the bottom-right corner, but this behavior
may change in future versions.
`width` and `height` determine the size of the frame.
`title` is a Unicode string.
If `clear` is True than the region inside of the frame will be cleared.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.
`bg_blend` is the blend type used by libtcod.
.. versionadded:: 8.5
.. versionchanged:: 9.0
`fg` and `bg` now default to `None` instead of white-on-black.
"""
x, y = self._pythonic_index(x, y)
title_ = title.encode("utf-8") # type: bytes
lib.print_frame(
self.console_c,
x,
y,
width,
height,
title_,
len(title_),
(fg,) if fg is not None else ffi.NULL,
(bg,) if bg is not None else ffi.NULL,
bg_blend,
clear,
)
|
python
|
def draw_frame(
self,
x: int,
y: int,
width: int,
height: int,
title: str = "",
clear: bool = True,
fg: Optional[Tuple[int, int, int]] = None,
bg: Optional[Tuple[int, int, int]] = None,
bg_blend: int = tcod.constants.BKGND_SET,
) -> None:
"""Draw a framed rectangle with an optional title.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console. You can use negative numbers if you want to
start printing relative to the bottom-right corner, but this behavior
may change in future versions.
`width` and `height` determine the size of the frame.
`title` is a Unicode string.
If `clear` is True than the region inside of the frame will be cleared.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.
`bg_blend` is the blend type used by libtcod.
.. versionadded:: 8.5
.. versionchanged:: 9.0
`fg` and `bg` now default to `None` instead of white-on-black.
"""
x, y = self._pythonic_index(x, y)
title_ = title.encode("utf-8") # type: bytes
lib.print_frame(
self.console_c,
x,
y,
width,
height,
title_,
len(title_),
(fg,) if fg is not None else ffi.NULL,
(bg,) if bg is not None else ffi.NULL,
bg_blend,
clear,
)
|
[
"def",
"draw_frame",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"width",
":",
"int",
",",
"height",
":",
"int",
",",
"title",
":",
"str",
"=",
"\"\"",
",",
"clear",
":",
"bool",
"=",
"True",
",",
"fg",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
"=",
"None",
",",
"bg",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
"=",
"None",
",",
"bg_blend",
":",
"int",
"=",
"tcod",
".",
"constants",
".",
"BKGND_SET",
",",
")",
"->",
"None",
":",
"x",
",",
"y",
"=",
"self",
".",
"_pythonic_index",
"(",
"x",
",",
"y",
")",
"title_",
"=",
"title",
".",
"encode",
"(",
"\"utf-8\"",
")",
"# type: bytes",
"lib",
".",
"print_frame",
"(",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"title_",
",",
"len",
"(",
"title_",
")",
",",
"(",
"fg",
",",
")",
"if",
"fg",
"is",
"not",
"None",
"else",
"ffi",
".",
"NULL",
",",
"(",
"bg",
",",
")",
"if",
"bg",
"is",
"not",
"None",
"else",
"ffi",
".",
"NULL",
",",
"bg_blend",
",",
"clear",
",",
")"
] |
Draw a framed rectangle with an optional title.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console. You can use negative numbers if you want to
start printing relative to the bottom-right corner, but this behavior
may change in future versions.
`width` and `height` determine the size of the frame.
`title` is a Unicode string.
If `clear` is True than the region inside of the frame will be cleared.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.
`bg_blend` is the blend type used by libtcod.
.. versionadded:: 8.5
.. versionchanged:: 9.0
`fg` and `bg` now default to `None` instead of white-on-black.
|
[
"Draw",
"a",
"framed",
"rectangle",
"with",
"an",
"optional",
"title",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L982-L1033
|
9,309
|
libtcod/python-tcod
|
tcod/console.py
|
Console.draw_rect
|
def draw_rect(
self,
x: int,
y: int,
width: int,
height: int,
ch: int,
fg: Optional[Tuple[int, int, int]] = None,
bg: Optional[Tuple[int, int, int]] = None,
bg_blend: int = tcod.constants.BKGND_SET,
) -> None:
"""Draw characters and colors over a rectangular region.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console. You can use negative numbers if you want to
start printing relative to the bottom-right corner, but this behavior
may change in future versions.
`width` and `height` determine the size of the rectangle.
`ch` is a Unicode integer. You can use 0 to leave the current
characters unchanged.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.
`bg_blend` is the blend type used by libtcod.
.. versionadded:: 8.5
.. versionchanged:: 9.0
`fg` and `bg` now default to `None` instead of white-on-black.
"""
x, y = self._pythonic_index(x, y)
lib.draw_rect(
self.console_c,
x,
y,
width,
height,
ch,
(fg,) if fg is not None else ffi.NULL,
(bg,) if bg is not None else ffi.NULL,
bg_blend,
)
|
python
|
def draw_rect(
self,
x: int,
y: int,
width: int,
height: int,
ch: int,
fg: Optional[Tuple[int, int, int]] = None,
bg: Optional[Tuple[int, int, int]] = None,
bg_blend: int = tcod.constants.BKGND_SET,
) -> None:
"""Draw characters and colors over a rectangular region.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console. You can use negative numbers if you want to
start printing relative to the bottom-right corner, but this behavior
may change in future versions.
`width` and `height` determine the size of the rectangle.
`ch` is a Unicode integer. You can use 0 to leave the current
characters unchanged.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.
`bg_blend` is the blend type used by libtcod.
.. versionadded:: 8.5
.. versionchanged:: 9.0
`fg` and `bg` now default to `None` instead of white-on-black.
"""
x, y = self._pythonic_index(x, y)
lib.draw_rect(
self.console_c,
x,
y,
width,
height,
ch,
(fg,) if fg is not None else ffi.NULL,
(bg,) if bg is not None else ffi.NULL,
bg_blend,
)
|
[
"def",
"draw_rect",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"width",
":",
"int",
",",
"height",
":",
"int",
",",
"ch",
":",
"int",
",",
"fg",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
"=",
"None",
",",
"bg",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
"=",
"None",
",",
"bg_blend",
":",
"int",
"=",
"tcod",
".",
"constants",
".",
"BKGND_SET",
",",
")",
"->",
"None",
":",
"x",
",",
"y",
"=",
"self",
".",
"_pythonic_index",
"(",
"x",
",",
"y",
")",
"lib",
".",
"draw_rect",
"(",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"ch",
",",
"(",
"fg",
",",
")",
"if",
"fg",
"is",
"not",
"None",
"else",
"ffi",
".",
"NULL",
",",
"(",
"bg",
",",
")",
"if",
"bg",
"is",
"not",
"None",
"else",
"ffi",
".",
"NULL",
",",
"bg_blend",
",",
")"
] |
Draw characters and colors over a rectangular region.
`x` and `y` are the starting tile, with ``0,0`` as the upper-left
corner of the console. You can use negative numbers if you want to
start printing relative to the bottom-right corner, but this behavior
may change in future versions.
`width` and `height` determine the size of the rectangle.
`ch` is a Unicode integer. You can use 0 to leave the current
characters unchanged.
`fg` and `bg` are the foreground text color and background tile color
respectfully. This is a 3-item tuple with (r, g, b) color values from
0 to 255. These parameters can also be set to `None` to leave the
colors unchanged.
`bg_blend` is the blend type used by libtcod.
.. versionadded:: 8.5
.. versionchanged:: 9.0
`fg` and `bg` now default to `None` instead of white-on-black.
|
[
"Draw",
"characters",
"and",
"colors",
"over",
"a",
"rectangular",
"region",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/console.py#L1035-L1081
|
9,310
|
libtcod/python-tcod
|
fonts/X11/bdf/bdf2png.py
|
Glyph.blit
|
def blit(self, image, x, y):
"""blit to the image array"""
# adjust the position with the local bbox
x += self.font_bbox[2] - self.bbox[2]
y += self.font_bbox[3] - self.bbox[3]
x += self.font_bbox[0] - self.bbox[0]
y += self.font_bbox[1] - self.bbox[1]
image[y:y+self.height, x:x+self.width] = self.bitmap * 255
|
python
|
def blit(self, image, x, y):
"""blit to the image array"""
# adjust the position with the local bbox
x += self.font_bbox[2] - self.bbox[2]
y += self.font_bbox[3] - self.bbox[3]
x += self.font_bbox[0] - self.bbox[0]
y += self.font_bbox[1] - self.bbox[1]
image[y:y+self.height, x:x+self.width] = self.bitmap * 255
|
[
"def",
"blit",
"(",
"self",
",",
"image",
",",
"x",
",",
"y",
")",
":",
"# adjust the position with the local bbox",
"x",
"+=",
"self",
".",
"font_bbox",
"[",
"2",
"]",
"-",
"self",
".",
"bbox",
"[",
"2",
"]",
"y",
"+=",
"self",
".",
"font_bbox",
"[",
"3",
"]",
"-",
"self",
".",
"bbox",
"[",
"3",
"]",
"x",
"+=",
"self",
".",
"font_bbox",
"[",
"0",
"]",
"-",
"self",
".",
"bbox",
"[",
"0",
"]",
"y",
"+=",
"self",
".",
"font_bbox",
"[",
"1",
"]",
"-",
"self",
".",
"bbox",
"[",
"1",
"]",
"image",
"[",
"y",
":",
"y",
"+",
"self",
".",
"height",
",",
"x",
":",
"x",
"+",
"self",
".",
"width",
"]",
"=",
"self",
".",
"bitmap",
"*",
"255"
] |
blit to the image array
|
[
"blit",
"to",
"the",
"image",
"array"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/fonts/X11/bdf/bdf2png.py#L80-L87
|
9,311
|
libtcod/python-tcod
|
fonts/X11/bdf/bdf2png.py
|
Glyph.parseBits
|
def parseBits(self, hexcode, width):
"""enumerate over bits in a line of data"""
bitarray = []
for byte in hexcode[::-1]:
bits = int(byte, 16)
for x in range(4):
bitarray.append(bool((2 ** x) & bits))
bitarray = bitarray[::-1]
return enumerate(bitarray[:width])
|
python
|
def parseBits(self, hexcode, width):
"""enumerate over bits in a line of data"""
bitarray = []
for byte in hexcode[::-1]:
bits = int(byte, 16)
for x in range(4):
bitarray.append(bool((2 ** x) & bits))
bitarray = bitarray[::-1]
return enumerate(bitarray[:width])
|
[
"def",
"parseBits",
"(",
"self",
",",
"hexcode",
",",
"width",
")",
":",
"bitarray",
"=",
"[",
"]",
"for",
"byte",
"in",
"hexcode",
"[",
":",
":",
"-",
"1",
"]",
":",
"bits",
"=",
"int",
"(",
"byte",
",",
"16",
")",
"for",
"x",
"in",
"range",
"(",
"4",
")",
":",
"bitarray",
".",
"append",
"(",
"bool",
"(",
"(",
"2",
"**",
"x",
")",
"&",
"bits",
")",
")",
"bitarray",
"=",
"bitarray",
"[",
":",
":",
"-",
"1",
"]",
"return",
"enumerate",
"(",
"bitarray",
"[",
":",
"width",
"]",
")"
] |
enumerate over bits in a line of data
|
[
"enumerate",
"over",
"bits",
"in",
"a",
"line",
"of",
"data"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/fonts/X11/bdf/bdf2png.py#L89-L97
|
9,312
|
Netflix-Skunkworks/raven-python-lambda
|
raven_python_lambda/__init__.py
|
memory_warning
|
def memory_warning(config, context):
"""Determines when memory usage is nearing it's max."""
used = psutil.Process(os.getpid()).memory_info().rss / 1048576
limit = float(context.memory_limit_in_mb)
p = used / limit
memory_threshold = config.get('memory_warning_threshold')
if p >= memory_threshold:
config['raven_client'].captureMessage(
'Memory Usage Warning',
level='warning',
extra={
'MemoryLimitInMB': context.memory_limit_in_mb,
'MemoryUsedInMB': math.floor(used)
}
)
else:
# nothing to do check back later
Timer(.5, memory_warning, (config, context)).start()
|
python
|
def memory_warning(config, context):
"""Determines when memory usage is nearing it's max."""
used = psutil.Process(os.getpid()).memory_info().rss / 1048576
limit = float(context.memory_limit_in_mb)
p = used / limit
memory_threshold = config.get('memory_warning_threshold')
if p >= memory_threshold:
config['raven_client'].captureMessage(
'Memory Usage Warning',
level='warning',
extra={
'MemoryLimitInMB': context.memory_limit_in_mb,
'MemoryUsedInMB': math.floor(used)
}
)
else:
# nothing to do check back later
Timer(.5, memory_warning, (config, context)).start()
|
[
"def",
"memory_warning",
"(",
"config",
",",
"context",
")",
":",
"used",
"=",
"psutil",
".",
"Process",
"(",
"os",
".",
"getpid",
"(",
")",
")",
".",
"memory_info",
"(",
")",
".",
"rss",
"/",
"1048576",
"limit",
"=",
"float",
"(",
"context",
".",
"memory_limit_in_mb",
")",
"p",
"=",
"used",
"/",
"limit",
"memory_threshold",
"=",
"config",
".",
"get",
"(",
"'memory_warning_threshold'",
")",
"if",
"p",
">=",
"memory_threshold",
":",
"config",
"[",
"'raven_client'",
"]",
".",
"captureMessage",
"(",
"'Memory Usage Warning'",
",",
"level",
"=",
"'warning'",
",",
"extra",
"=",
"{",
"'MemoryLimitInMB'",
":",
"context",
".",
"memory_limit_in_mb",
",",
"'MemoryUsedInMB'",
":",
"math",
".",
"floor",
"(",
"used",
")",
"}",
")",
"else",
":",
"# nothing to do check back later",
"Timer",
"(",
".5",
",",
"memory_warning",
",",
"(",
"config",
",",
"context",
")",
")",
".",
"start",
"(",
")"
] |
Determines when memory usage is nearing it's max.
|
[
"Determines",
"when",
"memory",
"usage",
"is",
"nearing",
"it",
"s",
"max",
"."
] |
640d5cfcef6e69ea685ca13469cfca71adf0e78c
|
https://github.com/Netflix-Skunkworks/raven-python-lambda/blob/640d5cfcef6e69ea685ca13469cfca71adf0e78c/raven_python_lambda/__init__.py#L233-L252
|
9,313
|
Netflix-Skunkworks/raven-python-lambda
|
raven_python_lambda/__init__.py
|
install_timers
|
def install_timers(config, context):
"""Create the timers as specified by the plugin configuration."""
timers = []
if config.get('capture_timeout_warnings'):
timeout_threshold = config.get('timeout_warning_threshold')
# Schedule the warning at the user specified threshold given in percent.
# ie: 0.50 of 30000 ms = 15000ms
# Schedule the error a few milliseconds before the actual timeout happens.
time_remaining = context.get_remaining_time_in_millis() / 1000
timers.append(Timer(time_remaining * timeout_threshold, timeout_warning, (config, context)))
timers.append(Timer(max(time_remaining - .5, 0), timeout_error, [config]))
if config.get('capture_memory_warnings'):
# Schedule the memory watch dog interval. Warning will re-schedule itself if necessary.
timers.append(Timer(.5, memory_warning, (config, context)))
for t in timers:
t.start()
return timers
|
python
|
def install_timers(config, context):
"""Create the timers as specified by the plugin configuration."""
timers = []
if config.get('capture_timeout_warnings'):
timeout_threshold = config.get('timeout_warning_threshold')
# Schedule the warning at the user specified threshold given in percent.
# ie: 0.50 of 30000 ms = 15000ms
# Schedule the error a few milliseconds before the actual timeout happens.
time_remaining = context.get_remaining_time_in_millis() / 1000
timers.append(Timer(time_remaining * timeout_threshold, timeout_warning, (config, context)))
timers.append(Timer(max(time_remaining - .5, 0), timeout_error, [config]))
if config.get('capture_memory_warnings'):
# Schedule the memory watch dog interval. Warning will re-schedule itself if necessary.
timers.append(Timer(.5, memory_warning, (config, context)))
for t in timers:
t.start()
return timers
|
[
"def",
"install_timers",
"(",
"config",
",",
"context",
")",
":",
"timers",
"=",
"[",
"]",
"if",
"config",
".",
"get",
"(",
"'capture_timeout_warnings'",
")",
":",
"timeout_threshold",
"=",
"config",
".",
"get",
"(",
"'timeout_warning_threshold'",
")",
"# Schedule the warning at the user specified threshold given in percent.",
"# ie: 0.50 of 30000 ms = 15000ms",
"# Schedule the error a few milliseconds before the actual timeout happens.",
"time_remaining",
"=",
"context",
".",
"get_remaining_time_in_millis",
"(",
")",
"/",
"1000",
"timers",
".",
"append",
"(",
"Timer",
"(",
"time_remaining",
"*",
"timeout_threshold",
",",
"timeout_warning",
",",
"(",
"config",
",",
"context",
")",
")",
")",
"timers",
".",
"append",
"(",
"Timer",
"(",
"max",
"(",
"time_remaining",
"-",
".5",
",",
"0",
")",
",",
"timeout_error",
",",
"[",
"config",
"]",
")",
")",
"if",
"config",
".",
"get",
"(",
"'capture_memory_warnings'",
")",
":",
"# Schedule the memory watch dog interval. Warning will re-schedule itself if necessary.",
"timers",
".",
"append",
"(",
"Timer",
"(",
".5",
",",
"memory_warning",
",",
"(",
"config",
",",
"context",
")",
")",
")",
"for",
"t",
"in",
"timers",
":",
"t",
".",
"start",
"(",
")",
"return",
"timers"
] |
Create the timers as specified by the plugin configuration.
|
[
"Create",
"the",
"timers",
"as",
"specified",
"by",
"the",
"plugin",
"configuration",
"."
] |
640d5cfcef6e69ea685ca13469cfca71adf0e78c
|
https://github.com/Netflix-Skunkworks/raven-python-lambda/blob/640d5cfcef6e69ea685ca13469cfca71adf0e78c/raven_python_lambda/__init__.py#L255-L274
|
9,314
|
ellmetha/django-machina
|
machina/templatetags/forum_tags.py
|
recurseforumcontents
|
def recurseforumcontents(parser, token):
""" Iterates over the content nodes and renders the contained forum block for each node. """
bits = token.contents.split()
forums_contents_var = template.Variable(bits[1])
template_nodes = parser.parse(('endrecurseforumcontents',))
parser.delete_first_token()
return RecurseTreeForumVisibilityContentNode(template_nodes, forums_contents_var)
|
python
|
def recurseforumcontents(parser, token):
""" Iterates over the content nodes and renders the contained forum block for each node. """
bits = token.contents.split()
forums_contents_var = template.Variable(bits[1])
template_nodes = parser.parse(('endrecurseforumcontents',))
parser.delete_first_token()
return RecurseTreeForumVisibilityContentNode(template_nodes, forums_contents_var)
|
[
"def",
"recurseforumcontents",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"forums_contents_var",
"=",
"template",
".",
"Variable",
"(",
"bits",
"[",
"1",
"]",
")",
"template_nodes",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endrecurseforumcontents'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"RecurseTreeForumVisibilityContentNode",
"(",
"template_nodes",
",",
"forums_contents_var",
")"
] |
Iterates over the content nodes and renders the contained forum block for each node.
|
[
"Iterates",
"over",
"the",
"content",
"nodes",
"and",
"renders",
"the",
"contained",
"forum",
"block",
"for",
"each",
"node",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_tags.py#L40-L48
|
9,315
|
ellmetha/django-machina
|
machina/templatetags/forum_tags.py
|
forum_list
|
def forum_list(context, forum_visibility_contents):
""" Renders the considered forum list.
This will render the given list of forums by respecting the order and the depth of each
forum in the forums tree.
Usage::
{% forum_list my_forums %}
"""
request = context.get('request')
tracking_handler = TrackingHandler(request=request)
data_dict = {
'forum_contents': forum_visibility_contents,
'unread_forums': tracking_handler.get_unread_forums_from_list(
request.user, forum_visibility_contents.forums),
'user': request.user,
'request': request,
}
root_level = forum_visibility_contents.root_level
if root_level is not None:
data_dict['root_level'] = root_level
data_dict['root_level_middle'] = root_level + 1
data_dict['root_level_sub'] = root_level + 2
return data_dict
|
python
|
def forum_list(context, forum_visibility_contents):
""" Renders the considered forum list.
This will render the given list of forums by respecting the order and the depth of each
forum in the forums tree.
Usage::
{% forum_list my_forums %}
"""
request = context.get('request')
tracking_handler = TrackingHandler(request=request)
data_dict = {
'forum_contents': forum_visibility_contents,
'unread_forums': tracking_handler.get_unread_forums_from_list(
request.user, forum_visibility_contents.forums),
'user': request.user,
'request': request,
}
root_level = forum_visibility_contents.root_level
if root_level is not None:
data_dict['root_level'] = root_level
data_dict['root_level_middle'] = root_level + 1
data_dict['root_level_sub'] = root_level + 2
return data_dict
|
[
"def",
"forum_list",
"(",
"context",
",",
"forum_visibility_contents",
")",
":",
"request",
"=",
"context",
".",
"get",
"(",
"'request'",
")",
"tracking_handler",
"=",
"TrackingHandler",
"(",
"request",
"=",
"request",
")",
"data_dict",
"=",
"{",
"'forum_contents'",
":",
"forum_visibility_contents",
",",
"'unread_forums'",
":",
"tracking_handler",
".",
"get_unread_forums_from_list",
"(",
"request",
".",
"user",
",",
"forum_visibility_contents",
".",
"forums",
")",
",",
"'user'",
":",
"request",
".",
"user",
",",
"'request'",
":",
"request",
",",
"}",
"root_level",
"=",
"forum_visibility_contents",
".",
"root_level",
"if",
"root_level",
"is",
"not",
"None",
":",
"data_dict",
"[",
"'root_level'",
"]",
"=",
"root_level",
"data_dict",
"[",
"'root_level_middle'",
"]",
"=",
"root_level",
"+",
"1",
"data_dict",
"[",
"'root_level_sub'",
"]",
"=",
"root_level",
"+",
"2",
"return",
"data_dict"
] |
Renders the considered forum list.
This will render the given list of forums by respecting the order and the depth of each
forum in the forums tree.
Usage::
{% forum_list my_forums %}
|
[
"Renders",
"the",
"considered",
"forum",
"list",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_tags.py#L52-L80
|
9,316
|
ellmetha/django-machina
|
machina/apps/forum_feeds/feeds.py
|
LastTopicsFeed.get_object
|
def get_object(self, request, *args, **kwargs):
""" Handles the considered object. """
forum_pk = kwargs.get('forum_pk', None)
descendants = kwargs.get('descendants', None)
self.user = request.user
if forum_pk:
forum = get_object_or_404(Forum, pk=forum_pk)
forums_qs = (
forum.get_descendants(include_self=True)
if descendants else Forum.objects.filter(pk=forum_pk)
)
self.forums = request.forum_permission_handler.get_readable_forums(
forums_qs, request.user,
)
else:
self.forums = request.forum_permission_handler.get_readable_forums(
Forum.objects.all(), request.user,
)
|
python
|
def get_object(self, request, *args, **kwargs):
""" Handles the considered object. """
forum_pk = kwargs.get('forum_pk', None)
descendants = kwargs.get('descendants', None)
self.user = request.user
if forum_pk:
forum = get_object_or_404(Forum, pk=forum_pk)
forums_qs = (
forum.get_descendants(include_self=True)
if descendants else Forum.objects.filter(pk=forum_pk)
)
self.forums = request.forum_permission_handler.get_readable_forums(
forums_qs, request.user,
)
else:
self.forums = request.forum_permission_handler.get_readable_forums(
Forum.objects.all(), request.user,
)
|
[
"def",
"get_object",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"forum_pk",
"=",
"kwargs",
".",
"get",
"(",
"'forum_pk'",
",",
"None",
")",
"descendants",
"=",
"kwargs",
".",
"get",
"(",
"'descendants'",
",",
"None",
")",
"self",
".",
"user",
"=",
"request",
".",
"user",
"if",
"forum_pk",
":",
"forum",
"=",
"get_object_or_404",
"(",
"Forum",
",",
"pk",
"=",
"forum_pk",
")",
"forums_qs",
"=",
"(",
"forum",
".",
"get_descendants",
"(",
"include_self",
"=",
"True",
")",
"if",
"descendants",
"else",
"Forum",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"forum_pk",
")",
")",
"self",
".",
"forums",
"=",
"request",
".",
"forum_permission_handler",
".",
"get_readable_forums",
"(",
"forums_qs",
",",
"request",
".",
"user",
",",
")",
"else",
":",
"self",
".",
"forums",
"=",
"request",
".",
"forum_permission_handler",
".",
"get_readable_forums",
"(",
"Forum",
".",
"objects",
".",
"all",
"(",
")",
",",
"request",
".",
"user",
",",
")"
] |
Handles the considered object.
|
[
"Handles",
"the",
"considered",
"object",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_feeds/feeds.py#L34-L52
|
9,317
|
ellmetha/django-machina
|
machina/apps/forum_feeds/feeds.py
|
LastTopicsFeed.items
|
def items(self):
""" Returns the items to include into the feed. """
return Topic.objects.filter(forum__in=self.forums, approved=True).order_by('-last_post_on')
|
python
|
def items(self):
""" Returns the items to include into the feed. """
return Topic.objects.filter(forum__in=self.forums, approved=True).order_by('-last_post_on')
|
[
"def",
"items",
"(",
"self",
")",
":",
"return",
"Topic",
".",
"objects",
".",
"filter",
"(",
"forum__in",
"=",
"self",
".",
"forums",
",",
"approved",
"=",
"True",
")",
".",
"order_by",
"(",
"'-last_post_on'",
")"
] |
Returns the items to include into the feed.
|
[
"Returns",
"the",
"items",
"to",
"include",
"into",
"the",
"feed",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_feeds/feeds.py#L54-L56
|
9,318
|
ellmetha/django-machina
|
machina/apps/forum_feeds/feeds.py
|
LastTopicsFeed.item_link
|
def item_link(self, item):
""" Generates a link for a specific item of the feed. """
return reverse_lazy(
'forum_conversation:topic',
kwargs={
'forum_slug': item.forum.slug,
'forum_pk': item.forum.pk,
'slug': item.slug,
'pk': item.id,
},
)
|
python
|
def item_link(self, item):
""" Generates a link for a specific item of the feed. """
return reverse_lazy(
'forum_conversation:topic',
kwargs={
'forum_slug': item.forum.slug,
'forum_pk': item.forum.pk,
'slug': item.slug,
'pk': item.id,
},
)
|
[
"def",
"item_link",
"(",
"self",
",",
"item",
")",
":",
"return",
"reverse_lazy",
"(",
"'forum_conversation:topic'",
",",
"kwargs",
"=",
"{",
"'forum_slug'",
":",
"item",
".",
"forum",
".",
"slug",
",",
"'forum_pk'",
":",
"item",
".",
"forum",
".",
"pk",
",",
"'slug'",
":",
"item",
".",
"slug",
",",
"'pk'",
":",
"item",
".",
"id",
",",
"}",
",",
")"
] |
Generates a link for a specific item of the feed.
|
[
"Generates",
"a",
"link",
"for",
"a",
"specific",
"item",
"of",
"the",
"feed",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_feeds/feeds.py#L58-L68
|
9,319
|
ellmetha/django-machina
|
machina/templatetags/forum_conversation_tags.py
|
topic_pages_inline_list
|
def topic_pages_inline_list(topic):
""" This will render an inline pagination for the posts related to the given topic.
Usage::
{% topic_pages_inline_list my_topic %}
"""
data_dict = {
'topic': topic,
}
pages_number = ((topic.posts_count - 1) // machina_settings.TOPIC_POSTS_NUMBER_PER_PAGE) + 1
if pages_number > 5:
data_dict['first_pages'] = range(1, 5)
data_dict['last_page'] = pages_number
elif pages_number > 1:
data_dict['first_pages'] = range(1, pages_number + 1)
return data_dict
|
python
|
def topic_pages_inline_list(topic):
""" This will render an inline pagination for the posts related to the given topic.
Usage::
{% topic_pages_inline_list my_topic %}
"""
data_dict = {
'topic': topic,
}
pages_number = ((topic.posts_count - 1) // machina_settings.TOPIC_POSTS_NUMBER_PER_PAGE) + 1
if pages_number > 5:
data_dict['first_pages'] = range(1, 5)
data_dict['last_page'] = pages_number
elif pages_number > 1:
data_dict['first_pages'] = range(1, pages_number + 1)
return data_dict
|
[
"def",
"topic_pages_inline_list",
"(",
"topic",
")",
":",
"data_dict",
"=",
"{",
"'topic'",
":",
"topic",
",",
"}",
"pages_number",
"=",
"(",
"(",
"topic",
".",
"posts_count",
"-",
"1",
")",
"//",
"machina_settings",
".",
"TOPIC_POSTS_NUMBER_PER_PAGE",
")",
"+",
"1",
"if",
"pages_number",
">",
"5",
":",
"data_dict",
"[",
"'first_pages'",
"]",
"=",
"range",
"(",
"1",
",",
"5",
")",
"data_dict",
"[",
"'last_page'",
"]",
"=",
"pages_number",
"elif",
"pages_number",
">",
"1",
":",
"data_dict",
"[",
"'first_pages'",
"]",
"=",
"range",
"(",
"1",
",",
"pages_number",
"+",
"1",
")",
"return",
"data_dict"
] |
This will render an inline pagination for the posts related to the given topic.
Usage::
{% topic_pages_inline_list my_topic %}
|
[
"This",
"will",
"render",
"an",
"inline",
"pagination",
"for",
"the",
"posts",
"related",
"to",
"the",
"given",
"topic",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_conversation_tags.py#L22-L41
|
9,320
|
ellmetha/django-machina
|
machina/apps/forum/admin.py
|
ForumAdmin.get_urls
|
def get_urls(self):
""" Returns the URLs associated with the admin abstraction. """
urls = super().get_urls()
forum_admin_urls = [
url(
r'^(?P<forum_id>[0-9]+)/move-forum/(?P<direction>up|down)/$',
self.admin_site.admin_view(self.moveforum_view),
name='forum_forum_move',
),
url(
r'^edit-global-permissions/$',
self.admin_site.admin_view(self.editpermissions_index_view),
name='forum_forum_editpermission_index',
),
url(
r'^edit-global-permissions/user/(?P<user_id>[0-9]+)/$',
self.admin_site.admin_view(self.editpermissions_user_view),
name='forum_forum_editpermission_user',
),
url(
r'^edit-global-permissions/user/anonymous/$',
self.admin_site.admin_view(self.editpermissions_anonymous_user_view),
name='forum_forum_editpermission_anonymous_user',
),
url(
r'^edit-global-permissions/group/(?P<group_id>[0-9]+)/$',
self.admin_site.admin_view(self.editpermissions_group_view),
name='forum_forum_editpermission_group',
),
url(
r'^(?P<forum_id>[0-9]+)/edit-permissions/$',
self.admin_site.admin_view(self.editpermissions_index_view),
name='forum_forum_editpermission_index',
),
url(
r'^(?P<forum_id>[0-9]+)/edit-permissions/user/(?P<user_id>[0-9]+)/$',
self.admin_site.admin_view(self.editpermissions_user_view),
name='forum_forum_editpermission_user',
),
url(
r'^(?P<forum_id>[0-9]+)/edit-permissions/user/anonymous/$',
self.admin_site.admin_view(self.editpermissions_anonymous_user_view),
name='forum_forum_editpermission_anonymous_user',
),
url(
r'^(?P<forum_id>[0-9]+)/edit-permissions/group/(?P<group_id>[0-9]+)/$',
self.admin_site.admin_view(self.editpermissions_group_view),
name='forum_forum_editpermission_group',
),
]
return forum_admin_urls + urls
|
python
|
def get_urls(self):
""" Returns the URLs associated with the admin abstraction. """
urls = super().get_urls()
forum_admin_urls = [
url(
r'^(?P<forum_id>[0-9]+)/move-forum/(?P<direction>up|down)/$',
self.admin_site.admin_view(self.moveforum_view),
name='forum_forum_move',
),
url(
r'^edit-global-permissions/$',
self.admin_site.admin_view(self.editpermissions_index_view),
name='forum_forum_editpermission_index',
),
url(
r'^edit-global-permissions/user/(?P<user_id>[0-9]+)/$',
self.admin_site.admin_view(self.editpermissions_user_view),
name='forum_forum_editpermission_user',
),
url(
r'^edit-global-permissions/user/anonymous/$',
self.admin_site.admin_view(self.editpermissions_anonymous_user_view),
name='forum_forum_editpermission_anonymous_user',
),
url(
r'^edit-global-permissions/group/(?P<group_id>[0-9]+)/$',
self.admin_site.admin_view(self.editpermissions_group_view),
name='forum_forum_editpermission_group',
),
url(
r'^(?P<forum_id>[0-9]+)/edit-permissions/$',
self.admin_site.admin_view(self.editpermissions_index_view),
name='forum_forum_editpermission_index',
),
url(
r'^(?P<forum_id>[0-9]+)/edit-permissions/user/(?P<user_id>[0-9]+)/$',
self.admin_site.admin_view(self.editpermissions_user_view),
name='forum_forum_editpermission_user',
),
url(
r'^(?P<forum_id>[0-9]+)/edit-permissions/user/anonymous/$',
self.admin_site.admin_view(self.editpermissions_anonymous_user_view),
name='forum_forum_editpermission_anonymous_user',
),
url(
r'^(?P<forum_id>[0-9]+)/edit-permissions/group/(?P<group_id>[0-9]+)/$',
self.admin_site.admin_view(self.editpermissions_group_view),
name='forum_forum_editpermission_group',
),
]
return forum_admin_urls + urls
|
[
"def",
"get_urls",
"(",
"self",
")",
":",
"urls",
"=",
"super",
"(",
")",
".",
"get_urls",
"(",
")",
"forum_admin_urls",
"=",
"[",
"url",
"(",
"r'^(?P<forum_id>[0-9]+)/move-forum/(?P<direction>up|down)/$'",
",",
"self",
".",
"admin_site",
".",
"admin_view",
"(",
"self",
".",
"moveforum_view",
")",
",",
"name",
"=",
"'forum_forum_move'",
",",
")",
",",
"url",
"(",
"r'^edit-global-permissions/$'",
",",
"self",
".",
"admin_site",
".",
"admin_view",
"(",
"self",
".",
"editpermissions_index_view",
")",
",",
"name",
"=",
"'forum_forum_editpermission_index'",
",",
")",
",",
"url",
"(",
"r'^edit-global-permissions/user/(?P<user_id>[0-9]+)/$'",
",",
"self",
".",
"admin_site",
".",
"admin_view",
"(",
"self",
".",
"editpermissions_user_view",
")",
",",
"name",
"=",
"'forum_forum_editpermission_user'",
",",
")",
",",
"url",
"(",
"r'^edit-global-permissions/user/anonymous/$'",
",",
"self",
".",
"admin_site",
".",
"admin_view",
"(",
"self",
".",
"editpermissions_anonymous_user_view",
")",
",",
"name",
"=",
"'forum_forum_editpermission_anonymous_user'",
",",
")",
",",
"url",
"(",
"r'^edit-global-permissions/group/(?P<group_id>[0-9]+)/$'",
",",
"self",
".",
"admin_site",
".",
"admin_view",
"(",
"self",
".",
"editpermissions_group_view",
")",
",",
"name",
"=",
"'forum_forum_editpermission_group'",
",",
")",
",",
"url",
"(",
"r'^(?P<forum_id>[0-9]+)/edit-permissions/$'",
",",
"self",
".",
"admin_site",
".",
"admin_view",
"(",
"self",
".",
"editpermissions_index_view",
")",
",",
"name",
"=",
"'forum_forum_editpermission_index'",
",",
")",
",",
"url",
"(",
"r'^(?P<forum_id>[0-9]+)/edit-permissions/user/(?P<user_id>[0-9]+)/$'",
",",
"self",
".",
"admin_site",
".",
"admin_view",
"(",
"self",
".",
"editpermissions_user_view",
")",
",",
"name",
"=",
"'forum_forum_editpermission_user'",
",",
")",
",",
"url",
"(",
"r'^(?P<forum_id>[0-9]+)/edit-permissions/user/anonymous/$'",
",",
"self",
".",
"admin_site",
".",
"admin_view",
"(",
"self",
".",
"editpermissions_anonymous_user_view",
")",
",",
"name",
"=",
"'forum_forum_editpermission_anonymous_user'",
",",
")",
",",
"url",
"(",
"r'^(?P<forum_id>[0-9]+)/edit-permissions/group/(?P<group_id>[0-9]+)/$'",
",",
"self",
".",
"admin_site",
".",
"admin_view",
"(",
"self",
".",
"editpermissions_group_view",
")",
",",
"name",
"=",
"'forum_forum_editpermission_group'",
",",
")",
",",
"]",
"return",
"forum_admin_urls",
"+",
"urls"
] |
Returns the URLs associated with the admin abstraction.
|
[
"Returns",
"the",
"URLs",
"associated",
"with",
"the",
"admin",
"abstraction",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L66-L116
|
9,321
|
ellmetha/django-machina
|
machina/apps/forum/admin.py
|
ForumAdmin.get_forum_perms_base_context
|
def get_forum_perms_base_context(self, request, obj=None):
""" Returns the context to provide to the template for permissions contents. """
context = {
'adminform': {'model_admin': self},
'media': self.media,
'object': obj,
'app_label': self.model._meta.app_label,
'opts': self.model._meta,
'has_change_permission': self.has_change_permission(request, obj),
}
try:
context.update(self.admin_site.each_context(request))
except TypeError: # pragma: no cover
# Django 1.7 compatibility
context.update(self.admin_site.each_context())
except AttributeError: # pragma: no cover
pass
return context
|
python
|
def get_forum_perms_base_context(self, request, obj=None):
""" Returns the context to provide to the template for permissions contents. """
context = {
'adminform': {'model_admin': self},
'media': self.media,
'object': obj,
'app_label': self.model._meta.app_label,
'opts': self.model._meta,
'has_change_permission': self.has_change_permission(request, obj),
}
try:
context.update(self.admin_site.each_context(request))
except TypeError: # pragma: no cover
# Django 1.7 compatibility
context.update(self.admin_site.each_context())
except AttributeError: # pragma: no cover
pass
return context
|
[
"def",
"get_forum_perms_base_context",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"context",
"=",
"{",
"'adminform'",
":",
"{",
"'model_admin'",
":",
"self",
"}",
",",
"'media'",
":",
"self",
".",
"media",
",",
"'object'",
":",
"obj",
",",
"'app_label'",
":",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
",",
"'opts'",
":",
"self",
".",
"model",
".",
"_meta",
",",
"'has_change_permission'",
":",
"self",
".",
"has_change_permission",
"(",
"request",
",",
"obj",
")",
",",
"}",
"try",
":",
"context",
".",
"update",
"(",
"self",
".",
"admin_site",
".",
"each_context",
"(",
"request",
")",
")",
"except",
"TypeError",
":",
"# pragma: no cover",
"# Django 1.7 compatibility",
"context",
".",
"update",
"(",
"self",
".",
"admin_site",
".",
"each_context",
"(",
")",
")",
"except",
"AttributeError",
":",
"# pragma: no cover",
"pass",
"return",
"context"
] |
Returns the context to provide to the template for permissions contents.
|
[
"Returns",
"the",
"context",
"to",
"provide",
"to",
"the",
"template",
"for",
"permissions",
"contents",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L118-L135
|
9,322
|
ellmetha/django-machina
|
machina/apps/forum/admin.py
|
ForumAdmin.moveforum_view
|
def moveforum_view(self, request, forum_id, direction):
""" Moves the given forum toward the requested direction. """
forum = get_object_or_404(Forum, pk=forum_id)
# Fetch the target
target, position = None, None
if direction == 'up':
target, position = forum.get_previous_sibling(), 'left'
elif direction == 'down':
target, position = forum.get_next_sibling(), 'right'
# Do the move
try:
assert target is not None
forum.move_to(target, position)
except (InvalidMove, AssertionError):
pass
self.message_user(request, _("'{}' forum successfully moved").format(forum.name))
return HttpResponseRedirect(reverse('admin:forum_forum_changelist'))
|
python
|
def moveforum_view(self, request, forum_id, direction):
""" Moves the given forum toward the requested direction. """
forum = get_object_or_404(Forum, pk=forum_id)
# Fetch the target
target, position = None, None
if direction == 'up':
target, position = forum.get_previous_sibling(), 'left'
elif direction == 'down':
target, position = forum.get_next_sibling(), 'right'
# Do the move
try:
assert target is not None
forum.move_to(target, position)
except (InvalidMove, AssertionError):
pass
self.message_user(request, _("'{}' forum successfully moved").format(forum.name))
return HttpResponseRedirect(reverse('admin:forum_forum_changelist'))
|
[
"def",
"moveforum_view",
"(",
"self",
",",
"request",
",",
"forum_id",
",",
"direction",
")",
":",
"forum",
"=",
"get_object_or_404",
"(",
"Forum",
",",
"pk",
"=",
"forum_id",
")",
"# Fetch the target",
"target",
",",
"position",
"=",
"None",
",",
"None",
"if",
"direction",
"==",
"'up'",
":",
"target",
",",
"position",
"=",
"forum",
".",
"get_previous_sibling",
"(",
")",
",",
"'left'",
"elif",
"direction",
"==",
"'down'",
":",
"target",
",",
"position",
"=",
"forum",
".",
"get_next_sibling",
"(",
")",
",",
"'right'",
"# Do the move",
"try",
":",
"assert",
"target",
"is",
"not",
"None",
"forum",
".",
"move_to",
"(",
"target",
",",
"position",
")",
"except",
"(",
"InvalidMove",
",",
"AssertionError",
")",
":",
"pass",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"\"'{}' forum successfully moved\"",
")",
".",
"format",
"(",
"forum",
".",
"name",
")",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'admin:forum_forum_changelist'",
")",
")"
] |
Moves the given forum toward the requested direction.
|
[
"Moves",
"the",
"given",
"forum",
"toward",
"the",
"requested",
"direction",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L137-L155
|
9,323
|
ellmetha/django-machina
|
machina/apps/forum/admin.py
|
ForumAdmin.editpermissions_index_view
|
def editpermissions_index_view(self, request, forum_id=None):
""" Allows to select how to edit forum permissions.
The view displays a form to select a user or a group in order to edit its permissions for
the considered forum.
"""
forum = get_object_or_404(Forum, pk=forum_id) if forum_id \
else None
# Set up the context
context = self.get_forum_perms_base_context(request, forum)
context['forum'] = forum
context['title'] = _('Forum permissions') if forum else _('Global forum permissions')
# Handles "copy permission from" form
permissions_copied = False
if forum and request.method == 'POST':
forum_form = PickForumForm(request.POST)
if forum_form.is_valid() and forum_form.cleaned_data['forum']:
self._copy_forum_permissions(forum_form.cleaned_data['forum'], forum)
self.message_user(request, _('Permissions successfully copied'))
permissions_copied = True
context['forum_form'] = forum_form
elif forum:
context['forum_form'] = PickForumForm()
# Handles user or group selection
if request.method == 'POST' and not permissions_copied:
user_form = PickUserForm(request.POST, admin_site=self.admin_site)
group_form = PickGroupForm(request.POST, admin_site=self.admin_site)
if user_form.is_valid() and group_form.is_valid():
user = user_form.cleaned_data.get('user', None) if user_form.cleaned_data else None
anonymous_user = (
user_form.cleaned_data.get('anonymous_user', None)
if user_form.cleaned_data else None
)
group = (
group_form.cleaned_data.get('group', None)
if group_form.cleaned_data else None
)
if not user and not anonymous_user and not group:
user_form._errors[NON_FIELD_ERRORS] = user_form.error_class(
[_('Choose either a user ID, a group ID or the anonymous user'), ])
elif user:
# Redirect to user
url_kwargs = (
{'forum_id': forum.id, 'user_id': user.id}
if forum else {'user_id': user.id}
)
return redirect(
reverse('admin:forum_forum_editpermission_user', kwargs=url_kwargs),
)
elif anonymous_user:
# Redirect to anonymous user
url_kwargs = {'forum_id': forum.id} if forum else {}
return redirect(
reverse(
'admin:forum_forum_editpermission_anonymous_user',
kwargs=url_kwargs,
),
)
elif group:
# Redirect to group
url_kwargs = (
{'forum_id': forum.id, 'group_id': group.id}
if forum else {'group_id': group.id}
)
return redirect(
reverse('admin:forum_forum_editpermission_group', kwargs=url_kwargs),
)
context['user_errors'] = helpers.AdminErrorList(user_form, [])
context['group_errors'] = helpers.AdminErrorList(group_form, [])
else:
user_form = PickUserForm(admin_site=self.admin_site)
group_form = PickGroupForm(admin_site=self.admin_site)
context['user_form'] = user_form
context['group_form'] = group_form
return render(request, self.editpermissions_index_view_template_name, context)
|
python
|
def editpermissions_index_view(self, request, forum_id=None):
""" Allows to select how to edit forum permissions.
The view displays a form to select a user or a group in order to edit its permissions for
the considered forum.
"""
forum = get_object_or_404(Forum, pk=forum_id) if forum_id \
else None
# Set up the context
context = self.get_forum_perms_base_context(request, forum)
context['forum'] = forum
context['title'] = _('Forum permissions') if forum else _('Global forum permissions')
# Handles "copy permission from" form
permissions_copied = False
if forum and request.method == 'POST':
forum_form = PickForumForm(request.POST)
if forum_form.is_valid() and forum_form.cleaned_data['forum']:
self._copy_forum_permissions(forum_form.cleaned_data['forum'], forum)
self.message_user(request, _('Permissions successfully copied'))
permissions_copied = True
context['forum_form'] = forum_form
elif forum:
context['forum_form'] = PickForumForm()
# Handles user or group selection
if request.method == 'POST' and not permissions_copied:
user_form = PickUserForm(request.POST, admin_site=self.admin_site)
group_form = PickGroupForm(request.POST, admin_site=self.admin_site)
if user_form.is_valid() and group_form.is_valid():
user = user_form.cleaned_data.get('user', None) if user_form.cleaned_data else None
anonymous_user = (
user_form.cleaned_data.get('anonymous_user', None)
if user_form.cleaned_data else None
)
group = (
group_form.cleaned_data.get('group', None)
if group_form.cleaned_data else None
)
if not user and not anonymous_user and not group:
user_form._errors[NON_FIELD_ERRORS] = user_form.error_class(
[_('Choose either a user ID, a group ID or the anonymous user'), ])
elif user:
# Redirect to user
url_kwargs = (
{'forum_id': forum.id, 'user_id': user.id}
if forum else {'user_id': user.id}
)
return redirect(
reverse('admin:forum_forum_editpermission_user', kwargs=url_kwargs),
)
elif anonymous_user:
# Redirect to anonymous user
url_kwargs = {'forum_id': forum.id} if forum else {}
return redirect(
reverse(
'admin:forum_forum_editpermission_anonymous_user',
kwargs=url_kwargs,
),
)
elif group:
# Redirect to group
url_kwargs = (
{'forum_id': forum.id, 'group_id': group.id}
if forum else {'group_id': group.id}
)
return redirect(
reverse('admin:forum_forum_editpermission_group', kwargs=url_kwargs),
)
context['user_errors'] = helpers.AdminErrorList(user_form, [])
context['group_errors'] = helpers.AdminErrorList(group_form, [])
else:
user_form = PickUserForm(admin_site=self.admin_site)
group_form = PickGroupForm(admin_site=self.admin_site)
context['user_form'] = user_form
context['group_form'] = group_form
return render(request, self.editpermissions_index_view_template_name, context)
|
[
"def",
"editpermissions_index_view",
"(",
"self",
",",
"request",
",",
"forum_id",
"=",
"None",
")",
":",
"forum",
"=",
"get_object_or_404",
"(",
"Forum",
",",
"pk",
"=",
"forum_id",
")",
"if",
"forum_id",
"else",
"None",
"# Set up the context",
"context",
"=",
"self",
".",
"get_forum_perms_base_context",
"(",
"request",
",",
"forum",
")",
"context",
"[",
"'forum'",
"]",
"=",
"forum",
"context",
"[",
"'title'",
"]",
"=",
"_",
"(",
"'Forum permissions'",
")",
"if",
"forum",
"else",
"_",
"(",
"'Global forum permissions'",
")",
"# Handles \"copy permission from\" form",
"permissions_copied",
"=",
"False",
"if",
"forum",
"and",
"request",
".",
"method",
"==",
"'POST'",
":",
"forum_form",
"=",
"PickForumForm",
"(",
"request",
".",
"POST",
")",
"if",
"forum_form",
".",
"is_valid",
"(",
")",
"and",
"forum_form",
".",
"cleaned_data",
"[",
"'forum'",
"]",
":",
"self",
".",
"_copy_forum_permissions",
"(",
"forum_form",
".",
"cleaned_data",
"[",
"'forum'",
"]",
",",
"forum",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"'Permissions successfully copied'",
")",
")",
"permissions_copied",
"=",
"True",
"context",
"[",
"'forum_form'",
"]",
"=",
"forum_form",
"elif",
"forum",
":",
"context",
"[",
"'forum_form'",
"]",
"=",
"PickForumForm",
"(",
")",
"# Handles user or group selection",
"if",
"request",
".",
"method",
"==",
"'POST'",
"and",
"not",
"permissions_copied",
":",
"user_form",
"=",
"PickUserForm",
"(",
"request",
".",
"POST",
",",
"admin_site",
"=",
"self",
".",
"admin_site",
")",
"group_form",
"=",
"PickGroupForm",
"(",
"request",
".",
"POST",
",",
"admin_site",
"=",
"self",
".",
"admin_site",
")",
"if",
"user_form",
".",
"is_valid",
"(",
")",
"and",
"group_form",
".",
"is_valid",
"(",
")",
":",
"user",
"=",
"user_form",
".",
"cleaned_data",
".",
"get",
"(",
"'user'",
",",
"None",
")",
"if",
"user_form",
".",
"cleaned_data",
"else",
"None",
"anonymous_user",
"=",
"(",
"user_form",
".",
"cleaned_data",
".",
"get",
"(",
"'anonymous_user'",
",",
"None",
")",
"if",
"user_form",
".",
"cleaned_data",
"else",
"None",
")",
"group",
"=",
"(",
"group_form",
".",
"cleaned_data",
".",
"get",
"(",
"'group'",
",",
"None",
")",
"if",
"group_form",
".",
"cleaned_data",
"else",
"None",
")",
"if",
"not",
"user",
"and",
"not",
"anonymous_user",
"and",
"not",
"group",
":",
"user_form",
".",
"_errors",
"[",
"NON_FIELD_ERRORS",
"]",
"=",
"user_form",
".",
"error_class",
"(",
"[",
"_",
"(",
"'Choose either a user ID, a group ID or the anonymous user'",
")",
",",
"]",
")",
"elif",
"user",
":",
"# Redirect to user",
"url_kwargs",
"=",
"(",
"{",
"'forum_id'",
":",
"forum",
".",
"id",
",",
"'user_id'",
":",
"user",
".",
"id",
"}",
"if",
"forum",
"else",
"{",
"'user_id'",
":",
"user",
".",
"id",
"}",
")",
"return",
"redirect",
"(",
"reverse",
"(",
"'admin:forum_forum_editpermission_user'",
",",
"kwargs",
"=",
"url_kwargs",
")",
",",
")",
"elif",
"anonymous_user",
":",
"# Redirect to anonymous user",
"url_kwargs",
"=",
"{",
"'forum_id'",
":",
"forum",
".",
"id",
"}",
"if",
"forum",
"else",
"{",
"}",
"return",
"redirect",
"(",
"reverse",
"(",
"'admin:forum_forum_editpermission_anonymous_user'",
",",
"kwargs",
"=",
"url_kwargs",
",",
")",
",",
")",
"elif",
"group",
":",
"# Redirect to group",
"url_kwargs",
"=",
"(",
"{",
"'forum_id'",
":",
"forum",
".",
"id",
",",
"'group_id'",
":",
"group",
".",
"id",
"}",
"if",
"forum",
"else",
"{",
"'group_id'",
":",
"group",
".",
"id",
"}",
")",
"return",
"redirect",
"(",
"reverse",
"(",
"'admin:forum_forum_editpermission_group'",
",",
"kwargs",
"=",
"url_kwargs",
")",
",",
")",
"context",
"[",
"'user_errors'",
"]",
"=",
"helpers",
".",
"AdminErrorList",
"(",
"user_form",
",",
"[",
"]",
")",
"context",
"[",
"'group_errors'",
"]",
"=",
"helpers",
".",
"AdminErrorList",
"(",
"group_form",
",",
"[",
"]",
")",
"else",
":",
"user_form",
"=",
"PickUserForm",
"(",
"admin_site",
"=",
"self",
".",
"admin_site",
")",
"group_form",
"=",
"PickGroupForm",
"(",
"admin_site",
"=",
"self",
".",
"admin_site",
")",
"context",
"[",
"'user_form'",
"]",
"=",
"user_form",
"context",
"[",
"'group_form'",
"]",
"=",
"group_form",
"return",
"render",
"(",
"request",
",",
"self",
".",
"editpermissions_index_view_template_name",
",",
"context",
")"
] |
Allows to select how to edit forum permissions.
The view displays a form to select a user or a group in order to edit its permissions for
the considered forum.
|
[
"Allows",
"to",
"select",
"how",
"to",
"edit",
"forum",
"permissions",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L157-L240
|
9,324
|
ellmetha/django-machina
|
machina/apps/forum/admin.py
|
ForumAdmin.editpermissions_user_view
|
def editpermissions_user_view(self, request, user_id, forum_id=None):
""" Allows to edit user permissions for the considered forum.
The view displays a form to define which permissions are granted for the given user for the
considered forum.
"""
user_model = get_user_model()
user = get_object_or_404(user_model, pk=user_id)
forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None
# Set up the context
context = self.get_forum_perms_base_context(request, forum)
context['forum'] = forum
context['title'] = '{} - {}'.format(_('Forum permissions'), user)
context['form'] = self._get_permissions_form(
request, UserForumPermission, {'forum': forum, 'user': user},
)
return render(request, self.editpermissions_user_view_template_name, context)
|
python
|
def editpermissions_user_view(self, request, user_id, forum_id=None):
""" Allows to edit user permissions for the considered forum.
The view displays a form to define which permissions are granted for the given user for the
considered forum.
"""
user_model = get_user_model()
user = get_object_or_404(user_model, pk=user_id)
forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None
# Set up the context
context = self.get_forum_perms_base_context(request, forum)
context['forum'] = forum
context['title'] = '{} - {}'.format(_('Forum permissions'), user)
context['form'] = self._get_permissions_form(
request, UserForumPermission, {'forum': forum, 'user': user},
)
return render(request, self.editpermissions_user_view_template_name, context)
|
[
"def",
"editpermissions_user_view",
"(",
"self",
",",
"request",
",",
"user_id",
",",
"forum_id",
"=",
"None",
")",
":",
"user_model",
"=",
"get_user_model",
"(",
")",
"user",
"=",
"get_object_or_404",
"(",
"user_model",
",",
"pk",
"=",
"user_id",
")",
"forum",
"=",
"get_object_or_404",
"(",
"Forum",
",",
"pk",
"=",
"forum_id",
")",
"if",
"forum_id",
"else",
"None",
"# Set up the context",
"context",
"=",
"self",
".",
"get_forum_perms_base_context",
"(",
"request",
",",
"forum",
")",
"context",
"[",
"'forum'",
"]",
"=",
"forum",
"context",
"[",
"'title'",
"]",
"=",
"'{} - {}'",
".",
"format",
"(",
"_",
"(",
"'Forum permissions'",
")",
",",
"user",
")",
"context",
"[",
"'form'",
"]",
"=",
"self",
".",
"_get_permissions_form",
"(",
"request",
",",
"UserForumPermission",
",",
"{",
"'forum'",
":",
"forum",
",",
"'user'",
":",
"user",
"}",
",",
")",
"return",
"render",
"(",
"request",
",",
"self",
".",
"editpermissions_user_view_template_name",
",",
"context",
")"
] |
Allows to edit user permissions for the considered forum.
The view displays a form to define which permissions are granted for the given user for the
considered forum.
|
[
"Allows",
"to",
"edit",
"user",
"permissions",
"for",
"the",
"considered",
"forum",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L242-L261
|
9,325
|
ellmetha/django-machina
|
machina/apps/forum/admin.py
|
ForumAdmin.editpermissions_anonymous_user_view
|
def editpermissions_anonymous_user_view(self, request, forum_id=None):
""" Allows to edit anonymous user permissions for the considered forum.
The view displays a form to define which permissions are granted for the anonymous user for
the considered forum.
"""
forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None
# Set up the context
context = self.get_forum_perms_base_context(request, forum)
context['forum'] = forum
context['title'] = '{} - {}'.format(_('Forum permissions'), _('Anonymous user'))
context['form'] = self._get_permissions_form(
request, UserForumPermission, {'forum': forum, 'anonymous_user': True},
)
return render(request, self.editpermissions_anonymous_user_view_template_name, context)
|
python
|
def editpermissions_anonymous_user_view(self, request, forum_id=None):
""" Allows to edit anonymous user permissions for the considered forum.
The view displays a form to define which permissions are granted for the anonymous user for
the considered forum.
"""
forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None
# Set up the context
context = self.get_forum_perms_base_context(request, forum)
context['forum'] = forum
context['title'] = '{} - {}'.format(_('Forum permissions'), _('Anonymous user'))
context['form'] = self._get_permissions_form(
request, UserForumPermission, {'forum': forum, 'anonymous_user': True},
)
return render(request, self.editpermissions_anonymous_user_view_template_name, context)
|
[
"def",
"editpermissions_anonymous_user_view",
"(",
"self",
",",
"request",
",",
"forum_id",
"=",
"None",
")",
":",
"forum",
"=",
"get_object_or_404",
"(",
"Forum",
",",
"pk",
"=",
"forum_id",
")",
"if",
"forum_id",
"else",
"None",
"# Set up the context",
"context",
"=",
"self",
".",
"get_forum_perms_base_context",
"(",
"request",
",",
"forum",
")",
"context",
"[",
"'forum'",
"]",
"=",
"forum",
"context",
"[",
"'title'",
"]",
"=",
"'{} - {}'",
".",
"format",
"(",
"_",
"(",
"'Forum permissions'",
")",
",",
"_",
"(",
"'Anonymous user'",
")",
")",
"context",
"[",
"'form'",
"]",
"=",
"self",
".",
"_get_permissions_form",
"(",
"request",
",",
"UserForumPermission",
",",
"{",
"'forum'",
":",
"forum",
",",
"'anonymous_user'",
":",
"True",
"}",
",",
")",
"return",
"render",
"(",
"request",
",",
"self",
".",
"editpermissions_anonymous_user_view_template_name",
",",
"context",
")"
] |
Allows to edit anonymous user permissions for the considered forum.
The view displays a form to define which permissions are granted for the anonymous user for
the considered forum.
|
[
"Allows",
"to",
"edit",
"anonymous",
"user",
"permissions",
"for",
"the",
"considered",
"forum",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L263-L280
|
9,326
|
ellmetha/django-machina
|
machina/apps/forum/admin.py
|
ForumAdmin.editpermissions_group_view
|
def editpermissions_group_view(self, request, group_id, forum_id=None):
""" Allows to edit group permissions for the considered forum.
The view displays a form to define which permissions are granted for the given group for the
considered forum.
"""
group = get_object_or_404(Group, pk=group_id)
forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None
# Set up the context
context = self.get_forum_perms_base_context(request, forum)
context['forum'] = forum
context['title'] = '{} - {}'.format(_('Forum permissions'), group)
context['form'] = self._get_permissions_form(
request, GroupForumPermission, {'forum': forum, 'group': group},
)
return render(request, self.editpermissions_group_view_template_name, context)
|
python
|
def editpermissions_group_view(self, request, group_id, forum_id=None):
""" Allows to edit group permissions for the considered forum.
The view displays a form to define which permissions are granted for the given group for the
considered forum.
"""
group = get_object_or_404(Group, pk=group_id)
forum = get_object_or_404(Forum, pk=forum_id) if forum_id else None
# Set up the context
context = self.get_forum_perms_base_context(request, forum)
context['forum'] = forum
context['title'] = '{} - {}'.format(_('Forum permissions'), group)
context['form'] = self._get_permissions_form(
request, GroupForumPermission, {'forum': forum, 'group': group},
)
return render(request, self.editpermissions_group_view_template_name, context)
|
[
"def",
"editpermissions_group_view",
"(",
"self",
",",
"request",
",",
"group_id",
",",
"forum_id",
"=",
"None",
")",
":",
"group",
"=",
"get_object_or_404",
"(",
"Group",
",",
"pk",
"=",
"group_id",
")",
"forum",
"=",
"get_object_or_404",
"(",
"Forum",
",",
"pk",
"=",
"forum_id",
")",
"if",
"forum_id",
"else",
"None",
"# Set up the context",
"context",
"=",
"self",
".",
"get_forum_perms_base_context",
"(",
"request",
",",
"forum",
")",
"context",
"[",
"'forum'",
"]",
"=",
"forum",
"context",
"[",
"'title'",
"]",
"=",
"'{} - {}'",
".",
"format",
"(",
"_",
"(",
"'Forum permissions'",
")",
",",
"group",
")",
"context",
"[",
"'form'",
"]",
"=",
"self",
".",
"_get_permissions_form",
"(",
"request",
",",
"GroupForumPermission",
",",
"{",
"'forum'",
":",
"forum",
",",
"'group'",
":",
"group",
"}",
",",
")",
"return",
"render",
"(",
"request",
",",
"self",
".",
"editpermissions_group_view_template_name",
",",
"context",
")"
] |
Allows to edit group permissions for the considered forum.
The view displays a form to define which permissions are granted for the given group for the
considered forum.
|
[
"Allows",
"to",
"edit",
"group",
"permissions",
"for",
"the",
"considered",
"forum",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/admin.py#L282-L300
|
9,327
|
ellmetha/django-machina
|
machina/templatetags/forum_permission_tags.py
|
get_permission
|
def get_permission(context, method, *args, **kwargs):
""" This will return a boolean indicating if the considered permission is granted for the passed
user.
Usage::
{% get_permission 'can_access_moderation_panel' request.user as var %}
"""
request = context.get('request', None)
perm_handler = request.forum_permission_handler if request else PermissionHandler()
allowed_methods = inspect.getmembers(perm_handler, predicate=inspect.ismethod)
allowed_method_names = [a[0] for a in allowed_methods if not a[0].startswith('_')]
if method not in allowed_method_names:
raise template.TemplateSyntaxError(
'Only the following methods are allowed through '
'this templatetag: {}'.format(allowed_method_names))
perm_method = getattr(perm_handler, method)
return perm_method(*args, **kwargs)
|
python
|
def get_permission(context, method, *args, **kwargs):
""" This will return a boolean indicating if the considered permission is granted for the passed
user.
Usage::
{% get_permission 'can_access_moderation_panel' request.user as var %}
"""
request = context.get('request', None)
perm_handler = request.forum_permission_handler if request else PermissionHandler()
allowed_methods = inspect.getmembers(perm_handler, predicate=inspect.ismethod)
allowed_method_names = [a[0] for a in allowed_methods if not a[0].startswith('_')]
if method not in allowed_method_names:
raise template.TemplateSyntaxError(
'Only the following methods are allowed through '
'this templatetag: {}'.format(allowed_method_names))
perm_method = getattr(perm_handler, method)
return perm_method(*args, **kwargs)
|
[
"def",
"get_permission",
"(",
"context",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"context",
".",
"get",
"(",
"'request'",
",",
"None",
")",
"perm_handler",
"=",
"request",
".",
"forum_permission_handler",
"if",
"request",
"else",
"PermissionHandler",
"(",
")",
"allowed_methods",
"=",
"inspect",
".",
"getmembers",
"(",
"perm_handler",
",",
"predicate",
"=",
"inspect",
".",
"ismethod",
")",
"allowed_method_names",
"=",
"[",
"a",
"[",
"0",
"]",
"for",
"a",
"in",
"allowed_methods",
"if",
"not",
"a",
"[",
"0",
"]",
".",
"startswith",
"(",
"'_'",
")",
"]",
"if",
"method",
"not",
"in",
"allowed_method_names",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"'Only the following methods are allowed through '",
"'this templatetag: {}'",
".",
"format",
"(",
"allowed_method_names",
")",
")",
"perm_method",
"=",
"getattr",
"(",
"perm_handler",
",",
"method",
")",
"return",
"perm_method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
This will return a boolean indicating if the considered permission is granted for the passed
user.
Usage::
{% get_permission 'can_access_moderation_panel' request.user as var %}
|
[
"This",
"will",
"return",
"a",
"boolean",
"indicating",
"if",
"the",
"considered",
"permission",
"is",
"granted",
"for",
"the",
"passed",
"user",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_permission_tags.py#L14-L35
|
9,328
|
ellmetha/django-machina
|
machina/apps/forum_conversation/forum_polls/forms.py
|
BaseTopicPollOptionFormset.total_form_count
|
def total_form_count(self):
"""
This rewrite of total_form_count allows to add an empty form to the formset only when
no initial data is provided.
"""
total_forms = super().total_form_count()
if not self.data and not self.files and self.initial_form_count() > 0:
total_forms -= self.extra
return total_forms
|
python
|
def total_form_count(self):
"""
This rewrite of total_form_count allows to add an empty form to the formset only when
no initial data is provided.
"""
total_forms = super().total_form_count()
if not self.data and not self.files and self.initial_form_count() > 0:
total_forms -= self.extra
return total_forms
|
[
"def",
"total_form_count",
"(",
"self",
")",
":",
"total_forms",
"=",
"super",
"(",
")",
".",
"total_form_count",
"(",
")",
"if",
"not",
"self",
".",
"data",
"and",
"not",
"self",
".",
"files",
"and",
"self",
".",
"initial_form_count",
"(",
")",
">",
"0",
":",
"total_forms",
"-=",
"self",
".",
"extra",
"return",
"total_forms"
] |
This rewrite of total_form_count allows to add an empty form to the formset only when
no initial data is provided.
|
[
"This",
"rewrite",
"of",
"total_form_count",
"allows",
"to",
"add",
"an",
"empty",
"form",
"to",
"the",
"formset",
"only",
"when",
"no",
"initial",
"data",
"is",
"provided",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_polls/forms.py#L52-L60
|
9,329
|
ellmetha/django-machina
|
machina/core/loading.py
|
get_classes
|
def get_classes(module_label, classnames):
""" Imports a set of classes from a given module.
Usage::
get_classes('forum.models', ['Forum', 'ForumReadTrack', ])
"""
app_label = module_label.split('.')[0]
app_module_path = _get_app_module_path(module_label)
if not app_module_path:
raise AppNotFoundError('No app found matching \'{}\''.format(module_label))
# Determines the full module path by appending the module label
# to the base package path of the considered application.
module_path = app_module_path
if '.' in app_module_path:
base_package = app_module_path.rsplit('.' + app_label, 1)[0]
module_path = '{}.{}'.format(base_package, module_label)
# Try to import this module from the related app that is specified
# in the Django settings.
local_imported_module = _import_module(module_path, classnames)
# If the module we tried to import is not located inside the machina
# vanilla apps, try to import it from the corresponding machina app.
machina_imported_module = None
if not app_module_path.startswith('machina.apps'):
machina_imported_module = _import_module(
'{}.{}'.format('machina.apps', module_label), classnames,
)
if local_imported_module is None and machina_imported_module is None:
raise AppNotFoundError('Error importing \'{}\''.format(module_path))
# Any local module is prioritized over the corresponding machina module
imported_modules = [
m for m in (local_imported_module, machina_imported_module) if m is not None
]
return _pick_up_classes(imported_modules, classnames)
|
python
|
def get_classes(module_label, classnames):
""" Imports a set of classes from a given module.
Usage::
get_classes('forum.models', ['Forum', 'ForumReadTrack', ])
"""
app_label = module_label.split('.')[0]
app_module_path = _get_app_module_path(module_label)
if not app_module_path:
raise AppNotFoundError('No app found matching \'{}\''.format(module_label))
# Determines the full module path by appending the module label
# to the base package path of the considered application.
module_path = app_module_path
if '.' in app_module_path:
base_package = app_module_path.rsplit('.' + app_label, 1)[0]
module_path = '{}.{}'.format(base_package, module_label)
# Try to import this module from the related app that is specified
# in the Django settings.
local_imported_module = _import_module(module_path, classnames)
# If the module we tried to import is not located inside the machina
# vanilla apps, try to import it from the corresponding machina app.
machina_imported_module = None
if not app_module_path.startswith('machina.apps'):
machina_imported_module = _import_module(
'{}.{}'.format('machina.apps', module_label), classnames,
)
if local_imported_module is None and machina_imported_module is None:
raise AppNotFoundError('Error importing \'{}\''.format(module_path))
# Any local module is prioritized over the corresponding machina module
imported_modules = [
m for m in (local_imported_module, machina_imported_module) if m is not None
]
return _pick_up_classes(imported_modules, classnames)
|
[
"def",
"get_classes",
"(",
"module_label",
",",
"classnames",
")",
":",
"app_label",
"=",
"module_label",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"app_module_path",
"=",
"_get_app_module_path",
"(",
"module_label",
")",
"if",
"not",
"app_module_path",
":",
"raise",
"AppNotFoundError",
"(",
"'No app found matching \\'{}\\''",
".",
"format",
"(",
"module_label",
")",
")",
"# Determines the full module path by appending the module label",
"# to the base package path of the considered application.",
"module_path",
"=",
"app_module_path",
"if",
"'.'",
"in",
"app_module_path",
":",
"base_package",
"=",
"app_module_path",
".",
"rsplit",
"(",
"'.'",
"+",
"app_label",
",",
"1",
")",
"[",
"0",
"]",
"module_path",
"=",
"'{}.{}'",
".",
"format",
"(",
"base_package",
",",
"module_label",
")",
"# Try to import this module from the related app that is specified",
"# in the Django settings.",
"local_imported_module",
"=",
"_import_module",
"(",
"module_path",
",",
"classnames",
")",
"# If the module we tried to import is not located inside the machina",
"# vanilla apps, try to import it from the corresponding machina app.",
"machina_imported_module",
"=",
"None",
"if",
"not",
"app_module_path",
".",
"startswith",
"(",
"'machina.apps'",
")",
":",
"machina_imported_module",
"=",
"_import_module",
"(",
"'{}.{}'",
".",
"format",
"(",
"'machina.apps'",
",",
"module_label",
")",
",",
"classnames",
",",
")",
"if",
"local_imported_module",
"is",
"None",
"and",
"machina_imported_module",
"is",
"None",
":",
"raise",
"AppNotFoundError",
"(",
"'Error importing \\'{}\\''",
".",
"format",
"(",
"module_path",
")",
")",
"# Any local module is prioritized over the corresponding machina module",
"imported_modules",
"=",
"[",
"m",
"for",
"m",
"in",
"(",
"local_imported_module",
",",
"machina_imported_module",
")",
"if",
"m",
"is",
"not",
"None",
"]",
"return",
"_pick_up_classes",
"(",
"imported_modules",
",",
"classnames",
")"
] |
Imports a set of classes from a given module.
Usage::
get_classes('forum.models', ['Forum', 'ForumReadTrack', ])
|
[
"Imports",
"a",
"set",
"of",
"classes",
"from",
"a",
"given",
"module",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L19-L59
|
9,330
|
ellmetha/django-machina
|
machina/core/loading.py
|
_import_module
|
def _import_module(module_path, classnames):
""" Tries to import the given Python module path. """
try:
imported_module = __import__(module_path, fromlist=classnames)
return imported_module
except ImportError:
# In case of an ImportError, the module being loaded generally does not exist. But an
# ImportError can occur if the module being loaded exists and another import located inside
# it failed.
#
# In order to provide a meaningfull traceback, the execution information can be inspected in
# order to determine which case to consider. If the execution information provides more than
# a certain amount of frames, this means that an ImportError occured while loading the
# initial Python module.
__, __, exc_traceback = sys.exc_info()
frames = traceback.extract_tb(exc_traceback)
if len(frames) > 1:
raise
|
python
|
def _import_module(module_path, classnames):
""" Tries to import the given Python module path. """
try:
imported_module = __import__(module_path, fromlist=classnames)
return imported_module
except ImportError:
# In case of an ImportError, the module being loaded generally does not exist. But an
# ImportError can occur if the module being loaded exists and another import located inside
# it failed.
#
# In order to provide a meaningfull traceback, the execution information can be inspected in
# order to determine which case to consider. If the execution information provides more than
# a certain amount of frames, this means that an ImportError occured while loading the
# initial Python module.
__, __, exc_traceback = sys.exc_info()
frames = traceback.extract_tb(exc_traceback)
if len(frames) > 1:
raise
|
[
"def",
"_import_module",
"(",
"module_path",
",",
"classnames",
")",
":",
"try",
":",
"imported_module",
"=",
"__import__",
"(",
"module_path",
",",
"fromlist",
"=",
"classnames",
")",
"return",
"imported_module",
"except",
"ImportError",
":",
"# In case of an ImportError, the module being loaded generally does not exist. But an",
"# ImportError can occur if the module being loaded exists and another import located inside",
"# it failed.",
"#",
"# In order to provide a meaningfull traceback, the execution information can be inspected in",
"# order to determine which case to consider. If the execution information provides more than",
"# a certain amount of frames, this means that an ImportError occured while loading the",
"# initial Python module.",
"__",
",",
"__",
",",
"exc_traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"frames",
"=",
"traceback",
".",
"extract_tb",
"(",
"exc_traceback",
")",
"if",
"len",
"(",
"frames",
")",
">",
"1",
":",
"raise"
] |
Tries to import the given Python module path.
|
[
"Tries",
"to",
"import",
"the",
"given",
"Python",
"module",
"path",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L62-L79
|
9,331
|
ellmetha/django-machina
|
machina/core/loading.py
|
_pick_up_classes
|
def _pick_up_classes(modules, classnames):
""" Given a list of class names to retrieve, try to fetch them from the specified list of
modules and returns the list of the fetched classes.
"""
klasses = []
for classname in classnames:
klass = None
for module in modules:
if hasattr(module, classname):
klass = getattr(module, classname)
break
if not klass:
raise ClassNotFoundError('Error fetching \'{}\' in {}'.format(
classname, str([module.__name__ for module in modules]))
)
klasses.append(klass)
return klasses
|
python
|
def _pick_up_classes(modules, classnames):
""" Given a list of class names to retrieve, try to fetch them from the specified list of
modules and returns the list of the fetched classes.
"""
klasses = []
for classname in classnames:
klass = None
for module in modules:
if hasattr(module, classname):
klass = getattr(module, classname)
break
if not klass:
raise ClassNotFoundError('Error fetching \'{}\' in {}'.format(
classname, str([module.__name__ for module in modules]))
)
klasses.append(klass)
return klasses
|
[
"def",
"_pick_up_classes",
"(",
"modules",
",",
"classnames",
")",
":",
"klasses",
"=",
"[",
"]",
"for",
"classname",
"in",
"classnames",
":",
"klass",
"=",
"None",
"for",
"module",
"in",
"modules",
":",
"if",
"hasattr",
"(",
"module",
",",
"classname",
")",
":",
"klass",
"=",
"getattr",
"(",
"module",
",",
"classname",
")",
"break",
"if",
"not",
"klass",
":",
"raise",
"ClassNotFoundError",
"(",
"'Error fetching \\'{}\\' in {}'",
".",
"format",
"(",
"classname",
",",
"str",
"(",
"[",
"module",
".",
"__name__",
"for",
"module",
"in",
"modules",
"]",
")",
")",
")",
"klasses",
".",
"append",
"(",
"klass",
")",
"return",
"klasses"
] |
Given a list of class names to retrieve, try to fetch them from the specified list of
modules and returns the list of the fetched classes.
|
[
"Given",
"a",
"list",
"of",
"class",
"names",
"to",
"retrieve",
"try",
"to",
"fetch",
"them",
"from",
"the",
"specified",
"list",
"of",
"modules",
"and",
"returns",
"the",
"list",
"of",
"the",
"fetched",
"classes",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L82-L98
|
9,332
|
ellmetha/django-machina
|
machina/core/loading.py
|
_get_app_module_path
|
def _get_app_module_path(module_label):
""" Given a module label, loop over the apps specified in the INSTALLED_APPS to find the
corresponding application module path.
"""
app_name = module_label.rsplit('.', 1)[0]
for app in settings.INSTALLED_APPS:
if app.endswith('.' + app_name) or app == app_name:
return app
return None
|
python
|
def _get_app_module_path(module_label):
""" Given a module label, loop over the apps specified in the INSTALLED_APPS to find the
corresponding application module path.
"""
app_name = module_label.rsplit('.', 1)[0]
for app in settings.INSTALLED_APPS:
if app.endswith('.' + app_name) or app == app_name:
return app
return None
|
[
"def",
"_get_app_module_path",
"(",
"module_label",
")",
":",
"app_name",
"=",
"module_label",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"0",
"]",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"if",
"app",
".",
"endswith",
"(",
"'.'",
"+",
"app_name",
")",
"or",
"app",
"==",
"app_name",
":",
"return",
"app",
"return",
"None"
] |
Given a module label, loop over the apps specified in the INSTALLED_APPS to find the
corresponding application module path.
|
[
"Given",
"a",
"module",
"label",
"loop",
"over",
"the",
"apps",
"specified",
"in",
"the",
"INSTALLED_APPS",
"to",
"find",
"the",
"corresponding",
"application",
"module",
"path",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L101-L109
|
9,333
|
ellmetha/django-machina
|
machina/apps/forum_tracking/handler.py
|
TrackingHandler.get_unread_forums
|
def get_unread_forums(self, user):
""" Returns the list of unread forums for the given user. """
return self.get_unread_forums_from_list(
user, self.perm_handler.get_readable_forums(Forum.objects.all(), user))
|
python
|
def get_unread_forums(self, user):
""" Returns the list of unread forums for the given user. """
return self.get_unread_forums_from_list(
user, self.perm_handler.get_readable_forums(Forum.objects.all(), user))
|
[
"def",
"get_unread_forums",
"(",
"self",
",",
"user",
")",
":",
"return",
"self",
".",
"get_unread_forums_from_list",
"(",
"user",
",",
"self",
".",
"perm_handler",
".",
"get_readable_forums",
"(",
"Forum",
".",
"objects",
".",
"all",
"(",
")",
",",
"user",
")",
")"
] |
Returns the list of unread forums for the given user.
|
[
"Returns",
"the",
"list",
"of",
"unread",
"forums",
"for",
"the",
"given",
"user",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/handler.py#L36-L39
|
9,334
|
ellmetha/django-machina
|
machina/apps/forum_tracking/handler.py
|
TrackingHandler.get_unread_forums_from_list
|
def get_unread_forums_from_list(self, user, forums):
""" Returns the list of unread forums for the given user from a given list of forums. """
unread_forums = []
# A user which is not authenticated will never see a forum as unread
if not user.is_authenticated:
return unread_forums
unread = ForumReadTrack.objects.get_unread_forums_from_list(forums, user)
unread_forums.extend(unread)
return unread_forums
|
python
|
def get_unread_forums_from_list(self, user, forums):
""" Returns the list of unread forums for the given user from a given list of forums. """
unread_forums = []
# A user which is not authenticated will never see a forum as unread
if not user.is_authenticated:
return unread_forums
unread = ForumReadTrack.objects.get_unread_forums_from_list(forums, user)
unread_forums.extend(unread)
return unread_forums
|
[
"def",
"get_unread_forums_from_list",
"(",
"self",
",",
"user",
",",
"forums",
")",
":",
"unread_forums",
"=",
"[",
"]",
"# A user which is not authenticated will never see a forum as unread",
"if",
"not",
"user",
".",
"is_authenticated",
":",
"return",
"unread_forums",
"unread",
"=",
"ForumReadTrack",
".",
"objects",
".",
"get_unread_forums_from_list",
"(",
"forums",
",",
"user",
")",
"unread_forums",
".",
"extend",
"(",
"unread",
")",
"return",
"unread_forums"
] |
Returns the list of unread forums for the given user from a given list of forums.
|
[
"Returns",
"the",
"list",
"of",
"unread",
"forums",
"for",
"the",
"given",
"user",
"from",
"a",
"given",
"list",
"of",
"forums",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/handler.py#L41-L52
|
9,335
|
ellmetha/django-machina
|
machina/apps/forum_tracking/handler.py
|
TrackingHandler.get_unread_topics
|
def get_unread_topics(self, topics, user):
""" Returns a list of unread topics for the given user from a given set of topics. """
unread_topics = []
# A user which is not authenticated will never see a topic as unread.
# If there are no topics to consider, we stop here.
if not user.is_authenticated or topics is None or not len(topics):
return unread_topics
# A topic can be unread if a track for itself exists with a mark time that
# is less important than its update date.
topic_ids = [topic.id for topic in topics]
topic_tracks = TopicReadTrack.objects.filter(topic__in=topic_ids, user=user)
tracked_topics = dict(topic_tracks.values_list('topic__pk', 'mark_time'))
if tracked_topics:
for topic in topics:
topic_last_modification_date = topic.last_post_on or topic.created
if (
topic.id in tracked_topics.keys() and
topic_last_modification_date > tracked_topics[topic.id]
):
unread_topics.append(topic)
# A topic can be unread if a track for its associated forum exists with
# a mark time that is less important than its creation or update date.
forum_ids = [topic.forum_id for topic in topics]
forum_tracks = ForumReadTrack.objects.filter(forum_id__in=forum_ids, user=user)
tracked_forums = dict(forum_tracks.values_list('forum__pk', 'mark_time'))
if tracked_forums:
for topic in topics:
topic_last_modification_date = topic.last_post_on or topic.created
if (
(topic.forum_id in tracked_forums.keys() and topic.id not in tracked_topics) and
topic_last_modification_date > tracked_forums[topic.forum_id]
):
unread_topics.append(topic)
# A topic can be unread if no tracks exists for it
for topic in topics:
if topic.forum_id not in tracked_forums and topic.id not in tracked_topics:
unread_topics.append(topic)
return list(set(unread_topics))
|
python
|
def get_unread_topics(self, topics, user):
""" Returns a list of unread topics for the given user from a given set of topics. """
unread_topics = []
# A user which is not authenticated will never see a topic as unread.
# If there are no topics to consider, we stop here.
if not user.is_authenticated or topics is None or not len(topics):
return unread_topics
# A topic can be unread if a track for itself exists with a mark time that
# is less important than its update date.
topic_ids = [topic.id for topic in topics]
topic_tracks = TopicReadTrack.objects.filter(topic__in=topic_ids, user=user)
tracked_topics = dict(topic_tracks.values_list('topic__pk', 'mark_time'))
if tracked_topics:
for topic in topics:
topic_last_modification_date = topic.last_post_on or topic.created
if (
topic.id in tracked_topics.keys() and
topic_last_modification_date > tracked_topics[topic.id]
):
unread_topics.append(topic)
# A topic can be unread if a track for its associated forum exists with
# a mark time that is less important than its creation or update date.
forum_ids = [topic.forum_id for topic in topics]
forum_tracks = ForumReadTrack.objects.filter(forum_id__in=forum_ids, user=user)
tracked_forums = dict(forum_tracks.values_list('forum__pk', 'mark_time'))
if tracked_forums:
for topic in topics:
topic_last_modification_date = topic.last_post_on or topic.created
if (
(topic.forum_id in tracked_forums.keys() and topic.id not in tracked_topics) and
topic_last_modification_date > tracked_forums[topic.forum_id]
):
unread_topics.append(topic)
# A topic can be unread if no tracks exists for it
for topic in topics:
if topic.forum_id not in tracked_forums and topic.id not in tracked_topics:
unread_topics.append(topic)
return list(set(unread_topics))
|
[
"def",
"get_unread_topics",
"(",
"self",
",",
"topics",
",",
"user",
")",
":",
"unread_topics",
"=",
"[",
"]",
"# A user which is not authenticated will never see a topic as unread.",
"# If there are no topics to consider, we stop here.",
"if",
"not",
"user",
".",
"is_authenticated",
"or",
"topics",
"is",
"None",
"or",
"not",
"len",
"(",
"topics",
")",
":",
"return",
"unread_topics",
"# A topic can be unread if a track for itself exists with a mark time that",
"# is less important than its update date.",
"topic_ids",
"=",
"[",
"topic",
".",
"id",
"for",
"topic",
"in",
"topics",
"]",
"topic_tracks",
"=",
"TopicReadTrack",
".",
"objects",
".",
"filter",
"(",
"topic__in",
"=",
"topic_ids",
",",
"user",
"=",
"user",
")",
"tracked_topics",
"=",
"dict",
"(",
"topic_tracks",
".",
"values_list",
"(",
"'topic__pk'",
",",
"'mark_time'",
")",
")",
"if",
"tracked_topics",
":",
"for",
"topic",
"in",
"topics",
":",
"topic_last_modification_date",
"=",
"topic",
".",
"last_post_on",
"or",
"topic",
".",
"created",
"if",
"(",
"topic",
".",
"id",
"in",
"tracked_topics",
".",
"keys",
"(",
")",
"and",
"topic_last_modification_date",
">",
"tracked_topics",
"[",
"topic",
".",
"id",
"]",
")",
":",
"unread_topics",
".",
"append",
"(",
"topic",
")",
"# A topic can be unread if a track for its associated forum exists with",
"# a mark time that is less important than its creation or update date.",
"forum_ids",
"=",
"[",
"topic",
".",
"forum_id",
"for",
"topic",
"in",
"topics",
"]",
"forum_tracks",
"=",
"ForumReadTrack",
".",
"objects",
".",
"filter",
"(",
"forum_id__in",
"=",
"forum_ids",
",",
"user",
"=",
"user",
")",
"tracked_forums",
"=",
"dict",
"(",
"forum_tracks",
".",
"values_list",
"(",
"'forum__pk'",
",",
"'mark_time'",
")",
")",
"if",
"tracked_forums",
":",
"for",
"topic",
"in",
"topics",
":",
"topic_last_modification_date",
"=",
"topic",
".",
"last_post_on",
"or",
"topic",
".",
"created",
"if",
"(",
"(",
"topic",
".",
"forum_id",
"in",
"tracked_forums",
".",
"keys",
"(",
")",
"and",
"topic",
".",
"id",
"not",
"in",
"tracked_topics",
")",
"and",
"topic_last_modification_date",
">",
"tracked_forums",
"[",
"topic",
".",
"forum_id",
"]",
")",
":",
"unread_topics",
".",
"append",
"(",
"topic",
")",
"# A topic can be unread if no tracks exists for it",
"for",
"topic",
"in",
"topics",
":",
"if",
"topic",
".",
"forum_id",
"not",
"in",
"tracked_forums",
"and",
"topic",
".",
"id",
"not",
"in",
"tracked_topics",
":",
"unread_topics",
".",
"append",
"(",
"topic",
")",
"return",
"list",
"(",
"set",
"(",
"unread_topics",
")",
")"
] |
Returns a list of unread topics for the given user from a given set of topics.
|
[
"Returns",
"a",
"list",
"of",
"unread",
"topics",
"for",
"the",
"given",
"user",
"from",
"a",
"given",
"set",
"of",
"topics",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/handler.py#L54-L98
|
9,336
|
ellmetha/django-machina
|
machina/apps/forum_tracking/handler.py
|
TrackingHandler.mark_forums_read
|
def mark_forums_read(self, forums, user):
""" Marks a list of forums as read. """
if not forums or not user.is_authenticated:
return
forums = sorted(forums, key=lambda f: f.level)
# Update all forum tracks to the current date for the considered forums
for forum in forums:
forum_track = ForumReadTrack.objects.get_or_create(forum=forum, user=user)[0]
forum_track.save()
# Delete all the unnecessary topic tracks
TopicReadTrack.objects.filter(topic__forum__in=forums, user=user).delete()
# Update parent forum tracks
self._update_parent_forum_tracks(forums[0], user)
|
python
|
def mark_forums_read(self, forums, user):
""" Marks a list of forums as read. """
if not forums or not user.is_authenticated:
return
forums = sorted(forums, key=lambda f: f.level)
# Update all forum tracks to the current date for the considered forums
for forum in forums:
forum_track = ForumReadTrack.objects.get_or_create(forum=forum, user=user)[0]
forum_track.save()
# Delete all the unnecessary topic tracks
TopicReadTrack.objects.filter(topic__forum__in=forums, user=user).delete()
# Update parent forum tracks
self._update_parent_forum_tracks(forums[0], user)
|
[
"def",
"mark_forums_read",
"(",
"self",
",",
"forums",
",",
"user",
")",
":",
"if",
"not",
"forums",
"or",
"not",
"user",
".",
"is_authenticated",
":",
"return",
"forums",
"=",
"sorted",
"(",
"forums",
",",
"key",
"=",
"lambda",
"f",
":",
"f",
".",
"level",
")",
"# Update all forum tracks to the current date for the considered forums",
"for",
"forum",
"in",
"forums",
":",
"forum_track",
"=",
"ForumReadTrack",
".",
"objects",
".",
"get_or_create",
"(",
"forum",
"=",
"forum",
",",
"user",
"=",
"user",
")",
"[",
"0",
"]",
"forum_track",
".",
"save",
"(",
")",
"# Delete all the unnecessary topic tracks",
"TopicReadTrack",
".",
"objects",
".",
"filter",
"(",
"topic__forum__in",
"=",
"forums",
",",
"user",
"=",
"user",
")",
".",
"delete",
"(",
")",
"# Update parent forum tracks",
"self",
".",
"_update_parent_forum_tracks",
"(",
"forums",
"[",
"0",
"]",
",",
"user",
")"
] |
Marks a list of forums as read.
|
[
"Marks",
"a",
"list",
"of",
"forums",
"as",
"read",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/handler.py#L100-L114
|
9,337
|
ellmetha/django-machina
|
machina/apps/forum_tracking/handler.py
|
TrackingHandler.mark_topic_read
|
def mark_topic_read(self, topic, user):
""" Marks a topic as read. """
if not user.is_authenticated:
return
forum = topic.forum
try:
forum_track = ForumReadTrack.objects.get(forum=forum, user=user)
except ForumReadTrack.DoesNotExist:
forum_track = None
if (
forum_track is None or
(topic.last_post_on and forum_track.mark_time < topic.last_post_on)
):
topic_track, created = TopicReadTrack.objects.get_or_create(topic=topic, user=user)
if not created:
topic_track.save() # mark_time filled
# If no other topic is unread inside the considered forum, the latter should also be
# marked as read.
unread_topics = (
forum.topics
.filter(
Q(tracks__user=user, tracks__mark_time__lt=F('last_post_on')) |
Q(
forum__tracks__user=user, forum__tracks__mark_time__lt=F('last_post_on'),
tracks__isnull=True,
)
)
.exclude(id=topic.id)
)
forum_topic_tracks = TopicReadTrack.objects.filter(topic__forum=forum, user=user)
if (
not unread_topics.exists() and
(
forum_track is not None or
forum_topic_tracks.count() == forum.topics.filter(approved=True).count()
)
):
# The topics that are marked as read inside the forum for the given user will be
# deleted while the forum track associated with the user must be created or updated.
# This is done only if there are as many topic tracks as approved topics in case
# the related forum has not beem previously marked as read.
TopicReadTrack.objects.filter(topic__forum=forum, user=user).delete()
forum_track, _ = ForumReadTrack.objects.get_or_create(forum=forum, user=user)
forum_track.save()
# Update parent forum tracks
self._update_parent_forum_tracks(forum, user)
|
python
|
def mark_topic_read(self, topic, user):
""" Marks a topic as read. """
if not user.is_authenticated:
return
forum = topic.forum
try:
forum_track = ForumReadTrack.objects.get(forum=forum, user=user)
except ForumReadTrack.DoesNotExist:
forum_track = None
if (
forum_track is None or
(topic.last_post_on and forum_track.mark_time < topic.last_post_on)
):
topic_track, created = TopicReadTrack.objects.get_or_create(topic=topic, user=user)
if not created:
topic_track.save() # mark_time filled
# If no other topic is unread inside the considered forum, the latter should also be
# marked as read.
unread_topics = (
forum.topics
.filter(
Q(tracks__user=user, tracks__mark_time__lt=F('last_post_on')) |
Q(
forum__tracks__user=user, forum__tracks__mark_time__lt=F('last_post_on'),
tracks__isnull=True,
)
)
.exclude(id=topic.id)
)
forum_topic_tracks = TopicReadTrack.objects.filter(topic__forum=forum, user=user)
if (
not unread_topics.exists() and
(
forum_track is not None or
forum_topic_tracks.count() == forum.topics.filter(approved=True).count()
)
):
# The topics that are marked as read inside the forum for the given user will be
# deleted while the forum track associated with the user must be created or updated.
# This is done only if there are as many topic tracks as approved topics in case
# the related forum has not beem previously marked as read.
TopicReadTrack.objects.filter(topic__forum=forum, user=user).delete()
forum_track, _ = ForumReadTrack.objects.get_or_create(forum=forum, user=user)
forum_track.save()
# Update parent forum tracks
self._update_parent_forum_tracks(forum, user)
|
[
"def",
"mark_topic_read",
"(",
"self",
",",
"topic",
",",
"user",
")",
":",
"if",
"not",
"user",
".",
"is_authenticated",
":",
"return",
"forum",
"=",
"topic",
".",
"forum",
"try",
":",
"forum_track",
"=",
"ForumReadTrack",
".",
"objects",
".",
"get",
"(",
"forum",
"=",
"forum",
",",
"user",
"=",
"user",
")",
"except",
"ForumReadTrack",
".",
"DoesNotExist",
":",
"forum_track",
"=",
"None",
"if",
"(",
"forum_track",
"is",
"None",
"or",
"(",
"topic",
".",
"last_post_on",
"and",
"forum_track",
".",
"mark_time",
"<",
"topic",
".",
"last_post_on",
")",
")",
":",
"topic_track",
",",
"created",
"=",
"TopicReadTrack",
".",
"objects",
".",
"get_or_create",
"(",
"topic",
"=",
"topic",
",",
"user",
"=",
"user",
")",
"if",
"not",
"created",
":",
"topic_track",
".",
"save",
"(",
")",
"# mark_time filled",
"# If no other topic is unread inside the considered forum, the latter should also be",
"# marked as read.",
"unread_topics",
"=",
"(",
"forum",
".",
"topics",
".",
"filter",
"(",
"Q",
"(",
"tracks__user",
"=",
"user",
",",
"tracks__mark_time__lt",
"=",
"F",
"(",
"'last_post_on'",
")",
")",
"|",
"Q",
"(",
"forum__tracks__user",
"=",
"user",
",",
"forum__tracks__mark_time__lt",
"=",
"F",
"(",
"'last_post_on'",
")",
",",
"tracks__isnull",
"=",
"True",
",",
")",
")",
".",
"exclude",
"(",
"id",
"=",
"topic",
".",
"id",
")",
")",
"forum_topic_tracks",
"=",
"TopicReadTrack",
".",
"objects",
".",
"filter",
"(",
"topic__forum",
"=",
"forum",
",",
"user",
"=",
"user",
")",
"if",
"(",
"not",
"unread_topics",
".",
"exists",
"(",
")",
"and",
"(",
"forum_track",
"is",
"not",
"None",
"or",
"forum_topic_tracks",
".",
"count",
"(",
")",
"==",
"forum",
".",
"topics",
".",
"filter",
"(",
"approved",
"=",
"True",
")",
".",
"count",
"(",
")",
")",
")",
":",
"# The topics that are marked as read inside the forum for the given user will be",
"# deleted while the forum track associated with the user must be created or updated.",
"# This is done only if there are as many topic tracks as approved topics in case",
"# the related forum has not beem previously marked as read.",
"TopicReadTrack",
".",
"objects",
".",
"filter",
"(",
"topic__forum",
"=",
"forum",
",",
"user",
"=",
"user",
")",
".",
"delete",
"(",
")",
"forum_track",
",",
"_",
"=",
"ForumReadTrack",
".",
"objects",
".",
"get_or_create",
"(",
"forum",
"=",
"forum",
",",
"user",
"=",
"user",
")",
"forum_track",
".",
"save",
"(",
")",
"# Update parent forum tracks",
"self",
".",
"_update_parent_forum_tracks",
"(",
"forum",
",",
"user",
")"
] |
Marks a topic as read.
|
[
"Marks",
"a",
"topic",
"as",
"read",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/handler.py#L116-L166
|
9,338
|
ellmetha/django-machina
|
machina/apps/forum/abstract_models.py
|
AbstractForum.clean
|
def clean(self):
""" Validates the forum instance. """
super().clean()
if self.parent and self.parent.is_link:
raise ValidationError(_('A forum can not have a link forum as parent'))
if self.is_category and self.parent and self.parent.is_category:
raise ValidationError(_('A category can not have another category as parent'))
if self.is_link and not self.link:
raise ValidationError(_('A link forum must have a link associated with it'))
|
python
|
def clean(self):
""" Validates the forum instance. """
super().clean()
if self.parent and self.parent.is_link:
raise ValidationError(_('A forum can not have a link forum as parent'))
if self.is_category and self.parent and self.parent.is_category:
raise ValidationError(_('A category can not have another category as parent'))
if self.is_link and not self.link:
raise ValidationError(_('A link forum must have a link associated with it'))
|
[
"def",
"clean",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"clean",
"(",
")",
"if",
"self",
".",
"parent",
"and",
"self",
".",
"parent",
".",
"is_link",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A forum can not have a link forum as parent'",
")",
")",
"if",
"self",
".",
"is_category",
"and",
"self",
".",
"parent",
"and",
"self",
".",
"parent",
".",
"is_category",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A category can not have another category as parent'",
")",
")",
"if",
"self",
".",
"is_link",
"and",
"not",
"self",
".",
"link",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A link forum must have a link associated with it'",
")",
")"
] |
Validates the forum instance.
|
[
"Validates",
"the",
"forum",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L134-L145
|
9,339
|
ellmetha/django-machina
|
machina/apps/forum/abstract_models.py
|
AbstractForum.get_image_upload_to
|
def get_image_upload_to(self, filename):
""" Returns the path to upload a new associated image to. """
dummy, ext = os.path.splitext(filename)
return os.path.join(
machina_settings.FORUM_IMAGE_UPLOAD_TO,
'{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext),
)
|
python
|
def get_image_upload_to(self, filename):
""" Returns the path to upload a new associated image to. """
dummy, ext = os.path.splitext(filename)
return os.path.join(
machina_settings.FORUM_IMAGE_UPLOAD_TO,
'{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext),
)
|
[
"def",
"get_image_upload_to",
"(",
"self",
",",
"filename",
")",
":",
"dummy",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"machina_settings",
".",
"FORUM_IMAGE_UPLOAD_TO",
",",
"'{id}{ext}'",
".",
"format",
"(",
"id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
",",
"ext",
"=",
"ext",
")",
",",
")"
] |
Returns the path to upload a new associated image to.
|
[
"Returns",
"the",
"path",
"to",
"upload",
"a",
"new",
"associated",
"image",
"to",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L147-L153
|
9,340
|
ellmetha/django-machina
|
machina/apps/forum/abstract_models.py
|
AbstractForum.save
|
def save(self, *args, **kwargs):
""" Saves the forum instance. """
# It is vital to track the changes of the parent associated with a forum in order to
# maintain counters up-to-date and to trigger other operations such as permissions updates.
old_instance = None
if self.pk:
old_instance = self.__class__._default_manager.get(pk=self.pk)
# Update the slug field
self.slug = slugify(force_text(self.name), allow_unicode=True)
# Do the save
super().save(*args, **kwargs)
# If any change has been made to the forum parent, trigger the update of the counters
if old_instance and old_instance.parent != self.parent:
self.update_trackers()
# Trigger the 'forum_moved' signal
signals.forum_moved.send(sender=self, previous_parent=old_instance.parent)
|
python
|
def save(self, *args, **kwargs):
""" Saves the forum instance. """
# It is vital to track the changes of the parent associated with a forum in order to
# maintain counters up-to-date and to trigger other operations such as permissions updates.
old_instance = None
if self.pk:
old_instance = self.__class__._default_manager.get(pk=self.pk)
# Update the slug field
self.slug = slugify(force_text(self.name), allow_unicode=True)
# Do the save
super().save(*args, **kwargs)
# If any change has been made to the forum parent, trigger the update of the counters
if old_instance and old_instance.parent != self.parent:
self.update_trackers()
# Trigger the 'forum_moved' signal
signals.forum_moved.send(sender=self, previous_parent=old_instance.parent)
|
[
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# It is vital to track the changes of the parent associated with a forum in order to",
"# maintain counters up-to-date and to trigger other operations such as permissions updates.",
"old_instance",
"=",
"None",
"if",
"self",
".",
"pk",
":",
"old_instance",
"=",
"self",
".",
"__class__",
".",
"_default_manager",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"pk",
")",
"# Update the slug field",
"self",
".",
"slug",
"=",
"slugify",
"(",
"force_text",
"(",
"self",
".",
"name",
")",
",",
"allow_unicode",
"=",
"True",
")",
"# Do the save",
"super",
"(",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# If any change has been made to the forum parent, trigger the update of the counters",
"if",
"old_instance",
"and",
"old_instance",
".",
"parent",
"!=",
"self",
".",
"parent",
":",
"self",
".",
"update_trackers",
"(",
")",
"# Trigger the 'forum_moved' signal",
"signals",
".",
"forum_moved",
".",
"send",
"(",
"sender",
"=",
"self",
",",
"previous_parent",
"=",
"old_instance",
".",
"parent",
")"
] |
Saves the forum instance.
|
[
"Saves",
"the",
"forum",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L155-L173
|
9,341
|
ellmetha/django-machina
|
machina/apps/forum/abstract_models.py
|
AbstractForum.update_trackers
|
def update_trackers(self):
""" Updates the denormalized trackers associated with the forum instance. """
direct_approved_topics = self.topics.filter(approved=True).order_by('-last_post_on')
# Compute the direct topics count and the direct posts count.
self.direct_topics_count = direct_approved_topics.count()
self.direct_posts_count = direct_approved_topics.aggregate(
total_posts_count=Sum('posts_count'))['total_posts_count'] or 0
# Forces the forum's 'last_post' ID and 'last_post_on' date to the corresponding values
# associated with the topic with the latest post.
if direct_approved_topics.exists():
self.last_post_id = direct_approved_topics[0].last_post_id
self.last_post_on = direct_approved_topics[0].last_post_on
else:
self.last_post_id = None
self.last_post_on = None
# Any save of a forum triggered from the update_tracker process will not result in checking
# for a change of the forum's parent.
self._simple_save()
|
python
|
def update_trackers(self):
""" Updates the denormalized trackers associated with the forum instance. """
direct_approved_topics = self.topics.filter(approved=True).order_by('-last_post_on')
# Compute the direct topics count and the direct posts count.
self.direct_topics_count = direct_approved_topics.count()
self.direct_posts_count = direct_approved_topics.aggregate(
total_posts_count=Sum('posts_count'))['total_posts_count'] or 0
# Forces the forum's 'last_post' ID and 'last_post_on' date to the corresponding values
# associated with the topic with the latest post.
if direct_approved_topics.exists():
self.last_post_id = direct_approved_topics[0].last_post_id
self.last_post_on = direct_approved_topics[0].last_post_on
else:
self.last_post_id = None
self.last_post_on = None
# Any save of a forum triggered from the update_tracker process will not result in checking
# for a change of the forum's parent.
self._simple_save()
|
[
"def",
"update_trackers",
"(",
"self",
")",
":",
"direct_approved_topics",
"=",
"self",
".",
"topics",
".",
"filter",
"(",
"approved",
"=",
"True",
")",
".",
"order_by",
"(",
"'-last_post_on'",
")",
"# Compute the direct topics count and the direct posts count.",
"self",
".",
"direct_topics_count",
"=",
"direct_approved_topics",
".",
"count",
"(",
")",
"self",
".",
"direct_posts_count",
"=",
"direct_approved_topics",
".",
"aggregate",
"(",
"total_posts_count",
"=",
"Sum",
"(",
"'posts_count'",
")",
")",
"[",
"'total_posts_count'",
"]",
"or",
"0",
"# Forces the forum's 'last_post' ID and 'last_post_on' date to the corresponding values",
"# associated with the topic with the latest post.",
"if",
"direct_approved_topics",
".",
"exists",
"(",
")",
":",
"self",
".",
"last_post_id",
"=",
"direct_approved_topics",
"[",
"0",
"]",
".",
"last_post_id",
"self",
".",
"last_post_on",
"=",
"direct_approved_topics",
"[",
"0",
"]",
".",
"last_post_on",
"else",
":",
"self",
".",
"last_post_id",
"=",
"None",
"self",
".",
"last_post_on",
"=",
"None",
"# Any save of a forum triggered from the update_tracker process will not result in checking",
"# for a change of the forum's parent.",
"self",
".",
"_simple_save",
"(",
")"
] |
Updates the denormalized trackers associated with the forum instance.
|
[
"Updates",
"the",
"denormalized",
"trackers",
"associated",
"with",
"the",
"forum",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L175-L195
|
9,342
|
ellmetha/django-machina
|
machina/templatetags/forum_tracking_tags.py
|
get_unread_topics
|
def get_unread_topics(context, topics, user):
""" This will return a list of unread topics for the given user from a given set of topics.
Usage::
{% get_unread_topics topics request.user as unread_topics %}
"""
request = context.get('request', None)
return TrackingHandler(request=request).get_unread_topics(topics, user)
|
python
|
def get_unread_topics(context, topics, user):
""" This will return a list of unread topics for the given user from a given set of topics.
Usage::
{% get_unread_topics topics request.user as unread_topics %}
"""
request = context.get('request', None)
return TrackingHandler(request=request).get_unread_topics(topics, user)
|
[
"def",
"get_unread_topics",
"(",
"context",
",",
"topics",
",",
"user",
")",
":",
"request",
"=",
"context",
".",
"get",
"(",
"'request'",
",",
"None",
")",
"return",
"TrackingHandler",
"(",
"request",
"=",
"request",
")",
".",
"get_unread_topics",
"(",
"topics",
",",
"user",
")"
] |
This will return a list of unread topics for the given user from a given set of topics.
Usage::
{% get_unread_topics topics request.user as unread_topics %}
|
[
"This",
"will",
"return",
"a",
"list",
"of",
"unread",
"topics",
"for",
"the",
"given",
"user",
"from",
"a",
"given",
"set",
"of",
"topics",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/templatetags/forum_tracking_tags.py#L12-L21
|
9,343
|
ellmetha/django-machina
|
machina/models/fields.py
|
ExtendedImageField.resize_image
|
def resize_image(self, data, size):
""" Resizes the given image to fit inside a box of the given size. """
from machina.core.compat import PILImage as Image
image = Image.open(BytesIO(data))
# Resize!
image.thumbnail(size, Image.ANTIALIAS)
string = BytesIO()
image.save(string, format='PNG')
return string.getvalue()
|
python
|
def resize_image(self, data, size):
""" Resizes the given image to fit inside a box of the given size. """
from machina.core.compat import PILImage as Image
image = Image.open(BytesIO(data))
# Resize!
image.thumbnail(size, Image.ANTIALIAS)
string = BytesIO()
image.save(string, format='PNG')
return string.getvalue()
|
[
"def",
"resize_image",
"(",
"self",
",",
"data",
",",
"size",
")",
":",
"from",
"machina",
".",
"core",
".",
"compat",
"import",
"PILImage",
"as",
"Image",
"image",
"=",
"Image",
".",
"open",
"(",
"BytesIO",
"(",
"data",
")",
")",
"# Resize!",
"image",
".",
"thumbnail",
"(",
"size",
",",
"Image",
".",
"ANTIALIAS",
")",
"string",
"=",
"BytesIO",
"(",
")",
"image",
".",
"save",
"(",
"string",
",",
"format",
"=",
"'PNG'",
")",
"return",
"string",
".",
"getvalue",
"(",
")"
] |
Resizes the given image to fit inside a box of the given size.
|
[
"Resizes",
"the",
"given",
"image",
"to",
"fit",
"inside",
"a",
"box",
"of",
"the",
"given",
"size",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/models/fields.py#L260-L270
|
9,344
|
ellmetha/django-machina
|
machina/apps/forum_conversation/forum_attachments/cache.py
|
AttachmentCache.get_backend
|
def get_backend(self):
""" Returns the associated cache backend. """
try:
cache = caches[machina_settings.ATTACHMENT_CACHE_NAME]
except InvalidCacheBackendError:
raise ImproperlyConfigured(
'The attachment cache backend ({}) is not configured'.format(
machina_settings.ATTACHMENT_CACHE_NAME,
),
)
return cache
|
python
|
def get_backend(self):
""" Returns the associated cache backend. """
try:
cache = caches[machina_settings.ATTACHMENT_CACHE_NAME]
except InvalidCacheBackendError:
raise ImproperlyConfigured(
'The attachment cache backend ({}) is not configured'.format(
machina_settings.ATTACHMENT_CACHE_NAME,
),
)
return cache
|
[
"def",
"get_backend",
"(",
"self",
")",
":",
"try",
":",
"cache",
"=",
"caches",
"[",
"machina_settings",
".",
"ATTACHMENT_CACHE_NAME",
"]",
"except",
"InvalidCacheBackendError",
":",
"raise",
"ImproperlyConfigured",
"(",
"'The attachment cache backend ({}) is not configured'",
".",
"format",
"(",
"machina_settings",
".",
"ATTACHMENT_CACHE_NAME",
",",
")",
",",
")",
"return",
"cache"
] |
Returns the associated cache backend.
|
[
"Returns",
"the",
"associated",
"cache",
"backend",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_attachments/cache.py#L33-L43
|
9,345
|
ellmetha/django-machina
|
machina/apps/forum_conversation/forum_attachments/cache.py
|
AttachmentCache.set
|
def set(self, key, files):
""" Stores the state of each file embedded in the request.FILES MultiValueDict instance.
This instance is assumed to be passed as the 'files' argument. Each state stored in the
cache is a dictionary containing the following values:
name
The name of the uploaded file.
size
The size of the uploaded file.
content_type
The content type of the uploaded file.
content_length
The content length of the uploaded file.
charset
The charset of the uploaded file.
content
The content of the uploaded file.
"""
files_states = {}
for name, upload in files.items():
# Generates the state of the file
state = {
'name': upload.name,
'size': upload.size,
'content_type': upload.content_type,
'charset': upload.charset,
'content': upload.file.read(),
}
files_states[name] = state
# Go to the first byte in the file for future use
upload.file.seek(0)
self.backend.set(key, files_states)
|
python
|
def set(self, key, files):
""" Stores the state of each file embedded in the request.FILES MultiValueDict instance.
This instance is assumed to be passed as the 'files' argument. Each state stored in the
cache is a dictionary containing the following values:
name
The name of the uploaded file.
size
The size of the uploaded file.
content_type
The content type of the uploaded file.
content_length
The content length of the uploaded file.
charset
The charset of the uploaded file.
content
The content of the uploaded file.
"""
files_states = {}
for name, upload in files.items():
# Generates the state of the file
state = {
'name': upload.name,
'size': upload.size,
'content_type': upload.content_type,
'charset': upload.charset,
'content': upload.file.read(),
}
files_states[name] = state
# Go to the first byte in the file for future use
upload.file.seek(0)
self.backend.set(key, files_states)
|
[
"def",
"set",
"(",
"self",
",",
"key",
",",
"files",
")",
":",
"files_states",
"=",
"{",
"}",
"for",
"name",
",",
"upload",
"in",
"files",
".",
"items",
"(",
")",
":",
"# Generates the state of the file",
"state",
"=",
"{",
"'name'",
":",
"upload",
".",
"name",
",",
"'size'",
":",
"upload",
".",
"size",
",",
"'content_type'",
":",
"upload",
".",
"content_type",
",",
"'charset'",
":",
"upload",
".",
"charset",
",",
"'content'",
":",
"upload",
".",
"file",
".",
"read",
"(",
")",
",",
"}",
"files_states",
"[",
"name",
"]",
"=",
"state",
"# Go to the first byte in the file for future use",
"upload",
".",
"file",
".",
"seek",
"(",
"0",
")",
"self",
".",
"backend",
".",
"set",
"(",
"key",
",",
"files_states",
")"
] |
Stores the state of each file embedded in the request.FILES MultiValueDict instance.
This instance is assumed to be passed as the 'files' argument. Each state stored in the
cache is a dictionary containing the following values:
name
The name of the uploaded file.
size
The size of the uploaded file.
content_type
The content type of the uploaded file.
content_length
The content length of the uploaded file.
charset
The charset of the uploaded file.
content
The content of the uploaded file.
|
[
"Stores",
"the",
"state",
"of",
"each",
"file",
"embedded",
"in",
"the",
"request",
".",
"FILES",
"MultiValueDict",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_attachments/cache.py#L45-L80
|
9,346
|
ellmetha/django-machina
|
machina/apps/forum_conversation/forum_attachments/cache.py
|
AttachmentCache.get
|
def get(self, key):
""" Regenerates a MultiValueDict instance containing the files related to all file states
stored for the given key.
"""
upload = None
files_states = self.backend.get(key)
files = MultiValueDict()
if files_states:
for name, state in files_states.items():
f = BytesIO()
f.write(state['content'])
# If the post is too large, we cannot use a
# InMemoryUploadedFile instance.
if state['size'] > settings.FILE_UPLOAD_MAX_MEMORY_SIZE:
upload = TemporaryUploadedFile(
state['name'],
state['content_type'],
state['size'],
state['charset'],
)
upload.file = f
else:
f = BytesIO()
f.write(state['content'])
upload = InMemoryUploadedFile(
file=f,
field_name=name,
name=state['name'],
content_type=state['content_type'],
size=state['size'],
charset=state['charset'],
)
files[name] = upload
# Go to the first byte in the file for future use
upload.file.seek(0)
return files
|
python
|
def get(self, key):
""" Regenerates a MultiValueDict instance containing the files related to all file states
stored for the given key.
"""
upload = None
files_states = self.backend.get(key)
files = MultiValueDict()
if files_states:
for name, state in files_states.items():
f = BytesIO()
f.write(state['content'])
# If the post is too large, we cannot use a
# InMemoryUploadedFile instance.
if state['size'] > settings.FILE_UPLOAD_MAX_MEMORY_SIZE:
upload = TemporaryUploadedFile(
state['name'],
state['content_type'],
state['size'],
state['charset'],
)
upload.file = f
else:
f = BytesIO()
f.write(state['content'])
upload = InMemoryUploadedFile(
file=f,
field_name=name,
name=state['name'],
content_type=state['content_type'],
size=state['size'],
charset=state['charset'],
)
files[name] = upload
# Go to the first byte in the file for future use
upload.file.seek(0)
return files
|
[
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"upload",
"=",
"None",
"files_states",
"=",
"self",
".",
"backend",
".",
"get",
"(",
"key",
")",
"files",
"=",
"MultiValueDict",
"(",
")",
"if",
"files_states",
":",
"for",
"name",
",",
"state",
"in",
"files_states",
".",
"items",
"(",
")",
":",
"f",
"=",
"BytesIO",
"(",
")",
"f",
".",
"write",
"(",
"state",
"[",
"'content'",
"]",
")",
"# If the post is too large, we cannot use a",
"# InMemoryUploadedFile instance.",
"if",
"state",
"[",
"'size'",
"]",
">",
"settings",
".",
"FILE_UPLOAD_MAX_MEMORY_SIZE",
":",
"upload",
"=",
"TemporaryUploadedFile",
"(",
"state",
"[",
"'name'",
"]",
",",
"state",
"[",
"'content_type'",
"]",
",",
"state",
"[",
"'size'",
"]",
",",
"state",
"[",
"'charset'",
"]",
",",
")",
"upload",
".",
"file",
"=",
"f",
"else",
":",
"f",
"=",
"BytesIO",
"(",
")",
"f",
".",
"write",
"(",
"state",
"[",
"'content'",
"]",
")",
"upload",
"=",
"InMemoryUploadedFile",
"(",
"file",
"=",
"f",
",",
"field_name",
"=",
"name",
",",
"name",
"=",
"state",
"[",
"'name'",
"]",
",",
"content_type",
"=",
"state",
"[",
"'content_type'",
"]",
",",
"size",
"=",
"state",
"[",
"'size'",
"]",
",",
"charset",
"=",
"state",
"[",
"'charset'",
"]",
",",
")",
"files",
"[",
"name",
"]",
"=",
"upload",
"# Go to the first byte in the file for future use",
"upload",
".",
"file",
".",
"seek",
"(",
"0",
")",
"return",
"files"
] |
Regenerates a MultiValueDict instance containing the files related to all file states
stored for the given key.
|
[
"Regenerates",
"a",
"MultiValueDict",
"instance",
"containing",
"the",
"files",
"related",
"to",
"all",
"file",
"states",
"stored",
"for",
"the",
"given",
"key",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_attachments/cache.py#L82-L120
|
9,347
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler.get_readable_forums
|
def get_readable_forums(self, forums, user):
""" Returns a queryset of forums that can be read by the considered user. """
# Any superuser should be able to read all the forums.
if user.is_superuser:
return forums
# Fetches the forums that can be read by the given user.
readable_forums = self._get_forums_for_user(
user, ['can_read_forum', ], use_tree_hierarchy=True)
return forums.filter(id__in=[f.id for f in readable_forums]) \
if isinstance(forums, (models.Manager, models.QuerySet)) \
else list(filter(lambda f: f in readable_forums, forums))
|
python
|
def get_readable_forums(self, forums, user):
""" Returns a queryset of forums that can be read by the considered user. """
# Any superuser should be able to read all the forums.
if user.is_superuser:
return forums
# Fetches the forums that can be read by the given user.
readable_forums = self._get_forums_for_user(
user, ['can_read_forum', ], use_tree_hierarchy=True)
return forums.filter(id__in=[f.id for f in readable_forums]) \
if isinstance(forums, (models.Manager, models.QuerySet)) \
else list(filter(lambda f: f in readable_forums, forums))
|
[
"def",
"get_readable_forums",
"(",
"self",
",",
"forums",
",",
"user",
")",
":",
"# Any superuser should be able to read all the forums.",
"if",
"user",
".",
"is_superuser",
":",
"return",
"forums",
"# Fetches the forums that can be read by the given user.",
"readable_forums",
"=",
"self",
".",
"_get_forums_for_user",
"(",
"user",
",",
"[",
"'can_read_forum'",
",",
"]",
",",
"use_tree_hierarchy",
"=",
"True",
")",
"return",
"forums",
".",
"filter",
"(",
"id__in",
"=",
"[",
"f",
".",
"id",
"for",
"f",
"in",
"readable_forums",
"]",
")",
"if",
"isinstance",
"(",
"forums",
",",
"(",
"models",
".",
"Manager",
",",
"models",
".",
"QuerySet",
")",
")",
"else",
"list",
"(",
"filter",
"(",
"lambda",
"f",
":",
"f",
"in",
"readable_forums",
",",
"forums",
")",
")"
] |
Returns a queryset of forums that can be read by the considered user.
|
[
"Returns",
"a",
"queryset",
"of",
"forums",
"that",
"can",
"be",
"read",
"by",
"the",
"considered",
"user",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L74-L85
|
9,348
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler.can_add_post
|
def can_add_post(self, topic, user):
""" Given a topic, checks whether the user can append posts to it. """
can_add_post = self._perform_basic_permission_check(
topic.forum, user, 'can_reply_to_topics',
)
can_add_post &= (
not topic.is_locked or
self._perform_basic_permission_check(topic.forum, user, 'can_reply_to_locked_topics')
)
return can_add_post
|
python
|
def can_add_post(self, topic, user):
""" Given a topic, checks whether the user can append posts to it. """
can_add_post = self._perform_basic_permission_check(
topic.forum, user, 'can_reply_to_topics',
)
can_add_post &= (
not topic.is_locked or
self._perform_basic_permission_check(topic.forum, user, 'can_reply_to_locked_topics')
)
return can_add_post
|
[
"def",
"can_add_post",
"(",
"self",
",",
"topic",
",",
"user",
")",
":",
"can_add_post",
"=",
"self",
".",
"_perform_basic_permission_check",
"(",
"topic",
".",
"forum",
",",
"user",
",",
"'can_reply_to_topics'",
",",
")",
"can_add_post",
"&=",
"(",
"not",
"topic",
".",
"is_locked",
"or",
"self",
".",
"_perform_basic_permission_check",
"(",
"topic",
".",
"forum",
",",
"user",
",",
"'can_reply_to_locked_topics'",
")",
")",
"return",
"can_add_post"
] |
Given a topic, checks whether the user can append posts to it.
|
[
"Given",
"a",
"topic",
"checks",
"whether",
"the",
"user",
"can",
"append",
"posts",
"to",
"it",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L114-L123
|
9,349
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler.can_edit_post
|
def can_edit_post(self, post, user):
""" Given a forum post, checks whether the user can edit the latter. """
checker = self._get_checker(user)
# A user can edit a post if...
# they are a superuser
# they are the original poster of the forum post
# they belong to the forum moderators
is_author = self._is_post_author(post, user)
can_edit = (
user.is_superuser or
(
is_author and checker.has_perm('can_edit_own_posts', post.topic.forum) and
not post.topic.is_locked
) or
checker.has_perm('can_edit_posts', post.topic.forum)
)
return can_edit
|
python
|
def can_edit_post(self, post, user):
""" Given a forum post, checks whether the user can edit the latter. """
checker = self._get_checker(user)
# A user can edit a post if...
# they are a superuser
# they are the original poster of the forum post
# they belong to the forum moderators
is_author = self._is_post_author(post, user)
can_edit = (
user.is_superuser or
(
is_author and checker.has_perm('can_edit_own_posts', post.topic.forum) and
not post.topic.is_locked
) or
checker.has_perm('can_edit_posts', post.topic.forum)
)
return can_edit
|
[
"def",
"can_edit_post",
"(",
"self",
",",
"post",
",",
"user",
")",
":",
"checker",
"=",
"self",
".",
"_get_checker",
"(",
"user",
")",
"# A user can edit a post if...",
"# they are a superuser",
"# they are the original poster of the forum post",
"# they belong to the forum moderators",
"is_author",
"=",
"self",
".",
"_is_post_author",
"(",
"post",
",",
"user",
")",
"can_edit",
"=",
"(",
"user",
".",
"is_superuser",
"or",
"(",
"is_author",
"and",
"checker",
".",
"has_perm",
"(",
"'can_edit_own_posts'",
",",
"post",
".",
"topic",
".",
"forum",
")",
"and",
"not",
"post",
".",
"topic",
".",
"is_locked",
")",
"or",
"checker",
".",
"has_perm",
"(",
"'can_edit_posts'",
",",
"post",
".",
"topic",
".",
"forum",
")",
")",
"return",
"can_edit"
] |
Given a forum post, checks whether the user can edit the latter.
|
[
"Given",
"a",
"forum",
"post",
"checks",
"whether",
"the",
"user",
"can",
"edit",
"the",
"latter",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L125-L142
|
9,350
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler.can_delete_post
|
def can_delete_post(self, post, user):
"""
Given a forum post, checks whether the user can delete the latter.
"""
checker = self._get_checker(user)
# A user can delete a post if...
# they are a superuser
# they are the original poster of the forum post
# they belong to the forum moderators
is_author = self._is_post_author(post, user)
can_delete = (
user.is_superuser or
(is_author and checker.has_perm('can_delete_own_posts', post.topic.forum)) or
checker.has_perm('can_delete_posts', post.topic.forum)
)
return can_delete
|
python
|
def can_delete_post(self, post, user):
"""
Given a forum post, checks whether the user can delete the latter.
"""
checker = self._get_checker(user)
# A user can delete a post if...
# they are a superuser
# they are the original poster of the forum post
# they belong to the forum moderators
is_author = self._is_post_author(post, user)
can_delete = (
user.is_superuser or
(is_author and checker.has_perm('can_delete_own_posts', post.topic.forum)) or
checker.has_perm('can_delete_posts', post.topic.forum)
)
return can_delete
|
[
"def",
"can_delete_post",
"(",
"self",
",",
"post",
",",
"user",
")",
":",
"checker",
"=",
"self",
".",
"_get_checker",
"(",
"user",
")",
"# A user can delete a post if...",
"# they are a superuser",
"# they are the original poster of the forum post",
"# they belong to the forum moderators",
"is_author",
"=",
"self",
".",
"_is_post_author",
"(",
"post",
",",
"user",
")",
"can_delete",
"=",
"(",
"user",
".",
"is_superuser",
"or",
"(",
"is_author",
"and",
"checker",
".",
"has_perm",
"(",
"'can_delete_own_posts'",
",",
"post",
".",
"topic",
".",
"forum",
")",
")",
"or",
"checker",
".",
"has_perm",
"(",
"'can_delete_posts'",
",",
"post",
".",
"topic",
".",
"forum",
")",
")",
"return",
"can_delete"
] |
Given a forum post, checks whether the user can delete the latter.
|
[
"Given",
"a",
"forum",
"post",
"checks",
"whether",
"the",
"user",
"can",
"delete",
"the",
"latter",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L144-L160
|
9,351
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler.can_vote_in_poll
|
def can_vote_in_poll(self, poll, user):
""" Given a poll, checks whether the user can answer to it. """
# First we have to check if the poll is curently open
if poll.duration:
poll_dtend = poll.created + dt.timedelta(days=poll.duration)
if poll_dtend < now():
return False
# Is this user allowed to vote in polls in the current forum?
can_vote = (
self._perform_basic_permission_check(poll.topic.forum, user, 'can_vote_in_polls') and
not poll.topic.is_locked
)
# Retrieve the user votes for the considered poll
user_votes = TopicPollVote.objects.filter(poll_option__poll=poll)
if user.is_anonymous:
forum_key = get_anonymous_user_forum_key(user)
if forum_key:
user_votes = user_votes.filter(anonymous_key=forum_key)
else:
# If the forum key of the anonymous user cannot be retrieved, the user should not be
# allowed to vote in the considered poll.
user_votes = user_votes.none()
can_vote = False
else:
user_votes = user_votes.filter(voter=user)
# If the user has already voted, they can vote again if the vote changes are allowed
if user_votes.exists() and can_vote:
can_vote = poll.user_changes
return can_vote
|
python
|
def can_vote_in_poll(self, poll, user):
""" Given a poll, checks whether the user can answer to it. """
# First we have to check if the poll is curently open
if poll.duration:
poll_dtend = poll.created + dt.timedelta(days=poll.duration)
if poll_dtend < now():
return False
# Is this user allowed to vote in polls in the current forum?
can_vote = (
self._perform_basic_permission_check(poll.topic.forum, user, 'can_vote_in_polls') and
not poll.topic.is_locked
)
# Retrieve the user votes for the considered poll
user_votes = TopicPollVote.objects.filter(poll_option__poll=poll)
if user.is_anonymous:
forum_key = get_anonymous_user_forum_key(user)
if forum_key:
user_votes = user_votes.filter(anonymous_key=forum_key)
else:
# If the forum key of the anonymous user cannot be retrieved, the user should not be
# allowed to vote in the considered poll.
user_votes = user_votes.none()
can_vote = False
else:
user_votes = user_votes.filter(voter=user)
# If the user has already voted, they can vote again if the vote changes are allowed
if user_votes.exists() and can_vote:
can_vote = poll.user_changes
return can_vote
|
[
"def",
"can_vote_in_poll",
"(",
"self",
",",
"poll",
",",
"user",
")",
":",
"# First we have to check if the poll is curently open",
"if",
"poll",
".",
"duration",
":",
"poll_dtend",
"=",
"poll",
".",
"created",
"+",
"dt",
".",
"timedelta",
"(",
"days",
"=",
"poll",
".",
"duration",
")",
"if",
"poll_dtend",
"<",
"now",
"(",
")",
":",
"return",
"False",
"# Is this user allowed to vote in polls in the current forum?",
"can_vote",
"=",
"(",
"self",
".",
"_perform_basic_permission_check",
"(",
"poll",
".",
"topic",
".",
"forum",
",",
"user",
",",
"'can_vote_in_polls'",
")",
"and",
"not",
"poll",
".",
"topic",
".",
"is_locked",
")",
"# Retrieve the user votes for the considered poll",
"user_votes",
"=",
"TopicPollVote",
".",
"objects",
".",
"filter",
"(",
"poll_option__poll",
"=",
"poll",
")",
"if",
"user",
".",
"is_anonymous",
":",
"forum_key",
"=",
"get_anonymous_user_forum_key",
"(",
"user",
")",
"if",
"forum_key",
":",
"user_votes",
"=",
"user_votes",
".",
"filter",
"(",
"anonymous_key",
"=",
"forum_key",
")",
"else",
":",
"# If the forum key of the anonymous user cannot be retrieved, the user should not be",
"# allowed to vote in the considered poll.",
"user_votes",
"=",
"user_votes",
".",
"none",
"(",
")",
"can_vote",
"=",
"False",
"else",
":",
"user_votes",
"=",
"user_votes",
".",
"filter",
"(",
"voter",
"=",
"user",
")",
"# If the user has already voted, they can vote again if the vote changes are allowed",
"if",
"user_votes",
".",
"exists",
"(",
")",
"and",
"can_vote",
":",
"can_vote",
"=",
"poll",
".",
"user_changes",
"return",
"can_vote"
] |
Given a poll, checks whether the user can answer to it.
|
[
"Given",
"a",
"poll",
"checks",
"whether",
"the",
"user",
"can",
"answer",
"to",
"it",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L168-L200
|
9,352
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler.can_subscribe_to_topic
|
def can_subscribe_to_topic(self, topic, user):
""" Given a topic, checks whether the user can add it to their subscription list. """
# A user can subscribe to topics if they are authenticated and if they have the permission
# to read the related forum. Of course a user can subscribe only if they have not already
# subscribed to the considered topic.
return (
user.is_authenticated and
not topic.has_subscriber(user) and
self._perform_basic_permission_check(topic.forum, user, 'can_read_forum')
)
|
python
|
def can_subscribe_to_topic(self, topic, user):
""" Given a topic, checks whether the user can add it to their subscription list. """
# A user can subscribe to topics if they are authenticated and if they have the permission
# to read the related forum. Of course a user can subscribe only if they have not already
# subscribed to the considered topic.
return (
user.is_authenticated and
not topic.has_subscriber(user) and
self._perform_basic_permission_check(topic.forum, user, 'can_read_forum')
)
|
[
"def",
"can_subscribe_to_topic",
"(",
"self",
",",
"topic",
",",
"user",
")",
":",
"# A user can subscribe to topics if they are authenticated and if they have the permission",
"# to read the related forum. Of course a user can subscribe only if they have not already",
"# subscribed to the considered topic.",
"return",
"(",
"user",
".",
"is_authenticated",
"and",
"not",
"topic",
".",
"has_subscriber",
"(",
"user",
")",
"and",
"self",
".",
"_perform_basic_permission_check",
"(",
"topic",
".",
"forum",
",",
"user",
",",
"'can_read_forum'",
")",
")"
] |
Given a topic, checks whether the user can add it to their subscription list.
|
[
"Given",
"a",
"topic",
"checks",
"whether",
"the",
"user",
"can",
"add",
"it",
"to",
"their",
"subscription",
"list",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L214-L223
|
9,353
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler.can_unsubscribe_from_topic
|
def can_unsubscribe_from_topic(self, topic, user):
""" Given a topic, checks whether the user can remove it from their subscription list. """
# A user can unsubscribe from topics if they are authenticated and if they have the
# permission to read the related forum. Of course a user can unsubscribe only if they are
# already a subscriber of the considered topic.
return (
user.is_authenticated and
topic.has_subscriber(user) and
self._perform_basic_permission_check(topic.forum, user, 'can_read_forum')
)
|
python
|
def can_unsubscribe_from_topic(self, topic, user):
""" Given a topic, checks whether the user can remove it from their subscription list. """
# A user can unsubscribe from topics if they are authenticated and if they have the
# permission to read the related forum. Of course a user can unsubscribe only if they are
# already a subscriber of the considered topic.
return (
user.is_authenticated and
topic.has_subscriber(user) and
self._perform_basic_permission_check(topic.forum, user, 'can_read_forum')
)
|
[
"def",
"can_unsubscribe_from_topic",
"(",
"self",
",",
"topic",
",",
"user",
")",
":",
"# A user can unsubscribe from topics if they are authenticated and if they have the",
"# permission to read the related forum. Of course a user can unsubscribe only if they are",
"# already a subscriber of the considered topic.",
"return",
"(",
"user",
".",
"is_authenticated",
"and",
"topic",
".",
"has_subscriber",
"(",
"user",
")",
"and",
"self",
".",
"_perform_basic_permission_check",
"(",
"topic",
".",
"forum",
",",
"user",
",",
"'can_read_forum'",
")",
")"
] |
Given a topic, checks whether the user can remove it from their subscription list.
|
[
"Given",
"a",
"topic",
"checks",
"whether",
"the",
"user",
"can",
"remove",
"it",
"from",
"their",
"subscription",
"list",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L225-L234
|
9,354
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler.get_target_forums_for_moved_topics
|
def get_target_forums_for_moved_topics(self, user):
""" Returns a list of forums in which the considered user can add topics that have been
moved from another forum.
"""
return [f for f in self._get_forums_for_user(user, ['can_move_topics', ]) if f.is_forum]
|
python
|
def get_target_forums_for_moved_topics(self, user):
""" Returns a list of forums in which the considered user can add topics that have been
moved from another forum.
"""
return [f for f in self._get_forums_for_user(user, ['can_move_topics', ]) if f.is_forum]
|
[
"def",
"get_target_forums_for_moved_topics",
"(",
"self",
",",
"user",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"self",
".",
"_get_forums_for_user",
"(",
"user",
",",
"[",
"'can_move_topics'",
",",
"]",
")",
"if",
"f",
".",
"is_forum",
"]"
] |
Returns a list of forums in which the considered user can add topics that have been
moved from another forum.
|
[
"Returns",
"a",
"list",
"of",
"forums",
"in",
"which",
"the",
"considered",
"user",
"can",
"add",
"topics",
"that",
"have",
"been",
"moved",
"from",
"another",
"forum",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L254-L258
|
9,355
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler.can_update_topics_to_sticky_topics
|
def can_update_topics_to_sticky_topics(self, forum, user):
""" Given a forum, checks whether the user can change its topic types to sticky topics. """
return (
self._perform_basic_permission_check(forum, user, 'can_edit_posts') and
self._perform_basic_permission_check(forum, user, 'can_post_stickies')
)
|
python
|
def can_update_topics_to_sticky_topics(self, forum, user):
""" Given a forum, checks whether the user can change its topic types to sticky topics. """
return (
self._perform_basic_permission_check(forum, user, 'can_edit_posts') and
self._perform_basic_permission_check(forum, user, 'can_post_stickies')
)
|
[
"def",
"can_update_topics_to_sticky_topics",
"(",
"self",
",",
"forum",
",",
"user",
")",
":",
"return",
"(",
"self",
".",
"_perform_basic_permission_check",
"(",
"forum",
",",
"user",
",",
"'can_edit_posts'",
")",
"and",
"self",
".",
"_perform_basic_permission_check",
"(",
"forum",
",",
"user",
",",
"'can_post_stickies'",
")",
")"
] |
Given a forum, checks whether the user can change its topic types to sticky topics.
|
[
"Given",
"a",
"forum",
"checks",
"whether",
"the",
"user",
"can",
"change",
"its",
"topic",
"types",
"to",
"sticky",
"topics",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L273-L278
|
9,356
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler.can_update_topics_to_announces
|
def can_update_topics_to_announces(self, forum, user):
""" Given a forum, checks whether the user can change its topic types to announces. """
return (
self._perform_basic_permission_check(forum, user, 'can_edit_posts') and
self._perform_basic_permission_check(forum, user, 'can_post_announcements')
)
|
python
|
def can_update_topics_to_announces(self, forum, user):
""" Given a forum, checks whether the user can change its topic types to announces. """
return (
self._perform_basic_permission_check(forum, user, 'can_edit_posts') and
self._perform_basic_permission_check(forum, user, 'can_post_announcements')
)
|
[
"def",
"can_update_topics_to_announces",
"(",
"self",
",",
"forum",
",",
"user",
")",
":",
"return",
"(",
"self",
".",
"_perform_basic_permission_check",
"(",
"forum",
",",
"user",
",",
"'can_edit_posts'",
")",
"and",
"self",
".",
"_perform_basic_permission_check",
"(",
"forum",
",",
"user",
",",
"'can_post_announcements'",
")",
")"
] |
Given a forum, checks whether the user can change its topic types to announces.
|
[
"Given",
"a",
"forum",
"checks",
"whether",
"the",
"user",
"can",
"change",
"its",
"topic",
"types",
"to",
"announces",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L280-L285
|
9,357
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler._get_hidden_forum_ids
|
def _get_hidden_forum_ids(self, forums, user):
""" Given a set of forums and a user, returns the list of forums that are not visible by
this user.
"""
visible_forums = self._get_forums_for_user(
user, ['can_see_forum', 'can_read_forum', ], use_tree_hierarchy=True,
)
return forums.exclude(id__in=[f.id for f in visible_forums])
|
python
|
def _get_hidden_forum_ids(self, forums, user):
""" Given a set of forums and a user, returns the list of forums that are not visible by
this user.
"""
visible_forums = self._get_forums_for_user(
user, ['can_see_forum', 'can_read_forum', ], use_tree_hierarchy=True,
)
return forums.exclude(id__in=[f.id for f in visible_forums])
|
[
"def",
"_get_hidden_forum_ids",
"(",
"self",
",",
"forums",
",",
"user",
")",
":",
"visible_forums",
"=",
"self",
".",
"_get_forums_for_user",
"(",
"user",
",",
"[",
"'can_see_forum'",
",",
"'can_read_forum'",
",",
"]",
",",
"use_tree_hierarchy",
"=",
"True",
",",
")",
"return",
"forums",
".",
"exclude",
"(",
"id__in",
"=",
"[",
"f",
".",
"id",
"for",
"f",
"in",
"visible_forums",
"]",
")"
] |
Given a set of forums and a user, returns the list of forums that are not visible by
this user.
|
[
"Given",
"a",
"set",
"of",
"forums",
"and",
"a",
"user",
"returns",
"the",
"list",
"of",
"forums",
"that",
"are",
"not",
"visible",
"by",
"this",
"user",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L303-L310
|
9,358
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler._perform_basic_permission_check
|
def _perform_basic_permission_check(self, forum, user, permission):
""" Given a forum and a user, checks whether the latter has the passed permission.
The workflow is:
1. The permission is granted if the user is a superuser
2. If not, a check is performed with the given permission
"""
checker = self._get_checker(user)
# The action is granted if...
# the user is the superuser
# the user has the permission to do so
check = (user.is_superuser or checker.has_perm(permission, forum))
return check
|
python
|
def _perform_basic_permission_check(self, forum, user, permission):
""" Given a forum and a user, checks whether the latter has the passed permission.
The workflow is:
1. The permission is granted if the user is a superuser
2. If not, a check is performed with the given permission
"""
checker = self._get_checker(user)
# The action is granted if...
# the user is the superuser
# the user has the permission to do so
check = (user.is_superuser or checker.has_perm(permission, forum))
return check
|
[
"def",
"_perform_basic_permission_check",
"(",
"self",
",",
"forum",
",",
"user",
",",
"permission",
")",
":",
"checker",
"=",
"self",
".",
"_get_checker",
"(",
"user",
")",
"# The action is granted if...",
"# the user is the superuser",
"# the user has the permission to do so",
"check",
"=",
"(",
"user",
".",
"is_superuser",
"or",
"checker",
".",
"has_perm",
"(",
"permission",
",",
"forum",
")",
")",
"return",
"check"
] |
Given a forum and a user, checks whether the latter has the passed permission.
The workflow is:
1. The permission is granted if the user is a superuser
2. If not, a check is performed with the given permission
|
[
"Given",
"a",
"forum",
"and",
"a",
"user",
"checks",
"whether",
"the",
"latter",
"has",
"the",
"passed",
"permission",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L480-L495
|
9,359
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler._get_checker
|
def _get_checker(self, user):
""" Return a ForumPermissionChecker instance for the given user. """
user_perm_checkers_cache_key = user.id if not user.is_anonymous else 'anonymous'
if user_perm_checkers_cache_key in self._user_perm_checkers_cache:
return self._user_perm_checkers_cache[user_perm_checkers_cache_key]
checker = ForumPermissionChecker(user)
self._user_perm_checkers_cache[user_perm_checkers_cache_key] = checker
return checker
|
python
|
def _get_checker(self, user):
""" Return a ForumPermissionChecker instance for the given user. """
user_perm_checkers_cache_key = user.id if not user.is_anonymous else 'anonymous'
if user_perm_checkers_cache_key in self._user_perm_checkers_cache:
return self._user_perm_checkers_cache[user_perm_checkers_cache_key]
checker = ForumPermissionChecker(user)
self._user_perm_checkers_cache[user_perm_checkers_cache_key] = checker
return checker
|
[
"def",
"_get_checker",
"(",
"self",
",",
"user",
")",
":",
"user_perm_checkers_cache_key",
"=",
"user",
".",
"id",
"if",
"not",
"user",
".",
"is_anonymous",
"else",
"'anonymous'",
"if",
"user_perm_checkers_cache_key",
"in",
"self",
".",
"_user_perm_checkers_cache",
":",
"return",
"self",
".",
"_user_perm_checkers_cache",
"[",
"user_perm_checkers_cache_key",
"]",
"checker",
"=",
"ForumPermissionChecker",
"(",
"user",
")",
"self",
".",
"_user_perm_checkers_cache",
"[",
"user_perm_checkers_cache_key",
"]",
"=",
"checker",
"return",
"checker"
] |
Return a ForumPermissionChecker instance for the given user.
|
[
"Return",
"a",
"ForumPermissionChecker",
"instance",
"for",
"the",
"given",
"user",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L497-L506
|
9,360
|
ellmetha/django-machina
|
machina/apps/forum_permission/handler.py
|
PermissionHandler._get_all_forums
|
def _get_all_forums(self):
""" Returns all forums. """
if not hasattr(self, '_all_forums'):
self._all_forums = list(Forum.objects.all())
return self._all_forums
|
python
|
def _get_all_forums(self):
""" Returns all forums. """
if not hasattr(self, '_all_forums'):
self._all_forums = list(Forum.objects.all())
return self._all_forums
|
[
"def",
"_get_all_forums",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_all_forums'",
")",
":",
"self",
".",
"_all_forums",
"=",
"list",
"(",
"Forum",
".",
"objects",
".",
"all",
"(",
")",
")",
"return",
"self",
".",
"_all_forums"
] |
Returns all forums.
|
[
"Returns",
"all",
"forums",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/handler.py#L508-L512
|
9,361
|
ellmetha/django-machina
|
machina/apps/forum/views.py
|
ForumView.get_forum
|
def get_forum(self):
""" Returns the forum to consider. """
if not hasattr(self, 'forum'):
self.forum = get_object_or_404(Forum, pk=self.kwargs['pk'])
return self.forum
|
python
|
def get_forum(self):
""" Returns the forum to consider. """
if not hasattr(self, 'forum'):
self.forum = get_object_or_404(Forum, pk=self.kwargs['pk'])
return self.forum
|
[
"def",
"get_forum",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'forum'",
")",
":",
"self",
".",
"forum",
"=",
"get_object_or_404",
"(",
"Forum",
",",
"pk",
"=",
"self",
".",
"kwargs",
"[",
"'pk'",
"]",
")",
"return",
"self",
".",
"forum"
] |
Returns the forum to consider.
|
[
"Returns",
"the",
"forum",
"to",
"consider",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/views.py#L74-L78
|
9,362
|
ellmetha/django-machina
|
machina/apps/forum/views.py
|
ForumView.send_signal
|
def send_signal(self, request, response, forum):
""" Sends the signal associated with the view. """
self.view_signal.send(
sender=self, forum=forum, user=request.user, request=request, response=response,
)
|
python
|
def send_signal(self, request, response, forum):
""" Sends the signal associated with the view. """
self.view_signal.send(
sender=self, forum=forum, user=request.user, request=request, response=response,
)
|
[
"def",
"send_signal",
"(",
"self",
",",
"request",
",",
"response",
",",
"forum",
")",
":",
"self",
".",
"view_signal",
".",
"send",
"(",
"sender",
"=",
"self",
",",
"forum",
"=",
"forum",
",",
"user",
"=",
"request",
".",
"user",
",",
"request",
"=",
"request",
",",
"response",
"=",
"response",
",",
")"
] |
Sends the signal associated with the view.
|
[
"Sends",
"the",
"signal",
"associated",
"with",
"the",
"view",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/views.py#L123-L127
|
9,363
|
ellmetha/django-machina
|
machina/apps/forum_conversation/abstract_models.py
|
AbstractTopic.has_subscriber
|
def has_subscriber(self, user):
""" Returns ``True`` if the given user is a subscriber of this topic. """
if not hasattr(self, '_subscribers'):
self._subscribers = list(self.subscribers.all())
return user in self._subscribers
|
python
|
def has_subscriber(self, user):
""" Returns ``True`` if the given user is a subscriber of this topic. """
if not hasattr(self, '_subscribers'):
self._subscribers = list(self.subscribers.all())
return user in self._subscribers
|
[
"def",
"has_subscriber",
"(",
"self",
",",
"user",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_subscribers'",
")",
":",
"self",
".",
"_subscribers",
"=",
"list",
"(",
"self",
".",
"subscribers",
".",
"all",
"(",
")",
")",
"return",
"user",
"in",
"self",
".",
"_subscribers"
] |
Returns ``True`` if the given user is a subscriber of this topic.
|
[
"Returns",
"True",
"if",
"the",
"given",
"user",
"is",
"a",
"subscriber",
"of",
"this",
"topic",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L133-L137
|
9,364
|
ellmetha/django-machina
|
machina/apps/forum_conversation/abstract_models.py
|
AbstractTopic.clean
|
def clean(self):
""" Validates the topic instance. """
super().clean()
if self.forum.is_category or self.forum.is_link:
raise ValidationError(
_('A topic can not be associated with a category or a link forum')
)
|
python
|
def clean(self):
""" Validates the topic instance. """
super().clean()
if self.forum.is_category or self.forum.is_link:
raise ValidationError(
_('A topic can not be associated with a category or a link forum')
)
|
[
"def",
"clean",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"clean",
"(",
")",
"if",
"self",
".",
"forum",
".",
"is_category",
"or",
"self",
".",
"forum",
".",
"is_link",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A topic can not be associated with a category or a link forum'",
")",
")"
] |
Validates the topic instance.
|
[
"Validates",
"the",
"topic",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L139-L145
|
9,365
|
ellmetha/django-machina
|
machina/apps/forum_conversation/abstract_models.py
|
AbstractTopic.save
|
def save(self, *args, **kwargs):
""" Saves the topic instance. """
# It is vital to track the changes of the forum associated with a topic in order to
# maintain counters up-to-date.
old_instance = None
if self.pk:
old_instance = self.__class__._default_manager.get(pk=self.pk)
# Update the slug field
self.slug = slugify(force_text(self.subject), allow_unicode=True)
# Do the save
super().save(*args, **kwargs)
# If any change has been made to the parent forum, trigger the update of the counters
if old_instance and old_instance.forum != self.forum:
self.update_trackers()
# The previous parent forum counters should also be updated
if old_instance.forum:
old_forum = old_instance.forum
old_forum.refresh_from_db()
old_forum.update_trackers()
|
python
|
def save(self, *args, **kwargs):
""" Saves the topic instance. """
# It is vital to track the changes of the forum associated with a topic in order to
# maintain counters up-to-date.
old_instance = None
if self.pk:
old_instance = self.__class__._default_manager.get(pk=self.pk)
# Update the slug field
self.slug = slugify(force_text(self.subject), allow_unicode=True)
# Do the save
super().save(*args, **kwargs)
# If any change has been made to the parent forum, trigger the update of the counters
if old_instance and old_instance.forum != self.forum:
self.update_trackers()
# The previous parent forum counters should also be updated
if old_instance.forum:
old_forum = old_instance.forum
old_forum.refresh_from_db()
old_forum.update_trackers()
|
[
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# It is vital to track the changes of the forum associated with a topic in order to",
"# maintain counters up-to-date.",
"old_instance",
"=",
"None",
"if",
"self",
".",
"pk",
":",
"old_instance",
"=",
"self",
".",
"__class__",
".",
"_default_manager",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"pk",
")",
"# Update the slug field",
"self",
".",
"slug",
"=",
"slugify",
"(",
"force_text",
"(",
"self",
".",
"subject",
")",
",",
"allow_unicode",
"=",
"True",
")",
"# Do the save",
"super",
"(",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# If any change has been made to the parent forum, trigger the update of the counters",
"if",
"old_instance",
"and",
"old_instance",
".",
"forum",
"!=",
"self",
".",
"forum",
":",
"self",
".",
"update_trackers",
"(",
")",
"# The previous parent forum counters should also be updated",
"if",
"old_instance",
".",
"forum",
":",
"old_forum",
"=",
"old_instance",
".",
"forum",
"old_forum",
".",
"refresh_from_db",
"(",
")",
"old_forum",
".",
"update_trackers",
"(",
")"
] |
Saves the topic instance.
|
[
"Saves",
"the",
"topic",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L147-L168
|
9,366
|
ellmetha/django-machina
|
machina/apps/forum_conversation/abstract_models.py
|
AbstractTopic.update_trackers
|
def update_trackers(self):
""" Updates the denormalized trackers associated with the topic instance. """
self.posts_count = self.posts.filter(approved=True).count()
first_post = self.posts.all().order_by('created').first()
last_post = self.posts.filter(approved=True).order_by('-created').first()
self.first_post = first_post
self.last_post = last_post
self.last_post_on = last_post.created if last_post else None
self._simple_save()
# Trigger the forum-level trackers update
self.forum.update_trackers()
|
python
|
def update_trackers(self):
""" Updates the denormalized trackers associated with the topic instance. """
self.posts_count = self.posts.filter(approved=True).count()
first_post = self.posts.all().order_by('created').first()
last_post = self.posts.filter(approved=True).order_by('-created').first()
self.first_post = first_post
self.last_post = last_post
self.last_post_on = last_post.created if last_post else None
self._simple_save()
# Trigger the forum-level trackers update
self.forum.update_trackers()
|
[
"def",
"update_trackers",
"(",
"self",
")",
":",
"self",
".",
"posts_count",
"=",
"self",
".",
"posts",
".",
"filter",
"(",
"approved",
"=",
"True",
")",
".",
"count",
"(",
")",
"first_post",
"=",
"self",
".",
"posts",
".",
"all",
"(",
")",
".",
"order_by",
"(",
"'created'",
")",
".",
"first",
"(",
")",
"last_post",
"=",
"self",
".",
"posts",
".",
"filter",
"(",
"approved",
"=",
"True",
")",
".",
"order_by",
"(",
"'-created'",
")",
".",
"first",
"(",
")",
"self",
".",
"first_post",
"=",
"first_post",
"self",
".",
"last_post",
"=",
"last_post",
"self",
".",
"last_post_on",
"=",
"last_post",
".",
"created",
"if",
"last_post",
"else",
"None",
"self",
".",
"_simple_save",
"(",
")",
"# Trigger the forum-level trackers update",
"self",
".",
"forum",
".",
"update_trackers",
"(",
")"
] |
Updates the denormalized trackers associated with the topic instance.
|
[
"Updates",
"the",
"denormalized",
"trackers",
"associated",
"with",
"the",
"topic",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L188-L198
|
9,367
|
ellmetha/django-machina
|
machina/apps/forum_conversation/abstract_models.py
|
AbstractPost.is_topic_head
|
def is_topic_head(self):
""" Returns ``True`` if the post is the first post of the topic. """
return self.topic.first_post.id == self.id if self.topic.first_post else False
|
python
|
def is_topic_head(self):
""" Returns ``True`` if the post is the first post of the topic. """
return self.topic.first_post.id == self.id if self.topic.first_post else False
|
[
"def",
"is_topic_head",
"(",
"self",
")",
":",
"return",
"self",
".",
"topic",
".",
"first_post",
".",
"id",
"==",
"self",
".",
"id",
"if",
"self",
".",
"topic",
".",
"first_post",
"else",
"False"
] |
Returns ``True`` if the post is the first post of the topic.
|
[
"Returns",
"True",
"if",
"the",
"post",
"is",
"the",
"first",
"post",
"of",
"the",
"topic",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L269-L271
|
9,368
|
ellmetha/django-machina
|
machina/apps/forum_conversation/abstract_models.py
|
AbstractPost.is_topic_tail
|
def is_topic_tail(self):
""" Returns ``True`` if the post is the last post of the topic. """
return self.topic.last_post.id == self.id if self.topic.last_post else False
|
python
|
def is_topic_tail(self):
""" Returns ``True`` if the post is the last post of the topic. """
return self.topic.last_post.id == self.id if self.topic.last_post else False
|
[
"def",
"is_topic_tail",
"(",
"self",
")",
":",
"return",
"self",
".",
"topic",
".",
"last_post",
".",
"id",
"==",
"self",
".",
"id",
"if",
"self",
".",
"topic",
".",
"last_post",
"else",
"False"
] |
Returns ``True`` if the post is the last post of the topic.
|
[
"Returns",
"True",
"if",
"the",
"post",
"is",
"the",
"last",
"post",
"of",
"the",
"topic",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L274-L276
|
9,369
|
ellmetha/django-machina
|
machina/apps/forum_conversation/abstract_models.py
|
AbstractPost.position
|
def position(self):
""" Returns an integer corresponding to the position of the post in the topic. """
position = self.topic.posts.filter(Q(created__lt=self.created) | Q(id=self.id)).count()
return position
|
python
|
def position(self):
""" Returns an integer corresponding to the position of the post in the topic. """
position = self.topic.posts.filter(Q(created__lt=self.created) | Q(id=self.id)).count()
return position
|
[
"def",
"position",
"(",
"self",
")",
":",
"position",
"=",
"self",
".",
"topic",
".",
"posts",
".",
"filter",
"(",
"Q",
"(",
"created__lt",
"=",
"self",
".",
"created",
")",
"|",
"Q",
"(",
"id",
"=",
"self",
".",
"id",
")",
")",
".",
"count",
"(",
")",
"return",
"position"
] |
Returns an integer corresponding to the position of the post in the topic.
|
[
"Returns",
"an",
"integer",
"corresponding",
"to",
"the",
"position",
"of",
"the",
"post",
"in",
"the",
"topic",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L284-L287
|
9,370
|
ellmetha/django-machina
|
machina/apps/forum_conversation/abstract_models.py
|
AbstractPost.clean
|
def clean(self):
""" Validates the post instance. """
super().clean()
# At least a poster (user) or a session key must be associated with
# the post.
if self.poster is None and self.anonymous_key is None:
raise ValidationError(
_('A user id or an anonymous key must be associated with a post.'),
)
if self.poster and self.anonymous_key:
raise ValidationError(
_('A user id or an anonymous key must be associated with a post, but not both.'),
)
if self.anonymous_key and not self.username:
raise ValidationError(_('A username must be specified if the poster is anonymous'))
|
python
|
def clean(self):
""" Validates the post instance. """
super().clean()
# At least a poster (user) or a session key must be associated with
# the post.
if self.poster is None and self.anonymous_key is None:
raise ValidationError(
_('A user id or an anonymous key must be associated with a post.'),
)
if self.poster and self.anonymous_key:
raise ValidationError(
_('A user id or an anonymous key must be associated with a post, but not both.'),
)
if self.anonymous_key and not self.username:
raise ValidationError(_('A username must be specified if the poster is anonymous'))
|
[
"def",
"clean",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"clean",
"(",
")",
"# At least a poster (user) or a session key must be associated with",
"# the post.",
"if",
"self",
".",
"poster",
"is",
"None",
"and",
"self",
".",
"anonymous_key",
"is",
"None",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A user id or an anonymous key must be associated with a post.'",
")",
",",
")",
"if",
"self",
".",
"poster",
"and",
"self",
".",
"anonymous_key",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A user id or an anonymous key must be associated with a post, but not both.'",
")",
",",
")",
"if",
"self",
".",
"anonymous_key",
"and",
"not",
"self",
".",
"username",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A username must be specified if the poster is anonymous'",
")",
")"
] |
Validates the post instance.
|
[
"Validates",
"the",
"post",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L289-L305
|
9,371
|
ellmetha/django-machina
|
machina/apps/forum_conversation/abstract_models.py
|
AbstractPost.save
|
def save(self, *args, **kwargs):
""" Saves the post instance. """
new_post = self.pk is None
super().save(*args, **kwargs)
# Ensures that the subject of the thread corresponds to the one associated
# with the first post. Do the same with the 'approved' flag.
if (new_post and self.topic.first_post is None) or self.is_topic_head:
if self.subject != self.topic.subject or self.approved != self.topic.approved:
self.topic.subject = self.subject
self.topic.approved = self.approved
# Trigger the topic-level trackers update
self.topic.update_trackers()
|
python
|
def save(self, *args, **kwargs):
""" Saves the post instance. """
new_post = self.pk is None
super().save(*args, **kwargs)
# Ensures that the subject of the thread corresponds to the one associated
# with the first post. Do the same with the 'approved' flag.
if (new_post and self.topic.first_post is None) or self.is_topic_head:
if self.subject != self.topic.subject or self.approved != self.topic.approved:
self.topic.subject = self.subject
self.topic.approved = self.approved
# Trigger the topic-level trackers update
self.topic.update_trackers()
|
[
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"new_post",
"=",
"self",
".",
"pk",
"is",
"None",
"super",
"(",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Ensures that the subject of the thread corresponds to the one associated",
"# with the first post. Do the same with the 'approved' flag.",
"if",
"(",
"new_post",
"and",
"self",
".",
"topic",
".",
"first_post",
"is",
"None",
")",
"or",
"self",
".",
"is_topic_head",
":",
"if",
"self",
".",
"subject",
"!=",
"self",
".",
"topic",
".",
"subject",
"or",
"self",
".",
"approved",
"!=",
"self",
".",
"topic",
".",
"approved",
":",
"self",
".",
"topic",
".",
"subject",
"=",
"self",
".",
"subject",
"self",
".",
"topic",
".",
"approved",
"=",
"self",
".",
"approved",
"# Trigger the topic-level trackers update",
"self",
".",
"topic",
".",
"update_trackers",
"(",
")"
] |
Saves the post instance.
|
[
"Saves",
"the",
"post",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L307-L320
|
9,372
|
ellmetha/django-machina
|
machina/apps/forum_conversation/abstract_models.py
|
AbstractPost.delete
|
def delete(self, using=None):
""" Deletes the post instance. """
if self.is_alone:
# The default way of operating is to trigger the deletion of the associated topic
# only if the considered post is the only post embedded in the topic
self.topic.delete()
else:
super(AbstractPost, self).delete(using)
self.topic.update_trackers()
|
python
|
def delete(self, using=None):
""" Deletes the post instance. """
if self.is_alone:
# The default way of operating is to trigger the deletion of the associated topic
# only if the considered post is the only post embedded in the topic
self.topic.delete()
else:
super(AbstractPost, self).delete(using)
self.topic.update_trackers()
|
[
"def",
"delete",
"(",
"self",
",",
"using",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_alone",
":",
"# The default way of operating is to trigger the deletion of the associated topic",
"# only if the considered post is the only post embedded in the topic",
"self",
".",
"topic",
".",
"delete",
"(",
")",
"else",
":",
"super",
"(",
"AbstractPost",
",",
"self",
")",
".",
"delete",
"(",
"using",
")",
"self",
".",
"topic",
".",
"update_trackers",
"(",
")"
] |
Deletes the post instance.
|
[
"Deletes",
"the",
"post",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/abstract_models.py#L322-L330
|
9,373
|
ellmetha/django-machina
|
machina/apps/forum/visibility.py
|
ForumVisibilityContentTree.from_forums
|
def from_forums(cls, forums):
""" Initializes a ``ForumVisibilityContentTree`` instance from a list of forums. """
root_level = None
current_path = []
nodes = []
# Ensures forums last posts and related poster relations are "followed" for better
# performance (only if we're considering a queryset).
forums = (
forums.select_related('last_post', 'last_post__poster')
if isinstance(forums, QuerySet) else forums
)
for forum in forums:
level = forum.level
# Set the root level to the top node level at the first iteration.
if root_level is None:
root_level = level
# Initializes a visibility forum node associated with current forum instance.
vcontent_node = ForumVisibilityContentNode(forum)
# Computes a relative level associated to the node.
relative_level = level - root_level
vcontent_node.relative_level = relative_level
# All children nodes will be stored in an array attached to the current node.
vcontent_node.children = []
# Removes the forum that are not in the current branch.
while len(current_path) > relative_level:
current_path.pop(-1)
if level != root_level:
# Update the parent of the current forum.
parent_node = current_path[-1]
vcontent_node.parent = parent_node
parent_node.children.append(vcontent_node)
# Sets visible flag if applicable. The visible flag is used to determine whether a forum
# can be seen in a forum list or not. A forum can be seen if one of the following
# statements is true:
#
# * the forum is a direct child of the starting forum for the considered level
# * the forum have a parent which is a category and this category is a direct child of
# the starting forum
# * the forum have its 'display_sub_forum_list' option set to True and have a parent
# which is another forum. The latter is a direct child of the starting forum
# * the forum have its 'display_sub_forum_list' option set to True and have a parent
# which is another forum. The later have a parent which is a category and this
# category is a direct child of the starting forum
#
# If forums at the root level don't have parents, the visible forums are those that can
# be seen from the root of the forums tree.
vcontent_node.visible = (
(relative_level == 0) or
(forum.display_sub_forum_list and relative_level == 1) or
(forum.is_category and relative_level == 1) or
(
relative_level == 2 and
vcontent_node.parent.parent.obj.is_category and
vcontent_node.parent.obj.is_forum
)
)
# Add the current forum to the end of the current branch and inserts the node inside the
# final node dictionary.
current_path.append(vcontent_node)
nodes.append(vcontent_node)
tree = cls(nodes=nodes)
for node in tree.nodes:
node.tree = tree
return tree
|
python
|
def from_forums(cls, forums):
""" Initializes a ``ForumVisibilityContentTree`` instance from a list of forums. """
root_level = None
current_path = []
nodes = []
# Ensures forums last posts and related poster relations are "followed" for better
# performance (only if we're considering a queryset).
forums = (
forums.select_related('last_post', 'last_post__poster')
if isinstance(forums, QuerySet) else forums
)
for forum in forums:
level = forum.level
# Set the root level to the top node level at the first iteration.
if root_level is None:
root_level = level
# Initializes a visibility forum node associated with current forum instance.
vcontent_node = ForumVisibilityContentNode(forum)
# Computes a relative level associated to the node.
relative_level = level - root_level
vcontent_node.relative_level = relative_level
# All children nodes will be stored in an array attached to the current node.
vcontent_node.children = []
# Removes the forum that are not in the current branch.
while len(current_path) > relative_level:
current_path.pop(-1)
if level != root_level:
# Update the parent of the current forum.
parent_node = current_path[-1]
vcontent_node.parent = parent_node
parent_node.children.append(vcontent_node)
# Sets visible flag if applicable. The visible flag is used to determine whether a forum
# can be seen in a forum list or not. A forum can be seen if one of the following
# statements is true:
#
# * the forum is a direct child of the starting forum for the considered level
# * the forum have a parent which is a category and this category is a direct child of
# the starting forum
# * the forum have its 'display_sub_forum_list' option set to True and have a parent
# which is another forum. The latter is a direct child of the starting forum
# * the forum have its 'display_sub_forum_list' option set to True and have a parent
# which is another forum. The later have a parent which is a category and this
# category is a direct child of the starting forum
#
# If forums at the root level don't have parents, the visible forums are those that can
# be seen from the root of the forums tree.
vcontent_node.visible = (
(relative_level == 0) or
(forum.display_sub_forum_list and relative_level == 1) or
(forum.is_category and relative_level == 1) or
(
relative_level == 2 and
vcontent_node.parent.parent.obj.is_category and
vcontent_node.parent.obj.is_forum
)
)
# Add the current forum to the end of the current branch and inserts the node inside the
# final node dictionary.
current_path.append(vcontent_node)
nodes.append(vcontent_node)
tree = cls(nodes=nodes)
for node in tree.nodes:
node.tree = tree
return tree
|
[
"def",
"from_forums",
"(",
"cls",
",",
"forums",
")",
":",
"root_level",
"=",
"None",
"current_path",
"=",
"[",
"]",
"nodes",
"=",
"[",
"]",
"# Ensures forums last posts and related poster relations are \"followed\" for better",
"# performance (only if we're considering a queryset).",
"forums",
"=",
"(",
"forums",
".",
"select_related",
"(",
"'last_post'",
",",
"'last_post__poster'",
")",
"if",
"isinstance",
"(",
"forums",
",",
"QuerySet",
")",
"else",
"forums",
")",
"for",
"forum",
"in",
"forums",
":",
"level",
"=",
"forum",
".",
"level",
"# Set the root level to the top node level at the first iteration.",
"if",
"root_level",
"is",
"None",
":",
"root_level",
"=",
"level",
"# Initializes a visibility forum node associated with current forum instance.",
"vcontent_node",
"=",
"ForumVisibilityContentNode",
"(",
"forum",
")",
"# Computes a relative level associated to the node.",
"relative_level",
"=",
"level",
"-",
"root_level",
"vcontent_node",
".",
"relative_level",
"=",
"relative_level",
"# All children nodes will be stored in an array attached to the current node.",
"vcontent_node",
".",
"children",
"=",
"[",
"]",
"# Removes the forum that are not in the current branch.",
"while",
"len",
"(",
"current_path",
")",
">",
"relative_level",
":",
"current_path",
".",
"pop",
"(",
"-",
"1",
")",
"if",
"level",
"!=",
"root_level",
":",
"# Update the parent of the current forum.",
"parent_node",
"=",
"current_path",
"[",
"-",
"1",
"]",
"vcontent_node",
".",
"parent",
"=",
"parent_node",
"parent_node",
".",
"children",
".",
"append",
"(",
"vcontent_node",
")",
"# Sets visible flag if applicable. The visible flag is used to determine whether a forum",
"# can be seen in a forum list or not. A forum can be seen if one of the following",
"# statements is true:",
"#",
"# * the forum is a direct child of the starting forum for the considered level",
"# * the forum have a parent which is a category and this category is a direct child of",
"# the starting forum",
"# * the forum have its 'display_sub_forum_list' option set to True and have a parent",
"# which is another forum. The latter is a direct child of the starting forum",
"# * the forum have its 'display_sub_forum_list' option set to True and have a parent",
"# which is another forum. The later have a parent which is a category and this",
"# category is a direct child of the starting forum",
"#",
"# If forums at the root level don't have parents, the visible forums are those that can",
"# be seen from the root of the forums tree.",
"vcontent_node",
".",
"visible",
"=",
"(",
"(",
"relative_level",
"==",
"0",
")",
"or",
"(",
"forum",
".",
"display_sub_forum_list",
"and",
"relative_level",
"==",
"1",
")",
"or",
"(",
"forum",
".",
"is_category",
"and",
"relative_level",
"==",
"1",
")",
"or",
"(",
"relative_level",
"==",
"2",
"and",
"vcontent_node",
".",
"parent",
".",
"parent",
".",
"obj",
".",
"is_category",
"and",
"vcontent_node",
".",
"parent",
".",
"obj",
".",
"is_forum",
")",
")",
"# Add the current forum to the end of the current branch and inserts the node inside the",
"# final node dictionary.",
"current_path",
".",
"append",
"(",
"vcontent_node",
")",
"nodes",
".",
"append",
"(",
"vcontent_node",
")",
"tree",
"=",
"cls",
"(",
"nodes",
"=",
"nodes",
")",
"for",
"node",
"in",
"tree",
".",
"nodes",
":",
"node",
".",
"tree",
"=",
"tree",
"return",
"tree"
] |
Initializes a ``ForumVisibilityContentTree`` instance from a list of forums.
|
[
"Initializes",
"a",
"ForumVisibilityContentTree",
"instance",
"from",
"a",
"list",
"of",
"forums",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L33-L108
|
9,374
|
ellmetha/django-machina
|
machina/apps/forum/visibility.py
|
ForumVisibilityContentNode.last_post
|
def last_post(self):
""" Returns the latest post associated with the node or one of its descendants. """
posts = [n.last_post for n in self.children if n.last_post is not None]
children_last_post = max(posts, key=lambda p: p.created) if posts else None
if children_last_post and self.obj.last_post_id:
return max(self.obj.last_post, children_last_post, key=lambda p: p.created)
return children_last_post or self.obj.last_post
|
python
|
def last_post(self):
""" Returns the latest post associated with the node or one of its descendants. """
posts = [n.last_post for n in self.children if n.last_post is not None]
children_last_post = max(posts, key=lambda p: p.created) if posts else None
if children_last_post and self.obj.last_post_id:
return max(self.obj.last_post, children_last_post, key=lambda p: p.created)
return children_last_post or self.obj.last_post
|
[
"def",
"last_post",
"(",
"self",
")",
":",
"posts",
"=",
"[",
"n",
".",
"last_post",
"for",
"n",
"in",
"self",
".",
"children",
"if",
"n",
".",
"last_post",
"is",
"not",
"None",
"]",
"children_last_post",
"=",
"max",
"(",
"posts",
",",
"key",
"=",
"lambda",
"p",
":",
"p",
".",
"created",
")",
"if",
"posts",
"else",
"None",
"if",
"children_last_post",
"and",
"self",
".",
"obj",
".",
"last_post_id",
":",
"return",
"max",
"(",
"self",
".",
"obj",
".",
"last_post",
",",
"children_last_post",
",",
"key",
"=",
"lambda",
"p",
":",
"p",
".",
"created",
")",
"return",
"children_last_post",
"or",
"self",
".",
"obj",
".",
"last_post"
] |
Returns the latest post associated with the node or one of its descendants.
|
[
"Returns",
"the",
"latest",
"post",
"associated",
"with",
"the",
"node",
"or",
"one",
"of",
"its",
"descendants",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L158-L164
|
9,375
|
ellmetha/django-machina
|
machina/apps/forum/visibility.py
|
ForumVisibilityContentNode.last_post_on
|
def last_post_on(self):
""" Returns the latest post date associated with the node or one of its descendants. """
dates = [n.last_post_on for n in self.children if n.last_post_on is not None]
children_last_post_on = max(dates) if dates else None
if children_last_post_on and self.obj.last_post_on:
return max(self.obj.last_post_on, children_last_post_on)
return children_last_post_on or self.obj.last_post_on
|
python
|
def last_post_on(self):
""" Returns the latest post date associated with the node or one of its descendants. """
dates = [n.last_post_on for n in self.children if n.last_post_on is not None]
children_last_post_on = max(dates) if dates else None
if children_last_post_on and self.obj.last_post_on:
return max(self.obj.last_post_on, children_last_post_on)
return children_last_post_on or self.obj.last_post_on
|
[
"def",
"last_post_on",
"(",
"self",
")",
":",
"dates",
"=",
"[",
"n",
".",
"last_post_on",
"for",
"n",
"in",
"self",
".",
"children",
"if",
"n",
".",
"last_post_on",
"is",
"not",
"None",
"]",
"children_last_post_on",
"=",
"max",
"(",
"dates",
")",
"if",
"dates",
"else",
"None",
"if",
"children_last_post_on",
"and",
"self",
".",
"obj",
".",
"last_post_on",
":",
"return",
"max",
"(",
"self",
".",
"obj",
".",
"last_post_on",
",",
"children_last_post_on",
")",
"return",
"children_last_post_on",
"or",
"self",
".",
"obj",
".",
"last_post_on"
] |
Returns the latest post date associated with the node or one of its descendants.
|
[
"Returns",
"the",
"latest",
"post",
"date",
"associated",
"with",
"the",
"node",
"or",
"one",
"of",
"its",
"descendants",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L167-L173
|
9,376
|
ellmetha/django-machina
|
machina/apps/forum/visibility.py
|
ForumVisibilityContentNode.next_sibling
|
def next_sibling(self):
""" Returns the next sibling of the current node.
The next sibling is searched in the parent node if we are not considering a top-level node.
Otherwise it is searched inside the list of nodes (which should be sorted by tree ID) that
is associated with the considered tree instance.
"""
if self.parent:
nodes = self.parent.children
index = nodes.index(self)
sibling = nodes[index + 1] if index < len(nodes) - 1 else None
else:
nodes = self.tree.nodes
index = nodes.index(self)
sibling = (
next((n for n in nodes[index + 1:] if n.level == self.level), None)
if index < len(nodes) - 1 else None
)
return sibling
|
python
|
def next_sibling(self):
""" Returns the next sibling of the current node.
The next sibling is searched in the parent node if we are not considering a top-level node.
Otherwise it is searched inside the list of nodes (which should be sorted by tree ID) that
is associated with the considered tree instance.
"""
if self.parent:
nodes = self.parent.children
index = nodes.index(self)
sibling = nodes[index + 1] if index < len(nodes) - 1 else None
else:
nodes = self.tree.nodes
index = nodes.index(self)
sibling = (
next((n for n in nodes[index + 1:] if n.level == self.level), None)
if index < len(nodes) - 1 else None
)
return sibling
|
[
"def",
"next_sibling",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"nodes",
"=",
"self",
".",
"parent",
".",
"children",
"index",
"=",
"nodes",
".",
"index",
"(",
"self",
")",
"sibling",
"=",
"nodes",
"[",
"index",
"+",
"1",
"]",
"if",
"index",
"<",
"len",
"(",
"nodes",
")",
"-",
"1",
"else",
"None",
"else",
":",
"nodes",
"=",
"self",
".",
"tree",
".",
"nodes",
"index",
"=",
"nodes",
".",
"index",
"(",
"self",
")",
"sibling",
"=",
"(",
"next",
"(",
"(",
"n",
"for",
"n",
"in",
"nodes",
"[",
"index",
"+",
"1",
":",
"]",
"if",
"n",
".",
"level",
"==",
"self",
".",
"level",
")",
",",
"None",
")",
"if",
"index",
"<",
"len",
"(",
"nodes",
")",
"-",
"1",
"else",
"None",
")",
"return",
"sibling"
] |
Returns the next sibling of the current node.
The next sibling is searched in the parent node if we are not considering a top-level node.
Otherwise it is searched inside the list of nodes (which should be sorted by tree ID) that
is associated with the considered tree instance.
|
[
"Returns",
"the",
"next",
"sibling",
"of",
"the",
"current",
"node",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L176-L194
|
9,377
|
ellmetha/django-machina
|
machina/apps/forum/visibility.py
|
ForumVisibilityContentNode.posts_count
|
def posts_count(self):
""" Returns the number of posts associated with the current node and its descendants. """
return self.obj.direct_posts_count + sum(n.posts_count for n in self.children)
|
python
|
def posts_count(self):
""" Returns the number of posts associated with the current node and its descendants. """
return self.obj.direct_posts_count + sum(n.posts_count for n in self.children)
|
[
"def",
"posts_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"obj",
".",
"direct_posts_count",
"+",
"sum",
"(",
"n",
".",
"posts_count",
"for",
"n",
"in",
"self",
".",
"children",
")"
] |
Returns the number of posts associated with the current node and its descendants.
|
[
"Returns",
"the",
"number",
"of",
"posts",
"associated",
"with",
"the",
"current",
"node",
"and",
"its",
"descendants",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L197-L199
|
9,378
|
ellmetha/django-machina
|
machina/apps/forum/visibility.py
|
ForumVisibilityContentNode.previous_sibling
|
def previous_sibling(self):
""" Returns the previous sibling of the current node.
The previous sibling is searched in the parent node if we are not considering a top-level
node. Otherwise it is searched inside the list of nodes (which should be sorted by tree ID)
that is associated with the considered tree instance.
"""
if self.parent:
nodes = self.parent.children
index = nodes.index(self)
sibling = nodes[index - 1] if index > 0 else None
else:
nodes = self.tree.nodes
index = nodes.index(self)
sibling = (
next((n for n in reversed(nodes[:index]) if n.level == self.level), None)
if index > 0 else None
)
return sibling
|
python
|
def previous_sibling(self):
""" Returns the previous sibling of the current node.
The previous sibling is searched in the parent node if we are not considering a top-level
node. Otherwise it is searched inside the list of nodes (which should be sorted by tree ID)
that is associated with the considered tree instance.
"""
if self.parent:
nodes = self.parent.children
index = nodes.index(self)
sibling = nodes[index - 1] if index > 0 else None
else:
nodes = self.tree.nodes
index = nodes.index(self)
sibling = (
next((n for n in reversed(nodes[:index]) if n.level == self.level), None)
if index > 0 else None
)
return sibling
|
[
"def",
"previous_sibling",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"nodes",
"=",
"self",
".",
"parent",
".",
"children",
"index",
"=",
"nodes",
".",
"index",
"(",
"self",
")",
"sibling",
"=",
"nodes",
"[",
"index",
"-",
"1",
"]",
"if",
"index",
">",
"0",
"else",
"None",
"else",
":",
"nodes",
"=",
"self",
".",
"tree",
".",
"nodes",
"index",
"=",
"nodes",
".",
"index",
"(",
"self",
")",
"sibling",
"=",
"(",
"next",
"(",
"(",
"n",
"for",
"n",
"in",
"reversed",
"(",
"nodes",
"[",
":",
"index",
"]",
")",
"if",
"n",
".",
"level",
"==",
"self",
".",
"level",
")",
",",
"None",
")",
"if",
"index",
">",
"0",
"else",
"None",
")",
"return",
"sibling"
] |
Returns the previous sibling of the current node.
The previous sibling is searched in the parent node if we are not considering a top-level
node. Otherwise it is searched inside the list of nodes (which should be sorted by tree ID)
that is associated with the considered tree instance.
|
[
"Returns",
"the",
"previous",
"sibling",
"of",
"the",
"current",
"node",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L202-L220
|
9,379
|
ellmetha/django-machina
|
machina/apps/forum/visibility.py
|
ForumVisibilityContentNode.topics_count
|
def topics_count(self):
""" Returns the number of topics associated with the current node and its descendants. """
return self.obj.direct_topics_count + sum(n.topics_count for n in self.children)
|
python
|
def topics_count(self):
""" Returns the number of topics associated with the current node and its descendants. """
return self.obj.direct_topics_count + sum(n.topics_count for n in self.children)
|
[
"def",
"topics_count",
"(",
"self",
")",
":",
"return",
"self",
".",
"obj",
".",
"direct_topics_count",
"+",
"sum",
"(",
"n",
".",
"topics_count",
"for",
"n",
"in",
"self",
".",
"children",
")"
] |
Returns the number of topics associated with the current node and its descendants.
|
[
"Returns",
"the",
"number",
"of",
"topics",
"associated",
"with",
"the",
"current",
"node",
"and",
"its",
"descendants",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/visibility.py#L223-L225
|
9,380
|
ellmetha/django-machina
|
machina/apps/forum_permission/checker.py
|
ForumPermissionChecker.has_perm
|
def has_perm(self, perm, forum):
""" Checks if the considered user has given permission for the passed forum. """
if not self.user.is_anonymous and not self.user.is_active:
# An inactive user cannot have permissions
return False
elif self.user and self.user.is_superuser:
# The superuser have all permissions
return True
return perm in self.get_perms(forum)
|
python
|
def has_perm(self, perm, forum):
""" Checks if the considered user has given permission for the passed forum. """
if not self.user.is_anonymous and not self.user.is_active:
# An inactive user cannot have permissions
return False
elif self.user and self.user.is_superuser:
# The superuser have all permissions
return True
return perm in self.get_perms(forum)
|
[
"def",
"has_perm",
"(",
"self",
",",
"perm",
",",
"forum",
")",
":",
"if",
"not",
"self",
".",
"user",
".",
"is_anonymous",
"and",
"not",
"self",
".",
"user",
".",
"is_active",
":",
"# An inactive user cannot have permissions",
"return",
"False",
"elif",
"self",
".",
"user",
"and",
"self",
".",
"user",
".",
"is_superuser",
":",
"# The superuser have all permissions",
"return",
"True",
"return",
"perm",
"in",
"self",
".",
"get_perms",
"(",
"forum",
")"
] |
Checks if the considered user has given permission for the passed forum.
|
[
"Checks",
"if",
"the",
"considered",
"user",
"has",
"given",
"permission",
"for",
"the",
"passed",
"forum",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/checker.py#L29-L37
|
9,381
|
ellmetha/django-machina
|
machina/apps/forum_conversation/forum_attachments/forms.py
|
BaseAttachmentFormset.save
|
def save(self, commit=True, **kwargs):
""" Saves the considered instances. """
if self.post:
for form in self.forms:
form.instance.post = self.post
super().save(commit)
|
python
|
def save(self, commit=True, **kwargs):
""" Saves the considered instances. """
if self.post:
for form in self.forms:
form.instance.post = self.post
super().save(commit)
|
[
"def",
"save",
"(",
"self",
",",
"commit",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"post",
":",
"for",
"form",
"in",
"self",
".",
"forms",
":",
"form",
".",
"instance",
".",
"post",
"=",
"self",
".",
"post",
"super",
"(",
")",
".",
"save",
"(",
"commit",
")"
] |
Saves the considered instances.
|
[
"Saves",
"the",
"considered",
"instances",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_attachments/forms.py#L34-L39
|
9,382
|
ellmetha/django-machina
|
machina/apps/forum_permission/viewmixins.py
|
PermissionRequiredMixin.get_required_permissions
|
def get_required_permissions(self, request):
""" Returns the required permissions to access the considered object. """
perms = []
if not self.permission_required:
return perms
if isinstance(self.permission_required, string_types):
perms = [self.permission_required, ]
elif isinstance(self.permission_required, Iterable):
perms = [perm for perm in self.permission_required]
else:
raise ImproperlyConfigured(
'\'PermissionRequiredMixin\' requires \'permission_required\' '
'attribute to be set to \'<app_label>.<permission codename>\' but is set to {} '
'instead'.format(self.permission_required)
)
return perms
|
python
|
def get_required_permissions(self, request):
""" Returns the required permissions to access the considered object. """
perms = []
if not self.permission_required:
return perms
if isinstance(self.permission_required, string_types):
perms = [self.permission_required, ]
elif isinstance(self.permission_required, Iterable):
perms = [perm for perm in self.permission_required]
else:
raise ImproperlyConfigured(
'\'PermissionRequiredMixin\' requires \'permission_required\' '
'attribute to be set to \'<app_label>.<permission codename>\' but is set to {} '
'instead'.format(self.permission_required)
)
return perms
|
[
"def",
"get_required_permissions",
"(",
"self",
",",
"request",
")",
":",
"perms",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"permission_required",
":",
"return",
"perms",
"if",
"isinstance",
"(",
"self",
".",
"permission_required",
",",
"string_types",
")",
":",
"perms",
"=",
"[",
"self",
".",
"permission_required",
",",
"]",
"elif",
"isinstance",
"(",
"self",
".",
"permission_required",
",",
"Iterable",
")",
":",
"perms",
"=",
"[",
"perm",
"for",
"perm",
"in",
"self",
".",
"permission_required",
"]",
"else",
":",
"raise",
"ImproperlyConfigured",
"(",
"'\\'PermissionRequiredMixin\\' requires \\'permission_required\\' '",
"'attribute to be set to \\'<app_label>.<permission codename>\\' but is set to {} '",
"'instead'",
".",
"format",
"(",
"self",
".",
"permission_required",
")",
")",
"return",
"perms"
] |
Returns the required permissions to access the considered object.
|
[
"Returns",
"the",
"required",
"permissions",
"to",
"access",
"the",
"considered",
"object",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/viewmixins.py#L51-L68
|
9,383
|
ellmetha/django-machina
|
machina/apps/forum_permission/viewmixins.py
|
PermissionRequiredMixin.check_permissions
|
def check_permissions(self, request):
""" Retrieves the controlled object and perform the permissions check. """
obj = (
hasattr(self, 'get_controlled_object') and self.get_controlled_object() or
hasattr(self, 'get_object') and self.get_object() or getattr(self, 'object', None)
)
user = request.user
# Get the permissions to check
perms = self.get_required_permissions(self)
# Check permissions
has_permissions = self.perform_permissions_check(user, obj, perms)
if not has_permissions and not user.is_authenticated:
return HttpResponseRedirect('{}?{}={}'.format(
resolve_url(self.login_url),
self.redirect_field_name,
urlquote(request.get_full_path())
))
elif not has_permissions:
raise PermissionDenied
|
python
|
def check_permissions(self, request):
""" Retrieves the controlled object and perform the permissions check. """
obj = (
hasattr(self, 'get_controlled_object') and self.get_controlled_object() or
hasattr(self, 'get_object') and self.get_object() or getattr(self, 'object', None)
)
user = request.user
# Get the permissions to check
perms = self.get_required_permissions(self)
# Check permissions
has_permissions = self.perform_permissions_check(user, obj, perms)
if not has_permissions and not user.is_authenticated:
return HttpResponseRedirect('{}?{}={}'.format(
resolve_url(self.login_url),
self.redirect_field_name,
urlquote(request.get_full_path())
))
elif not has_permissions:
raise PermissionDenied
|
[
"def",
"check_permissions",
"(",
"self",
",",
"request",
")",
":",
"obj",
"=",
"(",
"hasattr",
"(",
"self",
",",
"'get_controlled_object'",
")",
"and",
"self",
".",
"get_controlled_object",
"(",
")",
"or",
"hasattr",
"(",
"self",
",",
"'get_object'",
")",
"and",
"self",
".",
"get_object",
"(",
")",
"or",
"getattr",
"(",
"self",
",",
"'object'",
",",
"None",
")",
")",
"user",
"=",
"request",
".",
"user",
"# Get the permissions to check",
"perms",
"=",
"self",
".",
"get_required_permissions",
"(",
"self",
")",
"# Check permissions",
"has_permissions",
"=",
"self",
".",
"perform_permissions_check",
"(",
"user",
",",
"obj",
",",
"perms",
")",
"if",
"not",
"has_permissions",
"and",
"not",
"user",
".",
"is_authenticated",
":",
"return",
"HttpResponseRedirect",
"(",
"'{}?{}={}'",
".",
"format",
"(",
"resolve_url",
"(",
"self",
".",
"login_url",
")",
",",
"self",
".",
"redirect_field_name",
",",
"urlquote",
"(",
"request",
".",
"get_full_path",
"(",
")",
")",
")",
")",
"elif",
"not",
"has_permissions",
":",
"raise",
"PermissionDenied"
] |
Retrieves the controlled object and perform the permissions check.
|
[
"Retrieves",
"the",
"controlled",
"object",
"and",
"perform",
"the",
"permissions",
"check",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/viewmixins.py#L84-L105
|
9,384
|
ellmetha/django-machina
|
machina/apps/forum_permission/viewmixins.py
|
PermissionRequiredMixin.dispatch
|
def dispatch(self, request, *args, **kwargs):
""" Dispatches an incoming request. """
self.request = request
self.args = args
self.kwargs = kwargs
response = self.check_permissions(request)
if response:
return response
return super().dispatch(request, *args, **kwargs)
|
python
|
def dispatch(self, request, *args, **kwargs):
""" Dispatches an incoming request. """
self.request = request
self.args = args
self.kwargs = kwargs
response = self.check_permissions(request)
if response:
return response
return super().dispatch(request, *args, **kwargs)
|
[
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"request",
"=",
"request",
"self",
".",
"args",
"=",
"args",
"self",
".",
"kwargs",
"=",
"kwargs",
"response",
"=",
"self",
".",
"check_permissions",
"(",
"request",
")",
"if",
"response",
":",
"return",
"response",
"return",
"super",
"(",
")",
".",
"dispatch",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Dispatches an incoming request.
|
[
"Dispatches",
"an",
"incoming",
"request",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/viewmixins.py#L107-L115
|
9,385
|
ellmetha/django-machina
|
machina/apps/forum_tracking/receivers.py
|
update_user_trackers
|
def update_user_trackers(sender, topic, user, request, response, **kwargs):
""" Receiver to mark a topic being viewed as read.
This can result in marking the related forum tracker as read.
"""
TrackingHandler = get_class('forum_tracking.handler', 'TrackingHandler') # noqa
track_handler = TrackingHandler()
track_handler.mark_topic_read(topic, user)
|
python
|
def update_user_trackers(sender, topic, user, request, response, **kwargs):
""" Receiver to mark a topic being viewed as read.
This can result in marking the related forum tracker as read.
"""
TrackingHandler = get_class('forum_tracking.handler', 'TrackingHandler') # noqa
track_handler = TrackingHandler()
track_handler.mark_topic_read(topic, user)
|
[
"def",
"update_user_trackers",
"(",
"sender",
",",
"topic",
",",
"user",
",",
"request",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"TrackingHandler",
"=",
"get_class",
"(",
"'forum_tracking.handler'",
",",
"'TrackingHandler'",
")",
"# noqa",
"track_handler",
"=",
"TrackingHandler",
"(",
")",
"track_handler",
".",
"mark_topic_read",
"(",
"topic",
",",
"user",
")"
] |
Receiver to mark a topic being viewed as read.
This can result in marking the related forum tracker as read.
|
[
"Receiver",
"to",
"mark",
"a",
"topic",
"being",
"viewed",
"as",
"read",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/receivers.py#L18-L26
|
9,386
|
ellmetha/django-machina
|
machina/apps/forum/receivers.py
|
update_forum_redirects_counter
|
def update_forum_redirects_counter(sender, forum, user, request, response, **kwargs):
""" Handles the update of the link redirects counter associated with link forums. """
if forum.is_link and forum.link_redirects:
forum.link_redirects_count = F('link_redirects_count') + 1
forum.save()
|
python
|
def update_forum_redirects_counter(sender, forum, user, request, response, **kwargs):
""" Handles the update of the link redirects counter associated with link forums. """
if forum.is_link and forum.link_redirects:
forum.link_redirects_count = F('link_redirects_count') + 1
forum.save()
|
[
"def",
"update_forum_redirects_counter",
"(",
"sender",
",",
"forum",
",",
"user",
",",
"request",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"forum",
".",
"is_link",
"and",
"forum",
".",
"link_redirects",
":",
"forum",
".",
"link_redirects_count",
"=",
"F",
"(",
"'link_redirects_count'",
")",
"+",
"1",
"forum",
".",
"save",
"(",
")"
] |
Handles the update of the link redirects counter associated with link forums.
|
[
"Handles",
"the",
"update",
"of",
"the",
"link",
"redirects",
"counter",
"associated",
"with",
"link",
"forums",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/receivers.py#L16-L20
|
9,387
|
ellmetha/django-machina
|
machina/apps/forum_member/abstract_models.py
|
AbstractForumProfile.get_avatar_upload_to
|
def get_avatar_upload_to(self, filename):
""" Returns the path to upload the associated avatar to. """
dummy, ext = os.path.splitext(filename)
return os.path.join(
machina_settings.PROFILE_AVATAR_UPLOAD_TO,
'{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext),
)
|
python
|
def get_avatar_upload_to(self, filename):
""" Returns the path to upload the associated avatar to. """
dummy, ext = os.path.splitext(filename)
return os.path.join(
machina_settings.PROFILE_AVATAR_UPLOAD_TO,
'{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext),
)
|
[
"def",
"get_avatar_upload_to",
"(",
"self",
",",
"filename",
")",
":",
"dummy",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"machina_settings",
".",
"PROFILE_AVATAR_UPLOAD_TO",
",",
"'{id}{ext}'",
".",
"format",
"(",
"id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
",",
"ext",
"=",
"ext",
")",
",",
")"
] |
Returns the path to upload the associated avatar to.
|
[
"Returns",
"the",
"path",
"to",
"upload",
"the",
"associated",
"avatar",
"to",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_member/abstract_models.py#L60-L66
|
9,388
|
ellmetha/django-machina
|
machina/apps/forum_conversation/managers.py
|
ApprovedManager.get_queryset
|
def get_queryset(self):
""" Returns all the approved topics or posts. """
qs = super().get_queryset()
qs = qs.filter(approved=True)
return qs
|
python
|
def get_queryset(self):
""" Returns all the approved topics or posts. """
qs = super().get_queryset()
qs = qs.filter(approved=True)
return qs
|
[
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"super",
"(",
")",
".",
"get_queryset",
"(",
")",
"qs",
"=",
"qs",
".",
"filter",
"(",
"approved",
"=",
"True",
")",
"return",
"qs"
] |
Returns all the approved topics or posts.
|
[
"Returns",
"all",
"the",
"approved",
"topics",
"or",
"posts",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/managers.py#L13-L17
|
9,389
|
ellmetha/django-machina
|
machina/apps/forum_conversation/forum_polls/abstract_models.py
|
AbstractTopicPoll.votes
|
def votes(self):
""" Returns all the votes related to this topic poll. """
votes = []
for option in self.options.all():
votes += option.votes.all()
return votes
|
python
|
def votes(self):
""" Returns all the votes related to this topic poll. """
votes = []
for option in self.options.all():
votes += option.votes.all()
return votes
|
[
"def",
"votes",
"(",
"self",
")",
":",
"votes",
"=",
"[",
"]",
"for",
"option",
"in",
"self",
".",
"options",
".",
"all",
"(",
")",
":",
"votes",
"+=",
"option",
".",
"votes",
".",
"all",
"(",
")",
"return",
"votes"
] |
Returns all the votes related to this topic poll.
|
[
"Returns",
"all",
"the",
"votes",
"related",
"to",
"this",
"topic",
"poll",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_polls/abstract_models.py#L56-L61
|
9,390
|
ellmetha/django-machina
|
machina/apps/forum_conversation/forum_polls/abstract_models.py
|
AbstractTopicPollVote.clean
|
def clean(self):
""" Validates the considered instance. """
super().clean()
# At least a poster (user) or a session key must be associated with
# the vote instance.
if self.voter is None and self.anonymous_key is None:
raise ValidationError(_('A user id or an anonymous key must be used.'))
if self.voter and self.anonymous_key:
raise ValidationError(_('A user id or an anonymous key must be used, but not both.'))
|
python
|
def clean(self):
""" Validates the considered instance. """
super().clean()
# At least a poster (user) or a session key must be associated with
# the vote instance.
if self.voter is None and self.anonymous_key is None:
raise ValidationError(_('A user id or an anonymous key must be used.'))
if self.voter and self.anonymous_key:
raise ValidationError(_('A user id or an anonymous key must be used, but not both.'))
|
[
"def",
"clean",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"clean",
"(",
")",
"# At least a poster (user) or a session key must be associated with",
"# the vote instance.",
"if",
"self",
".",
"voter",
"is",
"None",
"and",
"self",
".",
"anonymous_key",
"is",
"None",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A user id or an anonymous key must be used.'",
")",
")",
"if",
"self",
".",
"voter",
"and",
"self",
".",
"anonymous_key",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A user id or an anonymous key must be used, but not both.'",
")",
")"
] |
Validates the considered instance.
|
[
"Validates",
"the",
"considered",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_polls/abstract_models.py#L114-L123
|
9,391
|
ellmetha/django-machina
|
machina/apps/forum_tracking/views.py
|
MarkForumsReadView.get_top_level_forum_url
|
def get_top_level_forum_url(self):
""" Returns the parent forum from which forums are marked as read. """
return (
reverse('forum:index') if self.top_level_forum is None else
reverse(
'forum:forum',
kwargs={'slug': self.top_level_forum.slug, 'pk': self.kwargs['pk']},
)
)
|
python
|
def get_top_level_forum_url(self):
""" Returns the parent forum from which forums are marked as read. """
return (
reverse('forum:index') if self.top_level_forum is None else
reverse(
'forum:forum',
kwargs={'slug': self.top_level_forum.slug, 'pk': self.kwargs['pk']},
)
)
|
[
"def",
"get_top_level_forum_url",
"(",
"self",
")",
":",
"return",
"(",
"reverse",
"(",
"'forum:index'",
")",
"if",
"self",
".",
"top_level_forum",
"is",
"None",
"else",
"reverse",
"(",
"'forum:forum'",
",",
"kwargs",
"=",
"{",
"'slug'",
":",
"self",
".",
"top_level_forum",
".",
"slug",
",",
"'pk'",
":",
"self",
".",
"kwargs",
"[",
"'pk'",
"]",
"}",
",",
")",
")"
] |
Returns the parent forum from which forums are marked as read.
|
[
"Returns",
"the",
"parent",
"forum",
"from",
"which",
"forums",
"are",
"marked",
"as",
"read",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/views.py#L53-L61
|
9,392
|
ellmetha/django-machina
|
machina/apps/forum_tracking/views.py
|
MarkForumsReadView.mark_as_read
|
def mark_as_read(self, request, pk):
""" Marks the considered forums as read. """
if self.top_level_forum is not None:
forums = request.forum_permission_handler.get_readable_forums(
self.top_level_forum.get_descendants(include_self=True), request.user,
)
else:
forums = request.forum_permission_handler.get_readable_forums(
Forum.objects.all(), request.user,
)
# Marks forums as read
track_handler.mark_forums_read(forums, request.user)
if len(forums):
messages.success(request, self.success_message)
return HttpResponseRedirect(self.get_top_level_forum_url())
|
python
|
def mark_as_read(self, request, pk):
""" Marks the considered forums as read. """
if self.top_level_forum is not None:
forums = request.forum_permission_handler.get_readable_forums(
self.top_level_forum.get_descendants(include_self=True), request.user,
)
else:
forums = request.forum_permission_handler.get_readable_forums(
Forum.objects.all(), request.user,
)
# Marks forums as read
track_handler.mark_forums_read(forums, request.user)
if len(forums):
messages.success(request, self.success_message)
return HttpResponseRedirect(self.get_top_level_forum_url())
|
[
"def",
"mark_as_read",
"(",
"self",
",",
"request",
",",
"pk",
")",
":",
"if",
"self",
".",
"top_level_forum",
"is",
"not",
"None",
":",
"forums",
"=",
"request",
".",
"forum_permission_handler",
".",
"get_readable_forums",
"(",
"self",
".",
"top_level_forum",
".",
"get_descendants",
"(",
"include_self",
"=",
"True",
")",
",",
"request",
".",
"user",
",",
")",
"else",
":",
"forums",
"=",
"request",
".",
"forum_permission_handler",
".",
"get_readable_forums",
"(",
"Forum",
".",
"objects",
".",
"all",
"(",
")",
",",
"request",
".",
"user",
",",
")",
"# Marks forums as read",
"track_handler",
".",
"mark_forums_read",
"(",
"forums",
",",
"request",
".",
"user",
")",
"if",
"len",
"(",
"forums",
")",
":",
"messages",
".",
"success",
"(",
"request",
",",
"self",
".",
"success_message",
")",
"return",
"HttpResponseRedirect",
"(",
"self",
".",
"get_top_level_forum_url",
"(",
")",
")"
] |
Marks the considered forums as read.
|
[
"Marks",
"the",
"considered",
"forums",
"as",
"read",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/views.py#L63-L80
|
9,393
|
ellmetha/django-machina
|
machina/apps/forum_tracking/views.py
|
MarkTopicsReadView.get_forum_url
|
def get_forum_url(self):
""" Returns the url of the forum whose topics will be marked read. """
return reverse('forum:forum', kwargs={'slug': self.forum.slug, 'pk': self.forum.pk})
|
python
|
def get_forum_url(self):
""" Returns the url of the forum whose topics will be marked read. """
return reverse('forum:forum', kwargs={'slug': self.forum.slug, 'pk': self.forum.pk})
|
[
"def",
"get_forum_url",
"(",
"self",
")",
":",
"return",
"reverse",
"(",
"'forum:forum'",
",",
"kwargs",
"=",
"{",
"'slug'",
":",
"self",
".",
"forum",
".",
"slug",
",",
"'pk'",
":",
"self",
".",
"forum",
".",
"pk",
"}",
")"
] |
Returns the url of the forum whose topics will be marked read.
|
[
"Returns",
"the",
"url",
"of",
"the",
"forum",
"whose",
"topics",
"will",
"be",
"marked",
"read",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/views.py#L113-L115
|
9,394
|
ellmetha/django-machina
|
machina/apps/forum_tracking/views.py
|
MarkTopicsReadView.mark_topics_read
|
def mark_topics_read(self, request, pk):
""" Marks forum topics as read. """
track_handler.mark_forums_read([self.forum, ], request.user)
messages.success(request, self.success_message)
return HttpResponseRedirect(self.get_forum_url())
|
python
|
def mark_topics_read(self, request, pk):
""" Marks forum topics as read. """
track_handler.mark_forums_read([self.forum, ], request.user)
messages.success(request, self.success_message)
return HttpResponseRedirect(self.get_forum_url())
|
[
"def",
"mark_topics_read",
"(",
"self",
",",
"request",
",",
"pk",
")",
":",
"track_handler",
".",
"mark_forums_read",
"(",
"[",
"self",
".",
"forum",
",",
"]",
",",
"request",
".",
"user",
")",
"messages",
".",
"success",
"(",
"request",
",",
"self",
".",
"success_message",
")",
"return",
"HttpResponseRedirect",
"(",
"self",
".",
"get_forum_url",
"(",
")",
")"
] |
Marks forum topics as read.
|
[
"Marks",
"forum",
"topics",
"as",
"read",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_tracking/views.py#L117-L121
|
9,395
|
ellmetha/django-machina
|
machina/core/db/models.py
|
get_model
|
def get_model(app_label, model_name):
""" Given an app label and a model name, returns the corresponding model class. """
try:
return apps.get_model(app_label, model_name)
except AppRegistryNotReady:
if apps.apps_ready and not apps.models_ready:
# If the models module of the considered app has not been loaded yet,
# we try to import it manually in order to retrieve the model class.
# This trick is usefull in order to get the model class during the
# ``apps.populate()`` call and the execution of related methods of AppConfig
# instances (eg. ``ready``).
# Firts, the config of the consideration must be retrieved
app_config = apps.get_app_config(app_label)
# Then the models module is manually imported
import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME))
# Finally, tries to return the registered model class
return apps.get_registered_model(app_label, model_name)
else:
raise
|
python
|
def get_model(app_label, model_name):
""" Given an app label and a model name, returns the corresponding model class. """
try:
return apps.get_model(app_label, model_name)
except AppRegistryNotReady:
if apps.apps_ready and not apps.models_ready:
# If the models module of the considered app has not been loaded yet,
# we try to import it manually in order to retrieve the model class.
# This trick is usefull in order to get the model class during the
# ``apps.populate()`` call and the execution of related methods of AppConfig
# instances (eg. ``ready``).
# Firts, the config of the consideration must be retrieved
app_config = apps.get_app_config(app_label)
# Then the models module is manually imported
import_module('%s.%s' % (app_config.name, MODELS_MODULE_NAME))
# Finally, tries to return the registered model class
return apps.get_registered_model(app_label, model_name)
else:
raise
|
[
"def",
"get_model",
"(",
"app_label",
",",
"model_name",
")",
":",
"try",
":",
"return",
"apps",
".",
"get_model",
"(",
"app_label",
",",
"model_name",
")",
"except",
"AppRegistryNotReady",
":",
"if",
"apps",
".",
"apps_ready",
"and",
"not",
"apps",
".",
"models_ready",
":",
"# If the models module of the considered app has not been loaded yet,",
"# we try to import it manually in order to retrieve the model class.",
"# This trick is usefull in order to get the model class during the",
"# ``apps.populate()`` call and the execution of related methods of AppConfig",
"# instances (eg. ``ready``).",
"# Firts, the config of the consideration must be retrieved",
"app_config",
"=",
"apps",
".",
"get_app_config",
"(",
"app_label",
")",
"# Then the models module is manually imported",
"import_module",
"(",
"'%s.%s'",
"%",
"(",
"app_config",
".",
"name",
",",
"MODELS_MODULE_NAME",
")",
")",
"# Finally, tries to return the registered model class",
"return",
"apps",
".",
"get_registered_model",
"(",
"app_label",
",",
"model_name",
")",
"else",
":",
"raise"
] |
Given an app label and a model name, returns the corresponding model class.
|
[
"Given",
"an",
"app",
"label",
"and",
"a",
"model",
"name",
"returns",
"the",
"corresponding",
"model",
"class",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/db/models.py#L12-L31
|
9,396
|
ellmetha/django-machina
|
machina/core/db/models.py
|
is_model_registered
|
def is_model_registered(app_label, model_name):
""" Checks whether the given model is registered or not.
It is usefull to prevent Machina models for being registered if they are overridden by local
apps.
"""
try:
apps.get_registered_model(app_label, model_name)
except LookupError:
return False
else:
return True
|
python
|
def is_model_registered(app_label, model_name):
""" Checks whether the given model is registered or not.
It is usefull to prevent Machina models for being registered if they are overridden by local
apps.
"""
try:
apps.get_registered_model(app_label, model_name)
except LookupError:
return False
else:
return True
|
[
"def",
"is_model_registered",
"(",
"app_label",
",",
"model_name",
")",
":",
"try",
":",
"apps",
".",
"get_registered_model",
"(",
"app_label",
",",
"model_name",
")",
"except",
"LookupError",
":",
"return",
"False",
"else",
":",
"return",
"True"
] |
Checks whether the given model is registered or not.
It is usefull to prevent Machina models for being registered if they are overridden by local
apps.
|
[
"Checks",
"whether",
"the",
"given",
"model",
"is",
"registered",
"or",
"not",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/db/models.py#L34-L46
|
9,397
|
ellmetha/django-machina
|
machina/apps/forum_permission/abstract_models.py
|
AbstractUserForumPermission.clean
|
def clean(self):
""" Validates the current instance. """
super().clean()
if (
(self.user is None and not self.anonymous_user) or
(self.user and self.anonymous_user)
):
raise ValidationError(
_('A permission should target either a user or an anonymous user'),
)
|
python
|
def clean(self):
""" Validates the current instance. """
super().clean()
if (
(self.user is None and not self.anonymous_user) or
(self.user and self.anonymous_user)
):
raise ValidationError(
_('A permission should target either a user or an anonymous user'),
)
|
[
"def",
"clean",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"clean",
"(",
")",
"if",
"(",
"(",
"self",
".",
"user",
"is",
"None",
"and",
"not",
"self",
".",
"anonymous_user",
")",
"or",
"(",
"self",
".",
"user",
"and",
"self",
".",
"anonymous_user",
")",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A permission should target either a user or an anonymous user'",
")",
",",
")"
] |
Validates the current instance.
|
[
"Validates",
"the",
"current",
"instance",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_permission/abstract_models.py#L94-L103
|
9,398
|
ellmetha/django-machina
|
machina/apps/forum_conversation/forum_attachments/views.py
|
AttachmentView.render_to_response
|
def render_to_response(self, context, **response_kwargs):
""" Generates the appropriate response. """
filename = os.path.basename(self.object.file.name)
# Try to guess the content type of the given file
content_type, _ = mimetypes.guess_type(self.object.file.name)
if not content_type:
content_type = 'text/plain'
response = HttpResponse(self.object.file, content_type=content_type)
response['Content-Disposition'] = 'attachment; filename={}'.format(filename)
return response
|
python
|
def render_to_response(self, context, **response_kwargs):
""" Generates the appropriate response. """
filename = os.path.basename(self.object.file.name)
# Try to guess the content type of the given file
content_type, _ = mimetypes.guess_type(self.object.file.name)
if not content_type:
content_type = 'text/plain'
response = HttpResponse(self.object.file, content_type=content_type)
response['Content-Disposition'] = 'attachment; filename={}'.format(filename)
return response
|
[
"def",
"render_to_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"object",
".",
"file",
".",
"name",
")",
"# Try to guess the content type of the given file",
"content_type",
",",
"_",
"=",
"mimetypes",
".",
"guess_type",
"(",
"self",
".",
"object",
".",
"file",
".",
"name",
")",
"if",
"not",
"content_type",
":",
"content_type",
"=",
"'text/plain'",
"response",
"=",
"HttpResponse",
"(",
"self",
".",
"object",
".",
"file",
",",
"content_type",
"=",
"content_type",
")",
"response",
"[",
"'Content-Disposition'",
"]",
"=",
"'attachment; filename={}'",
".",
"format",
"(",
"filename",
")",
"return",
"response"
] |
Generates the appropriate response.
|
[
"Generates",
"the",
"appropriate",
"response",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_attachments/views.py#L29-L41
|
9,399
|
ellmetha/django-machina
|
machina/apps/forum_conversation/forum_polls/views.py
|
TopicPollVoteView.get_form_kwargs
|
def get_form_kwargs(self):
""" Returns the keyword arguments to provide tp the associated form. """
kwargs = super(ModelFormMixin, self).get_form_kwargs()
kwargs['poll'] = self.object
return kwargs
|
python
|
def get_form_kwargs(self):
""" Returns the keyword arguments to provide tp the associated form. """
kwargs = super(ModelFormMixin, self).get_form_kwargs()
kwargs['poll'] = self.object
return kwargs
|
[
"def",
"get_form_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"super",
"(",
"ModelFormMixin",
",",
"self",
")",
".",
"get_form_kwargs",
"(",
")",
"kwargs",
"[",
"'poll'",
"]",
"=",
"self",
".",
"object",
"return",
"kwargs"
] |
Returns the keyword arguments to provide tp the associated form.
|
[
"Returns",
"the",
"keyword",
"arguments",
"to",
"provide",
"tp",
"the",
"associated",
"form",
"."
] |
89ac083c1eaf1cfdeae6686ee094cc86362e8c69
|
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_conversation/forum_polls/views.py#L37-L41
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.