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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
239,200
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.create_user
|
def create_user(self, projects=None, tasks=None):
"""Create and return a new user
:param projects: the projects for the user
:type projects: list of :class:`jukeboxcore.djadapter.models.Project`
:param tasks: the tasks for the user
:type tasks: list of :class:`jukeboxcore.djadapter.models.Task`
:returns: The created user or None
:rtype: None | :class:`jukeboxcore.djadapter.models.User`
:raises: None
"""
projects = projects or []
tasks = tasks or []
dialog = UserCreatorDialog(projects=projects, tasks=tasks, parent=self)
dialog.exec_()
user = dialog.user
if user:
userdata = djitemdata.UserItemData(user)
treemodel.TreeItem(userdata, self.users_model.root)
return user
|
python
|
def create_user(self, projects=None, tasks=None):
"""Create and return a new user
:param projects: the projects for the user
:type projects: list of :class:`jukeboxcore.djadapter.models.Project`
:param tasks: the tasks for the user
:type tasks: list of :class:`jukeboxcore.djadapter.models.Task`
:returns: The created user or None
:rtype: None | :class:`jukeboxcore.djadapter.models.User`
:raises: None
"""
projects = projects or []
tasks = tasks or []
dialog = UserCreatorDialog(projects=projects, tasks=tasks, parent=self)
dialog.exec_()
user = dialog.user
if user:
userdata = djitemdata.UserItemData(user)
treemodel.TreeItem(userdata, self.users_model.root)
return user
|
[
"def",
"create_user",
"(",
"self",
",",
"projects",
"=",
"None",
",",
"tasks",
"=",
"None",
")",
":",
"projects",
"=",
"projects",
"or",
"[",
"]",
"tasks",
"=",
"tasks",
"or",
"[",
"]",
"dialog",
"=",
"UserCreatorDialog",
"(",
"projects",
"=",
"projects",
",",
"tasks",
"=",
"tasks",
",",
"parent",
"=",
"self",
")",
"dialog",
".",
"exec_",
"(",
")",
"user",
"=",
"dialog",
".",
"user",
"if",
"user",
":",
"userdata",
"=",
"djitemdata",
".",
"UserItemData",
"(",
"user",
")",
"treemodel",
".",
"TreeItem",
"(",
"userdata",
",",
"self",
".",
"users_model",
".",
"root",
")",
"return",
"user"
] |
Create and return a new user
:param projects: the projects for the user
:type projects: list of :class:`jukeboxcore.djadapter.models.Project`
:param tasks: the tasks for the user
:type tasks: list of :class:`jukeboxcore.djadapter.models.Task`
:returns: The created user or None
:rtype: None | :class:`jukeboxcore.djadapter.models.User`
:raises: None
|
[
"Create",
"and",
"return",
"a",
"new",
"user"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1426-L1445
|
239,201
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.prj_show_path
|
def prj_show_path(self, ):
"""Show the dir in the a filebrowser of the project
:returns: None
:rtype: None
:raises: None
"""
f = self.prj_path_le.text()
osinter = ostool.get_interface()
osinter.open_path(f)
|
python
|
def prj_show_path(self, ):
"""Show the dir in the a filebrowser of the project
:returns: None
:rtype: None
:raises: None
"""
f = self.prj_path_le.text()
osinter = ostool.get_interface()
osinter.open_path(f)
|
[
"def",
"prj_show_path",
"(",
"self",
",",
")",
":",
"f",
"=",
"self",
".",
"prj_path_le",
".",
"text",
"(",
")",
"osinter",
"=",
"ostool",
".",
"get_interface",
"(",
")",
"osinter",
".",
"open_path",
"(",
"f",
")"
] |
Show the dir in the a filebrowser of the project
:returns: None
:rtype: None
:raises: None
|
[
"Show",
"the",
"dir",
"in",
"the",
"a",
"filebrowser",
"of",
"the",
"project"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1534-L1543
|
239,202
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.prj_save
|
def prj_save(self):
"""Save the current project
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_prj:
return
desc = self.prj_desc_pte.toPlainText()
semester = self.prj_semester_le.text()
fps = self.prj_fps_dsb.value()
resx = self.prj_res_x_sb.value()
resy = self.prj_res_y_sb.value()
scale = self.prj_scale_cb.currentText()
self.cur_prj.description = desc
self.cur_prj.semester = semester
self.cur_prj.framerate = fps
self.cur_prj.resx = resx
self.cur_prj.resy = resy
self.cur_prj.scale = scale
self.cur_prj.save()
|
python
|
def prj_save(self):
"""Save the current project
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_prj:
return
desc = self.prj_desc_pte.toPlainText()
semester = self.prj_semester_le.text()
fps = self.prj_fps_dsb.value()
resx = self.prj_res_x_sb.value()
resy = self.prj_res_y_sb.value()
scale = self.prj_scale_cb.currentText()
self.cur_prj.description = desc
self.cur_prj.semester = semester
self.cur_prj.framerate = fps
self.cur_prj.resx = resx
self.cur_prj.resy = resy
self.cur_prj.scale = scale
self.cur_prj.save()
|
[
"def",
"prj_save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"cur_prj",
":",
"return",
"desc",
"=",
"self",
".",
"prj_desc_pte",
".",
"toPlainText",
"(",
")",
"semester",
"=",
"self",
".",
"prj_semester_le",
".",
"text",
"(",
")",
"fps",
"=",
"self",
".",
"prj_fps_dsb",
".",
"value",
"(",
")",
"resx",
"=",
"self",
".",
"prj_res_x_sb",
".",
"value",
"(",
")",
"resy",
"=",
"self",
".",
"prj_res_y_sb",
".",
"value",
"(",
")",
"scale",
"=",
"self",
".",
"prj_scale_cb",
".",
"currentText",
"(",
")",
"self",
".",
"cur_prj",
".",
"description",
"=",
"desc",
"self",
".",
"cur_prj",
".",
"semester",
"=",
"semester",
"self",
".",
"cur_prj",
".",
"framerate",
"=",
"fps",
"self",
".",
"cur_prj",
".",
"resx",
"=",
"resx",
"self",
".",
"cur_prj",
".",
"resy",
"=",
"resy",
"self",
".",
"cur_prj",
".",
"scale",
"=",
"scale",
"self",
".",
"cur_prj",
".",
"save",
"(",
")"
] |
Save the current project
:returns: None
:rtype: None
:raises: None
|
[
"Save",
"the",
"current",
"project"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1545-L1567
|
239,203
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.seq_save
|
def seq_save(self):
"""Save the current sequence
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_seq:
return
desc = self.seq_desc_pte.toPlainText()
self.cur_seq.description = desc
self.cur_seq.save()
|
python
|
def seq_save(self):
"""Save the current sequence
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_seq:
return
desc = self.seq_desc_pte.toPlainText()
self.cur_seq.description = desc
self.cur_seq.save()
|
[
"def",
"seq_save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"cur_seq",
":",
"return",
"desc",
"=",
"self",
".",
"seq_desc_pte",
".",
"toPlainText",
"(",
")",
"self",
".",
"cur_seq",
".",
"description",
"=",
"desc",
"self",
".",
"cur_seq",
".",
"save",
"(",
")"
] |
Save the current sequence
:returns: None
:rtype: None
:raises: None
|
[
"Save",
"the",
"current",
"sequence"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1569-L1581
|
239,204
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.seq_view_shot
|
def seq_view_shot(self, ):
"""View the shot that is selected in the table view of the sequence page
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_seq:
return
i = self.seq_shot_tablev.currentIndex()
item = i.internalPointer()
if item:
shot = item.internal_data()
self.view_shot(shot)
|
python
|
def seq_view_shot(self, ):
"""View the shot that is selected in the table view of the sequence page
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_seq:
return
i = self.seq_shot_tablev.currentIndex()
item = i.internalPointer()
if item:
shot = item.internal_data()
self.view_shot(shot)
|
[
"def",
"seq_view_shot",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_seq",
":",
"return",
"i",
"=",
"self",
".",
"seq_shot_tablev",
".",
"currentIndex",
"(",
")",
"item",
"=",
"i",
".",
"internalPointer",
"(",
")",
"if",
"item",
":",
"shot",
"=",
"item",
".",
"internal_data",
"(",
")",
"self",
".",
"view_shot",
"(",
"shot",
")"
] |
View the shot that is selected in the table view of the sequence page
:returns: None
:rtype: None
:raises: None
|
[
"View",
"the",
"shot",
"that",
"is",
"selected",
"in",
"the",
"table",
"view",
"of",
"the",
"sequence",
"page"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1594-L1607
|
239,205
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.view_shot
|
def view_shot(self, shot):
"""View the given shot
:param shot: the shot to view
:type shot: :class:`jukeboxcore.djadapter.models.Shot`
:returns: None
:rtype: None
:raises: None
"""
log.debug('Viewing shot %s', shot.name)
self.cur_shot = None
self.pages_tabw.setCurrentIndex(3)
self.shot_name_le.setText(shot.name)
self.shot_prj_le.setText(shot.project.name)
self.shot_seq_le.setText(shot.sequence.name)
self.shot_start_sb.setValue(shot.startframe)
self.shot_end_sb.setValue(shot.endframe)
self.shot_handle_sb.setValue(shot.handlesize)
self.shot_desc_pte.setPlainText(shot.description)
assetsrootdata = treemodel.ListItemData(["Name", "Description"])
assetsrootitem = treemodel.TreeItem(assetsrootdata)
self.shot_asset_model = treemodel.TreeModel(assetsrootitem)
self.shot_asset_treev.setModel(self.shot_asset_model)
atypes = {}
assets = shot.assets.all()
for a in assets:
atype = a.atype
atypeitem = atypes.get(atype)
if not atypeitem:
atypedata = djitemdata.AtypeItemData(atype)
atypeitem = treemodel.TreeItem(atypedata, assetsrootitem)
atypes[atype] = atypeitem
assetdata = djitemdata.AssetItemData(a)
treemodel.TreeItem(assetdata, atypeitem)
tasksrootdata = treemodel.ListItemData(["Name", "Short"])
tasksrootitem = treemodel.TreeItem(tasksrootdata)
self.shot_task_model = treemodel.TreeModel(tasksrootitem)
self.shot_task_tablev.setModel(self.shot_task_model)
tasks = shot.tasks.all()
for t in tasks:
tdata = djitemdata.TaskItemData(t)
treemodel.TreeItem(tdata, tasksrootitem)
self.cur_shot = shot
|
python
|
def view_shot(self, shot):
"""View the given shot
:param shot: the shot to view
:type shot: :class:`jukeboxcore.djadapter.models.Shot`
:returns: None
:rtype: None
:raises: None
"""
log.debug('Viewing shot %s', shot.name)
self.cur_shot = None
self.pages_tabw.setCurrentIndex(3)
self.shot_name_le.setText(shot.name)
self.shot_prj_le.setText(shot.project.name)
self.shot_seq_le.setText(shot.sequence.name)
self.shot_start_sb.setValue(shot.startframe)
self.shot_end_sb.setValue(shot.endframe)
self.shot_handle_sb.setValue(shot.handlesize)
self.shot_desc_pte.setPlainText(shot.description)
assetsrootdata = treemodel.ListItemData(["Name", "Description"])
assetsrootitem = treemodel.TreeItem(assetsrootdata)
self.shot_asset_model = treemodel.TreeModel(assetsrootitem)
self.shot_asset_treev.setModel(self.shot_asset_model)
atypes = {}
assets = shot.assets.all()
for a in assets:
atype = a.atype
atypeitem = atypes.get(atype)
if not atypeitem:
atypedata = djitemdata.AtypeItemData(atype)
atypeitem = treemodel.TreeItem(atypedata, assetsrootitem)
atypes[atype] = atypeitem
assetdata = djitemdata.AssetItemData(a)
treemodel.TreeItem(assetdata, atypeitem)
tasksrootdata = treemodel.ListItemData(["Name", "Short"])
tasksrootitem = treemodel.TreeItem(tasksrootdata)
self.shot_task_model = treemodel.TreeModel(tasksrootitem)
self.shot_task_tablev.setModel(self.shot_task_model)
tasks = shot.tasks.all()
for t in tasks:
tdata = djitemdata.TaskItemData(t)
treemodel.TreeItem(tdata, tasksrootitem)
self.cur_shot = shot
|
[
"def",
"view_shot",
"(",
"self",
",",
"shot",
")",
":",
"log",
".",
"debug",
"(",
"'Viewing shot %s'",
",",
"shot",
".",
"name",
")",
"self",
".",
"cur_shot",
"=",
"None",
"self",
".",
"pages_tabw",
".",
"setCurrentIndex",
"(",
"3",
")",
"self",
".",
"shot_name_le",
".",
"setText",
"(",
"shot",
".",
"name",
")",
"self",
".",
"shot_prj_le",
".",
"setText",
"(",
"shot",
".",
"project",
".",
"name",
")",
"self",
".",
"shot_seq_le",
".",
"setText",
"(",
"shot",
".",
"sequence",
".",
"name",
")",
"self",
".",
"shot_start_sb",
".",
"setValue",
"(",
"shot",
".",
"startframe",
")",
"self",
".",
"shot_end_sb",
".",
"setValue",
"(",
"shot",
".",
"endframe",
")",
"self",
".",
"shot_handle_sb",
".",
"setValue",
"(",
"shot",
".",
"handlesize",
")",
"self",
".",
"shot_desc_pte",
".",
"setPlainText",
"(",
"shot",
".",
"description",
")",
"assetsrootdata",
"=",
"treemodel",
".",
"ListItemData",
"(",
"[",
"\"Name\"",
",",
"\"Description\"",
"]",
")",
"assetsrootitem",
"=",
"treemodel",
".",
"TreeItem",
"(",
"assetsrootdata",
")",
"self",
".",
"shot_asset_model",
"=",
"treemodel",
".",
"TreeModel",
"(",
"assetsrootitem",
")",
"self",
".",
"shot_asset_treev",
".",
"setModel",
"(",
"self",
".",
"shot_asset_model",
")",
"atypes",
"=",
"{",
"}",
"assets",
"=",
"shot",
".",
"assets",
".",
"all",
"(",
")",
"for",
"a",
"in",
"assets",
":",
"atype",
"=",
"a",
".",
"atype",
"atypeitem",
"=",
"atypes",
".",
"get",
"(",
"atype",
")",
"if",
"not",
"atypeitem",
":",
"atypedata",
"=",
"djitemdata",
".",
"AtypeItemData",
"(",
"atype",
")",
"atypeitem",
"=",
"treemodel",
".",
"TreeItem",
"(",
"atypedata",
",",
"assetsrootitem",
")",
"atypes",
"[",
"atype",
"]",
"=",
"atypeitem",
"assetdata",
"=",
"djitemdata",
".",
"AssetItemData",
"(",
"a",
")",
"treemodel",
".",
"TreeItem",
"(",
"assetdata",
",",
"atypeitem",
")",
"tasksrootdata",
"=",
"treemodel",
".",
"ListItemData",
"(",
"[",
"\"Name\"",
",",
"\"Short\"",
"]",
")",
"tasksrootitem",
"=",
"treemodel",
".",
"TreeItem",
"(",
"tasksrootdata",
")",
"self",
".",
"shot_task_model",
"=",
"treemodel",
".",
"TreeModel",
"(",
"tasksrootitem",
")",
"self",
".",
"shot_task_tablev",
".",
"setModel",
"(",
"self",
".",
"shot_task_model",
")",
"tasks",
"=",
"shot",
".",
"tasks",
".",
"all",
"(",
")",
"for",
"t",
"in",
"tasks",
":",
"tdata",
"=",
"djitemdata",
".",
"TaskItemData",
"(",
"t",
")",
"treemodel",
".",
"TreeItem",
"(",
"tdata",
",",
"tasksrootitem",
")",
"self",
".",
"cur_shot",
"=",
"shot"
] |
View the given shot
:param shot: the shot to view
:type shot: :class:`jukeboxcore.djadapter.models.Shot`
:returns: None
:rtype: None
:raises: None
|
[
"View",
"the",
"given",
"shot"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1623-L1668
|
239,206
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.create_shot
|
def create_shot(self, sequence):
"""Create and return a new shot
:param sequence: the sequence for the shot
:type sequence: :class:`jukeboxcore.djadapter.models.Sequence`
:returns: The created shot or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Shot`
:raises: None
"""
dialog = ShotCreatorDialog(sequence=sequence, parent=self)
dialog.exec_()
shot = dialog.shot
return shot
|
python
|
def create_shot(self, sequence):
"""Create and return a new shot
:param sequence: the sequence for the shot
:type sequence: :class:`jukeboxcore.djadapter.models.Sequence`
:returns: The created shot or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Shot`
:raises: None
"""
dialog = ShotCreatorDialog(sequence=sequence, parent=self)
dialog.exec_()
shot = dialog.shot
return shot
|
[
"def",
"create_shot",
"(",
"self",
",",
"sequence",
")",
":",
"dialog",
"=",
"ShotCreatorDialog",
"(",
"sequence",
"=",
"sequence",
",",
"parent",
"=",
"self",
")",
"dialog",
".",
"exec_",
"(",
")",
"shot",
"=",
"dialog",
".",
"shot",
"return",
"shot"
] |
Create and return a new shot
:param sequence: the sequence for the shot
:type sequence: :class:`jukeboxcore.djadapter.models.Sequence`
:returns: The created shot or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Shot`
:raises: None
|
[
"Create",
"and",
"return",
"a",
"new",
"shot"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1670-L1682
|
239,207
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.create_task
|
def create_task(self, element):
"""Create a new task for the given element
:param element: the element for the task
:type element: :class:`jukeboxcore.djadapter.models.Shot` | :class:`jukeboxcore.djadapter.models.Asset`
:returns: None
:rtype: None
:raises: None
"""
dialog = TaskCreatorDialog(element=element, parent=self)
dialog.exec_()
task = dialog.task
return task
|
python
|
def create_task(self, element):
"""Create a new task for the given element
:param element: the element for the task
:type element: :class:`jukeboxcore.djadapter.models.Shot` | :class:`jukeboxcore.djadapter.models.Asset`
:returns: None
:rtype: None
:raises: None
"""
dialog = TaskCreatorDialog(element=element, parent=self)
dialog.exec_()
task = dialog.task
return task
|
[
"def",
"create_task",
"(",
"self",
",",
"element",
")",
":",
"dialog",
"=",
"TaskCreatorDialog",
"(",
"element",
"=",
"element",
",",
"parent",
"=",
"self",
")",
"dialog",
".",
"exec_",
"(",
")",
"task",
"=",
"dialog",
".",
"task",
"return",
"task"
] |
Create a new task for the given element
:param element: the element for the task
:type element: :class:`jukeboxcore.djadapter.models.Shot` | :class:`jukeboxcore.djadapter.models.Asset`
:returns: None
:rtype: None
:raises: None
|
[
"Create",
"a",
"new",
"task",
"for",
"the",
"given",
"element"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1755-L1767
|
239,208
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.view_asset
|
def view_asset(self, asset):
"""View the given asset
:param asset: the asset to view
:type asset: :class:`jukeboxcore.djadapter.models.Asset`
:returns: None
:rtype: None
:raises: None
"""
log.debug('Viewing asset %s', asset.name)
self.cur_asset = None
self.pages_tabw.setCurrentIndex(5)
name = asset.name
prj = asset.project.name
atype = asset.atype.name
desc = asset.description
self.asset_name_le.setText(name)
self.asset_prj_le.setText(prj)
self.asset_atype_le.setText(atype)
self.asset_desc_pte.setPlainText(desc)
assetsrootdata = treemodel.ListItemData(["Name", "Description"])
assetsrootitem = treemodel.TreeItem(assetsrootdata)
self.asset_asset_model = treemodel.TreeModel(assetsrootitem)
self.asset_asset_treev.setModel(self.asset_asset_model)
atypes = {}
assets = asset.assets.all()
for a in assets:
atype = a.atype
atypeitem = atypes.get(atype)
if not atypeitem:
atypedata = djitemdata.AtypeItemData(atype)
atypeitem = treemodel.TreeItem(atypedata, assetsrootitem)
atypes[atype] = atypeitem
assetdata = djitemdata.AssetItemData(a)
treemodel.TreeItem(assetdata, atypeitem)
tasksrootdata = treemodel.ListItemData(["Name", "Short"])
tasksrootitem = treemodel.TreeItem(tasksrootdata)
self.asset_task_model = treemodel.TreeModel(tasksrootitem)
self.asset_task_tablev.setModel(self.asset_task_model)
tasks = asset.tasks.all()
for t in tasks:
tdata = djitemdata.TaskItemData(t)
treemodel.TreeItem(tdata, tasksrootitem)
self.cur_asset = asset
|
python
|
def view_asset(self, asset):
"""View the given asset
:param asset: the asset to view
:type asset: :class:`jukeboxcore.djadapter.models.Asset`
:returns: None
:rtype: None
:raises: None
"""
log.debug('Viewing asset %s', asset.name)
self.cur_asset = None
self.pages_tabw.setCurrentIndex(5)
name = asset.name
prj = asset.project.name
atype = asset.atype.name
desc = asset.description
self.asset_name_le.setText(name)
self.asset_prj_le.setText(prj)
self.asset_atype_le.setText(atype)
self.asset_desc_pte.setPlainText(desc)
assetsrootdata = treemodel.ListItemData(["Name", "Description"])
assetsrootitem = treemodel.TreeItem(assetsrootdata)
self.asset_asset_model = treemodel.TreeModel(assetsrootitem)
self.asset_asset_treev.setModel(self.asset_asset_model)
atypes = {}
assets = asset.assets.all()
for a in assets:
atype = a.atype
atypeitem = atypes.get(atype)
if not atypeitem:
atypedata = djitemdata.AtypeItemData(atype)
atypeitem = treemodel.TreeItem(atypedata, assetsrootitem)
atypes[atype] = atypeitem
assetdata = djitemdata.AssetItemData(a)
treemodel.TreeItem(assetdata, atypeitem)
tasksrootdata = treemodel.ListItemData(["Name", "Short"])
tasksrootitem = treemodel.TreeItem(tasksrootdata)
self.asset_task_model = treemodel.TreeModel(tasksrootitem)
self.asset_task_tablev.setModel(self.asset_task_model)
tasks = asset.tasks.all()
for t in tasks:
tdata = djitemdata.TaskItemData(t)
treemodel.TreeItem(tdata, tasksrootitem)
self.cur_asset = asset
|
[
"def",
"view_asset",
"(",
"self",
",",
"asset",
")",
":",
"log",
".",
"debug",
"(",
"'Viewing asset %s'",
",",
"asset",
".",
"name",
")",
"self",
".",
"cur_asset",
"=",
"None",
"self",
".",
"pages_tabw",
".",
"setCurrentIndex",
"(",
"5",
")",
"name",
"=",
"asset",
".",
"name",
"prj",
"=",
"asset",
".",
"project",
".",
"name",
"atype",
"=",
"asset",
".",
"atype",
".",
"name",
"desc",
"=",
"asset",
".",
"description",
"self",
".",
"asset_name_le",
".",
"setText",
"(",
"name",
")",
"self",
".",
"asset_prj_le",
".",
"setText",
"(",
"prj",
")",
"self",
".",
"asset_atype_le",
".",
"setText",
"(",
"atype",
")",
"self",
".",
"asset_desc_pte",
".",
"setPlainText",
"(",
"desc",
")",
"assetsrootdata",
"=",
"treemodel",
".",
"ListItemData",
"(",
"[",
"\"Name\"",
",",
"\"Description\"",
"]",
")",
"assetsrootitem",
"=",
"treemodel",
".",
"TreeItem",
"(",
"assetsrootdata",
")",
"self",
".",
"asset_asset_model",
"=",
"treemodel",
".",
"TreeModel",
"(",
"assetsrootitem",
")",
"self",
".",
"asset_asset_treev",
".",
"setModel",
"(",
"self",
".",
"asset_asset_model",
")",
"atypes",
"=",
"{",
"}",
"assets",
"=",
"asset",
".",
"assets",
".",
"all",
"(",
")",
"for",
"a",
"in",
"assets",
":",
"atype",
"=",
"a",
".",
"atype",
"atypeitem",
"=",
"atypes",
".",
"get",
"(",
"atype",
")",
"if",
"not",
"atypeitem",
":",
"atypedata",
"=",
"djitemdata",
".",
"AtypeItemData",
"(",
"atype",
")",
"atypeitem",
"=",
"treemodel",
".",
"TreeItem",
"(",
"atypedata",
",",
"assetsrootitem",
")",
"atypes",
"[",
"atype",
"]",
"=",
"atypeitem",
"assetdata",
"=",
"djitemdata",
".",
"AssetItemData",
"(",
"a",
")",
"treemodel",
".",
"TreeItem",
"(",
"assetdata",
",",
"atypeitem",
")",
"tasksrootdata",
"=",
"treemodel",
".",
"ListItemData",
"(",
"[",
"\"Name\"",
",",
"\"Short\"",
"]",
")",
"tasksrootitem",
"=",
"treemodel",
".",
"TreeItem",
"(",
"tasksrootdata",
")",
"self",
".",
"asset_task_model",
"=",
"treemodel",
".",
"TreeModel",
"(",
"tasksrootitem",
")",
"self",
".",
"asset_task_tablev",
".",
"setModel",
"(",
"self",
".",
"asset_task_model",
")",
"tasks",
"=",
"asset",
".",
"tasks",
".",
"all",
"(",
")",
"for",
"t",
"in",
"tasks",
":",
"tdata",
"=",
"djitemdata",
".",
"TaskItemData",
"(",
"t",
")",
"treemodel",
".",
"TreeItem",
"(",
"tdata",
",",
"tasksrootitem",
")",
"self",
".",
"cur_asset",
"=",
"asset"
] |
View the given asset
:param asset: the asset to view
:type asset: :class:`jukeboxcore.djadapter.models.Asset`
:returns: None
:rtype: None
:raises: None
|
[
"View",
"the",
"given",
"asset"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1769-L1816
|
239,209
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.shot_add_asset
|
def shot_add_asset(self, *args, **kwargs):
"""Add more assets to the shot.
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_shot:
return
dialog = AssetAdderDialog(shot=self.cur_shot)
dialog.exec_()
assets = dialog.assets
atypes = {}
for c in self.shot_asset_model.root.childItems:
atypes[c.internal_data()] = c
for asset in assets:
atypeitem = atypes.get(asset.atype)
if not atypeitem:
atypedata = djitemdata.AtypeItemData(asset.atype)
atypeitem = treemodel.TreeItem(atypedata, self.shot_asset_model.root)
atypes[asset.atype] = atypeitem
assetdata = djitemdata.AssetItemData(asset)
treemodel.TreeItem(assetdata, atypeitem)
self.cur_shot.save()
|
python
|
def shot_add_asset(self, *args, **kwargs):
"""Add more assets to the shot.
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_shot:
return
dialog = AssetAdderDialog(shot=self.cur_shot)
dialog.exec_()
assets = dialog.assets
atypes = {}
for c in self.shot_asset_model.root.childItems:
atypes[c.internal_data()] = c
for asset in assets:
atypeitem = atypes.get(asset.atype)
if not atypeitem:
atypedata = djitemdata.AtypeItemData(asset.atype)
atypeitem = treemodel.TreeItem(atypedata, self.shot_asset_model.root)
atypes[asset.atype] = atypeitem
assetdata = djitemdata.AssetItemData(asset)
treemodel.TreeItem(assetdata, atypeitem)
self.cur_shot.save()
|
[
"def",
"shot_add_asset",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cur_shot",
":",
"return",
"dialog",
"=",
"AssetAdderDialog",
"(",
"shot",
"=",
"self",
".",
"cur_shot",
")",
"dialog",
".",
"exec_",
"(",
")",
"assets",
"=",
"dialog",
".",
"assets",
"atypes",
"=",
"{",
"}",
"for",
"c",
"in",
"self",
".",
"shot_asset_model",
".",
"root",
".",
"childItems",
":",
"atypes",
"[",
"c",
".",
"internal_data",
"(",
")",
"]",
"=",
"c",
"for",
"asset",
"in",
"assets",
":",
"atypeitem",
"=",
"atypes",
".",
"get",
"(",
"asset",
".",
"atype",
")",
"if",
"not",
"atypeitem",
":",
"atypedata",
"=",
"djitemdata",
".",
"AtypeItemData",
"(",
"asset",
".",
"atype",
")",
"atypeitem",
"=",
"treemodel",
".",
"TreeItem",
"(",
"atypedata",
",",
"self",
".",
"shot_asset_model",
".",
"root",
")",
"atypes",
"[",
"asset",
".",
"atype",
"]",
"=",
"atypeitem",
"assetdata",
"=",
"djitemdata",
".",
"AssetItemData",
"(",
"asset",
")",
"treemodel",
".",
"TreeItem",
"(",
"assetdata",
",",
"atypeitem",
")",
"self",
".",
"cur_shot",
".",
"save",
"(",
")"
] |
Add more assets to the shot.
:returns: None
:rtype: None
:raises: None
|
[
"Add",
"more",
"assets",
"to",
"the",
"shot",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1818-L1841
|
239,210
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.create_asset
|
def create_asset(self, project, atype=None, shot=None, asset=None):
"""Create and return a new asset
:param project: the project for the asset
:type project: :class:`jukeboxcore.djadapter.models.Project`
:param atype: the assettype of the asset
:type atype: :class:`jukeboxcore.djadapter.models.Atype`
:param shot: the shot to add the asset to
:type shot: :class:`jukeboxcore.djadapter.models.Shot`
:param asset: the asset to add the new asset to
:type asset: :class:`jukeboxcore.djadapter.models.Asset`
:returns: The created asset or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Asset`
:raises: None
"""
element = shot or asset
dialog = AssetCreatorDialog(project=project, atype=atype, parent=self)
dialog.exec_()
asset = dialog.asset
if not atype:
element.assets.add(asset)
return asset
|
python
|
def create_asset(self, project, atype=None, shot=None, asset=None):
"""Create and return a new asset
:param project: the project for the asset
:type project: :class:`jukeboxcore.djadapter.models.Project`
:param atype: the assettype of the asset
:type atype: :class:`jukeboxcore.djadapter.models.Atype`
:param shot: the shot to add the asset to
:type shot: :class:`jukeboxcore.djadapter.models.Shot`
:param asset: the asset to add the new asset to
:type asset: :class:`jukeboxcore.djadapter.models.Asset`
:returns: The created asset or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Asset`
:raises: None
"""
element = shot or asset
dialog = AssetCreatorDialog(project=project, atype=atype, parent=self)
dialog.exec_()
asset = dialog.asset
if not atype:
element.assets.add(asset)
return asset
|
[
"def",
"create_asset",
"(",
"self",
",",
"project",
",",
"atype",
"=",
"None",
",",
"shot",
"=",
"None",
",",
"asset",
"=",
"None",
")",
":",
"element",
"=",
"shot",
"or",
"asset",
"dialog",
"=",
"AssetCreatorDialog",
"(",
"project",
"=",
"project",
",",
"atype",
"=",
"atype",
",",
"parent",
"=",
"self",
")",
"dialog",
".",
"exec_",
"(",
")",
"asset",
"=",
"dialog",
".",
"asset",
"if",
"not",
"atype",
":",
"element",
".",
"assets",
".",
"add",
"(",
"asset",
")",
"return",
"asset"
] |
Create and return a new asset
:param project: the project for the asset
:type project: :class:`jukeboxcore.djadapter.models.Project`
:param atype: the assettype of the asset
:type atype: :class:`jukeboxcore.djadapter.models.Atype`
:param shot: the shot to add the asset to
:type shot: :class:`jukeboxcore.djadapter.models.Shot`
:param asset: the asset to add the new asset to
:type asset: :class:`jukeboxcore.djadapter.models.Asset`
:returns: The created asset or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Asset`
:raises: None
|
[
"Create",
"and",
"return",
"a",
"new",
"asset"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1885-L1906
|
239,211
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.view_task
|
def view_task(self, task):
"""View the given task
:param task: the task to view
:type task: :class:`jukeboxcore.djadapter.models.Task`
:returns: None
:rtype: None
:raises: None
"""
log.debug('Viewing task %s', task.name)
self.cur_task = None
self.pages_tabw.setCurrentIndex(7)
self.task_dep_le.setText(task.name)
statusmap = {"New": 0, "Open": 1, "Done":2}
self.task_status_cb.setCurrentIndex(statusmap.get(task.status, -1))
dt = dt_to_qdatetime(task.deadline) if task.deadline else None
self.task_deadline_de.setDateTime(dt)
self.task_link_le.setText(task.element.name)
userrootdata = treemodel.ListItemData(['Username', 'First', 'Last', 'Email'])
userrootitem = treemodel.TreeItem(userrootdata)
for user in task.users.all():
userdata = djitemdata.UserItemData(user)
treemodel.TreeItem(userdata, userrootitem)
self.task_user_model = treemodel.TreeModel(userrootitem)
self.task_user_tablev.setModel(self.task_user_model)
self.cur_task = task
|
python
|
def view_task(self, task):
"""View the given task
:param task: the task to view
:type task: :class:`jukeboxcore.djadapter.models.Task`
:returns: None
:rtype: None
:raises: None
"""
log.debug('Viewing task %s', task.name)
self.cur_task = None
self.pages_tabw.setCurrentIndex(7)
self.task_dep_le.setText(task.name)
statusmap = {"New": 0, "Open": 1, "Done":2}
self.task_status_cb.setCurrentIndex(statusmap.get(task.status, -1))
dt = dt_to_qdatetime(task.deadline) if task.deadline else None
self.task_deadline_de.setDateTime(dt)
self.task_link_le.setText(task.element.name)
userrootdata = treemodel.ListItemData(['Username', 'First', 'Last', 'Email'])
userrootitem = treemodel.TreeItem(userrootdata)
for user in task.users.all():
userdata = djitemdata.UserItemData(user)
treemodel.TreeItem(userdata, userrootitem)
self.task_user_model = treemodel.TreeModel(userrootitem)
self.task_user_tablev.setModel(self.task_user_model)
self.cur_task = task
|
[
"def",
"view_task",
"(",
"self",
",",
"task",
")",
":",
"log",
".",
"debug",
"(",
"'Viewing task %s'",
",",
"task",
".",
"name",
")",
"self",
".",
"cur_task",
"=",
"None",
"self",
".",
"pages_tabw",
".",
"setCurrentIndex",
"(",
"7",
")",
"self",
".",
"task_dep_le",
".",
"setText",
"(",
"task",
".",
"name",
")",
"statusmap",
"=",
"{",
"\"New\"",
":",
"0",
",",
"\"Open\"",
":",
"1",
",",
"\"Done\"",
":",
"2",
"}",
"self",
".",
"task_status_cb",
".",
"setCurrentIndex",
"(",
"statusmap",
".",
"get",
"(",
"task",
".",
"status",
",",
"-",
"1",
")",
")",
"dt",
"=",
"dt_to_qdatetime",
"(",
"task",
".",
"deadline",
")",
"if",
"task",
".",
"deadline",
"else",
"None",
"self",
".",
"task_deadline_de",
".",
"setDateTime",
"(",
"dt",
")",
"self",
".",
"task_link_le",
".",
"setText",
"(",
"task",
".",
"element",
".",
"name",
")",
"userrootdata",
"=",
"treemodel",
".",
"ListItemData",
"(",
"[",
"'Username'",
",",
"'First'",
",",
"'Last'",
",",
"'Email'",
"]",
")",
"userrootitem",
"=",
"treemodel",
".",
"TreeItem",
"(",
"userrootdata",
")",
"for",
"user",
"in",
"task",
".",
"users",
".",
"all",
"(",
")",
":",
"userdata",
"=",
"djitemdata",
".",
"UserItemData",
"(",
"user",
")",
"treemodel",
".",
"TreeItem",
"(",
"userdata",
",",
"userrootitem",
")",
"self",
".",
"task_user_model",
"=",
"treemodel",
".",
"TreeModel",
"(",
"userrootitem",
")",
"self",
".",
"task_user_tablev",
".",
"setModel",
"(",
"self",
".",
"task_user_model",
")",
"self",
".",
"cur_task",
"=",
"task"
] |
View the given task
:param task: the task to view
:type task: :class:`jukeboxcore.djadapter.models.Task`
:returns: None
:rtype: None
:raises: None
|
[
"View",
"the",
"given",
"task"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1908-L1937
|
239,212
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.shot_save
|
def shot_save(self, ):
"""Save the current shot
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_shot:
return
desc = self.shot_desc_pte.toPlainText()
start = self.shot_start_sb.value()
end = self.shot_end_sb.value()
handle = self.shot_handle_sb.value()
self.cur_shot.description = desc
self.cur_shot.startframe = start
self.cur_shot.endframe = end
self.cur_shot.handlesize = handle
self.cur_shot.save()
|
python
|
def shot_save(self, ):
"""Save the current shot
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_shot:
return
desc = self.shot_desc_pte.toPlainText()
start = self.shot_start_sb.value()
end = self.shot_end_sb.value()
handle = self.shot_handle_sb.value()
self.cur_shot.description = desc
self.cur_shot.startframe = start
self.cur_shot.endframe = end
self.cur_shot.handlesize = handle
self.cur_shot.save()
|
[
"def",
"shot_save",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_shot",
":",
"return",
"desc",
"=",
"self",
".",
"shot_desc_pte",
".",
"toPlainText",
"(",
")",
"start",
"=",
"self",
".",
"shot_start_sb",
".",
"value",
"(",
")",
"end",
"=",
"self",
".",
"shot_end_sb",
".",
"value",
"(",
")",
"handle",
"=",
"self",
".",
"shot_handle_sb",
".",
"value",
"(",
")",
"self",
".",
"cur_shot",
".",
"description",
"=",
"desc",
"self",
".",
"cur_shot",
".",
"startframe",
"=",
"start",
"self",
".",
"cur_shot",
".",
"endframe",
"=",
"end",
"self",
".",
"cur_shot",
".",
"handlesize",
"=",
"handle",
"self",
".",
"cur_shot",
".",
"save",
"(",
")"
] |
Save the current shot
:returns: None
:rtype: None
:raises: None
|
[
"Save",
"the",
"current",
"shot"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1939-L1957
|
239,213
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.asset_view_prj
|
def asset_view_prj(self, ):
"""View the project of the current asset
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_asset:
return
prj = self.cur_asset.project
self.view_prj(prj)
|
python
|
def asset_view_prj(self, ):
"""View the project of the current asset
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_asset:
return
prj = self.cur_asset.project
self.view_prj(prj)
|
[
"def",
"asset_view_prj",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_asset",
":",
"return",
"prj",
"=",
"self",
".",
"cur_asset",
".",
"project",
"self",
".",
"view_prj",
"(",
"prj",
")"
] |
View the project of the current asset
:returns: None
:rtype: None
:raises: None
|
[
"View",
"the",
"project",
"of",
"the",
"current",
"asset"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1959-L1970
|
239,214
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.asset_view_atype
|
def asset_view_atype(self, ):
"""View the project of the current atype
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_asset:
return
atype = self.cur_asset.atype
self.view_atype(atype)
|
python
|
def asset_view_atype(self, ):
"""View the project of the current atype
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_asset:
return
atype = self.cur_asset.atype
self.view_atype(atype)
|
[
"def",
"asset_view_atype",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_asset",
":",
"return",
"atype",
"=",
"self",
".",
"cur_asset",
".",
"atype",
"self",
".",
"view_atype",
"(",
"atype",
")"
] |
View the project of the current atype
:returns: None
:rtype: None
:raises: None
|
[
"View",
"the",
"project",
"of",
"the",
"current",
"atype"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1972-L1983
|
239,215
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.atype_view_asset
|
def atype_view_asset(self, ):
"""View the project of the current assettype
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_atype:
return
i = self.atype_asset_treev.currentIndex()
item = i.internalPointer()
if item:
asset = item.internal_data()
if isinstance(asset, djadapter.models.Asset):
self.view_asset(asset)
|
python
|
def atype_view_asset(self, ):
"""View the project of the current assettype
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_atype:
return
i = self.atype_asset_treev.currentIndex()
item = i.internalPointer()
if item:
asset = item.internal_data()
if isinstance(asset, djadapter.models.Asset):
self.view_asset(asset)
|
[
"def",
"atype_view_asset",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_atype",
":",
"return",
"i",
"=",
"self",
".",
"atype_asset_treev",
".",
"currentIndex",
"(",
")",
"item",
"=",
"i",
".",
"internalPointer",
"(",
")",
"if",
"item",
":",
"asset",
"=",
"item",
".",
"internal_data",
"(",
")",
"if",
"isinstance",
"(",
"asset",
",",
"djadapter",
".",
"models",
".",
"Asset",
")",
":",
"self",
".",
"view_asset",
"(",
"asset",
")"
] |
View the project of the current assettype
:returns: None
:rtype: None
:raises: None
|
[
"View",
"the",
"project",
"of",
"the",
"current",
"assettype"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L1985-L2000
|
239,216
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.atype_save
|
def atype_save(self):
"""Save the current atype
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_atype:
return
desc = self.atype_desc_pte.toPlainText()
self.cur_atype.description = desc
self.cur_atype.save()
|
python
|
def atype_save(self):
"""Save the current atype
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_atype:
return
desc = self.atype_desc_pte.toPlainText()
self.cur_atype.description = desc
self.cur_atype.save()
|
[
"def",
"atype_save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"cur_atype",
":",
"return",
"desc",
"=",
"self",
".",
"atype_desc_pte",
".",
"toPlainText",
"(",
")",
"self",
".",
"cur_atype",
".",
"description",
"=",
"desc",
"self",
".",
"cur_atype",
".",
"save",
"(",
")"
] |
Save the current atype
:returns: None
:rtype: None
:raises: None
|
[
"Save",
"the",
"current",
"atype"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2019-L2031
|
239,217
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.asset_add_asset
|
def asset_add_asset(self, *args, **kwargs):
"""Add more assets to the asset.
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_asset:
return
dialog = AssetAdderDialog(asset=self.cur_asset)
dialog.exec_()
assets = dialog.assets
atypes = {}
for c in self.asset_asset_model.root.childItems:
atypes[c.internal_data()] = c
for asset in assets:
atypeitem = atypes.get(asset.atype)
if not atypeitem:
atypedata = djitemdata.AtypeItemData(asset.atype)
atypeitem = treemodel.TreeItem(atypedata, self.asset_asset_model.root)
atypes[asset.atype] = atypeitem
assetdata = djitemdata.AssetItemData(asset)
treemodel.TreeItem(assetdata, atypeitem)
self.cur_asset.save()
|
python
|
def asset_add_asset(self, *args, **kwargs):
"""Add more assets to the asset.
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_asset:
return
dialog = AssetAdderDialog(asset=self.cur_asset)
dialog.exec_()
assets = dialog.assets
atypes = {}
for c in self.asset_asset_model.root.childItems:
atypes[c.internal_data()] = c
for asset in assets:
atypeitem = atypes.get(asset.atype)
if not atypeitem:
atypedata = djitemdata.AtypeItemData(asset.atype)
atypeitem = treemodel.TreeItem(atypedata, self.asset_asset_model.root)
atypes[asset.atype] = atypeitem
assetdata = djitemdata.AssetItemData(asset)
treemodel.TreeItem(assetdata, atypeitem)
self.cur_asset.save()
|
[
"def",
"asset_add_asset",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cur_asset",
":",
"return",
"dialog",
"=",
"AssetAdderDialog",
"(",
"asset",
"=",
"self",
".",
"cur_asset",
")",
"dialog",
".",
"exec_",
"(",
")",
"assets",
"=",
"dialog",
".",
"assets",
"atypes",
"=",
"{",
"}",
"for",
"c",
"in",
"self",
".",
"asset_asset_model",
".",
"root",
".",
"childItems",
":",
"atypes",
"[",
"c",
".",
"internal_data",
"(",
")",
"]",
"=",
"c",
"for",
"asset",
"in",
"assets",
":",
"atypeitem",
"=",
"atypes",
".",
"get",
"(",
"asset",
".",
"atype",
")",
"if",
"not",
"atypeitem",
":",
"atypedata",
"=",
"djitemdata",
".",
"AtypeItemData",
"(",
"asset",
".",
"atype",
")",
"atypeitem",
"=",
"treemodel",
".",
"TreeItem",
"(",
"atypedata",
",",
"self",
".",
"asset_asset_model",
".",
"root",
")",
"atypes",
"[",
"asset",
".",
"atype",
"]",
"=",
"atypeitem",
"assetdata",
"=",
"djitemdata",
".",
"AssetItemData",
"(",
"asset",
")",
"treemodel",
".",
"TreeItem",
"(",
"assetdata",
",",
"atypeitem",
")",
"self",
".",
"cur_asset",
".",
"save",
"(",
")"
] |
Add more assets to the asset.
:returns: None
:rtype: None
:raises: None
|
[
"Add",
"more",
"assets",
"to",
"the",
"asset",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2050-L2073
|
239,218
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.asset_save
|
def asset_save(self):
"""Save the current asset
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_asset:
return
desc = self.asset_desc_pte.toPlainText()
self.cur_asset.description = desc
self.cur_asset.save()
|
python
|
def asset_save(self):
"""Save the current asset
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_asset:
return
desc = self.asset_desc_pte.toPlainText()
self.cur_asset.description = desc
self.cur_asset.save()
|
[
"def",
"asset_save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"cur_asset",
":",
"return",
"desc",
"=",
"self",
".",
"asset_desc_pte",
".",
"toPlainText",
"(",
")",
"self",
".",
"cur_asset",
".",
"description",
"=",
"desc",
"self",
".",
"cur_asset",
".",
"save",
"(",
")"
] |
Save the current asset
:returns: None
:rtype: None
:raises: None
|
[
"Save",
"the",
"current",
"asset"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2147-L2159
|
239,219
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.dep_add_prj
|
def dep_add_prj(self, *args, **kwargs):
"""Add projects to the current department
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_dep:
return
dialog = ProjectAdderDialog(department=self.cur_dep)
dialog.exec_()
prjs = dialog.projects
for prj in prjs:
prjdata = djitemdata.ProjectItemData(prj)
treemodel.TreeItem(prjdata, self.dep_prj_model.root)
|
python
|
def dep_add_prj(self, *args, **kwargs):
"""Add projects to the current department
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_dep:
return
dialog = ProjectAdderDialog(department=self.cur_dep)
dialog.exec_()
prjs = dialog.projects
for prj in prjs:
prjdata = djitemdata.ProjectItemData(prj)
treemodel.TreeItem(prjdata, self.dep_prj_model.root)
|
[
"def",
"dep_add_prj",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cur_dep",
":",
"return",
"dialog",
"=",
"ProjectAdderDialog",
"(",
"department",
"=",
"self",
".",
"cur_dep",
")",
"dialog",
".",
"exec_",
"(",
")",
"prjs",
"=",
"dialog",
".",
"projects",
"for",
"prj",
"in",
"prjs",
":",
"prjdata",
"=",
"djitemdata",
".",
"ProjectItemData",
"(",
"prj",
")",
"treemodel",
".",
"TreeItem",
"(",
"prjdata",
",",
"self",
".",
"dep_prj_model",
".",
"root",
")"
] |
Add projects to the current department
:returns: None
:rtype: None
:raises: None
|
[
"Add",
"projects",
"to",
"the",
"current",
"department"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2176-L2191
|
239,220
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.dep_remove_prj
|
def dep_remove_prj(self, *args, **kwargs):
"""Remove the selected project from the department
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_dep:
return
i = self.dep_prj_tablev.currentIndex()
item = i.internalPointer()
if item:
prj = item.internal_data()
self.cur_dep.projects.remove(prj)
item.set_parent(None)
|
python
|
def dep_remove_prj(self, *args, **kwargs):
"""Remove the selected project from the department
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_dep:
return
i = self.dep_prj_tablev.currentIndex()
item = i.internalPointer()
if item:
prj = item.internal_data()
self.cur_dep.projects.remove(prj)
item.set_parent(None)
|
[
"def",
"dep_remove_prj",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cur_dep",
":",
"return",
"i",
"=",
"self",
".",
"dep_prj_tablev",
".",
"currentIndex",
"(",
")",
"item",
"=",
"i",
".",
"internalPointer",
"(",
")",
"if",
"item",
":",
"prj",
"=",
"item",
".",
"internal_data",
"(",
")",
"self",
".",
"cur_dep",
".",
"projects",
".",
"remove",
"(",
"prj",
")",
"item",
".",
"set_parent",
"(",
"None",
")"
] |
Remove the selected project from the department
:returns: None
:rtype: None
:raises: None
|
[
"Remove",
"the",
"selected",
"project",
"from",
"the",
"department"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2193-L2207
|
239,221
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.dep_save
|
def dep_save(self, ):
"""Save the current department
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_dep:
return
ordervalue = self.dep_ordervalue_sb.value()
desc = self.dep_desc_pte.toPlainText()
self.cur_dep.ordervalue = ordervalue
self.cur_dep.description = desc
self.cur_dep.save()
|
python
|
def dep_save(self, ):
"""Save the current department
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_dep:
return
ordervalue = self.dep_ordervalue_sb.value()
desc = self.dep_desc_pte.toPlainText()
self.cur_dep.ordervalue = ordervalue
self.cur_dep.description = desc
self.cur_dep.save()
|
[
"def",
"dep_save",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_dep",
":",
"return",
"ordervalue",
"=",
"self",
".",
"dep_ordervalue_sb",
".",
"value",
"(",
")",
"desc",
"=",
"self",
".",
"dep_desc_pte",
".",
"toPlainText",
"(",
")",
"self",
".",
"cur_dep",
".",
"ordervalue",
"=",
"ordervalue",
"self",
".",
"cur_dep",
".",
"description",
"=",
"desc",
"self",
".",
"cur_dep",
".",
"save",
"(",
")"
] |
Save the current department
:returns: None
:rtype: None
:raises: None
|
[
"Save",
"the",
"current",
"department"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2209-L2222
|
239,222
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.task_add_user
|
def task_add_user(self, *args, **kwargs):
"""Add users to the current task
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_task:
return
dialog = UserAdderDialog(task=self.cur_task)
dialog.exec_()
users = dialog.users
for user in users:
userdata = djitemdata.UserItemData(user)
treemodel.TreeItem(userdata, self.task_user_model.root)
|
python
|
def task_add_user(self, *args, **kwargs):
"""Add users to the current task
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_task:
return
dialog = UserAdderDialog(task=self.cur_task)
dialog.exec_()
users = dialog.users
for user in users:
userdata = djitemdata.UserItemData(user)
treemodel.TreeItem(userdata, self.task_user_model.root)
|
[
"def",
"task_add_user",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cur_task",
":",
"return",
"dialog",
"=",
"UserAdderDialog",
"(",
"task",
"=",
"self",
".",
"cur_task",
")",
"dialog",
".",
"exec_",
"(",
")",
"users",
"=",
"dialog",
".",
"users",
"for",
"user",
"in",
"users",
":",
"userdata",
"=",
"djitemdata",
".",
"UserItemData",
"(",
"user",
")",
"treemodel",
".",
"TreeItem",
"(",
"userdata",
",",
"self",
".",
"task_user_model",
".",
"root",
")"
] |
Add users to the current task
:returns: None
:rtype: None
:raises: None
|
[
"Add",
"users",
"to",
"the",
"current",
"task"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2239-L2254
|
239,223
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.task_remove_user
|
def task_remove_user(self, *args, **kwargs):
"""Remove the selected user from the task
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_task:
return
i = self.task_user_tablev.currentIndex()
item = i.internalPointer()
if item:
user = item.internal_data()
self.cur_task.users.remove(user)
item.set_parent(None)
|
python
|
def task_remove_user(self, *args, **kwargs):
"""Remove the selected user from the task
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_task:
return
i = self.task_user_tablev.currentIndex()
item = i.internalPointer()
if item:
user = item.internal_data()
self.cur_task.users.remove(user)
item.set_parent(None)
|
[
"def",
"task_remove_user",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cur_task",
":",
"return",
"i",
"=",
"self",
".",
"task_user_tablev",
".",
"currentIndex",
"(",
")",
"item",
"=",
"i",
".",
"internalPointer",
"(",
")",
"if",
"item",
":",
"user",
"=",
"item",
".",
"internal_data",
"(",
")",
"self",
".",
"cur_task",
".",
"users",
".",
"remove",
"(",
"user",
")",
"item",
".",
"set_parent",
"(",
"None",
")"
] |
Remove the selected user from the task
:returns: None
:rtype: None
:raises: None
|
[
"Remove",
"the",
"selected",
"user",
"from",
"the",
"task"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2256-L2270
|
239,224
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.task_view_link
|
def task_view_link(self, ):
"""View the link of the current task
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_task:
return
e = self.cur_task.element
if isinstance(e, djadapter.models.Asset):
self.view_asset(e)
else:
self.view_shot(e)
|
python
|
def task_view_link(self, ):
"""View the link of the current task
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_task:
return
e = self.cur_task.element
if isinstance(e, djadapter.models.Asset):
self.view_asset(e)
else:
self.view_shot(e)
|
[
"def",
"task_view_link",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_task",
":",
"return",
"e",
"=",
"self",
".",
"cur_task",
".",
"element",
"if",
"isinstance",
"(",
"e",
",",
"djadapter",
".",
"models",
".",
"Asset",
")",
":",
"self",
".",
"view_asset",
"(",
"e",
")",
"else",
":",
"self",
".",
"view_shot",
"(",
"e",
")"
] |
View the link of the current task
:returns: None
:rtype: None
:raises: None
|
[
"View",
"the",
"link",
"of",
"the",
"current",
"task"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2283-L2296
|
239,225
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.task_save
|
def task_save(self, ):
"""Save the current task
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_task:
return
deadline = self.task_deadline_de.dateTime().toPython()
status = self.task_status_cb.currentText()
self.cur_task.deadline = deadline
self.cur_task.status = status
self.cur_task.save()
|
python
|
def task_save(self, ):
"""Save the current task
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_task:
return
deadline = self.task_deadline_de.dateTime().toPython()
status = self.task_status_cb.currentText()
self.cur_task.deadline = deadline
self.cur_task.status = status
self.cur_task.save()
|
[
"def",
"task_save",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_task",
":",
"return",
"deadline",
"=",
"self",
".",
"task_deadline_de",
".",
"dateTime",
"(",
")",
".",
"toPython",
"(",
")",
"status",
"=",
"self",
".",
"task_status_cb",
".",
"currentText",
"(",
")",
"self",
".",
"cur_task",
".",
"deadline",
"=",
"deadline",
"self",
".",
"cur_task",
".",
"status",
"=",
"status",
"self",
".",
"cur_task",
".",
"save",
"(",
")"
] |
Save the current task
:returns: None
:rtype: None
:raises: None
|
[
"Save",
"the",
"current",
"task"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2298-L2311
|
239,226
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.user_view_task
|
def user_view_task(self, ):
"""View the task that is selected
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_user:
return
i = self.user_task_treev.currentIndex()
item = i.internalPointer()
if item:
task = item.internal_data()
if isinstance(task, djadapter.models.Task):
self.view_task(task)
|
python
|
def user_view_task(self, ):
"""View the task that is selected
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_user:
return
i = self.user_task_treev.currentIndex()
item = i.internalPointer()
if item:
task = item.internal_data()
if isinstance(task, djadapter.models.Task):
self.view_task(task)
|
[
"def",
"user_view_task",
"(",
"self",
",",
")",
":",
"if",
"not",
"self",
".",
"cur_user",
":",
"return",
"i",
"=",
"self",
".",
"user_task_treev",
".",
"currentIndex",
"(",
")",
"item",
"=",
"i",
".",
"internalPointer",
"(",
")",
"if",
"item",
":",
"task",
"=",
"item",
".",
"internal_data",
"(",
")",
"if",
"isinstance",
"(",
"task",
",",
"djadapter",
".",
"models",
".",
"Task",
")",
":",
"self",
".",
"view_task",
"(",
"task",
")"
] |
View the task that is selected
:returns: None
:rtype: None
:raises: None
|
[
"View",
"the",
"task",
"that",
"is",
"selected"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2326-L2340
|
239,227
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.user_add_prj
|
def user_add_prj(self, *args, **kwargs):
"""Add projects to the current user
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_user:
return
dialog = ProjectAdderDialog(user=self.cur_user)
dialog.exec_()
prjs = dialog.projects
for prj in prjs:
prjdata = djitemdata.ProjectItemData(prj)
treemodel.TreeItem(prjdata, self.user_prj_model.root)
|
python
|
def user_add_prj(self, *args, **kwargs):
"""Add projects to the current user
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_user:
return
dialog = ProjectAdderDialog(user=self.cur_user)
dialog.exec_()
prjs = dialog.projects
for prj in prjs:
prjdata = djitemdata.ProjectItemData(prj)
treemodel.TreeItem(prjdata, self.user_prj_model.root)
|
[
"def",
"user_add_prj",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cur_user",
":",
"return",
"dialog",
"=",
"ProjectAdderDialog",
"(",
"user",
"=",
"self",
".",
"cur_user",
")",
"dialog",
".",
"exec_",
"(",
")",
"prjs",
"=",
"dialog",
".",
"projects",
"for",
"prj",
"in",
"prjs",
":",
"prjdata",
"=",
"djitemdata",
".",
"ProjectItemData",
"(",
"prj",
")",
"treemodel",
".",
"TreeItem",
"(",
"prjdata",
",",
"self",
".",
"user_prj_model",
".",
"root",
")"
] |
Add projects to the current user
:returns: None
:rtype: None
:raises: None
|
[
"Add",
"projects",
"to",
"the",
"current",
"user"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2355-L2370
|
239,228
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.user_remove_prj
|
def user_remove_prj(self, *args, **kwargs):
"""Remove the selected project from the user
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_user:
return
i = self.user_prj_tablev.currentIndex()
item = i.internalPointer()
if item:
prj = item.internal_data()
prj.users.remove(self.cur_user)
item.set_parent(None)
|
python
|
def user_remove_prj(self, *args, **kwargs):
"""Remove the selected project from the user
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_user:
return
i = self.user_prj_tablev.currentIndex()
item = i.internalPointer()
if item:
prj = item.internal_data()
prj.users.remove(self.cur_user)
item.set_parent(None)
|
[
"def",
"user_remove_prj",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cur_user",
":",
"return",
"i",
"=",
"self",
".",
"user_prj_tablev",
".",
"currentIndex",
"(",
")",
"item",
"=",
"i",
".",
"internalPointer",
"(",
")",
"if",
"item",
":",
"prj",
"=",
"item",
".",
"internal_data",
"(",
")",
"prj",
".",
"users",
".",
"remove",
"(",
"self",
".",
"cur_user",
")",
"item",
".",
"set_parent",
"(",
"None",
")"
] |
Remove the selected project from the user
:returns: None
:rtype: None
:raises: None
|
[
"Remove",
"the",
"selected",
"project",
"from",
"the",
"user"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2372-L2386
|
239,229
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/addons/guerilla/guerillamgmt.py
|
GuerillaMGMTWin.user_save
|
def user_save(self):
"""Save the current user
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_user:
return
username = self.user_username_le.text()
first = self.user_first_le.text()
last = self.user_last_le.text()
email = self.user_email_le.text()
self.cur_user.username = username
self.cur_user.first_name = first
self.cur_user.last_name = last
self.cur_user.email = email
self.cur_user.save()
|
python
|
def user_save(self):
"""Save the current user
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_user:
return
username = self.user_username_le.text()
first = self.user_first_le.text()
last = self.user_last_le.text()
email = self.user_email_le.text()
self.cur_user.username = username
self.cur_user.first_name = first
self.cur_user.last_name = last
self.cur_user.email = email
self.cur_user.save()
|
[
"def",
"user_save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"cur_user",
":",
"return",
"username",
"=",
"self",
".",
"user_username_le",
".",
"text",
"(",
")",
"first",
"=",
"self",
".",
"user_first_le",
".",
"text",
"(",
")",
"last",
"=",
"self",
".",
"user_last_le",
".",
"text",
"(",
")",
"email",
"=",
"self",
".",
"user_email_le",
".",
"text",
"(",
")",
"self",
".",
"cur_user",
".",
"username",
"=",
"username",
"self",
".",
"cur_user",
".",
"first_name",
"=",
"first",
"self",
".",
"cur_user",
".",
"last_name",
"=",
"last",
"self",
".",
"cur_user",
".",
"email",
"=",
"email",
"self",
".",
"cur_user",
".",
"save",
"(",
")"
] |
Save the current user
:returns: None
:rtype: None
:raises: None
|
[
"Save",
"the",
"current",
"user"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/guerilla/guerillamgmt.py#L2388-L2406
|
239,230
|
theSage21/lanchat
|
lanchat/chat.py
|
Node.run
|
def run(self):
"""Run self on provided screen"""
notice('Starting output thread', self.color)
o = Thread(target=self.__output_thread, name='output')
o.start()
self.threads.append(o)
try:
notice('Starting input thread', self.color)
self.__input_thread()
except KeyboardInterrupt:
self.__shutdown()
|
python
|
def run(self):
"""Run self on provided screen"""
notice('Starting output thread', self.color)
o = Thread(target=self.__output_thread, name='output')
o.start()
self.threads.append(o)
try:
notice('Starting input thread', self.color)
self.__input_thread()
except KeyboardInterrupt:
self.__shutdown()
|
[
"def",
"run",
"(",
"self",
")",
":",
"notice",
"(",
"'Starting output thread'",
",",
"self",
".",
"color",
")",
"o",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"__output_thread",
",",
"name",
"=",
"'output'",
")",
"o",
".",
"start",
"(",
")",
"self",
".",
"threads",
".",
"append",
"(",
"o",
")",
"try",
":",
"notice",
"(",
"'Starting input thread'",
",",
"self",
".",
"color",
")",
"self",
".",
"__input_thread",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"self",
".",
"__shutdown",
"(",
")"
] |
Run self on provided screen
|
[
"Run",
"self",
"on",
"provided",
"screen"
] |
66f5dcead67fef815347b956b1d3e149a7e13b29
|
https://github.com/theSage21/lanchat/blob/66f5dcead67fef815347b956b1d3e149a7e13b29/lanchat/chat.py#L40-L50
|
239,231
|
theSage21/lanchat
|
lanchat/chat.py
|
Node.__get_instructions
|
def __get_instructions(self):
"Get info from sockets"
if self.mode == 'c':
c, m = utils.recv(self.__s)
inst = [(c, m, self.__s)]
else:
inst = []
with self.__client_list_lock:
for com in self.clients:
c, m = utils.recv(com)
if c is not None:
inst.append((c, m, com))
return inst
|
python
|
def __get_instructions(self):
"Get info from sockets"
if self.mode == 'c':
c, m = utils.recv(self.__s)
inst = [(c, m, self.__s)]
else:
inst = []
with self.__client_list_lock:
for com in self.clients:
c, m = utils.recv(com)
if c is not None:
inst.append((c, m, com))
return inst
|
[
"def",
"__get_instructions",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"==",
"'c'",
":",
"c",
",",
"m",
"=",
"utils",
".",
"recv",
"(",
"self",
".",
"__s",
")",
"inst",
"=",
"[",
"(",
"c",
",",
"m",
",",
"self",
".",
"__s",
")",
"]",
"else",
":",
"inst",
"=",
"[",
"]",
"with",
"self",
".",
"__client_list_lock",
":",
"for",
"com",
"in",
"self",
".",
"clients",
":",
"c",
",",
"m",
"=",
"utils",
".",
"recv",
"(",
"com",
")",
"if",
"c",
"is",
"not",
"None",
":",
"inst",
".",
"append",
"(",
"(",
"c",
",",
"m",
",",
"com",
")",
")",
"return",
"inst"
] |
Get info from sockets
|
[
"Get",
"info",
"from",
"sockets"
] |
66f5dcead67fef815347b956b1d3e149a7e13b29
|
https://github.com/theSage21/lanchat/blob/66f5dcead67fef815347b956b1d3e149a7e13b29/lanchat/chat.py#L95-L107
|
239,232
|
theSage21/lanchat
|
lanchat/chat.py
|
Node.__process_instructions
|
def __process_instructions(self, inst):
"Act on instructions recieved"
to_send = []
for cmd, msg, com in inst:
if cmd not in config.CMDS: # ignore if it is not legal
continue
if cmd == 'MSG':
if self.mode == 's':
to_send.append((msg, com))
if self.color:
txt = config.Col.BOLD + msg + config.Col.ENDC
else:
txt = msg
print(txt)
if self.issue_alert:
os.system(self.alert)
elif cmd == 'QUIT':
if self.mode == 's': # client quit
com.close()
with self.__client_list_lock:
self.clients.remove(com)
else: # server quit
self.__s.close()
self.__make_client() # wait for new server
elif cmd == 'ASSUME':
if self.mode == 'c': # assume a server role if client
self.__s.close()
self.__make_server()
for msg, sender in to_send:
if self.mode == 'c':
utils.msg(msg, self.__s)
else:
with self.__client_list_lock:
for com in self.clients:
if com == sender:
continue
utils.msg(msg, com)
|
python
|
def __process_instructions(self, inst):
"Act on instructions recieved"
to_send = []
for cmd, msg, com in inst:
if cmd not in config.CMDS: # ignore if it is not legal
continue
if cmd == 'MSG':
if self.mode == 's':
to_send.append((msg, com))
if self.color:
txt = config.Col.BOLD + msg + config.Col.ENDC
else:
txt = msg
print(txt)
if self.issue_alert:
os.system(self.alert)
elif cmd == 'QUIT':
if self.mode == 's': # client quit
com.close()
with self.__client_list_lock:
self.clients.remove(com)
else: # server quit
self.__s.close()
self.__make_client() # wait for new server
elif cmd == 'ASSUME':
if self.mode == 'c': # assume a server role if client
self.__s.close()
self.__make_server()
for msg, sender in to_send:
if self.mode == 'c':
utils.msg(msg, self.__s)
else:
with self.__client_list_lock:
for com in self.clients:
if com == sender:
continue
utils.msg(msg, com)
|
[
"def",
"__process_instructions",
"(",
"self",
",",
"inst",
")",
":",
"to_send",
"=",
"[",
"]",
"for",
"cmd",
",",
"msg",
",",
"com",
"in",
"inst",
":",
"if",
"cmd",
"not",
"in",
"config",
".",
"CMDS",
":",
"# ignore if it is not legal",
"continue",
"if",
"cmd",
"==",
"'MSG'",
":",
"if",
"self",
".",
"mode",
"==",
"'s'",
":",
"to_send",
".",
"append",
"(",
"(",
"msg",
",",
"com",
")",
")",
"if",
"self",
".",
"color",
":",
"txt",
"=",
"config",
".",
"Col",
".",
"BOLD",
"+",
"msg",
"+",
"config",
".",
"Col",
".",
"ENDC",
"else",
":",
"txt",
"=",
"msg",
"print",
"(",
"txt",
")",
"if",
"self",
".",
"issue_alert",
":",
"os",
".",
"system",
"(",
"self",
".",
"alert",
")",
"elif",
"cmd",
"==",
"'QUIT'",
":",
"if",
"self",
".",
"mode",
"==",
"'s'",
":",
"# client quit",
"com",
".",
"close",
"(",
")",
"with",
"self",
".",
"__client_list_lock",
":",
"self",
".",
"clients",
".",
"remove",
"(",
"com",
")",
"else",
":",
"# server quit",
"self",
".",
"__s",
".",
"close",
"(",
")",
"self",
".",
"__make_client",
"(",
")",
"# wait for new server",
"elif",
"cmd",
"==",
"'ASSUME'",
":",
"if",
"self",
".",
"mode",
"==",
"'c'",
":",
"# assume a server role if client",
"self",
".",
"__s",
".",
"close",
"(",
")",
"self",
".",
"__make_server",
"(",
")",
"for",
"msg",
",",
"sender",
"in",
"to_send",
":",
"if",
"self",
".",
"mode",
"==",
"'c'",
":",
"utils",
".",
"msg",
"(",
"msg",
",",
"self",
".",
"__s",
")",
"else",
":",
"with",
"self",
".",
"__client_list_lock",
":",
"for",
"com",
"in",
"self",
".",
"clients",
":",
"if",
"com",
"==",
"sender",
":",
"continue",
"utils",
".",
"msg",
"(",
"msg",
",",
"com",
")"
] |
Act on instructions recieved
|
[
"Act",
"on",
"instructions",
"recieved"
] |
66f5dcead67fef815347b956b1d3e149a7e13b29
|
https://github.com/theSage21/lanchat/blob/66f5dcead67fef815347b956b1d3e149a7e13b29/lanchat/chat.py#L109-L145
|
239,233
|
theSage21/lanchat
|
lanchat/chat.py
|
Node.__make_server
|
def __make_server(self):
"Make this node a server"
notice('Making server, getting listening socket', self.color)
self.mode = 's'
sock = utils.get_server_sock()
self.__s = sock
with self.__client_list_lock:
self.clients = deque()
self.threads = deque()
notice('Making beacon', self.color)
b = Thread(target=self.__beacon_thread, name='beacon')
b.start()
self.threads.append(b)
l = Thread(target=self.__listen_thread, name='listen')
notice('Starting listen thread', self.color)
l.start()
self.threads.append(l)
|
python
|
def __make_server(self):
"Make this node a server"
notice('Making server, getting listening socket', self.color)
self.mode = 's'
sock = utils.get_server_sock()
self.__s = sock
with self.__client_list_lock:
self.clients = deque()
self.threads = deque()
notice('Making beacon', self.color)
b = Thread(target=self.__beacon_thread, name='beacon')
b.start()
self.threads.append(b)
l = Thread(target=self.__listen_thread, name='listen')
notice('Starting listen thread', self.color)
l.start()
self.threads.append(l)
|
[
"def",
"__make_server",
"(",
"self",
")",
":",
"notice",
"(",
"'Making server, getting listening socket'",
",",
"self",
".",
"color",
")",
"self",
".",
"mode",
"=",
"'s'",
"sock",
"=",
"utils",
".",
"get_server_sock",
"(",
")",
"self",
".",
"__s",
"=",
"sock",
"with",
"self",
".",
"__client_list_lock",
":",
"self",
".",
"clients",
"=",
"deque",
"(",
")",
"self",
".",
"threads",
"=",
"deque",
"(",
")",
"notice",
"(",
"'Making beacon'",
",",
"self",
".",
"color",
")",
"b",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"__beacon_thread",
",",
"name",
"=",
"'beacon'",
")",
"b",
".",
"start",
"(",
")",
"self",
".",
"threads",
".",
"append",
"(",
"b",
")",
"l",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"__listen_thread",
",",
"name",
"=",
"'listen'",
")",
"notice",
"(",
"'Starting listen thread'",
",",
"self",
".",
"color",
")",
"l",
".",
"start",
"(",
")",
"self",
".",
"threads",
".",
"append",
"(",
"l",
")"
] |
Make this node a server
|
[
"Make",
"this",
"node",
"a",
"server"
] |
66f5dcead67fef815347b956b1d3e149a7e13b29
|
https://github.com/theSage21/lanchat/blob/66f5dcead67fef815347b956b1d3e149a7e13b29/lanchat/chat.py#L176-L192
|
239,234
|
theSage21/lanchat
|
lanchat/chat.py
|
Node.__make_client
|
def __make_client(self):
"Make this node a client"
notice('Making client, getting server connection', self.color)
self.mode = 'c'
addr = utils.get_existing_server_addr()
sock = utils.get_client_sock(addr)
self.__s = sock
with self.__client_list_lock:
self.clients = deque()
self.threads = deque()
|
python
|
def __make_client(self):
"Make this node a client"
notice('Making client, getting server connection', self.color)
self.mode = 'c'
addr = utils.get_existing_server_addr()
sock = utils.get_client_sock(addr)
self.__s = sock
with self.__client_list_lock:
self.clients = deque()
self.threads = deque()
|
[
"def",
"__make_client",
"(",
"self",
")",
":",
"notice",
"(",
"'Making client, getting server connection'",
",",
"self",
".",
"color",
")",
"self",
".",
"mode",
"=",
"'c'",
"addr",
"=",
"utils",
".",
"get_existing_server_addr",
"(",
")",
"sock",
"=",
"utils",
".",
"get_client_sock",
"(",
"addr",
")",
"self",
".",
"__s",
"=",
"sock",
"with",
"self",
".",
"__client_list_lock",
":",
"self",
".",
"clients",
"=",
"deque",
"(",
")",
"self",
".",
"threads",
"=",
"deque",
"(",
")"
] |
Make this node a client
|
[
"Make",
"this",
"node",
"a",
"client"
] |
66f5dcead67fef815347b956b1d3e149a7e13b29
|
https://github.com/theSage21/lanchat/blob/66f5dcead67fef815347b956b1d3e149a7e13b29/lanchat/chat.py#L194-L203
|
239,235
|
jkwill87/teletype
|
teletype/io/common.py
|
erase_lines
|
def erase_lines(n=1):
""" Erases n lines from the screen and moves the cursor up to follow
"""
for _ in range(n):
print(codes.cursor["up"], end="")
print(codes.cursor["eol"], end="")
|
python
|
def erase_lines(n=1):
""" Erases n lines from the screen and moves the cursor up to follow
"""
for _ in range(n):
print(codes.cursor["up"], end="")
print(codes.cursor["eol"], end="")
|
[
"def",
"erase_lines",
"(",
"n",
"=",
"1",
")",
":",
"for",
"_",
"in",
"range",
"(",
"n",
")",
":",
"print",
"(",
"codes",
".",
"cursor",
"[",
"\"up\"",
"]",
",",
"end",
"=",
"\"\"",
")",
"print",
"(",
"codes",
".",
"cursor",
"[",
"\"eol\"",
"]",
",",
"end",
"=",
"\"\"",
")"
] |
Erases n lines from the screen and moves the cursor up to follow
|
[
"Erases",
"n",
"lines",
"from",
"the",
"screen",
"and",
"moves",
"the",
"cursor",
"up",
"to",
"follow"
] |
8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf
|
https://github.com/jkwill87/teletype/blob/8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf/teletype/io/common.py#L8-L13
|
239,236
|
jkwill87/teletype
|
teletype/io/common.py
|
move_cursor
|
def move_cursor(cols=0, rows=0):
""" Moves the cursor the given number of columns and rows
The cursor is moved right when cols is positive and left when negative.
The cursor is moved down when rows is positive and down when negative.
"""
if cols == 0 and rows == 0:
return
commands = ""
commands += codes.cursor["up" if rows < 0 else "down"] * abs(rows)
commands += codes.cursor["left" if cols < 0 else "right"] * abs(cols)
if commands:
print(commands, end="")
stdout.flush()
|
python
|
def move_cursor(cols=0, rows=0):
""" Moves the cursor the given number of columns and rows
The cursor is moved right when cols is positive and left when negative.
The cursor is moved down when rows is positive and down when negative.
"""
if cols == 0 and rows == 0:
return
commands = ""
commands += codes.cursor["up" if rows < 0 else "down"] * abs(rows)
commands += codes.cursor["left" if cols < 0 else "right"] * abs(cols)
if commands:
print(commands, end="")
stdout.flush()
|
[
"def",
"move_cursor",
"(",
"cols",
"=",
"0",
",",
"rows",
"=",
"0",
")",
":",
"if",
"cols",
"==",
"0",
"and",
"rows",
"==",
"0",
":",
"return",
"commands",
"=",
"\"\"",
"commands",
"+=",
"codes",
".",
"cursor",
"[",
"\"up\"",
"if",
"rows",
"<",
"0",
"else",
"\"down\"",
"]",
"*",
"abs",
"(",
"rows",
")",
"commands",
"+=",
"codes",
".",
"cursor",
"[",
"\"left\"",
"if",
"cols",
"<",
"0",
"else",
"\"right\"",
"]",
"*",
"abs",
"(",
"cols",
")",
"if",
"commands",
":",
"print",
"(",
"commands",
",",
"end",
"=",
"\"\"",
")",
"stdout",
".",
"flush",
"(",
")"
] |
Moves the cursor the given number of columns and rows
The cursor is moved right when cols is positive and left when negative.
The cursor is moved down when rows is positive and down when negative.
|
[
"Moves",
"the",
"cursor",
"the",
"given",
"number",
"of",
"columns",
"and",
"rows",
"The",
"cursor",
"is",
"moved",
"right",
"when",
"cols",
"is",
"positive",
"and",
"left",
"when",
"negative",
".",
"The",
"cursor",
"is",
"moved",
"down",
"when",
"rows",
"is",
"positive",
"and",
"down",
"when",
"negative",
"."
] |
8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf
|
https://github.com/jkwill87/teletype/blob/8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf/teletype/io/common.py#L22-L35
|
239,237
|
jkwill87/teletype
|
teletype/io/common.py
|
style_format
|
def style_format(text, style):
""" Wraps texts in terminal control sequences
Style can be passed as either a collection or space delimited string.
Valid styles can be found in the codes module. Invalid or unsuported styles
will just be ignored.
"""
if not style:
return text
if isinstance(style, str):
style = style.split(" ")
prefix = ""
for s in style:
prefix += codes.colours.get(s, "")
prefix += codes.highlights.get(s, "")
prefix += codes.modes.get(s, "")
return prefix + text + codes.modes["reset"]
|
python
|
def style_format(text, style):
""" Wraps texts in terminal control sequences
Style can be passed as either a collection or space delimited string.
Valid styles can be found in the codes module. Invalid or unsuported styles
will just be ignored.
"""
if not style:
return text
if isinstance(style, str):
style = style.split(" ")
prefix = ""
for s in style:
prefix += codes.colours.get(s, "")
prefix += codes.highlights.get(s, "")
prefix += codes.modes.get(s, "")
return prefix + text + codes.modes["reset"]
|
[
"def",
"style_format",
"(",
"text",
",",
"style",
")",
":",
"if",
"not",
"style",
":",
"return",
"text",
"if",
"isinstance",
"(",
"style",
",",
"str",
")",
":",
"style",
"=",
"style",
".",
"split",
"(",
"\" \"",
")",
"prefix",
"=",
"\"\"",
"for",
"s",
"in",
"style",
":",
"prefix",
"+=",
"codes",
".",
"colours",
".",
"get",
"(",
"s",
",",
"\"\"",
")",
"prefix",
"+=",
"codes",
".",
"highlights",
".",
"get",
"(",
"s",
",",
"\"\"",
")",
"prefix",
"+=",
"codes",
".",
"modes",
".",
"get",
"(",
"s",
",",
"\"\"",
")",
"return",
"prefix",
"+",
"text",
"+",
"codes",
".",
"modes",
"[",
"\"reset\"",
"]"
] |
Wraps texts in terminal control sequences
Style can be passed as either a collection or space delimited string.
Valid styles can be found in the codes module. Invalid or unsuported styles
will just be ignored.
|
[
"Wraps",
"texts",
"in",
"terminal",
"control",
"sequences"
] |
8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf
|
https://github.com/jkwill87/teletype/blob/8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf/teletype/io/common.py#L56-L72
|
239,238
|
jkwill87/teletype
|
teletype/io/common.py
|
style_print
|
def style_print(*values, **kwargs):
""" A convenience function that applies style_format to text before printing
"""
style = kwargs.pop("style", None)
values = [style_format(value, style) for value in values]
print(*values, **kwargs)
|
python
|
def style_print(*values, **kwargs):
""" A convenience function that applies style_format to text before printing
"""
style = kwargs.pop("style", None)
values = [style_format(value, style) for value in values]
print(*values, **kwargs)
|
[
"def",
"style_print",
"(",
"*",
"values",
",",
"*",
"*",
"kwargs",
")",
":",
"style",
"=",
"kwargs",
".",
"pop",
"(",
"\"style\"",
",",
"None",
")",
"values",
"=",
"[",
"style_format",
"(",
"value",
",",
"style",
")",
"for",
"value",
"in",
"values",
"]",
"print",
"(",
"*",
"values",
",",
"*",
"*",
"kwargs",
")"
] |
A convenience function that applies style_format to text before printing
|
[
"A",
"convenience",
"function",
"that",
"applies",
"style_format",
"to",
"text",
"before",
"printing"
] |
8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf
|
https://github.com/jkwill87/teletype/blob/8ba95c56dcb5e4d7f6ae155eb6cdabfdfaf346cf/teletype/io/common.py#L75-L80
|
239,239
|
guysv/txkernel
|
txkernel/connection.py
|
ConnectionFile.generate
|
def generate(cls, partial_props=None):
"""
Generate new connection file props from
defaults
"""
partial_props = partial_props or {}
props = partial_props.copy()
props.update(cls.DEFAULT_PROPERTIES)
return cls(props)
|
python
|
def generate(cls, partial_props=None):
"""
Generate new connection file props from
defaults
"""
partial_props = partial_props or {}
props = partial_props.copy()
props.update(cls.DEFAULT_PROPERTIES)
return cls(props)
|
[
"def",
"generate",
"(",
"cls",
",",
"partial_props",
"=",
"None",
")",
":",
"partial_props",
"=",
"partial_props",
"or",
"{",
"}",
"props",
"=",
"partial_props",
".",
"copy",
"(",
")",
"props",
".",
"update",
"(",
"cls",
".",
"DEFAULT_PROPERTIES",
")",
"return",
"cls",
"(",
"props",
")"
] |
Generate new connection file props from
defaults
|
[
"Generate",
"new",
"connection",
"file",
"props",
"from",
"defaults"
] |
a0aa1591df347732264f594bb13bc10d8aaf0f23
|
https://github.com/guysv/txkernel/blob/a0aa1591df347732264f594bb13bc10d8aaf0f23/txkernel/connection.py#L42-L50
|
239,240
|
guysv/txkernel
|
txkernel/connection.py
|
ConnectionFile.write_file
|
def write_file(self):
"""
Write a new connection file to disk. and
return its path
"""
name = "kernel-{pid}.json".format(pid=os.getpid())
path = os.path.join(jupyter_runtime_dir(), name)
# indentation, because why not.
connection_json = json.dumps(self.connection_props, indent=2)
with open(path, "w") as connection_file:
connection_file.write(connection_json)
return path
|
python
|
def write_file(self):
"""
Write a new connection file to disk. and
return its path
"""
name = "kernel-{pid}.json".format(pid=os.getpid())
path = os.path.join(jupyter_runtime_dir(), name)
# indentation, because why not.
connection_json = json.dumps(self.connection_props, indent=2)
with open(path, "w") as connection_file:
connection_file.write(connection_json)
return path
|
[
"def",
"write_file",
"(",
"self",
")",
":",
"name",
"=",
"\"kernel-{pid}.json\"",
".",
"format",
"(",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"jupyter_runtime_dir",
"(",
")",
",",
"name",
")",
"# indentation, because why not.",
"connection_json",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"connection_props",
",",
"indent",
"=",
"2",
")",
"with",
"open",
"(",
"path",
",",
"\"w\"",
")",
"as",
"connection_file",
":",
"connection_file",
".",
"write",
"(",
"connection_json",
")",
"return",
"path"
] |
Write a new connection file to disk. and
return its path
|
[
"Write",
"a",
"new",
"connection",
"file",
"to",
"disk",
".",
"and",
"return",
"its",
"path"
] |
a0aa1591df347732264f594bb13bc10d8aaf0f23
|
https://github.com/guysv/txkernel/blob/a0aa1591df347732264f594bb13bc10d8aaf0f23/txkernel/connection.py#L57-L71
|
239,241
|
Brazelton-Lab/bio_utils
|
bio_utils/verifiers/gff3.py
|
gff3_verifier
|
def gff3_verifier(entries, line=None):
"""Raises error if invalid GFF3 format detected
Args:
entries (list): A list of GFF3Entry instances
line (int): Line number of first entry
Raises:
FormatError: Error when GFF3 format incorrect with descriptive message
"""
regex = r'^[a-zA-Z0-9.:^*$@!+_?-|]+\t.+\t.+\t\d+\t\d+\t' \
+ r'\d*\.?\d*\t[+-.]\t[.0-2]\t.+{0}$'.format(os.linesep)
delimiter = r'\t'
for entry in entries:
try:
entry_verifier([entry.write()], regex, delimiter)
except FormatError as error:
# Format info on what entry error came from
if line:
intro = 'Line {0}'.format(str(line))
elif error.part == 0:
intro = 'Entry with source {0}'.format(entry.source)
else:
intro = 'Entry with Sequence ID {0}'.format(entry.seqid)
# Generate error
if error.part == 0:
msg = '{0} has no Sequence ID'.format(intro)
elif error.part == 1:
msg = '{0} has no source'.format(intro)
elif error.part == 2:
msg = '{0} has non-numerical characters in type'.format(intro)
elif error.part == 3:
msg = '{0} has non-numerical characters in ' \
'start position'.format(intro)
elif error.part == 4:
msg = '{0} has non-numerical characters in ' \
'end position'.format(intro)
elif error.part == 5:
msg = '{0} has non-numerical characters in score'.format(intro)
elif error.part == 6:
msg = '{0} strand not in [+-.]'.format(intro)
elif error.part == 7:
msg = '{0} phase not in [.0-2]'.format(intro)
elif error.part == 8:
msg = '{0} has no attributes'.format(intro)
else:
msg = 'Unknown Error: Likely a Bug'
raise FormatError(message=msg)
if line:
line += 1
|
python
|
def gff3_verifier(entries, line=None):
"""Raises error if invalid GFF3 format detected
Args:
entries (list): A list of GFF3Entry instances
line (int): Line number of first entry
Raises:
FormatError: Error when GFF3 format incorrect with descriptive message
"""
regex = r'^[a-zA-Z0-9.:^*$@!+_?-|]+\t.+\t.+\t\d+\t\d+\t' \
+ r'\d*\.?\d*\t[+-.]\t[.0-2]\t.+{0}$'.format(os.linesep)
delimiter = r'\t'
for entry in entries:
try:
entry_verifier([entry.write()], regex, delimiter)
except FormatError as error:
# Format info on what entry error came from
if line:
intro = 'Line {0}'.format(str(line))
elif error.part == 0:
intro = 'Entry with source {0}'.format(entry.source)
else:
intro = 'Entry with Sequence ID {0}'.format(entry.seqid)
# Generate error
if error.part == 0:
msg = '{0} has no Sequence ID'.format(intro)
elif error.part == 1:
msg = '{0} has no source'.format(intro)
elif error.part == 2:
msg = '{0} has non-numerical characters in type'.format(intro)
elif error.part == 3:
msg = '{0} has non-numerical characters in ' \
'start position'.format(intro)
elif error.part == 4:
msg = '{0} has non-numerical characters in ' \
'end position'.format(intro)
elif error.part == 5:
msg = '{0} has non-numerical characters in score'.format(intro)
elif error.part == 6:
msg = '{0} strand not in [+-.]'.format(intro)
elif error.part == 7:
msg = '{0} phase not in [.0-2]'.format(intro)
elif error.part == 8:
msg = '{0} has no attributes'.format(intro)
else:
msg = 'Unknown Error: Likely a Bug'
raise FormatError(message=msg)
if line:
line += 1
|
[
"def",
"gff3_verifier",
"(",
"entries",
",",
"line",
"=",
"None",
")",
":",
"regex",
"=",
"r'^[a-zA-Z0-9.:^*$@!+_?-|]+\\t.+\\t.+\\t\\d+\\t\\d+\\t'",
"+",
"r'\\d*\\.?\\d*\\t[+-.]\\t[.0-2]\\t.+{0}$'",
".",
"format",
"(",
"os",
".",
"linesep",
")",
"delimiter",
"=",
"r'\\t'",
"for",
"entry",
"in",
"entries",
":",
"try",
":",
"entry_verifier",
"(",
"[",
"entry",
".",
"write",
"(",
")",
"]",
",",
"regex",
",",
"delimiter",
")",
"except",
"FormatError",
"as",
"error",
":",
"# Format info on what entry error came from",
"if",
"line",
":",
"intro",
"=",
"'Line {0}'",
".",
"format",
"(",
"str",
"(",
"line",
")",
")",
"elif",
"error",
".",
"part",
"==",
"0",
":",
"intro",
"=",
"'Entry with source {0}'",
".",
"format",
"(",
"entry",
".",
"source",
")",
"else",
":",
"intro",
"=",
"'Entry with Sequence ID {0}'",
".",
"format",
"(",
"entry",
".",
"seqid",
")",
"# Generate error",
"if",
"error",
".",
"part",
"==",
"0",
":",
"msg",
"=",
"'{0} has no Sequence ID'",
".",
"format",
"(",
"intro",
")",
"elif",
"error",
".",
"part",
"==",
"1",
":",
"msg",
"=",
"'{0} has no source'",
".",
"format",
"(",
"intro",
")",
"elif",
"error",
".",
"part",
"==",
"2",
":",
"msg",
"=",
"'{0} has non-numerical characters in type'",
".",
"format",
"(",
"intro",
")",
"elif",
"error",
".",
"part",
"==",
"3",
":",
"msg",
"=",
"'{0} has non-numerical characters in '",
"'start position'",
".",
"format",
"(",
"intro",
")",
"elif",
"error",
".",
"part",
"==",
"4",
":",
"msg",
"=",
"'{0} has non-numerical characters in '",
"'end position'",
".",
"format",
"(",
"intro",
")",
"elif",
"error",
".",
"part",
"==",
"5",
":",
"msg",
"=",
"'{0} has non-numerical characters in score'",
".",
"format",
"(",
"intro",
")",
"elif",
"error",
".",
"part",
"==",
"6",
":",
"msg",
"=",
"'{0} strand not in [+-.]'",
".",
"format",
"(",
"intro",
")",
"elif",
"error",
".",
"part",
"==",
"7",
":",
"msg",
"=",
"'{0} phase not in [.0-2]'",
".",
"format",
"(",
"intro",
")",
"elif",
"error",
".",
"part",
"==",
"8",
":",
"msg",
"=",
"'{0} has no attributes'",
".",
"format",
"(",
"intro",
")",
"else",
":",
"msg",
"=",
"'Unknown Error: Likely a Bug'",
"raise",
"FormatError",
"(",
"message",
"=",
"msg",
")",
"if",
"line",
":",
"line",
"+=",
"1"
] |
Raises error if invalid GFF3 format detected
Args:
entries (list): A list of GFF3Entry instances
line (int): Line number of first entry
Raises:
FormatError: Error when GFF3 format incorrect with descriptive message
|
[
"Raises",
"error",
"if",
"invalid",
"GFF3",
"format",
"detected"
] |
5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7
|
https://github.com/Brazelton-Lab/bio_utils/blob/5a7ddf13ee0bf4baaaeb6b2b99e01bf74aa132b7/bio_utils/verifiers/gff3.py#L46-L100
|
239,242
|
utgwkk/py-timeparser
|
timeparser.py
|
parse
|
def parse(s, return_type=int):
'''
Parse time string and return seconds.
You can specify the type of return value both int or datetime.timedelta
with 'return_type' argument.
'''
RE_DAY = r'([0-9]+)d(ay)?'
RE_HOUR = r'([0-9]+)h(our)?'
RE_MINUTE = r'([0-9]+)m(in(ute)?)?'
RE_SECOND = r'([0-9]+)(s(ec(ond)?)?)?'
def _parse_time_with_unit(s):
retval = 0
md = re.match(RE_DAY, s)
mh = re.match(RE_HOUR, s)
mm = re.match(RE_MINUTE, s)
ms = re.match(RE_SECOND, s)
if md:
retval = 86400 * int(md.group(1))
elif mh:
retval = 3600 * int(mh.group(1))
elif mm:
retval = 60 * int(mm.group(1))
elif ms:
retval = int(ms.group(1))
return retval
if isinstance(s, (type(None), int, float)):
return s
if s[-1] in '0123456789':
s += 's'
m = re.match(r'^(%s)?(%s)?(%s)?(%s)?$' % (RE_DAY, RE_HOUR,
RE_MINUTE, RE_SECOND),
s)
if not m:
raise ParseError('invalid string: "%s"' % s)
times = [x for x in m.groups() if isinstance(x, str) and
re.match(r'[0-9]+[a-z]+', x)]
seconds = sum(_parse_time_with_unit(z) for z in times)
if return_type is int:
return seconds
elif return_type is timedelta:
return timedelta(seconds=seconds)
else:
raise TypeError('return_type "{}" is not supported.'.format(
return_type.__name__))
|
python
|
def parse(s, return_type=int):
'''
Parse time string and return seconds.
You can specify the type of return value both int or datetime.timedelta
with 'return_type' argument.
'''
RE_DAY = r'([0-9]+)d(ay)?'
RE_HOUR = r'([0-9]+)h(our)?'
RE_MINUTE = r'([0-9]+)m(in(ute)?)?'
RE_SECOND = r'([0-9]+)(s(ec(ond)?)?)?'
def _parse_time_with_unit(s):
retval = 0
md = re.match(RE_DAY, s)
mh = re.match(RE_HOUR, s)
mm = re.match(RE_MINUTE, s)
ms = re.match(RE_SECOND, s)
if md:
retval = 86400 * int(md.group(1))
elif mh:
retval = 3600 * int(mh.group(1))
elif mm:
retval = 60 * int(mm.group(1))
elif ms:
retval = int(ms.group(1))
return retval
if isinstance(s, (type(None), int, float)):
return s
if s[-1] in '0123456789':
s += 's'
m = re.match(r'^(%s)?(%s)?(%s)?(%s)?$' % (RE_DAY, RE_HOUR,
RE_MINUTE, RE_SECOND),
s)
if not m:
raise ParseError('invalid string: "%s"' % s)
times = [x for x in m.groups() if isinstance(x, str) and
re.match(r'[0-9]+[a-z]+', x)]
seconds = sum(_parse_time_with_unit(z) for z in times)
if return_type is int:
return seconds
elif return_type is timedelta:
return timedelta(seconds=seconds)
else:
raise TypeError('return_type "{}" is not supported.'.format(
return_type.__name__))
|
[
"def",
"parse",
"(",
"s",
",",
"return_type",
"=",
"int",
")",
":",
"RE_DAY",
"=",
"r'([0-9]+)d(ay)?'",
"RE_HOUR",
"=",
"r'([0-9]+)h(our)?'",
"RE_MINUTE",
"=",
"r'([0-9]+)m(in(ute)?)?'",
"RE_SECOND",
"=",
"r'([0-9]+)(s(ec(ond)?)?)?'",
"def",
"_parse_time_with_unit",
"(",
"s",
")",
":",
"retval",
"=",
"0",
"md",
"=",
"re",
".",
"match",
"(",
"RE_DAY",
",",
"s",
")",
"mh",
"=",
"re",
".",
"match",
"(",
"RE_HOUR",
",",
"s",
")",
"mm",
"=",
"re",
".",
"match",
"(",
"RE_MINUTE",
",",
"s",
")",
"ms",
"=",
"re",
".",
"match",
"(",
"RE_SECOND",
",",
"s",
")",
"if",
"md",
":",
"retval",
"=",
"86400",
"*",
"int",
"(",
"md",
".",
"group",
"(",
"1",
")",
")",
"elif",
"mh",
":",
"retval",
"=",
"3600",
"*",
"int",
"(",
"mh",
".",
"group",
"(",
"1",
")",
")",
"elif",
"mm",
":",
"retval",
"=",
"60",
"*",
"int",
"(",
"mm",
".",
"group",
"(",
"1",
")",
")",
"elif",
"ms",
":",
"retval",
"=",
"int",
"(",
"ms",
".",
"group",
"(",
"1",
")",
")",
"return",
"retval",
"if",
"isinstance",
"(",
"s",
",",
"(",
"type",
"(",
"None",
")",
",",
"int",
",",
"float",
")",
")",
":",
"return",
"s",
"if",
"s",
"[",
"-",
"1",
"]",
"in",
"'0123456789'",
":",
"s",
"+=",
"'s'",
"m",
"=",
"re",
".",
"match",
"(",
"r'^(%s)?(%s)?(%s)?(%s)?$'",
"%",
"(",
"RE_DAY",
",",
"RE_HOUR",
",",
"RE_MINUTE",
",",
"RE_SECOND",
")",
",",
"s",
")",
"if",
"not",
"m",
":",
"raise",
"ParseError",
"(",
"'invalid string: \"%s\"'",
"%",
"s",
")",
"times",
"=",
"[",
"x",
"for",
"x",
"in",
"m",
".",
"groups",
"(",
")",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
"and",
"re",
".",
"match",
"(",
"r'[0-9]+[a-z]+'",
",",
"x",
")",
"]",
"seconds",
"=",
"sum",
"(",
"_parse_time_with_unit",
"(",
"z",
")",
"for",
"z",
"in",
"times",
")",
"if",
"return_type",
"is",
"int",
":",
"return",
"seconds",
"elif",
"return_type",
"is",
"timedelta",
":",
"return",
"timedelta",
"(",
"seconds",
"=",
"seconds",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'return_type \"{}\" is not supported.'",
".",
"format",
"(",
"return_type",
".",
"__name__",
")",
")"
] |
Parse time string and return seconds.
You can specify the type of return value both int or datetime.timedelta
with 'return_type' argument.
|
[
"Parse",
"time",
"string",
"and",
"return",
"seconds",
".",
"You",
"can",
"specify",
"the",
"type",
"of",
"return",
"value",
"both",
"int",
"or",
"datetime",
".",
"timedelta",
"with",
"return_type",
"argument",
"."
] |
968668f58e5658936f214247c749e69ceeb2a66e
|
https://github.com/utgwkk/py-timeparser/blob/968668f58e5658936f214247c749e69ceeb2a66e/timeparser.py#L11-L60
|
239,243
|
FNNDSC/chrisapp
|
chrisapp/base.py
|
ChrisApp.path
|
def path(string):
"""
Define the 'path' data type that can be used by apps.
"""
if not os.path.exists(string):
msg = "Path %s not found!" % string
raise ArgumentTypeError(msg)
return string
|
python
|
def path(string):
"""
Define the 'path' data type that can be used by apps.
"""
if not os.path.exists(string):
msg = "Path %s not found!" % string
raise ArgumentTypeError(msg)
return string
|
[
"def",
"path",
"(",
"string",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"string",
")",
":",
"msg",
"=",
"\"Path %s not found!\"",
"%",
"string",
"raise",
"ArgumentTypeError",
"(",
"msg",
")",
"return",
"string"
] |
Define the 'path' data type that can be used by apps.
|
[
"Define",
"the",
"path",
"data",
"type",
"that",
"can",
"be",
"used",
"by",
"apps",
"."
] |
b176655f97206240fe173dfe86736f82f0d85bc4
|
https://github.com/FNNDSC/chrisapp/blob/b176655f97206240fe173dfe86736f82f0d85bc4/chrisapp/base.py#L183-L190
|
239,244
|
FNNDSC/chrisapp
|
chrisapp/base.py
|
ChrisApp.add_argument
|
def add_argument(self, *args, **kwargs):
"""
Add a parameter to this app.
"""
if not (('action' in kwargs) and (kwargs['action'] == 'help')):
# make sure required parameter options were defined
try:
name = kwargs['dest']
param_type = kwargs['type']
optional = kwargs['optional']
except KeyError as e:
detail = "%s option required. " % e
raise KeyError(detail)
if optional and ('default' not in kwargs):
detail = "A default value is required for optional parameters %s." % name
raise KeyError(detail)
# grab the default and help values
default = None
if 'default' in kwargs:
default = kwargs['default']
param_help = ""
if 'help' in kwargs:
param_help = kwargs['help']
# set the ArgumentParser's action
if param_type not in (str, int, float, bool, ChrisApp.path):
detail = "unsupported type: '%s'" % param_type
raise ValueError(detail)
action = 'store'
if param_type == bool:
action = 'store_false' if default else 'store_true'
del kwargs['default'] # 'default' and 'type' not allowed for boolean actions
del kwargs['type']
kwargs['action'] = action
# store the parameters internally (param_type.__name__ to enable json serialization)
param = {'name': name, 'type': param_type.__name__, 'optional': optional,
'flag': args[0], 'action': action, 'help': param_help, 'default': default}
self._parameters.append(param)
# add the parameter to the parser
del kwargs['optional']
ArgumentParser.add_argument(self, *args, **kwargs)
|
python
|
def add_argument(self, *args, **kwargs):
"""
Add a parameter to this app.
"""
if not (('action' in kwargs) and (kwargs['action'] == 'help')):
# make sure required parameter options were defined
try:
name = kwargs['dest']
param_type = kwargs['type']
optional = kwargs['optional']
except KeyError as e:
detail = "%s option required. " % e
raise KeyError(detail)
if optional and ('default' not in kwargs):
detail = "A default value is required for optional parameters %s." % name
raise KeyError(detail)
# grab the default and help values
default = None
if 'default' in kwargs:
default = kwargs['default']
param_help = ""
if 'help' in kwargs:
param_help = kwargs['help']
# set the ArgumentParser's action
if param_type not in (str, int, float, bool, ChrisApp.path):
detail = "unsupported type: '%s'" % param_type
raise ValueError(detail)
action = 'store'
if param_type == bool:
action = 'store_false' if default else 'store_true'
del kwargs['default'] # 'default' and 'type' not allowed for boolean actions
del kwargs['type']
kwargs['action'] = action
# store the parameters internally (param_type.__name__ to enable json serialization)
param = {'name': name, 'type': param_type.__name__, 'optional': optional,
'flag': args[0], 'action': action, 'help': param_help, 'default': default}
self._parameters.append(param)
# add the parameter to the parser
del kwargs['optional']
ArgumentParser.add_argument(self, *args, **kwargs)
|
[
"def",
"add_argument",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"(",
"(",
"'action'",
"in",
"kwargs",
")",
"and",
"(",
"kwargs",
"[",
"'action'",
"]",
"==",
"'help'",
")",
")",
":",
"# make sure required parameter options were defined",
"try",
":",
"name",
"=",
"kwargs",
"[",
"'dest'",
"]",
"param_type",
"=",
"kwargs",
"[",
"'type'",
"]",
"optional",
"=",
"kwargs",
"[",
"'optional'",
"]",
"except",
"KeyError",
"as",
"e",
":",
"detail",
"=",
"\"%s option required. \"",
"%",
"e",
"raise",
"KeyError",
"(",
"detail",
")",
"if",
"optional",
"and",
"(",
"'default'",
"not",
"in",
"kwargs",
")",
":",
"detail",
"=",
"\"A default value is required for optional parameters %s.\"",
"%",
"name",
"raise",
"KeyError",
"(",
"detail",
")",
"# grab the default and help values",
"default",
"=",
"None",
"if",
"'default'",
"in",
"kwargs",
":",
"default",
"=",
"kwargs",
"[",
"'default'",
"]",
"param_help",
"=",
"\"\"",
"if",
"'help'",
"in",
"kwargs",
":",
"param_help",
"=",
"kwargs",
"[",
"'help'",
"]",
"# set the ArgumentParser's action",
"if",
"param_type",
"not",
"in",
"(",
"str",
",",
"int",
",",
"float",
",",
"bool",
",",
"ChrisApp",
".",
"path",
")",
":",
"detail",
"=",
"\"unsupported type: '%s'\"",
"%",
"param_type",
"raise",
"ValueError",
"(",
"detail",
")",
"action",
"=",
"'store'",
"if",
"param_type",
"==",
"bool",
":",
"action",
"=",
"'store_false'",
"if",
"default",
"else",
"'store_true'",
"del",
"kwargs",
"[",
"'default'",
"]",
"# 'default' and 'type' not allowed for boolean actions",
"del",
"kwargs",
"[",
"'type'",
"]",
"kwargs",
"[",
"'action'",
"]",
"=",
"action",
"# store the parameters internally (param_type.__name__ to enable json serialization)",
"param",
"=",
"{",
"'name'",
":",
"name",
",",
"'type'",
":",
"param_type",
".",
"__name__",
",",
"'optional'",
":",
"optional",
",",
"'flag'",
":",
"args",
"[",
"0",
"]",
",",
"'action'",
":",
"action",
",",
"'help'",
":",
"param_help",
",",
"'default'",
":",
"default",
"}",
"self",
".",
"_parameters",
".",
"append",
"(",
"param",
")",
"# add the parameter to the parser",
"del",
"kwargs",
"[",
"'optional'",
"]",
"ArgumentParser",
".",
"add_argument",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Add a parameter to this app.
|
[
"Add",
"a",
"parameter",
"to",
"this",
"app",
"."
] |
b176655f97206240fe173dfe86736f82f0d85bc4
|
https://github.com/FNNDSC/chrisapp/blob/b176655f97206240fe173dfe86736f82f0d85bc4/chrisapp/base.py#L210-L253
|
239,245
|
FNNDSC/chrisapp
|
chrisapp/base.py
|
ChrisApp.save_json_representation
|
def save_json_representation(self, dir_path):
"""
Save the app's JSON representation object to a JSON file.
"""
file_name = self.__class__.__name__+ '.json'
file_path = os.path.join(dir_path, file_name)
with open(file_path, 'w') as outfile:
json.dump(self.get_json_representation(), outfile)
|
python
|
def save_json_representation(self, dir_path):
"""
Save the app's JSON representation object to a JSON file.
"""
file_name = self.__class__.__name__+ '.json'
file_path = os.path.join(dir_path, file_name)
with open(file_path, 'w') as outfile:
json.dump(self.get_json_representation(), outfile)
|
[
"def",
"save_json_representation",
"(",
"self",
",",
"dir_path",
")",
":",
"file_name",
"=",
"self",
".",
"__class__",
".",
"__name__",
"+",
"'.json'",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"file_name",
")",
"with",
"open",
"(",
"file_path",
",",
"'w'",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"self",
".",
"get_json_representation",
"(",
")",
",",
"outfile",
")"
] |
Save the app's JSON representation object to a JSON file.
|
[
"Save",
"the",
"app",
"s",
"JSON",
"representation",
"object",
"to",
"a",
"JSON",
"file",
"."
] |
b176655f97206240fe173dfe86736f82f0d85bc4
|
https://github.com/FNNDSC/chrisapp/blob/b176655f97206240fe173dfe86736f82f0d85bc4/chrisapp/base.py#L283-L290
|
239,246
|
FNNDSC/chrisapp
|
chrisapp/base.py
|
ChrisApp.launch
|
def launch(self, args=None):
"""
This method triggers the parsing of arguments.
"""
self.options = self.parse_args(args)
if self.options.saveinputmeta:
# save original input options
self.save_input_meta()
if self.options.inputmeta:
# read new options from JSON file
self.options = self.get_options_from_file(self.options.inputmeta)
self.run(self.options)
# if required save meta data for the output after running the plugin app
if self.options.saveoutputmeta:
self.save_output_meta()
|
python
|
def launch(self, args=None):
"""
This method triggers the parsing of arguments.
"""
self.options = self.parse_args(args)
if self.options.saveinputmeta:
# save original input options
self.save_input_meta()
if self.options.inputmeta:
# read new options from JSON file
self.options = self.get_options_from_file(self.options.inputmeta)
self.run(self.options)
# if required save meta data for the output after running the plugin app
if self.options.saveoutputmeta:
self.save_output_meta()
|
[
"def",
"launch",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"self",
".",
"options",
"=",
"self",
".",
"parse_args",
"(",
"args",
")",
"if",
"self",
".",
"options",
".",
"saveinputmeta",
":",
"# save original input options",
"self",
".",
"save_input_meta",
"(",
")",
"if",
"self",
".",
"options",
".",
"inputmeta",
":",
"# read new options from JSON file",
"self",
".",
"options",
"=",
"self",
".",
"get_options_from_file",
"(",
"self",
".",
"options",
".",
"inputmeta",
")",
"self",
".",
"run",
"(",
"self",
".",
"options",
")",
"# if required save meta data for the output after running the plugin app",
"if",
"self",
".",
"options",
".",
"saveoutputmeta",
":",
"self",
".",
"save_output_meta",
"(",
")"
] |
This method triggers the parsing of arguments.
|
[
"This",
"method",
"triggers",
"the",
"parsing",
"of",
"arguments",
"."
] |
b176655f97206240fe173dfe86736f82f0d85bc4
|
https://github.com/FNNDSC/chrisapp/blob/b176655f97206240fe173dfe86736f82f0d85bc4/chrisapp/base.py#L292-L306
|
239,247
|
FNNDSC/chrisapp
|
chrisapp/base.py
|
ChrisApp.get_options_from_file
|
def get_options_from_file(self, file_path):
"""
Return the options parsed from a JSON file.
"""
# read options JSON file
with open(file_path) as options_file:
options_dict = json.load(options_file)
options = []
for opt_name in options_dict:
options.append(opt_name)
options.append(options_dict[opt_name])
return self.parse_args(options)
|
python
|
def get_options_from_file(self, file_path):
"""
Return the options parsed from a JSON file.
"""
# read options JSON file
with open(file_path) as options_file:
options_dict = json.load(options_file)
options = []
for opt_name in options_dict:
options.append(opt_name)
options.append(options_dict[opt_name])
return self.parse_args(options)
|
[
"def",
"get_options_from_file",
"(",
"self",
",",
"file_path",
")",
":",
"# read options JSON file",
"with",
"open",
"(",
"file_path",
")",
"as",
"options_file",
":",
"options_dict",
"=",
"json",
".",
"load",
"(",
"options_file",
")",
"options",
"=",
"[",
"]",
"for",
"opt_name",
"in",
"options_dict",
":",
"options",
".",
"append",
"(",
"opt_name",
")",
"options",
".",
"append",
"(",
"options_dict",
"[",
"opt_name",
"]",
")",
"return",
"self",
".",
"parse_args",
"(",
"options",
")"
] |
Return the options parsed from a JSON file.
|
[
"Return",
"the",
"options",
"parsed",
"from",
"a",
"JSON",
"file",
"."
] |
b176655f97206240fe173dfe86736f82f0d85bc4
|
https://github.com/FNNDSC/chrisapp/blob/b176655f97206240fe173dfe86736f82f0d85bc4/chrisapp/base.py#L308-L319
|
239,248
|
FNNDSC/chrisapp
|
chrisapp/base.py
|
ChrisApp.save_output_meta
|
def save_output_meta(self):
"""
Save descriptive output meta data to a JSON file.
"""
options = self.options
file_path = os.path.join(options.outputdir, 'output.meta.json')
with open(file_path, 'w') as outfile:
json.dump(self.OUTPUT_META_DICT, outfile)
|
python
|
def save_output_meta(self):
"""
Save descriptive output meta data to a JSON file.
"""
options = self.options
file_path = os.path.join(options.outputdir, 'output.meta.json')
with open(file_path, 'w') as outfile:
json.dump(self.OUTPUT_META_DICT, outfile)
|
[
"def",
"save_output_meta",
"(",
"self",
")",
":",
"options",
"=",
"self",
".",
"options",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"options",
".",
"outputdir",
",",
"'output.meta.json'",
")",
"with",
"open",
"(",
"file_path",
",",
"'w'",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"self",
".",
"OUTPUT_META_DICT",
",",
"outfile",
")"
] |
Save descriptive output meta data to a JSON file.
|
[
"Save",
"descriptive",
"output",
"meta",
"data",
"to",
"a",
"JSON",
"file",
"."
] |
b176655f97206240fe173dfe86736f82f0d85bc4
|
https://github.com/FNNDSC/chrisapp/blob/b176655f97206240fe173dfe86736f82f0d85bc4/chrisapp/base.py#L330-L337
|
239,249
|
FNNDSC/chrisapp
|
chrisapp/base.py
|
ChrisApp.load_output_meta
|
def load_output_meta(self):
"""
Load descriptive output meta data from a JSON file in the input directory.
"""
options = self.options
file_path = os.path.join(options.inputdir, 'output.meta.json')
with open(file_path) as infile:
return json.load(infile)
|
python
|
def load_output_meta(self):
"""
Load descriptive output meta data from a JSON file in the input directory.
"""
options = self.options
file_path = os.path.join(options.inputdir, 'output.meta.json')
with open(file_path) as infile:
return json.load(infile)
|
[
"def",
"load_output_meta",
"(",
"self",
")",
":",
"options",
"=",
"self",
".",
"options",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"options",
".",
"inputdir",
",",
"'output.meta.json'",
")",
"with",
"open",
"(",
"file_path",
")",
"as",
"infile",
":",
"return",
"json",
".",
"load",
"(",
"infile",
")"
] |
Load descriptive output meta data from a JSON file in the input directory.
|
[
"Load",
"descriptive",
"output",
"meta",
"data",
"from",
"a",
"JSON",
"file",
"in",
"the",
"input",
"directory",
"."
] |
b176655f97206240fe173dfe86736f82f0d85bc4
|
https://github.com/FNNDSC/chrisapp/blob/b176655f97206240fe173dfe86736f82f0d85bc4/chrisapp/base.py#L339-L346
|
239,250
|
FNNDSC/chrisapp
|
chrisapp/base.py
|
ChrisApp.print_app_meta_data
|
def print_app_meta_data(self):
"""
Print the app's meta data.
"""
l_metaData = dir(self)
l_classVar = [x for x in l_metaData if x.isupper() ]
for str_var in l_classVar:
str_val = getattr(self, str_var)
print("%20s: %s" % (str_var, str_val))
|
python
|
def print_app_meta_data(self):
"""
Print the app's meta data.
"""
l_metaData = dir(self)
l_classVar = [x for x in l_metaData if x.isupper() ]
for str_var in l_classVar:
str_val = getattr(self, str_var)
print("%20s: %s" % (str_var, str_val))
|
[
"def",
"print_app_meta_data",
"(",
"self",
")",
":",
"l_metaData",
"=",
"dir",
"(",
"self",
")",
"l_classVar",
"=",
"[",
"x",
"for",
"x",
"in",
"l_metaData",
"if",
"x",
".",
"isupper",
"(",
")",
"]",
"for",
"str_var",
"in",
"l_classVar",
":",
"str_val",
"=",
"getattr",
"(",
"self",
",",
"str_var",
")",
"print",
"(",
"\"%20s: %s\"",
"%",
"(",
"str_var",
",",
"str_val",
")",
")"
] |
Print the app's meta data.
|
[
"Print",
"the",
"app",
"s",
"meta",
"data",
"."
] |
b176655f97206240fe173dfe86736f82f0d85bc4
|
https://github.com/FNNDSC/chrisapp/blob/b176655f97206240fe173dfe86736f82f0d85bc4/chrisapp/base.py#L354-L362
|
239,251
|
appstore-zencore/appserver
|
src/appserver.py
|
start
|
def start(context):
"""Start application server.
"""
config = context.obj["config"]
daemon = select(config, "application.daemon", False)
workspace = select(config, "application.workspace", None)
pidfile = select(config, "application.pidfile", DEFAULT_PIDFILE)
daemon_start(partial(main, config), pidfile, daemon, workspace)
|
python
|
def start(context):
"""Start application server.
"""
config = context.obj["config"]
daemon = select(config, "application.daemon", False)
workspace = select(config, "application.workspace", None)
pidfile = select(config, "application.pidfile", DEFAULT_PIDFILE)
daemon_start(partial(main, config), pidfile, daemon, workspace)
|
[
"def",
"start",
"(",
"context",
")",
":",
"config",
"=",
"context",
".",
"obj",
"[",
"\"config\"",
"]",
"daemon",
"=",
"select",
"(",
"config",
",",
"\"application.daemon\"",
",",
"False",
")",
"workspace",
"=",
"select",
"(",
"config",
",",
"\"application.workspace\"",
",",
"None",
")",
"pidfile",
"=",
"select",
"(",
"config",
",",
"\"application.pidfile\"",
",",
"DEFAULT_PIDFILE",
")",
"daemon_start",
"(",
"partial",
"(",
"main",
",",
"config",
")",
",",
"pidfile",
",",
"daemon",
",",
"workspace",
")"
] |
Start application server.
|
[
"Start",
"application",
"server",
"."
] |
5b8a5193f0e52bcc29dad73586b16294277a8bdc
|
https://github.com/appstore-zencore/appserver/blob/5b8a5193f0e52bcc29dad73586b16294277a8bdc/src/appserver.py#L72-L79
|
239,252
|
appstore-zencore/appserver
|
src/appserver.py
|
stop
|
def stop(context):
"""Stop application server.
"""
config = context.obj["config"]
pidfile = select(config, "application.pidfile", DEFAULT_PIDFILE)
daemon_stop(pidfile)
|
python
|
def stop(context):
"""Stop application server.
"""
config = context.obj["config"]
pidfile = select(config, "application.pidfile", DEFAULT_PIDFILE)
daemon_stop(pidfile)
|
[
"def",
"stop",
"(",
"context",
")",
":",
"config",
"=",
"context",
".",
"obj",
"[",
"\"config\"",
"]",
"pidfile",
"=",
"select",
"(",
"config",
",",
"\"application.pidfile\"",
",",
"DEFAULT_PIDFILE",
")",
"daemon_stop",
"(",
"pidfile",
")"
] |
Stop application server.
|
[
"Stop",
"application",
"server",
"."
] |
5b8a5193f0e52bcc29dad73586b16294277a8bdc
|
https://github.com/appstore-zencore/appserver/blob/5b8a5193f0e52bcc29dad73586b16294277a8bdc/src/appserver.py#L84-L89
|
239,253
|
roboogle/gtkmvc3
|
gtkmvco/examples/tutorial/step1/ctrl_glade.py
|
MyController.register_view
|
def register_view(self, view):
"""This method is called by the view, that calls it when it is
ready to register itself. Here we connect the 'pressed' signal
of the button with a controller's method. Signal 'destroy'
for the main window is handled as well."""
# connects the signals:
self.view['main_window'].connect('destroy', gtk.main_quit)
# initializes the text of label:
self.view.set_text("%d" % self.model.counter)
return
|
python
|
def register_view(self, view):
"""This method is called by the view, that calls it when it is
ready to register itself. Here we connect the 'pressed' signal
of the button with a controller's method. Signal 'destroy'
for the main window is handled as well."""
# connects the signals:
self.view['main_window'].connect('destroy', gtk.main_quit)
# initializes the text of label:
self.view.set_text("%d" % self.model.counter)
return
|
[
"def",
"register_view",
"(",
"self",
",",
"view",
")",
":",
"# connects the signals:",
"self",
".",
"view",
"[",
"'main_window'",
"]",
".",
"connect",
"(",
"'destroy'",
",",
"gtk",
".",
"main_quit",
")",
"# initializes the text of label:",
"self",
".",
"view",
".",
"set_text",
"(",
"\"%d\"",
"%",
"self",
".",
"model",
".",
"counter",
")",
"return"
] |
This method is called by the view, that calls it when it is
ready to register itself. Here we connect the 'pressed' signal
of the button with a controller's method. Signal 'destroy'
for the main window is handled as well.
|
[
"This",
"method",
"is",
"called",
"by",
"the",
"view",
"that",
"calls",
"it",
"when",
"it",
"is",
"ready",
"to",
"register",
"itself",
".",
"Here",
"we",
"connect",
"the",
"pressed",
"signal",
"of",
"the",
"button",
"with",
"a",
"controller",
"s",
"method",
".",
"Signal",
"destroy",
"for",
"the",
"main",
"window",
"is",
"handled",
"as",
"well",
"."
] |
63405fd8d2056be26af49103b13a8d5e57fe4dff
|
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/examples/tutorial/step1/ctrl_glade.py#L27-L38
|
239,254
|
robcharlwood/django-mothertongue
|
mothertongue/__init__.py
|
get_version
|
def get_version(svn=False, limit=3):
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:limit]])
if svn and limit >= 3:
from django.utils.version import get_svn_revision
import os
svn_rev = get_svn_revision(os.path.dirname(__file__))
if svn_rev:
v = '%s.%s' % (v, svn_rev)
return v
|
python
|
def get_version(svn=False, limit=3):
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:limit]])
if svn and limit >= 3:
from django.utils.version import get_svn_revision
import os
svn_rev = get_svn_revision(os.path.dirname(__file__))
if svn_rev:
v = '%s.%s' % (v, svn_rev)
return v
|
[
"def",
"get_version",
"(",
"svn",
"=",
"False",
",",
"limit",
"=",
"3",
")",
":",
"v",
"=",
"'.'",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"VERSION",
"[",
":",
"limit",
"]",
"]",
")",
"if",
"svn",
"and",
"limit",
">=",
"3",
":",
"from",
"django",
".",
"utils",
".",
"version",
"import",
"get_svn_revision",
"import",
"os",
"svn_rev",
"=",
"get_svn_revision",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"if",
"svn_rev",
":",
"v",
"=",
"'%s.%s'",
"%",
"(",
"v",
",",
"svn_rev",
")",
"return",
"v"
] |
Returns the version as a human-format string.
|
[
"Returns",
"the",
"version",
"as",
"a",
"human",
"-",
"format",
"string",
"."
] |
eeb1ec0057c8395bba58615870ab4bcda06c93d0
|
https://github.com/robcharlwood/django-mothertongue/blob/eeb1ec0057c8395bba58615870ab4bcda06c93d0/mothertongue/__init__.py#L6-L15
|
239,255
|
gestaolivre/brazil-types
|
brazil_types/types.py
|
CNPJ.format
|
def format(self, format_spec='f'):
u"""
Formata o CNPJ.
Códigos de formatação:
r -> raw
f -> formatado
>>> cnpj = CNPJ(58414462000135)
>>> cnpj.format('r')
'58414462000135'
>>> cnpj.format('f')
'58.414.462/0001-35'
"""
if format_spec == '' or format_spec == 'f':
cnpj = CNPJ.clean(self._cnpj)
return '{0}.{1}.{2}/{3}-{4}'.format(cnpj[0:2], cnpj[2:5], cnpj[5:8], cnpj[8:12], cnpj[12:14])
if format_spec == 'r':
return self._cnpj
raise ValueError(
"Unknown format code '{0}' for object of type '{1}'".format(format_spec, CNPJ.__name__))
|
python
|
def format(self, format_spec='f'):
u"""
Formata o CNPJ.
Códigos de formatação:
r -> raw
f -> formatado
>>> cnpj = CNPJ(58414462000135)
>>> cnpj.format('r')
'58414462000135'
>>> cnpj.format('f')
'58.414.462/0001-35'
"""
if format_spec == '' or format_spec == 'f':
cnpj = CNPJ.clean(self._cnpj)
return '{0}.{1}.{2}/{3}-{4}'.format(cnpj[0:2], cnpj[2:5], cnpj[5:8], cnpj[8:12], cnpj[12:14])
if format_spec == 'r':
return self._cnpj
raise ValueError(
"Unknown format code '{0}' for object of type '{1}'".format(format_spec, CNPJ.__name__))
|
[
"def",
"format",
"(",
"self",
",",
"format_spec",
"=",
"'f'",
")",
":",
"if",
"format_spec",
"==",
"''",
"or",
"format_spec",
"==",
"'f'",
":",
"cnpj",
"=",
"CNPJ",
".",
"clean",
"(",
"self",
".",
"_cnpj",
")",
"return",
"'{0}.{1}.{2}/{3}-{4}'",
".",
"format",
"(",
"cnpj",
"[",
"0",
":",
"2",
"]",
",",
"cnpj",
"[",
"2",
":",
"5",
"]",
",",
"cnpj",
"[",
"5",
":",
"8",
"]",
",",
"cnpj",
"[",
"8",
":",
"12",
"]",
",",
"cnpj",
"[",
"12",
":",
"14",
"]",
")",
"if",
"format_spec",
"==",
"'r'",
":",
"return",
"self",
".",
"_cnpj",
"raise",
"ValueError",
"(",
"\"Unknown format code '{0}' for object of type '{1}'\"",
".",
"format",
"(",
"format_spec",
",",
"CNPJ",
".",
"__name__",
")",
")"
] |
u"""
Formata o CNPJ.
Códigos de formatação:
r -> raw
f -> formatado
>>> cnpj = CNPJ(58414462000135)
>>> cnpj.format('r')
'58414462000135'
>>> cnpj.format('f')
'58.414.462/0001-35'
|
[
"u",
"Formata",
"o",
"CNPJ",
"."
] |
13db32c17d66d85166a2459f6b3d6fcff2c2b954
|
https://github.com/gestaolivre/brazil-types/blob/13db32c17d66d85166a2459f6b3d6fcff2c2b954/brazil_types/types.py#L108-L128
|
239,256
|
gestaolivre/brazil-types
|
brazil_types/types.py
|
CPF.format
|
def format(self, format_spec='f'):
u"""
Formata o CPF.
Códigos de formatação:
r -> raw
f -> formatado
>>> cpf = CPF(58119443659)
>>> cpf.format('r')
'58119443659'
>>> cpf.format('f')
'581.194.436-59'
"""
if format_spec == '' or format_spec == 'f':
cpf = CPF.clean(self._cpf)
return '{0}.{1}.{2}-{3}'.format(cpf[0:3], cpf[3:6], cpf[6:9], cpf[9:11])
if format_spec == 'r':
return self._cpf
raise ValueError(
"Unknown format code '{0}' for object of type '{1}'".format(format_spec, CPF.__name__))
|
python
|
def format(self, format_spec='f'):
u"""
Formata o CPF.
Códigos de formatação:
r -> raw
f -> formatado
>>> cpf = CPF(58119443659)
>>> cpf.format('r')
'58119443659'
>>> cpf.format('f')
'581.194.436-59'
"""
if format_spec == '' or format_spec == 'f':
cpf = CPF.clean(self._cpf)
return '{0}.{1}.{2}-{3}'.format(cpf[0:3], cpf[3:6], cpf[6:9], cpf[9:11])
if format_spec == 'r':
return self._cpf
raise ValueError(
"Unknown format code '{0}' for object of type '{1}'".format(format_spec, CPF.__name__))
|
[
"def",
"format",
"(",
"self",
",",
"format_spec",
"=",
"'f'",
")",
":",
"if",
"format_spec",
"==",
"''",
"or",
"format_spec",
"==",
"'f'",
":",
"cpf",
"=",
"CPF",
".",
"clean",
"(",
"self",
".",
"_cpf",
")",
"return",
"'{0}.{1}.{2}-{3}'",
".",
"format",
"(",
"cpf",
"[",
"0",
":",
"3",
"]",
",",
"cpf",
"[",
"3",
":",
"6",
"]",
",",
"cpf",
"[",
"6",
":",
"9",
"]",
",",
"cpf",
"[",
"9",
":",
"11",
"]",
")",
"if",
"format_spec",
"==",
"'r'",
":",
"return",
"self",
".",
"_cpf",
"raise",
"ValueError",
"(",
"\"Unknown format code '{0}' for object of type '{1}'\"",
".",
"format",
"(",
"format_spec",
",",
"CPF",
".",
"__name__",
")",
")"
] |
u"""
Formata o CPF.
Códigos de formatação:
r -> raw
f -> formatado
>>> cpf = CPF(58119443659)
>>> cpf.format('r')
'58119443659'
>>> cpf.format('f')
'581.194.436-59'
|
[
"u",
"Formata",
"o",
"CPF",
"."
] |
13db32c17d66d85166a2459f6b3d6fcff2c2b954
|
https://github.com/gestaolivre/brazil-types/blob/13db32c17d66d85166a2459f6b3d6fcff2c2b954/brazil_types/types.py#L254-L274
|
239,257
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/gui/widgets/releasewin.py
|
ReleaseWin.create_comment_edit
|
def create_comment_edit(self, ):
"""Create a text edit for comments
:returns: the created text edit
:rtype: :class:`jukeboxcore.gui.widgets.textedit.JB_PlainTextEdit`
:raises: None
"""
pte = JB_PlainTextEdit(parent=self)
pte.set_placeholder("Enter a comment before saving...")
pte.setMaximumHeight(120)
return pte
|
python
|
def create_comment_edit(self, ):
"""Create a text edit for comments
:returns: the created text edit
:rtype: :class:`jukeboxcore.gui.widgets.textedit.JB_PlainTextEdit`
:raises: None
"""
pte = JB_PlainTextEdit(parent=self)
pte.set_placeholder("Enter a comment before saving...")
pte.setMaximumHeight(120)
return pte
|
[
"def",
"create_comment_edit",
"(",
"self",
",",
")",
":",
"pte",
"=",
"JB_PlainTextEdit",
"(",
"parent",
"=",
"self",
")",
"pte",
".",
"set_placeholder",
"(",
"\"Enter a comment before saving...\"",
")",
"pte",
".",
"setMaximumHeight",
"(",
"120",
")",
"return",
"pte"
] |
Create a text edit for comments
:returns: the created text edit
:rtype: :class:`jukeboxcore.gui.widgets.textedit.JB_PlainTextEdit`
:raises: None
|
[
"Create",
"a",
"text",
"edit",
"for",
"comments"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/releasewin.py#L75-L85
|
239,258
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/gui/widgets/releasewin.py
|
ReleaseWin.release_callback
|
def release_callback(self, *args, **kwargs):
"""Create a new release
:returns: None
:rtype: None
:raises: None
"""
tf = self.browser.get_current_selection()
if not tf:
self.statusbar.showMessage("Select a file to release, please!")
return
tfi = TaskFileInfo.create_from_taskfile(tf)
checks = self.get_checks()
cleanups = self.get_cleanups()
comment = self.get_comment()
r = Release(tfi, checks, cleanups, comment)
self.statusbar.showMessage("Release in progress...")
try:
success = r.release()
except OSError:
self.statusbar.showMessage("Could not copy workfile!")
return
except Exception as e:
self.statusbar.showMessage("%s" % e)
return
if success:
self.statusbar.showMessage("Success!")
else:
self.statusbar.showMessage("Release failed!")
|
python
|
def release_callback(self, *args, **kwargs):
"""Create a new release
:returns: None
:rtype: None
:raises: None
"""
tf = self.browser.get_current_selection()
if not tf:
self.statusbar.showMessage("Select a file to release, please!")
return
tfi = TaskFileInfo.create_from_taskfile(tf)
checks = self.get_checks()
cleanups = self.get_cleanups()
comment = self.get_comment()
r = Release(tfi, checks, cleanups, comment)
self.statusbar.showMessage("Release in progress...")
try:
success = r.release()
except OSError:
self.statusbar.showMessage("Could not copy workfile!")
return
except Exception as e:
self.statusbar.showMessage("%s" % e)
return
if success:
self.statusbar.showMessage("Success!")
else:
self.statusbar.showMessage("Release failed!")
|
[
"def",
"release_callback",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tf",
"=",
"self",
".",
"browser",
".",
"get_current_selection",
"(",
")",
"if",
"not",
"tf",
":",
"self",
".",
"statusbar",
".",
"showMessage",
"(",
"\"Select a file to release, please!\"",
")",
"return",
"tfi",
"=",
"TaskFileInfo",
".",
"create_from_taskfile",
"(",
"tf",
")",
"checks",
"=",
"self",
".",
"get_checks",
"(",
")",
"cleanups",
"=",
"self",
".",
"get_cleanups",
"(",
")",
"comment",
"=",
"self",
".",
"get_comment",
"(",
")",
"r",
"=",
"Release",
"(",
"tfi",
",",
"checks",
",",
"cleanups",
",",
"comment",
")",
"self",
".",
"statusbar",
".",
"showMessage",
"(",
"\"Release in progress...\"",
")",
"try",
":",
"success",
"=",
"r",
".",
"release",
"(",
")",
"except",
"OSError",
":",
"self",
".",
"statusbar",
".",
"showMessage",
"(",
"\"Could not copy workfile!\"",
")",
"return",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"statusbar",
".",
"showMessage",
"(",
"\"%s\"",
"%",
"e",
")",
"return",
"if",
"success",
":",
"self",
".",
"statusbar",
".",
"showMessage",
"(",
"\"Success!\"",
")",
"else",
":",
"self",
".",
"statusbar",
".",
"showMessage",
"(",
"\"Release failed!\"",
")"
] |
Create a new release
:returns: None
:rtype: None
:raises: None
|
[
"Create",
"a",
"new",
"release"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/releasewin.py#L87-L115
|
239,259
|
praekelt/jmbo-music
|
music/management/commands/base_track_feed.py
|
_do_create
|
def _do_create(di):
"""Function that interprets a dictionary and creates objects"""
track = di['track'].strip()
artists = di['artist']
if isinstance(artists, StringType):
artists = [artists]
# todo: handle case where different artists have a song with the same title
tracks = Track.objects.filter(title=track, state='published')
if tracks:
track = tracks[0]
track_created = False
else:
track = Track.objects.create(title=track, state='published')
track_created = True
last_played = di.get('last_played', None)
if last_played and (track.last_played != last_played):
track.last_played = last_played
track.save()
if track_created:
track.length = di.get('length', 240)
track.sites = Site.objects.all()
track.save(set_image=False)
for artist in artists:
track.create_credit(artist.strip(), 'artist')
# Set image last since we need credits set
track.set_image()
|
python
|
def _do_create(di):
"""Function that interprets a dictionary and creates objects"""
track = di['track'].strip()
artists = di['artist']
if isinstance(artists, StringType):
artists = [artists]
# todo: handle case where different artists have a song with the same title
tracks = Track.objects.filter(title=track, state='published')
if tracks:
track = tracks[0]
track_created = False
else:
track = Track.objects.create(title=track, state='published')
track_created = True
last_played = di.get('last_played', None)
if last_played and (track.last_played != last_played):
track.last_played = last_played
track.save()
if track_created:
track.length = di.get('length', 240)
track.sites = Site.objects.all()
track.save(set_image=False)
for artist in artists:
track.create_credit(artist.strip(), 'artist')
# Set image last since we need credits set
track.set_image()
|
[
"def",
"_do_create",
"(",
"di",
")",
":",
"track",
"=",
"di",
"[",
"'track'",
"]",
".",
"strip",
"(",
")",
"artists",
"=",
"di",
"[",
"'artist'",
"]",
"if",
"isinstance",
"(",
"artists",
",",
"StringType",
")",
":",
"artists",
"=",
"[",
"artists",
"]",
"# todo: handle case where different artists have a song with the same title",
"tracks",
"=",
"Track",
".",
"objects",
".",
"filter",
"(",
"title",
"=",
"track",
",",
"state",
"=",
"'published'",
")",
"if",
"tracks",
":",
"track",
"=",
"tracks",
"[",
"0",
"]",
"track_created",
"=",
"False",
"else",
":",
"track",
"=",
"Track",
".",
"objects",
".",
"create",
"(",
"title",
"=",
"track",
",",
"state",
"=",
"'published'",
")",
"track_created",
"=",
"True",
"last_played",
"=",
"di",
".",
"get",
"(",
"'last_played'",
",",
"None",
")",
"if",
"last_played",
"and",
"(",
"track",
".",
"last_played",
"!=",
"last_played",
")",
":",
"track",
".",
"last_played",
"=",
"last_played",
"track",
".",
"save",
"(",
")",
"if",
"track_created",
":",
"track",
".",
"length",
"=",
"di",
".",
"get",
"(",
"'length'",
",",
"240",
")",
"track",
".",
"sites",
"=",
"Site",
".",
"objects",
".",
"all",
"(",
")",
"track",
".",
"save",
"(",
"set_image",
"=",
"False",
")",
"for",
"artist",
"in",
"artists",
":",
"track",
".",
"create_credit",
"(",
"artist",
".",
"strip",
"(",
")",
",",
"'artist'",
")",
"# Set image last since we need credits set",
"track",
".",
"set_image",
"(",
")"
] |
Function that interprets a dictionary and creates objects
|
[
"Function",
"that",
"interprets",
"a",
"dictionary",
"and",
"creates",
"objects"
] |
baeacaa1971b9110ff952fc4eca938c6b426f33e
|
https://github.com/praekelt/jmbo-music/blob/baeacaa1971b9110ff952fc4eca938c6b426f33e/music/management/commands/base_track_feed.py#L13-L41
|
239,260
|
toumorokoshi/jenks
|
jenks/data.py
|
JenksData.get_jobs_from_argument
|
def get_jobs_from_argument(self, raw_job_string):
""" return a list of jobs corresponding to the raw_job_string """
jobs = []
if raw_job_string.startswith(":"):
job_keys = raw_job_string.strip(" :")
jobs.extend([job for job in self.jobs(job_keys)])
# we assume a job code
else:
assert "/" in raw_job_string, "Job Code {0} is improperly formatted!".format(raw_job_string)
host, job_name = raw_job_string.rsplit("/", 1)
host_url = self._config_dict.get(host, {}).get('url', host)
host = self.get_host(host_url)
if host.has_job(job_name):
jobs.append(JenksJob(None, host, job_name,
lambda: self._get_job_api_instance(host_url, job_name)))
else:
raise JenksDataException(
"Could not find Job {0}/{1}!".format(host, job_name))
return jobs
|
python
|
def get_jobs_from_argument(self, raw_job_string):
""" return a list of jobs corresponding to the raw_job_string """
jobs = []
if raw_job_string.startswith(":"):
job_keys = raw_job_string.strip(" :")
jobs.extend([job for job in self.jobs(job_keys)])
# we assume a job code
else:
assert "/" in raw_job_string, "Job Code {0} is improperly formatted!".format(raw_job_string)
host, job_name = raw_job_string.rsplit("/", 1)
host_url = self._config_dict.get(host, {}).get('url', host)
host = self.get_host(host_url)
if host.has_job(job_name):
jobs.append(JenksJob(None, host, job_name,
lambda: self._get_job_api_instance(host_url, job_name)))
else:
raise JenksDataException(
"Could not find Job {0}/{1}!".format(host, job_name))
return jobs
|
[
"def",
"get_jobs_from_argument",
"(",
"self",
",",
"raw_job_string",
")",
":",
"jobs",
"=",
"[",
"]",
"if",
"raw_job_string",
".",
"startswith",
"(",
"\":\"",
")",
":",
"job_keys",
"=",
"raw_job_string",
".",
"strip",
"(",
"\" :\"",
")",
"jobs",
".",
"extend",
"(",
"[",
"job",
"for",
"job",
"in",
"self",
".",
"jobs",
"(",
"job_keys",
")",
"]",
")",
"# we assume a job code",
"else",
":",
"assert",
"\"/\"",
"in",
"raw_job_string",
",",
"\"Job Code {0} is improperly formatted!\"",
".",
"format",
"(",
"raw_job_string",
")",
"host",
",",
"job_name",
"=",
"raw_job_string",
".",
"rsplit",
"(",
"\"/\"",
",",
"1",
")",
"host_url",
"=",
"self",
".",
"_config_dict",
".",
"get",
"(",
"host",
",",
"{",
"}",
")",
".",
"get",
"(",
"'url'",
",",
"host",
")",
"host",
"=",
"self",
".",
"get_host",
"(",
"host_url",
")",
"if",
"host",
".",
"has_job",
"(",
"job_name",
")",
":",
"jobs",
".",
"append",
"(",
"JenksJob",
"(",
"None",
",",
"host",
",",
"job_name",
",",
"lambda",
":",
"self",
".",
"_get_job_api_instance",
"(",
"host_url",
",",
"job_name",
")",
")",
")",
"else",
":",
"raise",
"JenksDataException",
"(",
"\"Could not find Job {0}/{1}!\"",
".",
"format",
"(",
"host",
",",
"job_name",
")",
")",
"return",
"jobs"
] |
return a list of jobs corresponding to the raw_job_string
|
[
"return",
"a",
"list",
"of",
"jobs",
"corresponding",
"to",
"the",
"raw_job_string"
] |
d3333a7b86ba290b7185aa5b8da75e76a28124f5
|
https://github.com/toumorokoshi/jenks/blob/d3333a7b86ba290b7185aa5b8da75e76a28124f5/jenks/data.py#L81-L99
|
239,261
|
roboogle/gtkmvc3
|
gtkmvco/examples/treeview/predicates.py
|
eqdate
|
def eqdate(y):
"""
Like eq but compares datetime with y,m,d tuple.
Also accepts magic string 'TODAY'.
"""
y = datetime.date.today() if y == 'TODAY' else datetime.date(*y)
return lambda x: x == y
|
python
|
def eqdate(y):
"""
Like eq but compares datetime with y,m,d tuple.
Also accepts magic string 'TODAY'.
"""
y = datetime.date.today() if y == 'TODAY' else datetime.date(*y)
return lambda x: x == y
|
[
"def",
"eqdate",
"(",
"y",
")",
":",
"y",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"if",
"y",
"==",
"'TODAY'",
"else",
"datetime",
".",
"date",
"(",
"*",
"y",
")",
"return",
"lambda",
"x",
":",
"x",
"==",
"y"
] |
Like eq but compares datetime with y,m,d tuple.
Also accepts magic string 'TODAY'.
|
[
"Like",
"eq",
"but",
"compares",
"datetime",
"with",
"y",
"m",
"d",
"tuple",
".",
"Also",
"accepts",
"magic",
"string",
"TODAY",
"."
] |
63405fd8d2056be26af49103b13a8d5e57fe4dff
|
https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/examples/treeview/predicates.py#L46-L52
|
239,262
|
pbrisk/mathtoolspy
|
mathtoolspy/utils/math_fcts.py
|
get_grid
|
def get_grid(start, end, nsteps=100):
"""
Generates a equal distanced list of float values with nsteps+1 values, begining start and ending with end.
:param start: the start value of the generated list.
:type float
:param end: the end value of the generated list.
:type float
:param nsteps: optional the number of steps (default=100), i.e. the generated list contains nstep+1 values.
:type int
"""
step = (end-start) / float(nsteps)
return [start + i * step for i in xrange(nsteps+1)]
|
python
|
def get_grid(start, end, nsteps=100):
"""
Generates a equal distanced list of float values with nsteps+1 values, begining start and ending with end.
:param start: the start value of the generated list.
:type float
:param end: the end value of the generated list.
:type float
:param nsteps: optional the number of steps (default=100), i.e. the generated list contains nstep+1 values.
:type int
"""
step = (end-start) / float(nsteps)
return [start + i * step for i in xrange(nsteps+1)]
|
[
"def",
"get_grid",
"(",
"start",
",",
"end",
",",
"nsteps",
"=",
"100",
")",
":",
"step",
"=",
"(",
"end",
"-",
"start",
")",
"/",
"float",
"(",
"nsteps",
")",
"return",
"[",
"start",
"+",
"i",
"*",
"step",
"for",
"i",
"in",
"xrange",
"(",
"nsteps",
"+",
"1",
")",
"]"
] |
Generates a equal distanced list of float values with nsteps+1 values, begining start and ending with end.
:param start: the start value of the generated list.
:type float
:param end: the end value of the generated list.
:type float
:param nsteps: optional the number of steps (default=100), i.e. the generated list contains nstep+1 values.
:type int
|
[
"Generates",
"a",
"equal",
"distanced",
"list",
"of",
"float",
"values",
"with",
"nsteps",
"+",
"1",
"values",
"begining",
"start",
"and",
"ending",
"with",
"end",
"."
] |
d0d35b45d20f346ba8a755e53ed0aa182fab43dd
|
https://github.com/pbrisk/mathtoolspy/blob/d0d35b45d20f346ba8a755e53ed0aa182fab43dd/mathtoolspy/utils/math_fcts.py#L77-L96
|
239,263
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/gui/filesysitemdata.py
|
taskfileinfo_task_data
|
def taskfileinfo_task_data(tfi, role):
"""Return the data for task
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the task
:rtype: depending on role
:raises: None
"""
task = tfi.task
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return task.name
|
python
|
def taskfileinfo_task_data(tfi, role):
"""Return the data for task
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the task
:rtype: depending on role
:raises: None
"""
task = tfi.task
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return task.name
|
[
"def",
"taskfileinfo_task_data",
"(",
"tfi",
",",
"role",
")",
":",
"task",
"=",
"tfi",
".",
"task",
"if",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"DisplayRole",
"or",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"EditRole",
":",
"return",
"task",
".",
"name"
] |
Return the data for task
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the task
:rtype: depending on role
:raises: None
|
[
"Return",
"the",
"data",
"for",
"task"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/filesysitemdata.py#L27-L40
|
239,264
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/gui/filesysitemdata.py
|
taskfileinfo_descriptor_data
|
def taskfileinfo_descriptor_data(tfi, role):
"""Return the data for descriptor
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the descriptor
:rtype: depending on role
:raises: None
"""
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return tfi.descriptor
|
python
|
def taskfileinfo_descriptor_data(tfi, role):
"""Return the data for descriptor
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the descriptor
:rtype: depending on role
:raises: None
"""
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return tfi.descriptor
|
[
"def",
"taskfileinfo_descriptor_data",
"(",
"tfi",
",",
"role",
")",
":",
"if",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"DisplayRole",
"or",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"EditRole",
":",
"return",
"tfi",
".",
"descriptor"
] |
Return the data for descriptor
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the descriptor
:rtype: depending on role
:raises: None
|
[
"Return",
"the",
"data",
"for",
"descriptor"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/filesysitemdata.py#L43-L55
|
239,265
|
bwesterb/sarah
|
src/drv.py
|
DiscreteRandomVariable.pick
|
def pick(self):
""" picks a value accoriding to the given density """
v = random.uniform(0, self.ub)
d = self.dist
c = self.vc - 1
s = self.vc
while True:
s = s / 2
if s == 0:
break
if v <= d[c][1]:
c -= s
else:
c += s
# we only need this logic when increasing c
while len(d) <= c:
s = s / 2
c -= s
if s == 0:
break
# we may have converged from the left, instead of the right
if c == len(d) or v <= d[c][1]:
c -= 1
return d[c][0]
|
python
|
def pick(self):
""" picks a value accoriding to the given density """
v = random.uniform(0, self.ub)
d = self.dist
c = self.vc - 1
s = self.vc
while True:
s = s / 2
if s == 0:
break
if v <= d[c][1]:
c -= s
else:
c += s
# we only need this logic when increasing c
while len(d) <= c:
s = s / 2
c -= s
if s == 0:
break
# we may have converged from the left, instead of the right
if c == len(d) or v <= d[c][1]:
c -= 1
return d[c][0]
|
[
"def",
"pick",
"(",
"self",
")",
":",
"v",
"=",
"random",
".",
"uniform",
"(",
"0",
",",
"self",
".",
"ub",
")",
"d",
"=",
"self",
".",
"dist",
"c",
"=",
"self",
".",
"vc",
"-",
"1",
"s",
"=",
"self",
".",
"vc",
"while",
"True",
":",
"s",
"=",
"s",
"/",
"2",
"if",
"s",
"==",
"0",
":",
"break",
"if",
"v",
"<=",
"d",
"[",
"c",
"]",
"[",
"1",
"]",
":",
"c",
"-=",
"s",
"else",
":",
"c",
"+=",
"s",
"# we only need this logic when increasing c",
"while",
"len",
"(",
"d",
")",
"<=",
"c",
":",
"s",
"=",
"s",
"/",
"2",
"c",
"-=",
"s",
"if",
"s",
"==",
"0",
":",
"break",
"# we may have converged from the left, instead of the right",
"if",
"c",
"==",
"len",
"(",
"d",
")",
"or",
"v",
"<=",
"d",
"[",
"c",
"]",
"[",
"1",
"]",
":",
"c",
"-=",
"1",
"return",
"d",
"[",
"c",
"]",
"[",
"0",
"]"
] |
picks a value accoriding to the given density
|
[
"picks",
"a",
"value",
"accoriding",
"to",
"the",
"given",
"density"
] |
a9e46e875dfff1dc11255d714bb736e5eb697809
|
https://github.com/bwesterb/sarah/blob/a9e46e875dfff1dc11255d714bb736e5eb697809/src/drv.py#L24-L47
|
239,266
|
usc-isi-i2/dig-extractor
|
digExtractor/extractor_processor.py
|
ExtractorProcessor.set_output_fields
|
def set_output_fields(self, output_fields):
"""Defines where to put the dictionary output of the extractor in the doc, but renames
the fields of the extracted output for the document or just filters the keys"""
if isinstance(output_fields, dict) or isinstance(output_fields, list):
self.output_fields = output_fields
elif isinstance(output_fields, basestring):
self.output_field = output_fields
else:
raise ValueError("set_output_fields requires a dictionary of "
+ "output fields to remap, a list of keys to filter, or a scalar string")
return self
|
python
|
def set_output_fields(self, output_fields):
"""Defines where to put the dictionary output of the extractor in the doc, but renames
the fields of the extracted output for the document or just filters the keys"""
if isinstance(output_fields, dict) or isinstance(output_fields, list):
self.output_fields = output_fields
elif isinstance(output_fields, basestring):
self.output_field = output_fields
else:
raise ValueError("set_output_fields requires a dictionary of "
+ "output fields to remap, a list of keys to filter, or a scalar string")
return self
|
[
"def",
"set_output_fields",
"(",
"self",
",",
"output_fields",
")",
":",
"if",
"isinstance",
"(",
"output_fields",
",",
"dict",
")",
"or",
"isinstance",
"(",
"output_fields",
",",
"list",
")",
":",
"self",
".",
"output_fields",
"=",
"output_fields",
"elif",
"isinstance",
"(",
"output_fields",
",",
"basestring",
")",
":",
"self",
".",
"output_field",
"=",
"output_fields",
"else",
":",
"raise",
"ValueError",
"(",
"\"set_output_fields requires a dictionary of \"",
"+",
"\"output fields to remap, a list of keys to filter, or a scalar string\"",
")",
"return",
"self"
] |
Defines where to put the dictionary output of the extractor in the doc, but renames
the fields of the extracted output for the document or just filters the keys
|
[
"Defines",
"where",
"to",
"put",
"the",
"dictionary",
"output",
"of",
"the",
"extractor",
"in",
"the",
"doc",
"but",
"renames",
"the",
"fields",
"of",
"the",
"extracted",
"output",
"for",
"the",
"document",
"or",
"just",
"filters",
"the",
"keys"
] |
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
|
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L45-L55
|
239,267
|
usc-isi-i2/dig-extractor
|
digExtractor/extractor_processor.py
|
ExtractorProcessor.__get_jp
|
def __get_jp(self, extractor_processor, sub_output=None):
"""Tries to get name from ExtractorProcessor to filter on first.
Otherwise falls back to filtering based on its metadata"""
if sub_output is None and extractor_processor.output_field is None:
raise ValueError(
"ExtractorProcessors input paths cannot be unioned across fields. Please specify either a sub_output or use a single scalar output_field")
if extractor_processor.get_output_jsonpath_with_name(sub_output) is not None:
return extractor_processor.get_output_jsonpath_with_name(sub_output)
else:
return extractor_processor.get_output_jsonpath(sub_output)
|
python
|
def __get_jp(self, extractor_processor, sub_output=None):
"""Tries to get name from ExtractorProcessor to filter on first.
Otherwise falls back to filtering based on its metadata"""
if sub_output is None and extractor_processor.output_field is None:
raise ValueError(
"ExtractorProcessors input paths cannot be unioned across fields. Please specify either a sub_output or use a single scalar output_field")
if extractor_processor.get_output_jsonpath_with_name(sub_output) is not None:
return extractor_processor.get_output_jsonpath_with_name(sub_output)
else:
return extractor_processor.get_output_jsonpath(sub_output)
|
[
"def",
"__get_jp",
"(",
"self",
",",
"extractor_processor",
",",
"sub_output",
"=",
"None",
")",
":",
"if",
"sub_output",
"is",
"None",
"and",
"extractor_processor",
".",
"output_field",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"ExtractorProcessors input paths cannot be unioned across fields. Please specify either a sub_output or use a single scalar output_field\"",
")",
"if",
"extractor_processor",
".",
"get_output_jsonpath_with_name",
"(",
"sub_output",
")",
"is",
"not",
"None",
":",
"return",
"extractor_processor",
".",
"get_output_jsonpath_with_name",
"(",
"sub_output",
")",
"else",
":",
"return",
"extractor_processor",
".",
"get_output_jsonpath",
"(",
"sub_output",
")"
] |
Tries to get name from ExtractorProcessor to filter on first.
Otherwise falls back to filtering based on its metadata
|
[
"Tries",
"to",
"get",
"name",
"from",
"ExtractorProcessor",
"to",
"filter",
"on",
"first",
".",
"Otherwise",
"falls",
"back",
"to",
"filtering",
"based",
"on",
"its",
"metadata"
] |
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
|
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L57-L66
|
239,268
|
usc-isi-i2/dig-extractor
|
digExtractor/extractor_processor.py
|
ExtractorProcessor.set_extractor_processor_inputs
|
def set_extractor_processor_inputs(self, extractor_processors,
sub_output=None):
"""Instead of specifying fields in the source document to rename
for the extractor, allows the user to specify ExtractorProcessors that
are executed earlier in the chain and generate json paths from
their output fields"""
if not (isinstance(extractor_processors, ExtractorProcessor) or
isinstance(extractor_processors, types.ListType)):
raise ValueError(
"extractor_processors must be an ExtractorProcessor or a list")
if isinstance(extractor_processors, ExtractorProcessor):
extractor_processor = extractor_processors
self.input_fields = self.__get_jp(extractor_processor, sub_output)
elif isinstance(extractor_processors, types.ListType):
self.input_fields = list()
for extractor_processor in extractor_processors:
if isinstance(extractor_processor, ExtractorProcessor):
self.input_fields.append(
self.__get_jp(extractor_processor, sub_output))
elif isinstance(extractor_processor, list):
self.input_fields.append(
reduce(lambda a, b: "{}|{}".format(a, b),
["({})".format(self.__get_jp(x, sub_output))
for x in extractor_processor]))
self.generate_json_paths()
return self
|
python
|
def set_extractor_processor_inputs(self, extractor_processors,
sub_output=None):
"""Instead of specifying fields in the source document to rename
for the extractor, allows the user to specify ExtractorProcessors that
are executed earlier in the chain and generate json paths from
their output fields"""
if not (isinstance(extractor_processors, ExtractorProcessor) or
isinstance(extractor_processors, types.ListType)):
raise ValueError(
"extractor_processors must be an ExtractorProcessor or a list")
if isinstance(extractor_processors, ExtractorProcessor):
extractor_processor = extractor_processors
self.input_fields = self.__get_jp(extractor_processor, sub_output)
elif isinstance(extractor_processors, types.ListType):
self.input_fields = list()
for extractor_processor in extractor_processors:
if isinstance(extractor_processor, ExtractorProcessor):
self.input_fields.append(
self.__get_jp(extractor_processor, sub_output))
elif isinstance(extractor_processor, list):
self.input_fields.append(
reduce(lambda a, b: "{}|{}".format(a, b),
["({})".format(self.__get_jp(x, sub_output))
for x in extractor_processor]))
self.generate_json_paths()
return self
|
[
"def",
"set_extractor_processor_inputs",
"(",
"self",
",",
"extractor_processors",
",",
"sub_output",
"=",
"None",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"extractor_processors",
",",
"ExtractorProcessor",
")",
"or",
"isinstance",
"(",
"extractor_processors",
",",
"types",
".",
"ListType",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"extractor_processors must be an ExtractorProcessor or a list\"",
")",
"if",
"isinstance",
"(",
"extractor_processors",
",",
"ExtractorProcessor",
")",
":",
"extractor_processor",
"=",
"extractor_processors",
"self",
".",
"input_fields",
"=",
"self",
".",
"__get_jp",
"(",
"extractor_processor",
",",
"sub_output",
")",
"elif",
"isinstance",
"(",
"extractor_processors",
",",
"types",
".",
"ListType",
")",
":",
"self",
".",
"input_fields",
"=",
"list",
"(",
")",
"for",
"extractor_processor",
"in",
"extractor_processors",
":",
"if",
"isinstance",
"(",
"extractor_processor",
",",
"ExtractorProcessor",
")",
":",
"self",
".",
"input_fields",
".",
"append",
"(",
"self",
".",
"__get_jp",
"(",
"extractor_processor",
",",
"sub_output",
")",
")",
"elif",
"isinstance",
"(",
"extractor_processor",
",",
"list",
")",
":",
"self",
".",
"input_fields",
".",
"append",
"(",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"\"{}|{}\"",
".",
"format",
"(",
"a",
",",
"b",
")",
",",
"[",
"\"({})\"",
".",
"format",
"(",
"self",
".",
"__get_jp",
"(",
"x",
",",
"sub_output",
")",
")",
"for",
"x",
"in",
"extractor_processor",
"]",
")",
")",
"self",
".",
"generate_json_paths",
"(",
")",
"return",
"self"
] |
Instead of specifying fields in the source document to rename
for the extractor, allows the user to specify ExtractorProcessors that
are executed earlier in the chain and generate json paths from
their output fields
|
[
"Instead",
"of",
"specifying",
"fields",
"in",
"the",
"source",
"document",
"to",
"rename",
"for",
"the",
"extractor",
"allows",
"the",
"user",
"to",
"specify",
"ExtractorProcessors",
"that",
"are",
"executed",
"earlier",
"in",
"the",
"chain",
"and",
"generate",
"json",
"paths",
"from",
"their",
"output",
"fields"
] |
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
|
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L68-L95
|
239,269
|
usc-isi-i2/dig-extractor
|
digExtractor/extractor_processor.py
|
ExtractorProcessor.get_output_jsonpath_field
|
def get_output_jsonpath_field(self, sub_output=None):
"""attempts to create an output jsonpath from a particular ouput field"""
if sub_output is not None:
if self.output_fields is None or\
(isinstance(self.output_fields, dict) and not sub_output in self.output_fields.itervalues()) or\
(isinstance(self.output_fields, list) and not sub_output in self.output_fields):
raise ValueError(
"Cannot generate output jsonpath because this ExtractorProcessor will not output {}".format(sub_output))
output_jsonpath_field = sub_output
else:
output_jsonpath_field = self.output_field
return output_jsonpath_field
|
python
|
def get_output_jsonpath_field(self, sub_output=None):
"""attempts to create an output jsonpath from a particular ouput field"""
if sub_output is not None:
if self.output_fields is None or\
(isinstance(self.output_fields, dict) and not sub_output in self.output_fields.itervalues()) or\
(isinstance(self.output_fields, list) and not sub_output in self.output_fields):
raise ValueError(
"Cannot generate output jsonpath because this ExtractorProcessor will not output {}".format(sub_output))
output_jsonpath_field = sub_output
else:
output_jsonpath_field = self.output_field
return output_jsonpath_field
|
[
"def",
"get_output_jsonpath_field",
"(",
"self",
",",
"sub_output",
"=",
"None",
")",
":",
"if",
"sub_output",
"is",
"not",
"None",
":",
"if",
"self",
".",
"output_fields",
"is",
"None",
"or",
"(",
"isinstance",
"(",
"self",
".",
"output_fields",
",",
"dict",
")",
"and",
"not",
"sub_output",
"in",
"self",
".",
"output_fields",
".",
"itervalues",
"(",
")",
")",
"or",
"(",
"isinstance",
"(",
"self",
".",
"output_fields",
",",
"list",
")",
"and",
"not",
"sub_output",
"in",
"self",
".",
"output_fields",
")",
":",
"raise",
"ValueError",
"(",
"\"Cannot generate output jsonpath because this ExtractorProcessor will not output {}\"",
".",
"format",
"(",
"sub_output",
")",
")",
"output_jsonpath_field",
"=",
"sub_output",
"else",
":",
"output_jsonpath_field",
"=",
"self",
".",
"output_field",
"return",
"output_jsonpath_field"
] |
attempts to create an output jsonpath from a particular ouput field
|
[
"attempts",
"to",
"create",
"an",
"output",
"jsonpath",
"from",
"a",
"particular",
"ouput",
"field"
] |
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
|
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L97-L108
|
239,270
|
usc-isi-i2/dig-extractor
|
digExtractor/extractor_processor.py
|
ExtractorProcessor.get_output_jsonpath_with_name
|
def get_output_jsonpath_with_name(self, sub_output=None):
"""If ExtractorProcessor has a name defined, return
a JSONPath that has a filter on that name"""
if self.name is None:
return None
output_jsonpath_field = self.get_output_jsonpath_field(sub_output)
extractor_filter = "name='{}'".format(self.name)
output_jsonpath = "{}[?{}].(result[*][value])".format(
output_jsonpath_field, extractor_filter)
return output_jsonpath
|
python
|
def get_output_jsonpath_with_name(self, sub_output=None):
"""If ExtractorProcessor has a name defined, return
a JSONPath that has a filter on that name"""
if self.name is None:
return None
output_jsonpath_field = self.get_output_jsonpath_field(sub_output)
extractor_filter = "name='{}'".format(self.name)
output_jsonpath = "{}[?{}].(result[*][value])".format(
output_jsonpath_field, extractor_filter)
return output_jsonpath
|
[
"def",
"get_output_jsonpath_with_name",
"(",
"self",
",",
"sub_output",
"=",
"None",
")",
":",
"if",
"self",
".",
"name",
"is",
"None",
":",
"return",
"None",
"output_jsonpath_field",
"=",
"self",
".",
"get_output_jsonpath_field",
"(",
"sub_output",
")",
"extractor_filter",
"=",
"\"name='{}'\"",
".",
"format",
"(",
"self",
".",
"name",
")",
"output_jsonpath",
"=",
"\"{}[?{}].(result[*][value])\"",
".",
"format",
"(",
"output_jsonpath_field",
",",
"extractor_filter",
")",
"return",
"output_jsonpath"
] |
If ExtractorProcessor has a name defined, return
a JSONPath that has a filter on that name
|
[
"If",
"ExtractorProcessor",
"has",
"a",
"name",
"defined",
"return",
"a",
"JSONPath",
"that",
"has",
"a",
"filter",
"on",
"that",
"name"
] |
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
|
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L110-L121
|
239,271
|
usc-isi-i2/dig-extractor
|
digExtractor/extractor_processor.py
|
ExtractorProcessor.get_output_jsonpath
|
def get_output_jsonpath(self, sub_output=None):
"""Attempt to build a JSONPath filter for this ExtractorProcessor
that captures how to get at the outputs of the wrapped Extractor"""
output_jsonpath_field = self.get_output_jsonpath_field(sub_output)
metadata = self.extractor.get_metadata()
metadata['source'] = str(self.input_fields)
extractor_filter = ""
is_first = True
for key, value in metadata.iteritems():
if is_first:
is_first = False
else:
extractor_filter = extractor_filter + " & "
if isinstance(value, basestring):
extractor_filter = extractor_filter\
+ "{}=\"{}\"".format(key,
re.sub('(?<=[^\\\])\"', "'", value))
elif isinstance(value, types.ListType):
extractor_filter = extractor_filter\
+ "{}={}".format(key, str(value))
output_jsonpath = "{}[?{}].result.value".format(
output_jsonpath_field, extractor_filter)
return output_jsonpath
|
python
|
def get_output_jsonpath(self, sub_output=None):
"""Attempt to build a JSONPath filter for this ExtractorProcessor
that captures how to get at the outputs of the wrapped Extractor"""
output_jsonpath_field = self.get_output_jsonpath_field(sub_output)
metadata = self.extractor.get_metadata()
metadata['source'] = str(self.input_fields)
extractor_filter = ""
is_first = True
for key, value in metadata.iteritems():
if is_first:
is_first = False
else:
extractor_filter = extractor_filter + " & "
if isinstance(value, basestring):
extractor_filter = extractor_filter\
+ "{}=\"{}\"".format(key,
re.sub('(?<=[^\\\])\"', "'", value))
elif isinstance(value, types.ListType):
extractor_filter = extractor_filter\
+ "{}={}".format(key, str(value))
output_jsonpath = "{}[?{}].result.value".format(
output_jsonpath_field, extractor_filter)
return output_jsonpath
|
[
"def",
"get_output_jsonpath",
"(",
"self",
",",
"sub_output",
"=",
"None",
")",
":",
"output_jsonpath_field",
"=",
"self",
".",
"get_output_jsonpath_field",
"(",
"sub_output",
")",
"metadata",
"=",
"self",
".",
"extractor",
".",
"get_metadata",
"(",
")",
"metadata",
"[",
"'source'",
"]",
"=",
"str",
"(",
"self",
".",
"input_fields",
")",
"extractor_filter",
"=",
"\"\"",
"is_first",
"=",
"True",
"for",
"key",
",",
"value",
"in",
"metadata",
".",
"iteritems",
"(",
")",
":",
"if",
"is_first",
":",
"is_first",
"=",
"False",
"else",
":",
"extractor_filter",
"=",
"extractor_filter",
"+",
"\" & \"",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"extractor_filter",
"=",
"extractor_filter",
"+",
"\"{}=\\\"{}\\\"\"",
".",
"format",
"(",
"key",
",",
"re",
".",
"sub",
"(",
"'(?<=[^\\\\\\])\\\"'",
",",
"\"'\"",
",",
"value",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"types",
".",
"ListType",
")",
":",
"extractor_filter",
"=",
"extractor_filter",
"+",
"\"{}={}\"",
".",
"format",
"(",
"key",
",",
"str",
"(",
"value",
")",
")",
"output_jsonpath",
"=",
"\"{}[?{}].result.value\"",
".",
"format",
"(",
"output_jsonpath_field",
",",
"extractor_filter",
")",
"return",
"output_jsonpath"
] |
Attempt to build a JSONPath filter for this ExtractorProcessor
that captures how to get at the outputs of the wrapped Extractor
|
[
"Attempt",
"to",
"build",
"a",
"JSONPath",
"filter",
"for",
"this",
"ExtractorProcessor",
"that",
"captures",
"how",
"to",
"get",
"at",
"the",
"outputs",
"of",
"the",
"wrapped",
"Extractor"
] |
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
|
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L123-L148
|
239,272
|
usc-isi-i2/dig-extractor
|
digExtractor/extractor_processor.py
|
ExtractorProcessor.set_input_fields
|
def set_input_fields(self, input_fields):
"""Given a scalar or ordered list of strings generate JSONPaths
that describe how to access the values necessary for the Extractor """
if not (isinstance(input_fields, basestring) or
isinstance(input_fields, types.ListType)):
raise ValueError("input_fields must be a string or a list")
self.input_fields = input_fields
self.generate_json_paths()
return self
|
python
|
def set_input_fields(self, input_fields):
"""Given a scalar or ordered list of strings generate JSONPaths
that describe how to access the values necessary for the Extractor """
if not (isinstance(input_fields, basestring) or
isinstance(input_fields, types.ListType)):
raise ValueError("input_fields must be a string or a list")
self.input_fields = input_fields
self.generate_json_paths()
return self
|
[
"def",
"set_input_fields",
"(",
"self",
",",
"input_fields",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"input_fields",
",",
"basestring",
")",
"or",
"isinstance",
"(",
"input_fields",
",",
"types",
".",
"ListType",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"input_fields must be a string or a list\"",
")",
"self",
".",
"input_fields",
"=",
"input_fields",
"self",
".",
"generate_json_paths",
"(",
")",
"return",
"self"
] |
Given a scalar or ordered list of strings generate JSONPaths
that describe how to access the values necessary for the Extractor
|
[
"Given",
"a",
"scalar",
"or",
"ordered",
"list",
"of",
"strings",
"generate",
"JSONPaths",
"that",
"describe",
"how",
"to",
"access",
"the",
"values",
"necessary",
"for",
"the",
"Extractor"
] |
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
|
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L150-L158
|
239,273
|
usc-isi-i2/dig-extractor
|
digExtractor/extractor_processor.py
|
ExtractorProcessor.generate_json_paths
|
def generate_json_paths(self):
"""Given a scalar or ordered list of strings parse them to
generate JSONPaths"""
if isinstance(self.input_fields, basestring):
try:
self.jsonpaths = parse(self.input_fields)
except Exception as exception:
print "input_fields failed {}".format(self.input_fields)
raise exception
elif isinstance(self.input_fields, types.ListType):
self.jsonpaths = list()
for input_field in self.input_fields:
self.jsonpaths.append(parse(input_field))
if len(self.jsonpaths) == 1:
self.jsonpaths = self.jsonpaths[0]
|
python
|
def generate_json_paths(self):
"""Given a scalar or ordered list of strings parse them to
generate JSONPaths"""
if isinstance(self.input_fields, basestring):
try:
self.jsonpaths = parse(self.input_fields)
except Exception as exception:
print "input_fields failed {}".format(self.input_fields)
raise exception
elif isinstance(self.input_fields, types.ListType):
self.jsonpaths = list()
for input_field in self.input_fields:
self.jsonpaths.append(parse(input_field))
if len(self.jsonpaths) == 1:
self.jsonpaths = self.jsonpaths[0]
|
[
"def",
"generate_json_paths",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"input_fields",
",",
"basestring",
")",
":",
"try",
":",
"self",
".",
"jsonpaths",
"=",
"parse",
"(",
"self",
".",
"input_fields",
")",
"except",
"Exception",
"as",
"exception",
":",
"print",
"\"input_fields failed {}\"",
".",
"format",
"(",
"self",
".",
"input_fields",
")",
"raise",
"exception",
"elif",
"isinstance",
"(",
"self",
".",
"input_fields",
",",
"types",
".",
"ListType",
")",
":",
"self",
".",
"jsonpaths",
"=",
"list",
"(",
")",
"for",
"input_field",
"in",
"self",
".",
"input_fields",
":",
"self",
".",
"jsonpaths",
".",
"append",
"(",
"parse",
"(",
"input_field",
")",
")",
"if",
"len",
"(",
"self",
".",
"jsonpaths",
")",
"==",
"1",
":",
"self",
".",
"jsonpaths",
"=",
"self",
".",
"jsonpaths",
"[",
"0",
"]"
] |
Given a scalar or ordered list of strings parse them to
generate JSONPaths
|
[
"Given",
"a",
"scalar",
"or",
"ordered",
"list",
"of",
"strings",
"parse",
"them",
"to",
"generate",
"JSONPaths"
] |
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
|
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L160-L175
|
239,274
|
usc-isi-i2/dig-extractor
|
digExtractor/extractor_processor.py
|
ExtractorProcessor.insert_extracted_value
|
def insert_extracted_value(self, doc, extracted_value,
output_field, original_output_field=None):
"""inserts the extracted value into doc at the field specified
by output_field"""
if not extracted_value:
return doc
metadata = self.extractor.get_metadata()
if not self.extractor.get_include_context():
if isinstance(extracted_value, list):
result = list()
for ev in extracted_value:
result.append({'value': ev})
else:
result = {'value': extracted_value}
else:
result = extracted_value
metadata['result'] = result
metadata['source'] = str(self.input_fields)
if original_output_field is not None:
metadata['original_output_field'] = original_output_field
if self.name is not None:
metadata['name'] = self.name
field_elements = output_field.split('.')
while len(field_elements) > 1:
field_element = field_elements.pop(0)
if '[' in field_element:
if not field_element.startswith('['):
array_field_elements = field_element.split('[', 1)
array_field_element = array_field_elements[0]
doc = doc[array_field_element]
field_element = array_field_elements[1]
array_elements = field_element.split(']')
for array_element in array_elements:
if not array_element:
continue
if array_element.startswith('['):
array_element = array_element[1:]
if array_element.isdigit() and isinstance(doc, list):
doc = doc[int(array_element)]
else:
doc = doc[array_element]
else:
if field_element not in doc:
doc[field_element] = {}
doc = doc[field_element]
field_element = field_elements[0]
if field_element in doc:
output = doc[field_element]
if isinstance(output, dict):
output = [output, metadata]
elif isinstance(output, types.ListType):
output.append(metadata)
else:
output = [metadata]
doc[field_element] = output
|
python
|
def insert_extracted_value(self, doc, extracted_value,
output_field, original_output_field=None):
"""inserts the extracted value into doc at the field specified
by output_field"""
if not extracted_value:
return doc
metadata = self.extractor.get_metadata()
if not self.extractor.get_include_context():
if isinstance(extracted_value, list):
result = list()
for ev in extracted_value:
result.append({'value': ev})
else:
result = {'value': extracted_value}
else:
result = extracted_value
metadata['result'] = result
metadata['source'] = str(self.input_fields)
if original_output_field is not None:
metadata['original_output_field'] = original_output_field
if self.name is not None:
metadata['name'] = self.name
field_elements = output_field.split('.')
while len(field_elements) > 1:
field_element = field_elements.pop(0)
if '[' in field_element:
if not field_element.startswith('['):
array_field_elements = field_element.split('[', 1)
array_field_element = array_field_elements[0]
doc = doc[array_field_element]
field_element = array_field_elements[1]
array_elements = field_element.split(']')
for array_element in array_elements:
if not array_element:
continue
if array_element.startswith('['):
array_element = array_element[1:]
if array_element.isdigit() and isinstance(doc, list):
doc = doc[int(array_element)]
else:
doc = doc[array_element]
else:
if field_element not in doc:
doc[field_element] = {}
doc = doc[field_element]
field_element = field_elements[0]
if field_element in doc:
output = doc[field_element]
if isinstance(output, dict):
output = [output, metadata]
elif isinstance(output, types.ListType):
output.append(metadata)
else:
output = [metadata]
doc[field_element] = output
|
[
"def",
"insert_extracted_value",
"(",
"self",
",",
"doc",
",",
"extracted_value",
",",
"output_field",
",",
"original_output_field",
"=",
"None",
")",
":",
"if",
"not",
"extracted_value",
":",
"return",
"doc",
"metadata",
"=",
"self",
".",
"extractor",
".",
"get_metadata",
"(",
")",
"if",
"not",
"self",
".",
"extractor",
".",
"get_include_context",
"(",
")",
":",
"if",
"isinstance",
"(",
"extracted_value",
",",
"list",
")",
":",
"result",
"=",
"list",
"(",
")",
"for",
"ev",
"in",
"extracted_value",
":",
"result",
".",
"append",
"(",
"{",
"'value'",
":",
"ev",
"}",
")",
"else",
":",
"result",
"=",
"{",
"'value'",
":",
"extracted_value",
"}",
"else",
":",
"result",
"=",
"extracted_value",
"metadata",
"[",
"'result'",
"]",
"=",
"result",
"metadata",
"[",
"'source'",
"]",
"=",
"str",
"(",
"self",
".",
"input_fields",
")",
"if",
"original_output_field",
"is",
"not",
"None",
":",
"metadata",
"[",
"'original_output_field'",
"]",
"=",
"original_output_field",
"if",
"self",
".",
"name",
"is",
"not",
"None",
":",
"metadata",
"[",
"'name'",
"]",
"=",
"self",
".",
"name",
"field_elements",
"=",
"output_field",
".",
"split",
"(",
"'.'",
")",
"while",
"len",
"(",
"field_elements",
")",
">",
"1",
":",
"field_element",
"=",
"field_elements",
".",
"pop",
"(",
"0",
")",
"if",
"'['",
"in",
"field_element",
":",
"if",
"not",
"field_element",
".",
"startswith",
"(",
"'['",
")",
":",
"array_field_elements",
"=",
"field_element",
".",
"split",
"(",
"'['",
",",
"1",
")",
"array_field_element",
"=",
"array_field_elements",
"[",
"0",
"]",
"doc",
"=",
"doc",
"[",
"array_field_element",
"]",
"field_element",
"=",
"array_field_elements",
"[",
"1",
"]",
"array_elements",
"=",
"field_element",
".",
"split",
"(",
"']'",
")",
"for",
"array_element",
"in",
"array_elements",
":",
"if",
"not",
"array_element",
":",
"continue",
"if",
"array_element",
".",
"startswith",
"(",
"'['",
")",
":",
"array_element",
"=",
"array_element",
"[",
"1",
":",
"]",
"if",
"array_element",
".",
"isdigit",
"(",
")",
"and",
"isinstance",
"(",
"doc",
",",
"list",
")",
":",
"doc",
"=",
"doc",
"[",
"int",
"(",
"array_element",
")",
"]",
"else",
":",
"doc",
"=",
"doc",
"[",
"array_element",
"]",
"else",
":",
"if",
"field_element",
"not",
"in",
"doc",
":",
"doc",
"[",
"field_element",
"]",
"=",
"{",
"}",
"doc",
"=",
"doc",
"[",
"field_element",
"]",
"field_element",
"=",
"field_elements",
"[",
"0",
"]",
"if",
"field_element",
"in",
"doc",
":",
"output",
"=",
"doc",
"[",
"field_element",
"]",
"if",
"isinstance",
"(",
"output",
",",
"dict",
")",
":",
"output",
"=",
"[",
"output",
",",
"metadata",
"]",
"elif",
"isinstance",
"(",
"output",
",",
"types",
".",
"ListType",
")",
":",
"output",
".",
"append",
"(",
"metadata",
")",
"else",
":",
"output",
"=",
"[",
"metadata",
"]",
"doc",
"[",
"field_element",
"]",
"=",
"output"
] |
inserts the extracted value into doc at the field specified
by output_field
|
[
"inserts",
"the",
"extracted",
"value",
"into",
"doc",
"at",
"the",
"field",
"specified",
"by",
"output_field"
] |
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
|
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L186-L244
|
239,275
|
usc-isi-i2/dig-extractor
|
digExtractor/extractor_processor.py
|
ExtractorProcessor.extract_from_renamed_inputs
|
def extract_from_renamed_inputs(self, doc, renamed_inputs):
"""Apply the extractor to a document containing the renamed_inputs
and insert the resulting value if defined in the value field
of a copy of the extractor's metadata and insert that into the doc"""
extracted_value = self.extractor.extract(renamed_inputs)
if not extracted_value:
return doc
if self.output_fields is not None and isinstance(extracted_value, dict):
if isinstance(self.output_fields, list):
for field in self.output_fields:
if field in extracted_value:
self.insert_extracted_value(
doc, extracted_value[field], field)
elif isinstance(self.output_fields, dict):
for key, value in self.output_fields.iteritems():
if key in extracted_value:
self.insert_extracted_value(
doc, extracted_value[key], value, key)
else:
self.insert_extracted_value(
doc, extracted_value, self.output_field)
|
python
|
def extract_from_renamed_inputs(self, doc, renamed_inputs):
"""Apply the extractor to a document containing the renamed_inputs
and insert the resulting value if defined in the value field
of a copy of the extractor's metadata and insert that into the doc"""
extracted_value = self.extractor.extract(renamed_inputs)
if not extracted_value:
return doc
if self.output_fields is not None and isinstance(extracted_value, dict):
if isinstance(self.output_fields, list):
for field in self.output_fields:
if field in extracted_value:
self.insert_extracted_value(
doc, extracted_value[field], field)
elif isinstance(self.output_fields, dict):
for key, value in self.output_fields.iteritems():
if key in extracted_value:
self.insert_extracted_value(
doc, extracted_value[key], value, key)
else:
self.insert_extracted_value(
doc, extracted_value, self.output_field)
|
[
"def",
"extract_from_renamed_inputs",
"(",
"self",
",",
"doc",
",",
"renamed_inputs",
")",
":",
"extracted_value",
"=",
"self",
".",
"extractor",
".",
"extract",
"(",
"renamed_inputs",
")",
"if",
"not",
"extracted_value",
":",
"return",
"doc",
"if",
"self",
".",
"output_fields",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"extracted_value",
",",
"dict",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"output_fields",
",",
"list",
")",
":",
"for",
"field",
"in",
"self",
".",
"output_fields",
":",
"if",
"field",
"in",
"extracted_value",
":",
"self",
".",
"insert_extracted_value",
"(",
"doc",
",",
"extracted_value",
"[",
"field",
"]",
",",
"field",
")",
"elif",
"isinstance",
"(",
"self",
".",
"output_fields",
",",
"dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"output_fields",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
"in",
"extracted_value",
":",
"self",
".",
"insert_extracted_value",
"(",
"doc",
",",
"extracted_value",
"[",
"key",
"]",
",",
"value",
",",
"key",
")",
"else",
":",
"self",
".",
"insert_extracted_value",
"(",
"doc",
",",
"extracted_value",
",",
"self",
".",
"output_field",
")"
] |
Apply the extractor to a document containing the renamed_inputs
and insert the resulting value if defined in the value field
of a copy of the extractor's metadata and insert that into the doc
|
[
"Apply",
"the",
"extractor",
"to",
"a",
"document",
"containing",
"the",
"renamed_inputs",
"and",
"insert",
"the",
"resulting",
"value",
"if",
"defined",
"in",
"the",
"value",
"field",
"of",
"a",
"copy",
"of",
"the",
"extractor",
"s",
"metadata",
"and",
"insert",
"that",
"into",
"the",
"doc"
] |
87c138e0300d77e35ebeb5f5e9488c3d71e60eb3
|
https://github.com/usc-isi-i2/dig-extractor/blob/87c138e0300d77e35ebeb5f5e9488c3d71e60eb3/digExtractor/extractor_processor.py#L246-L267
|
239,276
|
tarvitz/django-unity-asset-server-http-client
|
duashttp/router.py
|
UnityAssetServerRouter.db_for_write
|
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to duashttp.
"""
if model._meta.app_label == 'duashttp':
if not DUAS_ENABLE_DB_WRITE:
raise ImproperlyConfigured(
"Set `DUAS_ENABLE_DB_WRITE` to True in your settings to enable "
"write operations on unity asset server database"
)
return DUAS_DB_ROUTE_PREFIX
return None
|
python
|
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to duashttp.
"""
if model._meta.app_label == 'duashttp':
if not DUAS_ENABLE_DB_WRITE:
raise ImproperlyConfigured(
"Set `DUAS_ENABLE_DB_WRITE` to True in your settings to enable "
"write operations on unity asset server database"
)
return DUAS_DB_ROUTE_PREFIX
return None
|
[
"def",
"db_for_write",
"(",
"self",
",",
"model",
",",
"*",
"*",
"hints",
")",
":",
"if",
"model",
".",
"_meta",
".",
"app_label",
"==",
"'duashttp'",
":",
"if",
"not",
"DUAS_ENABLE_DB_WRITE",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"Set `DUAS_ENABLE_DB_WRITE` to True in your settings to enable \"",
"\"write operations on unity asset server database\"",
")",
"return",
"DUAS_DB_ROUTE_PREFIX",
"return",
"None"
] |
Attempts to write auth models go to duashttp.
|
[
"Attempts",
"to",
"write",
"auth",
"models",
"go",
"to",
"duashttp",
"."
] |
2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1
|
https://github.com/tarvitz/django-unity-asset-server-http-client/blob/2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1/duashttp/router.py#L23-L34
|
239,277
|
tarvitz/django-unity-asset-server-http-client
|
duashttp/router.py
|
UnityAssetServerRouter.allow_migrate
|
def allow_migrate(self, db, model):
"""
Make sure the auth app only appears in the 'duashttp'
database.
"""
if db == DUAS_DB_ROUTE_PREFIX:
return model._meta.app_label == 'duashttp'
elif model._meta.app_label == 'duashttp':
return False
return None
|
python
|
def allow_migrate(self, db, model):
"""
Make sure the auth app only appears in the 'duashttp'
database.
"""
if db == DUAS_DB_ROUTE_PREFIX:
return model._meta.app_label == 'duashttp'
elif model._meta.app_label == 'duashttp':
return False
return None
|
[
"def",
"allow_migrate",
"(",
"self",
",",
"db",
",",
"model",
")",
":",
"if",
"db",
"==",
"DUAS_DB_ROUTE_PREFIX",
":",
"return",
"model",
".",
"_meta",
".",
"app_label",
"==",
"'duashttp'",
"elif",
"model",
".",
"_meta",
".",
"app_label",
"==",
"'duashttp'",
":",
"return",
"False",
"return",
"None"
] |
Make sure the auth app only appears in the 'duashttp'
database.
|
[
"Make",
"sure",
"the",
"auth",
"app",
"only",
"appears",
"in",
"the",
"duashttp",
"database",
"."
] |
2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1
|
https://github.com/tarvitz/django-unity-asset-server-http-client/blob/2b7e3b1116b5e98b31c2e267bdd66a77e0579ad1/duashttp/router.py#L45-L54
|
239,278
|
aaronbassett/sometimes
|
sometimes/decorators.py
|
sometimes
|
def sometimes(fn):
"""
They've done studies, you know. 50% of the time,
it works every time.
"""
def wrapped(*args, **kwargs):
wrapped.x += 1
if wrapped.x % 2 == 1:
return fn(*args, **kwargs)
wrapped.x = 0
return wrapped
|
python
|
def sometimes(fn):
"""
They've done studies, you know. 50% of the time,
it works every time.
"""
def wrapped(*args, **kwargs):
wrapped.x += 1
if wrapped.x % 2 == 1:
return fn(*args, **kwargs)
wrapped.x = 0
return wrapped
|
[
"def",
"sometimes",
"(",
"fn",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"wrapped",
".",
"x",
"+=",
"1",
"if",
"wrapped",
".",
"x",
"%",
"2",
"==",
"1",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"wrapped",
".",
"x",
"=",
"0",
"return",
"wrapped"
] |
They've done studies, you know. 50% of the time,
it works every time.
|
[
"They",
"ve",
"done",
"studies",
"you",
"know",
".",
"50%",
"of",
"the",
"time",
"it",
"works",
"every",
"time",
"."
] |
d71959c4bdf5643a1d1e4e60f719da94406df6e6
|
https://github.com/aaronbassett/sometimes/blob/d71959c4bdf5643a1d1e4e60f719da94406df6e6/sometimes/decorators.py#L7-L19
|
239,279
|
aaronbassett/sometimes
|
sometimes/decorators.py
|
percent_of_the_time
|
def percent_of_the_time(p):
"""
Function has a X percentage chance of running
"""
def decorator(fn):
def wrapped(*args, **kwargs):
if in_percentage(p):
fn(*args, **kwargs)
return wrapped
return decorator
|
python
|
def percent_of_the_time(p):
"""
Function has a X percentage chance of running
"""
def decorator(fn):
def wrapped(*args, **kwargs):
if in_percentage(p):
fn(*args, **kwargs)
return wrapped
return decorator
|
[
"def",
"percent_of_the_time",
"(",
"p",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"in_percentage",
"(",
"p",
")",
":",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped",
"return",
"decorator"
] |
Function has a X percentage chance of running
|
[
"Function",
"has",
"a",
"X",
"percentage",
"chance",
"of",
"running"
] |
d71959c4bdf5643a1d1e4e60f719da94406df6e6
|
https://github.com/aaronbassett/sometimes/blob/d71959c4bdf5643a1d1e4e60f719da94406df6e6/sometimes/decorators.py#L35-L47
|
239,280
|
aaronbassett/sometimes
|
sometimes/decorators.py
|
rarely
|
def rarely(fn):
"""
Only 5% chance of happening
"""
def wrapped(*args, **kwargs):
if in_percentage(5):
fn(*args, **kwargs)
return wrapped
|
python
|
def rarely(fn):
"""
Only 5% chance of happening
"""
def wrapped(*args, **kwargs):
if in_percentage(5):
fn(*args, **kwargs)
return wrapped
|
[
"def",
"rarely",
"(",
"fn",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"in_percentage",
"(",
"5",
")",
":",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped"
] |
Only 5% chance of happening
|
[
"Only",
"5%",
"chance",
"of",
"happening"
] |
d71959c4bdf5643a1d1e4e60f719da94406df6e6
|
https://github.com/aaronbassett/sometimes/blob/d71959c4bdf5643a1d1e4e60f719da94406df6e6/sometimes/decorators.py#L50-L57
|
239,281
|
aaronbassett/sometimes
|
sometimes/decorators.py
|
mostly
|
def mostly(fn):
"""
95% chance of happening
"""
def wrapped(*args, **kwargs):
if in_percentage(95):
fn(*args, **kwargs)
return wrapped
|
python
|
def mostly(fn):
"""
95% chance of happening
"""
def wrapped(*args, **kwargs):
if in_percentage(95):
fn(*args, **kwargs)
return wrapped
|
[
"def",
"mostly",
"(",
"fn",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"in_percentage",
"(",
"95",
")",
":",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped"
] |
95% chance of happening
|
[
"95%",
"chance",
"of",
"happening"
] |
d71959c4bdf5643a1d1e4e60f719da94406df6e6
|
https://github.com/aaronbassett/sometimes/blob/d71959c4bdf5643a1d1e4e60f719da94406df6e6/sometimes/decorators.py#L60-L67
|
239,282
|
aaronbassett/sometimes
|
sometimes/decorators.py
|
times
|
def times(x, y):
"""
Do something a random amount of times
between x & y
"""
def decorator(fn):
def wrapped(*args, **kwargs):
n = random.randint(x, y)
for z in range(1, n):
fn(*args, **kwargs)
return wrapped
return decorator
|
python
|
def times(x, y):
"""
Do something a random amount of times
between x & y
"""
def decorator(fn):
def wrapped(*args, **kwargs):
n = random.randint(x, y)
for z in range(1, n):
fn(*args, **kwargs)
return wrapped
return decorator
|
[
"def",
"times",
"(",
"x",
",",
"y",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"n",
"=",
"random",
".",
"randint",
"(",
"x",
",",
"y",
")",
"for",
"z",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped",
"return",
"decorator"
] |
Do something a random amount of times
between x & y
|
[
"Do",
"something",
"a",
"random",
"amount",
"of",
"times",
"between",
"x",
"&",
"y"
] |
d71959c4bdf5643a1d1e4e60f719da94406df6e6
|
https://github.com/aaronbassett/sometimes/blob/d71959c4bdf5643a1d1e4e60f719da94406df6e6/sometimes/decorators.py#L70-L84
|
239,283
|
6809/dragonlib
|
dragonlib/core/basic.py
|
BasicTokenUtil.pformat_tokens
|
def pformat_tokens(self, tokens):
"""
format a tokenized BASIC program line. Useful for debugging.
returns a list of formated string lines.
"""
result = []
for token_value in self.iter_token_values(tokens):
char = self.token2ascii(token_value)
if token_value > 0xff:
result.append("\t$%04x -> %s" % (token_value, repr(char)))
else:
result.append("\t $%02x -> %s" % (token_value, repr(char)))
return result
|
python
|
def pformat_tokens(self, tokens):
"""
format a tokenized BASIC program line. Useful for debugging.
returns a list of formated string lines.
"""
result = []
for token_value in self.iter_token_values(tokens):
char = self.token2ascii(token_value)
if token_value > 0xff:
result.append("\t$%04x -> %s" % (token_value, repr(char)))
else:
result.append("\t $%02x -> %s" % (token_value, repr(char)))
return result
|
[
"def",
"pformat_tokens",
"(",
"self",
",",
"tokens",
")",
":",
"result",
"=",
"[",
"]",
"for",
"token_value",
"in",
"self",
".",
"iter_token_values",
"(",
"tokens",
")",
":",
"char",
"=",
"self",
".",
"token2ascii",
"(",
"token_value",
")",
"if",
"token_value",
">",
"0xff",
":",
"result",
".",
"append",
"(",
"\"\\t$%04x -> %s\"",
"%",
"(",
"token_value",
",",
"repr",
"(",
"char",
")",
")",
")",
"else",
":",
"result",
".",
"append",
"(",
"\"\\t $%02x -> %s\"",
"%",
"(",
"token_value",
",",
"repr",
"(",
"char",
")",
")",
")",
"return",
"result"
] |
format a tokenized BASIC program line. Useful for debugging.
returns a list of formated string lines.
|
[
"format",
"a",
"tokenized",
"BASIC",
"program",
"line",
".",
"Useful",
"for",
"debugging",
".",
"returns",
"a",
"list",
"of",
"formated",
"string",
"lines",
"."
] |
faa4011e76c5857db96efdb4199e2fd49711e999
|
https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/core/basic.py#L136-L149
|
239,284
|
6809/dragonlib
|
dragonlib/core/basic.py
|
RenumTool.get_destinations
|
def get_destinations(self, ascii_listing):
"""
returns all line numbers that are used in a jump.
"""
self.destinations = set()
def collect_destinations(matchobj):
numbers = matchobj.group("no")
if numbers:
self.destinations.update(set(
[n.strip() for n in numbers.split(",")]
))
for line in self._iter_lines(ascii_listing):
self.renum_regex.sub(collect_destinations, line)
return sorted([int(no) for no in self.destinations if no])
|
python
|
def get_destinations(self, ascii_listing):
"""
returns all line numbers that are used in a jump.
"""
self.destinations = set()
def collect_destinations(matchobj):
numbers = matchobj.group("no")
if numbers:
self.destinations.update(set(
[n.strip() for n in numbers.split(",")]
))
for line in self._iter_lines(ascii_listing):
self.renum_regex.sub(collect_destinations, line)
return sorted([int(no) for no in self.destinations if no])
|
[
"def",
"get_destinations",
"(",
"self",
",",
"ascii_listing",
")",
":",
"self",
".",
"destinations",
"=",
"set",
"(",
")",
"def",
"collect_destinations",
"(",
"matchobj",
")",
":",
"numbers",
"=",
"matchobj",
".",
"group",
"(",
"\"no\"",
")",
"if",
"numbers",
":",
"self",
".",
"destinations",
".",
"update",
"(",
"set",
"(",
"[",
"n",
".",
"strip",
"(",
")",
"for",
"n",
"in",
"numbers",
".",
"split",
"(",
"\",\"",
")",
"]",
")",
")",
"for",
"line",
"in",
"self",
".",
"_iter_lines",
"(",
"ascii_listing",
")",
":",
"self",
".",
"renum_regex",
".",
"sub",
"(",
"collect_destinations",
",",
"line",
")",
"return",
"sorted",
"(",
"[",
"int",
"(",
"no",
")",
"for",
"no",
"in",
"self",
".",
"destinations",
"if",
"no",
"]",
")"
] |
returns all line numbers that are used in a jump.
|
[
"returns",
"all",
"line",
"numbers",
"that",
"are",
"used",
"in",
"a",
"jump",
"."
] |
faa4011e76c5857db96efdb4199e2fd49711e999
|
https://github.com/6809/dragonlib/blob/faa4011e76c5857db96efdb4199e2fd49711e999/dragonlib/core/basic.py#L451-L466
|
239,285
|
majerteam/sqla_inspect
|
sqla_inspect/excel.py
|
get_cell_format
|
def get_cell_format(column_dict, key=None):
"""
Return the cell format for the given column
:param column_dict: The column datas collected during inspection
:param key: The exportation key
"""
format = column_dict.get('format')
prop = column_dict.get('__col__')
if format is None and prop is not None:
if hasattr(prop, 'columns'):
sqla_column = prop.columns[0]
column_type = getattr(sqla_column.type, 'impl', sqla_column.type)
format = FORMAT_REGISTRY.get_item(column_type)
return format
|
python
|
def get_cell_format(column_dict, key=None):
"""
Return the cell format for the given column
:param column_dict: The column datas collected during inspection
:param key: The exportation key
"""
format = column_dict.get('format')
prop = column_dict.get('__col__')
if format is None and prop is not None:
if hasattr(prop, 'columns'):
sqla_column = prop.columns[0]
column_type = getattr(sqla_column.type, 'impl', sqla_column.type)
format = FORMAT_REGISTRY.get_item(column_type)
return format
|
[
"def",
"get_cell_format",
"(",
"column_dict",
",",
"key",
"=",
"None",
")",
":",
"format",
"=",
"column_dict",
".",
"get",
"(",
"'format'",
")",
"prop",
"=",
"column_dict",
".",
"get",
"(",
"'__col__'",
")",
"if",
"format",
"is",
"None",
"and",
"prop",
"is",
"not",
"None",
":",
"if",
"hasattr",
"(",
"prop",
",",
"'columns'",
")",
":",
"sqla_column",
"=",
"prop",
".",
"columns",
"[",
"0",
"]",
"column_type",
"=",
"getattr",
"(",
"sqla_column",
".",
"type",
",",
"'impl'",
",",
"sqla_column",
".",
"type",
")",
"format",
"=",
"FORMAT_REGISTRY",
".",
"get_item",
"(",
"column_type",
")",
"return",
"format"
] |
Return the cell format for the given column
:param column_dict: The column datas collected during inspection
:param key: The exportation key
|
[
"Return",
"the",
"cell",
"format",
"for",
"the",
"given",
"column"
] |
67edb5541e6a56b0a657d3774d1e19c1110cd402
|
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/excel.py#L189-L204
|
239,286
|
majerteam/sqla_inspect
|
sqla_inspect/excel.py
|
XlsWriter.save_book
|
def save_book(self, f_buf=None):
"""
Return a file buffer containing the resulting xls
:param obj f_buf: A file buffer supporting the write and seek
methods
"""
if f_buf is None:
f_buf = StringIO.StringIO()
f_buf.write(openpyxl.writer.excel.save_virtual_workbook(self.book))
f_buf.seek(0)
return f_buf
|
python
|
def save_book(self, f_buf=None):
"""
Return a file buffer containing the resulting xls
:param obj f_buf: A file buffer supporting the write and seek
methods
"""
if f_buf is None:
f_buf = StringIO.StringIO()
f_buf.write(openpyxl.writer.excel.save_virtual_workbook(self.book))
f_buf.seek(0)
return f_buf
|
[
"def",
"save_book",
"(",
"self",
",",
"f_buf",
"=",
"None",
")",
":",
"if",
"f_buf",
"is",
"None",
":",
"f_buf",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"f_buf",
".",
"write",
"(",
"openpyxl",
".",
"writer",
".",
"excel",
".",
"save_virtual_workbook",
"(",
"self",
".",
"book",
")",
")",
"f_buf",
".",
"seek",
"(",
"0",
")",
"return",
"f_buf"
] |
Return a file buffer containing the resulting xls
:param obj f_buf: A file buffer supporting the write and seek
methods
|
[
"Return",
"a",
"file",
"buffer",
"containing",
"the",
"resulting",
"xls"
] |
67edb5541e6a56b0a657d3774d1e19c1110cd402
|
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/excel.py#L70-L81
|
239,287
|
majerteam/sqla_inspect
|
sqla_inspect/excel.py
|
XlsWriter.set_color
|
def set_color(self, cell, color):
"""
Set the given color to the provided cell
cell
A xls cell object
color
A openpyxl color var
"""
cell.style = cell.style.copy(font=Font(color=Color(rgb=color)))
|
python
|
def set_color(self, cell, color):
"""
Set the given color to the provided cell
cell
A xls cell object
color
A openpyxl color var
"""
cell.style = cell.style.copy(font=Font(color=Color(rgb=color)))
|
[
"def",
"set_color",
"(",
"self",
",",
"cell",
",",
"color",
")",
":",
"cell",
".",
"style",
"=",
"cell",
".",
"style",
".",
"copy",
"(",
"font",
"=",
"Font",
"(",
"color",
"=",
"Color",
"(",
"rgb",
"=",
"color",
")",
")",
")"
] |
Set the given color to the provided cell
cell
A xls cell object
color
A openpyxl color var
|
[
"Set",
"the",
"given",
"color",
"to",
"the",
"provided",
"cell"
] |
67edb5541e6a56b0a657d3774d1e19c1110cd402
|
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/excel.py#L83-L95
|
239,288
|
majerteam/sqla_inspect
|
sqla_inspect/excel.py
|
XlsWriter.format_row
|
def format_row(self, row):
"""
The render method expects rows as lists, here we switch our row format
from dict to list respecting the order of the headers
"""
res = []
headers = getattr(self, 'headers', [])
for column in headers:
column_name = column['name']
value = row.get(column_name, '')
if hasattr(self, "format_%s" % column_name):
value = getattr(self, "format_%s" % column_name)(value)
res.append(value)
return res
|
python
|
def format_row(self, row):
"""
The render method expects rows as lists, here we switch our row format
from dict to list respecting the order of the headers
"""
res = []
headers = getattr(self, 'headers', [])
for column in headers:
column_name = column['name']
value = row.get(column_name, '')
if hasattr(self, "format_%s" % column_name):
value = getattr(self, "format_%s" % column_name)(value)
res.append(value)
return res
|
[
"def",
"format_row",
"(",
"self",
",",
"row",
")",
":",
"res",
"=",
"[",
"]",
"headers",
"=",
"getattr",
"(",
"self",
",",
"'headers'",
",",
"[",
"]",
")",
"for",
"column",
"in",
"headers",
":",
"column_name",
"=",
"column",
"[",
"'name'",
"]",
"value",
"=",
"row",
".",
"get",
"(",
"column_name",
",",
"''",
")",
"if",
"hasattr",
"(",
"self",
",",
"\"format_%s\"",
"%",
"column_name",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"\"format_%s\"",
"%",
"column_name",
")",
"(",
"value",
")",
"res",
".",
"append",
"(",
"value",
")",
"return",
"res"
] |
The render method expects rows as lists, here we switch our row format
from dict to list respecting the order of the headers
|
[
"The",
"render",
"method",
"expects",
"rows",
"as",
"lists",
"here",
"we",
"switch",
"our",
"row",
"format",
"from",
"dict",
"to",
"list",
"respecting",
"the",
"order",
"of",
"the",
"headers"
] |
67edb5541e6a56b0a657d3774d1e19c1110cd402
|
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/excel.py#L97-L110
|
239,289
|
majerteam/sqla_inspect
|
sqla_inspect/excel.py
|
XlsWriter._render_rows
|
def _render_rows(self):
"""
Render the rows in the current stylesheet
"""
_datas = getattr(self, '_datas', ())
headers = getattr(self, 'headers', ())
for index, row in enumerate(_datas):
row_number = index + 2
for col_num, value in enumerate(row):
cell = self.worksheet.cell(row=row_number, column=col_num + 1)
if value is not None:
cell.value = value
else:
cell.value = ""
if len(headers) > col_num:
header = headers[col_num]
format = get_cell_format(header)
if format is not None:
cell.number_format = format
|
python
|
def _render_rows(self):
"""
Render the rows in the current stylesheet
"""
_datas = getattr(self, '_datas', ())
headers = getattr(self, 'headers', ())
for index, row in enumerate(_datas):
row_number = index + 2
for col_num, value in enumerate(row):
cell = self.worksheet.cell(row=row_number, column=col_num + 1)
if value is not None:
cell.value = value
else:
cell.value = ""
if len(headers) > col_num:
header = headers[col_num]
format = get_cell_format(header)
if format is not None:
cell.number_format = format
|
[
"def",
"_render_rows",
"(",
"self",
")",
":",
"_datas",
"=",
"getattr",
"(",
"self",
",",
"'_datas'",
",",
"(",
")",
")",
"headers",
"=",
"getattr",
"(",
"self",
",",
"'headers'",
",",
"(",
")",
")",
"for",
"index",
",",
"row",
"in",
"enumerate",
"(",
"_datas",
")",
":",
"row_number",
"=",
"index",
"+",
"2",
"for",
"col_num",
",",
"value",
"in",
"enumerate",
"(",
"row",
")",
":",
"cell",
"=",
"self",
".",
"worksheet",
".",
"cell",
"(",
"row",
"=",
"row_number",
",",
"column",
"=",
"col_num",
"+",
"1",
")",
"if",
"value",
"is",
"not",
"None",
":",
"cell",
".",
"value",
"=",
"value",
"else",
":",
"cell",
".",
"value",
"=",
"\"\"",
"if",
"len",
"(",
"headers",
")",
">",
"col_num",
":",
"header",
"=",
"headers",
"[",
"col_num",
"]",
"format",
"=",
"get_cell_format",
"(",
"header",
")",
"if",
"format",
"is",
"not",
"None",
":",
"cell",
".",
"number_format",
"=",
"format"
] |
Render the rows in the current stylesheet
|
[
"Render",
"the",
"rows",
"in",
"the",
"current",
"stylesheet"
] |
67edb5541e6a56b0a657d3774d1e19c1110cd402
|
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/excel.py#L130-L148
|
239,290
|
majerteam/sqla_inspect
|
sqla_inspect/excel.py
|
SqlaXlsExporter._get_related_exporter
|
def _get_related_exporter(self, related_obj, column):
"""
returns an SqlaXlsExporter for the given related object and stores it in
the column object as a cache
"""
result = column.get('sqla_xls_exporter')
if result is None:
worksheet = self.book.create_sheet(
title=column.get('label', 'default title')
)
result = column['sqla_xls_exporter'] = SqlaXlsExporter(
related_obj.__class__,
worksheet=worksheet
)
return result
|
python
|
def _get_related_exporter(self, related_obj, column):
"""
returns an SqlaXlsExporter for the given related object and stores it in
the column object as a cache
"""
result = column.get('sqla_xls_exporter')
if result is None:
worksheet = self.book.create_sheet(
title=column.get('label', 'default title')
)
result = column['sqla_xls_exporter'] = SqlaXlsExporter(
related_obj.__class__,
worksheet=worksheet
)
return result
|
[
"def",
"_get_related_exporter",
"(",
"self",
",",
"related_obj",
",",
"column",
")",
":",
"result",
"=",
"column",
".",
"get",
"(",
"'sqla_xls_exporter'",
")",
"if",
"result",
"is",
"None",
":",
"worksheet",
"=",
"self",
".",
"book",
".",
"create_sheet",
"(",
"title",
"=",
"column",
".",
"get",
"(",
"'label'",
",",
"'default title'",
")",
")",
"result",
"=",
"column",
"[",
"'sqla_xls_exporter'",
"]",
"=",
"SqlaXlsExporter",
"(",
"related_obj",
".",
"__class__",
",",
"worksheet",
"=",
"worksheet",
")",
"return",
"result"
] |
returns an SqlaXlsExporter for the given related object and stores it in
the column object as a cache
|
[
"returns",
"an",
"SqlaXlsExporter",
"for",
"the",
"given",
"related",
"object",
"and",
"stores",
"it",
"in",
"the",
"column",
"object",
"as",
"a",
"cache"
] |
67edb5541e6a56b0a657d3774d1e19c1110cd402
|
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/excel.py#L258-L272
|
239,291
|
majerteam/sqla_inspect
|
sqla_inspect/excel.py
|
SqlaXlsExporter._populate
|
def _populate(self):
"""
Enhance the default populate script by handling related elements
"""
XlsWriter._populate(self)
for header in self.headers:
if "sqla_xls_exporter" in header:
header['sqla_xls_exporter']._populate()
|
python
|
def _populate(self):
"""
Enhance the default populate script by handling related elements
"""
XlsWriter._populate(self)
for header in self.headers:
if "sqla_xls_exporter" in header:
header['sqla_xls_exporter']._populate()
|
[
"def",
"_populate",
"(",
"self",
")",
":",
"XlsWriter",
".",
"_populate",
"(",
"self",
")",
"for",
"header",
"in",
"self",
".",
"headers",
":",
"if",
"\"sqla_xls_exporter\"",
"in",
"header",
":",
"header",
"[",
"'sqla_xls_exporter'",
"]",
".",
"_populate",
"(",
")"
] |
Enhance the default populate script by handling related elements
|
[
"Enhance",
"the",
"default",
"populate",
"script",
"by",
"handling",
"related",
"elements"
] |
67edb5541e6a56b0a657d3774d1e19c1110cd402
|
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/excel.py#L301-L308
|
239,292
|
omtinez/pddb
|
pddb/pddb.py
|
PandasDatabase.get_table_schema
|
def get_table_schema(self, tname):
''' Returns a list of column names of the provided table name '''
tname = self._check_tname(tname, noload=True)
if tname not in self._schemas:
raise ValueError('Table "%s" not found in schema store' % tname)
return list(self._schemas[tname])
|
python
|
def get_table_schema(self, tname):
''' Returns a list of column names of the provided table name '''
tname = self._check_tname(tname, noload=True)
if tname not in self._schemas:
raise ValueError('Table "%s" not found in schema store' % tname)
return list(self._schemas[tname])
|
[
"def",
"get_table_schema",
"(",
"self",
",",
"tname",
")",
":",
"tname",
"=",
"self",
".",
"_check_tname",
"(",
"tname",
",",
"noload",
"=",
"True",
")",
"if",
"tname",
"not",
"in",
"self",
".",
"_schemas",
":",
"raise",
"ValueError",
"(",
"'Table \"%s\" not found in schema store'",
"%",
"tname",
")",
"return",
"list",
"(",
"self",
".",
"_schemas",
"[",
"tname",
"]",
")"
] |
Returns a list of column names of the provided table name
|
[
"Returns",
"a",
"list",
"of",
"column",
"names",
"of",
"the",
"provided",
"table",
"name"
] |
a24cee0702c8286c5c466c51ca65cf8dbc2c183c
|
https://github.com/omtinez/pddb/blob/a24cee0702c8286c5c466c51ca65cf8dbc2c183c/pddb/pddb.py#L142-L147
|
239,293
|
omtinez/pddb
|
pddb/pddb.py
|
PandasDatabase.load
|
def load(self, table_names=None, table_schemas=None, table_rowgens=None):
'''
Initiates the tables, schemas and record generators for this database.
Parameters
----------
table_names : list of str, str or None
List of tables to load into this database. If `auto_load` is true, inserting a record
into a new table not provided here will automatically create that table.
table_schemas : dict of <table_name, column_list> or None
Dictionary with each table name as a key and a list of its columns as value. Any keys
present here but not present in `table_names` will also trigger table creation, so
table names provided in both parameters are redundant but harmless.
table_rowgens: dict of <table_name, function> or None
For all tables present in the keys of the provided dictionary, when an insert operation
occurs, the corresponding function is called. The function must return a dictionary and
is used as a "base record" which is complemented by the actual record being inserted.
For example, when a table has a rowgen like `lambda: {"Timestamp": time.ctime()}` and
a record like `{"Name": "John"}` is inserted, the database will then contain a record
like `{"Timestamp": "Sun Jan 10 08:36:12 2016", "Name": "John"}`.
'''
# Check for table schemas
if table_schemas is not None:
table_schemas = self._check_case_dict(table_schemas, warn=True)
for schema_key, schema_value in table_schemas.items():
table_schemas[schema_key] = self._check_columns(schema_value, add_id=True)
elif not self.dynamic_schema:
raise ValueError('Table schemas must be provided if dynamic schema is disabled')
# Check for row generators
if table_rowgens is not None:
table_rowgens = self._check_case_dict(table_rowgens, warn=True)
# If table_names is not directly provided, infer it from one of the other parameters
if table_names is None:
if table_schemas is not None:
table_names = list(table_schemas.keys())
self._print(
'Inferring table name from table_schemas for tables %r'% table_names)
elif table_rowgens is not None:
table_names = list(table_rowgens.keys())
self._print(
'Inferring table name from table_rowgens for tables %r' % table_names)
else:
req_params = 'table_names,table_schemas,table_rowgens'
raise ValueError(
'At least one of the parameters must be provided: [%s]' % req_params)
table_names = self._check_table_names(table_names, warn=True)
self._print('Loading tables %r' % table_names)
# Update schemas and row generators without losing previous ones
for tname in table_names:
if table_schemas is not None and tname in table_schemas:
self._schemas[tname] = list(table_schemas[tname]) # make a copy
if table_rowgens is not None and tname in table_rowgens:
self._rowgens[tname] = table_rowgens[tname]
with self._lock:
for tname in table_names:
# Standardize case, since Windows paths are case insensitive
tname = self._check_case_str(tname, warn=True)
# CSV has same filename as table under database folder
tpath = os.path.join(self.root_dir, self.name, tname + '.csv')
# Table already exists, simply load it
if os.path.isfile(tpath):
if self.auto_load:
dataframe = read_csv(tpath, dtype=str)
self._db[tname] = dataframe
schema = self._check_columns(dataframe.columns.tolist())
self._schemas[tname] = schema
elif self.persistent:
raise ValueError(
'Auto load tables is disabled but table "%s" already exists and would'
'be overwritten' % tname)
# Table not found, try to create it using given schema
elif table_schemas is not None and tname in self._schemas:
self._db[tname] = DataFrame(columns=self._schemas[tname], dtype=str)
# Table not found, dynamic schema
elif self.dynamic_schema:
self._print('Creating table "%s" using dynamic schema' % tname)
self._db[tname] = DataFrame(columns=self._blank_schema, dtype=str)
self._schemas[tname] = list(self._blank_schema)
# Table not found and schema not given when dynamic_schema not enabled
else:
raise ValueError(
'Table %s not found and schema was not passed as a parameter' % tname)
|
python
|
def load(self, table_names=None, table_schemas=None, table_rowgens=None):
'''
Initiates the tables, schemas and record generators for this database.
Parameters
----------
table_names : list of str, str or None
List of tables to load into this database. If `auto_load` is true, inserting a record
into a new table not provided here will automatically create that table.
table_schemas : dict of <table_name, column_list> or None
Dictionary with each table name as a key and a list of its columns as value. Any keys
present here but not present in `table_names` will also trigger table creation, so
table names provided in both parameters are redundant but harmless.
table_rowgens: dict of <table_name, function> or None
For all tables present in the keys of the provided dictionary, when an insert operation
occurs, the corresponding function is called. The function must return a dictionary and
is used as a "base record" which is complemented by the actual record being inserted.
For example, when a table has a rowgen like `lambda: {"Timestamp": time.ctime()}` and
a record like `{"Name": "John"}` is inserted, the database will then contain a record
like `{"Timestamp": "Sun Jan 10 08:36:12 2016", "Name": "John"}`.
'''
# Check for table schemas
if table_schemas is not None:
table_schemas = self._check_case_dict(table_schemas, warn=True)
for schema_key, schema_value in table_schemas.items():
table_schemas[schema_key] = self._check_columns(schema_value, add_id=True)
elif not self.dynamic_schema:
raise ValueError('Table schemas must be provided if dynamic schema is disabled')
# Check for row generators
if table_rowgens is not None:
table_rowgens = self._check_case_dict(table_rowgens, warn=True)
# If table_names is not directly provided, infer it from one of the other parameters
if table_names is None:
if table_schemas is not None:
table_names = list(table_schemas.keys())
self._print(
'Inferring table name from table_schemas for tables %r'% table_names)
elif table_rowgens is not None:
table_names = list(table_rowgens.keys())
self._print(
'Inferring table name from table_rowgens for tables %r' % table_names)
else:
req_params = 'table_names,table_schemas,table_rowgens'
raise ValueError(
'At least one of the parameters must be provided: [%s]' % req_params)
table_names = self._check_table_names(table_names, warn=True)
self._print('Loading tables %r' % table_names)
# Update schemas and row generators without losing previous ones
for tname in table_names:
if table_schemas is not None and tname in table_schemas:
self._schemas[tname] = list(table_schemas[tname]) # make a copy
if table_rowgens is not None and tname in table_rowgens:
self._rowgens[tname] = table_rowgens[tname]
with self._lock:
for tname in table_names:
# Standardize case, since Windows paths are case insensitive
tname = self._check_case_str(tname, warn=True)
# CSV has same filename as table under database folder
tpath = os.path.join(self.root_dir, self.name, tname + '.csv')
# Table already exists, simply load it
if os.path.isfile(tpath):
if self.auto_load:
dataframe = read_csv(tpath, dtype=str)
self._db[tname] = dataframe
schema = self._check_columns(dataframe.columns.tolist())
self._schemas[tname] = schema
elif self.persistent:
raise ValueError(
'Auto load tables is disabled but table "%s" already exists and would'
'be overwritten' % tname)
# Table not found, try to create it using given schema
elif table_schemas is not None and tname in self._schemas:
self._db[tname] = DataFrame(columns=self._schemas[tname], dtype=str)
# Table not found, dynamic schema
elif self.dynamic_schema:
self._print('Creating table "%s" using dynamic schema' % tname)
self._db[tname] = DataFrame(columns=self._blank_schema, dtype=str)
self._schemas[tname] = list(self._blank_schema)
# Table not found and schema not given when dynamic_schema not enabled
else:
raise ValueError(
'Table %s not found and schema was not passed as a parameter' % tname)
|
[
"def",
"load",
"(",
"self",
",",
"table_names",
"=",
"None",
",",
"table_schemas",
"=",
"None",
",",
"table_rowgens",
"=",
"None",
")",
":",
"# Check for table schemas",
"if",
"table_schemas",
"is",
"not",
"None",
":",
"table_schemas",
"=",
"self",
".",
"_check_case_dict",
"(",
"table_schemas",
",",
"warn",
"=",
"True",
")",
"for",
"schema_key",
",",
"schema_value",
"in",
"table_schemas",
".",
"items",
"(",
")",
":",
"table_schemas",
"[",
"schema_key",
"]",
"=",
"self",
".",
"_check_columns",
"(",
"schema_value",
",",
"add_id",
"=",
"True",
")",
"elif",
"not",
"self",
".",
"dynamic_schema",
":",
"raise",
"ValueError",
"(",
"'Table schemas must be provided if dynamic schema is disabled'",
")",
"# Check for row generators",
"if",
"table_rowgens",
"is",
"not",
"None",
":",
"table_rowgens",
"=",
"self",
".",
"_check_case_dict",
"(",
"table_rowgens",
",",
"warn",
"=",
"True",
")",
"# If table_names is not directly provided, infer it from one of the other parameters",
"if",
"table_names",
"is",
"None",
":",
"if",
"table_schemas",
"is",
"not",
"None",
":",
"table_names",
"=",
"list",
"(",
"table_schemas",
".",
"keys",
"(",
")",
")",
"self",
".",
"_print",
"(",
"'Inferring table name from table_schemas for tables %r'",
"%",
"table_names",
")",
"elif",
"table_rowgens",
"is",
"not",
"None",
":",
"table_names",
"=",
"list",
"(",
"table_rowgens",
".",
"keys",
"(",
")",
")",
"self",
".",
"_print",
"(",
"'Inferring table name from table_rowgens for tables %r'",
"%",
"table_names",
")",
"else",
":",
"req_params",
"=",
"'table_names,table_schemas,table_rowgens'",
"raise",
"ValueError",
"(",
"'At least one of the parameters must be provided: [%s]'",
"%",
"req_params",
")",
"table_names",
"=",
"self",
".",
"_check_table_names",
"(",
"table_names",
",",
"warn",
"=",
"True",
")",
"self",
".",
"_print",
"(",
"'Loading tables %r'",
"%",
"table_names",
")",
"# Update schemas and row generators without losing previous ones",
"for",
"tname",
"in",
"table_names",
":",
"if",
"table_schemas",
"is",
"not",
"None",
"and",
"tname",
"in",
"table_schemas",
":",
"self",
".",
"_schemas",
"[",
"tname",
"]",
"=",
"list",
"(",
"table_schemas",
"[",
"tname",
"]",
")",
"# make a copy",
"if",
"table_rowgens",
"is",
"not",
"None",
"and",
"tname",
"in",
"table_rowgens",
":",
"self",
".",
"_rowgens",
"[",
"tname",
"]",
"=",
"table_rowgens",
"[",
"tname",
"]",
"with",
"self",
".",
"_lock",
":",
"for",
"tname",
"in",
"table_names",
":",
"# Standardize case, since Windows paths are case insensitive",
"tname",
"=",
"self",
".",
"_check_case_str",
"(",
"tname",
",",
"warn",
"=",
"True",
")",
"# CSV has same filename as table under database folder",
"tpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"root_dir",
",",
"self",
".",
"name",
",",
"tname",
"+",
"'.csv'",
")",
"# Table already exists, simply load it",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"tpath",
")",
":",
"if",
"self",
".",
"auto_load",
":",
"dataframe",
"=",
"read_csv",
"(",
"tpath",
",",
"dtype",
"=",
"str",
")",
"self",
".",
"_db",
"[",
"tname",
"]",
"=",
"dataframe",
"schema",
"=",
"self",
".",
"_check_columns",
"(",
"dataframe",
".",
"columns",
".",
"tolist",
"(",
")",
")",
"self",
".",
"_schemas",
"[",
"tname",
"]",
"=",
"schema",
"elif",
"self",
".",
"persistent",
":",
"raise",
"ValueError",
"(",
"'Auto load tables is disabled but table \"%s\" already exists and would'",
"'be overwritten'",
"%",
"tname",
")",
"# Table not found, try to create it using given schema",
"elif",
"table_schemas",
"is",
"not",
"None",
"and",
"tname",
"in",
"self",
".",
"_schemas",
":",
"self",
".",
"_db",
"[",
"tname",
"]",
"=",
"DataFrame",
"(",
"columns",
"=",
"self",
".",
"_schemas",
"[",
"tname",
"]",
",",
"dtype",
"=",
"str",
")",
"# Table not found, dynamic schema",
"elif",
"self",
".",
"dynamic_schema",
":",
"self",
".",
"_print",
"(",
"'Creating table \"%s\" using dynamic schema'",
"%",
"tname",
")",
"self",
".",
"_db",
"[",
"tname",
"]",
"=",
"DataFrame",
"(",
"columns",
"=",
"self",
".",
"_blank_schema",
",",
"dtype",
"=",
"str",
")",
"self",
".",
"_schemas",
"[",
"tname",
"]",
"=",
"list",
"(",
"self",
".",
"_blank_schema",
")",
"# Table not found and schema not given when dynamic_schema not enabled",
"else",
":",
"raise",
"ValueError",
"(",
"'Table %s not found and schema was not passed as a parameter'",
"%",
"tname",
")"
] |
Initiates the tables, schemas and record generators for this database.
Parameters
----------
table_names : list of str, str or None
List of tables to load into this database. If `auto_load` is true, inserting a record
into a new table not provided here will automatically create that table.
table_schemas : dict of <table_name, column_list> or None
Dictionary with each table name as a key and a list of its columns as value. Any keys
present here but not present in `table_names` will also trigger table creation, so
table names provided in both parameters are redundant but harmless.
table_rowgens: dict of <table_name, function> or None
For all tables present in the keys of the provided dictionary, when an insert operation
occurs, the corresponding function is called. The function must return a dictionary and
is used as a "base record" which is complemented by the actual record being inserted.
For example, when a table has a rowgen like `lambda: {"Timestamp": time.ctime()}` and
a record like `{"Name": "John"}` is inserted, the database will then contain a record
like `{"Timestamp": "Sun Jan 10 08:36:12 2016", "Name": "John"}`.
|
[
"Initiates",
"the",
"tables",
"schemas",
"and",
"record",
"generators",
"for",
"this",
"database",
"."
] |
a24cee0702c8286c5c466c51ca65cf8dbc2c183c
|
https://github.com/omtinez/pddb/blob/a24cee0702c8286c5c466c51ca65cf8dbc2c183c/pddb/pddb.py#L160-L253
|
239,294
|
omtinez/pddb
|
pddb/pddb.py
|
PandasDatabase.drop_all
|
def drop_all(self):
''' Drops all tables from this database '''
self.drop(self.get_table_names())
if self.persistent:
with self._lock:
try:
dbfolder = os.path.join(self.root_dir, self.name)
if os.path.exists(dbfolder) and not os.listdir(dbfolder):
rmtree(dbfolder)
except (IOError, WindowsError):
self._print('Failed to delete folder %s when dropping database' % self.name)
finally:
del self
|
python
|
def drop_all(self):
''' Drops all tables from this database '''
self.drop(self.get_table_names())
if self.persistent:
with self._lock:
try:
dbfolder = os.path.join(self.root_dir, self.name)
if os.path.exists(dbfolder) and not os.listdir(dbfolder):
rmtree(dbfolder)
except (IOError, WindowsError):
self._print('Failed to delete folder %s when dropping database' % self.name)
finally:
del self
|
[
"def",
"drop_all",
"(",
"self",
")",
":",
"self",
".",
"drop",
"(",
"self",
".",
"get_table_names",
"(",
")",
")",
"if",
"self",
".",
"persistent",
":",
"with",
"self",
".",
"_lock",
":",
"try",
":",
"dbfolder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"root_dir",
",",
"self",
".",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dbfolder",
")",
"and",
"not",
"os",
".",
"listdir",
"(",
"dbfolder",
")",
":",
"rmtree",
"(",
"dbfolder",
")",
"except",
"(",
"IOError",
",",
"WindowsError",
")",
":",
"self",
".",
"_print",
"(",
"'Failed to delete folder %s when dropping database'",
"%",
"self",
".",
"name",
")",
"finally",
":",
"del",
"self"
] |
Drops all tables from this database
|
[
"Drops",
"all",
"tables",
"from",
"this",
"database"
] |
a24cee0702c8286c5c466c51ca65cf8dbc2c183c
|
https://github.com/omtinez/pddb/blob/a24cee0702c8286c5c466c51ca65cf8dbc2c183c/pddb/pddb.py#L281-L293
|
239,295
|
omtinez/pddb
|
pddb/pddb.py
|
PandasDatabase.find
|
def find(self, tname, where=None, where_not=None, columns=None, astype=None):
'''
Find records in the provided table from the database. If no records are found, return empty
list, str or dataframe depending on the value of `astype`.
Parameters
----------
tname : str
Table to search records from.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the found records, if any.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `dataframe`, `str`,
`dict`, `json`. If this is `None`, falls back to the type provided to the constructor.
If a type was provided to the constructor but the user wants to avoid any casting,
"nonetype" should be passed as the value.
Returns
-------
records : str, list or dataframe
Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.insert("test", record={"Name": "John"})
Name John
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
dtype: object
>>> db.find("test", astype="dict")
[{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}]
>>> db.find("test", astype="dataframe")
__id__ Name
0 dc876999-1f5b-4262-b6bf-c23b875f3a54 John
>>> db.find("test", astype=None)
__id__ Name
0 dc876999-1f5b-4262-b6bf-c23b875f3a54 John
>>> db.find("test", where={"Name": "John"}, astype="dict")
[{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}]
>>> db.find("test", where_not={"Name": "John"}, astype="dict")
[]
'''
try:
# Find is inherently read-only so don't try to autoload table
tname = self._check_tname(tname, noload=True)
except ValueError:
return self._output(DataFrame(), astype=astype)
where = PandasDatabase._check_conditions(where)
where_not = PandasDatabase._check_conditions(where_not)
columns = PandasDatabase._check_type_iter(str, columns)
dataframe = self._db[tname]
if len(columns) > 0 and len(dataframe) > 0:
dataframe = dataframe[columns]
# Parse the conditions to match
if len(where) > 0:
dataframe = dataframe[self._get_condition_mask(dataframe, where)]
# Parse the conditions not to match
if len(where_not) > 0:
dataframe = dataframe[~self._get_condition_mask(dataframe, where_not)]
self._print('Found %d records in table "%s" where %r and where not %r'
% (len(dataframe), tname, where, where_not))
return self._output(dataframe, astype=astype)
|
python
|
def find(self, tname, where=None, where_not=None, columns=None, astype=None):
'''
Find records in the provided table from the database. If no records are found, return empty
list, str or dataframe depending on the value of `astype`.
Parameters
----------
tname : str
Table to search records from.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the found records, if any.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `dataframe`, `str`,
`dict`, `json`. If this is `None`, falls back to the type provided to the constructor.
If a type was provided to the constructor but the user wants to avoid any casting,
"nonetype" should be passed as the value.
Returns
-------
records : str, list or dataframe
Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.insert("test", record={"Name": "John"})
Name John
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
dtype: object
>>> db.find("test", astype="dict")
[{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}]
>>> db.find("test", astype="dataframe")
__id__ Name
0 dc876999-1f5b-4262-b6bf-c23b875f3a54 John
>>> db.find("test", astype=None)
__id__ Name
0 dc876999-1f5b-4262-b6bf-c23b875f3a54 John
>>> db.find("test", where={"Name": "John"}, astype="dict")
[{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}]
>>> db.find("test", where_not={"Name": "John"}, astype="dict")
[]
'''
try:
# Find is inherently read-only so don't try to autoload table
tname = self._check_tname(tname, noload=True)
except ValueError:
return self._output(DataFrame(), astype=astype)
where = PandasDatabase._check_conditions(where)
where_not = PandasDatabase._check_conditions(where_not)
columns = PandasDatabase._check_type_iter(str, columns)
dataframe = self._db[tname]
if len(columns) > 0 and len(dataframe) > 0:
dataframe = dataframe[columns]
# Parse the conditions to match
if len(where) > 0:
dataframe = dataframe[self._get_condition_mask(dataframe, where)]
# Parse the conditions not to match
if len(where_not) > 0:
dataframe = dataframe[~self._get_condition_mask(dataframe, where_not)]
self._print('Found %d records in table "%s" where %r and where not %r'
% (len(dataframe), tname, where, where_not))
return self._output(dataframe, astype=astype)
|
[
"def",
"find",
"(",
"self",
",",
"tname",
",",
"where",
"=",
"None",
",",
"where_not",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"astype",
"=",
"None",
")",
":",
"try",
":",
"# Find is inherently read-only so don't try to autoload table",
"tname",
"=",
"self",
".",
"_check_tname",
"(",
"tname",
",",
"noload",
"=",
"True",
")",
"except",
"ValueError",
":",
"return",
"self",
".",
"_output",
"(",
"DataFrame",
"(",
")",
",",
"astype",
"=",
"astype",
")",
"where",
"=",
"PandasDatabase",
".",
"_check_conditions",
"(",
"where",
")",
"where_not",
"=",
"PandasDatabase",
".",
"_check_conditions",
"(",
"where_not",
")",
"columns",
"=",
"PandasDatabase",
".",
"_check_type_iter",
"(",
"str",
",",
"columns",
")",
"dataframe",
"=",
"self",
".",
"_db",
"[",
"tname",
"]",
"if",
"len",
"(",
"columns",
")",
">",
"0",
"and",
"len",
"(",
"dataframe",
")",
">",
"0",
":",
"dataframe",
"=",
"dataframe",
"[",
"columns",
"]",
"# Parse the conditions to match",
"if",
"len",
"(",
"where",
")",
">",
"0",
":",
"dataframe",
"=",
"dataframe",
"[",
"self",
".",
"_get_condition_mask",
"(",
"dataframe",
",",
"where",
")",
"]",
"# Parse the conditions not to match",
"if",
"len",
"(",
"where_not",
")",
">",
"0",
":",
"dataframe",
"=",
"dataframe",
"[",
"~",
"self",
".",
"_get_condition_mask",
"(",
"dataframe",
",",
"where_not",
")",
"]",
"self",
".",
"_print",
"(",
"'Found %d records in table \"%s\" where %r and where not %r'",
"%",
"(",
"len",
"(",
"dataframe",
")",
",",
"tname",
",",
"where",
",",
"where_not",
")",
")",
"return",
"self",
".",
"_output",
"(",
"dataframe",
",",
"astype",
"=",
"astype",
")"
] |
Find records in the provided table from the database. If no records are found, return empty
list, str or dataframe depending on the value of `astype`.
Parameters
----------
tname : str
Table to search records from.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the found records, if any.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `dataframe`, `str`,
`dict`, `json`. If this is `None`, falls back to the type provided to the constructor.
If a type was provided to the constructor but the user wants to avoid any casting,
"nonetype" should be passed as the value.
Returns
-------
records : str, list or dataframe
Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.insert("test", record={"Name": "John"})
Name John
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
dtype: object
>>> db.find("test", astype="dict")
[{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}]
>>> db.find("test", astype="dataframe")
__id__ Name
0 dc876999-1f5b-4262-b6bf-c23b875f3a54 John
>>> db.find("test", astype=None)
__id__ Name
0 dc876999-1f5b-4262-b6bf-c23b875f3a54 John
>>> db.find("test", where={"Name": "John"}, astype="dict")
[{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}]
>>> db.find("test", where_not={"Name": "John"}, astype="dict")
[]
|
[
"Find",
"records",
"in",
"the",
"provided",
"table",
"from",
"the",
"database",
".",
"If",
"no",
"records",
"are",
"found",
"return",
"empty",
"list",
"str",
"or",
"dataframe",
"depending",
"on",
"the",
"value",
"of",
"astype",
"."
] |
a24cee0702c8286c5c466c51ca65cf8dbc2c183c
|
https://github.com/omtinez/pddb/blob/a24cee0702c8286c5c466c51ca65cf8dbc2c183c/pddb/pddb.py#L401-L471
|
239,296
|
omtinez/pddb
|
pddb/pddb.py
|
PandasDatabase.find_one
|
def find_one(self, tname, where=None, where_not=None, columns=None, astype=None):
'''
Find a single record in the provided table from the database. If multiple match, return
the first one based on the internal order of the records. If no records are found, return
empty dictionary, string or series depending on the value of `astype`.
Parameters
----------
tname : str
Table to search records from.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the found records, if any.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `series`, `str`, `dict`,
`json`. If this is `None`, falls back to the type provided to the constructor.
If a type was provided to the constructor but the user wants to avoid any casting,
"nonetype" should be passed as the value.
Returns
-------
records : str, dict or series
Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.insert("test", record={"Name": "John"})
Name John
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
dtype: object
>>> db.find_one("test", astype="dict")
{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}
>>> db.find_one("test", astype="series")
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
Name John
Name: 0, dtype: object
>>> db.find_one("test", astype=None)
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
Name John
Name: 0, dtype: object
>>> db.find_one("test", where={"Name": "John"}, astype="dict")
{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}
>>> db.find_one("test", where_not={"Name": "John"}, astype="dict")
{}
'''
records = self.find(tname, where=where, where_not=where_not, columns=columns,
astype='dataframe')
return self._output(records, single=True, astype=astype)
|
python
|
def find_one(self, tname, where=None, where_not=None, columns=None, astype=None):
'''
Find a single record in the provided table from the database. If multiple match, return
the first one based on the internal order of the records. If no records are found, return
empty dictionary, string or series depending on the value of `astype`.
Parameters
----------
tname : str
Table to search records from.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the found records, if any.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `series`, `str`, `dict`,
`json`. If this is `None`, falls back to the type provided to the constructor.
If a type was provided to the constructor but the user wants to avoid any casting,
"nonetype" should be passed as the value.
Returns
-------
records : str, dict or series
Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.insert("test", record={"Name": "John"})
Name John
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
dtype: object
>>> db.find_one("test", astype="dict")
{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}
>>> db.find_one("test", astype="series")
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
Name John
Name: 0, dtype: object
>>> db.find_one("test", astype=None)
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
Name John
Name: 0, dtype: object
>>> db.find_one("test", where={"Name": "John"}, astype="dict")
{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}
>>> db.find_one("test", where_not={"Name": "John"}, astype="dict")
{}
'''
records = self.find(tname, where=where, where_not=where_not, columns=columns,
astype='dataframe')
return self._output(records, single=True, astype=astype)
|
[
"def",
"find_one",
"(",
"self",
",",
"tname",
",",
"where",
"=",
"None",
",",
"where_not",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"astype",
"=",
"None",
")",
":",
"records",
"=",
"self",
".",
"find",
"(",
"tname",
",",
"where",
"=",
"where",
",",
"where_not",
"=",
"where_not",
",",
"columns",
"=",
"columns",
",",
"astype",
"=",
"'dataframe'",
")",
"return",
"self",
".",
"_output",
"(",
"records",
",",
"single",
"=",
"True",
",",
"astype",
"=",
"astype",
")"
] |
Find a single record in the provided table from the database. If multiple match, return
the first one based on the internal order of the records. If no records are found, return
empty dictionary, string or series depending on the value of `astype`.
Parameters
----------
tname : str
Table to search records from.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the found records, if any.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `series`, `str`, `dict`,
`json`. If this is `None`, falls back to the type provided to the constructor.
If a type was provided to the constructor but the user wants to avoid any casting,
"nonetype" should be passed as the value.
Returns
-------
records : str, dict or series
Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.insert("test", record={"Name": "John"})
Name John
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
dtype: object
>>> db.find_one("test", astype="dict")
{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}
>>> db.find_one("test", astype="series")
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
Name John
Name: 0, dtype: object
>>> db.find_one("test", astype=None)
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
Name John
Name: 0, dtype: object
>>> db.find_one("test", where={"Name": "John"}, astype="dict")
{'Name': 'John', '__id__': 'dc876999-1f5b-4262-b6bf-c23b875f3a54'}
>>> db.find_one("test", where_not={"Name": "John"}, astype="dict")
{}
|
[
"Find",
"a",
"single",
"record",
"in",
"the",
"provided",
"table",
"from",
"the",
"database",
".",
"If",
"multiple",
"match",
"return",
"the",
"first",
"one",
"based",
"on",
"the",
"internal",
"order",
"of",
"the",
"records",
".",
"If",
"no",
"records",
"are",
"found",
"return",
"empty",
"dictionary",
"string",
"or",
"series",
"depending",
"on",
"the",
"value",
"of",
"astype",
"."
] |
a24cee0702c8286c5c466c51ca65cf8dbc2c183c
|
https://github.com/omtinez/pddb/blob/a24cee0702c8286c5c466c51ca65cf8dbc2c183c/pddb/pddb.py#L473-L525
|
239,297
|
omtinez/pddb
|
pddb/pddb.py
|
PandasDatabase.insert
|
def insert(self, tname, record=None, columns=None, astype=None):
'''
Inserts record into the provided table from the database. Returns inserted record as
list, str or series depending on the value of `astype`.
Parameters
----------
tname : str
Table to insert records into.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the inserted records.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `series`, `str`, `dict`
`json`. If this is `None`, falls back to the type provided to the constructor.
If a type was provided to the constructor but the user wants to avoid any casting,
"nonetype" should be passed as the value.
Returns
-------
record : str, dict or series
Inserted record. Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.insert("test", record={"Name": "John"})
Name John
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
dtype: object
'''
tname = self._check_tname(tname)
record = PandasDatabase._check_dict_type(str, str, record, cast=self.auto_cast)
columns = PandasDatabase._check_type_iter(str, columns)
record[self._id_colname] = str(uuid.uuid4())
# If a row generation function exists for this table, use that
record_new = {}
if tname in self._rowgens:
self._print('Using row generator to create new record in "%s"' % tname)
record_new = self._rowgens[tname]()
# Set as many fields as provided in new record, leave the rest as-is
if record is not None:
for field_key, field_val in record.items():
record_new[field_key] = field_val
with self._lock:
self._print('Inserting new record into "%s": %r' % (tname, record_new))
self._update_schema(tname, record_new.keys())
row = Series(record_new)
self._db[tname].loc[len(self._db[tname])] = row
# Save the changes to disk if required
if self.auto_save:
self.save()
if len(columns) > 0:
row = row[columns]
return self._output(row, single=True, astype=astype)
|
python
|
def insert(self, tname, record=None, columns=None, astype=None):
'''
Inserts record into the provided table from the database. Returns inserted record as
list, str or series depending on the value of `astype`.
Parameters
----------
tname : str
Table to insert records into.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the inserted records.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `series`, `str`, `dict`
`json`. If this is `None`, falls back to the type provided to the constructor.
If a type was provided to the constructor but the user wants to avoid any casting,
"nonetype" should be passed as the value.
Returns
-------
record : str, dict or series
Inserted record. Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.insert("test", record={"Name": "John"})
Name John
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
dtype: object
'''
tname = self._check_tname(tname)
record = PandasDatabase._check_dict_type(str, str, record, cast=self.auto_cast)
columns = PandasDatabase._check_type_iter(str, columns)
record[self._id_colname] = str(uuid.uuid4())
# If a row generation function exists for this table, use that
record_new = {}
if tname in self._rowgens:
self._print('Using row generator to create new record in "%s"' % tname)
record_new = self._rowgens[tname]()
# Set as many fields as provided in new record, leave the rest as-is
if record is not None:
for field_key, field_val in record.items():
record_new[field_key] = field_val
with self._lock:
self._print('Inserting new record into "%s": %r' % (tname, record_new))
self._update_schema(tname, record_new.keys())
row = Series(record_new)
self._db[tname].loc[len(self._db[tname])] = row
# Save the changes to disk if required
if self.auto_save:
self.save()
if len(columns) > 0:
row = row[columns]
return self._output(row, single=True, astype=astype)
|
[
"def",
"insert",
"(",
"self",
",",
"tname",
",",
"record",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"astype",
"=",
"None",
")",
":",
"tname",
"=",
"self",
".",
"_check_tname",
"(",
"tname",
")",
"record",
"=",
"PandasDatabase",
".",
"_check_dict_type",
"(",
"str",
",",
"str",
",",
"record",
",",
"cast",
"=",
"self",
".",
"auto_cast",
")",
"columns",
"=",
"PandasDatabase",
".",
"_check_type_iter",
"(",
"str",
",",
"columns",
")",
"record",
"[",
"self",
".",
"_id_colname",
"]",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"# If a row generation function exists for this table, use that",
"record_new",
"=",
"{",
"}",
"if",
"tname",
"in",
"self",
".",
"_rowgens",
":",
"self",
".",
"_print",
"(",
"'Using row generator to create new record in \"%s\"'",
"%",
"tname",
")",
"record_new",
"=",
"self",
".",
"_rowgens",
"[",
"tname",
"]",
"(",
")",
"# Set as many fields as provided in new record, leave the rest as-is",
"if",
"record",
"is",
"not",
"None",
":",
"for",
"field_key",
",",
"field_val",
"in",
"record",
".",
"items",
"(",
")",
":",
"record_new",
"[",
"field_key",
"]",
"=",
"field_val",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_print",
"(",
"'Inserting new record into \"%s\": %r'",
"%",
"(",
"tname",
",",
"record_new",
")",
")",
"self",
".",
"_update_schema",
"(",
"tname",
",",
"record_new",
".",
"keys",
"(",
")",
")",
"row",
"=",
"Series",
"(",
"record_new",
")",
"self",
".",
"_db",
"[",
"tname",
"]",
".",
"loc",
"[",
"len",
"(",
"self",
".",
"_db",
"[",
"tname",
"]",
")",
"]",
"=",
"row",
"# Save the changes to disk if required",
"if",
"self",
".",
"auto_save",
":",
"self",
".",
"save",
"(",
")",
"if",
"len",
"(",
"columns",
")",
">",
"0",
":",
"row",
"=",
"row",
"[",
"columns",
"]",
"return",
"self",
".",
"_output",
"(",
"row",
",",
"single",
"=",
"True",
",",
"astype",
"=",
"astype",
")"
] |
Inserts record into the provided table from the database. Returns inserted record as
list, str or series depending on the value of `astype`.
Parameters
----------
tname : str
Table to insert records into.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the inserted records.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `series`, `str`, `dict`
`json`. If this is `None`, falls back to the type provided to the constructor.
If a type was provided to the constructor but the user wants to avoid any casting,
"nonetype" should be passed as the value.
Returns
-------
record : str, dict or series
Inserted record. Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.insert("test", record={"Name": "John"})
Name John
__id__ dc876999-1f5b-4262-b6bf-c23b875f3a54
dtype: object
|
[
"Inserts",
"record",
"into",
"the",
"provided",
"table",
"from",
"the",
"database",
".",
"Returns",
"inserted",
"record",
"as",
"list",
"str",
"or",
"series",
"depending",
"on",
"the",
"value",
"of",
"astype",
"."
] |
a24cee0702c8286c5c466c51ca65cf8dbc2c183c
|
https://github.com/omtinez/pddb/blob/a24cee0702c8286c5c466c51ca65cf8dbc2c183c/pddb/pddb.py#L599-L664
|
239,298
|
omtinez/pddb
|
pddb/pddb.py
|
PandasDatabase.upsert
|
def upsert(self, tname, record=None, where=None, where_not=None, columns=None, astype=None):
'''
Attempts to update records in the provided table from the database. If none are found,
inserts new record that would match all the conditions. Returns updated or inserted record
as list, dict, str, dataframe or series depending on the value of `astype`.
Parameters
----------
tname : str
Table to update or insert records into.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the updated or inserted records.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `dataframe`, `series`,
`str`, `dict`, `json`. If this is `None`, falls back to the type provided to the
constructor. If a type was provided to the constructor but the user wants to avoid any
casting, "nonetype" should be passed as the value.
Returns
-------
records : list, dict, str, dataframe or series
Updated or inserted records. Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.upsert("test", record={"Name": "John", "Color": "Blue"})
Color Blue
Name John
__id__ a8f31bdd-8e57-4fa7-96f6-e6b20bf7a9dc
dtype: object
>>> db.upsert("test", where={"Name": "Jane", "Color": "Red"})
Color Red
Name Jane
__id__ 65c3bc2b-020c-48f0-b448-5fdb4e548abe
dtype: object
>>> db.upsert("test", record={"Color": "Yellow"}, where={"Name": "John"})
__id__ Name Color
0 a8f31bdd-8e57-4fa7-96f6-e6b20bf7a9dc John Yellow
'''
tname = self._check_tname(tname)
where = PandasDatabase._check_conditions(where)
where_not = PandasDatabase._check_conditions(where_not)
columns = PandasDatabase._check_type_iter(str, columns)
record = PandasDatabase._check_dict_type(str, str, record, cast=self.auto_cast)
# Attempt search only if where conditions are given
if (where is not None and len(where) > 0) \
or (where_not is not None and len(where_not) > 0):
ixs = self.find(tname, where=where, where_not=where_not, astype='dataframe').index
# If no records matched the where conditions, default to insert
if len(ixs) == 0:
self._print(
'Warning: No records in "%s" matched the conditions %s' % (tname, where))
# Add all the key-value pairs from the where condition
for cond_key, cond_value in where.items():
record[cond_key] = cond_value[0] if len(cond_value) > 0 else None
# Create a new record
record_new = self.insert(tname, record=record, columns=columns, astype='series')
# If the default value of the column provided in where_not conflicts, error out
if where_not is not None and any([record_new[cond_key] in cond_value
for cond_key, cond_value in where_not.items()]):
_id = PandasDatabase._id_colname
self.delete(tname, where={_id: record_new[_id]})
raise ValueError('Cannot insert new record because default values conflict '
'with conditions provided: %s' % where_not)
# Otherwise return created record
return self._output(record_new, astype=astype)
# If existing record(s) must be updated
elif len(ixs) > 0:
self._print('Updating %d record(s) in "%s" where %r and where not %r'
% (len(ixs), tname, where, where_not))
with self._lock:
self._update_schema(tname, record.keys())
for field_key, field_val in record.items():
self._db[tname].loc[ixs, field_key] = field_val
# Save the changes to disk if required
if self.auto_save:
self.save()
# Return updated records
rows = self._db[tname].loc[ixs]
if len(columns) > 0:
rows = rows[columns]
return self._output(rows, astype=astype)
# Insert if no where conditions are given
else:
# Return the new record
new_record = self.insert(tname, record=record, columns=columns, astype='series')
return self._output(new_record, astype=astype)
|
python
|
def upsert(self, tname, record=None, where=None, where_not=None, columns=None, astype=None):
'''
Attempts to update records in the provided table from the database. If none are found,
inserts new record that would match all the conditions. Returns updated or inserted record
as list, dict, str, dataframe or series depending on the value of `astype`.
Parameters
----------
tname : str
Table to update or insert records into.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the updated or inserted records.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `dataframe`, `series`,
`str`, `dict`, `json`. If this is `None`, falls back to the type provided to the
constructor. If a type was provided to the constructor but the user wants to avoid any
casting, "nonetype" should be passed as the value.
Returns
-------
records : list, dict, str, dataframe or series
Updated or inserted records. Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.upsert("test", record={"Name": "John", "Color": "Blue"})
Color Blue
Name John
__id__ a8f31bdd-8e57-4fa7-96f6-e6b20bf7a9dc
dtype: object
>>> db.upsert("test", where={"Name": "Jane", "Color": "Red"})
Color Red
Name Jane
__id__ 65c3bc2b-020c-48f0-b448-5fdb4e548abe
dtype: object
>>> db.upsert("test", record={"Color": "Yellow"}, where={"Name": "John"})
__id__ Name Color
0 a8f31bdd-8e57-4fa7-96f6-e6b20bf7a9dc John Yellow
'''
tname = self._check_tname(tname)
where = PandasDatabase._check_conditions(where)
where_not = PandasDatabase._check_conditions(where_not)
columns = PandasDatabase._check_type_iter(str, columns)
record = PandasDatabase._check_dict_type(str, str, record, cast=self.auto_cast)
# Attempt search only if where conditions are given
if (where is not None and len(where) > 0) \
or (where_not is not None and len(where_not) > 0):
ixs = self.find(tname, where=where, where_not=where_not, astype='dataframe').index
# If no records matched the where conditions, default to insert
if len(ixs) == 0:
self._print(
'Warning: No records in "%s" matched the conditions %s' % (tname, where))
# Add all the key-value pairs from the where condition
for cond_key, cond_value in where.items():
record[cond_key] = cond_value[0] if len(cond_value) > 0 else None
# Create a new record
record_new = self.insert(tname, record=record, columns=columns, astype='series')
# If the default value of the column provided in where_not conflicts, error out
if where_not is not None and any([record_new[cond_key] in cond_value
for cond_key, cond_value in where_not.items()]):
_id = PandasDatabase._id_colname
self.delete(tname, where={_id: record_new[_id]})
raise ValueError('Cannot insert new record because default values conflict '
'with conditions provided: %s' % where_not)
# Otherwise return created record
return self._output(record_new, astype=astype)
# If existing record(s) must be updated
elif len(ixs) > 0:
self._print('Updating %d record(s) in "%s" where %r and where not %r'
% (len(ixs), tname, where, where_not))
with self._lock:
self._update_schema(tname, record.keys())
for field_key, field_val in record.items():
self._db[tname].loc[ixs, field_key] = field_val
# Save the changes to disk if required
if self.auto_save:
self.save()
# Return updated records
rows = self._db[tname].loc[ixs]
if len(columns) > 0:
rows = rows[columns]
return self._output(rows, astype=astype)
# Insert if no where conditions are given
else:
# Return the new record
new_record = self.insert(tname, record=record, columns=columns, astype='series')
return self._output(new_record, astype=astype)
|
[
"def",
"upsert",
"(",
"self",
",",
"tname",
",",
"record",
"=",
"None",
",",
"where",
"=",
"None",
",",
"where_not",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"astype",
"=",
"None",
")",
":",
"tname",
"=",
"self",
".",
"_check_tname",
"(",
"tname",
")",
"where",
"=",
"PandasDatabase",
".",
"_check_conditions",
"(",
"where",
")",
"where_not",
"=",
"PandasDatabase",
".",
"_check_conditions",
"(",
"where_not",
")",
"columns",
"=",
"PandasDatabase",
".",
"_check_type_iter",
"(",
"str",
",",
"columns",
")",
"record",
"=",
"PandasDatabase",
".",
"_check_dict_type",
"(",
"str",
",",
"str",
",",
"record",
",",
"cast",
"=",
"self",
".",
"auto_cast",
")",
"# Attempt search only if where conditions are given",
"if",
"(",
"where",
"is",
"not",
"None",
"and",
"len",
"(",
"where",
")",
">",
"0",
")",
"or",
"(",
"where_not",
"is",
"not",
"None",
"and",
"len",
"(",
"where_not",
")",
">",
"0",
")",
":",
"ixs",
"=",
"self",
".",
"find",
"(",
"tname",
",",
"where",
"=",
"where",
",",
"where_not",
"=",
"where_not",
",",
"astype",
"=",
"'dataframe'",
")",
".",
"index",
"# If no records matched the where conditions, default to insert",
"if",
"len",
"(",
"ixs",
")",
"==",
"0",
":",
"self",
".",
"_print",
"(",
"'Warning: No records in \"%s\" matched the conditions %s'",
"%",
"(",
"tname",
",",
"where",
")",
")",
"# Add all the key-value pairs from the where condition",
"for",
"cond_key",
",",
"cond_value",
"in",
"where",
".",
"items",
"(",
")",
":",
"record",
"[",
"cond_key",
"]",
"=",
"cond_value",
"[",
"0",
"]",
"if",
"len",
"(",
"cond_value",
")",
">",
"0",
"else",
"None",
"# Create a new record",
"record_new",
"=",
"self",
".",
"insert",
"(",
"tname",
",",
"record",
"=",
"record",
",",
"columns",
"=",
"columns",
",",
"astype",
"=",
"'series'",
")",
"# If the default value of the column provided in where_not conflicts, error out",
"if",
"where_not",
"is",
"not",
"None",
"and",
"any",
"(",
"[",
"record_new",
"[",
"cond_key",
"]",
"in",
"cond_value",
"for",
"cond_key",
",",
"cond_value",
"in",
"where_not",
".",
"items",
"(",
")",
"]",
")",
":",
"_id",
"=",
"PandasDatabase",
".",
"_id_colname",
"self",
".",
"delete",
"(",
"tname",
",",
"where",
"=",
"{",
"_id",
":",
"record_new",
"[",
"_id",
"]",
"}",
")",
"raise",
"ValueError",
"(",
"'Cannot insert new record because default values conflict '",
"'with conditions provided: %s'",
"%",
"where_not",
")",
"# Otherwise return created record",
"return",
"self",
".",
"_output",
"(",
"record_new",
",",
"astype",
"=",
"astype",
")",
"# If existing record(s) must be updated",
"elif",
"len",
"(",
"ixs",
")",
">",
"0",
":",
"self",
".",
"_print",
"(",
"'Updating %d record(s) in \"%s\" where %r and where not %r'",
"%",
"(",
"len",
"(",
"ixs",
")",
",",
"tname",
",",
"where",
",",
"where_not",
")",
")",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_update_schema",
"(",
"tname",
",",
"record",
".",
"keys",
"(",
")",
")",
"for",
"field_key",
",",
"field_val",
"in",
"record",
".",
"items",
"(",
")",
":",
"self",
".",
"_db",
"[",
"tname",
"]",
".",
"loc",
"[",
"ixs",
",",
"field_key",
"]",
"=",
"field_val",
"# Save the changes to disk if required",
"if",
"self",
".",
"auto_save",
":",
"self",
".",
"save",
"(",
")",
"# Return updated records",
"rows",
"=",
"self",
".",
"_db",
"[",
"tname",
"]",
".",
"loc",
"[",
"ixs",
"]",
"if",
"len",
"(",
"columns",
")",
">",
"0",
":",
"rows",
"=",
"rows",
"[",
"columns",
"]",
"return",
"self",
".",
"_output",
"(",
"rows",
",",
"astype",
"=",
"astype",
")",
"# Insert if no where conditions are given",
"else",
":",
"# Return the new record",
"new_record",
"=",
"self",
".",
"insert",
"(",
"tname",
",",
"record",
"=",
"record",
",",
"columns",
"=",
"columns",
",",
"astype",
"=",
"'series'",
")",
"return",
"self",
".",
"_output",
"(",
"new_record",
",",
"astype",
"=",
"astype",
")"
] |
Attempts to update records in the provided table from the database. If none are found,
inserts new record that would match all the conditions. Returns updated or inserted record
as list, dict, str, dataframe or series depending on the value of `astype`.
Parameters
----------
tname : str
Table to update or insert records into.
where : dict or None (default `None`)
Dictionary of <column, value> where value can be of str type for exact match or a
compiled regex expression for more advanced matching.
where_not : dict or None (default `None`)
Identical to `where` but for negative-matching.
columns: list of str, str or None (default `None`)
Column(s) to return for the updated or inserted records.
astype: str, type or None (default `None`)
Type to cast the output to. Possible values are: `nonetype`, `dataframe`, `series`,
`str`, `dict`, `json`. If this is `None`, falls back to the type provided to the
constructor. If a type was provided to the constructor but the user wants to avoid any
casting, "nonetype" should be passed as the value.
Returns
-------
records : list, dict, str, dataframe or series
Updated or inserted records. Output type depends on `astype` parameter.
Examples
--------
>>> db = PandasDatabase("test")
>>> db.upsert("test", record={"Name": "John", "Color": "Blue"})
Color Blue
Name John
__id__ a8f31bdd-8e57-4fa7-96f6-e6b20bf7a9dc
dtype: object
>>> db.upsert("test", where={"Name": "Jane", "Color": "Red"})
Color Red
Name Jane
__id__ 65c3bc2b-020c-48f0-b448-5fdb4e548abe
dtype: object
>>> db.upsert("test", record={"Color": "Yellow"}, where={"Name": "John"})
__id__ Name Color
0 a8f31bdd-8e57-4fa7-96f6-e6b20bf7a9dc John Yellow
|
[
"Attempts",
"to",
"update",
"records",
"in",
"the",
"provided",
"table",
"from",
"the",
"database",
".",
"If",
"none",
"are",
"found",
"inserts",
"new",
"record",
"that",
"would",
"match",
"all",
"the",
"conditions",
".",
"Returns",
"updated",
"or",
"inserted",
"record",
"as",
"list",
"dict",
"str",
"dataframe",
"or",
"series",
"depending",
"on",
"the",
"value",
"of",
"astype",
"."
] |
a24cee0702c8286c5c466c51ca65cf8dbc2c183c
|
https://github.com/omtinez/pddb/blob/a24cee0702c8286c5c466c51ca65cf8dbc2c183c/pddb/pddb.py#L666-L770
|
239,299
|
omtinez/pddb
|
pddb/pddb.py
|
PandasDatabase._extract_params
|
def _extract_params(request_dict, param_list, param_fallback=False):
''' Extract pddb parameters from request '''
if not param_list or not request_dict:
return dict()
query = dict()
for param in param_list:
# Retrieve all items in the form of {param: value} and
# convert {param__key: value} into {param: {key: value}}
for query_key, query_value in request_dict.items():
if param == query_key:
query[param] = query_value
else:
query_key_parts = query_key.split('__', 1)
if param == query_key_parts[0]:
query[param] = {query_key_parts[1]: query_value}
# Convert special string "__null__" into Python None
nullifier = lambda d: {k:(nullifier(v) if isinstance(v, dict) else # pylint: disable=used-before-assignment
(None if v == '__null__' else v)) for k, v in d.items()}
# When fallback is enabled and no parameter matched, assume query refers to first parameter
if param_fallback and all([param_key not in query.keys() for param_key in param_list]):
query = {param_list[0]: dict(request_dict)}
# Return a dictionary with only the requested parameters
return {k:v for k, v in nullifier(query).items() if k in param_list}
|
python
|
def _extract_params(request_dict, param_list, param_fallback=False):
''' Extract pddb parameters from request '''
if not param_list or not request_dict:
return dict()
query = dict()
for param in param_list:
# Retrieve all items in the form of {param: value} and
# convert {param__key: value} into {param: {key: value}}
for query_key, query_value in request_dict.items():
if param == query_key:
query[param] = query_value
else:
query_key_parts = query_key.split('__', 1)
if param == query_key_parts[0]:
query[param] = {query_key_parts[1]: query_value}
# Convert special string "__null__" into Python None
nullifier = lambda d: {k:(nullifier(v) if isinstance(v, dict) else # pylint: disable=used-before-assignment
(None if v == '__null__' else v)) for k, v in d.items()}
# When fallback is enabled and no parameter matched, assume query refers to first parameter
if param_fallback and all([param_key not in query.keys() for param_key in param_list]):
query = {param_list[0]: dict(request_dict)}
# Return a dictionary with only the requested parameters
return {k:v for k, v in nullifier(query).items() if k in param_list}
|
[
"def",
"_extract_params",
"(",
"request_dict",
",",
"param_list",
",",
"param_fallback",
"=",
"False",
")",
":",
"if",
"not",
"param_list",
"or",
"not",
"request_dict",
":",
"return",
"dict",
"(",
")",
"query",
"=",
"dict",
"(",
")",
"for",
"param",
"in",
"param_list",
":",
"# Retrieve all items in the form of {param: value} and",
"# convert {param__key: value} into {param: {key: value}}",
"for",
"query_key",
",",
"query_value",
"in",
"request_dict",
".",
"items",
"(",
")",
":",
"if",
"param",
"==",
"query_key",
":",
"query",
"[",
"param",
"]",
"=",
"query_value",
"else",
":",
"query_key_parts",
"=",
"query_key",
".",
"split",
"(",
"'__'",
",",
"1",
")",
"if",
"param",
"==",
"query_key_parts",
"[",
"0",
"]",
":",
"query",
"[",
"param",
"]",
"=",
"{",
"query_key_parts",
"[",
"1",
"]",
":",
"query_value",
"}",
"# Convert special string \"__null__\" into Python None",
"nullifier",
"=",
"lambda",
"d",
":",
"{",
"k",
":",
"(",
"nullifier",
"(",
"v",
")",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
"else",
"# pylint: disable=used-before-assignment",
"(",
"None",
"if",
"v",
"==",
"'__null__'",
"else",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
"}",
"# When fallback is enabled and no parameter matched, assume query refers to first parameter",
"if",
"param_fallback",
"and",
"all",
"(",
"[",
"param_key",
"not",
"in",
"query",
".",
"keys",
"(",
")",
"for",
"param_key",
"in",
"param_list",
"]",
")",
":",
"query",
"=",
"{",
"param_list",
"[",
"0",
"]",
":",
"dict",
"(",
"request_dict",
")",
"}",
"# Return a dictionary with only the requested parameters",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"nullifier",
"(",
"query",
")",
".",
"items",
"(",
")",
"if",
"k",
"in",
"param_list",
"}"
] |
Extract pddb parameters from request
|
[
"Extract",
"pddb",
"parameters",
"from",
"request"
] |
a24cee0702c8286c5c466c51ca65cf8dbc2c183c
|
https://github.com/omtinez/pddb/blob/a24cee0702c8286c5c466c51ca65cf8dbc2c183c/pddb/pddb.py#L970-L997
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.