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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
7,200
|
Kautenja/nes-py
|
nes_py/wrappers/binary_to_discrete_space_env.py
|
BinarySpaceToDiscreteSpaceEnv.get_action_meanings
|
def get_action_meanings(self):
"""Return a list of actions meanings."""
actions = sorted(self._action_meanings.keys())
return [self._action_meanings[action] for action in actions]
|
python
|
def get_action_meanings(self):
"""Return a list of actions meanings."""
actions = sorted(self._action_meanings.keys())
return [self._action_meanings[action] for action in actions]
|
[
"def",
"get_action_meanings",
"(",
"self",
")",
":",
"actions",
"=",
"sorted",
"(",
"self",
".",
"_action_meanings",
".",
"keys",
"(",
")",
")",
"return",
"[",
"self",
".",
"_action_meanings",
"[",
"action",
"]",
"for",
"action",
"in",
"actions",
"]"
] |
Return a list of actions meanings.
|
[
"Return",
"a",
"list",
"of",
"actions",
"meanings",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/wrappers/binary_to_discrete_space_env.py#L90-L93
|
7,201
|
Kautenja/nes-py
|
nes_py/_rom.py
|
ROM.prg_rom
|
def prg_rom(self):
"""Return the PRG ROM of the ROM file."""
try:
return self.raw_data[self.prg_rom_start:self.prg_rom_stop]
except IndexError:
raise ValueError('failed to read PRG-ROM on ROM.')
|
python
|
def prg_rom(self):
"""Return the PRG ROM of the ROM file."""
try:
return self.raw_data[self.prg_rom_start:self.prg_rom_stop]
except IndexError:
raise ValueError('failed to read PRG-ROM on ROM.')
|
[
"def",
"prg_rom",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"raw_data",
"[",
"self",
".",
"prg_rom_start",
":",
"self",
".",
"prg_rom_stop",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"'failed to read PRG-ROM on ROM.'",
")"
] |
Return the PRG ROM of the ROM file.
|
[
"Return",
"the",
"PRG",
"ROM",
"of",
"the",
"ROM",
"file",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/_rom.py#L201-L206
|
7,202
|
Kautenja/nes-py
|
nes_py/_rom.py
|
ROM.chr_rom
|
def chr_rom(self):
"""Return the CHR ROM of the ROM file."""
try:
return self.raw_data[self.chr_rom_start:self.chr_rom_stop]
except IndexError:
raise ValueError('failed to read CHR-ROM on ROM.')
|
python
|
def chr_rom(self):
"""Return the CHR ROM of the ROM file."""
try:
return self.raw_data[self.chr_rom_start:self.chr_rom_stop]
except IndexError:
raise ValueError('failed to read CHR-ROM on ROM.')
|
[
"def",
"chr_rom",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"raw_data",
"[",
"self",
".",
"chr_rom_start",
":",
"self",
".",
"chr_rom_stop",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"'failed to read CHR-ROM on ROM.'",
")"
] |
Return the CHR ROM of the ROM file.
|
[
"Return",
"the",
"CHR",
"ROM",
"of",
"the",
"ROM",
"file",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/_rom.py#L219-L224
|
7,203
|
Kautenja/nes-py
|
nes_py/nes_env.py
|
NESEnv._screen_buffer
|
def _screen_buffer(self):
"""Setup the screen buffer from the C++ code."""
# get the address of the screen
address = _LIB.Screen(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(SCREEN_TENSOR)).contents
# create a NumPy array from the buffer
screen = np.frombuffer(buffer_, dtype='uint8')
# reshape the screen from a column vector to a tensor
screen = screen.reshape(SCREEN_SHAPE_32_BIT)
# flip the bytes if the machine is little-endian (which it likely is)
if sys.byteorder == 'little':
# invert the little-endian BGRx channels to big-endian xRGB
screen = screen[:, :, ::-1]
# remove the 0th axis (padding from storing colors in 32 bit)
return screen[:, :, 1:]
|
python
|
def _screen_buffer(self):
"""Setup the screen buffer from the C++ code."""
# get the address of the screen
address = _LIB.Screen(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(SCREEN_TENSOR)).contents
# create a NumPy array from the buffer
screen = np.frombuffer(buffer_, dtype='uint8')
# reshape the screen from a column vector to a tensor
screen = screen.reshape(SCREEN_SHAPE_32_BIT)
# flip the bytes if the machine is little-endian (which it likely is)
if sys.byteorder == 'little':
# invert the little-endian BGRx channels to big-endian xRGB
screen = screen[:, :, ::-1]
# remove the 0th axis (padding from storing colors in 32 bit)
return screen[:, :, 1:]
|
[
"def",
"_screen_buffer",
"(",
"self",
")",
":",
"# get the address of the screen",
"address",
"=",
"_LIB",
".",
"Screen",
"(",
"self",
".",
"_env",
")",
"# create a buffer from the contents of the address location",
"buffer_",
"=",
"ctypes",
".",
"cast",
"(",
"address",
",",
"ctypes",
".",
"POINTER",
"(",
"SCREEN_TENSOR",
")",
")",
".",
"contents",
"# create a NumPy array from the buffer",
"screen",
"=",
"np",
".",
"frombuffer",
"(",
"buffer_",
",",
"dtype",
"=",
"'uint8'",
")",
"# reshape the screen from a column vector to a tensor",
"screen",
"=",
"screen",
".",
"reshape",
"(",
"SCREEN_SHAPE_32_BIT",
")",
"# flip the bytes if the machine is little-endian (which it likely is)",
"if",
"sys",
".",
"byteorder",
"==",
"'little'",
":",
"# invert the little-endian BGRx channels to big-endian xRGB",
"screen",
"=",
"screen",
"[",
":",
",",
":",
",",
":",
":",
"-",
"1",
"]",
"# remove the 0th axis (padding from storing colors in 32 bit)",
"return",
"screen",
"[",
":",
",",
":",
",",
"1",
":",
"]"
] |
Setup the screen buffer from the C++ code.
|
[
"Setup",
"the",
"screen",
"buffer",
"from",
"the",
"C",
"++",
"code",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L152-L167
|
7,204
|
Kautenja/nes-py
|
nes_py/nes_env.py
|
NESEnv._ram_buffer
|
def _ram_buffer(self):
"""Setup the RAM buffer from the C++ code."""
# get the address of the RAM
address = _LIB.Memory(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(RAM_VECTOR)).contents
# create a NumPy array from the buffer
return np.frombuffer(buffer_, dtype='uint8')
|
python
|
def _ram_buffer(self):
"""Setup the RAM buffer from the C++ code."""
# get the address of the RAM
address = _LIB.Memory(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(RAM_VECTOR)).contents
# create a NumPy array from the buffer
return np.frombuffer(buffer_, dtype='uint8')
|
[
"def",
"_ram_buffer",
"(",
"self",
")",
":",
"# get the address of the RAM",
"address",
"=",
"_LIB",
".",
"Memory",
"(",
"self",
".",
"_env",
")",
"# create a buffer from the contents of the address location",
"buffer_",
"=",
"ctypes",
".",
"cast",
"(",
"address",
",",
"ctypes",
".",
"POINTER",
"(",
"RAM_VECTOR",
")",
")",
".",
"contents",
"# create a NumPy array from the buffer",
"return",
"np",
".",
"frombuffer",
"(",
"buffer_",
",",
"dtype",
"=",
"'uint8'",
")"
] |
Setup the RAM buffer from the C++ code.
|
[
"Setup",
"the",
"RAM",
"buffer",
"from",
"the",
"C",
"++",
"code",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L169-L176
|
7,205
|
Kautenja/nes-py
|
nes_py/nes_env.py
|
NESEnv._controller_buffer
|
def _controller_buffer(self, port):
"""
Find the pointer to a controller and setup a NumPy buffer.
Args:
port: the port of the controller to setup
Returns:
a NumPy buffer with the controller's binary data
"""
# get the address of the controller
address = _LIB.Controller(self._env, port)
# create a memory buffer using the ctypes pointer for this vector
buffer_ = ctypes.cast(address, ctypes.POINTER(CONTROLLER_VECTOR)).contents
# create a NumPy buffer from the binary data and return it
return np.frombuffer(buffer_, dtype='uint8')
|
python
|
def _controller_buffer(self, port):
"""
Find the pointer to a controller and setup a NumPy buffer.
Args:
port: the port of the controller to setup
Returns:
a NumPy buffer with the controller's binary data
"""
# get the address of the controller
address = _LIB.Controller(self._env, port)
# create a memory buffer using the ctypes pointer for this vector
buffer_ = ctypes.cast(address, ctypes.POINTER(CONTROLLER_VECTOR)).contents
# create a NumPy buffer from the binary data and return it
return np.frombuffer(buffer_, dtype='uint8')
|
[
"def",
"_controller_buffer",
"(",
"self",
",",
"port",
")",
":",
"# get the address of the controller",
"address",
"=",
"_LIB",
".",
"Controller",
"(",
"self",
".",
"_env",
",",
"port",
")",
"# create a memory buffer using the ctypes pointer for this vector",
"buffer_",
"=",
"ctypes",
".",
"cast",
"(",
"address",
",",
"ctypes",
".",
"POINTER",
"(",
"CONTROLLER_VECTOR",
")",
")",
".",
"contents",
"# create a NumPy buffer from the binary data and return it",
"return",
"np",
".",
"frombuffer",
"(",
"buffer_",
",",
"dtype",
"=",
"'uint8'",
")"
] |
Find the pointer to a controller and setup a NumPy buffer.
Args:
port: the port of the controller to setup
Returns:
a NumPy buffer with the controller's binary data
|
[
"Find",
"the",
"pointer",
"to",
"a",
"controller",
"and",
"setup",
"a",
"NumPy",
"buffer",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L178-L194
|
7,206
|
Kautenja/nes-py
|
nes_py/nes_env.py
|
NESEnv._frame_advance
|
def _frame_advance(self, action):
"""
Advance a frame in the emulator with an action.
Args:
action (byte): the action to press on the joy-pad
Returns:
None
"""
# set the action on the controller
self.controllers[0][:] = action
# perform a step on the emulator
_LIB.Step(self._env)
|
python
|
def _frame_advance(self, action):
"""
Advance a frame in the emulator with an action.
Args:
action (byte): the action to press on the joy-pad
Returns:
None
"""
# set the action on the controller
self.controllers[0][:] = action
# perform a step on the emulator
_LIB.Step(self._env)
|
[
"def",
"_frame_advance",
"(",
"self",
",",
"action",
")",
":",
"# set the action on the controller",
"self",
".",
"controllers",
"[",
"0",
"]",
"[",
":",
"]",
"=",
"action",
"# perform a step on the emulator",
"_LIB",
".",
"Step",
"(",
"self",
".",
"_env",
")"
] |
Advance a frame in the emulator with an action.
Args:
action (byte): the action to press on the joy-pad
Returns:
None
|
[
"Advance",
"a",
"frame",
"in",
"the",
"emulator",
"with",
"an",
"action",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L196-L210
|
7,207
|
Kautenja/nes-py
|
nes_py/nes_env.py
|
NESEnv.reset
|
def reset(self):
"""
Reset the state of the environment and returns an initial observation.
Returns:
state (np.ndarray): next frame as a result of the given action
"""
# call the before reset callback
self._will_reset()
# reset the emulator
if self._has_backup:
self._restore()
else:
_LIB.Reset(self._env)
# call the after reset callback
self._did_reset()
# set the done flag to false
self.done = False
# return the screen from the emulator
return self.screen
|
python
|
def reset(self):
"""
Reset the state of the environment and returns an initial observation.
Returns:
state (np.ndarray): next frame as a result of the given action
"""
# call the before reset callback
self._will_reset()
# reset the emulator
if self._has_backup:
self._restore()
else:
_LIB.Reset(self._env)
# call the after reset callback
self._did_reset()
# set the done flag to false
self.done = False
# return the screen from the emulator
return self.screen
|
[
"def",
"reset",
"(",
"self",
")",
":",
"# call the before reset callback",
"self",
".",
"_will_reset",
"(",
")",
"# reset the emulator",
"if",
"self",
".",
"_has_backup",
":",
"self",
".",
"_restore",
"(",
")",
"else",
":",
"_LIB",
".",
"Reset",
"(",
"self",
".",
"_env",
")",
"# call the after reset callback",
"self",
".",
"_did_reset",
"(",
")",
"# set the done flag to false",
"self",
".",
"done",
"=",
"False",
"# return the screen from the emulator",
"return",
"self",
".",
"screen"
] |
Reset the state of the environment and returns an initial observation.
Returns:
state (np.ndarray): next frame as a result of the given action
|
[
"Reset",
"the",
"state",
"of",
"the",
"environment",
"and",
"returns",
"an",
"initial",
"observation",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L245-L265
|
7,208
|
Kautenja/nes-py
|
nes_py/nes_env.py
|
NESEnv.step
|
def step(self, action):
"""
Run one frame of the NES and return the relevant observation data.
Args:
action (byte): the bitmap determining which buttons to press
Returns:
a tuple of:
- state (np.ndarray): next frame as a result of the given action
- reward (float) : amount of reward returned after given action
- done (boolean): whether the episode has ended
- info (dict): contains auxiliary diagnostic information
"""
# if the environment is done, raise an error
if self.done:
raise ValueError('cannot step in a done environment! call `reset`')
# set the action on the controller
self.controllers[0][:] = action
# pass the action to the emulator as an unsigned byte
_LIB.Step(self._env)
# get the reward for this step
reward = self._get_reward()
# get the done flag for this step
self.done = self._get_done()
# get the info for this step
info = self._get_info()
# call the after step callback
self._did_step(self.done)
# bound the reward in [min, max]
if reward < self.reward_range[0]:
reward = self.reward_range[0]
elif reward > self.reward_range[1]:
reward = self.reward_range[1]
# return the screen from the emulator and other relevant data
return self.screen, reward, self.done, info
|
python
|
def step(self, action):
"""
Run one frame of the NES and return the relevant observation data.
Args:
action (byte): the bitmap determining which buttons to press
Returns:
a tuple of:
- state (np.ndarray): next frame as a result of the given action
- reward (float) : amount of reward returned after given action
- done (boolean): whether the episode has ended
- info (dict): contains auxiliary diagnostic information
"""
# if the environment is done, raise an error
if self.done:
raise ValueError('cannot step in a done environment! call `reset`')
# set the action on the controller
self.controllers[0][:] = action
# pass the action to the emulator as an unsigned byte
_LIB.Step(self._env)
# get the reward for this step
reward = self._get_reward()
# get the done flag for this step
self.done = self._get_done()
# get the info for this step
info = self._get_info()
# call the after step callback
self._did_step(self.done)
# bound the reward in [min, max]
if reward < self.reward_range[0]:
reward = self.reward_range[0]
elif reward > self.reward_range[1]:
reward = self.reward_range[1]
# return the screen from the emulator and other relevant data
return self.screen, reward, self.done, info
|
[
"def",
"step",
"(",
"self",
",",
"action",
")",
":",
"# if the environment is done, raise an error",
"if",
"self",
".",
"done",
":",
"raise",
"ValueError",
"(",
"'cannot step in a done environment! call `reset`'",
")",
"# set the action on the controller",
"self",
".",
"controllers",
"[",
"0",
"]",
"[",
":",
"]",
"=",
"action",
"# pass the action to the emulator as an unsigned byte",
"_LIB",
".",
"Step",
"(",
"self",
".",
"_env",
")",
"# get the reward for this step",
"reward",
"=",
"self",
".",
"_get_reward",
"(",
")",
"# get the done flag for this step",
"self",
".",
"done",
"=",
"self",
".",
"_get_done",
"(",
")",
"# get the info for this step",
"info",
"=",
"self",
".",
"_get_info",
"(",
")",
"# call the after step callback",
"self",
".",
"_did_step",
"(",
"self",
".",
"done",
")",
"# bound the reward in [min, max]",
"if",
"reward",
"<",
"self",
".",
"reward_range",
"[",
"0",
"]",
":",
"reward",
"=",
"self",
".",
"reward_range",
"[",
"0",
"]",
"elif",
"reward",
">",
"self",
".",
"reward_range",
"[",
"1",
"]",
":",
"reward",
"=",
"self",
".",
"reward_range",
"[",
"1",
"]",
"# return the screen from the emulator and other relevant data",
"return",
"self",
".",
"screen",
",",
"reward",
",",
"self",
".",
"done",
",",
"info"
] |
Run one frame of the NES and return the relevant observation data.
Args:
action (byte): the bitmap determining which buttons to press
Returns:
a tuple of:
- state (np.ndarray): next frame as a result of the given action
- reward (float) : amount of reward returned after given action
- done (boolean): whether the episode has ended
- info (dict): contains auxiliary diagnostic information
|
[
"Run",
"one",
"frame",
"of",
"the",
"NES",
"and",
"return",
"the",
"relevant",
"observation",
"data",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L271-L307
|
7,209
|
Kautenja/nes-py
|
nes_py/nes_env.py
|
NESEnv.close
|
def close(self):
"""Close the environment."""
# make sure the environment hasn't already been closed
if self._env is None:
raise ValueError('env has already been closed.')
# purge the environment from C++ memory
_LIB.Close(self._env)
# deallocate the object locally
self._env = None
# if there is an image viewer open, delete it
if self.viewer is not None:
self.viewer.close()
|
python
|
def close(self):
"""Close the environment."""
# make sure the environment hasn't already been closed
if self._env is None:
raise ValueError('env has already been closed.')
# purge the environment from C++ memory
_LIB.Close(self._env)
# deallocate the object locally
self._env = None
# if there is an image viewer open, delete it
if self.viewer is not None:
self.viewer.close()
|
[
"def",
"close",
"(",
"self",
")",
":",
"# make sure the environment hasn't already been closed",
"if",
"self",
".",
"_env",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'env has already been closed.'",
")",
"# purge the environment from C++ memory",
"_LIB",
".",
"Close",
"(",
"self",
".",
"_env",
")",
"# deallocate the object locally",
"self",
".",
"_env",
"=",
"None",
"# if there is an image viewer open, delete it",
"if",
"self",
".",
"viewer",
"is",
"not",
"None",
":",
"self",
".",
"viewer",
".",
"close",
"(",
")"
] |
Close the environment.
|
[
"Close",
"the",
"environment",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L334-L345
|
7,210
|
Kautenja/nes-py
|
nes_py/nes_env.py
|
NESEnv.render
|
def render(self, mode='human'):
"""
Render the environment.
Args:
mode (str): the mode to render with:
- human: render to the current display
- rgb_array: Return an numpy.ndarray with shape (x, y, 3),
representing RGB values for an x-by-y pixel image
Returns:
a numpy array if mode is 'rgb_array', None otherwise
"""
if mode == 'human':
# if the viewer isn't setup, import it and create one
if self.viewer is None:
from ._image_viewer import ImageViewer
# get the caption for the ImageViewer
if self.spec is None:
# if there is no spec, just use the .nes filename
caption = self._rom_path.split('/')[-1]
else:
# set the caption to the OpenAI Gym id
caption = self.spec.id
# create the ImageViewer to display frames
self.viewer = ImageViewer(
caption=caption,
height=SCREEN_HEIGHT,
width=SCREEN_WIDTH,
)
# show the screen on the image viewer
self.viewer.show(self.screen)
elif mode == 'rgb_array':
return self.screen
else:
# unpack the modes as comma delineated strings ('a', 'b', ...)
render_modes = [repr(x) for x in self.metadata['render.modes']]
msg = 'valid render modes are: {}'.format(', '.join(render_modes))
raise NotImplementedError(msg)
|
python
|
def render(self, mode='human'):
"""
Render the environment.
Args:
mode (str): the mode to render with:
- human: render to the current display
- rgb_array: Return an numpy.ndarray with shape (x, y, 3),
representing RGB values for an x-by-y pixel image
Returns:
a numpy array if mode is 'rgb_array', None otherwise
"""
if mode == 'human':
# if the viewer isn't setup, import it and create one
if self.viewer is None:
from ._image_viewer import ImageViewer
# get the caption for the ImageViewer
if self.spec is None:
# if there is no spec, just use the .nes filename
caption = self._rom_path.split('/')[-1]
else:
# set the caption to the OpenAI Gym id
caption = self.spec.id
# create the ImageViewer to display frames
self.viewer = ImageViewer(
caption=caption,
height=SCREEN_HEIGHT,
width=SCREEN_WIDTH,
)
# show the screen on the image viewer
self.viewer.show(self.screen)
elif mode == 'rgb_array':
return self.screen
else:
# unpack the modes as comma delineated strings ('a', 'b', ...)
render_modes = [repr(x) for x in self.metadata['render.modes']]
msg = 'valid render modes are: {}'.format(', '.join(render_modes))
raise NotImplementedError(msg)
|
[
"def",
"render",
"(",
"self",
",",
"mode",
"=",
"'human'",
")",
":",
"if",
"mode",
"==",
"'human'",
":",
"# if the viewer isn't setup, import it and create one",
"if",
"self",
".",
"viewer",
"is",
"None",
":",
"from",
".",
"_image_viewer",
"import",
"ImageViewer",
"# get the caption for the ImageViewer",
"if",
"self",
".",
"spec",
"is",
"None",
":",
"# if there is no spec, just use the .nes filename",
"caption",
"=",
"self",
".",
"_rom_path",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"else",
":",
"# set the caption to the OpenAI Gym id",
"caption",
"=",
"self",
".",
"spec",
".",
"id",
"# create the ImageViewer to display frames",
"self",
".",
"viewer",
"=",
"ImageViewer",
"(",
"caption",
"=",
"caption",
",",
"height",
"=",
"SCREEN_HEIGHT",
",",
"width",
"=",
"SCREEN_WIDTH",
",",
")",
"# show the screen on the image viewer",
"self",
".",
"viewer",
".",
"show",
"(",
"self",
".",
"screen",
")",
"elif",
"mode",
"==",
"'rgb_array'",
":",
"return",
"self",
".",
"screen",
"else",
":",
"# unpack the modes as comma delineated strings ('a', 'b', ...)",
"render_modes",
"=",
"[",
"repr",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"metadata",
"[",
"'render.modes'",
"]",
"]",
"msg",
"=",
"'valid render modes are: {}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"render_modes",
")",
")",
"raise",
"NotImplementedError",
"(",
"msg",
")"
] |
Render the environment.
Args:
mode (str): the mode to render with:
- human: render to the current display
- rgb_array: Return an numpy.ndarray with shape (x, y, 3),
representing RGB values for an x-by-y pixel image
Returns:
a numpy array if mode is 'rgb_array', None otherwise
|
[
"Render",
"the",
"environment",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L347-L386
|
7,211
|
Kautenja/nes-py
|
nes_py/app/cli.py
|
_get_args
|
def _get_args():
"""Parse arguments from the command line and return them."""
parser = argparse.ArgumentParser(description=__doc__)
# add the argument for the Super Mario Bros environment to run
parser.add_argument('--rom', '-r',
type=str,
help='The path to the ROM to play.',
required=True,
)
# add the argument for the mode of execution as either human or random
parser.add_argument('--mode', '-m',
type=str,
default='human',
choices=['human', 'random'],
help='The execution mode for the emulation.',
)
# add the argument for the number of steps to take in random mode
parser.add_argument('--steps', '-s',
type=int,
default=500,
help='The number of random steps to take.',
)
return parser.parse_args()
|
python
|
def _get_args():
"""Parse arguments from the command line and return them."""
parser = argparse.ArgumentParser(description=__doc__)
# add the argument for the Super Mario Bros environment to run
parser.add_argument('--rom', '-r',
type=str,
help='The path to the ROM to play.',
required=True,
)
# add the argument for the mode of execution as either human or random
parser.add_argument('--mode', '-m',
type=str,
default='human',
choices=['human', 'random'],
help='The execution mode for the emulation.',
)
# add the argument for the number of steps to take in random mode
parser.add_argument('--steps', '-s',
type=int,
default=500,
help='The number of random steps to take.',
)
return parser.parse_args()
|
[
"def",
"_get_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"# add the argument for the Super Mario Bros environment to run",
"parser",
".",
"add_argument",
"(",
"'--rom'",
",",
"'-r'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'The path to the ROM to play.'",
",",
"required",
"=",
"True",
",",
")",
"# add the argument for the mode of execution as either human or random",
"parser",
".",
"add_argument",
"(",
"'--mode'",
",",
"'-m'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'human'",
",",
"choices",
"=",
"[",
"'human'",
",",
"'random'",
"]",
",",
"help",
"=",
"'The execution mode for the emulation.'",
",",
")",
"# add the argument for the number of steps to take in random mode",
"parser",
".",
"add_argument",
"(",
"'--steps'",
",",
"'-s'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"500",
",",
"help",
"=",
"'The number of random steps to take.'",
",",
")",
"return",
"parser",
".",
"parse_args",
"(",
")"
] |
Parse arguments from the command line and return them.
|
[
"Parse",
"arguments",
"from",
"the",
"command",
"line",
"and",
"return",
"them",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/cli.py#L8-L30
|
7,212
|
Kautenja/nes-py
|
nes_py/app/cli.py
|
main
|
def main():
"""The main entry point for the command line interface."""
# get arguments from the command line
args = _get_args()
# create the environment
env = NESEnv(args.rom)
# play the environment with the given mode
if args.mode == 'human':
play_human(env)
else:
play_random(env, args.steps)
|
python
|
def main():
"""The main entry point for the command line interface."""
# get arguments from the command line
args = _get_args()
# create the environment
env = NESEnv(args.rom)
# play the environment with the given mode
if args.mode == 'human':
play_human(env)
else:
play_random(env, args.steps)
|
[
"def",
"main",
"(",
")",
":",
"# get arguments from the command line",
"args",
"=",
"_get_args",
"(",
")",
"# create the environment",
"env",
"=",
"NESEnv",
"(",
"args",
".",
"rom",
")",
"# play the environment with the given mode",
"if",
"args",
".",
"mode",
"==",
"'human'",
":",
"play_human",
"(",
"env",
")",
"else",
":",
"play_random",
"(",
"env",
",",
"args",
".",
"steps",
")"
] |
The main entry point for the command line interface.
|
[
"The",
"main",
"entry",
"point",
"for",
"the",
"command",
"line",
"interface",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/cli.py#L33-L43
|
7,213
|
Kautenja/nes-py
|
nes_py/app/play_random.py
|
play_random
|
def play_random(env, steps):
"""
Play the environment making uniformly random decisions.
Args:
env (gym.Env): the initialized gym environment to play
steps (int): the number of random steps to take
Returns:
None
"""
try:
done = True
progress = tqdm(range(steps))
for _ in progress:
if done:
_ = env.reset()
action = env.action_space.sample()
_, reward, done, info = env.step(action)
progress.set_postfix(reward=reward, info=info)
env.render()
except KeyboardInterrupt:
pass
# close the environment
env.close()
|
python
|
def play_random(env, steps):
"""
Play the environment making uniformly random decisions.
Args:
env (gym.Env): the initialized gym environment to play
steps (int): the number of random steps to take
Returns:
None
"""
try:
done = True
progress = tqdm(range(steps))
for _ in progress:
if done:
_ = env.reset()
action = env.action_space.sample()
_, reward, done, info = env.step(action)
progress.set_postfix(reward=reward, info=info)
env.render()
except KeyboardInterrupt:
pass
# close the environment
env.close()
|
[
"def",
"play_random",
"(",
"env",
",",
"steps",
")",
":",
"try",
":",
"done",
"=",
"True",
"progress",
"=",
"tqdm",
"(",
"range",
"(",
"steps",
")",
")",
"for",
"_",
"in",
"progress",
":",
"if",
"done",
":",
"_",
"=",
"env",
".",
"reset",
"(",
")",
"action",
"=",
"env",
".",
"action_space",
".",
"sample",
"(",
")",
"_",
",",
"reward",
",",
"done",
",",
"info",
"=",
"env",
".",
"step",
"(",
"action",
")",
"progress",
".",
"set_postfix",
"(",
"reward",
"=",
"reward",
",",
"info",
"=",
"info",
")",
"env",
".",
"render",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"pass",
"# close the environment",
"env",
".",
"close",
"(",
")"
] |
Play the environment making uniformly random decisions.
Args:
env (gym.Env): the initialized gym environment to play
steps (int): the number of random steps to take
Returns:
None
|
[
"Play",
"the",
"environment",
"making",
"uniformly",
"random",
"decisions",
"."
] |
a113885198d418f38fcf24b8f79ac508975788c2
|
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/play_random.py#L5-L30
|
7,214
|
czielinski/portfolioopt
|
portfolioopt/portfolioopt.py
|
markowitz_portfolio
|
def markowitz_portfolio(cov_mat, exp_rets, target_ret,
allow_short=False, market_neutral=False):
"""
Computes a Markowitz portfolio.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
exp_rets: pandas.Series
Expected asset returns (often historical returns).
target_ret: float
Target return of portfolio.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
market_neutral: bool, optional
If 'False' sum of weights equals one.
If 'True' sum of weights equal zero, i.e. create a
market neutral portfolio (implies allow_short=True).
Returns
-------
weights: pandas.Series
Optimal asset weights.
"""
if not isinstance(cov_mat, pd.DataFrame):
raise ValueError("Covariance matrix is not a DataFrame")
if not isinstance(exp_rets, pd.Series):
raise ValueError("Expected returns is not a Series")
if not isinstance(target_ret, float):
raise ValueError("Target return is not a float")
if not cov_mat.index.equals(exp_rets.index):
raise ValueError("Indices do not match")
if market_neutral and not allow_short:
warnings.warn("A market neutral portfolio implies shorting")
allow_short=True
n = len(cov_mat)
P = opt.matrix(cov_mat.values)
q = opt.matrix(0.0, (n, 1))
# Constraints Gx <= h
if not allow_short:
# exp_rets*x >= target_ret and x >= 0
G = opt.matrix(np.vstack((-exp_rets.values,
-np.identity(n))))
h = opt.matrix(np.vstack((-target_ret,
+np.zeros((n, 1)))))
else:
# exp_rets*x >= target_ret
G = opt.matrix(-exp_rets.values).T
h = opt.matrix(-target_ret)
# Constraints Ax = b
# sum(x) = 1
A = opt.matrix(1.0, (1, n))
if not market_neutral:
b = opt.matrix(1.0)
else:
b = opt.matrix(0.0)
# Solve
optsolvers.options['show_progress'] = False
sol = optsolvers.qp(P, q, G, h, A, b)
if sol['status'] != 'optimal':
warnings.warn("Convergence problem")
# Put weights into a labeled series
weights = pd.Series(sol['x'], index=cov_mat.index)
return weights
|
python
|
def markowitz_portfolio(cov_mat, exp_rets, target_ret,
allow_short=False, market_neutral=False):
"""
Computes a Markowitz portfolio.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
exp_rets: pandas.Series
Expected asset returns (often historical returns).
target_ret: float
Target return of portfolio.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
market_neutral: bool, optional
If 'False' sum of weights equals one.
If 'True' sum of weights equal zero, i.e. create a
market neutral portfolio (implies allow_short=True).
Returns
-------
weights: pandas.Series
Optimal asset weights.
"""
if not isinstance(cov_mat, pd.DataFrame):
raise ValueError("Covariance matrix is not a DataFrame")
if not isinstance(exp_rets, pd.Series):
raise ValueError("Expected returns is not a Series")
if not isinstance(target_ret, float):
raise ValueError("Target return is not a float")
if not cov_mat.index.equals(exp_rets.index):
raise ValueError("Indices do not match")
if market_neutral and not allow_short:
warnings.warn("A market neutral portfolio implies shorting")
allow_short=True
n = len(cov_mat)
P = opt.matrix(cov_mat.values)
q = opt.matrix(0.0, (n, 1))
# Constraints Gx <= h
if not allow_short:
# exp_rets*x >= target_ret and x >= 0
G = opt.matrix(np.vstack((-exp_rets.values,
-np.identity(n))))
h = opt.matrix(np.vstack((-target_ret,
+np.zeros((n, 1)))))
else:
# exp_rets*x >= target_ret
G = opt.matrix(-exp_rets.values).T
h = opt.matrix(-target_ret)
# Constraints Ax = b
# sum(x) = 1
A = opt.matrix(1.0, (1, n))
if not market_neutral:
b = opt.matrix(1.0)
else:
b = opt.matrix(0.0)
# Solve
optsolvers.options['show_progress'] = False
sol = optsolvers.qp(P, q, G, h, A, b)
if sol['status'] != 'optimal':
warnings.warn("Convergence problem")
# Put weights into a labeled series
weights = pd.Series(sol['x'], index=cov_mat.index)
return weights
|
[
"def",
"markowitz_portfolio",
"(",
"cov_mat",
",",
"exp_rets",
",",
"target_ret",
",",
"allow_short",
"=",
"False",
",",
"market_neutral",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"cov_mat",
",",
"pd",
".",
"DataFrame",
")",
":",
"raise",
"ValueError",
"(",
"\"Covariance matrix is not a DataFrame\"",
")",
"if",
"not",
"isinstance",
"(",
"exp_rets",
",",
"pd",
".",
"Series",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected returns is not a Series\"",
")",
"if",
"not",
"isinstance",
"(",
"target_ret",
",",
"float",
")",
":",
"raise",
"ValueError",
"(",
"\"Target return is not a float\"",
")",
"if",
"not",
"cov_mat",
".",
"index",
".",
"equals",
"(",
"exp_rets",
".",
"index",
")",
":",
"raise",
"ValueError",
"(",
"\"Indices do not match\"",
")",
"if",
"market_neutral",
"and",
"not",
"allow_short",
":",
"warnings",
".",
"warn",
"(",
"\"A market neutral portfolio implies shorting\"",
")",
"allow_short",
"=",
"True",
"n",
"=",
"len",
"(",
"cov_mat",
")",
"P",
"=",
"opt",
".",
"matrix",
"(",
"cov_mat",
".",
"values",
")",
"q",
"=",
"opt",
".",
"matrix",
"(",
"0.0",
",",
"(",
"n",
",",
"1",
")",
")",
"# Constraints Gx <= h",
"if",
"not",
"allow_short",
":",
"# exp_rets*x >= target_ret and x >= 0",
"G",
"=",
"opt",
".",
"matrix",
"(",
"np",
".",
"vstack",
"(",
"(",
"-",
"exp_rets",
".",
"values",
",",
"-",
"np",
".",
"identity",
"(",
"n",
")",
")",
")",
")",
"h",
"=",
"opt",
".",
"matrix",
"(",
"np",
".",
"vstack",
"(",
"(",
"-",
"target_ret",
",",
"+",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"1",
")",
")",
")",
")",
")",
"else",
":",
"# exp_rets*x >= target_ret",
"G",
"=",
"opt",
".",
"matrix",
"(",
"-",
"exp_rets",
".",
"values",
")",
".",
"T",
"h",
"=",
"opt",
".",
"matrix",
"(",
"-",
"target_ret",
")",
"# Constraints Ax = b",
"# sum(x) = 1",
"A",
"=",
"opt",
".",
"matrix",
"(",
"1.0",
",",
"(",
"1",
",",
"n",
")",
")",
"if",
"not",
"market_neutral",
":",
"b",
"=",
"opt",
".",
"matrix",
"(",
"1.0",
")",
"else",
":",
"b",
"=",
"opt",
".",
"matrix",
"(",
"0.0",
")",
"# Solve",
"optsolvers",
".",
"options",
"[",
"'show_progress'",
"]",
"=",
"False",
"sol",
"=",
"optsolvers",
".",
"qp",
"(",
"P",
",",
"q",
",",
"G",
",",
"h",
",",
"A",
",",
"b",
")",
"if",
"sol",
"[",
"'status'",
"]",
"!=",
"'optimal'",
":",
"warnings",
".",
"warn",
"(",
"\"Convergence problem\"",
")",
"# Put weights into a labeled series",
"weights",
"=",
"pd",
".",
"Series",
"(",
"sol",
"[",
"'x'",
"]",
",",
"index",
"=",
"cov_mat",
".",
"index",
")",
"return",
"weights"
] |
Computes a Markowitz portfolio.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
exp_rets: pandas.Series
Expected asset returns (often historical returns).
target_ret: float
Target return of portfolio.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
market_neutral: bool, optional
If 'False' sum of weights equals one.
If 'True' sum of weights equal zero, i.e. create a
market neutral portfolio (implies allow_short=True).
Returns
-------
weights: pandas.Series
Optimal asset weights.
|
[
"Computes",
"a",
"Markowitz",
"portfolio",
"."
] |
96ac25daab0c0dbc8933330a92ff31fb898112f2
|
https://github.com/czielinski/portfolioopt/blob/96ac25daab0c0dbc8933330a92ff31fb898112f2/portfolioopt/portfolioopt.py#L45-L122
|
7,215
|
czielinski/portfolioopt
|
portfolioopt/portfolioopt.py
|
min_var_portfolio
|
def min_var_portfolio(cov_mat, allow_short=False):
"""
Computes the minimum variance portfolio.
Note: As the variance is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral minimum variance portfolios. This is because
the variance approaches zero with decreasing leverage,
i.e. the market neutral portfolio with minimum variance
is not invested at all.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
Returns
-------
weights: pandas.Series
Optimal asset weights.
"""
if not isinstance(cov_mat, pd.DataFrame):
raise ValueError("Covariance matrix is not a DataFrame")
n = len(cov_mat)
P = opt.matrix(cov_mat.values)
q = opt.matrix(0.0, (n, 1))
# Constraints Gx <= h
if not allow_short:
# x >= 0
G = opt.matrix(-np.identity(n))
h = opt.matrix(0.0, (n, 1))
else:
G = None
h = None
# Constraints Ax = b
# sum(x) = 1
A = opt.matrix(1.0, (1, n))
b = opt.matrix(1.0)
# Solve
optsolvers.options['show_progress'] = False
sol = optsolvers.qp(P, q, G, h, A, b)
if sol['status'] != 'optimal':
warnings.warn("Convergence problem")
# Put weights into a labeled series
weights = pd.Series(sol['x'], index=cov_mat.index)
return weights
|
python
|
def min_var_portfolio(cov_mat, allow_short=False):
"""
Computes the minimum variance portfolio.
Note: As the variance is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral minimum variance portfolios. This is because
the variance approaches zero with decreasing leverage,
i.e. the market neutral portfolio with minimum variance
is not invested at all.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
Returns
-------
weights: pandas.Series
Optimal asset weights.
"""
if not isinstance(cov_mat, pd.DataFrame):
raise ValueError("Covariance matrix is not a DataFrame")
n = len(cov_mat)
P = opt.matrix(cov_mat.values)
q = opt.matrix(0.0, (n, 1))
# Constraints Gx <= h
if not allow_short:
# x >= 0
G = opt.matrix(-np.identity(n))
h = opt.matrix(0.0, (n, 1))
else:
G = None
h = None
# Constraints Ax = b
# sum(x) = 1
A = opt.matrix(1.0, (1, n))
b = opt.matrix(1.0)
# Solve
optsolvers.options['show_progress'] = False
sol = optsolvers.qp(P, q, G, h, A, b)
if sol['status'] != 'optimal':
warnings.warn("Convergence problem")
# Put weights into a labeled series
weights = pd.Series(sol['x'], index=cov_mat.index)
return weights
|
[
"def",
"min_var_portfolio",
"(",
"cov_mat",
",",
"allow_short",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"cov_mat",
",",
"pd",
".",
"DataFrame",
")",
":",
"raise",
"ValueError",
"(",
"\"Covariance matrix is not a DataFrame\"",
")",
"n",
"=",
"len",
"(",
"cov_mat",
")",
"P",
"=",
"opt",
".",
"matrix",
"(",
"cov_mat",
".",
"values",
")",
"q",
"=",
"opt",
".",
"matrix",
"(",
"0.0",
",",
"(",
"n",
",",
"1",
")",
")",
"# Constraints Gx <= h",
"if",
"not",
"allow_short",
":",
"# x >= 0",
"G",
"=",
"opt",
".",
"matrix",
"(",
"-",
"np",
".",
"identity",
"(",
"n",
")",
")",
"h",
"=",
"opt",
".",
"matrix",
"(",
"0.0",
",",
"(",
"n",
",",
"1",
")",
")",
"else",
":",
"G",
"=",
"None",
"h",
"=",
"None",
"# Constraints Ax = b",
"# sum(x) = 1",
"A",
"=",
"opt",
".",
"matrix",
"(",
"1.0",
",",
"(",
"1",
",",
"n",
")",
")",
"b",
"=",
"opt",
".",
"matrix",
"(",
"1.0",
")",
"# Solve",
"optsolvers",
".",
"options",
"[",
"'show_progress'",
"]",
"=",
"False",
"sol",
"=",
"optsolvers",
".",
"qp",
"(",
"P",
",",
"q",
",",
"G",
",",
"h",
",",
"A",
",",
"b",
")",
"if",
"sol",
"[",
"'status'",
"]",
"!=",
"'optimal'",
":",
"warnings",
".",
"warn",
"(",
"\"Convergence problem\"",
")",
"# Put weights into a labeled series",
"weights",
"=",
"pd",
".",
"Series",
"(",
"sol",
"[",
"'x'",
"]",
",",
"index",
"=",
"cov_mat",
".",
"index",
")",
"return",
"weights"
] |
Computes the minimum variance portfolio.
Note: As the variance is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral minimum variance portfolios. This is because
the variance approaches zero with decreasing leverage,
i.e. the market neutral portfolio with minimum variance
is not invested at all.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
Returns
-------
weights: pandas.Series
Optimal asset weights.
|
[
"Computes",
"the",
"minimum",
"variance",
"portfolio",
"."
] |
96ac25daab0c0dbc8933330a92ff31fb898112f2
|
https://github.com/czielinski/portfolioopt/blob/96ac25daab0c0dbc8933330a92ff31fb898112f2/portfolioopt/portfolioopt.py#L125-L180
|
7,216
|
czielinski/portfolioopt
|
example.py
|
print_portfolio_info
|
def print_portfolio_info(returns, avg_rets, weights):
"""
Print information on expected portfolio performance.
"""
ret = (weights * avg_rets).sum()
std = (weights * returns).sum(1).std()
sharpe = ret / std
print("Optimal weights:\n{}\n".format(weights))
print("Expected return: {}".format(ret))
print("Expected variance: {}".format(std**2))
print("Expected Sharpe: {}".format(sharpe))
|
python
|
def print_portfolio_info(returns, avg_rets, weights):
"""
Print information on expected portfolio performance.
"""
ret = (weights * avg_rets).sum()
std = (weights * returns).sum(1).std()
sharpe = ret / std
print("Optimal weights:\n{}\n".format(weights))
print("Expected return: {}".format(ret))
print("Expected variance: {}".format(std**2))
print("Expected Sharpe: {}".format(sharpe))
|
[
"def",
"print_portfolio_info",
"(",
"returns",
",",
"avg_rets",
",",
"weights",
")",
":",
"ret",
"=",
"(",
"weights",
"*",
"avg_rets",
")",
".",
"sum",
"(",
")",
"std",
"=",
"(",
"weights",
"*",
"returns",
")",
".",
"sum",
"(",
"1",
")",
".",
"std",
"(",
")",
"sharpe",
"=",
"ret",
"/",
"std",
"print",
"(",
"\"Optimal weights:\\n{}\\n\"",
".",
"format",
"(",
"weights",
")",
")",
"print",
"(",
"\"Expected return: {}\"",
".",
"format",
"(",
"ret",
")",
")",
"print",
"(",
"\"Expected variance: {}\"",
".",
"format",
"(",
"std",
"**",
"2",
")",
")",
"print",
"(",
"\"Expected Sharpe: {}\"",
".",
"format",
"(",
"sharpe",
")",
")"
] |
Print information on expected portfolio performance.
|
[
"Print",
"information",
"on",
"expected",
"portfolio",
"performance",
"."
] |
96ac25daab0c0dbc8933330a92ff31fb898112f2
|
https://github.com/czielinski/portfolioopt/blob/96ac25daab0c0dbc8933330a92ff31fb898112f2/example.py#L36-L46
|
7,217
|
CityOfZion/neo-boa
|
boa/code/module.py
|
Module.main
|
def main(self):
"""
Return the default method in this module.
:return: the default method in this module
:rtype: ``boa.code.method.Method``
"""
for m in self.methods:
if m.name in ['Main', 'main']:
return m
if len(self.methods):
return self.methods[0]
return None
|
python
|
def main(self):
"""
Return the default method in this module.
:return: the default method in this module
:rtype: ``boa.code.method.Method``
"""
for m in self.methods:
if m.name in ['Main', 'main']:
return m
if len(self.methods):
return self.methods[0]
return None
|
[
"def",
"main",
"(",
"self",
")",
":",
"for",
"m",
"in",
"self",
".",
"methods",
":",
"if",
"m",
".",
"name",
"in",
"[",
"'Main'",
",",
"'main'",
"]",
":",
"return",
"m",
"if",
"len",
"(",
"self",
".",
"methods",
")",
":",
"return",
"self",
".",
"methods",
"[",
"0",
"]",
"return",
"None"
] |
Return the default method in this module.
:return: the default method in this module
:rtype: ``boa.code.method.Method``
|
[
"Return",
"the",
"default",
"method",
"in",
"this",
"module",
"."
] |
5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b
|
https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/code/module.py#L74-L90
|
7,218
|
CityOfZion/neo-boa
|
boa/code/module.py
|
Module.orderered_methods
|
def orderered_methods(self):
"""
An ordered list of methods
:return: A list of ordered methods is this module
:rtype: list
"""
oms = []
self.methods.reverse()
if self.main:
oms = [self.main]
for m in self.methods:
if m == self.main:
continue
oms.append(m)
return oms
|
python
|
def orderered_methods(self):
"""
An ordered list of methods
:return: A list of ordered methods is this module
:rtype: list
"""
oms = []
self.methods.reverse()
if self.main:
oms = [self.main]
for m in self.methods:
if m == self.main:
continue
oms.append(m)
return oms
|
[
"def",
"orderered_methods",
"(",
"self",
")",
":",
"oms",
"=",
"[",
"]",
"self",
".",
"methods",
".",
"reverse",
"(",
")",
"if",
"self",
".",
"main",
":",
"oms",
"=",
"[",
"self",
".",
"main",
"]",
"for",
"m",
"in",
"self",
".",
"methods",
":",
"if",
"m",
"==",
"self",
".",
"main",
":",
"continue",
"oms",
".",
"append",
"(",
"m",
")",
"return",
"oms"
] |
An ordered list of methods
:return: A list of ordered methods is this module
:rtype: list
|
[
"An",
"ordered",
"list",
"of",
"methods"
] |
5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b
|
https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/code/module.py#L93-L114
|
7,219
|
CityOfZion/neo-boa
|
boa/code/module.py
|
Module.write_methods
|
def write_methods(self):
"""
Write all methods in the current module to a byte string.
:return: A bytestring of all current methods in this module
:rtype: bytes
"""
b_array = bytearray()
for key, vm_token in self.all_vm_tokens.items():
b_array.append(vm_token.out_op)
if vm_token.data is not None and vm_token.vm_op != VMOp.NOP:
b_array = b_array + vm_token.data
# self.to_s()
return b_array
|
python
|
def write_methods(self):
"""
Write all methods in the current module to a byte string.
:return: A bytestring of all current methods in this module
:rtype: bytes
"""
b_array = bytearray()
for key, vm_token in self.all_vm_tokens.items():
b_array.append(vm_token.out_op)
if vm_token.data is not None and vm_token.vm_op != VMOp.NOP:
b_array = b_array + vm_token.data
# self.to_s()
return b_array
|
[
"def",
"write_methods",
"(",
"self",
")",
":",
"b_array",
"=",
"bytearray",
"(",
")",
"for",
"key",
",",
"vm_token",
"in",
"self",
".",
"all_vm_tokens",
".",
"items",
"(",
")",
":",
"b_array",
".",
"append",
"(",
"vm_token",
".",
"out_op",
")",
"if",
"vm_token",
".",
"data",
"is",
"not",
"None",
"and",
"vm_token",
".",
"vm_op",
"!=",
"VMOp",
".",
"NOP",
":",
"b_array",
"=",
"b_array",
"+",
"vm_token",
".",
"data",
"# self.to_s()",
"return",
"b_array"
] |
Write all methods in the current module to a byte string.
:return: A bytestring of all current methods in this module
:rtype: bytes
|
[
"Write",
"all",
"methods",
"in",
"the",
"current",
"module",
"to",
"a",
"byte",
"string",
"."
] |
5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b
|
https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/code/module.py#L215-L232
|
7,220
|
CityOfZion/neo-boa
|
boa/code/module.py
|
Module.link_methods
|
def link_methods(self):
"""
Perform linkage of addresses between methods.
"""
from ..compiler import Compiler
for method in self.methods:
method.prepare()
self.all_vm_tokens = OrderedDict()
address = 0
for method in self.orderered_methods:
if not method.is_interop:
# print("ADDING METHOD %s " % method.full_name)
method.address = address
for key, vmtoken in method.vm_tokens.items():
self.all_vm_tokens[address] = vmtoken
address += 1
if vmtoken.data is not None and vmtoken.vm_op != VMOp.NOP:
address += len(vmtoken.data)
vmtoken.addr = vmtoken.addr + method.address
for key, vmtoken in self.all_vm_tokens.items():
if vmtoken.src_method is not None:
target_method = self.method_by_name(vmtoken.target_method)
if target_method:
jump_len = target_method.address - vmtoken.addr
param_ret_counts = bytearray()
if Compiler.instance().nep8:
param_ret_counts = vmtoken.data[0:2]
jump_len -= 2
if jump_len > -32767 and jump_len < 32767:
vmtoken.data = param_ret_counts + jump_len.to_bytes(2, 'little', signed=True)
else:
vmtoken.data = param_ret_counts + jump_len.to_bytes(4, 'little', signed=True)
else:
raise Exception("Target method %s not found" % vmtoken.target_method)
|
python
|
def link_methods(self):
"""
Perform linkage of addresses between methods.
"""
from ..compiler import Compiler
for method in self.methods:
method.prepare()
self.all_vm_tokens = OrderedDict()
address = 0
for method in self.orderered_methods:
if not method.is_interop:
# print("ADDING METHOD %s " % method.full_name)
method.address = address
for key, vmtoken in method.vm_tokens.items():
self.all_vm_tokens[address] = vmtoken
address += 1
if vmtoken.data is not None and vmtoken.vm_op != VMOp.NOP:
address += len(vmtoken.data)
vmtoken.addr = vmtoken.addr + method.address
for key, vmtoken in self.all_vm_tokens.items():
if vmtoken.src_method is not None:
target_method = self.method_by_name(vmtoken.target_method)
if target_method:
jump_len = target_method.address - vmtoken.addr
param_ret_counts = bytearray()
if Compiler.instance().nep8:
param_ret_counts = vmtoken.data[0:2]
jump_len -= 2
if jump_len > -32767 and jump_len < 32767:
vmtoken.data = param_ret_counts + jump_len.to_bytes(2, 'little', signed=True)
else:
vmtoken.data = param_ret_counts + jump_len.to_bytes(4, 'little', signed=True)
else:
raise Exception("Target method %s not found" % vmtoken.target_method)
|
[
"def",
"link_methods",
"(",
"self",
")",
":",
"from",
".",
".",
"compiler",
"import",
"Compiler",
"for",
"method",
"in",
"self",
".",
"methods",
":",
"method",
".",
"prepare",
"(",
")",
"self",
".",
"all_vm_tokens",
"=",
"OrderedDict",
"(",
")",
"address",
"=",
"0",
"for",
"method",
"in",
"self",
".",
"orderered_methods",
":",
"if",
"not",
"method",
".",
"is_interop",
":",
"# print(\"ADDING METHOD %s \" % method.full_name)",
"method",
".",
"address",
"=",
"address",
"for",
"key",
",",
"vmtoken",
"in",
"method",
".",
"vm_tokens",
".",
"items",
"(",
")",
":",
"self",
".",
"all_vm_tokens",
"[",
"address",
"]",
"=",
"vmtoken",
"address",
"+=",
"1",
"if",
"vmtoken",
".",
"data",
"is",
"not",
"None",
"and",
"vmtoken",
".",
"vm_op",
"!=",
"VMOp",
".",
"NOP",
":",
"address",
"+=",
"len",
"(",
"vmtoken",
".",
"data",
")",
"vmtoken",
".",
"addr",
"=",
"vmtoken",
".",
"addr",
"+",
"method",
".",
"address",
"for",
"key",
",",
"vmtoken",
"in",
"self",
".",
"all_vm_tokens",
".",
"items",
"(",
")",
":",
"if",
"vmtoken",
".",
"src_method",
"is",
"not",
"None",
":",
"target_method",
"=",
"self",
".",
"method_by_name",
"(",
"vmtoken",
".",
"target_method",
")",
"if",
"target_method",
":",
"jump_len",
"=",
"target_method",
".",
"address",
"-",
"vmtoken",
".",
"addr",
"param_ret_counts",
"=",
"bytearray",
"(",
")",
"if",
"Compiler",
".",
"instance",
"(",
")",
".",
"nep8",
":",
"param_ret_counts",
"=",
"vmtoken",
".",
"data",
"[",
"0",
":",
"2",
"]",
"jump_len",
"-=",
"2",
"if",
"jump_len",
">",
"-",
"32767",
"and",
"jump_len",
"<",
"32767",
":",
"vmtoken",
".",
"data",
"=",
"param_ret_counts",
"+",
"jump_len",
".",
"to_bytes",
"(",
"2",
",",
"'little'",
",",
"signed",
"=",
"True",
")",
"else",
":",
"vmtoken",
".",
"data",
"=",
"param_ret_counts",
"+",
"jump_len",
".",
"to_bytes",
"(",
"4",
",",
"'little'",
",",
"signed",
"=",
"True",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Target method %s not found\"",
"%",
"vmtoken",
".",
"target_method",
")"
] |
Perform linkage of addresses between methods.
|
[
"Perform",
"linkage",
"of",
"addresses",
"between",
"methods",
"."
] |
5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b
|
https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/code/module.py#L234-L280
|
7,221
|
CityOfZion/neo-boa
|
boa/code/module.py
|
Module.export_debug
|
def export_debug(self, output_path):
"""
this method is used to generate a debug map for NEO debugger
"""
file_hash = hashlib.md5(open(output_path, 'rb').read()).hexdigest()
avm_name = os.path.splitext(os.path.basename(output_path))[0]
json_data = self.generate_debug_json(avm_name, file_hash)
mapfilename = output_path.replace('.avm', '.debug.json')
with open(mapfilename, 'w+') as out_file:
out_file.write(json_data)
|
python
|
def export_debug(self, output_path):
"""
this method is used to generate a debug map for NEO debugger
"""
file_hash = hashlib.md5(open(output_path, 'rb').read()).hexdigest()
avm_name = os.path.splitext(os.path.basename(output_path))[0]
json_data = self.generate_debug_json(avm_name, file_hash)
mapfilename = output_path.replace('.avm', '.debug.json')
with open(mapfilename, 'w+') as out_file:
out_file.write(json_data)
|
[
"def",
"export_debug",
"(",
"self",
",",
"output_path",
")",
":",
"file_hash",
"=",
"hashlib",
".",
"md5",
"(",
"open",
"(",
"output_path",
",",
"'rb'",
")",
".",
"read",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"avm_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"output_path",
")",
")",
"[",
"0",
"]",
"json_data",
"=",
"self",
".",
"generate_debug_json",
"(",
"avm_name",
",",
"file_hash",
")",
"mapfilename",
"=",
"output_path",
".",
"replace",
"(",
"'.avm'",
",",
"'.debug.json'",
")",
"with",
"open",
"(",
"mapfilename",
",",
"'w+'",
")",
"as",
"out_file",
":",
"out_file",
".",
"write",
"(",
"json_data",
")"
] |
this method is used to generate a debug map for NEO debugger
|
[
"this",
"method",
"is",
"used",
"to",
"generate",
"a",
"debug",
"map",
"for",
"NEO",
"debugger"
] |
5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b
|
https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/code/module.py#L363-L375
|
7,222
|
CityOfZion/neo-boa
|
boa/compiler.py
|
Compiler.load_and_save
|
def load_and_save(path, output_path=None, use_nep8=True):
"""
Call `load_and_save` to load a Python file to be compiled to the .avm format and save the result.
By default, the resultant .avm file is saved along side the source file.
:param path: The path of the Python file to compile
:param output_path: Optional path to save the compiled `.avm` file
:return: the instance of the compiler
The following returns the compiler object for inspection
.. code-block:: python
from boa.compiler import Compiler
Compiler.load_and_save('path/to/your/file.py')
"""
compiler = Compiler.load(os.path.abspath(path), use_nep8=use_nep8)
data = compiler.write()
if output_path is None:
fullpath = os.path.realpath(path)
path, filename = os.path.split(fullpath)
newfilename = filename.replace('.py', '.avm')
output_path = '%s/%s' % (path, newfilename)
Compiler.write_file(data, output_path)
compiler.entry_module.export_debug(output_path)
return data
|
python
|
def load_and_save(path, output_path=None, use_nep8=True):
"""
Call `load_and_save` to load a Python file to be compiled to the .avm format and save the result.
By default, the resultant .avm file is saved along side the source file.
:param path: The path of the Python file to compile
:param output_path: Optional path to save the compiled `.avm` file
:return: the instance of the compiler
The following returns the compiler object for inspection
.. code-block:: python
from boa.compiler import Compiler
Compiler.load_and_save('path/to/your/file.py')
"""
compiler = Compiler.load(os.path.abspath(path), use_nep8=use_nep8)
data = compiler.write()
if output_path is None:
fullpath = os.path.realpath(path)
path, filename = os.path.split(fullpath)
newfilename = filename.replace('.py', '.avm')
output_path = '%s/%s' % (path, newfilename)
Compiler.write_file(data, output_path)
compiler.entry_module.export_debug(output_path)
return data
|
[
"def",
"load_and_save",
"(",
"path",
",",
"output_path",
"=",
"None",
",",
"use_nep8",
"=",
"True",
")",
":",
"compiler",
"=",
"Compiler",
".",
"load",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
",",
"use_nep8",
"=",
"use_nep8",
")",
"data",
"=",
"compiler",
".",
"write",
"(",
")",
"if",
"output_path",
"is",
"None",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"fullpath",
")",
"newfilename",
"=",
"filename",
".",
"replace",
"(",
"'.py'",
",",
"'.avm'",
")",
"output_path",
"=",
"'%s/%s'",
"%",
"(",
"path",
",",
"newfilename",
")",
"Compiler",
".",
"write_file",
"(",
"data",
",",
"output_path",
")",
"compiler",
".",
"entry_module",
".",
"export_debug",
"(",
"output_path",
")",
"return",
"data"
] |
Call `load_and_save` to load a Python file to be compiled to the .avm format and save the result.
By default, the resultant .avm file is saved along side the source file.
:param path: The path of the Python file to compile
:param output_path: Optional path to save the compiled `.avm` file
:return: the instance of the compiler
The following returns the compiler object for inspection
.. code-block:: python
from boa.compiler import Compiler
Compiler.load_and_save('path/to/your/file.py')
|
[
"Call",
"load_and_save",
"to",
"load",
"a",
"Python",
"file",
"to",
"be",
"compiled",
"to",
"the",
".",
"avm",
"format",
"and",
"save",
"the",
"result",
".",
"By",
"default",
"the",
"resultant",
".",
"avm",
"file",
"is",
"saved",
"along",
"side",
"the",
"source",
"file",
"."
] |
5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b
|
https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/compiler.py#L79-L108
|
7,223
|
CityOfZion/neo-boa
|
boa/compiler.py
|
Compiler.load
|
def load(path, use_nep8=True):
"""
Call `load` to load a Python file to be compiled but not to write to .avm
:param path: the path of the Python file to compile
:return: The instance of the compiler
The following returns the compiler object for inspection.
.. code-block:: python
from boa.compiler import Compiler
compiler = Compiler.load('path/to/your/file.py')
"""
Compiler.__instance = None
compiler = Compiler.instance()
compiler.nep8 = use_nep8
compiler.entry_module = Module(path)
return compiler
|
python
|
def load(path, use_nep8=True):
"""
Call `load` to load a Python file to be compiled but not to write to .avm
:param path: the path of the Python file to compile
:return: The instance of the compiler
The following returns the compiler object for inspection.
.. code-block:: python
from boa.compiler import Compiler
compiler = Compiler.load('path/to/your/file.py')
"""
Compiler.__instance = None
compiler = Compiler.instance()
compiler.nep8 = use_nep8
compiler.entry_module = Module(path)
return compiler
|
[
"def",
"load",
"(",
"path",
",",
"use_nep8",
"=",
"True",
")",
":",
"Compiler",
".",
"__instance",
"=",
"None",
"compiler",
"=",
"Compiler",
".",
"instance",
"(",
")",
"compiler",
".",
"nep8",
"=",
"use_nep8",
"compiler",
".",
"entry_module",
"=",
"Module",
"(",
"path",
")",
"return",
"compiler"
] |
Call `load` to load a Python file to be compiled but not to write to .avm
:param path: the path of the Python file to compile
:return: The instance of the compiler
The following returns the compiler object for inspection.
.. code-block:: python
from boa.compiler import Compiler
compiler = Compiler.load('path/to/your/file.py')
|
[
"Call",
"load",
"to",
"load",
"a",
"Python",
"file",
"to",
"be",
"compiled",
"but",
"not",
"to",
"write",
"to",
".",
"avm"
] |
5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b
|
https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/compiler.py#L111-L133
|
7,224
|
swimlane/swimlane-python
|
swimlane/core/adapters/helper.py
|
HelperAdapter.add_record_references
|
def add_record_references(self, app_id, record_id, field_id, target_record_ids):
"""Bulk operation to directly add record references without making any additional requests
Warnings:
Does not perform any app, record, or target app/record validation
Args:
app_id (str): Full App ID string
record_id (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
target_record_ids (List(str)): List of full target reference Record ID strings
"""
self._swimlane.request(
'post',
'app/{0}/record/{1}/add-references'.format(app_id, record_id),
json={
'fieldId': field_id,
'targetRecordIds': target_record_ids
}
)
|
python
|
def add_record_references(self, app_id, record_id, field_id, target_record_ids):
"""Bulk operation to directly add record references without making any additional requests
Warnings:
Does not perform any app, record, or target app/record validation
Args:
app_id (str): Full App ID string
record_id (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
target_record_ids (List(str)): List of full target reference Record ID strings
"""
self._swimlane.request(
'post',
'app/{0}/record/{1}/add-references'.format(app_id, record_id),
json={
'fieldId': field_id,
'targetRecordIds': target_record_ids
}
)
|
[
"def",
"add_record_references",
"(",
"self",
",",
"app_id",
",",
"record_id",
",",
"field_id",
",",
"target_record_ids",
")",
":",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'post'",
",",
"'app/{0}/record/{1}/add-references'",
".",
"format",
"(",
"app_id",
",",
"record_id",
")",
",",
"json",
"=",
"{",
"'fieldId'",
":",
"field_id",
",",
"'targetRecordIds'",
":",
"target_record_ids",
"}",
")"
] |
Bulk operation to directly add record references without making any additional requests
Warnings:
Does not perform any app, record, or target app/record validation
Args:
app_id (str): Full App ID string
record_id (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
target_record_ids (List(str)): List of full target reference Record ID strings
|
[
"Bulk",
"operation",
"to",
"directly",
"add",
"record",
"references",
"without",
"making",
"any",
"additional",
"requests"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/helper.py#L11-L31
|
7,225
|
swimlane/swimlane-python
|
swimlane/core/adapters/helper.py
|
HelperAdapter.add_comment
|
def add_comment(self, app_id, record_id, field_id, message):
"""Directly add a comment to a record without retrieving the app or record first
Warnings:
Does not perform any app, record, or field ID validation
Args:
app_id (str): Full App ID string
record_id (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
message (str): New comment message body
"""
self._swimlane.request(
'post',
'app/{0}/record/{1}/{2}/comment'.format(
app_id,
record_id,
field_id
),
json={
'message': message,
'createdDate': pendulum.now().to_rfc3339_string()
}
)
|
python
|
def add_comment(self, app_id, record_id, field_id, message):
"""Directly add a comment to a record without retrieving the app or record first
Warnings:
Does not perform any app, record, or field ID validation
Args:
app_id (str): Full App ID string
record_id (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
message (str): New comment message body
"""
self._swimlane.request(
'post',
'app/{0}/record/{1}/{2}/comment'.format(
app_id,
record_id,
field_id
),
json={
'message': message,
'createdDate': pendulum.now().to_rfc3339_string()
}
)
|
[
"def",
"add_comment",
"(",
"self",
",",
"app_id",
",",
"record_id",
",",
"field_id",
",",
"message",
")",
":",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'post'",
",",
"'app/{0}/record/{1}/{2}/comment'",
".",
"format",
"(",
"app_id",
",",
"record_id",
",",
"field_id",
")",
",",
"json",
"=",
"{",
"'message'",
":",
"message",
",",
"'createdDate'",
":",
"pendulum",
".",
"now",
"(",
")",
".",
"to_rfc3339_string",
"(",
")",
"}",
")"
] |
Directly add a comment to a record without retrieving the app or record first
Warnings:
Does not perform any app, record, or field ID validation
Args:
app_id (str): Full App ID string
record_id (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
message (str): New comment message body
|
[
"Directly",
"add",
"a",
"comment",
"to",
"a",
"record",
"without",
"retrieving",
"the",
"app",
"or",
"record",
"first"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/helper.py#L33-L57
|
7,226
|
swimlane/swimlane-python
|
swimlane/core/fields/reference.py
|
ReferenceCursor._evaluate
|
def _evaluate(self):
"""Scan for orphaned records and retrieve any records that have not already been grabbed"""
retrieved_records = SortedDict()
for record_id, record in six.iteritems(self._elements):
if record is self._field._unset:
# Record has not yet been retrieved, get it
try:
record = self.target_app.records.get(id=record_id)
except SwimlaneHTTP400Error:
# Record appears to be orphaned, don't include in set of elements
logger.debug("Received 400 response retrieving record '{}', ignoring assumed orphaned record")
continue
retrieved_records[record_id] = record
self._elements = retrieved_records
return self._elements.values()
|
python
|
def _evaluate(self):
"""Scan for orphaned records and retrieve any records that have not already been grabbed"""
retrieved_records = SortedDict()
for record_id, record in six.iteritems(self._elements):
if record is self._field._unset:
# Record has not yet been retrieved, get it
try:
record = self.target_app.records.get(id=record_id)
except SwimlaneHTTP400Error:
# Record appears to be orphaned, don't include in set of elements
logger.debug("Received 400 response retrieving record '{}', ignoring assumed orphaned record")
continue
retrieved_records[record_id] = record
self._elements = retrieved_records
return self._elements.values()
|
[
"def",
"_evaluate",
"(",
"self",
")",
":",
"retrieved_records",
"=",
"SortedDict",
"(",
")",
"for",
"record_id",
",",
"record",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_elements",
")",
":",
"if",
"record",
"is",
"self",
".",
"_field",
".",
"_unset",
":",
"# Record has not yet been retrieved, get it",
"try",
":",
"record",
"=",
"self",
".",
"target_app",
".",
"records",
".",
"get",
"(",
"id",
"=",
"record_id",
")",
"except",
"SwimlaneHTTP400Error",
":",
"# Record appears to be orphaned, don't include in set of elements",
"logger",
".",
"debug",
"(",
"\"Received 400 response retrieving record '{}', ignoring assumed orphaned record\"",
")",
"continue",
"retrieved_records",
"[",
"record_id",
"]",
"=",
"record",
"self",
".",
"_elements",
"=",
"retrieved_records",
"return",
"self",
".",
"_elements",
".",
"values",
"(",
")"
] |
Scan for orphaned records and retrieve any records that have not already been grabbed
|
[
"Scan",
"for",
"orphaned",
"records",
"and",
"retrieve",
"any",
"records",
"that",
"have",
"not",
"already",
"been",
"grabbed"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L26-L45
|
7,227
|
swimlane/swimlane-python
|
swimlane/core/fields/reference.py
|
ReferenceCursor.add
|
def add(self, record):
"""Add a reference to the provided record"""
self._field.validate_value(record)
self._elements[record.id] = record
self._sync_field()
|
python
|
def add(self, record):
"""Add a reference to the provided record"""
self._field.validate_value(record)
self._elements[record.id] = record
self._sync_field()
|
[
"def",
"add",
"(",
"self",
",",
"record",
")",
":",
"self",
".",
"_field",
".",
"validate_value",
"(",
"record",
")",
"self",
".",
"_elements",
"[",
"record",
".",
"id",
"]",
"=",
"record",
"self",
".",
"_sync_field",
"(",
")"
] |
Add a reference to the provided record
|
[
"Add",
"a",
"reference",
"to",
"the",
"provided",
"record"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L47-L51
|
7,228
|
swimlane/swimlane-python
|
swimlane/core/fields/reference.py
|
ReferenceCursor.remove
|
def remove(self, record):
"""Remove a reference to the provided record"""
self._field.validate_value(record)
del self._elements[record.id]
self._sync_field()
|
python
|
def remove(self, record):
"""Remove a reference to the provided record"""
self._field.validate_value(record)
del self._elements[record.id]
self._sync_field()
|
[
"def",
"remove",
"(",
"self",
",",
"record",
")",
":",
"self",
".",
"_field",
".",
"validate_value",
"(",
"record",
")",
"del",
"self",
".",
"_elements",
"[",
"record",
".",
"id",
"]",
"self",
".",
"_sync_field",
"(",
")"
] |
Remove a reference to the provided record
|
[
"Remove",
"a",
"reference",
"to",
"the",
"provided",
"record"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L53-L57
|
7,229
|
swimlane/swimlane-python
|
swimlane/core/fields/reference.py
|
ReferenceField.target_app
|
def target_app(self):
"""Defer target app retrieval until requested"""
if self.__target_app is None:
self.__target_app = self._swimlane.apps.get(id=self.__target_app_id)
return self.__target_app
|
python
|
def target_app(self):
"""Defer target app retrieval until requested"""
if self.__target_app is None:
self.__target_app = self._swimlane.apps.get(id=self.__target_app_id)
return self.__target_app
|
[
"def",
"target_app",
"(",
"self",
")",
":",
"if",
"self",
".",
"__target_app",
"is",
"None",
":",
"self",
".",
"__target_app",
"=",
"self",
".",
"_swimlane",
".",
"apps",
".",
"get",
"(",
"id",
"=",
"self",
".",
"__target_app_id",
")",
"return",
"self",
".",
"__target_app"
] |
Defer target app retrieval until requested
|
[
"Defer",
"target",
"app",
"retrieval",
"until",
"requested"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L73-L78
|
7,230
|
swimlane/swimlane-python
|
swimlane/core/fields/reference.py
|
ReferenceField.validate_value
|
def validate_value(self, value):
"""Validate provided record is a part of the appropriate target app for the field"""
if value not in (None, self._unset):
super(ReferenceField, self).validate_value(value)
if value.app != self.target_app:
raise ValidationError(
self.record,
"Reference field '{}' has target app '{}', cannot reference record '{}' from app '{}'".format(
self.name,
self.target_app,
value,
value.app
)
)
|
python
|
def validate_value(self, value):
"""Validate provided record is a part of the appropriate target app for the field"""
if value not in (None, self._unset):
super(ReferenceField, self).validate_value(value)
if value.app != self.target_app:
raise ValidationError(
self.record,
"Reference field '{}' has target app '{}', cannot reference record '{}' from app '{}'".format(
self.name,
self.target_app,
value,
value.app
)
)
|
[
"def",
"validate_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"(",
"None",
",",
"self",
".",
"_unset",
")",
":",
"super",
"(",
"ReferenceField",
",",
"self",
")",
".",
"validate_value",
"(",
"value",
")",
"if",
"value",
".",
"app",
"!=",
"self",
".",
"target_app",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"\"Reference field '{}' has target app '{}', cannot reference record '{}' from app '{}'\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"target_app",
",",
"value",
",",
"value",
".",
"app",
")",
")"
] |
Validate provided record is a part of the appropriate target app for the field
|
[
"Validate",
"provided",
"record",
"is",
"a",
"part",
"of",
"the",
"appropriate",
"target",
"app",
"for",
"the",
"field"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L80-L95
|
7,231
|
swimlane/swimlane-python
|
swimlane/core/fields/reference.py
|
ReferenceField.set_swimlane
|
def set_swimlane(self, value):
"""Store record ids in separate location for later use, but ignore initial value"""
# Move single record into list to be handled the same by cursor class
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]
# Values come in as a list of record ids or None
value = value or []
records = SortedDict()
for record_id in value:
records[record_id] = self._unset
return super(ReferenceField, self).set_swimlane(records)
|
python
|
def set_swimlane(self, value):
"""Store record ids in separate location for later use, but ignore initial value"""
# Move single record into list to be handled the same by cursor class
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]
# Values come in as a list of record ids or None
value = value or []
records = SortedDict()
for record_id in value:
records[record_id] = self._unset
return super(ReferenceField, self).set_swimlane(records)
|
[
"def",
"set_swimlane",
"(",
"self",
",",
"value",
")",
":",
"# Move single record into list to be handled the same by cursor class",
"if",
"not",
"self",
".",
"multiselect",
":",
"if",
"value",
"and",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"value",
"]",
"# Values come in as a list of record ids or None",
"value",
"=",
"value",
"or",
"[",
"]",
"records",
"=",
"SortedDict",
"(",
")",
"for",
"record_id",
"in",
"value",
":",
"records",
"[",
"record_id",
"]",
"=",
"self",
".",
"_unset",
"return",
"super",
"(",
"ReferenceField",
",",
"self",
")",
".",
"set_swimlane",
"(",
"records",
")"
] |
Store record ids in separate location for later use, but ignore initial value
|
[
"Store",
"record",
"ids",
"in",
"separate",
"location",
"for",
"later",
"use",
"but",
"ignore",
"initial",
"value"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L101-L117
|
7,232
|
swimlane/swimlane-python
|
swimlane/core/fields/reference.py
|
ReferenceField.set_python
|
def set_python(self, value):
"""Expect list of record instances, convert to a SortedDict for internal representation"""
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]
value = value or []
records = SortedDict()
for record in value:
self.validate_value(record)
records[record.id] = record
return_value = self._set(records)
self.record._raw['values'][self.id] = self.get_swimlane()
return return_value
|
python
|
def set_python(self, value):
"""Expect list of record instances, convert to a SortedDict for internal representation"""
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]
value = value or []
records = SortedDict()
for record in value:
self.validate_value(record)
records[record.id] = record
return_value = self._set(records)
self.record._raw['values'][self.id] = self.get_swimlane()
return return_value
|
[
"def",
"set_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"multiselect",
":",
"if",
"value",
"and",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"value",
"]",
"value",
"=",
"value",
"or",
"[",
"]",
"records",
"=",
"SortedDict",
"(",
")",
"for",
"record",
"in",
"value",
":",
"self",
".",
"validate_value",
"(",
"record",
")",
"records",
"[",
"record",
".",
"id",
"]",
"=",
"record",
"return_value",
"=",
"self",
".",
"_set",
"(",
"records",
")",
"self",
".",
"record",
".",
"_raw",
"[",
"'values'",
"]",
"[",
"self",
".",
"id",
"]",
"=",
"self",
".",
"get_swimlane",
"(",
")",
"return",
"return_value"
] |
Expect list of record instances, convert to a SortedDict for internal representation
|
[
"Expect",
"list",
"of",
"record",
"instances",
"convert",
"to",
"a",
"SortedDict",
"for",
"internal",
"representation"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L119-L136
|
7,233
|
swimlane/swimlane-python
|
swimlane/core/fields/reference.py
|
ReferenceField.get_swimlane
|
def get_swimlane(self):
"""Return list of record ids"""
value = super(ReferenceField, self).get_swimlane()
if value:
ids = list(value.keys())
if self.multiselect:
return ids
return ids[0]
return None
|
python
|
def get_swimlane(self):
"""Return list of record ids"""
value = super(ReferenceField, self).get_swimlane()
if value:
ids = list(value.keys())
if self.multiselect:
return ids
return ids[0]
return None
|
[
"def",
"get_swimlane",
"(",
"self",
")",
":",
"value",
"=",
"super",
"(",
"ReferenceField",
",",
"self",
")",
".",
"get_swimlane",
"(",
")",
"if",
"value",
":",
"ids",
"=",
"list",
"(",
"value",
".",
"keys",
"(",
")",
")",
"if",
"self",
".",
"multiselect",
":",
"return",
"ids",
"return",
"ids",
"[",
"0",
"]",
"return",
"None"
] |
Return list of record ids
|
[
"Return",
"list",
"of",
"record",
"ids"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L138-L149
|
7,234
|
swimlane/swimlane-python
|
swimlane/core/fields/reference.py
|
ReferenceField.get_python
|
def get_python(self):
"""Return cursor if multi-select, direct value if single-select"""
cursor = super(ReferenceField, self).get_python()
if self.multiselect:
return cursor
else:
try:
return cursor[0]
except IndexError:
return None
|
python
|
def get_python(self):
"""Return cursor if multi-select, direct value if single-select"""
cursor = super(ReferenceField, self).get_python()
if self.multiselect:
return cursor
else:
try:
return cursor[0]
except IndexError:
return None
|
[
"def",
"get_python",
"(",
"self",
")",
":",
"cursor",
"=",
"super",
"(",
"ReferenceField",
",",
"self",
")",
".",
"get_python",
"(",
")",
"if",
"self",
".",
"multiselect",
":",
"return",
"cursor",
"else",
":",
"try",
":",
"return",
"cursor",
"[",
"0",
"]",
"except",
"IndexError",
":",
"return",
"None"
] |
Return cursor if multi-select, direct value if single-select
|
[
"Return",
"cursor",
"if",
"multi",
"-",
"select",
"direct",
"value",
"if",
"single",
"-",
"select"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L151-L162
|
7,235
|
swimlane/swimlane-python
|
swimlane/core/adapters/app.py
|
AppAdapter.get
|
def get(self, key, value):
"""Get single app by one of id or name
Supports resource cache
Keyword Args:
id (str): Full app id
name (str): App name
Returns:
App: Corresponding App resource instance
Raises:
TypeError: No or multiple keyword arguments provided
ValueError: No matching app found on server
"""
if key == 'id':
# Server returns 204 instead of 404 for a non-existent app id
response = self._swimlane.request('get', 'app/{}'.format(value))
if response.status_code == 204:
raise ValueError('No app with id "{}"'.format(value))
return App(
self._swimlane,
response.json()
)
else:
# Workaround for lack of support for get by name
# Holdover from previous driver support, to be fixed as part of 3.x
for app in self.list():
if value and value == app.name:
return app
# No matching app found
raise ValueError('No app with name "{}"'.format(value))
|
python
|
def get(self, key, value):
"""Get single app by one of id or name
Supports resource cache
Keyword Args:
id (str): Full app id
name (str): App name
Returns:
App: Corresponding App resource instance
Raises:
TypeError: No or multiple keyword arguments provided
ValueError: No matching app found on server
"""
if key == 'id':
# Server returns 204 instead of 404 for a non-existent app id
response = self._swimlane.request('get', 'app/{}'.format(value))
if response.status_code == 204:
raise ValueError('No app with id "{}"'.format(value))
return App(
self._swimlane,
response.json()
)
else:
# Workaround for lack of support for get by name
# Holdover from previous driver support, to be fixed as part of 3.x
for app in self.list():
if value and value == app.name:
return app
# No matching app found
raise ValueError('No app with name "{}"'.format(value))
|
[
"def",
"get",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"'id'",
":",
"# Server returns 204 instead of 404 for a non-existent app id",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"'app/{}'",
".",
"format",
"(",
"value",
")",
")",
"if",
"response",
".",
"status_code",
"==",
"204",
":",
"raise",
"ValueError",
"(",
"'No app with id \"{}\"'",
".",
"format",
"(",
"value",
")",
")",
"return",
"App",
"(",
"self",
".",
"_swimlane",
",",
"response",
".",
"json",
"(",
")",
")",
"else",
":",
"# Workaround for lack of support for get by name",
"# Holdover from previous driver support, to be fixed as part of 3.x",
"for",
"app",
"in",
"self",
".",
"list",
"(",
")",
":",
"if",
"value",
"and",
"value",
"==",
"app",
".",
"name",
":",
"return",
"app",
"# No matching app found",
"raise",
"ValueError",
"(",
"'No app with name \"{}\"'",
".",
"format",
"(",
"value",
")",
")"
] |
Get single app by one of id or name
Supports resource cache
Keyword Args:
id (str): Full app id
name (str): App name
Returns:
App: Corresponding App resource instance
Raises:
TypeError: No or multiple keyword arguments provided
ValueError: No matching app found on server
|
[
"Get",
"single",
"app",
"by",
"one",
"of",
"id",
"or",
"name"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/app.py#L12-L46
|
7,236
|
swimlane/swimlane-python
|
swimlane/core/adapters/app.py
|
AppAdapter.list
|
def list(self):
"""Retrieve list of all apps
Returns:
:class:`list` of :class:`~swimlane.core.resources.app.App`: List of all retrieved apps
"""
response = self._swimlane.request('get', 'app')
return [App(self._swimlane, item) for item in response.json()]
|
python
|
def list(self):
"""Retrieve list of all apps
Returns:
:class:`list` of :class:`~swimlane.core.resources.app.App`: List of all retrieved apps
"""
response = self._swimlane.request('get', 'app')
return [App(self._swimlane, item) for item in response.json()]
|
[
"def",
"list",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"'app'",
")",
"return",
"[",
"App",
"(",
"self",
".",
"_swimlane",
",",
"item",
")",
"for",
"item",
"in",
"response",
".",
"json",
"(",
")",
"]"
] |
Retrieve list of all apps
Returns:
:class:`list` of :class:`~swimlane.core.resources.app.App`: List of all retrieved apps
|
[
"Retrieve",
"list",
"of",
"all",
"apps"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/app.py#L48-L55
|
7,237
|
swimlane/swimlane-python
|
swimlane/core/resources/usergroup.py
|
Group.users
|
def users(self):
"""Returns a GroupUsersCursor with list of User instances for this Group
.. versionadded:: 2.16.2
"""
if self.__users is None:
self.__users = GroupUsersCursor(swimlane=self._swimlane, user_ids=self.__user_ids)
return self.__users
|
python
|
def users(self):
"""Returns a GroupUsersCursor with list of User instances for this Group
.. versionadded:: 2.16.2
"""
if self.__users is None:
self.__users = GroupUsersCursor(swimlane=self._swimlane, user_ids=self.__user_ids)
return self.__users
|
[
"def",
"users",
"(",
"self",
")",
":",
"if",
"self",
".",
"__users",
"is",
"None",
":",
"self",
".",
"__users",
"=",
"GroupUsersCursor",
"(",
"swimlane",
"=",
"self",
".",
"_swimlane",
",",
"user_ids",
"=",
"self",
".",
"__user_ids",
")",
"return",
"self",
".",
"__users"
] |
Returns a GroupUsersCursor with list of User instances for this Group
.. versionadded:: 2.16.2
|
[
"Returns",
"a",
"GroupUsersCursor",
"with",
"list",
"of",
"User",
"instances",
"for",
"this",
"Group"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/resources/usergroup.py#L104-L111
|
7,238
|
swimlane/swimlane-python
|
swimlane/core/resources/usergroup.py
|
GroupUsersCursor._evaluate
|
def _evaluate(self):
"""Lazily retrieve and build User instances from returned data"""
if self._elements:
for element in self._elements:
yield element
else:
for user_id in self.__user_ids:
element = self._swimlane.users.get(id=user_id)
self._elements.append(element)
yield element
|
python
|
def _evaluate(self):
"""Lazily retrieve and build User instances from returned data"""
if self._elements:
for element in self._elements:
yield element
else:
for user_id in self.__user_ids:
element = self._swimlane.users.get(id=user_id)
self._elements.append(element)
yield element
|
[
"def",
"_evaluate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_elements",
":",
"for",
"element",
"in",
"self",
".",
"_elements",
":",
"yield",
"element",
"else",
":",
"for",
"user_id",
"in",
"self",
".",
"__user_ids",
":",
"element",
"=",
"self",
".",
"_swimlane",
".",
"users",
".",
"get",
"(",
"id",
"=",
"user_id",
")",
"self",
".",
"_elements",
".",
"append",
"(",
"element",
")",
"yield",
"element"
] |
Lazily retrieve and build User instances from returned data
|
[
"Lazily",
"retrieve",
"and",
"build",
"User",
"instances",
"from",
"returned",
"data"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/resources/usergroup.py#L154-L163
|
7,239
|
swimlane/swimlane-python
|
swimlane/core/client.py
|
_user_raw_from_login_content
|
def _user_raw_from_login_content(login_content):
"""Returns a User instance with appropriate raw data parsed from login response content"""
matching_keys = [
'displayName',
'lastLogin',
'active',
'name',
'isMe',
'lastPasswordChangedDate',
'passwordResetRequired',
'groups',
'roles',
'email',
'isAdmin',
'createdDate',
'modifiedDate',
'createdByUser',
'modifiedByUser',
'userName',
'id',
'disabled'
]
raw_data = {
'$type': User._type,
}
for key in matching_keys:
if key in login_content:
raw_data[key] = login_content[key]
return raw_data
|
python
|
def _user_raw_from_login_content(login_content):
"""Returns a User instance with appropriate raw data parsed from login response content"""
matching_keys = [
'displayName',
'lastLogin',
'active',
'name',
'isMe',
'lastPasswordChangedDate',
'passwordResetRequired',
'groups',
'roles',
'email',
'isAdmin',
'createdDate',
'modifiedDate',
'createdByUser',
'modifiedByUser',
'userName',
'id',
'disabled'
]
raw_data = {
'$type': User._type,
}
for key in matching_keys:
if key in login_content:
raw_data[key] = login_content[key]
return raw_data
|
[
"def",
"_user_raw_from_login_content",
"(",
"login_content",
")",
":",
"matching_keys",
"=",
"[",
"'displayName'",
",",
"'lastLogin'",
",",
"'active'",
",",
"'name'",
",",
"'isMe'",
",",
"'lastPasswordChangedDate'",
",",
"'passwordResetRequired'",
",",
"'groups'",
",",
"'roles'",
",",
"'email'",
",",
"'isAdmin'",
",",
"'createdDate'",
",",
"'modifiedDate'",
",",
"'createdByUser'",
",",
"'modifiedByUser'",
",",
"'userName'",
",",
"'id'",
",",
"'disabled'",
"]",
"raw_data",
"=",
"{",
"'$type'",
":",
"User",
".",
"_type",
",",
"}",
"for",
"key",
"in",
"matching_keys",
":",
"if",
"key",
"in",
"login_content",
":",
"raw_data",
"[",
"key",
"]",
"=",
"login_content",
"[",
"key",
"]",
"return",
"raw_data"
] |
Returns a User instance with appropriate raw data parsed from login response content
|
[
"Returns",
"a",
"User",
"instance",
"with",
"appropriate",
"raw",
"data",
"parsed",
"from",
"login",
"response",
"content"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/client.py#L384-L415
|
7,240
|
swimlane/swimlane-python
|
swimlane/core/client.py
|
Swimlane.__verify_server_version
|
def __verify_server_version(self):
"""Verify connected to supported server product version
Notes:
Logs warning if connecting to a newer minor server version
Raises:
swimlane.exceptions.InvalidServerVersion: If server major version is higher than package major version
"""
if compare_versions('.'.join([_lib_major_version, _lib_minor_version]), self.product_version) > 0:
logger.warning('Client version {} connecting to server with newer minor release {}.'.format(
_lib_full_version,
self.product_version
))
if compare_versions(_lib_major_version, self.product_version) != 0:
raise InvalidSwimlaneProductVersion(
self,
'{}.0'.format(_lib_major_version),
'{}.0'.format(str(int(_lib_major_version) + 1))
)
|
python
|
def __verify_server_version(self):
"""Verify connected to supported server product version
Notes:
Logs warning if connecting to a newer minor server version
Raises:
swimlane.exceptions.InvalidServerVersion: If server major version is higher than package major version
"""
if compare_versions('.'.join([_lib_major_version, _lib_minor_version]), self.product_version) > 0:
logger.warning('Client version {} connecting to server with newer minor release {}.'.format(
_lib_full_version,
self.product_version
))
if compare_versions(_lib_major_version, self.product_version) != 0:
raise InvalidSwimlaneProductVersion(
self,
'{}.0'.format(_lib_major_version),
'{}.0'.format(str(int(_lib_major_version) + 1))
)
|
[
"def",
"__verify_server_version",
"(",
"self",
")",
":",
"if",
"compare_versions",
"(",
"'.'",
".",
"join",
"(",
"[",
"_lib_major_version",
",",
"_lib_minor_version",
"]",
")",
",",
"self",
".",
"product_version",
")",
">",
"0",
":",
"logger",
".",
"warning",
"(",
"'Client version {} connecting to server with newer minor release {}.'",
".",
"format",
"(",
"_lib_full_version",
",",
"self",
".",
"product_version",
")",
")",
"if",
"compare_versions",
"(",
"_lib_major_version",
",",
"self",
".",
"product_version",
")",
"!=",
"0",
":",
"raise",
"InvalidSwimlaneProductVersion",
"(",
"self",
",",
"'{}.0'",
".",
"format",
"(",
"_lib_major_version",
")",
",",
"'{}.0'",
".",
"format",
"(",
"str",
"(",
"int",
"(",
"_lib_major_version",
")",
"+",
"1",
")",
")",
")"
] |
Verify connected to supported server product version
Notes:
Logs warning if connecting to a newer minor server version
Raises:
swimlane.exceptions.InvalidServerVersion: If server major version is higher than package major version
|
[
"Verify",
"connected",
"to",
"supported",
"server",
"product",
"version"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/client.py#L141-L161
|
7,241
|
swimlane/swimlane-python
|
swimlane/core/client.py
|
Swimlane.settings
|
def settings(self):
"""Retrieve and cache settings from server"""
if not self.__settings:
self.__settings = self.request('get', 'settings').json()
return self.__settings
|
python
|
def settings(self):
"""Retrieve and cache settings from server"""
if not self.__settings:
self.__settings = self.request('get', 'settings').json()
return self.__settings
|
[
"def",
"settings",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__settings",
":",
"self",
".",
"__settings",
"=",
"self",
".",
"request",
"(",
"'get'",
",",
"'settings'",
")",
".",
"json",
"(",
")",
"return",
"self",
".",
"__settings"
] |
Retrieve and cache settings from server
|
[
"Retrieve",
"and",
"cache",
"settings",
"from",
"server"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/client.py#L229-L233
|
7,242
|
swimlane/swimlane-python
|
swimlane/core/client.py
|
Swimlane.product_version
|
def product_version(self):
"""Swimlane product version"""
version_separator = '+'
if version_separator in self.version:
# Post product/build version separation
return self.version.split(version_separator)[0]
# Pre product/build version separation
return self.version.split('-')[0]
|
python
|
def product_version(self):
"""Swimlane product version"""
version_separator = '+'
if version_separator in self.version:
# Post product/build version separation
return self.version.split(version_separator)[0]
# Pre product/build version separation
return self.version.split('-')[0]
|
[
"def",
"product_version",
"(",
"self",
")",
":",
"version_separator",
"=",
"'+'",
"if",
"version_separator",
"in",
"self",
".",
"version",
":",
"# Post product/build version separation",
"return",
"self",
".",
"version",
".",
"split",
"(",
"version_separator",
")",
"[",
"0",
"]",
"# Pre product/build version separation",
"return",
"self",
".",
"version",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]"
] |
Swimlane product version
|
[
"Swimlane",
"product",
"version"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/client.py#L241-L248
|
7,243
|
swimlane/swimlane-python
|
swimlane/core/client.py
|
Swimlane.build_number
|
def build_number(self):
"""Swimlane build number"""
version_separator = '+'
if version_separator in self.version:
# Post product/build version separation
return self.version.split(version_separator)[2]
# Pre product/build version separation
return self.version.split('-')[1]
|
python
|
def build_number(self):
"""Swimlane build number"""
version_separator = '+'
if version_separator in self.version:
# Post product/build version separation
return self.version.split(version_separator)[2]
# Pre product/build version separation
return self.version.split('-')[1]
|
[
"def",
"build_number",
"(",
"self",
")",
":",
"version_separator",
"=",
"'+'",
"if",
"version_separator",
"in",
"self",
".",
"version",
":",
"# Post product/build version separation",
"return",
"self",
".",
"version",
".",
"split",
"(",
"version_separator",
")",
"[",
"2",
"]",
"# Pre product/build version separation",
"return",
"self",
".",
"version",
".",
"split",
"(",
"'-'",
")",
"[",
"1",
"]"
] |
Swimlane build number
|
[
"Swimlane",
"build",
"number"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/client.py#L264-L271
|
7,244
|
swimlane/swimlane-python
|
swimlane/core/client.py
|
SwimlaneJwtAuth.authenticate
|
def authenticate(self):
"""Send login request and update User instance, login headers, and token expiration"""
# Temporarily remove auth from Swimlane session for auth request to avoid recursive loop during login request
self._swimlane._session.auth = None
resp = self._swimlane.request(
'post',
'user/login',
json={
'userName': self._username,
'password': self._password
},
)
self._swimlane._session.auth = self
# Get JWT from response content
json_content = resp.json()
token = json_content.pop('token', None)
# Grab token expiration
token_data = jwt.decode(token, verify=False)
token_expiration = pendulum.from_timestamp(token_data['exp'])
headers = {
'Authorization': 'Bearer {}'.format(token)
}
# Create User instance for authenticating user from login response data
user = User(self._swimlane, _user_raw_from_login_content(json_content))
self._login_headers = headers
self.user = user
self._token_expiration = token_expiration
|
python
|
def authenticate(self):
"""Send login request and update User instance, login headers, and token expiration"""
# Temporarily remove auth from Swimlane session for auth request to avoid recursive loop during login request
self._swimlane._session.auth = None
resp = self._swimlane.request(
'post',
'user/login',
json={
'userName': self._username,
'password': self._password
},
)
self._swimlane._session.auth = self
# Get JWT from response content
json_content = resp.json()
token = json_content.pop('token', None)
# Grab token expiration
token_data = jwt.decode(token, verify=False)
token_expiration = pendulum.from_timestamp(token_data['exp'])
headers = {
'Authorization': 'Bearer {}'.format(token)
}
# Create User instance for authenticating user from login response data
user = User(self._swimlane, _user_raw_from_login_content(json_content))
self._login_headers = headers
self.user = user
self._token_expiration = token_expiration
|
[
"def",
"authenticate",
"(",
"self",
")",
":",
"# Temporarily remove auth from Swimlane session for auth request to avoid recursive loop during login request",
"self",
".",
"_swimlane",
".",
"_session",
".",
"auth",
"=",
"None",
"resp",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'post'",
",",
"'user/login'",
",",
"json",
"=",
"{",
"'userName'",
":",
"self",
".",
"_username",
",",
"'password'",
":",
"self",
".",
"_password",
"}",
",",
")",
"self",
".",
"_swimlane",
".",
"_session",
".",
"auth",
"=",
"self",
"# Get JWT from response content",
"json_content",
"=",
"resp",
".",
"json",
"(",
")",
"token",
"=",
"json_content",
".",
"pop",
"(",
"'token'",
",",
"None",
")",
"# Grab token expiration",
"token_data",
"=",
"jwt",
".",
"decode",
"(",
"token",
",",
"verify",
"=",
"False",
")",
"token_expiration",
"=",
"pendulum",
".",
"from_timestamp",
"(",
"token_data",
"[",
"'exp'",
"]",
")",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer {}'",
".",
"format",
"(",
"token",
")",
"}",
"# Create User instance for authenticating user from login response data",
"user",
"=",
"User",
"(",
"self",
".",
"_swimlane",
",",
"_user_raw_from_login_content",
"(",
"json_content",
")",
")",
"self",
".",
"_login_headers",
"=",
"headers",
"self",
".",
"user",
"=",
"user",
"self",
".",
"_token_expiration",
"=",
"token_expiration"
] |
Send login request and update User instance, login headers, and token expiration
|
[
"Send",
"login",
"request",
"and",
"update",
"User",
"instance",
"login",
"headers",
"and",
"token",
"expiration"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/client.py#L349-L381
|
7,245
|
swimlane/swimlane-python
|
swimlane/core/cursor.py
|
PaginatedCursor._evaluate
|
def _evaluate(self):
"""Lazily retrieve and paginate report results and build Record instances from returned data"""
if self._elements:
for element in self._elements:
yield element
else:
for page in itertools.count():
raw_elements = self._retrieve_raw_elements(page)
for raw_element in raw_elements:
element = self._parse_raw_element(raw_element)
self._elements.append(element)
yield element
if self.__limit and len(self._elements) >= self.__limit:
break
if any([
len(raw_elements) < self.page_size,
(self.__limit and len(self._elements) >= self.__limit)
]):
break
|
python
|
def _evaluate(self):
"""Lazily retrieve and paginate report results and build Record instances from returned data"""
if self._elements:
for element in self._elements:
yield element
else:
for page in itertools.count():
raw_elements = self._retrieve_raw_elements(page)
for raw_element in raw_elements:
element = self._parse_raw_element(raw_element)
self._elements.append(element)
yield element
if self.__limit and len(self._elements) >= self.__limit:
break
if any([
len(raw_elements) < self.page_size,
(self.__limit and len(self._elements) >= self.__limit)
]):
break
|
[
"def",
"_evaluate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_elements",
":",
"for",
"element",
"in",
"self",
".",
"_elements",
":",
"yield",
"element",
"else",
":",
"for",
"page",
"in",
"itertools",
".",
"count",
"(",
")",
":",
"raw_elements",
"=",
"self",
".",
"_retrieve_raw_elements",
"(",
"page",
")",
"for",
"raw_element",
"in",
"raw_elements",
":",
"element",
"=",
"self",
".",
"_parse_raw_element",
"(",
"raw_element",
")",
"self",
".",
"_elements",
".",
"append",
"(",
"element",
")",
"yield",
"element",
"if",
"self",
".",
"__limit",
"and",
"len",
"(",
"self",
".",
"_elements",
")",
">=",
"self",
".",
"__limit",
":",
"break",
"if",
"any",
"(",
"[",
"len",
"(",
"raw_elements",
")",
"<",
"self",
".",
"page_size",
",",
"(",
"self",
".",
"__limit",
"and",
"len",
"(",
"self",
".",
"_elements",
")",
">=",
"self",
".",
"__limit",
")",
"]",
")",
":",
"break"
] |
Lazily retrieve and paginate report results and build Record instances from returned data
|
[
"Lazily",
"retrieve",
"and",
"paginate",
"report",
"results",
"and",
"build",
"Record",
"instances",
"from",
"returned",
"data"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/cursor.py#L44-L64
|
7,246
|
swimlane/swimlane-python
|
swimlane/core/fields/usergroup.py
|
UserGroupField._validate_user
|
def _validate_user(self, user):
"""Validate a User instance against allowed user IDs or membership in a group"""
# All users allowed
if self._show_all_users:
return
# User specifically allowed
if user.id in self._allowed_user_ids:
return
# User allowed by group membership
user_member_group_ids = set([g['id'] for g in user._raw['groups']])
if user_member_group_ids & self._allowed_member_ids:
return
raise ValidationError(
self.record,
'User `{}` is not a valid selection for field `{}`'.format(
user,
self.name
)
)
|
python
|
def _validate_user(self, user):
"""Validate a User instance against allowed user IDs or membership in a group"""
# All users allowed
if self._show_all_users:
return
# User specifically allowed
if user.id in self._allowed_user_ids:
return
# User allowed by group membership
user_member_group_ids = set([g['id'] for g in user._raw['groups']])
if user_member_group_ids & self._allowed_member_ids:
return
raise ValidationError(
self.record,
'User `{}` is not a valid selection for field `{}`'.format(
user,
self.name
)
)
|
[
"def",
"_validate_user",
"(",
"self",
",",
"user",
")",
":",
"# All users allowed",
"if",
"self",
".",
"_show_all_users",
":",
"return",
"# User specifically allowed",
"if",
"user",
".",
"id",
"in",
"self",
".",
"_allowed_user_ids",
":",
"return",
"# User allowed by group membership",
"user_member_group_ids",
"=",
"set",
"(",
"[",
"g",
"[",
"'id'",
"]",
"for",
"g",
"in",
"user",
".",
"_raw",
"[",
"'groups'",
"]",
"]",
")",
"if",
"user_member_group_ids",
"&",
"self",
".",
"_allowed_member_ids",
":",
"return",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"'User `{}` is not a valid selection for field `{}`'",
".",
"format",
"(",
"user",
",",
"self",
".",
"name",
")",
")"
] |
Validate a User instance against allowed user IDs or membership in a group
|
[
"Validate",
"a",
"User",
"instance",
"against",
"allowed",
"user",
"IDs",
"or",
"membership",
"in",
"a",
"group"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/usergroup.py#L56-L77
|
7,247
|
swimlane/swimlane-python
|
swimlane/core/fields/usergroup.py
|
UserGroupField._validate_group
|
def _validate_group(self, group):
"""Validate a Group instance against allowed group IDs or subgroup of a parent group"""
# All groups allowed
if self._show_all_groups:
return
# Group specifically allowed
if group.id in self._allowed_group_ids:
return
# Group allowed by subgroup membership
for parent_group_id in self._allowed_subgroup_ids:
# Get each group, and check subgroup ids
parent_group = self._swimlane.groups.get(id=parent_group_id)
parent_group_child_ids = set([g['id'] for g in parent_group._raw['groups']])
if group.id in parent_group_child_ids:
return
raise ValidationError(
self.record,
'Group `{}` is not a valid selection for field `{}`'.format(
group,
self.name
)
)
|
python
|
def _validate_group(self, group):
"""Validate a Group instance against allowed group IDs or subgroup of a parent group"""
# All groups allowed
if self._show_all_groups:
return
# Group specifically allowed
if group.id in self._allowed_group_ids:
return
# Group allowed by subgroup membership
for parent_group_id in self._allowed_subgroup_ids:
# Get each group, and check subgroup ids
parent_group = self._swimlane.groups.get(id=parent_group_id)
parent_group_child_ids = set([g['id'] for g in parent_group._raw['groups']])
if group.id in parent_group_child_ids:
return
raise ValidationError(
self.record,
'Group `{}` is not a valid selection for field `{}`'.format(
group,
self.name
)
)
|
[
"def",
"_validate_group",
"(",
"self",
",",
"group",
")",
":",
"# All groups allowed",
"if",
"self",
".",
"_show_all_groups",
":",
"return",
"# Group specifically allowed",
"if",
"group",
".",
"id",
"in",
"self",
".",
"_allowed_group_ids",
":",
"return",
"# Group allowed by subgroup membership",
"for",
"parent_group_id",
"in",
"self",
".",
"_allowed_subgroup_ids",
":",
"# Get each group, and check subgroup ids",
"parent_group",
"=",
"self",
".",
"_swimlane",
".",
"groups",
".",
"get",
"(",
"id",
"=",
"parent_group_id",
")",
"parent_group_child_ids",
"=",
"set",
"(",
"[",
"g",
"[",
"'id'",
"]",
"for",
"g",
"in",
"parent_group",
".",
"_raw",
"[",
"'groups'",
"]",
"]",
")",
"if",
"group",
".",
"id",
"in",
"parent_group_child_ids",
":",
"return",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"'Group `{}` is not a valid selection for field `{}`'",
".",
"format",
"(",
"group",
",",
"self",
".",
"name",
")",
")"
] |
Validate a Group instance against allowed group IDs or subgroup of a parent group
|
[
"Validate",
"a",
"Group",
"instance",
"against",
"allowed",
"group",
"IDs",
"or",
"subgroup",
"of",
"a",
"parent",
"group"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/usergroup.py#L79-L103
|
7,248
|
swimlane/swimlane-python
|
swimlane/core/fields/usergroup.py
|
UserGroupField.cast_to_python
|
def cast_to_python(self, value):
"""Convert JSON definition to UserGroup object"""
# v2.x does not provide a distinction between users and groups at the field selection level, can only return
# UserGroup instances instead of specific User or Group instances
if value is not None:
value = UserGroup(self._swimlane, value)
return value
|
python
|
def cast_to_python(self, value):
"""Convert JSON definition to UserGroup object"""
# v2.x does not provide a distinction between users and groups at the field selection level, can only return
# UserGroup instances instead of specific User or Group instances
if value is not None:
value = UserGroup(self._swimlane, value)
return value
|
[
"def",
"cast_to_python",
"(",
"self",
",",
"value",
")",
":",
"# v2.x does not provide a distinction between users and groups at the field selection level, can only return",
"# UserGroup instances instead of specific User or Group instances",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"UserGroup",
"(",
"self",
".",
"_swimlane",
",",
"value",
")",
"return",
"value"
] |
Convert JSON definition to UserGroup object
|
[
"Convert",
"JSON",
"definition",
"to",
"UserGroup",
"object"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/usergroup.py#L112-L119
|
7,249
|
swimlane/swimlane-python
|
swimlane/core/fields/base/cursor.py
|
CursorField.cursor
|
def cursor(self):
"""Cache and return cursor_class instance"""
if self._cursor is None:
# pylint: disable=not-callable
self._cursor = self.cursor_class(self, self.get_initial_elements())
return self._cursor
|
python
|
def cursor(self):
"""Cache and return cursor_class instance"""
if self._cursor is None:
# pylint: disable=not-callable
self._cursor = self.cursor_class(self, self.get_initial_elements())
return self._cursor
|
[
"def",
"cursor",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cursor",
"is",
"None",
":",
"# pylint: disable=not-callable",
"self",
".",
"_cursor",
"=",
"self",
".",
"cursor_class",
"(",
"self",
",",
"self",
".",
"get_initial_elements",
"(",
")",
")",
"return",
"self",
".",
"_cursor"
] |
Cache and return cursor_class instance
|
[
"Cache",
"and",
"return",
"cursor_class",
"instance"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/cursor.py#L72-L78
|
7,250
|
swimlane/swimlane-python
|
swimlane/core/fields/comment.py
|
CommentCursor.comment
|
def comment(self, message):
"""Add new comment to record comment field"""
message = str(message)
sw_repr = {
'$type': 'Core.Models.Record.Comments, Core',
'createdByUser': self._record._swimlane.user.as_usergroup_selection(),
'createdDate': pendulum.now().to_rfc3339_string(),
'message': message
}
comment = Comment(self._swimlane, sw_repr)
self._elements.append(comment)
self._record._raw['comments'].setdefault(self._field.id, [])
self._record._raw['comments'][self._field.id].append(comment._raw)
return comment
|
python
|
def comment(self, message):
"""Add new comment to record comment field"""
message = str(message)
sw_repr = {
'$type': 'Core.Models.Record.Comments, Core',
'createdByUser': self._record._swimlane.user.as_usergroup_selection(),
'createdDate': pendulum.now().to_rfc3339_string(),
'message': message
}
comment = Comment(self._swimlane, sw_repr)
self._elements.append(comment)
self._record._raw['comments'].setdefault(self._field.id, [])
self._record._raw['comments'][self._field.id].append(comment._raw)
return comment
|
[
"def",
"comment",
"(",
"self",
",",
"message",
")",
":",
"message",
"=",
"str",
"(",
"message",
")",
"sw_repr",
"=",
"{",
"'$type'",
":",
"'Core.Models.Record.Comments, Core'",
",",
"'createdByUser'",
":",
"self",
".",
"_record",
".",
"_swimlane",
".",
"user",
".",
"as_usergroup_selection",
"(",
")",
",",
"'createdDate'",
":",
"pendulum",
".",
"now",
"(",
")",
".",
"to_rfc3339_string",
"(",
")",
",",
"'message'",
":",
"message",
"}",
"comment",
"=",
"Comment",
"(",
"self",
".",
"_swimlane",
",",
"sw_repr",
")",
"self",
".",
"_elements",
".",
"append",
"(",
"comment",
")",
"self",
".",
"_record",
".",
"_raw",
"[",
"'comments'",
"]",
".",
"setdefault",
"(",
"self",
".",
"_field",
".",
"id",
",",
"[",
"]",
")",
"self",
".",
"_record",
".",
"_raw",
"[",
"'comments'",
"]",
"[",
"self",
".",
"_field",
".",
"id",
"]",
".",
"append",
"(",
"comment",
".",
"_raw",
")",
"return",
"comment"
] |
Add new comment to record comment field
|
[
"Add",
"new",
"comment",
"to",
"record",
"comment",
"field"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/comment.py#L10-L27
|
7,251
|
swimlane/swimlane-python
|
swimlane/utils/__init__.py
|
get_recursive_subclasses
|
def get_recursive_subclasses(cls):
"""Return list of all subclasses for a class, including subclasses of direct subclasses"""
return cls.__subclasses__() + [g for s in cls.__subclasses__() for g in get_recursive_subclasses(s)]
|
python
|
def get_recursive_subclasses(cls):
"""Return list of all subclasses for a class, including subclasses of direct subclasses"""
return cls.__subclasses__() + [g for s in cls.__subclasses__() for g in get_recursive_subclasses(s)]
|
[
"def",
"get_recursive_subclasses",
"(",
"cls",
")",
":",
"return",
"cls",
".",
"__subclasses__",
"(",
")",
"+",
"[",
"g",
"for",
"s",
"in",
"cls",
".",
"__subclasses__",
"(",
")",
"for",
"g",
"in",
"get_recursive_subclasses",
"(",
"s",
")",
"]"
] |
Return list of all subclasses for a class, including subclasses of direct subclasses
|
[
"Return",
"list",
"of",
"all",
"subclasses",
"for",
"a",
"class",
"including",
"subclasses",
"of",
"direct",
"subclasses"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/utils/__init__.py#L24-L26
|
7,252
|
swimlane/swimlane-python
|
swimlane/utils/__init__.py
|
import_submodules
|
def import_submodules(package):
"""Return list of imported module instances from beneath root_package"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for _, full_name, is_pkg in pkgutil.walk_packages(package.__path__, package.__name__ + '.'):
results[full_name] = importlib.import_module(full_name)
if is_pkg:
results.update(import_submodules(full_name))
return results
|
python
|
def import_submodules(package):
"""Return list of imported module instances from beneath root_package"""
if isinstance(package, str):
package = importlib.import_module(package)
results = {}
for _, full_name, is_pkg in pkgutil.walk_packages(package.__path__, package.__name__ + '.'):
results[full_name] = importlib.import_module(full_name)
if is_pkg:
results.update(import_submodules(full_name))
return results
|
[
"def",
"import_submodules",
"(",
"package",
")",
":",
"if",
"isinstance",
"(",
"package",
",",
"str",
")",
":",
"package",
"=",
"importlib",
".",
"import_module",
"(",
"package",
")",
"results",
"=",
"{",
"}",
"for",
"_",
",",
"full_name",
",",
"is_pkg",
"in",
"pkgutil",
".",
"walk_packages",
"(",
"package",
".",
"__path__",
",",
"package",
".",
"__name__",
"+",
"'.'",
")",
":",
"results",
"[",
"full_name",
"]",
"=",
"importlib",
".",
"import_module",
"(",
"full_name",
")",
"if",
"is_pkg",
":",
"results",
".",
"update",
"(",
"import_submodules",
"(",
"full_name",
")",
")",
"return",
"results"
] |
Return list of imported module instances from beneath root_package
|
[
"Return",
"list",
"of",
"imported",
"module",
"instances",
"from",
"beneath",
"root_package"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/utils/__init__.py#L29-L43
|
7,253
|
swimlane/swimlane-python
|
swimlane/utils/__init__.py
|
one_of_keyword_only
|
def one_of_keyword_only(*valid_keywords):
"""Decorator to help make one-and-only-one keyword-only argument functions more reusable
Notes:
Decorated function should take 2 arguments, the first for the key, the second the value
Examples:
::
@one_of_keyword_only('a', 'b', 'c')
def func(key, value):
if key == 'a':
...
elif key == 'b':
...
else:
# key = 'c'
...
...
func(a=1)
func(b=2)
func(c=3)
try:
func(d=4)
except TypeError:
...
try:
func(a=1, b=2)
except TypeError:
...
Args:
*valid_keywords (str): All allowed keyword argument names
Raises:
TypeError: On decorated call, if 0 or 2+ arguments are provided or kwargs contains a key not in valid_keywords
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
sentinel = object()
values = {}
for key in valid_keywords:
kwarg_value = kwargs.pop(key, sentinel)
if kwarg_value is not sentinel:
values[key] = kwarg_value
if kwargs:
raise TypeError('Unexpected arguments: {}'.format(kwargs))
if not values:
raise TypeError('Must provide one of {} as keyword argument'.format(', '.join(valid_keywords)))
if len(values) > 1:
raise TypeError('Must provide only one of {} as keyword argument. Received {}'.format(
', '.join(valid_keywords),
values
))
return func(*(args + values.popitem()))
return wrapper
return decorator
|
python
|
def one_of_keyword_only(*valid_keywords):
"""Decorator to help make one-and-only-one keyword-only argument functions more reusable
Notes:
Decorated function should take 2 arguments, the first for the key, the second the value
Examples:
::
@one_of_keyword_only('a', 'b', 'c')
def func(key, value):
if key == 'a':
...
elif key == 'b':
...
else:
# key = 'c'
...
...
func(a=1)
func(b=2)
func(c=3)
try:
func(d=4)
except TypeError:
...
try:
func(a=1, b=2)
except TypeError:
...
Args:
*valid_keywords (str): All allowed keyword argument names
Raises:
TypeError: On decorated call, if 0 or 2+ arguments are provided or kwargs contains a key not in valid_keywords
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
sentinel = object()
values = {}
for key in valid_keywords:
kwarg_value = kwargs.pop(key, sentinel)
if kwarg_value is not sentinel:
values[key] = kwarg_value
if kwargs:
raise TypeError('Unexpected arguments: {}'.format(kwargs))
if not values:
raise TypeError('Must provide one of {} as keyword argument'.format(', '.join(valid_keywords)))
if len(values) > 1:
raise TypeError('Must provide only one of {} as keyword argument. Received {}'.format(
', '.join(valid_keywords),
values
))
return func(*(args + values.popitem()))
return wrapper
return decorator
|
[
"def",
"one_of_keyword_only",
"(",
"*",
"valid_keywords",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"sentinel",
"=",
"object",
"(",
")",
"values",
"=",
"{",
"}",
"for",
"key",
"in",
"valid_keywords",
":",
"kwarg_value",
"=",
"kwargs",
".",
"pop",
"(",
"key",
",",
"sentinel",
")",
"if",
"kwarg_value",
"is",
"not",
"sentinel",
":",
"values",
"[",
"key",
"]",
"=",
"kwarg_value",
"if",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'Unexpected arguments: {}'",
".",
"format",
"(",
"kwargs",
")",
")",
"if",
"not",
"values",
":",
"raise",
"TypeError",
"(",
"'Must provide one of {} as keyword argument'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"valid_keywords",
")",
")",
")",
"if",
"len",
"(",
"values",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"'Must provide only one of {} as keyword argument. Received {}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"valid_keywords",
")",
",",
"values",
")",
")",
"return",
"func",
"(",
"*",
"(",
"args",
"+",
"values",
".",
"popitem",
"(",
")",
")",
")",
"return",
"wrapper",
"return",
"decorator"
] |
Decorator to help make one-and-only-one keyword-only argument functions more reusable
Notes:
Decorated function should take 2 arguments, the first for the key, the second the value
Examples:
::
@one_of_keyword_only('a', 'b', 'c')
def func(key, value):
if key == 'a':
...
elif key == 'b':
...
else:
# key = 'c'
...
...
func(a=1)
func(b=2)
func(c=3)
try:
func(d=4)
except TypeError:
...
try:
func(a=1, b=2)
except TypeError:
...
Args:
*valid_keywords (str): All allowed keyword argument names
Raises:
TypeError: On decorated call, if 0 or 2+ arguments are provided or kwargs contains a key not in valid_keywords
|
[
"Decorator",
"to",
"help",
"make",
"one",
"-",
"and",
"-",
"only",
"-",
"one",
"keyword",
"-",
"only",
"argument",
"functions",
"more",
"reusable"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/utils/__init__.py#L46-L117
|
7,254
|
swimlane/swimlane-python
|
swimlane/core/fields/datetime.py
|
DatetimeField.get_python
|
def get_python(self):
"""Coerce to best date type representation for the field subtype"""
value = super(DatetimeField, self).get_python()
if value is not None:
# Handle subtypes with matching Pendulum types
if self.input_type == self._type_time:
value = value.time()
if self.input_type == self._type_date:
value = value.date()
return value
|
python
|
def get_python(self):
"""Coerce to best date type representation for the field subtype"""
value = super(DatetimeField, self).get_python()
if value is not None:
# Handle subtypes with matching Pendulum types
if self.input_type == self._type_time:
value = value.time()
if self.input_type == self._type_date:
value = value.date()
return value
|
[
"def",
"get_python",
"(",
"self",
")",
":",
"value",
"=",
"super",
"(",
"DatetimeField",
",",
"self",
")",
".",
"get_python",
"(",
")",
"if",
"value",
"is",
"not",
"None",
":",
"# Handle subtypes with matching Pendulum types",
"if",
"self",
".",
"input_type",
"==",
"self",
".",
"_type_time",
":",
"value",
"=",
"value",
".",
"time",
"(",
")",
"if",
"self",
".",
"input_type",
"==",
"self",
".",
"_type_date",
":",
"value",
"=",
"value",
".",
"date",
"(",
")",
"return",
"value"
] |
Coerce to best date type representation for the field subtype
|
[
"Coerce",
"to",
"best",
"date",
"type",
"representation",
"for",
"the",
"field",
"subtype"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/datetime.py#L68-L79
|
7,255
|
swimlane/swimlane-python
|
swimlane/core/fields/datetime.py
|
DatetimeField.cast_to_swimlane
|
def cast_to_swimlane(self, value):
"""Return datetimes formatted as expected by API and timespans as millisecond epochs"""
if value is None:
return value
if self.input_type == self._type_interval:
return value.in_seconds() * 1000
return self.format_datetime(value)
|
python
|
def cast_to_swimlane(self, value):
"""Return datetimes formatted as expected by API and timespans as millisecond epochs"""
if value is None:
return value
if self.input_type == self._type_interval:
return value.in_seconds() * 1000
return self.format_datetime(value)
|
[
"def",
"cast_to_swimlane",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"value",
"if",
"self",
".",
"input_type",
"==",
"self",
".",
"_type_interval",
":",
"return",
"value",
".",
"in_seconds",
"(",
")",
"*",
"1000",
"return",
"self",
".",
"format_datetime",
"(",
"value",
")"
] |
Return datetimes formatted as expected by API and timespans as millisecond epochs
|
[
"Return",
"datetimes",
"formatted",
"as",
"expected",
"by",
"API",
"and",
"timespans",
"as",
"millisecond",
"epochs"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/datetime.py#L86-L94
|
7,256
|
swimlane/swimlane-python
|
swimlane/core/fields/datetime.py
|
DatetimeField.for_json
|
def for_json(self):
"""Return date ISO8601 string formats for datetime, date, and time values, milliseconds for intervals"""
value = super(DatetimeField, self).for_json()
# Order of instance checks matters for proper inheritance checks
if isinstance(value, pendulum.Interval):
return value.in_seconds() * 1000
if isinstance(value, datetime):
return self.format_datetime(value)
if isinstance(value, pendulum.Time):
return str(value)
if isinstance(value, pendulum.Date):
return value.to_date_string()
|
python
|
def for_json(self):
"""Return date ISO8601 string formats for datetime, date, and time values, milliseconds for intervals"""
value = super(DatetimeField, self).for_json()
# Order of instance checks matters for proper inheritance checks
if isinstance(value, pendulum.Interval):
return value.in_seconds() * 1000
if isinstance(value, datetime):
return self.format_datetime(value)
if isinstance(value, pendulum.Time):
return str(value)
if isinstance(value, pendulum.Date):
return value.to_date_string()
|
[
"def",
"for_json",
"(",
"self",
")",
":",
"value",
"=",
"super",
"(",
"DatetimeField",
",",
"self",
")",
".",
"for_json",
"(",
")",
"# Order of instance checks matters for proper inheritance checks",
"if",
"isinstance",
"(",
"value",
",",
"pendulum",
".",
"Interval",
")",
":",
"return",
"value",
".",
"in_seconds",
"(",
")",
"*",
"1000",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"return",
"self",
".",
"format_datetime",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"pendulum",
".",
"Time",
")",
":",
"return",
"str",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"pendulum",
".",
"Date",
")",
":",
"return",
"value",
".",
"to_date_string",
"(",
")"
] |
Return date ISO8601 string formats for datetime, date, and time values, milliseconds for intervals
|
[
"Return",
"date",
"ISO8601",
"string",
"formats",
"for",
"datetime",
"date",
"and",
"time",
"values",
"milliseconds",
"for",
"intervals"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/datetime.py#L96-L108
|
7,257
|
swimlane/swimlane-python
|
swimlane/core/resources/report.py
|
report_factory
|
def report_factory(app, report_name, **kwargs):
"""Report instance factory populating boilerplate raw data
Args:
app (App): Swimlane App instance
report_name (str): Generated Report name
Keyword Args
**kwargs: Kwargs to pass to the Report class
"""
# pylint: disable=protected-access
created = pendulum.now().to_rfc3339_string()
user_model = app._swimlane.user.as_usergroup_selection()
return Report(
app,
{
"$type": Report._type,
"groupBys": [],
"aggregates": [],
"applicationIds": [app.id],
"columns": [],
"sorts": {
"$type": "System.Collections.Generic.Dictionary`2"
"[[System.String, mscorlib],"
"[Core.Models.Search.SortTypes, Core]], mscorlib",
},
"filters": [],
"defaultSearchReport": False,
"allowed": [],
"permissions": {
"$type": "Core.Models.Security.PermissionMatrix, Core"
},
"createdDate": created,
"modifiedDate": created,
"createdByUser": user_model,
"modifiedByUser": user_model,
"id": None,
"name": report_name,
"disabled": False,
"keywords": ""
},
**kwargs
)
|
python
|
def report_factory(app, report_name, **kwargs):
"""Report instance factory populating boilerplate raw data
Args:
app (App): Swimlane App instance
report_name (str): Generated Report name
Keyword Args
**kwargs: Kwargs to pass to the Report class
"""
# pylint: disable=protected-access
created = pendulum.now().to_rfc3339_string()
user_model = app._swimlane.user.as_usergroup_selection()
return Report(
app,
{
"$type": Report._type,
"groupBys": [],
"aggregates": [],
"applicationIds": [app.id],
"columns": [],
"sorts": {
"$type": "System.Collections.Generic.Dictionary`2"
"[[System.String, mscorlib],"
"[Core.Models.Search.SortTypes, Core]], mscorlib",
},
"filters": [],
"defaultSearchReport": False,
"allowed": [],
"permissions": {
"$type": "Core.Models.Security.PermissionMatrix, Core"
},
"createdDate": created,
"modifiedDate": created,
"createdByUser": user_model,
"modifiedByUser": user_model,
"id": None,
"name": report_name,
"disabled": False,
"keywords": ""
},
**kwargs
)
|
[
"def",
"report_factory",
"(",
"app",
",",
"report_name",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=protected-access",
"created",
"=",
"pendulum",
".",
"now",
"(",
")",
".",
"to_rfc3339_string",
"(",
")",
"user_model",
"=",
"app",
".",
"_swimlane",
".",
"user",
".",
"as_usergroup_selection",
"(",
")",
"return",
"Report",
"(",
"app",
",",
"{",
"\"$type\"",
":",
"Report",
".",
"_type",
",",
"\"groupBys\"",
":",
"[",
"]",
",",
"\"aggregates\"",
":",
"[",
"]",
",",
"\"applicationIds\"",
":",
"[",
"app",
".",
"id",
"]",
",",
"\"columns\"",
":",
"[",
"]",
",",
"\"sorts\"",
":",
"{",
"\"$type\"",
":",
"\"System.Collections.Generic.Dictionary`2\"",
"\"[[System.String, mscorlib],\"",
"\"[Core.Models.Search.SortTypes, Core]], mscorlib\"",
",",
"}",
",",
"\"filters\"",
":",
"[",
"]",
",",
"\"defaultSearchReport\"",
":",
"False",
",",
"\"allowed\"",
":",
"[",
"]",
",",
"\"permissions\"",
":",
"{",
"\"$type\"",
":",
"\"Core.Models.Security.PermissionMatrix, Core\"",
"}",
",",
"\"createdDate\"",
":",
"created",
",",
"\"modifiedDate\"",
":",
"created",
",",
"\"createdByUser\"",
":",
"user_model",
",",
"\"modifiedByUser\"",
":",
"user_model",
",",
"\"id\"",
":",
"None",
",",
"\"name\"",
":",
"report_name",
",",
"\"disabled\"",
":",
"False",
",",
"\"keywords\"",
":",
"\"\"",
"}",
",",
"*",
"*",
"kwargs",
")"
] |
Report instance factory populating boilerplate raw data
Args:
app (App): Swimlane App instance
report_name (str): Generated Report name
Keyword Args
**kwargs: Kwargs to pass to the Report class
|
[
"Report",
"instance",
"factory",
"populating",
"boilerplate",
"raw",
"data"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/resources/report.py#L113-L156
|
7,258
|
swimlane/swimlane-python
|
swimlane/core/resources/report.py
|
Report.filter
|
def filter(self, field_name, operand, value):
"""Adds a filter to report
Notes:
All filters are currently AND'ed together
Args:
field_name (str): Target field name to filter on
operand (str): Operand used in comparison. See `swimlane.core.search` for options
value: Target value used in comparision
"""
if operand not in self._FILTER_OPERANDS:
raise ValueError('Operand must be one of {}'.format(', '.join(self._FILTER_OPERANDS)))
# Use temp Record instance for target app to translate values into expected API format
record_stub = record_factory(self._app)
field = record_stub.get_field(field_name)
self._raw['filters'].append({
"fieldId": field.id,
"filterType": operand,
"value": field.get_report(value)
})
|
python
|
def filter(self, field_name, operand, value):
"""Adds a filter to report
Notes:
All filters are currently AND'ed together
Args:
field_name (str): Target field name to filter on
operand (str): Operand used in comparison. See `swimlane.core.search` for options
value: Target value used in comparision
"""
if operand not in self._FILTER_OPERANDS:
raise ValueError('Operand must be one of {}'.format(', '.join(self._FILTER_OPERANDS)))
# Use temp Record instance for target app to translate values into expected API format
record_stub = record_factory(self._app)
field = record_stub.get_field(field_name)
self._raw['filters'].append({
"fieldId": field.id,
"filterType": operand,
"value": field.get_report(value)
})
|
[
"def",
"filter",
"(",
"self",
",",
"field_name",
",",
"operand",
",",
"value",
")",
":",
"if",
"operand",
"not",
"in",
"self",
".",
"_FILTER_OPERANDS",
":",
"raise",
"ValueError",
"(",
"'Operand must be one of {}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"self",
".",
"_FILTER_OPERANDS",
")",
")",
")",
"# Use temp Record instance for target app to translate values into expected API format",
"record_stub",
"=",
"record_factory",
"(",
"self",
".",
"_app",
")",
"field",
"=",
"record_stub",
".",
"get_field",
"(",
"field_name",
")",
"self",
".",
"_raw",
"[",
"'filters'",
"]",
".",
"append",
"(",
"{",
"\"fieldId\"",
":",
"field",
".",
"id",
",",
"\"filterType\"",
":",
"operand",
",",
"\"value\"",
":",
"field",
".",
"get_report",
"(",
"value",
")",
"}",
")"
] |
Adds a filter to report
Notes:
All filters are currently AND'ed together
Args:
field_name (str): Target field name to filter on
operand (str): Operand used in comparison. See `swimlane.core.search` for options
value: Target value used in comparision
|
[
"Adds",
"a",
"filter",
"to",
"report"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/resources/report.py#L88-L110
|
7,259
|
swimlane/swimlane-python
|
swimlane/core/adapters/report.py
|
ReportAdapter.list
|
def list(self):
"""Retrieve all reports for parent app
Returns:
:class:`list` of :class:`~swimlane.core.resources.report.Report`: List of all returned reports
"""
raw_reports = self._swimlane.request('get', "reports?appId={}".format(self._app.id)).json()
# Ignore StatsReports for now
return [Report(self._app, raw_report) for raw_report in raw_reports if raw_report['$type'] == Report._type]
|
python
|
def list(self):
"""Retrieve all reports for parent app
Returns:
:class:`list` of :class:`~swimlane.core.resources.report.Report`: List of all returned reports
"""
raw_reports = self._swimlane.request('get', "reports?appId={}".format(self._app.id)).json()
# Ignore StatsReports for now
return [Report(self._app, raw_report) for raw_report in raw_reports if raw_report['$type'] == Report._type]
|
[
"def",
"list",
"(",
"self",
")",
":",
"raw_reports",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"\"reports?appId={}\"",
".",
"format",
"(",
"self",
".",
"_app",
".",
"id",
")",
")",
".",
"json",
"(",
")",
"# Ignore StatsReports for now",
"return",
"[",
"Report",
"(",
"self",
".",
"_app",
",",
"raw_report",
")",
"for",
"raw_report",
"in",
"raw_reports",
"if",
"raw_report",
"[",
"'$type'",
"]",
"==",
"Report",
".",
"_type",
"]"
] |
Retrieve all reports for parent app
Returns:
:class:`list` of :class:`~swimlane.core.resources.report.Report`: List of all returned reports
|
[
"Retrieve",
"all",
"reports",
"for",
"parent",
"app"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/report.py#L20-L28
|
7,260
|
swimlane/swimlane-python
|
swimlane/core/adapters/report.py
|
ReportAdapter.get
|
def get(self, report_id):
"""Retrieve report by ID
Args:
report_id (str): Full report ID
Returns:
Report: Corresponding Report instance
"""
return Report(
self._app,
self._swimlane.request('get', "reports/{0}".format(report_id)).json()
)
|
python
|
def get(self, report_id):
"""Retrieve report by ID
Args:
report_id (str): Full report ID
Returns:
Report: Corresponding Report instance
"""
return Report(
self._app,
self._swimlane.request('get', "reports/{0}".format(report_id)).json()
)
|
[
"def",
"get",
"(",
"self",
",",
"report_id",
")",
":",
"return",
"Report",
"(",
"self",
".",
"_app",
",",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"\"reports/{0}\"",
".",
"format",
"(",
"report_id",
")",
")",
".",
"json",
"(",
")",
")"
] |
Retrieve report by ID
Args:
report_id (str): Full report ID
Returns:
Report: Corresponding Report instance
|
[
"Retrieve",
"report",
"by",
"ID"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/report.py#L30-L42
|
7,261
|
swimlane/swimlane-python
|
swimlane/core/adapters/usergroup.py
|
GroupAdapter.get
|
def get(self, key, value):
"""Retrieve single group record by id or name
Supports resource cache
Keyword Args:
id (str): Full Group ID
name (str): Group name
Raises:
TypeError: Unexpected or more than one keyword argument provided
ValueError: No matching group found based on provided inputs
Returns:
Group: Group instance matching provided inputs
"""
if key == 'id':
response = self._swimlane.request('get', 'groups/{}'.format(value))
return Group(self._swimlane, response.json())
else:
response = self._swimlane.request('get', 'groups/lookup?name={}'.format(value))
matched_groups = response.json()
for group_data in matched_groups:
if group_data.get('name') == value:
return Group(self._swimlane, group_data)
raise ValueError('Unable to find group with name "{}"'.format(value))
|
python
|
def get(self, key, value):
"""Retrieve single group record by id or name
Supports resource cache
Keyword Args:
id (str): Full Group ID
name (str): Group name
Raises:
TypeError: Unexpected or more than one keyword argument provided
ValueError: No matching group found based on provided inputs
Returns:
Group: Group instance matching provided inputs
"""
if key == 'id':
response = self._swimlane.request('get', 'groups/{}'.format(value))
return Group(self._swimlane, response.json())
else:
response = self._swimlane.request('get', 'groups/lookup?name={}'.format(value))
matched_groups = response.json()
for group_data in matched_groups:
if group_data.get('name') == value:
return Group(self._swimlane, group_data)
raise ValueError('Unable to find group with name "{}"'.format(value))
|
[
"def",
"get",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"'id'",
":",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"'groups/{}'",
".",
"format",
"(",
"value",
")",
")",
"return",
"Group",
"(",
"self",
".",
"_swimlane",
",",
"response",
".",
"json",
"(",
")",
")",
"else",
":",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"'groups/lookup?name={}'",
".",
"format",
"(",
"value",
")",
")",
"matched_groups",
"=",
"response",
".",
"json",
"(",
")",
"for",
"group_data",
"in",
"matched_groups",
":",
"if",
"group_data",
".",
"get",
"(",
"'name'",
")",
"==",
"value",
":",
"return",
"Group",
"(",
"self",
".",
"_swimlane",
",",
"group_data",
")",
"raise",
"ValueError",
"(",
"'Unable to find group with name \"{}\"'",
".",
"format",
"(",
"value",
")",
")"
] |
Retrieve single group record by id or name
Supports resource cache
Keyword Args:
id (str): Full Group ID
name (str): Group name
Raises:
TypeError: Unexpected or more than one keyword argument provided
ValueError: No matching group found based on provided inputs
Returns:
Group: Group instance matching provided inputs
|
[
"Retrieve",
"single",
"group",
"record",
"by",
"id",
"or",
"name"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/usergroup.py#L45-L73
|
7,262
|
swimlane/swimlane-python
|
swimlane/core/adapters/usergroup.py
|
UserAdapter.get
|
def get(self, arg, value):
"""Retrieve single user record by id or username
Warnings:
User display names are not unique. If using `display_name`, method will fail if multiple Users are returned
with the same display name
Keyword Args:
id (str): Full User ID
display_name (str): User display name
Returns:
User: User instance matching provided inputs
Raises:
TypeError: Unexpected or more than one keyword argument provided
ValueError: No matching user found based on provided inputs, or multiple Users with same display name
"""
if arg == 'id':
response = self._swimlane.request('get', 'user/{}'.format(value))
try:
user_data = response.json()
except ValueError:
raise ValueError('Unable to find user with ID "{}"'.format(value))
return User(self._swimlane, user_data)
else:
response = self._swimlane.request('get', 'user/search?query={}'.format(quote_plus(value)))
matched_users = response.json()
# Display name not unique, fail if multiple users share the same target display name
target_matches = []
for user_data in matched_users:
user_display_name = user_data.get('displayName')
if user_display_name == value:
target_matches.append(user_data)
# No matches
if not target_matches:
raise ValueError('Unable to find user with display name "{}"'.format(value))
# Multiple matches
if len(target_matches) > 1:
raise ValueError('Multiple users returned with display name "{}". Matching user IDs: {}'.format(
value,
', '.join(['"{}"'.format(r['id']) for r in target_matches])
))
return User(self._swimlane, target_matches[0])
|
python
|
def get(self, arg, value):
"""Retrieve single user record by id or username
Warnings:
User display names are not unique. If using `display_name`, method will fail if multiple Users are returned
with the same display name
Keyword Args:
id (str): Full User ID
display_name (str): User display name
Returns:
User: User instance matching provided inputs
Raises:
TypeError: Unexpected or more than one keyword argument provided
ValueError: No matching user found based on provided inputs, or multiple Users with same display name
"""
if arg == 'id':
response = self._swimlane.request('get', 'user/{}'.format(value))
try:
user_data = response.json()
except ValueError:
raise ValueError('Unable to find user with ID "{}"'.format(value))
return User(self._swimlane, user_data)
else:
response = self._swimlane.request('get', 'user/search?query={}'.format(quote_plus(value)))
matched_users = response.json()
# Display name not unique, fail if multiple users share the same target display name
target_matches = []
for user_data in matched_users:
user_display_name = user_data.get('displayName')
if user_display_name == value:
target_matches.append(user_data)
# No matches
if not target_matches:
raise ValueError('Unable to find user with display name "{}"'.format(value))
# Multiple matches
if len(target_matches) > 1:
raise ValueError('Multiple users returned with display name "{}". Matching user IDs: {}'.format(
value,
', '.join(['"{}"'.format(r['id']) for r in target_matches])
))
return User(self._swimlane, target_matches[0])
|
[
"def",
"get",
"(",
"self",
",",
"arg",
",",
"value",
")",
":",
"if",
"arg",
"==",
"'id'",
":",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"'user/{}'",
".",
"format",
"(",
"value",
")",
")",
"try",
":",
"user_data",
"=",
"response",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'Unable to find user with ID \"{}\"'",
".",
"format",
"(",
"value",
")",
")",
"return",
"User",
"(",
"self",
".",
"_swimlane",
",",
"user_data",
")",
"else",
":",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"'user/search?query={}'",
".",
"format",
"(",
"quote_plus",
"(",
"value",
")",
")",
")",
"matched_users",
"=",
"response",
".",
"json",
"(",
")",
"# Display name not unique, fail if multiple users share the same target display name",
"target_matches",
"=",
"[",
"]",
"for",
"user_data",
"in",
"matched_users",
":",
"user_display_name",
"=",
"user_data",
".",
"get",
"(",
"'displayName'",
")",
"if",
"user_display_name",
"==",
"value",
":",
"target_matches",
".",
"append",
"(",
"user_data",
")",
"# No matches",
"if",
"not",
"target_matches",
":",
"raise",
"ValueError",
"(",
"'Unable to find user with display name \"{}\"'",
".",
"format",
"(",
"value",
")",
")",
"# Multiple matches",
"if",
"len",
"(",
"target_matches",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'Multiple users returned with display name \"{}\". Matching user IDs: {}'",
".",
"format",
"(",
"value",
",",
"', '",
".",
"join",
"(",
"[",
"'\"{}\"'",
".",
"format",
"(",
"r",
"[",
"'id'",
"]",
")",
"for",
"r",
"in",
"target_matches",
"]",
")",
")",
")",
"return",
"User",
"(",
"self",
".",
"_swimlane",
",",
"target_matches",
"[",
"0",
"]",
")"
] |
Retrieve single user record by id or username
Warnings:
User display names are not unique. If using `display_name`, method will fail if multiple Users are returned
with the same display name
Keyword Args:
id (str): Full User ID
display_name (str): User display name
Returns:
User: User instance matching provided inputs
Raises:
TypeError: Unexpected or more than one keyword argument provided
ValueError: No matching user found based on provided inputs, or multiple Users with same display name
|
[
"Retrieve",
"single",
"user",
"record",
"by",
"id",
"or",
"username"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/usergroup.py#L111-L162
|
7,263
|
swimlane/swimlane-python
|
swimlane/core/fields/history.py
|
RevisionCursor._evaluate
|
def _evaluate(self):
"""Lazily retrieves, caches, and returns the list of record _revisions"""
if not self.__retrieved:
self._elements = self._retrieve_revisions()
self.__retrieved = True
return super(RevisionCursor, self)._evaluate()
|
python
|
def _evaluate(self):
"""Lazily retrieves, caches, and returns the list of record _revisions"""
if not self.__retrieved:
self._elements = self._retrieve_revisions()
self.__retrieved = True
return super(RevisionCursor, self)._evaluate()
|
[
"def",
"_evaluate",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__retrieved",
":",
"self",
".",
"_elements",
"=",
"self",
".",
"_retrieve_revisions",
"(",
")",
"self",
".",
"__retrieved",
"=",
"True",
"return",
"super",
"(",
"RevisionCursor",
",",
"self",
")",
".",
"_evaluate",
"(",
")"
] |
Lazily retrieves, caches, and returns the list of record _revisions
|
[
"Lazily",
"retrieves",
"caches",
"and",
"returns",
"the",
"list",
"of",
"record",
"_revisions"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/history.py#L15-L21
|
7,264
|
swimlane/swimlane-python
|
swimlane/core/fields/history.py
|
RevisionCursor._retrieve_revisions
|
def _retrieve_revisions(self):
"""Retrieve and populate Revision instances from history API endpoint"""
response = self._swimlane.request(
'get',
'history',
params={
'type': 'Records',
'id': self._record.id
}
)
raw_revisions = response.json()
return [Revision(self._record, raw) for raw in raw_revisions]
|
python
|
def _retrieve_revisions(self):
"""Retrieve and populate Revision instances from history API endpoint"""
response = self._swimlane.request(
'get',
'history',
params={
'type': 'Records',
'id': self._record.id
}
)
raw_revisions = response.json()
return [Revision(self._record, raw) for raw in raw_revisions]
|
[
"def",
"_retrieve_revisions",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"'history'",
",",
"params",
"=",
"{",
"'type'",
":",
"'Records'",
",",
"'id'",
":",
"self",
".",
"_record",
".",
"id",
"}",
")",
"raw_revisions",
"=",
"response",
".",
"json",
"(",
")",
"return",
"[",
"Revision",
"(",
"self",
".",
"_record",
",",
"raw",
")",
"for",
"raw",
"in",
"raw_revisions",
"]"
] |
Retrieve and populate Revision instances from history API endpoint
|
[
"Retrieve",
"and",
"populate",
"Revision",
"instances",
"from",
"history",
"API",
"endpoint"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/history.py#L23-L36
|
7,265
|
swimlane/swimlane-python
|
swimlane/core/fields/valueslist.py
|
ValuesListField.validate_value
|
def validate_value(self, value):
"""Validate provided value is one of the valid options"""
super(ValuesListField, self).validate_value(value)
if value is not None:
if value not in self.selection_to_id_map:
raise ValidationError(
self.record,
'Field "{}" invalid value "{}". Valid options: {}'.format(
self.name,
value,
', '.join(self.selection_to_id_map.keys())
)
)
|
python
|
def validate_value(self, value):
"""Validate provided value is one of the valid options"""
super(ValuesListField, self).validate_value(value)
if value is not None:
if value not in self.selection_to_id_map:
raise ValidationError(
self.record,
'Field "{}" invalid value "{}". Valid options: {}'.format(
self.name,
value,
', '.join(self.selection_to_id_map.keys())
)
)
|
[
"def",
"validate_value",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"ValuesListField",
",",
"self",
")",
".",
"validate_value",
"(",
"value",
")",
"if",
"value",
"is",
"not",
"None",
":",
"if",
"value",
"not",
"in",
"self",
".",
"selection_to_id_map",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"'Field \"{}\" invalid value \"{}\". Valid options: {}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"value",
",",
"', '",
".",
"join",
"(",
"self",
".",
"selection_to_id_map",
".",
"keys",
"(",
")",
")",
")",
")"
] |
Validate provided value is one of the valid options
|
[
"Validate",
"provided",
"value",
"is",
"one",
"of",
"the",
"valid",
"options"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/valueslist.py#L20-L33
|
7,266
|
swimlane/swimlane-python
|
swimlane/core/fields/valueslist.py
|
ValuesListField.cast_to_report
|
def cast_to_report(self, value):
"""Report format uses only the value's id"""
value = super(ValuesListField, self).cast_to_report(value)
if value:
return value['id']
|
python
|
def cast_to_report(self, value):
"""Report format uses only the value's id"""
value = super(ValuesListField, self).cast_to_report(value)
if value:
return value['id']
|
[
"def",
"cast_to_report",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
"ValuesListField",
",",
"self",
")",
".",
"cast_to_report",
"(",
"value",
")",
"if",
"value",
":",
"return",
"value",
"[",
"'id'",
"]"
] |
Report format uses only the value's id
|
[
"Report",
"format",
"uses",
"only",
"the",
"value",
"s",
"id"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/valueslist.py#L53-L58
|
7,267
|
swimlane/swimlane-python
|
swimlane/core/adapters/record.py
|
validate_filters_or_records
|
def validate_filters_or_records(filters_or_records):
"""Validation for filters_or_records variable from bulk_modify and bulk_delete"""
# If filters_or_records is empty, fail
if not filters_or_records:
raise ValueError('Must provide at least one filter tuples or Records')
# If filters_or_records is not list of Record or tuple, fail
if not isinstance(filters_or_records[0], (Record, tuple)):
raise ValueError('Cannot provide both filter tuples and Records')
# If filters_or_records is not list of either Record or only tuple, fail
_type = type(filters_or_records[0])
for item in filters_or_records:
if not isinstance(item, _type):
raise ValueError("Expected filter tuple or Record, received {0}".format(item))
return _type
|
python
|
def validate_filters_or_records(filters_or_records):
"""Validation for filters_or_records variable from bulk_modify and bulk_delete"""
# If filters_or_records is empty, fail
if not filters_or_records:
raise ValueError('Must provide at least one filter tuples or Records')
# If filters_or_records is not list of Record or tuple, fail
if not isinstance(filters_or_records[0], (Record, tuple)):
raise ValueError('Cannot provide both filter tuples and Records')
# If filters_or_records is not list of either Record or only tuple, fail
_type = type(filters_or_records[0])
for item in filters_or_records:
if not isinstance(item, _type):
raise ValueError("Expected filter tuple or Record, received {0}".format(item))
return _type
|
[
"def",
"validate_filters_or_records",
"(",
"filters_or_records",
")",
":",
"# If filters_or_records is empty, fail",
"if",
"not",
"filters_or_records",
":",
"raise",
"ValueError",
"(",
"'Must provide at least one filter tuples or Records'",
")",
"# If filters_or_records is not list of Record or tuple, fail",
"if",
"not",
"isinstance",
"(",
"filters_or_records",
"[",
"0",
"]",
",",
"(",
"Record",
",",
"tuple",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot provide both filter tuples and Records'",
")",
"# If filters_or_records is not list of either Record or only tuple, fail",
"_type",
"=",
"type",
"(",
"filters_or_records",
"[",
"0",
"]",
")",
"for",
"item",
"in",
"filters_or_records",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"_type",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected filter tuple or Record, received {0}\"",
".",
"format",
"(",
"item",
")",
")",
"return",
"_type"
] |
Validation for filters_or_records variable from bulk_modify and bulk_delete
|
[
"Validation",
"for",
"filters_or_records",
"variable",
"from",
"bulk_modify",
"and",
"bulk_delete"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/record.py#L373-L387
|
7,268
|
swimlane/swimlane-python
|
swimlane/core/adapters/record.py
|
RecordAdapter.get
|
def get(self, key, value):
"""Get a single record by id
Supports resource cache
.. versionchanged:: 2.17.0
Added option to retrieve record by tracking_id
Keyword Args:
id (str): Full record ID
tracking_id (str): Record Tracking ID
Returns:
Record: Matching Record instance returned from API
Raises:
TypeError: No id argument provided
"""
if key == 'id':
response = self._swimlane.request('get', "app/{0}/record/{1}".format(self._app.id, value))
return Record(self._app, response.json())
if key == 'tracking_id':
response = self._swimlane.request('get', "app/{0}/record/tracking/{1}".format(self._app.id, value))
return Record(self._app, response.json())
|
python
|
def get(self, key, value):
"""Get a single record by id
Supports resource cache
.. versionchanged:: 2.17.0
Added option to retrieve record by tracking_id
Keyword Args:
id (str): Full record ID
tracking_id (str): Record Tracking ID
Returns:
Record: Matching Record instance returned from API
Raises:
TypeError: No id argument provided
"""
if key == 'id':
response = self._swimlane.request('get', "app/{0}/record/{1}".format(self._app.id, value))
return Record(self._app, response.json())
if key == 'tracking_id':
response = self._swimlane.request('get', "app/{0}/record/tracking/{1}".format(self._app.id, value))
return Record(self._app, response.json())
|
[
"def",
"get",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"'id'",
":",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"\"app/{0}/record/{1}\"",
".",
"format",
"(",
"self",
".",
"_app",
".",
"id",
",",
"value",
")",
")",
"return",
"Record",
"(",
"self",
".",
"_app",
",",
"response",
".",
"json",
"(",
")",
")",
"if",
"key",
"==",
"'tracking_id'",
":",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"\"app/{0}/record/tracking/{1}\"",
".",
"format",
"(",
"self",
".",
"_app",
".",
"id",
",",
"value",
")",
")",
"return",
"Record",
"(",
"self",
".",
"_app",
",",
"response",
".",
"json",
"(",
")",
")"
] |
Get a single record by id
Supports resource cache
.. versionchanged:: 2.17.0
Added option to retrieve record by tracking_id
Keyword Args:
id (str): Full record ID
tracking_id (str): Record Tracking ID
Returns:
Record: Matching Record instance returned from API
Raises:
TypeError: No id argument provided
|
[
"Get",
"a",
"single",
"record",
"by",
"id"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/record.py#L17-L40
|
7,269
|
swimlane/swimlane-python
|
swimlane/core/adapters/record.py
|
RecordAdapter.search
|
def search(self, *filters, **kwargs):
"""Shortcut to generate a new temporary search report using provided filters and return the resulting records
Args:
*filters (tuple): Zero or more filter tuples of (field_name, operator, field_value)
Keyword Args:
keywords (list(str)): List of strings of keywords to use in report search
limit (int): Set maximum number of returned Records, defaults to `Report.default_limit`. Set to 0 to return
all records
Notes:
Uses a temporary Report instance with a random name to facilitate search. Records are normally paginated,
but are returned as a single list here, potentially causing performance issues with large searches.
All provided filters are AND'ed together
Filter operators are available as constants in `swimlane.core.search`
Examples:
::
# Return records matching all filters with default limit
from swimlane.core import search
records = app.records.search(
('field_name', 'equals', 'field_value'),
('other_field', search.NOT_EQ, 'value')
)
::
# Run keyword search with multiple keywords
records = app.records.search(keywords=['example', 'test'])
::
# Return all records from app
records = app.records.search(limit=0)
Returns:
:class:`list` of :class:`~swimlane.core.resources.record.Record`: List of Record instances returned from the
search results
"""
report = self._app.reports.build(
'search-' + random_string(8),
keywords=kwargs.pop('keywords', []),
limit=kwargs.pop('limit', Report.default_limit)
)
for filter_tuples in filters:
report.filter(*filter_tuples)
return list(report)
|
python
|
def search(self, *filters, **kwargs):
"""Shortcut to generate a new temporary search report using provided filters and return the resulting records
Args:
*filters (tuple): Zero or more filter tuples of (field_name, operator, field_value)
Keyword Args:
keywords (list(str)): List of strings of keywords to use in report search
limit (int): Set maximum number of returned Records, defaults to `Report.default_limit`. Set to 0 to return
all records
Notes:
Uses a temporary Report instance with a random name to facilitate search. Records are normally paginated,
but are returned as a single list here, potentially causing performance issues with large searches.
All provided filters are AND'ed together
Filter operators are available as constants in `swimlane.core.search`
Examples:
::
# Return records matching all filters with default limit
from swimlane.core import search
records = app.records.search(
('field_name', 'equals', 'field_value'),
('other_field', search.NOT_EQ, 'value')
)
::
# Run keyword search with multiple keywords
records = app.records.search(keywords=['example', 'test'])
::
# Return all records from app
records = app.records.search(limit=0)
Returns:
:class:`list` of :class:`~swimlane.core.resources.record.Record`: List of Record instances returned from the
search results
"""
report = self._app.reports.build(
'search-' + random_string(8),
keywords=kwargs.pop('keywords', []),
limit=kwargs.pop('limit', Report.default_limit)
)
for filter_tuples in filters:
report.filter(*filter_tuples)
return list(report)
|
[
"def",
"search",
"(",
"self",
",",
"*",
"filters",
",",
"*",
"*",
"kwargs",
")",
":",
"report",
"=",
"self",
".",
"_app",
".",
"reports",
".",
"build",
"(",
"'search-'",
"+",
"random_string",
"(",
"8",
")",
",",
"keywords",
"=",
"kwargs",
".",
"pop",
"(",
"'keywords'",
",",
"[",
"]",
")",
",",
"limit",
"=",
"kwargs",
".",
"pop",
"(",
"'limit'",
",",
"Report",
".",
"default_limit",
")",
")",
"for",
"filter_tuples",
"in",
"filters",
":",
"report",
".",
"filter",
"(",
"*",
"filter_tuples",
")",
"return",
"list",
"(",
"report",
")"
] |
Shortcut to generate a new temporary search report using provided filters and return the resulting records
Args:
*filters (tuple): Zero or more filter tuples of (field_name, operator, field_value)
Keyword Args:
keywords (list(str)): List of strings of keywords to use in report search
limit (int): Set maximum number of returned Records, defaults to `Report.default_limit`. Set to 0 to return
all records
Notes:
Uses a temporary Report instance with a random name to facilitate search. Records are normally paginated,
but are returned as a single list here, potentially causing performance issues with large searches.
All provided filters are AND'ed together
Filter operators are available as constants in `swimlane.core.search`
Examples:
::
# Return records matching all filters with default limit
from swimlane.core import search
records = app.records.search(
('field_name', 'equals', 'field_value'),
('other_field', search.NOT_EQ, 'value')
)
::
# Run keyword search with multiple keywords
records = app.records.search(keywords=['example', 'test'])
::
# Return all records from app
records = app.records.search(limit=0)
Returns:
:class:`list` of :class:`~swimlane.core.resources.record.Record`: List of Record instances returned from the
search results
|
[
"Shortcut",
"to",
"generate",
"a",
"new",
"temporary",
"search",
"report",
"using",
"provided",
"filters",
"and",
"return",
"the",
"resulting",
"records"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/record.py#L42-L98
|
7,270
|
swimlane/swimlane-python
|
swimlane/core/adapters/record.py
|
RecordAdapter.create
|
def create(self, **fields):
"""Create and return a new record in associated app and return the newly created Record instance
Args:
**fields: Field names and values to be validated and sent to server with create request
Notes:
Keyword arguments should be field names with their respective python values
Field values are validated before sending create request to server
Examples:
Create a new record on an app with simple field names
::
record = app.records.create(
field_a='Some Value',
someOtherField=100,
...
)
Create a new record on an app with complex field names
::
record = app.records.create(**{
'Field 1': 'Field 1 Value',
'Field 2': 100,
...
})
Returns:
Record: Newly created Record instance with data as returned from API response
Raises:
swimlane.exceptions.UnknownField: If any fields are provided that are not available on target app
swimlane.exceptions.ValidationError: If any field fails validation before creation
"""
new_record = record_factory(self._app, fields)
new_record.save()
return new_record
|
python
|
def create(self, **fields):
"""Create and return a new record in associated app and return the newly created Record instance
Args:
**fields: Field names and values to be validated and sent to server with create request
Notes:
Keyword arguments should be field names with their respective python values
Field values are validated before sending create request to server
Examples:
Create a new record on an app with simple field names
::
record = app.records.create(
field_a='Some Value',
someOtherField=100,
...
)
Create a new record on an app with complex field names
::
record = app.records.create(**{
'Field 1': 'Field 1 Value',
'Field 2': 100,
...
})
Returns:
Record: Newly created Record instance with data as returned from API response
Raises:
swimlane.exceptions.UnknownField: If any fields are provided that are not available on target app
swimlane.exceptions.ValidationError: If any field fails validation before creation
"""
new_record = record_factory(self._app, fields)
new_record.save()
return new_record
|
[
"def",
"create",
"(",
"self",
",",
"*",
"*",
"fields",
")",
":",
"new_record",
"=",
"record_factory",
"(",
"self",
".",
"_app",
",",
"fields",
")",
"new_record",
".",
"save",
"(",
")",
"return",
"new_record"
] |
Create and return a new record in associated app and return the newly created Record instance
Args:
**fields: Field names and values to be validated and sent to server with create request
Notes:
Keyword arguments should be field names with their respective python values
Field values are validated before sending create request to server
Examples:
Create a new record on an app with simple field names
::
record = app.records.create(
field_a='Some Value',
someOtherField=100,
...
)
Create a new record on an app with complex field names
::
record = app.records.create(**{
'Field 1': 'Field 1 Value',
'Field 2': 100,
...
})
Returns:
Record: Newly created Record instance with data as returned from API response
Raises:
swimlane.exceptions.UnknownField: If any fields are provided that are not available on target app
swimlane.exceptions.ValidationError: If any field fails validation before creation
|
[
"Create",
"and",
"return",
"a",
"new",
"record",
"in",
"associated",
"app",
"and",
"return",
"the",
"newly",
"created",
"Record",
"instance"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/record.py#L100-L143
|
7,271
|
swimlane/swimlane-python
|
swimlane/core/adapters/record.py
|
RecordAdapter.bulk_create
|
def bulk_create(self, *records):
"""Create and validate multiple records in associated app
Args:
*records (dict): One or more dicts of new record field names and values
Notes:
Requires Swimlane 2.15+
Validates like :meth:`create`, but only sends a single request to create all provided fields, and does not
return the newly created records
Any validation failures on any of the records will abort the batch creation, not creating any new records
Does not return the newly created records
Examples:
Create 3 new records with single request
::
app.records.bulk_create(
{'Field 1': 'value 1', ...},
{'Field 1': 'value 2', ...},
{'Field 1': 'value 3', ...}
)
Raises:
swimlane.exceptions.UnknownField: If any field in any new record cannot be found
swimlane.exceptions.ValidationError: If any field in any new record fails validation
TypeError: If no dict of fields was provided, or any provided argument is not a dict
"""
if not records:
raise TypeError('Must provide at least one record')
if any(not isinstance(r, dict) for r in records):
raise TypeError('New records must be provided as dicts')
# Create local records from factory for initial full validation
new_records = []
for record_data in records:
record = record_factory(self._app, record_data)
record.validate()
new_records.append(record)
self._swimlane.request(
'post',
'app/{}/record/batch'.format(self._app.id),
json=[r._raw for r in new_records]
)
|
python
|
def bulk_create(self, *records):
"""Create and validate multiple records in associated app
Args:
*records (dict): One or more dicts of new record field names and values
Notes:
Requires Swimlane 2.15+
Validates like :meth:`create`, but only sends a single request to create all provided fields, and does not
return the newly created records
Any validation failures on any of the records will abort the batch creation, not creating any new records
Does not return the newly created records
Examples:
Create 3 new records with single request
::
app.records.bulk_create(
{'Field 1': 'value 1', ...},
{'Field 1': 'value 2', ...},
{'Field 1': 'value 3', ...}
)
Raises:
swimlane.exceptions.UnknownField: If any field in any new record cannot be found
swimlane.exceptions.ValidationError: If any field in any new record fails validation
TypeError: If no dict of fields was provided, or any provided argument is not a dict
"""
if not records:
raise TypeError('Must provide at least one record')
if any(not isinstance(r, dict) for r in records):
raise TypeError('New records must be provided as dicts')
# Create local records from factory for initial full validation
new_records = []
for record_data in records:
record = record_factory(self._app, record_data)
record.validate()
new_records.append(record)
self._swimlane.request(
'post',
'app/{}/record/batch'.format(self._app.id),
json=[r._raw for r in new_records]
)
|
[
"def",
"bulk_create",
"(",
"self",
",",
"*",
"records",
")",
":",
"if",
"not",
"records",
":",
"raise",
"TypeError",
"(",
"'Must provide at least one record'",
")",
"if",
"any",
"(",
"not",
"isinstance",
"(",
"r",
",",
"dict",
")",
"for",
"r",
"in",
"records",
")",
":",
"raise",
"TypeError",
"(",
"'New records must be provided as dicts'",
")",
"# Create local records from factory for initial full validation",
"new_records",
"=",
"[",
"]",
"for",
"record_data",
"in",
"records",
":",
"record",
"=",
"record_factory",
"(",
"self",
".",
"_app",
",",
"record_data",
")",
"record",
".",
"validate",
"(",
")",
"new_records",
".",
"append",
"(",
"record",
")",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'post'",
",",
"'app/{}/record/batch'",
".",
"format",
"(",
"self",
".",
"_app",
".",
"id",
")",
",",
"json",
"=",
"[",
"r",
".",
"_raw",
"for",
"r",
"in",
"new_records",
"]",
")"
] |
Create and validate multiple records in associated app
Args:
*records (dict): One or more dicts of new record field names and values
Notes:
Requires Swimlane 2.15+
Validates like :meth:`create`, but only sends a single request to create all provided fields, and does not
return the newly created records
Any validation failures on any of the records will abort the batch creation, not creating any new records
Does not return the newly created records
Examples:
Create 3 new records with single request
::
app.records.bulk_create(
{'Field 1': 'value 1', ...},
{'Field 1': 'value 2', ...},
{'Field 1': 'value 3', ...}
)
Raises:
swimlane.exceptions.UnknownField: If any field in any new record cannot be found
swimlane.exceptions.ValidationError: If any field in any new record fails validation
TypeError: If no dict of fields was provided, or any provided argument is not a dict
|
[
"Create",
"and",
"validate",
"multiple",
"records",
"in",
"associated",
"app"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/record.py#L146-L198
|
7,272
|
swimlane/swimlane-python
|
swimlane/core/fields/list.py
|
_ListFieldCursor._validate_list
|
def _validate_list(self, target):
"""Validate a list against field validation rules"""
# Check list length restrictions
min_items = self._field.field_definition.get('minItems')
max_items = self._field.field_definition.get('maxItems')
if min_items is not None:
if len(target) < min_items:
raise ValidationError(
self._record,
"Field '{}' must have a minimum of {} item(s)".format(self._field.name, min_items)
)
if max_items is not None:
if len(target) > max_items:
raise ValidationError(
self._record,
"Field '{}' can only have a maximum of {} item(s)".format(self._field.name, max_items)
)
# Individual item validation
for item in target:
self._validate_item(item)
|
python
|
def _validate_list(self, target):
"""Validate a list against field validation rules"""
# Check list length restrictions
min_items = self._field.field_definition.get('minItems')
max_items = self._field.field_definition.get('maxItems')
if min_items is not None:
if len(target) < min_items:
raise ValidationError(
self._record,
"Field '{}' must have a minimum of {} item(s)".format(self._field.name, min_items)
)
if max_items is not None:
if len(target) > max_items:
raise ValidationError(
self._record,
"Field '{}' can only have a maximum of {} item(s)".format(self._field.name, max_items)
)
# Individual item validation
for item in target:
self._validate_item(item)
|
[
"def",
"_validate_list",
"(",
"self",
",",
"target",
")",
":",
"# Check list length restrictions",
"min_items",
"=",
"self",
".",
"_field",
".",
"field_definition",
".",
"get",
"(",
"'minItems'",
")",
"max_items",
"=",
"self",
".",
"_field",
".",
"field_definition",
".",
"get",
"(",
"'maxItems'",
")",
"if",
"min_items",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"target",
")",
"<",
"min_items",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"_record",
",",
"\"Field '{}' must have a minimum of {} item(s)\"",
".",
"format",
"(",
"self",
".",
"_field",
".",
"name",
",",
"min_items",
")",
")",
"if",
"max_items",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"target",
")",
">",
"max_items",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"_record",
",",
"\"Field '{}' can only have a maximum of {} item(s)\"",
".",
"format",
"(",
"self",
".",
"_field",
".",
"name",
",",
"max_items",
")",
")",
"# Individual item validation",
"for",
"item",
"in",
"target",
":",
"self",
".",
"_validate_item",
"(",
"item",
")"
] |
Validate a list against field validation rules
|
[
"Validate",
"a",
"list",
"against",
"field",
"validation",
"rules"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/list.py#L18-L40
|
7,273
|
swimlane/swimlane-python
|
swimlane/core/fields/list.py
|
ListField.set_swimlane
|
def set_swimlane(self, value):
"""Convert from list of dicts with values to list of values
Cache list items with their ID pairs to restore existing IDs to unmodified values to prevent workflow
evaluating on each save for any already existing values
"""
value = value or []
self._initial_value_to_ids_map = defaultdict(list)
for item in value:
self._initial_value_to_ids_map[item['value']].append(item['id'])
return super(ListField, self).set_swimlane([d['value'] for d in value])
|
python
|
def set_swimlane(self, value):
"""Convert from list of dicts with values to list of values
Cache list items with their ID pairs to restore existing IDs to unmodified values to prevent workflow
evaluating on each save for any already existing values
"""
value = value or []
self._initial_value_to_ids_map = defaultdict(list)
for item in value:
self._initial_value_to_ids_map[item['value']].append(item['id'])
return super(ListField, self).set_swimlane([d['value'] for d in value])
|
[
"def",
"set_swimlane",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"value",
"or",
"[",
"]",
"self",
".",
"_initial_value_to_ids_map",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"item",
"in",
"value",
":",
"self",
".",
"_initial_value_to_ids_map",
"[",
"item",
"[",
"'value'",
"]",
"]",
".",
"append",
"(",
"item",
"[",
"'id'",
"]",
")",
"return",
"super",
"(",
"ListField",
",",
"self",
")",
".",
"set_swimlane",
"(",
"[",
"d",
"[",
"'value'",
"]",
"for",
"d",
"in",
"value",
"]",
")"
] |
Convert from list of dicts with values to list of values
Cache list items with their ID pairs to restore existing IDs to unmodified values to prevent workflow
evaluating on each save for any already existing values
|
[
"Convert",
"from",
"list",
"of",
"dicts",
"with",
"values",
"to",
"list",
"of",
"values"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/list.py#L207-L219
|
7,274
|
swimlane/swimlane-python
|
swimlane/core/fields/list.py
|
ListField.set_python
|
def set_python(self, value):
"""Validate using cursor for consistency between direct set of values vs modification of cursor values"""
if not isinstance(value, (list, type(None))):
raise ValidationError(
self.record,
"Field '{}' must be set to a list, not '{}'".format(
self.name,
value.__class__
)
)
value = value or []
self.cursor._validate_list(value)
return super(ListField, self).set_python(value)
|
python
|
def set_python(self, value):
"""Validate using cursor for consistency between direct set of values vs modification of cursor values"""
if not isinstance(value, (list, type(None))):
raise ValidationError(
self.record,
"Field '{}' must be set to a list, not '{}'".format(
self.name,
value.__class__
)
)
value = value or []
self.cursor._validate_list(value)
return super(ListField, self).set_python(value)
|
[
"def",
"set_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"\"Field '{}' must be set to a list, not '{}'\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"value",
".",
"__class__",
")",
")",
"value",
"=",
"value",
"or",
"[",
"]",
"self",
".",
"cursor",
".",
"_validate_list",
"(",
"value",
")",
"return",
"super",
"(",
"ListField",
",",
"self",
")",
".",
"set_python",
"(",
"value",
")"
] |
Validate using cursor for consistency between direct set of values vs modification of cursor values
|
[
"Validate",
"using",
"cursor",
"for",
"consistency",
"between",
"direct",
"set",
"of",
"values",
"vs",
"modification",
"of",
"cursor",
"values"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/list.py#L221-L233
|
7,275
|
swimlane/swimlane-python
|
swimlane/core/fields/list.py
|
ListField.cast_to_swimlane
|
def cast_to_swimlane(self, value):
"""Restore swimlane format, attempting to keep initial IDs for any previously existing values"""
value = super(ListField, self).cast_to_swimlane(value)
if not value:
return None
# Copy initial values to pop IDs out as each value is hydrated back to server format, without modifying initial
# cache of value -> list(ids) map
value_ids = deepcopy(self._initial_value_to_ids_map)
return [self._build_list_item(item, value_ids[item].pop(0) if value_ids[item] else None) for item in value]
|
python
|
def cast_to_swimlane(self, value):
"""Restore swimlane format, attempting to keep initial IDs for any previously existing values"""
value = super(ListField, self).cast_to_swimlane(value)
if not value:
return None
# Copy initial values to pop IDs out as each value is hydrated back to server format, without modifying initial
# cache of value -> list(ids) map
value_ids = deepcopy(self._initial_value_to_ids_map)
return [self._build_list_item(item, value_ids[item].pop(0) if value_ids[item] else None) for item in value]
|
[
"def",
"cast_to_swimlane",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
"ListField",
",",
"self",
")",
".",
"cast_to_swimlane",
"(",
"value",
")",
"if",
"not",
"value",
":",
"return",
"None",
"# Copy initial values to pop IDs out as each value is hydrated back to server format, without modifying initial",
"# cache of value -> list(ids) map",
"value_ids",
"=",
"deepcopy",
"(",
"self",
".",
"_initial_value_to_ids_map",
")",
"return",
"[",
"self",
".",
"_build_list_item",
"(",
"item",
",",
"value_ids",
"[",
"item",
"]",
".",
"pop",
"(",
"0",
")",
"if",
"value_ids",
"[",
"item",
"]",
"else",
"None",
")",
"for",
"item",
"in",
"value",
"]"
] |
Restore swimlane format, attempting to keep initial IDs for any previously existing values
|
[
"Restore",
"swimlane",
"format",
"attempting",
"to",
"keep",
"initial",
"IDs",
"for",
"any",
"previously",
"existing",
"values"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/list.py#L235-L246
|
7,276
|
swimlane/swimlane-python
|
swimlane/core/fields/base/multiselect.py
|
MultiSelectCursor.select
|
def select(self, element):
"""Add an element to the set of selected elements
Proxy to internal set.add and sync field
"""
self._field.validate_value(element)
self._elements.add(element)
self._sync_field()
|
python
|
def select(self, element):
"""Add an element to the set of selected elements
Proxy to internal set.add and sync field
"""
self._field.validate_value(element)
self._elements.add(element)
self._sync_field()
|
[
"def",
"select",
"(",
"self",
",",
"element",
")",
":",
"self",
".",
"_field",
".",
"validate_value",
"(",
"element",
")",
"self",
".",
"_elements",
".",
"add",
"(",
"element",
")",
"self",
".",
"_sync_field",
"(",
")"
] |
Add an element to the set of selected elements
Proxy to internal set.add and sync field
|
[
"Add",
"an",
"element",
"to",
"the",
"set",
"of",
"selected",
"elements",
"Proxy",
"to",
"internal",
"set",
".",
"add",
"and",
"sync",
"field"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/multiselect.py#L17-L24
|
7,277
|
swimlane/swimlane-python
|
swimlane/core/fields/base/multiselect.py
|
MultiSelectField.get_python
|
def get_python(self):
"""Only return cursor instance if configured for multiselect"""
if self.multiselect:
return super(MultiSelectField, self).get_python()
return self._get()
|
python
|
def get_python(self):
"""Only return cursor instance if configured for multiselect"""
if self.multiselect:
return super(MultiSelectField, self).get_python()
return self._get()
|
[
"def",
"get_python",
"(",
"self",
")",
":",
"if",
"self",
".",
"multiselect",
":",
"return",
"super",
"(",
"MultiSelectField",
",",
"self",
")",
".",
"get_python",
"(",
")",
"return",
"self",
".",
"_get",
"(",
")"
] |
Only return cursor instance if configured for multiselect
|
[
"Only",
"return",
"cursor",
"instance",
"if",
"configured",
"for",
"multiselect"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/multiselect.py#L40-L45
|
7,278
|
swimlane/swimlane-python
|
swimlane/core/fields/base/multiselect.py
|
MultiSelectField.get_swimlane
|
def get_swimlane(self):
"""Handle multi-select and single-select modes"""
if self.multiselect:
value = self._get()
children = []
if value:
for child in value:
children.append(self.cast_to_swimlane(child))
return children
return None
return super(MultiSelectField, self).get_swimlane()
|
python
|
def get_swimlane(self):
"""Handle multi-select and single-select modes"""
if self.multiselect:
value = self._get()
children = []
if value:
for child in value:
children.append(self.cast_to_swimlane(child))
return children
return None
return super(MultiSelectField, self).get_swimlane()
|
[
"def",
"get_swimlane",
"(",
"self",
")",
":",
"if",
"self",
".",
"multiselect",
":",
"value",
"=",
"self",
".",
"_get",
"(",
")",
"children",
"=",
"[",
"]",
"if",
"value",
":",
"for",
"child",
"in",
"value",
":",
"children",
".",
"append",
"(",
"self",
".",
"cast_to_swimlane",
"(",
"child",
")",
")",
"return",
"children",
"return",
"None",
"return",
"super",
"(",
"MultiSelectField",
",",
"self",
")",
".",
"get_swimlane",
"(",
")"
] |
Handle multi-select and single-select modes
|
[
"Handle",
"multi",
"-",
"select",
"and",
"single",
"-",
"select",
"modes"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/multiselect.py#L47-L58
|
7,279
|
swimlane/swimlane-python
|
swimlane/core/fields/base/multiselect.py
|
MultiSelectField.set_python
|
def set_python(self, value):
"""Override to remove key from raw data when empty to work with server 2.16+ validation"""
if self.multiselect:
value = value or []
elements = []
for element in value:
self.validate_value(element)
elements.append(element)
value = elements
else:
self.validate_value(value)
self._set(value)
|
python
|
def set_python(self, value):
"""Override to remove key from raw data when empty to work with server 2.16+ validation"""
if self.multiselect:
value = value or []
elements = []
for element in value:
self.validate_value(element)
elements.append(element)
value = elements
else:
self.validate_value(value)
self._set(value)
|
[
"def",
"set_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"multiselect",
":",
"value",
"=",
"value",
"or",
"[",
"]",
"elements",
"=",
"[",
"]",
"for",
"element",
"in",
"value",
":",
"self",
".",
"validate_value",
"(",
"element",
")",
"elements",
".",
"append",
"(",
"element",
")",
"value",
"=",
"elements",
"else",
":",
"self",
".",
"validate_value",
"(",
"value",
")",
"self",
".",
"_set",
"(",
"value",
")"
] |
Override to remove key from raw data when empty to work with server 2.16+ validation
|
[
"Override",
"to",
"remove",
"key",
"from",
"raw",
"data",
"when",
"empty",
"to",
"work",
"with",
"server",
"2",
".",
"16",
"+",
"validation"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/multiselect.py#L64-L78
|
7,280
|
swimlane/swimlane-python
|
swimlane/core/fields/base/multiselect.py
|
MultiSelectField.set_swimlane
|
def set_swimlane(self, value):
"""Cast all multi-select elements to correct internal type like single-select mode"""
if self.multiselect:
value = value or []
children = []
for child in value:
children.append(self.cast_to_python(child))
return self._set(children)
return super(MultiSelectField, self).set_swimlane(value)
|
python
|
def set_swimlane(self, value):
"""Cast all multi-select elements to correct internal type like single-select mode"""
if self.multiselect:
value = value or []
children = []
for child in value:
children.append(self.cast_to_python(child))
return self._set(children)
return super(MultiSelectField, self).set_swimlane(value)
|
[
"def",
"set_swimlane",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"multiselect",
":",
"value",
"=",
"value",
"or",
"[",
"]",
"children",
"=",
"[",
"]",
"for",
"child",
"in",
"value",
":",
"children",
".",
"append",
"(",
"self",
".",
"cast_to_python",
"(",
"child",
")",
")",
"return",
"self",
".",
"_set",
"(",
"children",
")",
"return",
"super",
"(",
"MultiSelectField",
",",
"self",
")",
".",
"set_swimlane",
"(",
"value",
")"
] |
Cast all multi-select elements to correct internal type like single-select mode
|
[
"Cast",
"all",
"multi",
"-",
"select",
"elements",
"to",
"correct",
"internal",
"type",
"like",
"single",
"-",
"select",
"mode"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/multiselect.py#L80-L91
|
7,281
|
swimlane/swimlane-python
|
swimlane/core/fields/base/multiselect.py
|
MultiSelectField.for_json
|
def for_json(self):
"""Handle multi-select vs single-select"""
if self.multiselect:
return super(MultiSelectField, self).for_json()
value = self.get_python()
if hasattr(value, 'for_json'):
return value.for_json()
return value
|
python
|
def for_json(self):
"""Handle multi-select vs single-select"""
if self.multiselect:
return super(MultiSelectField, self).for_json()
value = self.get_python()
if hasattr(value, 'for_json'):
return value.for_json()
return value
|
[
"def",
"for_json",
"(",
"self",
")",
":",
"if",
"self",
".",
"multiselect",
":",
"return",
"super",
"(",
"MultiSelectField",
",",
"self",
")",
".",
"for_json",
"(",
")",
"value",
"=",
"self",
".",
"get_python",
"(",
")",
"if",
"hasattr",
"(",
"value",
",",
"'for_json'",
")",
":",
"return",
"value",
".",
"for_json",
"(",
")",
"return",
"value"
] |
Handle multi-select vs single-select
|
[
"Handle",
"multi",
"-",
"select",
"vs",
"single",
"-",
"select"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/multiselect.py#L93-L103
|
7,282
|
swimlane/swimlane-python
|
swimlane/core/resources/record.py
|
record_factory
|
def record_factory(app, fields=None):
"""Return a temporary Record instance to be used for field validation and value parsing
Args:
app (App): Target App to create a transient Record instance for
fields (dict): Optional dict of fields and values to set on new Record instance before returning
Returns:
Record: Unsaved Record instance to be used for validation, creation, etc.
"""
# pylint: disable=line-too-long
record = Record(app, {
'$type': Record._type,
'isNew': True,
'applicationId': app.id,
'comments': {
'$type': 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collections.Generic.List`1[[Core.Models.Record.Comments, Core]], mscorlib]], mscorlib'
},
'values': {
'$type': 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib'
}
})
fields = fields or {}
for name, value in six.iteritems(fields):
record[name] = value
# Pop off fields with None value to allow for saving empty fields
copy_raw = copy.copy(record._raw)
values_dict = {}
for key, value in six.iteritems(copy_raw['values']):
if value is not None:
values_dict[key] = value
record._raw['values'] = values_dict
return record
|
python
|
def record_factory(app, fields=None):
"""Return a temporary Record instance to be used for field validation and value parsing
Args:
app (App): Target App to create a transient Record instance for
fields (dict): Optional dict of fields and values to set on new Record instance before returning
Returns:
Record: Unsaved Record instance to be used for validation, creation, etc.
"""
# pylint: disable=line-too-long
record = Record(app, {
'$type': Record._type,
'isNew': True,
'applicationId': app.id,
'comments': {
'$type': 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collections.Generic.List`1[[Core.Models.Record.Comments, Core]], mscorlib]], mscorlib'
},
'values': {
'$type': 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib'
}
})
fields = fields or {}
for name, value in six.iteritems(fields):
record[name] = value
# Pop off fields with None value to allow for saving empty fields
copy_raw = copy.copy(record._raw)
values_dict = {}
for key, value in six.iteritems(copy_raw['values']):
if value is not None:
values_dict[key] = value
record._raw['values'] = values_dict
return record
|
[
"def",
"record_factory",
"(",
"app",
",",
"fields",
"=",
"None",
")",
":",
"# pylint: disable=line-too-long",
"record",
"=",
"Record",
"(",
"app",
",",
"{",
"'$type'",
":",
"Record",
".",
"_type",
",",
"'isNew'",
":",
"True",
",",
"'applicationId'",
":",
"app",
".",
"id",
",",
"'comments'",
":",
"{",
"'$type'",
":",
"'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collections.Generic.List`1[[Core.Models.Record.Comments, Core]], mscorlib]], mscorlib'",
"}",
",",
"'values'",
":",
"{",
"'$type'",
":",
"'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib'",
"}",
"}",
")",
"fields",
"=",
"fields",
"or",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"fields",
")",
":",
"record",
"[",
"name",
"]",
"=",
"value",
"# Pop off fields with None value to allow for saving empty fields",
"copy_raw",
"=",
"copy",
".",
"copy",
"(",
"record",
".",
"_raw",
")",
"values_dict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"copy_raw",
"[",
"'values'",
"]",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"values_dict",
"[",
"key",
"]",
"=",
"value",
"record",
".",
"_raw",
"[",
"'values'",
"]",
"=",
"values_dict",
"return",
"record"
] |
Return a temporary Record instance to be used for field validation and value parsing
Args:
app (App): Target App to create a transient Record instance for
fields (dict): Optional dict of fields and values to set on new Record instance before returning
Returns:
Record: Unsaved Record instance to be used for validation, creation, etc.
|
[
"Return",
"a",
"temporary",
"Record",
"instance",
"to",
"be",
"used",
"for",
"field",
"validation",
"and",
"value",
"parsing"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/resources/record.py#L311-L347
|
7,283
|
swimlane/swimlane-python
|
swimlane/core/fields/text.py
|
TextField.set_python
|
def set_python(self, value):
"""Set field internal value from the python representation of field value"""
# hook exists to stringify before validation
# set to string if not string or unicode
if value is not None and not isinstance(value, self.supported_types) or isinstance(value, int):
value = str(value)
return super(TextField, self).set_python(value)
|
python
|
def set_python(self, value):
"""Set field internal value from the python representation of field value"""
# hook exists to stringify before validation
# set to string if not string or unicode
if value is not None and not isinstance(value, self.supported_types) or isinstance(value, int):
value = str(value)
return super(TextField, self).set_python(value)
|
[
"def",
"set_python",
"(",
"self",
",",
"value",
")",
":",
"# hook exists to stringify before validation",
"# set to string if not string or unicode",
"if",
"value",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"supported_types",
")",
"or",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"return",
"super",
"(",
"TextField",
",",
"self",
")",
".",
"set_python",
"(",
"value",
")"
] |
Set field internal value from the python representation of field value
|
[
"Set",
"field",
"internal",
"value",
"from",
"the",
"python",
"representation",
"of",
"field",
"value"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/text.py#L15-L23
|
7,284
|
swimlane/swimlane-python
|
swimlane/utils/version.py
|
compare_versions
|
def compare_versions(version_a, version_b, zerofill=False):
"""Return direction of version relative to provided version sections
Args:
version_a (str): First version to compare
version_b (str): Second version to compare
zerofill (bool): If True, treat any missing version sections as 0, otherwise ignore section. Defaults to False
Returns:
int: 0 if equal, -1 if a > b, 1 if a < b
Examples:
If a is equal to b, return 0
If a is greater than b, return -1
If a is less than b, return 1
>>> compare_versions('2', '2') == 0
>>> compare_versions('2', '1') == -1
>>> compare_versions('2', '3') == 1
If zerofill is False (default), sections not included in both versions are ignored during comparison
>>> compare_versions('2.13.2', '2.13') == 0
>>> compare_versions('2.13.2-1234', '3') == 1
If zerofill is True, any sections in one version not included in other version are set to 0
>>> compare_versions('2.13.2', '2.13', True) == -1
>>> compare_versions('2.13.2-1234', '2.13.2', True) == -1
>>> compare_versions('2.13.2', '2.13.2', True) == 0
"""
a_sections = list((int(match) for match in re.findall(r'\d+', version_a)))
b_sections = list((int(match) for match in re.findall(r'\d+', version_b)))
if zerofill:
max_sections = max([len(a_sections), len(b_sections)])
a_sections += [0 for _ in range(max(max_sections - len(a_sections), 0))]
b_sections += [0 for _ in range(max(max_sections - len(b_sections), 0))]
else:
min_sections = min([len(a_sections), len(b_sections)])
a_sections = a_sections[:min_sections]
b_sections = b_sections[:min_sections]
return (b_sections > a_sections) - (b_sections < a_sections)
|
python
|
def compare_versions(version_a, version_b, zerofill=False):
"""Return direction of version relative to provided version sections
Args:
version_a (str): First version to compare
version_b (str): Second version to compare
zerofill (bool): If True, treat any missing version sections as 0, otherwise ignore section. Defaults to False
Returns:
int: 0 if equal, -1 if a > b, 1 if a < b
Examples:
If a is equal to b, return 0
If a is greater than b, return -1
If a is less than b, return 1
>>> compare_versions('2', '2') == 0
>>> compare_versions('2', '1') == -1
>>> compare_versions('2', '3') == 1
If zerofill is False (default), sections not included in both versions are ignored during comparison
>>> compare_versions('2.13.2', '2.13') == 0
>>> compare_versions('2.13.2-1234', '3') == 1
If zerofill is True, any sections in one version not included in other version are set to 0
>>> compare_versions('2.13.2', '2.13', True) == -1
>>> compare_versions('2.13.2-1234', '2.13.2', True) == -1
>>> compare_versions('2.13.2', '2.13.2', True) == 0
"""
a_sections = list((int(match) for match in re.findall(r'\d+', version_a)))
b_sections = list((int(match) for match in re.findall(r'\d+', version_b)))
if zerofill:
max_sections = max([len(a_sections), len(b_sections)])
a_sections += [0 for _ in range(max(max_sections - len(a_sections), 0))]
b_sections += [0 for _ in range(max(max_sections - len(b_sections), 0))]
else:
min_sections = min([len(a_sections), len(b_sections)])
a_sections = a_sections[:min_sections]
b_sections = b_sections[:min_sections]
return (b_sections > a_sections) - (b_sections < a_sections)
|
[
"def",
"compare_versions",
"(",
"version_a",
",",
"version_b",
",",
"zerofill",
"=",
"False",
")",
":",
"a_sections",
"=",
"list",
"(",
"(",
"int",
"(",
"match",
")",
"for",
"match",
"in",
"re",
".",
"findall",
"(",
"r'\\d+'",
",",
"version_a",
")",
")",
")",
"b_sections",
"=",
"list",
"(",
"(",
"int",
"(",
"match",
")",
"for",
"match",
"in",
"re",
".",
"findall",
"(",
"r'\\d+'",
",",
"version_b",
")",
")",
")",
"if",
"zerofill",
":",
"max_sections",
"=",
"max",
"(",
"[",
"len",
"(",
"a_sections",
")",
",",
"len",
"(",
"b_sections",
")",
"]",
")",
"a_sections",
"+=",
"[",
"0",
"for",
"_",
"in",
"range",
"(",
"max",
"(",
"max_sections",
"-",
"len",
"(",
"a_sections",
")",
",",
"0",
")",
")",
"]",
"b_sections",
"+=",
"[",
"0",
"for",
"_",
"in",
"range",
"(",
"max",
"(",
"max_sections",
"-",
"len",
"(",
"b_sections",
")",
",",
"0",
")",
")",
"]",
"else",
":",
"min_sections",
"=",
"min",
"(",
"[",
"len",
"(",
"a_sections",
")",
",",
"len",
"(",
"b_sections",
")",
"]",
")",
"a_sections",
"=",
"a_sections",
"[",
":",
"min_sections",
"]",
"b_sections",
"=",
"b_sections",
"[",
":",
"min_sections",
"]",
"return",
"(",
"b_sections",
">",
"a_sections",
")",
"-",
"(",
"b_sections",
"<",
"a_sections",
")"
] |
Return direction of version relative to provided version sections
Args:
version_a (str): First version to compare
version_b (str): Second version to compare
zerofill (bool): If True, treat any missing version sections as 0, otherwise ignore section. Defaults to False
Returns:
int: 0 if equal, -1 if a > b, 1 if a < b
Examples:
If a is equal to b, return 0
If a is greater than b, return -1
If a is less than b, return 1
>>> compare_versions('2', '2') == 0
>>> compare_versions('2', '1') == -1
>>> compare_versions('2', '3') == 1
If zerofill is False (default), sections not included in both versions are ignored during comparison
>>> compare_versions('2.13.2', '2.13') == 0
>>> compare_versions('2.13.2-1234', '3') == 1
If zerofill is True, any sections in one version not included in other version are set to 0
>>> compare_versions('2.13.2', '2.13', True) == -1
>>> compare_versions('2.13.2-1234', '2.13.2', True) == -1
>>> compare_versions('2.13.2', '2.13.2', True) == 0
|
[
"Return",
"direction",
"of",
"version",
"relative",
"to",
"provided",
"version",
"sections"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/utils/version.py#L9-L56
|
7,285
|
swimlane/swimlane-python
|
swimlane/utils/version.py
|
requires_swimlane_version
|
def requires_swimlane_version(min_version=None, max_version=None):
"""Decorator for SwimlaneResolver methods verifying Swimlane server build version is within a given inclusive range
Raises:
InvalidVersion: Raised before decorated method call if Swimlane server version is out of provided range
ValueError: If neither min_version or max_version were provided, or if those values conflict (2.15 < 2.14)
"""
if min_version is None and max_version is None:
raise ValueError('Must provide either min_version, max_version, or both')
if min_version and max_version and compare_versions(min_version, max_version) < 0:
raise ValueError('min_version must be <= max_version ({}, {})'.format(min_version, max_version))
def decorator(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
swimlane = self._swimlane
if min_version and compare_versions(min_version, swimlane.build_version, True) < 0:
raise InvalidSwimlaneBuildVersion(swimlane, min_version, max_version)
if max_version and compare_versions(swimlane.build_version, max_version, True) < 0:
raise InvalidSwimlaneBuildVersion(swimlane, min_version, max_version)
return func(self, *args, **kwargs)
return wrapper
return decorator
|
python
|
def requires_swimlane_version(min_version=None, max_version=None):
"""Decorator for SwimlaneResolver methods verifying Swimlane server build version is within a given inclusive range
Raises:
InvalidVersion: Raised before decorated method call if Swimlane server version is out of provided range
ValueError: If neither min_version or max_version were provided, or if those values conflict (2.15 < 2.14)
"""
if min_version is None and max_version is None:
raise ValueError('Must provide either min_version, max_version, or both')
if min_version and max_version and compare_versions(min_version, max_version) < 0:
raise ValueError('min_version must be <= max_version ({}, {})'.format(min_version, max_version))
def decorator(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
swimlane = self._swimlane
if min_version and compare_versions(min_version, swimlane.build_version, True) < 0:
raise InvalidSwimlaneBuildVersion(swimlane, min_version, max_version)
if max_version and compare_versions(swimlane.build_version, max_version, True) < 0:
raise InvalidSwimlaneBuildVersion(swimlane, min_version, max_version)
return func(self, *args, **kwargs)
return wrapper
return decorator
|
[
"def",
"requires_swimlane_version",
"(",
"min_version",
"=",
"None",
",",
"max_version",
"=",
"None",
")",
":",
"if",
"min_version",
"is",
"None",
"and",
"max_version",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Must provide either min_version, max_version, or both'",
")",
"if",
"min_version",
"and",
"max_version",
"and",
"compare_versions",
"(",
"min_version",
",",
"max_version",
")",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'min_version must be <= max_version ({}, {})'",
".",
"format",
"(",
"min_version",
",",
"max_version",
")",
")",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"swimlane",
"=",
"self",
".",
"_swimlane",
"if",
"min_version",
"and",
"compare_versions",
"(",
"min_version",
",",
"swimlane",
".",
"build_version",
",",
"True",
")",
"<",
"0",
":",
"raise",
"InvalidSwimlaneBuildVersion",
"(",
"swimlane",
",",
"min_version",
",",
"max_version",
")",
"if",
"max_version",
"and",
"compare_versions",
"(",
"swimlane",
".",
"build_version",
",",
"max_version",
",",
"True",
")",
"<",
"0",
":",
"raise",
"InvalidSwimlaneBuildVersion",
"(",
"swimlane",
",",
"min_version",
",",
"max_version",
")",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper",
"return",
"decorator"
] |
Decorator for SwimlaneResolver methods verifying Swimlane server build version is within a given inclusive range
Raises:
InvalidVersion: Raised before decorated method call if Swimlane server version is out of provided range
ValueError: If neither min_version or max_version were provided, or if those values conflict (2.15 < 2.14)
|
[
"Decorator",
"for",
"SwimlaneResolver",
"methods",
"verifying",
"Swimlane",
"server",
"build",
"version",
"is",
"within",
"a",
"given",
"inclusive",
"range"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/utils/version.py#L59-L89
|
7,286
|
swimlane/swimlane-python
|
swimlane/core/fields/base/field.py
|
Field.get_report
|
def get_report(self, value):
"""Return provided field Python value formatted for use in report filter"""
if self.multiselect:
value = value or []
children = []
for child in value:
children.append(self.cast_to_report(child))
return children
return self.cast_to_report(value)
|
python
|
def get_report(self, value):
"""Return provided field Python value formatted for use in report filter"""
if self.multiselect:
value = value or []
children = []
for child in value:
children.append(self.cast_to_report(child))
return children
return self.cast_to_report(value)
|
[
"def",
"get_report",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"multiselect",
":",
"value",
"=",
"value",
"or",
"[",
"]",
"children",
"=",
"[",
"]",
"for",
"child",
"in",
"value",
":",
"children",
".",
"append",
"(",
"self",
".",
"cast_to_report",
"(",
"child",
")",
")",
"return",
"children",
"return",
"self",
".",
"cast_to_report",
"(",
"value",
")"
] |
Return provided field Python value formatted for use in report filter
|
[
"Return",
"provided",
"field",
"Python",
"value",
"formatted",
"for",
"use",
"in",
"report",
"filter"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/field.py#L57-L68
|
7,287
|
swimlane/swimlane-python
|
swimlane/core/fields/base/field.py
|
Field.get_bulk_modify
|
def get_bulk_modify(self, value):
"""Return value in format for bulk modify"""
if self.multiselect:
value = value or []
return [self.cast_to_bulk_modify(child) for child in value]
return self.cast_to_bulk_modify(value)
|
python
|
def get_bulk_modify(self, value):
"""Return value in format for bulk modify"""
if self.multiselect:
value = value or []
return [self.cast_to_bulk_modify(child) for child in value]
return self.cast_to_bulk_modify(value)
|
[
"def",
"get_bulk_modify",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"multiselect",
":",
"value",
"=",
"value",
"or",
"[",
"]",
"return",
"[",
"self",
".",
"cast_to_bulk_modify",
"(",
"child",
")",
"for",
"child",
"in",
"value",
"]",
"return",
"self",
".",
"cast_to_bulk_modify",
"(",
"value",
")"
] |
Return value in format for bulk modify
|
[
"Return",
"value",
"in",
"format",
"for",
"bulk",
"modify"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/field.py#L70-L76
|
7,288
|
swimlane/swimlane-python
|
swimlane/core/fields/base/field.py
|
Field.validate_value
|
def validate_value(self, value):
"""Validate value is an acceptable type during set_python operation"""
if self.readonly:
raise ValidationError(self.record, "Cannot set readonly field '{}'".format(self.name))
if value not in (None, self._unset):
if self.supported_types and not isinstance(value, tuple(self.supported_types)):
raise ValidationError(self.record, "Field '{}' expects one of {}, got '{}' instead".format(
self.name,
', '.join([repr(t.__name__) for t in self.supported_types]),
type(value).__name__)
)
|
python
|
def validate_value(self, value):
"""Validate value is an acceptable type during set_python operation"""
if self.readonly:
raise ValidationError(self.record, "Cannot set readonly field '{}'".format(self.name))
if value not in (None, self._unset):
if self.supported_types and not isinstance(value, tuple(self.supported_types)):
raise ValidationError(self.record, "Field '{}' expects one of {}, got '{}' instead".format(
self.name,
', '.join([repr(t.__name__) for t in self.supported_types]),
type(value).__name__)
)
|
[
"def",
"validate_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"readonly",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"\"Cannot set readonly field '{}'\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"value",
"not",
"in",
"(",
"None",
",",
"self",
".",
"_unset",
")",
":",
"if",
"self",
".",
"supported_types",
"and",
"not",
"isinstance",
"(",
"value",
",",
"tuple",
"(",
"self",
".",
"supported_types",
")",
")",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"\"Field '{}' expects one of {}, got '{}' instead\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"', '",
".",
"join",
"(",
"[",
"repr",
"(",
"t",
".",
"__name__",
")",
"for",
"t",
"in",
"self",
".",
"supported_types",
"]",
")",
",",
"type",
"(",
"value",
")",
".",
"__name__",
")",
")"
] |
Validate value is an acceptable type during set_python operation
|
[
"Validate",
"value",
"is",
"an",
"acceptable",
"type",
"during",
"set_python",
"operation"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/field.py#L101-L111
|
7,289
|
swimlane/swimlane-python
|
swimlane/core/fields/base/field.py
|
Field._set
|
def _set(self, value):
"""Default setter used for both representations unless overridden"""
self._value = value
self.record._raw['values'][self.id] = self.get_swimlane()
|
python
|
def _set(self, value):
"""Default setter used for both representations unless overridden"""
self._value = value
self.record._raw['values'][self.id] = self.get_swimlane()
|
[
"def",
"_set",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_value",
"=",
"value",
"self",
".",
"record",
".",
"_raw",
"[",
"'values'",
"]",
"[",
"self",
".",
"id",
"]",
"=",
"self",
".",
"get_swimlane",
"(",
")"
] |
Default setter used for both representations unless overridden
|
[
"Default",
"setter",
"used",
"for",
"both",
"representations",
"unless",
"overridden"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/field.py#L113-L116
|
7,290
|
swimlane/swimlane-python
|
swimlane/core/fields/__init__.py
|
resolve_field_class
|
def resolve_field_class(field_definition):
"""Return field class most fitting of provided Swimlane field definition"""
try:
return _FIELD_TYPE_MAP[field_definition['$type']]
except KeyError as error:
error.message = 'No field available to handle Swimlane $type "{}"'.format(field_definition)
raise
|
python
|
def resolve_field_class(field_definition):
"""Return field class most fitting of provided Swimlane field definition"""
try:
return _FIELD_TYPE_MAP[field_definition['$type']]
except KeyError as error:
error.message = 'No field available to handle Swimlane $type "{}"'.format(field_definition)
raise
|
[
"def",
"resolve_field_class",
"(",
"field_definition",
")",
":",
"try",
":",
"return",
"_FIELD_TYPE_MAP",
"[",
"field_definition",
"[",
"'$type'",
"]",
"]",
"except",
"KeyError",
"as",
"error",
":",
"error",
".",
"message",
"=",
"'No field available to handle Swimlane $type \"{}\"'",
".",
"format",
"(",
"field_definition",
")",
"raise"
] |
Return field class most fitting of provided Swimlane field definition
|
[
"Return",
"field",
"class",
"most",
"fitting",
"of",
"provided",
"Swimlane",
"field",
"definition"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/__init__.py#L37-L43
|
7,291
|
swimlane/swimlane-python
|
swimlane/core/cache.py
|
get_cache_index_key
|
def get_cache_index_key(resource):
"""Return a usable cache lookup key for an already initialized resource
Args:
resource (APIResource|tuple): APIResource instance or 3-length tuple key returned from this function
Raises:
TypeError: If resource is not an APIResource instance or acceptable 3-length tuple cache key
"""
if isinstance(resource, APIResource):
attr, attr_value = list(resource.get_cache_index_keys().items())[0]
key = (type(resource), attr, attr_value)
else:
key = tuple(resource)
if len(key) != 3:
raise TypeError('Cache key must be tuple of (class, key, value), got `{!r}` instead'.format(key))
if not issubclass(key[0], APIResource):
raise TypeError('First value of cache key must be a subclass of APIResource, got `{!r}` instead'.format(key[0]))
return key
|
python
|
def get_cache_index_key(resource):
"""Return a usable cache lookup key for an already initialized resource
Args:
resource (APIResource|tuple): APIResource instance or 3-length tuple key returned from this function
Raises:
TypeError: If resource is not an APIResource instance or acceptable 3-length tuple cache key
"""
if isinstance(resource, APIResource):
attr, attr_value = list(resource.get_cache_index_keys().items())[0]
key = (type(resource), attr, attr_value)
else:
key = tuple(resource)
if len(key) != 3:
raise TypeError('Cache key must be tuple of (class, key, value), got `{!r}` instead'.format(key))
if not issubclass(key[0], APIResource):
raise TypeError('First value of cache key must be a subclass of APIResource, got `{!r}` instead'.format(key[0]))
return key
|
[
"def",
"get_cache_index_key",
"(",
"resource",
")",
":",
"if",
"isinstance",
"(",
"resource",
",",
"APIResource",
")",
":",
"attr",
",",
"attr_value",
"=",
"list",
"(",
"resource",
".",
"get_cache_index_keys",
"(",
")",
".",
"items",
"(",
")",
")",
"[",
"0",
"]",
"key",
"=",
"(",
"type",
"(",
"resource",
")",
",",
"attr",
",",
"attr_value",
")",
"else",
":",
"key",
"=",
"tuple",
"(",
"resource",
")",
"if",
"len",
"(",
"key",
")",
"!=",
"3",
":",
"raise",
"TypeError",
"(",
"'Cache key must be tuple of (class, key, value), got `{!r}` instead'",
".",
"format",
"(",
"key",
")",
")",
"if",
"not",
"issubclass",
"(",
"key",
"[",
"0",
"]",
",",
"APIResource",
")",
":",
"raise",
"TypeError",
"(",
"'First value of cache key must be a subclass of APIResource, got `{!r}` instead'",
".",
"format",
"(",
"key",
"[",
"0",
"]",
")",
")",
"return",
"key"
] |
Return a usable cache lookup key for an already initialized resource
Args:
resource (APIResource|tuple): APIResource instance or 3-length tuple key returned from this function
Raises:
TypeError: If resource is not an APIResource instance or acceptable 3-length tuple cache key
|
[
"Return",
"a",
"usable",
"cache",
"lookup",
"key",
"for",
"an",
"already",
"initialized",
"resource"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/cache.py#L106-L127
|
7,292
|
swimlane/swimlane-python
|
swimlane/core/cache.py
|
check_cache
|
def check_cache(resource_type):
"""Decorator for adapter methods to check cache for resource before normally sending requests to retrieve data
Only works with single kwargs, almost always used with @one_of_keyword_only decorator
Args:
resource_type (type(APIResource)): Subclass of APIResource of cache to be checked when called
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
adapter = args[0]
key, val = list(kwargs.items())[0]
except IndexError:
logger.warning("Couldn't generate full index key, skipping cache")
else:
index_key = (resource_type, key, val)
try:
cached_record = adapter._swimlane.resources_cache[index_key]
except KeyError:
logger.debug('Cache miss: `{!r}`'.format(index_key))
else:
logger.debug('Cache hit: `{!r}`'.format(cached_record))
return cached_record
# Fallback to default function call
return func(*args, **kwargs)
return wrapper
return decorator
|
python
|
def check_cache(resource_type):
"""Decorator for adapter methods to check cache for resource before normally sending requests to retrieve data
Only works with single kwargs, almost always used with @one_of_keyword_only decorator
Args:
resource_type (type(APIResource)): Subclass of APIResource of cache to be checked when called
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
adapter = args[0]
key, val = list(kwargs.items())[0]
except IndexError:
logger.warning("Couldn't generate full index key, skipping cache")
else:
index_key = (resource_type, key, val)
try:
cached_record = adapter._swimlane.resources_cache[index_key]
except KeyError:
logger.debug('Cache miss: `{!r}`'.format(index_key))
else:
logger.debug('Cache hit: `{!r}`'.format(cached_record))
return cached_record
# Fallback to default function call
return func(*args, **kwargs)
return wrapper
return decorator
|
[
"def",
"check_cache",
"(",
"resource_type",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"adapter",
"=",
"args",
"[",
"0",
"]",
"key",
",",
"val",
"=",
"list",
"(",
"kwargs",
".",
"items",
"(",
")",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"logger",
".",
"warning",
"(",
"\"Couldn't generate full index key, skipping cache\"",
")",
"else",
":",
"index_key",
"=",
"(",
"resource_type",
",",
"key",
",",
"val",
")",
"try",
":",
"cached_record",
"=",
"adapter",
".",
"_swimlane",
".",
"resources_cache",
"[",
"index_key",
"]",
"except",
"KeyError",
":",
"logger",
".",
"debug",
"(",
"'Cache miss: `{!r}`'",
".",
"format",
"(",
"index_key",
")",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Cache hit: `{!r}`'",
".",
"format",
"(",
"cached_record",
")",
")",
"return",
"cached_record",
"# Fallback to default function call",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper",
"return",
"decorator"
] |
Decorator for adapter methods to check cache for resource before normally sending requests to retrieve data
Only works with single kwargs, almost always used with @one_of_keyword_only decorator
Args:
resource_type (type(APIResource)): Subclass of APIResource of cache to be checked when called
|
[
"Decorator",
"for",
"adapter",
"methods",
"to",
"check",
"cache",
"for",
"resource",
"before",
"normally",
"sending",
"requests",
"to",
"retrieve",
"data"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/cache.py#L130-L162
|
7,293
|
swimlane/swimlane-python
|
swimlane/core/cache.py
|
ResourcesCache.cache
|
def cache(self, resource):
"""Insert a resource instance into appropriate resource cache"""
if not isinstance(resource, APIResource):
raise TypeError('Cannot cache `{!r}`, can only cache APIResource instances'.format(resource))
# Disable inserts to cache when disabled
if self.__cache_max_size == 0:
return
try:
cache_internal_key = resource.get_cache_internal_key()
cache_index_keys = resource.get_cache_index_keys().items()
except NotImplementedError:
logger.warning(
'Not caching `{!r}`, resource did not provide all necessary cache details'.format(resource)
)
else:
resource_type = type(resource)
for key, value in cache_index_keys:
self.__cache_index_key_map[(resource_type, key, value)] = cache_internal_key
self.__caches[resource_type][cache_internal_key] = resource
logger.debug('Cached `{!r}`'.format(resource))
|
python
|
def cache(self, resource):
"""Insert a resource instance into appropriate resource cache"""
if not isinstance(resource, APIResource):
raise TypeError('Cannot cache `{!r}`, can only cache APIResource instances'.format(resource))
# Disable inserts to cache when disabled
if self.__cache_max_size == 0:
return
try:
cache_internal_key = resource.get_cache_internal_key()
cache_index_keys = resource.get_cache_index_keys().items()
except NotImplementedError:
logger.warning(
'Not caching `{!r}`, resource did not provide all necessary cache details'.format(resource)
)
else:
resource_type = type(resource)
for key, value in cache_index_keys:
self.__cache_index_key_map[(resource_type, key, value)] = cache_internal_key
self.__caches[resource_type][cache_internal_key] = resource
logger.debug('Cached `{!r}`'.format(resource))
|
[
"def",
"cache",
"(",
"self",
",",
"resource",
")",
":",
"if",
"not",
"isinstance",
"(",
"resource",
",",
"APIResource",
")",
":",
"raise",
"TypeError",
"(",
"'Cannot cache `{!r}`, can only cache APIResource instances'",
".",
"format",
"(",
"resource",
")",
")",
"# Disable inserts to cache when disabled",
"if",
"self",
".",
"__cache_max_size",
"==",
"0",
":",
"return",
"try",
":",
"cache_internal_key",
"=",
"resource",
".",
"get_cache_internal_key",
"(",
")",
"cache_index_keys",
"=",
"resource",
".",
"get_cache_index_keys",
"(",
")",
".",
"items",
"(",
")",
"except",
"NotImplementedError",
":",
"logger",
".",
"warning",
"(",
"'Not caching `{!r}`, resource did not provide all necessary cache details'",
".",
"format",
"(",
"resource",
")",
")",
"else",
":",
"resource_type",
"=",
"type",
"(",
"resource",
")",
"for",
"key",
",",
"value",
"in",
"cache_index_keys",
":",
"self",
".",
"__cache_index_key_map",
"[",
"(",
"resource_type",
",",
"key",
",",
"value",
")",
"]",
"=",
"cache_internal_key",
"self",
".",
"__caches",
"[",
"resource_type",
"]",
"[",
"cache_internal_key",
"]",
"=",
"resource",
"logger",
".",
"debug",
"(",
"'Cached `{!r}`'",
".",
"format",
"(",
"resource",
")",
")"
] |
Insert a resource instance into appropriate resource cache
|
[
"Insert",
"a",
"resource",
"instance",
"into",
"appropriate",
"resource",
"cache"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/cache.py#L70-L94
|
7,294
|
swimlane/swimlane-python
|
swimlane/core/cache.py
|
ResourcesCache.clear
|
def clear(self, *resource_types):
"""Clear cache for each provided APIResource class, or all resources if no classes are provided"""
resource_types = resource_types or tuple(self.__caches.keys())
for cls in resource_types:
# Clear and delete cache instances to guarantee no lingering references
self.__caches[cls].clear()
del self.__caches[cls]
|
python
|
def clear(self, *resource_types):
"""Clear cache for each provided APIResource class, or all resources if no classes are provided"""
resource_types = resource_types or tuple(self.__caches.keys())
for cls in resource_types:
# Clear and delete cache instances to guarantee no lingering references
self.__caches[cls].clear()
del self.__caches[cls]
|
[
"def",
"clear",
"(",
"self",
",",
"*",
"resource_types",
")",
":",
"resource_types",
"=",
"resource_types",
"or",
"tuple",
"(",
"self",
".",
"__caches",
".",
"keys",
"(",
")",
")",
"for",
"cls",
"in",
"resource_types",
":",
"# Clear and delete cache instances to guarantee no lingering references",
"self",
".",
"__caches",
"[",
"cls",
"]",
".",
"clear",
"(",
")",
"del",
"self",
".",
"__caches",
"[",
"cls",
"]"
] |
Clear cache for each provided APIResource class, or all resources if no classes are provided
|
[
"Clear",
"cache",
"for",
"each",
"provided",
"APIResource",
"class",
"or",
"all",
"resources",
"if",
"no",
"classes",
"are",
"provided"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/cache.py#L96-L103
|
7,295
|
swimlane/swimlane-python
|
swimlane/core/fields/attachment.py
|
AttachmentsField._set
|
def _set(self, value):
"""Override setter, allow clearing cursor"""
super(AttachmentsField, self)._set(value)
self._cursor = None
|
python
|
def _set(self, value):
"""Override setter, allow clearing cursor"""
super(AttachmentsField, self)._set(value)
self._cursor = None
|
[
"def",
"_set",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"AttachmentsField",
",",
"self",
")",
".",
"_set",
"(",
"value",
")",
"self",
".",
"_cursor",
"=",
"None"
] |
Override setter, allow clearing cursor
|
[
"Override",
"setter",
"allow",
"clearing",
"cursor"
] |
588fc503a76799bcdb5aecdf2f64a6ee05e3922d
|
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/attachment.py#L58-L61
|
7,296
|
MicroPyramid/django-mfa
|
django_mfa/views.py
|
verify_otp
|
def verify_otp(request):
"""
Verify a OTP request
"""
ctx = {}
if request.method == "POST":
verification_code = request.POST.get('verification_code')
if verification_code is None:
ctx['error_message'] = "Missing verification code."
else:
otp_ = UserOTP.objects.get(user=request.user)
totp_ = totp.TOTP(otp_.secret_key)
is_verified = totp_.verify(verification_code)
if is_verified:
request.session['verfied_otp'] = True
response = redirect(request.POST.get("next", settings.LOGIN_REDIRECT_URL))
return update_rmb_cookie(request, response)
ctx['error_message'] = "Your code is expired or invalid."
ctx['next'] = request.GET.get('next', settings.LOGIN_REDIRECT_URL)
return render(request, 'django_mfa/login_verify.html', ctx, status=400)
|
python
|
def verify_otp(request):
"""
Verify a OTP request
"""
ctx = {}
if request.method == "POST":
verification_code = request.POST.get('verification_code')
if verification_code is None:
ctx['error_message'] = "Missing verification code."
else:
otp_ = UserOTP.objects.get(user=request.user)
totp_ = totp.TOTP(otp_.secret_key)
is_verified = totp_.verify(verification_code)
if is_verified:
request.session['verfied_otp'] = True
response = redirect(request.POST.get("next", settings.LOGIN_REDIRECT_URL))
return update_rmb_cookie(request, response)
ctx['error_message'] = "Your code is expired or invalid."
ctx['next'] = request.GET.get('next', settings.LOGIN_REDIRECT_URL)
return render(request, 'django_mfa/login_verify.html', ctx, status=400)
|
[
"def",
"verify_otp",
"(",
"request",
")",
":",
"ctx",
"=",
"{",
"}",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"verification_code",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"'verification_code'",
")",
"if",
"verification_code",
"is",
"None",
":",
"ctx",
"[",
"'error_message'",
"]",
"=",
"\"Missing verification code.\"",
"else",
":",
"otp_",
"=",
"UserOTP",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"request",
".",
"user",
")",
"totp_",
"=",
"totp",
".",
"TOTP",
"(",
"otp_",
".",
"secret_key",
")",
"is_verified",
"=",
"totp_",
".",
"verify",
"(",
"verification_code",
")",
"if",
"is_verified",
":",
"request",
".",
"session",
"[",
"'verfied_otp'",
"]",
"=",
"True",
"response",
"=",
"redirect",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"\"next\"",
",",
"settings",
".",
"LOGIN_REDIRECT_URL",
")",
")",
"return",
"update_rmb_cookie",
"(",
"request",
",",
"response",
")",
"ctx",
"[",
"'error_message'",
"]",
"=",
"\"Your code is expired or invalid.\"",
"ctx",
"[",
"'next'",
"]",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
",",
"settings",
".",
"LOGIN_REDIRECT_URL",
")",
"return",
"render",
"(",
"request",
",",
"'django_mfa/login_verify.html'",
",",
"ctx",
",",
"status",
"=",
"400",
")"
] |
Verify a OTP request
|
[
"Verify",
"a",
"OTP",
"request"
] |
7baf16297ffa8b5b4aa0b9961a889a964fcbdb39
|
https://github.com/MicroPyramid/django-mfa/blob/7baf16297ffa8b5b4aa0b9961a889a964fcbdb39/django_mfa/views.py#L142-L166
|
7,297
|
MicroPyramid/django-mfa
|
django_mfa/totp.py
|
TOTP.at
|
def at(self, for_time, counter_offset=0):
"""
Accepts either a Unix timestamp integer or a Time object.
Time objects will be adjusted to UTC automatically
@param [Time/Integer] time the time to generate an OTP for
@param [Integer] counter_offset an amount of ticks to add to the time counter
"""
if not isinstance(for_time, datetime.datetime):
for_time = datetime.datetime.fromtimestamp(int(for_time))
return self.generate_otp(self.timecode(for_time) + counter_offset)
|
python
|
def at(self, for_time, counter_offset=0):
"""
Accepts either a Unix timestamp integer or a Time object.
Time objects will be adjusted to UTC automatically
@param [Time/Integer] time the time to generate an OTP for
@param [Integer] counter_offset an amount of ticks to add to the time counter
"""
if not isinstance(for_time, datetime.datetime):
for_time = datetime.datetime.fromtimestamp(int(for_time))
return self.generate_otp(self.timecode(for_time) + counter_offset)
|
[
"def",
"at",
"(",
"self",
",",
"for_time",
",",
"counter_offset",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"for_time",
",",
"datetime",
".",
"datetime",
")",
":",
"for_time",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"for_time",
")",
")",
"return",
"self",
".",
"generate_otp",
"(",
"self",
".",
"timecode",
"(",
"for_time",
")",
"+",
"counter_offset",
")"
] |
Accepts either a Unix timestamp integer or a Time object.
Time objects will be adjusted to UTC automatically
@param [Time/Integer] time the time to generate an OTP for
@param [Integer] counter_offset an amount of ticks to add to the time counter
|
[
"Accepts",
"either",
"a",
"Unix",
"timestamp",
"integer",
"or",
"a",
"Time",
"object",
".",
"Time",
"objects",
"will",
"be",
"adjusted",
"to",
"UTC",
"automatically"
] |
7baf16297ffa8b5b4aa0b9961a889a964fcbdb39
|
https://github.com/MicroPyramid/django-mfa/blob/7baf16297ffa8b5b4aa0b9961a889a964fcbdb39/django_mfa/totp.py#L19-L28
|
7,298
|
MicroPyramid/django-mfa
|
django_mfa/totp.py
|
TOTP.verify
|
def verify(self, otp, for_time=None, valid_window=0):
"""
Verifies the OTP passed in against the current time OTP
@param [String/Integer] otp the OTP to check against
@param [Integer] valid_window extends the validity to this many counter ticks before and after the current one
"""
if for_time is None:
for_time = datetime.datetime.now()
if valid_window:
for i in range(-valid_window, valid_window + 1):
if utils.strings_equal(str(otp), str(self.at(for_time, i))):
return True
return False
return utils.strings_equal(str(otp), str(self.at(for_time)))
|
python
|
def verify(self, otp, for_time=None, valid_window=0):
"""
Verifies the OTP passed in against the current time OTP
@param [String/Integer] otp the OTP to check against
@param [Integer] valid_window extends the validity to this many counter ticks before and after the current one
"""
if for_time is None:
for_time = datetime.datetime.now()
if valid_window:
for i in range(-valid_window, valid_window + 1):
if utils.strings_equal(str(otp), str(self.at(for_time, i))):
return True
return False
return utils.strings_equal(str(otp), str(self.at(for_time)))
|
[
"def",
"verify",
"(",
"self",
",",
"otp",
",",
"for_time",
"=",
"None",
",",
"valid_window",
"=",
"0",
")",
":",
"if",
"for_time",
"is",
"None",
":",
"for_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"if",
"valid_window",
":",
"for",
"i",
"in",
"range",
"(",
"-",
"valid_window",
",",
"valid_window",
"+",
"1",
")",
":",
"if",
"utils",
".",
"strings_equal",
"(",
"str",
"(",
"otp",
")",
",",
"str",
"(",
"self",
".",
"at",
"(",
"for_time",
",",
"i",
")",
")",
")",
":",
"return",
"True",
"return",
"False",
"return",
"utils",
".",
"strings_equal",
"(",
"str",
"(",
"otp",
")",
",",
"str",
"(",
"self",
".",
"at",
"(",
"for_time",
")",
")",
")"
] |
Verifies the OTP passed in against the current time OTP
@param [String/Integer] otp the OTP to check against
@param [Integer] valid_window extends the validity to this many counter ticks before and after the current one
|
[
"Verifies",
"the",
"OTP",
"passed",
"in",
"against",
"the",
"current",
"time",
"OTP"
] |
7baf16297ffa8b5b4aa0b9961a889a964fcbdb39
|
https://github.com/MicroPyramid/django-mfa/blob/7baf16297ffa8b5b4aa0b9961a889a964fcbdb39/django_mfa/totp.py#L37-L52
|
7,299
|
MicroPyramid/django-mfa
|
django_mfa/totp.py
|
TOTP.provisioning_uri
|
def provisioning_uri(self, name, issuer_name=None):
"""
Returns the provisioning URI for the OTP
This can then be encoded in a QR Code and used
to provision the Google Authenticator app
@param [String] name of the account
@return [String] provisioning uri
"""
return utils.build_uri(self.secret, name, issuer_name=issuer_name)
|
python
|
def provisioning_uri(self, name, issuer_name=None):
"""
Returns the provisioning URI for the OTP
This can then be encoded in a QR Code and used
to provision the Google Authenticator app
@param [String] name of the account
@return [String] provisioning uri
"""
return utils.build_uri(self.secret, name, issuer_name=issuer_name)
|
[
"def",
"provisioning_uri",
"(",
"self",
",",
"name",
",",
"issuer_name",
"=",
"None",
")",
":",
"return",
"utils",
".",
"build_uri",
"(",
"self",
".",
"secret",
",",
"name",
",",
"issuer_name",
"=",
"issuer_name",
")"
] |
Returns the provisioning URI for the OTP
This can then be encoded in a QR Code and used
to provision the Google Authenticator app
@param [String] name of the account
@return [String] provisioning uri
|
[
"Returns",
"the",
"provisioning",
"URI",
"for",
"the",
"OTP",
"This",
"can",
"then",
"be",
"encoded",
"in",
"a",
"QR",
"Code",
"and",
"used",
"to",
"provision",
"the",
"Google",
"Authenticator",
"app"
] |
7baf16297ffa8b5b4aa0b9961a889a964fcbdb39
|
https://github.com/MicroPyramid/django-mfa/blob/7baf16297ffa8b5b4aa0b9961a889a964fcbdb39/django_mfa/totp.py#L54-L62
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.