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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
236,700 | Guake/guake | guake/prefs.py | PrefsCallbacks.on_backspace_binding_changed | def on_backspace_binding_changed(self, combo):
"""Changes the value of compat_backspace in dconf
"""
val = combo.get_active_text()
self.settings.general.set_string('compat-backspace', ERASE_BINDINGS[val]) | python | def on_backspace_binding_changed(self, combo):
val = combo.get_active_text()
self.settings.general.set_string('compat-backspace', ERASE_BINDINGS[val]) | [
"def",
"on_backspace_binding_changed",
"(",
"self",
",",
"combo",
")",
":",
"val",
"=",
"combo",
".",
"get_active_text",
"(",
")",
"self",
".",
"settings",
".",
"general",
".",
"set_string",
"(",
"'compat-backspace'",
",",
"ERASE_BINDINGS",
"[",
"val",
"]",
... | Changes the value of compat_backspace in dconf | [
"Changes",
"the",
"value",
"of",
"compat_backspace",
"in",
"dconf"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L640-L644 |
236,701 | Guake/guake | guake/prefs.py | PrefsCallbacks.on_window_vertical_displacement_value_changed | def on_window_vertical_displacement_value_changed(self, spin):
"""Changes the value of window-vertical-displacement
"""
self.settings.general.set_int('window-vertical-displacement', int(spin.get_value())) | python | def on_window_vertical_displacement_value_changed(self, spin):
self.settings.general.set_int('window-vertical-displacement', int(spin.get_value())) | [
"def",
"on_window_vertical_displacement_value_changed",
"(",
"self",
",",
"spin",
")",
":",
"self",
".",
"settings",
".",
"general",
".",
"set_int",
"(",
"'window-vertical-displacement'",
",",
"int",
"(",
"spin",
".",
"get_value",
"(",
")",
")",
")"
] | Changes the value of window-vertical-displacement | [
"Changes",
"the",
"value",
"of",
"window",
"-",
"vertical",
"-",
"displacement"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L691-L694 |
236,702 | Guake/guake | guake/prefs.py | PrefsCallbacks.on_window_horizontal_displacement_value_changed | def on_window_horizontal_displacement_value_changed(self, spin):
"""Changes the value of window-horizontal-displacement
"""
self.settings.general.set_int('window-horizontal-displacement', int(spin.get_value())) | python | def on_window_horizontal_displacement_value_changed(self, spin):
self.settings.general.set_int('window-horizontal-displacement', int(spin.get_value())) | [
"def",
"on_window_horizontal_displacement_value_changed",
"(",
"self",
",",
"spin",
")",
":",
"self",
".",
"settings",
".",
"general",
".",
"set_int",
"(",
"'window-horizontal-displacement'",
",",
"int",
"(",
"spin",
".",
"get_value",
"(",
")",
")",
")"
] | Changes the value of window-horizontal-displacement | [
"Changes",
"the",
"value",
"of",
"window",
"-",
"horizontal",
"-",
"displacement"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L696-L699 |
236,703 | Guake/guake | guake/prefs.py | PrefsDialog.toggle_use_font_background_sensitivity | def toggle_use_font_background_sensitivity(self, chk):
"""If the user chooses to use the gnome default font
configuration it means that he will not be able to use the
font selector.
"""
self.get_widget('palette_16').set_sensitive(chk.get_active())
self.get_widget('palette_17').set_sensitive(chk.get_active()) | python | def toggle_use_font_background_sensitivity(self, chk):
self.get_widget('palette_16').set_sensitive(chk.get_active())
self.get_widget('palette_17').set_sensitive(chk.get_active()) | [
"def",
"toggle_use_font_background_sensitivity",
"(",
"self",
",",
"chk",
")",
":",
"self",
".",
"get_widget",
"(",
"'palette_16'",
")",
".",
"set_sensitive",
"(",
"chk",
".",
"get_active",
"(",
")",
")",
"self",
".",
"get_widget",
"(",
"'palette_17'",
")",
... | If the user chooses to use the gnome default font
configuration it means that he will not be able to use the
font selector. | [
"If",
"the",
"user",
"chooses",
"to",
"use",
"the",
"gnome",
"default",
"font",
"configuration",
"it",
"means",
"that",
"he",
"will",
"not",
"be",
"able",
"to",
"use",
"the",
"font",
"selector",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L866-L872 |
236,704 | Guake/guake | guake/prefs.py | PrefsDialog.toggle_quick_open_command_line_sensitivity | def toggle_quick_open_command_line_sensitivity(self, chk):
"""When the user unchecks 'enable quick open', the command line should be disabled
"""
self.get_widget('quick_open_command_line').set_sensitive(chk.get_active())
self.get_widget('quick_open_in_current_terminal').set_sensitive(chk.get_active()) | python | def toggle_quick_open_command_line_sensitivity(self, chk):
self.get_widget('quick_open_command_line').set_sensitive(chk.get_active())
self.get_widget('quick_open_in_current_terminal').set_sensitive(chk.get_active()) | [
"def",
"toggle_quick_open_command_line_sensitivity",
"(",
"self",
",",
"chk",
")",
":",
"self",
".",
"get_widget",
"(",
"'quick_open_command_line'",
")",
".",
"set_sensitive",
"(",
"chk",
".",
"get_active",
"(",
")",
")",
"self",
".",
"get_widget",
"(",
"'quick_... | When the user unchecks 'enable quick open', the command line should be disabled | [
"When",
"the",
"user",
"unchecks",
"enable",
"quick",
"open",
"the",
"command",
"line",
"should",
"be",
"disabled"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L880-L884 |
236,705 | Guake/guake | guake/prefs.py | PrefsDialog.on_cursor_shape_changed | def on_cursor_shape_changed(self, combo):
"""Changes the value of cursor_shape in dconf
"""
index = combo.get_active()
self.settings.style.set_int('cursor-shape', index) | python | def on_cursor_shape_changed(self, combo):
index = combo.get_active()
self.settings.style.set_int('cursor-shape', index) | [
"def",
"on_cursor_shape_changed",
"(",
"self",
",",
"combo",
")",
":",
"index",
"=",
"combo",
".",
"get_active",
"(",
")",
"self",
".",
"settings",
".",
"style",
".",
"set_int",
"(",
"'cursor-shape'",
",",
"index",
")"
] | Changes the value of cursor_shape in dconf | [
"Changes",
"the",
"value",
"of",
"cursor_shape",
"in",
"dconf"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L918-L922 |
236,706 | Guake/guake | guake/prefs.py | PrefsDialog.set_palette_name | def set_palette_name(self, palette_name):
"""If the given palette matches an existing one, shows it in the
combobox
"""
combo = self.get_widget('palette_name')
found = False
log.debug("wanting palette: %r", palette_name)
for i in combo.get_model():
if i[0] == palette_name:
combo.set_active_iter(i.iter)
found = True
break
if not found:
combo.set_active(self.custom_palette_index) | python | def set_palette_name(self, palette_name):
combo = self.get_widget('palette_name')
found = False
log.debug("wanting palette: %r", palette_name)
for i in combo.get_model():
if i[0] == palette_name:
combo.set_active_iter(i.iter)
found = True
break
if not found:
combo.set_active(self.custom_palette_index) | [
"def",
"set_palette_name",
"(",
"self",
",",
"palette_name",
")",
":",
"combo",
"=",
"self",
".",
"get_widget",
"(",
"'palette_name'",
")",
"found",
"=",
"False",
"log",
".",
"debug",
"(",
"\"wanting palette: %r\"",
",",
"palette_name",
")",
"for",
"i",
"in"... | If the given palette matches an existing one, shows it in the
combobox | [
"If",
"the",
"given",
"palette",
"matches",
"an",
"existing",
"one",
"shows",
"it",
"in",
"the",
"combobox"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L944-L957 |
236,707 | Guake/guake | guake/prefs.py | PrefsDialog.set_palette_colors | def set_palette_colors(self, palette):
"""Updates the color buttons with the given palette
"""
palette = palette.split(':')
for i, pal in enumerate(palette):
x, color = Gdk.Color.parse(pal)
self.get_widget('palette_%d' % i).set_color(color) | python | def set_palette_colors(self, palette):
palette = palette.split(':')
for i, pal in enumerate(palette):
x, color = Gdk.Color.parse(pal)
self.get_widget('palette_%d' % i).set_color(color) | [
"def",
"set_palette_colors",
"(",
"self",
",",
"palette",
")",
":",
"palette",
"=",
"palette",
".",
"split",
"(",
"':'",
")",
"for",
"i",
",",
"pal",
"in",
"enumerate",
"(",
"palette",
")",
":",
"x",
",",
"color",
"=",
"Gdk",
".",
"Color",
".",
"pa... | Updates the color buttons with the given palette | [
"Updates",
"the",
"color",
"buttons",
"with",
"the",
"given",
"palette"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L1000-L1006 |
236,708 | Guake/guake | guake/prefs.py | PrefsDialog._load_hooks_settings | def _load_hooks_settings(self):
"""load hooks settings"""
log.debug("executing _load_hooks_settings")
hook_show_widget = self.get_widget("hook_show")
hook_show_setting = self.settings.hooks.get_string("show")
if hook_show_widget is not None:
if hook_show_setting is not None:
hook_show_widget.set_text(hook_show_setting) | python | def _load_hooks_settings(self):
log.debug("executing _load_hooks_settings")
hook_show_widget = self.get_widget("hook_show")
hook_show_setting = self.settings.hooks.get_string("show")
if hook_show_widget is not None:
if hook_show_setting is not None:
hook_show_widget.set_text(hook_show_setting) | [
"def",
"_load_hooks_settings",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"executing _load_hooks_settings\"",
")",
"hook_show_widget",
"=",
"self",
".",
"get_widget",
"(",
"\"hook_show\"",
")",
"hook_show_setting",
"=",
"self",
".",
"settings",
".",
"hooks... | load hooks settings | [
"load",
"hooks",
"settings"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L1028-L1035 |
236,709 | Guake/guake | guake/prefs.py | PrefsDialog._load_screen_settings | def _load_screen_settings(self):
"""Load screen settings"""
# display number / use primary display
combo = self.get_widget('display_n')
dest_screen = self.settings.general.get_int('display-n')
# If Guake is configured to use a screen that is not currently attached,
# default to 'primary display' option.
screen = self.get_widget('config-window').get_screen()
n_screens = screen.get_n_monitors()
if dest_screen > n_screens - 1:
self.settings.general.set_boolean('mouse-display', False)
dest_screen = screen.get_primary_monitor()
self.settings.general.set_int('display-n', dest_screen)
if dest_screen == ALWAYS_ON_PRIMARY:
first_item = combo.get_model().get_iter_first()
combo.set_active_iter(first_item)
else:
seen_first = False # first item "always on primary" is special
for i in combo.get_model():
if seen_first:
i_int = int(i[0].split()[0]) # extracts 1 from '1' or from '1 (primary)'
if i_int == dest_screen:
combo.set_active_iter(i.iter)
else:
seen_first = True | python | def _load_screen_settings(self):
# display number / use primary display
combo = self.get_widget('display_n')
dest_screen = self.settings.general.get_int('display-n')
# If Guake is configured to use a screen that is not currently attached,
# default to 'primary display' option.
screen = self.get_widget('config-window').get_screen()
n_screens = screen.get_n_monitors()
if dest_screen > n_screens - 1:
self.settings.general.set_boolean('mouse-display', False)
dest_screen = screen.get_primary_monitor()
self.settings.general.set_int('display-n', dest_screen)
if dest_screen == ALWAYS_ON_PRIMARY:
first_item = combo.get_model().get_iter_first()
combo.set_active_iter(first_item)
else:
seen_first = False # first item "always on primary" is special
for i in combo.get_model():
if seen_first:
i_int = int(i[0].split()[0]) # extracts 1 from '1' or from '1 (primary)'
if i_int == dest_screen:
combo.set_active_iter(i.iter)
else:
seen_first = True | [
"def",
"_load_screen_settings",
"(",
"self",
")",
":",
"# display number / use primary display",
"combo",
"=",
"self",
".",
"get_widget",
"(",
"'display_n'",
")",
"dest_screen",
"=",
"self",
".",
"settings",
".",
"general",
".",
"get_int",
"(",
"'display-n'",
")",... | Load screen settings | [
"Load",
"screen",
"settings"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L1046-L1071 |
236,710 | Guake/guake | guake/prefs.py | PrefsDialog.populate_keys_tree | def populate_keys_tree(self):
"""Reads the HOTKEYS global variable and insert all data in
the TreeStore used by the preferences window treeview.
"""
for group in HOTKEYS:
parent = self.store.append(None, [None, group['label'], None, None])
for item in group['keys']:
if item['key'] == "show-hide" or item['key'] == "show-focus":
accel = self.settings.keybindingsGlobal.get_string(item['key'])
else:
accel = self.settings.keybindingsLocal.get_string(item['key'])
gsettings_path = item['key']
keycode, mask = Gtk.accelerator_parse(accel)
keylabel = Gtk.accelerator_get_label(keycode, mask)
self.store.append(parent, [gsettings_path, item['label'], keylabel, accel])
self.get_widget('treeview-keys').expand_all() | python | def populate_keys_tree(self):
for group in HOTKEYS:
parent = self.store.append(None, [None, group['label'], None, None])
for item in group['keys']:
if item['key'] == "show-hide" or item['key'] == "show-focus":
accel = self.settings.keybindingsGlobal.get_string(item['key'])
else:
accel = self.settings.keybindingsLocal.get_string(item['key'])
gsettings_path = item['key']
keycode, mask = Gtk.accelerator_parse(accel)
keylabel = Gtk.accelerator_get_label(keycode, mask)
self.store.append(parent, [gsettings_path, item['label'], keylabel, accel])
self.get_widget('treeview-keys').expand_all() | [
"def",
"populate_keys_tree",
"(",
"self",
")",
":",
"for",
"group",
"in",
"HOTKEYS",
":",
"parent",
"=",
"self",
".",
"store",
".",
"append",
"(",
"None",
",",
"[",
"None",
",",
"group",
"[",
"'label'",
"]",
",",
"None",
",",
"None",
"]",
")",
"for... | Reads the HOTKEYS global variable and insert all data in
the TreeStore used by the preferences window treeview. | [
"Reads",
"the",
"HOTKEYS",
"global",
"variable",
"and",
"insert",
"all",
"data",
"in",
"the",
"TreeStore",
"used",
"by",
"the",
"preferences",
"window",
"treeview",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L1340-L1355 |
236,711 | Guake/guake | guake/prefs.py | PrefsDialog.populate_display_n | def populate_display_n(self):
"""Get the number of displays and populate this drop-down box
with them all. Prepend the "always on primary" option.
"""
cb = self.get_widget('display_n')
screen = self.get_widget('config-window').get_screen()
cb.append_text("always on primary")
for m in range(0, int(screen.get_n_monitors())):
if m == int(screen.get_primary_monitor()):
# TODO l10n
cb.append_text(str(m) + ' ' + '(primary)')
else:
cb.append_text(str(m)) | python | def populate_display_n(self):
cb = self.get_widget('display_n')
screen = self.get_widget('config-window').get_screen()
cb.append_text("always on primary")
for m in range(0, int(screen.get_n_monitors())):
if m == int(screen.get_primary_monitor()):
# TODO l10n
cb.append_text(str(m) + ' ' + '(primary)')
else:
cb.append_text(str(m)) | [
"def",
"populate_display_n",
"(",
"self",
")",
":",
"cb",
"=",
"self",
".",
"get_widget",
"(",
"'display_n'",
")",
"screen",
"=",
"self",
".",
"get_widget",
"(",
"'config-window'",
")",
".",
"get_screen",
"(",
")",
"cb",
".",
"append_text",
"(",
"\"always ... | Get the number of displays and populate this drop-down box
with them all. Prepend the "always on primary" option. | [
"Get",
"the",
"number",
"of",
"displays",
"and",
"populate",
"this",
"drop",
"-",
"down",
"box",
"with",
"them",
"all",
".",
"Prepend",
"the",
"always",
"on",
"primary",
"option",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L1357-L1371 |
236,712 | Guake/guake | guake/prefs.py | PrefsDialog.on_accel_cleared | def on_accel_cleared(self, cellrendereraccel, path):
"""If the user tries to clear a keybinding with the backspace
key this callback will be called and it just fill the model
with an empty key and set the 'disabled' string in dconf path.
"""
dconf_path = self.store[path][HOTKET_MODEL_INDEX_DCONF]
if dconf_path == "show-hide":
# cannot disable 'show-hide' hotkey
log.warn("Cannot disable 'show-hide' hotkey")
self.settings.keybindingsGlobal.set_string(dconf_path, old_accel)
else:
self.store[path][HOTKET_MODEL_INDEX_HUMAN_ACCEL] = ""
self.store[path][HOTKET_MODEL_INDEX_ACCEL] = "None"
if dconf_path == "show-focus":
self.settings.keybindingsGlobal.set_string(dconf_path, 'disabled')
else:
self.settings.keybindingsLocal.set_string(dconf_path, 'disabled') | python | def on_accel_cleared(self, cellrendereraccel, path):
dconf_path = self.store[path][HOTKET_MODEL_INDEX_DCONF]
if dconf_path == "show-hide":
# cannot disable 'show-hide' hotkey
log.warn("Cannot disable 'show-hide' hotkey")
self.settings.keybindingsGlobal.set_string(dconf_path, old_accel)
else:
self.store[path][HOTKET_MODEL_INDEX_HUMAN_ACCEL] = ""
self.store[path][HOTKET_MODEL_INDEX_ACCEL] = "None"
if dconf_path == "show-focus":
self.settings.keybindingsGlobal.set_string(dconf_path, 'disabled')
else:
self.settings.keybindingsLocal.set_string(dconf_path, 'disabled') | [
"def",
"on_accel_cleared",
"(",
"self",
",",
"cellrendereraccel",
",",
"path",
")",
":",
"dconf_path",
"=",
"self",
".",
"store",
"[",
"path",
"]",
"[",
"HOTKET_MODEL_INDEX_DCONF",
"]",
"if",
"dconf_path",
"==",
"\"show-hide\"",
":",
"# cannot disable 'show-hide' ... | If the user tries to clear a keybinding with the backspace
key this callback will be called and it just fill the model
with an empty key and set the 'disabled' string in dconf path. | [
"If",
"the",
"user",
"tries",
"to",
"clear",
"a",
"keybinding",
"with",
"the",
"backspace",
"key",
"this",
"callback",
"will",
"be",
"called",
"and",
"it",
"just",
"fill",
"the",
"model",
"with",
"an",
"empty",
"key",
"and",
"set",
"the",
"disabled",
"st... | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L1438-L1455 |
236,713 | Guake/guake | guake/prefs.py | PrefsDialog.start_editing | def start_editing(self, treeview, event):
"""Make the treeview grab the focus and start editing the cell
that the user has clicked to avoid confusion with two or three
clicks before editing a keybinding.
Thanks to gnome-keybinding-properties.c =)
"""
x, y = int(event.x), int(event.y)
ret = treeview.get_path_at_pos(x, y)
if not ret:
return False
path, column, cellx, celly = ret
treeview.row_activated(path, Gtk.TreeViewColumn(None))
treeview.set_cursor(path)
return False | python | def start_editing(self, treeview, event):
x, y = int(event.x), int(event.y)
ret = treeview.get_path_at_pos(x, y)
if not ret:
return False
path, column, cellx, celly = ret
treeview.row_activated(path, Gtk.TreeViewColumn(None))
treeview.set_cursor(path)
return False | [
"def",
"start_editing",
"(",
"self",
",",
"treeview",
",",
"event",
")",
":",
"x",
",",
"y",
"=",
"int",
"(",
"event",
".",
"x",
")",
",",
"int",
"(",
"event",
".",
"y",
")",
"ret",
"=",
"treeview",
".",
"get_path_at_pos",
"(",
"x",
",",
"y",
"... | Make the treeview grab the focus and start editing the cell
that the user has clicked to avoid confusion with two or three
clicks before editing a keybinding.
Thanks to gnome-keybinding-properties.c =) | [
"Make",
"the",
"treeview",
"grab",
"the",
"focus",
"and",
"start",
"editing",
"the",
"cell",
"that",
"the",
"user",
"has",
"clicked",
"to",
"avoid",
"confusion",
"with",
"two",
"or",
"three",
"clicks",
"before",
"editing",
"a",
"keybinding",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/prefs.py#L1457-L1474 |
236,714 | Guake/guake | guake/utils.py | save_tabs_when_changed | def save_tabs_when_changed(func):
"""Decorator for save-tabs-when-changed
"""
def wrapper(*args, **kwargs):
func(*args, **kwargs)
log.debug("mom, I've been called: %s %s", func.__name__, func)
# Find me the Guake!
clsname = args[0].__class__.__name__
g = None
if clsname == 'Guake':
g = args[0]
elif getattr(args[0], 'get_guake', None):
g = args[0].get_guake()
elif getattr(args[0], 'get_notebook', None):
g = args[0].get_notebook().guake
elif getattr(args[0], 'guake', None):
g = args[0].guake
elif getattr(args[0], 'notebook', None):
g = args[0].notebook.guake
# Tada!
if g and g.settings.general.get_boolean('save-tabs-when-changed'):
g.save_tabs()
return wrapper | python | def save_tabs_when_changed(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
log.debug("mom, I've been called: %s %s", func.__name__, func)
# Find me the Guake!
clsname = args[0].__class__.__name__
g = None
if clsname == 'Guake':
g = args[0]
elif getattr(args[0], 'get_guake', None):
g = args[0].get_guake()
elif getattr(args[0], 'get_notebook', None):
g = args[0].get_notebook().guake
elif getattr(args[0], 'guake', None):
g = args[0].guake
elif getattr(args[0], 'notebook', None):
g = args[0].notebook.guake
# Tada!
if g and g.settings.general.get_boolean('save-tabs-when-changed'):
g.save_tabs()
return wrapper | [
"def",
"save_tabs_when_changed",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"log",
".",
"debug",
"(",
"\"mom, I've been called: %s %s\"",
",",
"f... | Decorator for save-tabs-when-changed | [
"Decorator",
"for",
"save",
"-",
"tabs",
"-",
"when",
"-",
"changed"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/utils.py#L58-L84 |
236,715 | Guake/guake | guake/utils.py | RectCalculator.get_final_window_monitor | def get_final_window_monitor(cls, settings, window):
"""Gets the final screen number for the main window of guake.
"""
screen = window.get_screen()
# fetch settings
use_mouse = settings.general.get_boolean('mouse-display')
dest_screen = settings.general.get_int('display-n')
if use_mouse:
# TODO PORT get_pointer is deprecated
# https://developer.gnome.org/gtk3/stable/GtkWidget.html#gtk-widget-get-pointer
win, x, y, _ = screen.get_root_window().get_pointer()
dest_screen = screen.get_monitor_at_point(x, y)
# If Guake is configured to use a screen that is not currently attached,
# default to 'primary display' option.
n_screens = screen.get_n_monitors()
if dest_screen > n_screens - 1:
settings.general.set_boolean('mouse-display', False)
settings.general.set_int('display-n', dest_screen)
dest_screen = screen.get_primary_monitor()
# Use primary display if configured
if dest_screen == ALWAYS_ON_PRIMARY:
dest_screen = screen.get_primary_monitor()
return dest_screen | python | def get_final_window_monitor(cls, settings, window):
screen = window.get_screen()
# fetch settings
use_mouse = settings.general.get_boolean('mouse-display')
dest_screen = settings.general.get_int('display-n')
if use_mouse:
# TODO PORT get_pointer is deprecated
# https://developer.gnome.org/gtk3/stable/GtkWidget.html#gtk-widget-get-pointer
win, x, y, _ = screen.get_root_window().get_pointer()
dest_screen = screen.get_monitor_at_point(x, y)
# If Guake is configured to use a screen that is not currently attached,
# default to 'primary display' option.
n_screens = screen.get_n_monitors()
if dest_screen > n_screens - 1:
settings.general.set_boolean('mouse-display', False)
settings.general.set_int('display-n', dest_screen)
dest_screen = screen.get_primary_monitor()
# Use primary display if configured
if dest_screen == ALWAYS_ON_PRIMARY:
dest_screen = screen.get_primary_monitor()
return dest_screen | [
"def",
"get_final_window_monitor",
"(",
"cls",
",",
"settings",
",",
"window",
")",
":",
"screen",
"=",
"window",
".",
"get_screen",
"(",
")",
"# fetch settings",
"use_mouse",
"=",
"settings",
".",
"general",
".",
"get_boolean",
"(",
"'mouse-display'",
")",
"d... | Gets the final screen number for the main window of guake. | [
"Gets",
"the",
"final",
"screen",
"number",
"for",
"the",
"main",
"window",
"of",
"guake",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/utils.py#L312-L341 |
236,716 | Guake/guake | guake/dialogs.py | PromptQuitDialog.quit | def quit(self):
"""Run the "are you sure" dialog for quitting Guake
"""
# Stop an open "close tab" dialog from obstructing a quit
response = self.run() == Gtk.ResponseType.YES
self.destroy()
# Keep Guake focussed after dismissing tab-close prompt
# if tab == -1:
# self.window.present()
return response | python | def quit(self):
# Stop an open "close tab" dialog from obstructing a quit
response = self.run() == Gtk.ResponseType.YES
self.destroy()
# Keep Guake focussed after dismissing tab-close prompt
# if tab == -1:
# self.window.present()
return response | [
"def",
"quit",
"(",
"self",
")",
":",
"# Stop an open \"close tab\" dialog from obstructing a quit",
"response",
"=",
"self",
".",
"run",
"(",
")",
"==",
"Gtk",
".",
"ResponseType",
".",
"YES",
"self",
".",
"destroy",
"(",
")",
"# Keep Guake focussed after dismissin... | Run the "are you sure" dialog for quitting Guake | [
"Run",
"the",
"are",
"you",
"sure",
"dialog",
"for",
"quitting",
"Guake"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/dialogs.py#L70-L79 |
236,717 | Guake/guake | guake/boxes.py | TerminalBox.set_terminal | def set_terminal(self, terminal):
"""Packs the terminal widget.
"""
if self.terminal is not None:
raise RuntimeError("TerminalBox: terminal already set")
self.terminal = terminal
self.terminal.connect("grab-focus", self.on_terminal_focus)
self.terminal.connect("button-press-event", self.on_button_press, None)
self.terminal.connect('child-exited', self.on_terminal_exited)
self.pack_start(self.terminal, True, True, 0)
self.terminal.show()
self.add_scroll_bar() | python | def set_terminal(self, terminal):
if self.terminal is not None:
raise RuntimeError("TerminalBox: terminal already set")
self.terminal = terminal
self.terminal.connect("grab-focus", self.on_terminal_focus)
self.terminal.connect("button-press-event", self.on_button_press, None)
self.terminal.connect('child-exited', self.on_terminal_exited)
self.pack_start(self.terminal, True, True, 0)
self.terminal.show()
self.add_scroll_bar() | [
"def",
"set_terminal",
"(",
"self",
",",
"terminal",
")",
":",
"if",
"self",
".",
"terminal",
"is",
"not",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"TerminalBox: terminal already set\"",
")",
"self",
".",
"terminal",
"=",
"terminal",
"self",
".",
"terminal... | Packs the terminal widget. | [
"Packs",
"the",
"terminal",
"widget",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/boxes.py#L309-L321 |
236,718 | Guake/guake | guake/boxes.py | TerminalBox.add_scroll_bar | def add_scroll_bar(self):
"""Packs the scrollbar.
"""
adj = self.terminal.get_vadjustment()
scroll = Gtk.VScrollbar(adj)
scroll.show()
self.pack_start(scroll, False, False, 0) | python | def add_scroll_bar(self):
adj = self.terminal.get_vadjustment()
scroll = Gtk.VScrollbar(adj)
scroll.show()
self.pack_start(scroll, False, False, 0) | [
"def",
"add_scroll_bar",
"(",
"self",
")",
":",
"adj",
"=",
"self",
".",
"terminal",
".",
"get_vadjustment",
"(",
")",
"scroll",
"=",
"Gtk",
".",
"VScrollbar",
"(",
"adj",
")",
"scroll",
".",
"show",
"(",
")",
"self",
".",
"pack_start",
"(",
"scroll",
... | Packs the scrollbar. | [
"Packs",
"the",
"scrollbar",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/boxes.py#L323-L329 |
236,719 | Guake/guake | guake/guake_app.py | Guake.execute_command | def execute_command(self, command, tab=None):
# TODO DBUS_ONLY
"""Execute the `command' in the `tab'. If tab is None, the
command will be executed in the currently selected
tab. Command should end with '\n', otherwise it will be
appended to the string.
"""
# TODO CONTEXTMENU this has to be rewriten and only serves the
# dbus interface, maybe this should be moved to dbusinterface.py
if not self.get_notebook().has_page():
self.add_tab()
if command[-1] != '\n':
command += '\n'
terminal = self.get_notebook().get_current_terminal()
terminal.feed_child(command) | python | def execute_command(self, command, tab=None):
# TODO DBUS_ONLY
# TODO CONTEXTMENU this has to be rewriten and only serves the
# dbus interface, maybe this should be moved to dbusinterface.py
if not self.get_notebook().has_page():
self.add_tab()
if command[-1] != '\n':
command += '\n'
terminal = self.get_notebook().get_current_terminal()
terminal.feed_child(command) | [
"def",
"execute_command",
"(",
"self",
",",
"command",
",",
"tab",
"=",
"None",
")",
":",
"# TODO DBUS_ONLY",
"# TODO CONTEXTMENU this has to be rewriten and only serves the",
"# dbus interface, maybe this should be moved to dbusinterface.py",
"if",
"not",
"self",
".",
"get_not... | Execute the `command' in the `tab'. If tab is None, the
command will be executed in the currently selected
tab. Command should end with '\n', otherwise it will be
appended to the string. | [
"Execute",
"the",
"command",
"in",
"the",
"tab",
".",
"If",
"tab",
"is",
"None",
"the",
"command",
"will",
"be",
"executed",
"in",
"the",
"currently",
"selected",
"tab",
".",
"Command",
"should",
"end",
"with",
"\\",
"n",
"otherwise",
"it",
"will",
"be",... | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L386-L402 |
236,720 | Guake/guake | guake/guake_app.py | Guake.execute_command_by_uuid | def execute_command_by_uuid(self, tab_uuid, command):
# TODO DBUS_ONLY
"""Execute the `command' in the tab whose terminal has the `tab_uuid' uuid
"""
if command[-1] != '\n':
command += '\n'
try:
tab_uuid = uuid.UUID(tab_uuid)
page_index, = (
index for index, t in enumerate(self.get_notebook().iter_terminals())
if t.get_uuid() == tab_uuid
)
except ValueError:
pass
else:
terminals = self.get_notebook().get_terminals_for_page(page_index)
for current_vte in terminals:
current_vte.feed_child(command) | python | def execute_command_by_uuid(self, tab_uuid, command):
# TODO DBUS_ONLY
if command[-1] != '\n':
command += '\n'
try:
tab_uuid = uuid.UUID(tab_uuid)
page_index, = (
index for index, t in enumerate(self.get_notebook().iter_terminals())
if t.get_uuid() == tab_uuid
)
except ValueError:
pass
else:
terminals = self.get_notebook().get_terminals_for_page(page_index)
for current_vte in terminals:
current_vte.feed_child(command) | [
"def",
"execute_command_by_uuid",
"(",
"self",
",",
"tab_uuid",
",",
"command",
")",
":",
"# TODO DBUS_ONLY",
"if",
"command",
"[",
"-",
"1",
"]",
"!=",
"'\\n'",
":",
"command",
"+=",
"'\\n'",
"try",
":",
"tab_uuid",
"=",
"uuid",
".",
"UUID",
"(",
"tab_u... | Execute the `command' in the tab whose terminal has the `tab_uuid' uuid | [
"Execute",
"the",
"command",
"in",
"the",
"tab",
"whose",
"terminal",
"has",
"the",
"tab_uuid",
"uuid"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L404-L421 |
236,721 | Guake/guake | guake/guake_app.py | Guake.on_window_losefocus | def on_window_losefocus(self, window, event):
"""Hides terminal main window when it loses the focus and if
the window_losefocus gconf variable is True.
"""
if not HidePrevention(self.window).may_hide():
return
value = self.settings.general.get_boolean('window-losefocus')
visible = window.get_property('visible')
self.losefocus_time = get_server_time(self.window)
if visible and value:
log.info("Hiding on focus lose")
self.hide() | python | def on_window_losefocus(self, window, event):
if not HidePrevention(self.window).may_hide():
return
value = self.settings.general.get_boolean('window-losefocus')
visible = window.get_property('visible')
self.losefocus_time = get_server_time(self.window)
if visible and value:
log.info("Hiding on focus lose")
self.hide() | [
"def",
"on_window_losefocus",
"(",
"self",
",",
"window",
",",
"event",
")",
":",
"if",
"not",
"HidePrevention",
"(",
"self",
".",
"window",
")",
".",
"may_hide",
"(",
")",
":",
"return",
"value",
"=",
"self",
".",
"settings",
".",
"general",
".",
"get... | Hides terminal main window when it loses the focus and if
the window_losefocus gconf variable is True. | [
"Hides",
"terminal",
"main",
"window",
"when",
"it",
"loses",
"the",
"focus",
"and",
"if",
"the",
"window_losefocus",
"gconf",
"variable",
"is",
"True",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L423-L435 |
236,722 | Guake/guake | guake/guake_app.py | Guake.show_menu | def show_menu(self, status_icon, button, activate_time):
"""Show the tray icon menu.
"""
menu = self.get_widget('tray-menu')
menu.popup(None, None, None, Gtk.StatusIcon.position_menu, button, activate_time) | python | def show_menu(self, status_icon, button, activate_time):
menu = self.get_widget('tray-menu')
menu.popup(None, None, None, Gtk.StatusIcon.position_menu, button, activate_time) | [
"def",
"show_menu",
"(",
"self",
",",
"status_icon",
",",
"button",
",",
"activate_time",
")",
":",
"menu",
"=",
"self",
".",
"get_widget",
"(",
"'tray-menu'",
")",
"menu",
".",
"popup",
"(",
"None",
",",
"None",
",",
"None",
",",
"Gtk",
".",
"StatusIc... | Show the tray icon menu. | [
"Show",
"the",
"tray",
"icon",
"menu",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L437-L441 |
236,723 | Guake/guake | guake/guake_app.py | Guake.show_hide | def show_hide(self, *args):
"""Toggles the main window visibility
"""
log.debug("Show_hide called")
if self.forceHide:
self.forceHide = False
return
if not HidePrevention(self.window).may_hide():
return
if not self.win_prepare():
return
if not self.window.get_property('visible'):
log.info("Showing the terminal")
self.show()
self.set_terminal_focus()
return
# Disable the focus_if_open feature
# - if doesn't work seamlessly on all system
# - self.window.window.get_state doesn't provides us the right information on all
# systems, especially on MATE/XFCE
#
# if self.client.get_bool(KEY('/general/focus_if_open')):
# restore_focus = False
# if self.window.window:
# state = int(self.window.window.get_state())
# if ((state & GDK_WINDOW_STATE_STICKY or
# state & GDK_WINDOW_STATE_WITHDRAWN
# )):
# restore_focus = True
# else:
# restore_focus = True
# if not self.hidden:
# restore_focus = True
# if restore_focus:
# log.debug("DBG: Restoring the focus to the terminal")
# self.hide()
# self.show()
# self.window.window.focus()
# self.set_terminal_focus()
# return
log.info("Hiding the terminal")
self.hide() | python | def show_hide(self, *args):
log.debug("Show_hide called")
if self.forceHide:
self.forceHide = False
return
if not HidePrevention(self.window).may_hide():
return
if not self.win_prepare():
return
if not self.window.get_property('visible'):
log.info("Showing the terminal")
self.show()
self.set_terminal_focus()
return
# Disable the focus_if_open feature
# - if doesn't work seamlessly on all system
# - self.window.window.get_state doesn't provides us the right information on all
# systems, especially on MATE/XFCE
#
# if self.client.get_bool(KEY('/general/focus_if_open')):
# restore_focus = False
# if self.window.window:
# state = int(self.window.window.get_state())
# if ((state & GDK_WINDOW_STATE_STICKY or
# state & GDK_WINDOW_STATE_WITHDRAWN
# )):
# restore_focus = True
# else:
# restore_focus = True
# if not self.hidden:
# restore_focus = True
# if restore_focus:
# log.debug("DBG: Restoring the focus to the terminal")
# self.hide()
# self.show()
# self.window.window.focus()
# self.set_terminal_focus()
# return
log.info("Hiding the terminal")
self.hide() | [
"def",
"show_hide",
"(",
"self",
",",
"*",
"args",
")",
":",
"log",
".",
"debug",
"(",
"\"Show_hide called\"",
")",
"if",
"self",
".",
"forceHide",
":",
"self",
".",
"forceHide",
"=",
"False",
"return",
"if",
"not",
"HidePrevention",
"(",
"self",
".",
... | Toggles the main window visibility | [
"Toggles",
"the",
"main",
"window",
"visibility"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L472-L518 |
236,724 | Guake/guake | guake/guake_app.py | Guake.show | def show(self):
"""Shows the main window and grabs the focus on it.
"""
self.hidden = False
# setting window in all desktops
window_rect = RectCalculator.set_final_window_rect(self.settings, self.window)
self.window.stick()
# add tab must be called before window.show to avoid a
# blank screen before adding the tab.
if not self.get_notebook().has_page():
self.add_tab()
self.window.set_keep_below(False)
self.window.show_all()
# this is needed because self.window.show_all() results in showing every
# thing which includes the scrollbar too
self.settings.general.triggerOnChangedValue(self.settings.general, "use-scrollbar")
# move the window even when in fullscreen-mode
log.debug("Moving window to: %r", window_rect)
self.window.move(window_rect.x, window_rect.y)
# this works around an issue in fluxbox
if not FullscreenManager(self.settings, self.window).is_fullscreen():
self.settings.general.triggerOnChangedValue(self.settings.general, 'window-height')
time = get_server_time(self.window)
# TODO PORT this
# When minized, the window manager seems to refuse to resume
# log.debug("self.window: %s. Dir=%s", type(self.window), dir(self.window))
# is_iconified = self.is_iconified()
# if is_iconified:
# log.debug("Is iconified. Ubuntu Trick => "
# "removing skip_taskbar_hint and skip_pager_hint "
# "so deiconify can work!")
# self.get_widget('window-root').set_skip_taskbar_hint(False)
# self.get_widget('window-root').set_skip_pager_hint(False)
# self.get_widget('window-root').set_urgency_hint(False)
# log.debug("get_skip_taskbar_hint: {}".format(
# self.get_widget('window-root').get_skip_taskbar_hint()))
# log.debug("get_skip_pager_hint: {}".format(
# self.get_widget('window-root').get_skip_pager_hint()))
# log.debug("get_urgency_hint: {}".format(
# self.get_widget('window-root').get_urgency_hint()))
# glib.timeout_add_seconds(1, lambda: self.timeout_restore(time))
#
log.debug("order to present and deiconify")
self.window.present()
self.window.deiconify()
self.window.show()
self.window.get_window().focus(time)
self.window.set_type_hint(Gdk.WindowTypeHint.DOCK)
self.window.set_type_hint(Gdk.WindowTypeHint.NORMAL)
# log.debug("Restoring skip_taskbar_hint and skip_pager_hint")
# if is_iconified:
# self.get_widget('window-root').set_skip_taskbar_hint(False)
# self.get_widget('window-root').set_skip_pager_hint(False)
# self.get_widget('window-root').set_urgency_hint(False)
# This is here because vte color configuration works only after the
# widget is shown.
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'color')
self.settings.styleBackground.triggerOnChangedValue(self.settings.styleBackground, 'color')
log.debug("Current window position: %r", self.window.get_position())
self.execute_hook('show') | python | def show(self):
self.hidden = False
# setting window in all desktops
window_rect = RectCalculator.set_final_window_rect(self.settings, self.window)
self.window.stick()
# add tab must be called before window.show to avoid a
# blank screen before adding the tab.
if not self.get_notebook().has_page():
self.add_tab()
self.window.set_keep_below(False)
self.window.show_all()
# this is needed because self.window.show_all() results in showing every
# thing which includes the scrollbar too
self.settings.general.triggerOnChangedValue(self.settings.general, "use-scrollbar")
# move the window even when in fullscreen-mode
log.debug("Moving window to: %r", window_rect)
self.window.move(window_rect.x, window_rect.y)
# this works around an issue in fluxbox
if not FullscreenManager(self.settings, self.window).is_fullscreen():
self.settings.general.triggerOnChangedValue(self.settings.general, 'window-height')
time = get_server_time(self.window)
# TODO PORT this
# When minized, the window manager seems to refuse to resume
# log.debug("self.window: %s. Dir=%s", type(self.window), dir(self.window))
# is_iconified = self.is_iconified()
# if is_iconified:
# log.debug("Is iconified. Ubuntu Trick => "
# "removing skip_taskbar_hint and skip_pager_hint "
# "so deiconify can work!")
# self.get_widget('window-root').set_skip_taskbar_hint(False)
# self.get_widget('window-root').set_skip_pager_hint(False)
# self.get_widget('window-root').set_urgency_hint(False)
# log.debug("get_skip_taskbar_hint: {}".format(
# self.get_widget('window-root').get_skip_taskbar_hint()))
# log.debug("get_skip_pager_hint: {}".format(
# self.get_widget('window-root').get_skip_pager_hint()))
# log.debug("get_urgency_hint: {}".format(
# self.get_widget('window-root').get_urgency_hint()))
# glib.timeout_add_seconds(1, lambda: self.timeout_restore(time))
#
log.debug("order to present and deiconify")
self.window.present()
self.window.deiconify()
self.window.show()
self.window.get_window().focus(time)
self.window.set_type_hint(Gdk.WindowTypeHint.DOCK)
self.window.set_type_hint(Gdk.WindowTypeHint.NORMAL)
# log.debug("Restoring skip_taskbar_hint and skip_pager_hint")
# if is_iconified:
# self.get_widget('window-root').set_skip_taskbar_hint(False)
# self.get_widget('window-root').set_skip_pager_hint(False)
# self.get_widget('window-root').set_urgency_hint(False)
# This is here because vte color configuration works only after the
# widget is shown.
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'color')
self.settings.styleBackground.triggerOnChangedValue(self.settings.styleBackground, 'color')
log.debug("Current window position: %r", self.window.get_position())
self.execute_hook('show') | [
"def",
"show",
"(",
"self",
")",
":",
"self",
".",
"hidden",
"=",
"False",
"# setting window in all desktops",
"window_rect",
"=",
"RectCalculator",
".",
"set_final_window_rect",
"(",
"self",
".",
"settings",
",",
"self",
".",
"window",
")",
"self",
".",
"wind... | Shows the main window and grabs the focus on it. | [
"Shows",
"the",
"main",
"window",
"and",
"grabs",
"the",
"focus",
"on",
"it",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L568-L641 |
236,725 | Guake/guake | guake/guake_app.py | Guake.hide | def hide(self):
"""Hides the main window of the terminal and sets the visible
flag to False.
"""
if not HidePrevention(self.window).may_hide():
return
self.hidden = True
self.get_widget('window-root').unstick()
self.window.hide() | python | def hide(self):
if not HidePrevention(self.window).may_hide():
return
self.hidden = True
self.get_widget('window-root').unstick()
self.window.hide() | [
"def",
"hide",
"(",
"self",
")",
":",
"if",
"not",
"HidePrevention",
"(",
"self",
".",
"window",
")",
".",
"may_hide",
"(",
")",
":",
"return",
"self",
".",
"hidden",
"=",
"True",
"self",
".",
"get_widget",
"(",
"'window-root'",
")",
".",
"unstick",
... | Hides the main window of the terminal and sets the visible
flag to False. | [
"Hides",
"the",
"main",
"window",
"of",
"the",
"terminal",
"and",
"sets",
"the",
"visible",
"flag",
"to",
"False",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L660-L668 |
236,726 | Guake/guake | guake/guake_app.py | Guake.load_config | def load_config(self):
""""Just a proxy for all the configuration stuff.
"""
self.settings.general.triggerOnChangedValue(self.settings.general, 'use-trayicon')
self.settings.general.triggerOnChangedValue(self.settings.general, 'prompt-on-quit')
self.settings.general.triggerOnChangedValue(self.settings.general, 'prompt-on-close-tab')
self.settings.general.triggerOnChangedValue(self.settings.general, 'window-tabbar')
self.settings.general.triggerOnChangedValue(self.settings.general, 'mouse-display')
self.settings.general.triggerOnChangedValue(self.settings.general, 'display-n')
self.settings.general.triggerOnChangedValue(self.settings.general, 'window-ontop')
if not FullscreenManager(self.settings, self.window).is_fullscreen():
self.settings.general.triggerOnChangedValue(self.settings.general, 'window-height')
self.settings.general.triggerOnChangedValue(self.settings.general, 'window-width')
self.settings.general.triggerOnChangedValue(self.settings.general, 'use-scrollbar')
self.settings.general.triggerOnChangedValue(self.settings.general, 'history-size')
self.settings.general.triggerOnChangedValue(self.settings.general, 'infinite-history')
self.settings.general.triggerOnChangedValue(self.settings.general, 'use-vte-titles')
self.settings.general.triggerOnChangedValue(self.settings.general, 'set-window-title')
self.settings.general.triggerOnChangedValue(self.settings.general, 'abbreviate-tab-names')
self.settings.general.triggerOnChangedValue(self.settings.general, 'max-tab-name-length')
self.settings.general.triggerOnChangedValue(self.settings.general, 'quick-open-enable')
self.settings.general.triggerOnChangedValue(
self.settings.general, 'quick-open-command-line'
)
self.settings.style.triggerOnChangedValue(self.settings.style, 'cursor-shape')
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'style')
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'palette')
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'palette-name')
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'allow-bold')
self.settings.styleBackground.triggerOnChangedValue(
self.settings.styleBackground, 'transparency'
)
self.settings.general.triggerOnChangedValue(self.settings.general, 'use-default-font')
self.settings.general.triggerOnChangedValue(self.settings.general, 'compat-backspace')
self.settings.general.triggerOnChangedValue(self.settings.general, 'compat-delete') | python | def load_config(self):
"self.settings.general.triggerOnChangedValue(self.settings.general, 'use-trayicon')
self.settings.general.triggerOnChangedValue(self.settings.general, 'prompt-on-quit')
self.settings.general.triggerOnChangedValue(self.settings.general, 'prompt-on-close-tab')
self.settings.general.triggerOnChangedValue(self.settings.general, 'window-tabbar')
self.settings.general.triggerOnChangedValue(self.settings.general, 'mouse-display')
self.settings.general.triggerOnChangedValue(self.settings.general, 'display-n')
self.settings.general.triggerOnChangedValue(self.settings.general, 'window-ontop')
if not FullscreenManager(self.settings, self.window).is_fullscreen():
self.settings.general.triggerOnChangedValue(self.settings.general, 'window-height')
self.settings.general.triggerOnChangedValue(self.settings.general, 'window-width')
self.settings.general.triggerOnChangedValue(self.settings.general, 'use-scrollbar')
self.settings.general.triggerOnChangedValue(self.settings.general, 'history-size')
self.settings.general.triggerOnChangedValue(self.settings.general, 'infinite-history')
self.settings.general.triggerOnChangedValue(self.settings.general, 'use-vte-titles')
self.settings.general.triggerOnChangedValue(self.settings.general, 'set-window-title')
self.settings.general.triggerOnChangedValue(self.settings.general, 'abbreviate-tab-names')
self.settings.general.triggerOnChangedValue(self.settings.general, 'max-tab-name-length')
self.settings.general.triggerOnChangedValue(self.settings.general, 'quick-open-enable')
self.settings.general.triggerOnChangedValue(
self.settings.general, 'quick-open-command-line'
)
self.settings.style.triggerOnChangedValue(self.settings.style, 'cursor-shape')
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'style')
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'palette')
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'palette-name')
self.settings.styleFont.triggerOnChangedValue(self.settings.styleFont, 'allow-bold')
self.settings.styleBackground.triggerOnChangedValue(
self.settings.styleBackground, 'transparency'
)
self.settings.general.triggerOnChangedValue(self.settings.general, 'use-default-font')
self.settings.general.triggerOnChangedValue(self.settings.general, 'compat-backspace')
self.settings.general.triggerOnChangedValue(self.settings.general, 'compat-delete') | [
"def",
"load_config",
"(",
"self",
")",
":",
"self",
".",
"settings",
".",
"general",
".",
"triggerOnChangedValue",
"(",
"self",
".",
"settings",
".",
"general",
",",
"'use-trayicon'",
")",
"self",
".",
"settings",
".",
"general",
".",
"triggerOnChangedValue",... | Just a proxy for all the configuration stuff. | [
"Just",
"a",
"proxy",
"for",
"all",
"the",
"configuration",
"stuff",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L681-L716 |
236,727 | Guake/guake | guake/guake_app.py | Guake.accel_quit | def accel_quit(self, *args):
"""Callback to prompt the user whether to quit Guake or not.
"""
procs = self.notebook_manager.get_running_fg_processes_count()
tabs = self.notebook_manager.get_n_pages()
notebooks = self.notebook_manager.get_n_notebooks()
prompt_cfg = self.settings.general.get_boolean('prompt-on-quit')
prompt_tab_cfg = self.settings.general.get_int('prompt-on-close-tab')
# "Prompt on tab close" config overrides "prompt on quit" config
if prompt_cfg or (prompt_tab_cfg == 1 and procs > 0) or (prompt_tab_cfg == 2):
log.debug("Remaining procs=%r", procs)
if PromptQuitDialog(self.window, procs, tabs, notebooks).quit():
log.info("Quitting Guake")
Gtk.main_quit()
else:
log.info("Quitting Guake")
Gtk.main_quit() | python | def accel_quit(self, *args):
procs = self.notebook_manager.get_running_fg_processes_count()
tabs = self.notebook_manager.get_n_pages()
notebooks = self.notebook_manager.get_n_notebooks()
prompt_cfg = self.settings.general.get_boolean('prompt-on-quit')
prompt_tab_cfg = self.settings.general.get_int('prompt-on-close-tab')
# "Prompt on tab close" config overrides "prompt on quit" config
if prompt_cfg or (prompt_tab_cfg == 1 and procs > 0) or (prompt_tab_cfg == 2):
log.debug("Remaining procs=%r", procs)
if PromptQuitDialog(self.window, procs, tabs, notebooks).quit():
log.info("Quitting Guake")
Gtk.main_quit()
else:
log.info("Quitting Guake")
Gtk.main_quit() | [
"def",
"accel_quit",
"(",
"self",
",",
"*",
"args",
")",
":",
"procs",
"=",
"self",
".",
"notebook_manager",
".",
"get_running_fg_processes_count",
"(",
")",
"tabs",
"=",
"self",
".",
"notebook_manager",
".",
"get_n_pages",
"(",
")",
"notebooks",
"=",
"self"... | Callback to prompt the user whether to quit Guake or not. | [
"Callback",
"to",
"prompt",
"the",
"user",
"whether",
"to",
"quit",
"Guake",
"or",
"not",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L739-L755 |
236,728 | Guake/guake | guake/guake_app.py | Guake.accel_reset_terminal | def accel_reset_terminal(self, *args):
# TODO KEYBINDINGS ONLY
"""Callback to reset and clean the terminal"""
HidePrevention(self.window).prevent()
current_term = self.get_notebook().get_current_terminal()
current_term.reset(True, True)
HidePrevention(self.window).allow()
return True | python | def accel_reset_terminal(self, *args):
# TODO KEYBINDINGS ONLY
HidePrevention(self.window).prevent()
current_term = self.get_notebook().get_current_terminal()
current_term.reset(True, True)
HidePrevention(self.window).allow()
return True | [
"def",
"accel_reset_terminal",
"(",
"self",
",",
"*",
"args",
")",
":",
"# TODO KEYBINDINGS ONLY",
"HidePrevention",
"(",
"self",
".",
"window",
")",
".",
"prevent",
"(",
")",
"current_term",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_termin... | Callback to reset and clean the terminal | [
"Callback",
"to",
"reset",
"and",
"clean",
"the",
"terminal"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L757-L764 |
236,729 | Guake/guake | guake/guake_app.py | Guake.accel_zoom_in | def accel_zoom_in(self, *args):
"""Callback to zoom in.
"""
for term in self.get_notebook().iter_terminals():
term.increase_font_size()
return True | python | def accel_zoom_in(self, *args):
for term in self.get_notebook().iter_terminals():
term.increase_font_size()
return True | [
"def",
"accel_zoom_in",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"term",
"in",
"self",
".",
"get_notebook",
"(",
")",
".",
"iter_terminals",
"(",
")",
":",
"term",
".",
"increase_font_size",
"(",
")",
"return",
"True"
] | Callback to zoom in. | [
"Callback",
"to",
"zoom",
"in",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L766-L771 |
236,730 | Guake/guake | guake/guake_app.py | Guake.accel_zoom_out | def accel_zoom_out(self, *args):
"""Callback to zoom out.
"""
for term in self.get_notebook().iter_terminals():
term.decrease_font_size()
return True | python | def accel_zoom_out(self, *args):
for term in self.get_notebook().iter_terminals():
term.decrease_font_size()
return True | [
"def",
"accel_zoom_out",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"term",
"in",
"self",
".",
"get_notebook",
"(",
")",
".",
"iter_terminals",
"(",
")",
":",
"term",
".",
"decrease_font_size",
"(",
")",
"return",
"True"
] | Callback to zoom out. | [
"Callback",
"to",
"zoom",
"out",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L773-L778 |
236,731 | Guake/guake | guake/guake_app.py | Guake.accel_increase_height | def accel_increase_height(self, *args):
"""Callback to increase height.
"""
height = self.settings.general.get_int('window-height')
self.settings.general.set_int('window-height', min(height + 2, 100))
return True | python | def accel_increase_height(self, *args):
height = self.settings.general.get_int('window-height')
self.settings.general.set_int('window-height', min(height + 2, 100))
return True | [
"def",
"accel_increase_height",
"(",
"self",
",",
"*",
"args",
")",
":",
"height",
"=",
"self",
".",
"settings",
".",
"general",
".",
"get_int",
"(",
"'window-height'",
")",
"self",
".",
"settings",
".",
"general",
".",
"set_int",
"(",
"'window-height'",
"... | Callback to increase height. | [
"Callback",
"to",
"increase",
"height",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L780-L785 |
236,732 | Guake/guake | guake/guake_app.py | Guake.accel_decrease_height | def accel_decrease_height(self, *args):
"""Callback to decrease height.
"""
height = self.settings.general.get_int('window-height')
self.settings.general.set_int('window-height', max(height - 2, 0))
return True | python | def accel_decrease_height(self, *args):
height = self.settings.general.get_int('window-height')
self.settings.general.set_int('window-height', max(height - 2, 0))
return True | [
"def",
"accel_decrease_height",
"(",
"self",
",",
"*",
"args",
")",
":",
"height",
"=",
"self",
".",
"settings",
".",
"general",
".",
"get_int",
"(",
"'window-height'",
")",
"self",
".",
"settings",
".",
"general",
".",
"set_int",
"(",
"'window-height'",
"... | Callback to decrease height. | [
"Callback",
"to",
"decrease",
"height",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L787-L792 |
236,733 | Guake/guake | guake/guake_app.py | Guake.accel_increase_transparency | def accel_increase_transparency(self, *args):
"""Callback to increase transparency.
"""
transparency = self.settings.styleBackground.get_int('transparency')
if int(transparency) - 2 > 0:
self.settings.styleBackground.set_int('transparency', int(transparency) - 2)
return True | python | def accel_increase_transparency(self, *args):
transparency = self.settings.styleBackground.get_int('transparency')
if int(transparency) - 2 > 0:
self.settings.styleBackground.set_int('transparency', int(transparency) - 2)
return True | [
"def",
"accel_increase_transparency",
"(",
"self",
",",
"*",
"args",
")",
":",
"transparency",
"=",
"self",
".",
"settings",
".",
"styleBackground",
".",
"get_int",
"(",
"'transparency'",
")",
"if",
"int",
"(",
"transparency",
")",
"-",
"2",
">",
"0",
":",... | Callback to increase transparency. | [
"Callback",
"to",
"increase",
"transparency",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L794-L800 |
236,734 | Guake/guake | guake/guake_app.py | Guake.accel_decrease_transparency | def accel_decrease_transparency(self, *args):
"""Callback to decrease transparency.
"""
transparency = self.settings.styleBackground.get_int('transparency')
if int(transparency) + 2 < MAX_TRANSPARENCY:
self.settings.styleBackground.set_int('transparency', int(transparency) + 2)
return True | python | def accel_decrease_transparency(self, *args):
transparency = self.settings.styleBackground.get_int('transparency')
if int(transparency) + 2 < MAX_TRANSPARENCY:
self.settings.styleBackground.set_int('transparency', int(transparency) + 2)
return True | [
"def",
"accel_decrease_transparency",
"(",
"self",
",",
"*",
"args",
")",
":",
"transparency",
"=",
"self",
".",
"settings",
".",
"styleBackground",
".",
"get_int",
"(",
"'transparency'",
")",
"if",
"int",
"(",
"transparency",
")",
"+",
"2",
"<",
"MAX_TRANSP... | Callback to decrease transparency. | [
"Callback",
"to",
"decrease",
"transparency",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L802-L808 |
236,735 | Guake/guake | guake/guake_app.py | Guake.accel_toggle_transparency | def accel_toggle_transparency(self, *args):
"""Callback to toggle transparency.
"""
self.transparency_toggled = not self.transparency_toggled
self.settings.styleBackground.triggerOnChangedValue(
self.settings.styleBackground, 'transparency'
)
return True | python | def accel_toggle_transparency(self, *args):
self.transparency_toggled = not self.transparency_toggled
self.settings.styleBackground.triggerOnChangedValue(
self.settings.styleBackground, 'transparency'
)
return True | [
"def",
"accel_toggle_transparency",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"transparency_toggled",
"=",
"not",
"self",
".",
"transparency_toggled",
"self",
".",
"settings",
".",
"styleBackground",
".",
"triggerOnChangedValue",
"(",
"self",
".",
"s... | Callback to toggle transparency. | [
"Callback",
"to",
"toggle",
"transparency",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L810-L817 |
236,736 | Guake/guake | guake/guake_app.py | Guake.accel_prev | def accel_prev(self, *args):
"""Callback to go to the previous tab. Called by the accel key.
"""
if self.get_notebook().get_current_page() == 0:
self.get_notebook().set_current_page(self.get_notebook().get_n_pages() - 1)
else:
self.get_notebook().prev_page()
return True | python | def accel_prev(self, *args):
if self.get_notebook().get_current_page() == 0:
self.get_notebook().set_current_page(self.get_notebook().get_n_pages() - 1)
else:
self.get_notebook().prev_page()
return True | [
"def",
"accel_prev",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"==",
"0",
":",
"self",
".",
"get_notebook",
"(",
")",
".",
"set_current_page",
"(",
"self",
".",
"get_noteboo... | Callback to go to the previous tab. Called by the accel key. | [
"Callback",
"to",
"go",
"to",
"the",
"previous",
"tab",
".",
"Called",
"by",
"the",
"accel",
"key",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L831-L838 |
236,737 | Guake/guake | guake/guake_app.py | Guake.accel_next | def accel_next(self, *args):
"""Callback to go to the next tab. Called by the accel key.
"""
if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():
self.get_notebook().set_current_page(0)
else:
self.get_notebook().next_page()
return True | python | def accel_next(self, *args):
if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():
self.get_notebook().set_current_page(0)
else:
self.get_notebook().next_page()
return True | [
"def",
"accel_next",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"+",
"1",
"==",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_n_pages",
"(",
")",
":",
"self",
".",
"ge... | Callback to go to the next tab. Called by the accel key. | [
"Callback",
"to",
"go",
"to",
"the",
"next",
"tab",
".",
"Called",
"by",
"the",
"accel",
"key",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L840-L847 |
236,738 | Guake/guake | guake/guake_app.py | Guake.accel_move_tab_left | def accel_move_tab_left(self, *args):
# TODO KEYBINDINGS ONLY
""" Callback to move a tab to the left """
pos = self.get_notebook().get_current_page()
if pos != 0:
self.move_tab(pos, pos - 1)
return True | python | def accel_move_tab_left(self, *args):
# TODO KEYBINDINGS ONLY
pos = self.get_notebook().get_current_page()
if pos != 0:
self.move_tab(pos, pos - 1)
return True | [
"def",
"accel_move_tab_left",
"(",
"self",
",",
"*",
"args",
")",
":",
"# TODO KEYBINDINGS ONLY",
"pos",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"if",
"pos",
"!=",
"0",
":",
"self",
".",
"move_tab",
"(",
"pos",
",",... | Callback to move a tab to the left | [
"Callback",
"to",
"move",
"a",
"tab",
"to",
"the",
"left"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L849-L855 |
236,739 | Guake/guake | guake/guake_app.py | Guake.accel_move_tab_right | def accel_move_tab_right(self, *args):
# TODO KEYBINDINGS ONLY
""" Callback to move a tab to the right """
pos = self.get_notebook().get_current_page()
if pos != self.get_notebook().get_n_pages() - 1:
self.move_tab(pos, pos + 1)
return True | python | def accel_move_tab_right(self, *args):
# TODO KEYBINDINGS ONLY
pos = self.get_notebook().get_current_page()
if pos != self.get_notebook().get_n_pages() - 1:
self.move_tab(pos, pos + 1)
return True | [
"def",
"accel_move_tab_right",
"(",
"self",
",",
"*",
"args",
")",
":",
"# TODO KEYBINDINGS ONLY",
"pos",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"if",
"pos",
"!=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_n_p... | Callback to move a tab to the right | [
"Callback",
"to",
"move",
"a",
"tab",
"to",
"the",
"right"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L857-L863 |
236,740 | Guake/guake | guake/guake_app.py | Guake.accel_rename_current_tab | def accel_rename_current_tab(self, *args):
"""Callback to show the rename tab dialog. Called by the accel
key.
"""
page_num = self.get_notebook().get_current_page()
page = self.get_notebook().get_nth_page(page_num)
self.get_notebook().get_tab_label(page).on_rename(None)
return True | python | def accel_rename_current_tab(self, *args):
page_num = self.get_notebook().get_current_page()
page = self.get_notebook().get_nth_page(page_num)
self.get_notebook().get_tab_label(page).on_rename(None)
return True | [
"def",
"accel_rename_current_tab",
"(",
"self",
",",
"*",
"args",
")",
":",
"page_num",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"page",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_nth_page",
"(",
"page_num",... | Callback to show the rename tab dialog. Called by the accel
key. | [
"Callback",
"to",
"show",
"the",
"rename",
"tab",
"dialog",
".",
"Called",
"by",
"the",
"accel",
"key",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L886-L893 |
236,741 | Guake/guake | guake/guake_app.py | Guake.accel_toggle_hide_on_lose_focus | def accel_toggle_hide_on_lose_focus(self, *args):
"""Callback toggle whether the window should hide when it loses
focus. Called by the accel key.
"""
if self.settings.general.get_boolean('window-losefocus'):
self.settings.general.set_boolean('window-losefocus', False)
else:
self.settings.general.set_boolean('window-losefocus', True)
return True | python | def accel_toggle_hide_on_lose_focus(self, *args):
if self.settings.general.get_boolean('window-losefocus'):
self.settings.general.set_boolean('window-losefocus', False)
else:
self.settings.general.set_boolean('window-losefocus', True)
return True | [
"def",
"accel_toggle_hide_on_lose_focus",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"settings",
".",
"general",
".",
"get_boolean",
"(",
"'window-losefocus'",
")",
":",
"self",
".",
"settings",
".",
"general",
".",
"set_boolean",
"(",
"'win... | Callback toggle whether the window should hide when it loses
focus. Called by the accel key. | [
"Callback",
"toggle",
"whether",
"the",
"window",
"should",
"hide",
"when",
"it",
"loses",
"focus",
".",
"Called",
"by",
"the",
"accel",
"key",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L911-L919 |
236,742 | Guake/guake | guake/guake_app.py | Guake.recompute_tabs_titles | def recompute_tabs_titles(self):
"""Updates labels on all tabs. This is required when `self.abbreviate`
changes
"""
use_vte_titles = self.settings.general.get_boolean("use-vte-titles")
if not use_vte_titles:
return
# TODO NOTEBOOK this code only works if there is only one terminal in a
# page, this need to be rewritten
for terminal in self.get_notebook().iter_terminals():
page_num = self.get_notebook().page_num(terminal.get_parent())
self.get_notebook().rename_page(page_num, self.compute_tab_title(terminal), False) | python | def recompute_tabs_titles(self):
use_vte_titles = self.settings.general.get_boolean("use-vte-titles")
if not use_vte_titles:
return
# TODO NOTEBOOK this code only works if there is only one terminal in a
# page, this need to be rewritten
for terminal in self.get_notebook().iter_terminals():
page_num = self.get_notebook().page_num(terminal.get_parent())
self.get_notebook().rename_page(page_num, self.compute_tab_title(terminal), False) | [
"def",
"recompute_tabs_titles",
"(",
"self",
")",
":",
"use_vte_titles",
"=",
"self",
".",
"settings",
".",
"general",
".",
"get_boolean",
"(",
"\"use-vte-titles\"",
")",
"if",
"not",
"use_vte_titles",
":",
"return",
"# TODO NOTEBOOK this code only works if there is onl... | Updates labels on all tabs. This is required when `self.abbreviate`
changes | [
"Updates",
"labels",
"on",
"all",
"tabs",
".",
"This",
"is",
"required",
"when",
"self",
".",
"abbreviate",
"changes"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L933-L945 |
236,743 | Guake/guake | guake/guake_app.py | Guake.compute_tab_title | def compute_tab_title(self, vte):
"""Abbreviate and cut vte terminal title when necessary
"""
vte_title = vte.get_window_title() or _("Terminal")
try:
current_directory = vte.get_current_directory()
if self.abbreviate and vte_title.endswith(current_directory):
parts = current_directory.split('/')
parts = [s[:1] for s in parts[:-1]] + [parts[-1]]
vte_title = vte_title[:len(vte_title) - len(current_directory)] + '/'.join(parts)
except OSError:
pass
return TabNameUtils.shorten(vte_title, self.settings) | python | def compute_tab_title(self, vte):
vte_title = vte.get_window_title() or _("Terminal")
try:
current_directory = vte.get_current_directory()
if self.abbreviate and vte_title.endswith(current_directory):
parts = current_directory.split('/')
parts = [s[:1] for s in parts[:-1]] + [parts[-1]]
vte_title = vte_title[:len(vte_title) - len(current_directory)] + '/'.join(parts)
except OSError:
pass
return TabNameUtils.shorten(vte_title, self.settings) | [
"def",
"compute_tab_title",
"(",
"self",
",",
"vte",
")",
":",
"vte_title",
"=",
"vte",
".",
"get_window_title",
"(",
")",
"or",
"_",
"(",
"\"Terminal\"",
")",
"try",
":",
"current_directory",
"=",
"vte",
".",
"get_current_directory",
"(",
")",
"if",
"self... | Abbreviate and cut vte terminal title when necessary | [
"Abbreviate",
"and",
"cut",
"vte",
"terminal",
"title",
"when",
"necessary"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L947-L959 |
236,744 | Guake/guake | guake/guake_app.py | Guake.close_tab | def close_tab(self, *args):
"""Closes the current tab.
"""
prompt_cfg = self.settings.general.get_int('prompt-on-close-tab')
self.get_notebook().delete_page_current(prompt=prompt_cfg) | python | def close_tab(self, *args):
prompt_cfg = self.settings.general.get_int('prompt-on-close-tab')
self.get_notebook().delete_page_current(prompt=prompt_cfg) | [
"def",
"close_tab",
"(",
"self",
",",
"*",
"args",
")",
":",
"prompt_cfg",
"=",
"self",
".",
"settings",
".",
"general",
".",
"get_int",
"(",
"'prompt-on-close-tab'",
")",
"self",
".",
"get_notebook",
"(",
")",
".",
"delete_page_current",
"(",
"prompt",
"=... | Closes the current tab. | [
"Closes",
"the",
"current",
"tab",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L997-L1001 |
236,745 | Guake/guake | guake/guake_app.py | Guake.rename_tab_uuid | def rename_tab_uuid(self, term_uuid, new_text, user_set=True):
"""Rename an already added tab by its UUID
"""
term_uuid = uuid.UUID(term_uuid)
page_index, = (
index for index, t in enumerate(self.get_notebook().iter_terminals())
if t.get_uuid() == term_uuid
)
self.get_notebook().rename_page(page_index, new_text, user_set) | python | def rename_tab_uuid(self, term_uuid, new_text, user_set=True):
term_uuid = uuid.UUID(term_uuid)
page_index, = (
index for index, t in enumerate(self.get_notebook().iter_terminals())
if t.get_uuid() == term_uuid
)
self.get_notebook().rename_page(page_index, new_text, user_set) | [
"def",
"rename_tab_uuid",
"(",
"self",
",",
"term_uuid",
",",
"new_text",
",",
"user_set",
"=",
"True",
")",
":",
"term_uuid",
"=",
"uuid",
".",
"UUID",
"(",
"term_uuid",
")",
"page_index",
",",
"=",
"(",
"index",
"for",
"index",
",",
"t",
"in",
"enume... | Rename an already added tab by its UUID | [
"Rename",
"an",
"already",
"added",
"tab",
"by",
"its",
"UUID"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L1003-L1011 |
236,746 | Guake/guake | guake/guake_app.py | Guake.get_selected_uuidtab | def get_selected_uuidtab(self):
# TODO DBUS ONLY
"""Returns the uuid of the current selected terminal
"""
page_num = self.get_notebook().get_current_page()
terminals = self.get_notebook().get_terminals_for_page(page_num)
return str(terminals[0].get_uuid()) | python | def get_selected_uuidtab(self):
# TODO DBUS ONLY
page_num = self.get_notebook().get_current_page()
terminals = self.get_notebook().get_terminals_for_page(page_num)
return str(terminals[0].get_uuid()) | [
"def",
"get_selected_uuidtab",
"(",
"self",
")",
":",
"# TODO DBUS ONLY",
"page_num",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"terminals",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_terminals_for_page",
"(",
"p... | Returns the uuid of the current selected terminal | [
"Returns",
"the",
"uuid",
"of",
"the",
"current",
"selected",
"terminal"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L1093-L1099 |
236,747 | Guake/guake | guake/guake_app.py | Guake.search_on_web | def search_on_web(self, *args):
"""Search for the selected text on the web
"""
# TODO KEYBINDINGS ONLY
current_term = self.get_notebook().get_current_terminal()
if current_term.get_has_selection():
current_term.copy_clipboard()
guake_clipboard = Gtk.Clipboard.get_default(self.window.get_display())
search_query = guake_clipboard.wait_for_text()
search_query = quote_plus(search_query)
if search_query:
# TODO search provider should be selectable (someone might
# prefer bing.com, the internet is a strange place ¯\_(ツ)_/¯ )
search_url = "https://www.google.com/#q={!s}&safe=off".format(search_query, )
Gtk.show_uri(self.window.get_screen(), search_url, get_server_time(self.window))
return True | python | def search_on_web(self, *args):
# TODO KEYBINDINGS ONLY
current_term = self.get_notebook().get_current_terminal()
if current_term.get_has_selection():
current_term.copy_clipboard()
guake_clipboard = Gtk.Clipboard.get_default(self.window.get_display())
search_query = guake_clipboard.wait_for_text()
search_query = quote_plus(search_query)
if search_query:
# TODO search provider should be selectable (someone might
# prefer bing.com, the internet is a strange place ¯\_(ツ)_/¯ )
search_url = "https://www.google.com/#q={!s}&safe=off".format(search_query, )
Gtk.show_uri(self.window.get_screen(), search_url, get_server_time(self.window))
return True | [
"def",
"search_on_web",
"(",
"self",
",",
"*",
"args",
")",
":",
"# TODO KEYBINDINGS ONLY",
"current_term",
"=",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_terminal",
"(",
")",
"if",
"current_term",
".",
"get_has_selection",
"(",
")",
":",
"curre... | Search for the selected text on the web | [
"Search",
"for",
"the",
"selected",
"text",
"on",
"the",
"web"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L1101-L1117 |
236,748 | Guake/guake | guake/guake_app.py | Guake.execute_hook | def execute_hook(self, event_name):
"""Execute shell commands related to current event_name"""
hook = self.settings.hooks.get_string('{!s}'.format(event_name))
if hook is not None and hook != "":
hook = hook.split()
try:
subprocess.Popen(hook)
except OSError as oserr:
if oserr.errno == 8:
log.error("Hook execution failed! Check shebang at first line of %s!", hook)
log.debug(traceback.format_exc())
else:
log.error(str(oserr))
except Exception as e:
log.error("hook execution failed! %s", e)
log.debug(traceback.format_exc())
else:
log.debug("hook on event %s has been executed", event_name) | python | def execute_hook(self, event_name):
hook = self.settings.hooks.get_string('{!s}'.format(event_name))
if hook is not None and hook != "":
hook = hook.split()
try:
subprocess.Popen(hook)
except OSError as oserr:
if oserr.errno == 8:
log.error("Hook execution failed! Check shebang at first line of %s!", hook)
log.debug(traceback.format_exc())
else:
log.error(str(oserr))
except Exception as e:
log.error("hook execution failed! %s", e)
log.debug(traceback.format_exc())
else:
log.debug("hook on event %s has been executed", event_name) | [
"def",
"execute_hook",
"(",
"self",
",",
"event_name",
")",
":",
"hook",
"=",
"self",
".",
"settings",
".",
"hooks",
".",
"get_string",
"(",
"'{!s}'",
".",
"format",
"(",
"event_name",
")",
")",
"if",
"hook",
"is",
"not",
"None",
"and",
"hook",
"!=",
... | Execute shell commands related to current event_name | [
"Execute",
"shell",
"commands",
"related",
"to",
"current",
"event_name"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/guake_app.py#L1125-L1142 |
236,749 | Guake/guake | guake/theme.py | get_resource_dirs | def get_resource_dirs(resource):
"""Returns a list of all known resource dirs for a given resource.
:param str resource:
Name of the resource (e.g. "themes")
:return:
A list of resource dirs
"""
dirs = [
os.path.join(dir, resource) for dir in
itertools.chain(GLib.get_system_data_dirs(), GUAKE_THEME_DIR, GLib.get_user_data_dir())
]
dirs += [os.path.join(os.path.expanduser("~"), ".{}".format(resource))]
return [Path(dir) for dir in dirs if os.path.isdir(dir)] | python | def get_resource_dirs(resource):
dirs = [
os.path.join(dir, resource) for dir in
itertools.chain(GLib.get_system_data_dirs(), GUAKE_THEME_DIR, GLib.get_user_data_dir())
]
dirs += [os.path.join(os.path.expanduser("~"), ".{}".format(resource))]
return [Path(dir) for dir in dirs if os.path.isdir(dir)] | [
"def",
"get_resource_dirs",
"(",
"resource",
")",
":",
"dirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"resource",
")",
"for",
"dir",
"in",
"itertools",
".",
"chain",
"(",
"GLib",
".",
"get_system_data_dirs",
"(",
")",
",",
"GUAKE_TH... | Returns a list of all known resource dirs for a given resource.
:param str resource:
Name of the resource (e.g. "themes")
:return:
A list of resource dirs | [
"Returns",
"a",
"list",
"of",
"all",
"known",
"resource",
"dirs",
"for",
"a",
"given",
"resource",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/theme.py#L22-L36 |
236,750 | Guake/guake | guake/terminal.py | GuakeTerminal.configure_terminal | def configure_terminal(self):
"""Sets all customized properties on the terminal
"""
client = self.guake.settings.general
word_chars = client.get_string('word-chars')
if word_chars:
self.set_word_char_exceptions(word_chars)
self.set_audible_bell(client.get_boolean('use-audible-bell'))
self.set_sensitive(True)
cursor_blink_mode = self.guake.settings.style.get_int('cursor-blink-mode')
self.set_property('cursor-blink-mode', cursor_blink_mode)
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 50):
self.set_allow_hyperlink(True)
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 56):
try:
self.set_bold_is_bright(self.guake.settings.styleFont.get_boolean('bold-is-bright'))
except: # pylint: disable=bare-except
log.error("set_bold_is_bright not supported by your version of VTE")
# TODO PORT is this still the case with the newer vte version?
# -- Ubuntu has a patch to libvte which disables mouse scrolling in apps
# -- like vim and less by default. If this is the case, enable it back.
if hasattr(self, "set_alternate_screen_scroll"):
self.set_alternate_screen_scroll(True)
self.set_can_default(True)
self.set_can_focus(True) | python | def configure_terminal(self):
client = self.guake.settings.general
word_chars = client.get_string('word-chars')
if word_chars:
self.set_word_char_exceptions(word_chars)
self.set_audible_bell(client.get_boolean('use-audible-bell'))
self.set_sensitive(True)
cursor_blink_mode = self.guake.settings.style.get_int('cursor-blink-mode')
self.set_property('cursor-blink-mode', cursor_blink_mode)
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 50):
self.set_allow_hyperlink(True)
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 56):
try:
self.set_bold_is_bright(self.guake.settings.styleFont.get_boolean('bold-is-bright'))
except: # pylint: disable=bare-except
log.error("set_bold_is_bright not supported by your version of VTE")
# TODO PORT is this still the case with the newer vte version?
# -- Ubuntu has a patch to libvte which disables mouse scrolling in apps
# -- like vim and less by default. If this is the case, enable it back.
if hasattr(self, "set_alternate_screen_scroll"):
self.set_alternate_screen_scroll(True)
self.set_can_default(True)
self.set_can_focus(True) | [
"def",
"configure_terminal",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"guake",
".",
"settings",
".",
"general",
"word_chars",
"=",
"client",
".",
"get_string",
"(",
"'word-chars'",
")",
"if",
"word_chars",
":",
"self",
".",
"set_word_char_exceptions"... | Sets all customized properties on the terminal | [
"Sets",
"all",
"customized",
"properties",
"on",
"the",
"terminal"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/terminal.py#L143-L172 |
236,751 | Guake/guake | guake/terminal.py | GuakeTerminal.is_file_on_local_server | def is_file_on_local_server(self, text) -> Tuple[Optional[Path], Optional[int], Optional[int]]:
"""Test if the provided text matches a file on local server
Supports:
- absolute path
- relative path (using current working directory)
- file:line syntax
- file:line:colum syntax
Args:
text (str): candidate for file search
Returns
- Tuple(None, None, None) if the provided text does not match anything
- Tuple(file path, None, None) if only a file path is found
- Tuple(file path, linenumber, None) if line number is found
- Tuple(file path, linenumber, columnnumber) if line and column numbers are found
"""
lineno = None
colno = None
py_func = None
# "<File>:<line>:<col>"
m = re.compile(r"(.*)\:(\d+)\:(\d+)$").match(text)
if m:
text = m.group(1)
lineno = m.group(2)
colno = m.group(3)
else:
# "<File>:<line>"
m = re.compile(r"(.*)\:(\d+)$").match(text)
if m:
text = m.group(1)
lineno = m.group(2)
else:
# "<File>::<python_function>"
m = re.compile(r"^(.*)\:\:([a-zA-Z0-9\_]+)$").match(text)
if m:
text = m.group(1)
py_func = m.group(2).strip()
def find_lineno(text, pt, lineno, py_func):
# print("text={!r}, pt={!r}, lineno={!r}, py_func={!r}".format(text,
# pt, lineno, py_func))
if lineno:
return lineno
if not py_func:
return
with pt.open() as f:
for i, line in enumerate(f.readlines()):
if line.startswith("def {}".format(py_func)):
return i + 1
break
pt = Path(text)
log.debug("checking file existance: %r", pt)
try:
if pt.exists():
lineno = find_lineno(text, pt, lineno, py_func)
log.info("File exists: %r, line=%r", pt.absolute().as_posix(), lineno)
return (pt, lineno, colno)
log.debug("No file found matching: %r", text)
cwd = self.get_current_directory()
pt = Path(cwd) / pt
log.debug("checking file existance: %r", pt)
if pt.exists():
lineno = find_lineno(text, pt, lineno, py_func)
log.info("File exists: %r, line=%r", pt.absolute().as_posix(), lineno)
return (pt, lineno, colno)
log.debug("file does not exist: %s", str(pt))
except OSError:
log.debug("not a file name: %r", text)
return (None, None, None) | python | def is_file_on_local_server(self, text) -> Tuple[Optional[Path], Optional[int], Optional[int]]:
lineno = None
colno = None
py_func = None
# "<File>:<line>:<col>"
m = re.compile(r"(.*)\:(\d+)\:(\d+)$").match(text)
if m:
text = m.group(1)
lineno = m.group(2)
colno = m.group(3)
else:
# "<File>:<line>"
m = re.compile(r"(.*)\:(\d+)$").match(text)
if m:
text = m.group(1)
lineno = m.group(2)
else:
# "<File>::<python_function>"
m = re.compile(r"^(.*)\:\:([a-zA-Z0-9\_]+)$").match(text)
if m:
text = m.group(1)
py_func = m.group(2).strip()
def find_lineno(text, pt, lineno, py_func):
# print("text={!r}, pt={!r}, lineno={!r}, py_func={!r}".format(text,
# pt, lineno, py_func))
if lineno:
return lineno
if not py_func:
return
with pt.open() as f:
for i, line in enumerate(f.readlines()):
if line.startswith("def {}".format(py_func)):
return i + 1
break
pt = Path(text)
log.debug("checking file existance: %r", pt)
try:
if pt.exists():
lineno = find_lineno(text, pt, lineno, py_func)
log.info("File exists: %r, line=%r", pt.absolute().as_posix(), lineno)
return (pt, lineno, colno)
log.debug("No file found matching: %r", text)
cwd = self.get_current_directory()
pt = Path(cwd) / pt
log.debug("checking file existance: %r", pt)
if pt.exists():
lineno = find_lineno(text, pt, lineno, py_func)
log.info("File exists: %r, line=%r", pt.absolute().as_posix(), lineno)
return (pt, lineno, colno)
log.debug("file does not exist: %s", str(pt))
except OSError:
log.debug("not a file name: %r", text)
return (None, None, None) | [
"def",
"is_file_on_local_server",
"(",
"self",
",",
"text",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"Path",
"]",
",",
"Optional",
"[",
"int",
"]",
",",
"Optional",
"[",
"int",
"]",
"]",
":",
"lineno",
"=",
"None",
"colno",
"=",
"None",
"py_func",
"... | Test if the provided text matches a file on local server
Supports:
- absolute path
- relative path (using current working directory)
- file:line syntax
- file:line:colum syntax
Args:
text (str): candidate for file search
Returns
- Tuple(None, None, None) if the provided text does not match anything
- Tuple(file path, None, None) if only a file path is found
- Tuple(file path, linenumber, None) if line number is found
- Tuple(file path, linenumber, columnnumber) if line and column numbers are found | [
"Test",
"if",
"the",
"provided",
"text",
"matches",
"a",
"file",
"on",
"local",
"server"
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/terminal.py#L226-L297 |
236,752 | Guake/guake | guake/terminal.py | GuakeTerminal.button_press | def button_press(self, terminal, event):
"""Handles the button press event in the terminal widget. If
any match string is caught, another application is open to
handle the matched resource uri.
"""
self.matched_value = ''
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 46):
matched_string = self.match_check_event(event)
else:
matched_string = self.match_check(
int(event.x / self.get_char_width()), int(event.y / self.get_char_height())
)
self.found_link = None
if event.button == 1 and (event.get_state() & Gdk.ModifierType.CONTROL_MASK):
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) > (0, 50):
s = self.hyperlink_check_event(event)
else:
s = None
if s is not None:
self._on_ctrl_click_matcher((s, None))
elif self.get_has_selection():
self.quick_open()
elif matched_string and matched_string[0]:
self._on_ctrl_click_matcher(matched_string)
elif event.button == 3 and matched_string:
self.found_link = self.handleTerminalMatch(matched_string)
self.matched_value = matched_string[0] | python | def button_press(self, terminal, event):
self.matched_value = ''
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 46):
matched_string = self.match_check_event(event)
else:
matched_string = self.match_check(
int(event.x / self.get_char_width()), int(event.y / self.get_char_height())
)
self.found_link = None
if event.button == 1 and (event.get_state() & Gdk.ModifierType.CONTROL_MASK):
if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) > (0, 50):
s = self.hyperlink_check_event(event)
else:
s = None
if s is not None:
self._on_ctrl_click_matcher((s, None))
elif self.get_has_selection():
self.quick_open()
elif matched_string and matched_string[0]:
self._on_ctrl_click_matcher(matched_string)
elif event.button == 3 and matched_string:
self.found_link = self.handleTerminalMatch(matched_string)
self.matched_value = matched_string[0] | [
"def",
"button_press",
"(",
"self",
",",
"terminal",
",",
"event",
")",
":",
"self",
".",
"matched_value",
"=",
"''",
"if",
"(",
"Vte",
".",
"MAJOR_VERSION",
",",
"Vte",
".",
"MINOR_VERSION",
")",
">=",
"(",
"0",
",",
"46",
")",
":",
"matched_string",
... | Handles the button press event in the terminal widget. If
any match string is caught, another application is open to
handle the matched resource uri. | [
"Handles",
"the",
"button",
"press",
"event",
"in",
"the",
"terminal",
"widget",
".",
"If",
"any",
"match",
"string",
"is",
"caught",
"another",
"application",
"is",
"open",
"to",
"handle",
"the",
"matched",
"resource",
"uri",
"."
] | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/terminal.py#L299-L327 |
236,753 | Guake/guake | guake/terminal.py | GuakeTerminal.delete_shell | def delete_shell(self, pid):
"""This function will kill the shell on a tab, trying to send
a sigterm and if it doesn't work, a sigkill. Between these two
signals, we have a timeout of 3 seconds, so is recommended to
call this in another thread. This doesn't change any thing in
UI, so you can use python's start_new_thread.
"""
try:
os.kill(pid, signal.SIGHUP)
except OSError:
pass
num_tries = 30
while num_tries > 0:
try:
# Try to wait for the pid to be closed. If it does not
# exist anymore, an OSError is raised and we can
# safely ignore it.
if os.waitpid(pid, os.WNOHANG)[0] != 0:
break
except OSError:
break
sleep(0.1)
num_tries -= 1
if num_tries == 0:
try:
os.kill(pid, signal.SIGKILL)
os.waitpid(pid, 0)
except OSError:
# if this part of code was reached, means that SIGTERM
# did the work and SIGKILL wasnt needed.
pass | python | def delete_shell(self, pid):
try:
os.kill(pid, signal.SIGHUP)
except OSError:
pass
num_tries = 30
while num_tries > 0:
try:
# Try to wait for the pid to be closed. If it does not
# exist anymore, an OSError is raised and we can
# safely ignore it.
if os.waitpid(pid, os.WNOHANG)[0] != 0:
break
except OSError:
break
sleep(0.1)
num_tries -= 1
if num_tries == 0:
try:
os.kill(pid, signal.SIGKILL)
os.waitpid(pid, 0)
except OSError:
# if this part of code was reached, means that SIGTERM
# did the work and SIGKILL wasnt needed.
pass | [
"def",
"delete_shell",
"(",
"self",
",",
"pid",
")",
":",
"try",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGHUP",
")",
"except",
"OSError",
":",
"pass",
"num_tries",
"=",
"30",
"while",
"num_tries",
">",
"0",
":",
"try",
":",
"# Tr... | This function will kill the shell on a tab, trying to send
a sigterm and if it doesn't work, a sigkill. Between these two
signals, we have a timeout of 3 seconds, so is recommended to
call this in another thread. This doesn't change any thing in
UI, so you can use python's start_new_thread. | [
"This",
"function",
"will",
"kill",
"the",
"shell",
"on",
"a",
"tab",
"trying",
"to",
"send",
"a",
"sigterm",
"and",
"if",
"it",
"doesn",
"t",
"work",
"a",
"sigkill",
".",
"Between",
"these",
"two",
"signals",
"we",
"have",
"a",
"timeout",
"of",
"3",
... | 4153ef38f9044cbed6494075fce80acd5809df2b | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/terminal.py#L463-L495 |
236,754 | graphql-python/graphql-core | graphql/utils/is_valid_value.py | is_valid_value | def is_valid_value(value, type):
# type: (Any, Any) -> List
"""Given a type and any value, return True if that value is valid."""
if isinstance(type, GraphQLNonNull):
of_type = type.of_type
if value is None:
return [u'Expected "{}", found null.'.format(type)]
return is_valid_value(value, of_type)
if value is None:
return _empty_list
if isinstance(type, GraphQLList):
item_type = type.of_type
if not isinstance(value, string_types) and isinstance(value, Iterable):
errors = []
for i, item in enumerate(value):
item_errors = is_valid_value(item, item_type)
for error in item_errors:
errors.append(u"In element #{}: {}".format(i, error))
return errors
else:
return is_valid_value(value, item_type)
if isinstance(type, GraphQLInputObjectType):
if not isinstance(value, Mapping):
return [u'Expected "{}", found not an object.'.format(type)]
fields = type.fields
errors = []
for provided_field in sorted(value.keys()):
if provided_field not in fields:
errors.append(u'In field "{}": Unknown field.'.format(provided_field))
for field_name, field in fields.items():
subfield_errors = is_valid_value(value.get(field_name), field.type)
errors.extend(
u'In field "{}": {}'.format(field_name, e) for e in subfield_errors
)
return errors
assert isinstance(type, (GraphQLScalarType, GraphQLEnumType)), "Must be input type"
# Scalar/Enum input checks to ensure the type can parse the value to
# a non-null value.
parse_result = type.parse_value(value)
if parse_result is None:
return [u'Expected type "{}", found {}.'.format(type, json.dumps(value))]
return _empty_list | python | def is_valid_value(value, type):
# type: (Any, Any) -> List
if isinstance(type, GraphQLNonNull):
of_type = type.of_type
if value is None:
return [u'Expected "{}", found null.'.format(type)]
return is_valid_value(value, of_type)
if value is None:
return _empty_list
if isinstance(type, GraphQLList):
item_type = type.of_type
if not isinstance(value, string_types) and isinstance(value, Iterable):
errors = []
for i, item in enumerate(value):
item_errors = is_valid_value(item, item_type)
for error in item_errors:
errors.append(u"In element #{}: {}".format(i, error))
return errors
else:
return is_valid_value(value, item_type)
if isinstance(type, GraphQLInputObjectType):
if not isinstance(value, Mapping):
return [u'Expected "{}", found not an object.'.format(type)]
fields = type.fields
errors = []
for provided_field in sorted(value.keys()):
if provided_field not in fields:
errors.append(u'In field "{}": Unknown field.'.format(provided_field))
for field_name, field in fields.items():
subfield_errors = is_valid_value(value.get(field_name), field.type)
errors.extend(
u'In field "{}": {}'.format(field_name, e) for e in subfield_errors
)
return errors
assert isinstance(type, (GraphQLScalarType, GraphQLEnumType)), "Must be input type"
# Scalar/Enum input checks to ensure the type can parse the value to
# a non-null value.
parse_result = type.parse_value(value)
if parse_result is None:
return [u'Expected type "{}", found {}.'.format(type, json.dumps(value))]
return _empty_list | [
"def",
"is_valid_value",
"(",
"value",
",",
"type",
")",
":",
"# type: (Any, Any) -> List",
"if",
"isinstance",
"(",
"type",
",",
"GraphQLNonNull",
")",
":",
"of_type",
"=",
"type",
".",
"of_type",
"if",
"value",
"is",
"None",
":",
"return",
"[",
"u'Expected... | Given a type and any value, return True if that value is valid. | [
"Given",
"a",
"type",
"and",
"any",
"value",
"return",
"True",
"if",
"that",
"value",
"is",
"valid",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/is_valid_value.py#L28-L82 |
236,755 | graphql-python/graphql-core | graphql/backend/cache.py | get_unique_schema_id | def get_unique_schema_id(schema):
# type: (GraphQLSchema) -> str
"""Get a unique id given a GraphQLSchema"""
assert isinstance(schema, GraphQLSchema), (
"Must receive a GraphQLSchema as schema. Received {}"
).format(repr(schema))
if schema not in _cached_schemas:
_cached_schemas[schema] = sha1(str(schema).encode("utf-8")).hexdigest()
return _cached_schemas[schema] | python | def get_unique_schema_id(schema):
# type: (GraphQLSchema) -> str
assert isinstance(schema, GraphQLSchema), (
"Must receive a GraphQLSchema as schema. Received {}"
).format(repr(schema))
if schema not in _cached_schemas:
_cached_schemas[schema] = sha1(str(schema).encode("utf-8")).hexdigest()
return _cached_schemas[schema] | [
"def",
"get_unique_schema_id",
"(",
"schema",
")",
":",
"# type: (GraphQLSchema) -> str",
"assert",
"isinstance",
"(",
"schema",
",",
"GraphQLSchema",
")",
",",
"(",
"\"Must receive a GraphQLSchema as schema. Received {}\"",
")",
".",
"format",
"(",
"repr",
"(",
"schema... | Get a unique id given a GraphQLSchema | [
"Get",
"a",
"unique",
"id",
"given",
"a",
"GraphQLSchema"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/backend/cache.py#L18-L27 |
236,756 | graphql-python/graphql-core | graphql/backend/cache.py | get_unique_document_id | def get_unique_document_id(query_str):
# type: (str) -> str
"""Get a unique id given a query_string"""
assert isinstance(query_str, string_types), (
"Must receive a string as query_str. Received {}"
).format(repr(query_str))
if query_str not in _cached_queries:
_cached_queries[query_str] = sha1(str(query_str).encode("utf-8")).hexdigest()
return _cached_queries[query_str] | python | def get_unique_document_id(query_str):
# type: (str) -> str
assert isinstance(query_str, string_types), (
"Must receive a string as query_str. Received {}"
).format(repr(query_str))
if query_str not in _cached_queries:
_cached_queries[query_str] = sha1(str(query_str).encode("utf-8")).hexdigest()
return _cached_queries[query_str] | [
"def",
"get_unique_document_id",
"(",
"query_str",
")",
":",
"# type: (str) -> str",
"assert",
"isinstance",
"(",
"query_str",
",",
"string_types",
")",
",",
"(",
"\"Must receive a string as query_str. Received {}\"",
")",
".",
"format",
"(",
"repr",
"(",
"query_str",
... | Get a unique id given a query_string | [
"Get",
"a",
"unique",
"id",
"given",
"a",
"query_string"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/backend/cache.py#L30-L39 |
236,757 | graphql-python/graphql-core | graphql/backend/cache.py | GraphQLCachedBackend.get_key_for_schema_and_document_string | def get_key_for_schema_and_document_string(self, schema, request_string):
# type: (GraphQLSchema, str) -> int
"""This method returns a unique key given a schema and a request_string"""
if self.use_consistent_hash:
schema_id = get_unique_schema_id(schema)
document_id = get_unique_document_id(request_string)
return hash((schema_id, document_id))
return hash((schema, request_string)) | python | def get_key_for_schema_and_document_string(self, schema, request_string):
# type: (GraphQLSchema, str) -> int
if self.use_consistent_hash:
schema_id = get_unique_schema_id(schema)
document_id = get_unique_document_id(request_string)
return hash((schema_id, document_id))
return hash((schema, request_string)) | [
"def",
"get_key_for_schema_and_document_string",
"(",
"self",
",",
"schema",
",",
"request_string",
")",
":",
"# type: (GraphQLSchema, str) -> int",
"if",
"self",
".",
"use_consistent_hash",
":",
"schema_id",
"=",
"get_unique_schema_id",
"(",
"schema",
")",
"document_id",... | This method returns a unique key given a schema and a request_string | [
"This",
"method",
"returns",
"a",
"unique",
"key",
"given",
"a",
"schema",
"and",
"a",
"request_string"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/backend/cache.py#L62-L69 |
236,758 | graphql-python/graphql-core | graphql/validation/rules/fields_on_correct_type.py | get_suggested_type_names | def get_suggested_type_names(schema, output_type, field_name):
"""Go through all of the implementations of type, as well as the interfaces
that they implement. If any of those types include the provided field,
suggest them, sorted by how often the type is referenced, starting
with Interfaces."""
if isinstance(output_type, (GraphQLInterfaceType, GraphQLUnionType)):
suggested_object_types = []
interface_usage_count = OrderedDict()
for possible_type in schema.get_possible_types(output_type):
if not possible_type.fields.get(field_name):
return
# This object type defines this field.
suggested_object_types.append(possible_type.name)
for possible_interface in possible_type.interfaces:
if not possible_interface.fields.get(field_name):
continue
# This interface type defines this field.
interface_usage_count[possible_interface.name] = (
interface_usage_count.get(possible_interface.name, 0) + 1
)
# Suggest interface types based on how common they are.
suggested_interface_types = sorted(
list(interface_usage_count.keys()),
key=lambda k: interface_usage_count[k],
reverse=True,
)
# Suggest both interface and object types.
suggested_interface_types.extend(suggested_object_types)
return suggested_interface_types
# Otherwise, must be an Object type, which does not have possible fields.
return [] | python | def get_suggested_type_names(schema, output_type, field_name):
if isinstance(output_type, (GraphQLInterfaceType, GraphQLUnionType)):
suggested_object_types = []
interface_usage_count = OrderedDict()
for possible_type in schema.get_possible_types(output_type):
if not possible_type.fields.get(field_name):
return
# This object type defines this field.
suggested_object_types.append(possible_type.name)
for possible_interface in possible_type.interfaces:
if not possible_interface.fields.get(field_name):
continue
# This interface type defines this field.
interface_usage_count[possible_interface.name] = (
interface_usage_count.get(possible_interface.name, 0) + 1
)
# Suggest interface types based on how common they are.
suggested_interface_types = sorted(
list(interface_usage_count.keys()),
key=lambda k: interface_usage_count[k],
reverse=True,
)
# Suggest both interface and object types.
suggested_interface_types.extend(suggested_object_types)
return suggested_interface_types
# Otherwise, must be an Object type, which does not have possible fields.
return [] | [
"def",
"get_suggested_type_names",
"(",
"schema",
",",
"output_type",
",",
"field_name",
")",
":",
"if",
"isinstance",
"(",
"output_type",
",",
"(",
"GraphQLInterfaceType",
",",
"GraphQLUnionType",
")",
")",
":",
"suggested_object_types",
"=",
"[",
"]",
"interface... | Go through all of the implementations of type, as well as the interfaces
that they implement. If any of those types include the provided field,
suggest them, sorted by how often the type is referenced, starting
with Interfaces. | [
"Go",
"through",
"all",
"of",
"the",
"implementations",
"of",
"type",
"as",
"well",
"as",
"the",
"interfaces",
"that",
"they",
"implement",
".",
"If",
"any",
"of",
"those",
"types",
"include",
"the",
"provided",
"field",
"suggest",
"them",
"sorted",
"by",
... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/fields_on_correct_type.py#L91-L128 |
236,759 | graphql-python/graphql-core | graphql/validation/rules/fields_on_correct_type.py | get_suggested_field_names | def get_suggested_field_names(schema, graphql_type, field_name):
"""For the field name provided, determine if there are any similar field names
that may be the result of a typo."""
if isinstance(graphql_type, (GraphQLInterfaceType, GraphQLObjectType)):
possible_field_names = list(graphql_type.fields.keys())
return suggestion_list(field_name, possible_field_names)
# Otherwise, must be a Union type, which does not define fields.
return [] | python | def get_suggested_field_names(schema, graphql_type, field_name):
if isinstance(graphql_type, (GraphQLInterfaceType, GraphQLObjectType)):
possible_field_names = list(graphql_type.fields.keys())
return suggestion_list(field_name, possible_field_names)
# Otherwise, must be a Union type, which does not define fields.
return [] | [
"def",
"get_suggested_field_names",
"(",
"schema",
",",
"graphql_type",
",",
"field_name",
")",
":",
"if",
"isinstance",
"(",
"graphql_type",
",",
"(",
"GraphQLInterfaceType",
",",
"GraphQLObjectType",
")",
")",
":",
"possible_field_names",
"=",
"list",
"(",
"grap... | For the field name provided, determine if there are any similar field names
that may be the result of a typo. | [
"For",
"the",
"field",
"name",
"provided",
"determine",
"if",
"there",
"are",
"any",
"similar",
"field",
"names",
"that",
"may",
"be",
"the",
"result",
"of",
"a",
"typo",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/fields_on_correct_type.py#L131-L141 |
236,760 | graphql-python/graphql-core | graphql/backend/compiled.py | GraphQLCompiledDocument.from_code | def from_code(
cls,
schema, # type: GraphQLSchema
code, # type: Union[str, Any]
uptodate=None, # type: Optional[bool]
extra_namespace=None, # type: Optional[Dict[str, Any]]
):
# type: (...) -> GraphQLCompiledDocument
"""Creates a GraphQLDocument object from compiled code and the globals. This
is used by the loaders and schema to create a document object.
"""
if isinstance(code, string_types):
filename = "<document>"
code = compile(code, filename, "exec")
namespace = {"__file__": code.co_filename}
exec(code, namespace)
if extra_namespace:
namespace.update(extra_namespace)
rv = cls._from_namespace(schema, namespace)
# rv._uptodate = uptodate
return rv | python | def from_code(
cls,
schema, # type: GraphQLSchema
code, # type: Union[str, Any]
uptodate=None, # type: Optional[bool]
extra_namespace=None, # type: Optional[Dict[str, Any]]
):
# type: (...) -> GraphQLCompiledDocument
if isinstance(code, string_types):
filename = "<document>"
code = compile(code, filename, "exec")
namespace = {"__file__": code.co_filename}
exec(code, namespace)
if extra_namespace:
namespace.update(extra_namespace)
rv = cls._from_namespace(schema, namespace)
# rv._uptodate = uptodate
return rv | [
"def",
"from_code",
"(",
"cls",
",",
"schema",
",",
"# type: GraphQLSchema",
"code",
",",
"# type: Union[str, Any]",
"uptodate",
"=",
"None",
",",
"# type: Optional[bool]",
"extra_namespace",
"=",
"None",
",",
"# type: Optional[Dict[str, Any]]",
")",
":",
"# type: (...)... | Creates a GraphQLDocument object from compiled code and the globals. This
is used by the loaders and schema to create a document object. | [
"Creates",
"a",
"GraphQLDocument",
"object",
"from",
"compiled",
"code",
"and",
"the",
"globals",
".",
"This",
"is",
"used",
"by",
"the",
"loaders",
"and",
"schema",
"to",
"create",
"a",
"document",
"object",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/backend/compiled.py#L12-L32 |
236,761 | graphql-python/graphql-core | graphql/utils/suggestion_list.py | suggestion_list | def suggestion_list(inp, options):
"""
Given an invalid input string and a list of valid options, returns a filtered
list of valid options sorted based on their similarity with the input.
"""
options_by_distance = OrderedDict()
input_threshold = len(inp) / 2
for option in options:
distance = lexical_distance(inp, option)
threshold = max(input_threshold, len(option) / 2, 1)
if distance <= threshold:
options_by_distance[option] = distance
return sorted(
list(options_by_distance.keys()), key=lambda k: options_by_distance[k]
) | python | def suggestion_list(inp, options):
options_by_distance = OrderedDict()
input_threshold = len(inp) / 2
for option in options:
distance = lexical_distance(inp, option)
threshold = max(input_threshold, len(option) / 2, 1)
if distance <= threshold:
options_by_distance[option] = distance
return sorted(
list(options_by_distance.keys()), key=lambda k: options_by_distance[k]
) | [
"def",
"suggestion_list",
"(",
"inp",
",",
"options",
")",
":",
"options_by_distance",
"=",
"OrderedDict",
"(",
")",
"input_threshold",
"=",
"len",
"(",
"inp",
")",
"/",
"2",
"for",
"option",
"in",
"options",
":",
"distance",
"=",
"lexical_distance",
"(",
... | Given an invalid input string and a list of valid options, returns a filtered
list of valid options sorted based on their similarity with the input. | [
"Given",
"an",
"invalid",
"input",
"string",
"and",
"a",
"list",
"of",
"valid",
"options",
"returns",
"a",
"filtered",
"list",
"of",
"valid",
"options",
"sorted",
"based",
"on",
"their",
"similarity",
"with",
"the",
"input",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/suggestion_list.py#L4-L20 |
236,762 | graphql-python/graphql-core | graphql/utils/suggestion_list.py | lexical_distance | def lexical_distance(a, b):
"""
Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or a swap of two
adjacent characters.
This distance can be useful for detecting typos in input or sorting
@returns distance in number of edits
"""
d = [[i] for i in range(len(a) + 1)] or []
d_len = len(d) or 1
for i in range(d_len):
for j in range(1, len(b) + 1):
if i == 0:
d[i].append(j)
else:
d[i].append(0)
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
if i > 1 and j < 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
d[i][j] = min(d[i][j], d[i - 2][j - 2] + cost)
return d[len(a)][len(b)] | python | def lexical_distance(a, b):
d = [[i] for i in range(len(a) + 1)] or []
d_len = len(d) or 1
for i in range(d_len):
for j in range(1, len(b) + 1):
if i == 0:
d[i].append(j)
else:
d[i].append(0)
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
if i > 1 and j < 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
d[i][j] = min(d[i][j], d[i - 2][j - 2] + cost)
return d[len(a)][len(b)] | [
"def",
"lexical_distance",
"(",
"a",
",",
"b",
")",
":",
"d",
"=",
"[",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
"+",
"1",
")",
"]",
"or",
"[",
"]",
"d_len",
"=",
"len",
"(",
"d",
")",
"or",
"1",
"for",
"i",
... | Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or a swap of two
adjacent characters.
This distance can be useful for detecting typos in input or sorting
@returns distance in number of edits | [
"Computes",
"the",
"lexical",
"distance",
"between",
"strings",
"A",
"and",
"B",
".",
"The",
"distance",
"between",
"two",
"strings",
"is",
"given",
"by",
"counting",
"the",
"minimum",
"number",
"of",
"edits",
"needed",
"to",
"transform",
"string",
"A",
"int... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/suggestion_list.py#L23-L52 |
236,763 | graphql-python/graphql-core | graphql/pyutils/version.py | get_complete_version | def get_complete_version(version=None):
"""Returns a tuple of the graphql version. If version argument is non-empty,
then checks for correctness of the tuple provided.
"""
if version is None:
from graphql import VERSION as version
else:
assert len(version) == 5
assert version[3] in ("alpha", "beta", "rc", "final")
return version | python | def get_complete_version(version=None):
if version is None:
from graphql import VERSION as version
else:
assert len(version) == 5
assert version[3] in ("alpha", "beta", "rc", "final")
return version | [
"def",
"get_complete_version",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"is",
"None",
":",
"from",
"graphql",
"import",
"VERSION",
"as",
"version",
"else",
":",
"assert",
"len",
"(",
"version",
")",
"==",
"5",
"assert",
"version",
"[",
"3"... | Returns a tuple of the graphql version. If version argument is non-empty,
then checks for correctness of the tuple provided. | [
"Returns",
"a",
"tuple",
"of",
"the",
"graphql",
"version",
".",
"If",
"version",
"argument",
"is",
"non",
"-",
"empty",
"then",
"checks",
"for",
"correctness",
"of",
"the",
"tuple",
"provided",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/pyutils/version.py#L40-L50 |
236,764 | graphql-python/graphql-core | graphql/language/lexer.py | read_token | def read_token(source, from_position):
# type: (Source, int) -> Token
"""Gets the next token from the source starting at the given position.
This skips over whitespace and comments until it finds the next lexable
token, then lexes punctuators immediately or calls the appropriate
helper fucntion for more complicated tokens."""
body = source.body
body_length = len(body)
position = position_after_whitespace(body, from_position)
if position >= body_length:
return Token(TokenKind.EOF, position, position)
code = char_code_at(body, position)
if code:
if code < 0x0020 and code not in (0x0009, 0x000A, 0x000D):
raise GraphQLSyntaxError(
source, position, u"Invalid character {}.".format(print_char_code(code))
)
kind = PUNCT_CODE_TO_KIND.get(code)
if kind is not None:
return Token(kind, position, position + 1)
if code == 46: # .
if (
char_code_at(body, position + 1)
== char_code_at(body, position + 2)
== 46
):
return Token(TokenKind.SPREAD, position, position + 3)
elif 65 <= code <= 90 or code == 95 or 97 <= code <= 122:
# A-Z, _, a-z
return read_name(source, position)
elif code == 45 or 48 <= code <= 57: # -, 0-9
return read_number(source, position, code)
elif code == 34: # "
return read_string(source, position)
raise GraphQLSyntaxError(
source, position, u"Unexpected character {}.".format(print_char_code(code))
) | python | def read_token(source, from_position):
# type: (Source, int) -> Token
body = source.body
body_length = len(body)
position = position_after_whitespace(body, from_position)
if position >= body_length:
return Token(TokenKind.EOF, position, position)
code = char_code_at(body, position)
if code:
if code < 0x0020 and code not in (0x0009, 0x000A, 0x000D):
raise GraphQLSyntaxError(
source, position, u"Invalid character {}.".format(print_char_code(code))
)
kind = PUNCT_CODE_TO_KIND.get(code)
if kind is not None:
return Token(kind, position, position + 1)
if code == 46: # .
if (
char_code_at(body, position + 1)
== char_code_at(body, position + 2)
== 46
):
return Token(TokenKind.SPREAD, position, position + 3)
elif 65 <= code <= 90 or code == 95 or 97 <= code <= 122:
# A-Z, _, a-z
return read_name(source, position)
elif code == 45 or 48 <= code <= 57: # -, 0-9
return read_number(source, position, code)
elif code == 34: # "
return read_string(source, position)
raise GraphQLSyntaxError(
source, position, u"Unexpected character {}.".format(print_char_code(code))
) | [
"def",
"read_token",
"(",
"source",
",",
"from_position",
")",
":",
"# type: (Source, int) -> Token",
"body",
"=",
"source",
".",
"body",
"body_length",
"=",
"len",
"(",
"body",
")",
"position",
"=",
"position_after_whitespace",
"(",
"body",
",",
"from_position",
... | Gets the next token from the source starting at the given position.
This skips over whitespace and comments until it finds the next lexable
token, then lexes punctuators immediately or calls the appropriate
helper fucntion for more complicated tokens. | [
"Gets",
"the",
"next",
"token",
"from",
"the",
"source",
"starting",
"at",
"the",
"given",
"position",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/lexer.py#L152-L198 |
236,765 | graphql-python/graphql-core | graphql/language/lexer.py | position_after_whitespace | def position_after_whitespace(body, start_position):
# type: (str, int) -> int
"""Reads from body starting at start_position until it finds a
non-whitespace or commented character, then returns the position of
that character for lexing."""
body_length = len(body)
position = start_position
while position < body_length:
code = char_code_at(body, position)
if code in ignored_whitespace_characters:
position += 1
elif code == 35: # #, skip comments
position += 1
while position < body_length:
code = char_code_at(body, position)
if not (
code is not None
and (code > 0x001F or code == 0x0009)
and code not in (0x000A, 0x000D)
):
break
position += 1
else:
break
return position | python | def position_after_whitespace(body, start_position):
# type: (str, int) -> int
body_length = len(body)
position = start_position
while position < body_length:
code = char_code_at(body, position)
if code in ignored_whitespace_characters:
position += 1
elif code == 35: # #, skip comments
position += 1
while position < body_length:
code = char_code_at(body, position)
if not (
code is not None
and (code > 0x001F or code == 0x0009)
and code not in (0x000A, 0x000D)
):
break
position += 1
else:
break
return position | [
"def",
"position_after_whitespace",
"(",
"body",
",",
"start_position",
")",
":",
"# type: (str, int) -> int",
"body_length",
"=",
"len",
"(",
"body",
")",
"position",
"=",
"start_position",
"while",
"position",
"<",
"body_length",
":",
"code",
"=",
"char_code_at",
... | Reads from body starting at start_position until it finds a
non-whitespace or commented character, then returns the position of
that character for lexing. | [
"Reads",
"from",
"body",
"starting",
"at",
"start_position",
"until",
"it",
"finds",
"a",
"non",
"-",
"whitespace",
"or",
"commented",
"character",
"then",
"returns",
"the",
"position",
"of",
"that",
"character",
"for",
"lexing",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/lexer.py#L217-L243 |
236,766 | graphql-python/graphql-core | graphql/language/lexer.py | read_number | def read_number(source, start, first_code):
# type: (Source, int, Optional[int]) -> Token
r"""Reads a number token from the source file, either a float
or an int depending on whether a decimal point appears.
Int: -?(0|[1-9][0-9]*)
Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?"""
code = first_code
body = source.body
position = start
is_float = False
if code == 45: # -
position += 1
code = char_code_at(body, position)
if code == 48: # 0
position += 1
code = char_code_at(body, position)
if code is not None and 48 <= code <= 57:
raise GraphQLSyntaxError(
source,
position,
u"Invalid number, unexpected digit after 0: {}.".format(
print_char_code(code)
),
)
else:
position = read_digits(source, position, code)
code = char_code_at(body, position)
if code == 46: # .
is_float = True
position += 1
code = char_code_at(body, position)
position = read_digits(source, position, code)
code = char_code_at(body, position)
if code in (69, 101): # E e
is_float = True
position += 1
code = char_code_at(body, position)
if code in (43, 45): # + -
position += 1
code = char_code_at(body, position)
position = read_digits(source, position, code)
return Token(
TokenKind.FLOAT if is_float else TokenKind.INT,
start,
position,
body[start:position],
) | python | def read_number(source, start, first_code):
# type: (Source, int, Optional[int]) -> Token
r"""Reads a number token from the source file, either a float
or an int depending on whether a decimal point appears.
Int: -?(0|[1-9][0-9]*)
Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?"""
code = first_code
body = source.body
position = start
is_float = False
if code == 45: # -
position += 1
code = char_code_at(body, position)
if code == 48: # 0
position += 1
code = char_code_at(body, position)
if code is not None and 48 <= code <= 57:
raise GraphQLSyntaxError(
source,
position,
u"Invalid number, unexpected digit after 0: {}.".format(
print_char_code(code)
),
)
else:
position = read_digits(source, position, code)
code = char_code_at(body, position)
if code == 46: # .
is_float = True
position += 1
code = char_code_at(body, position)
position = read_digits(source, position, code)
code = char_code_at(body, position)
if code in (69, 101): # E e
is_float = True
position += 1
code = char_code_at(body, position)
if code in (43, 45): # + -
position += 1
code = char_code_at(body, position)
position = read_digits(source, position, code)
return Token(
TokenKind.FLOAT if is_float else TokenKind.INT,
start,
position,
body[start:position],
) | [
"def",
"read_number",
"(",
"source",
",",
"start",
",",
"first_code",
")",
":",
"# type: (Source, int, Optional[int]) -> Token",
"code",
"=",
"first_code",
"body",
"=",
"source",
".",
"body",
"position",
"=",
"start",
"is_float",
"=",
"False",
"if",
"code",
"=="... | r"""Reads a number token from the source file, either a float
or an int depending on whether a decimal point appears.
Int: -?(0|[1-9][0-9]*)
Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? | [
"r",
"Reads",
"a",
"number",
"token",
"from",
"the",
"source",
"file",
"either",
"a",
"float",
"or",
"an",
"int",
"depending",
"on",
"whether",
"a",
"decimal",
"point",
"appears",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/lexer.py#L246-L301 |
236,767 | graphql-python/graphql-core | graphql/language/lexer.py | read_string | def read_string(source, start):
# type: (Source, int) -> Token
"""Reads a string token from the source file.
"([^"\\\u000A\u000D\u2028\u2029]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
"""
body = source.body
body_length = len(body)
position = start + 1
chunk_start = position
code = 0 # type: Optional[int]
value = [] # type: List[str]
append = value.append
while position < body_length:
code = char_code_at(body, position)
if code in (
None,
# LineTerminator
0x000A,
0x000D,
# Quote
34,
):
break
if code < 0x0020 and code != 0x0009: # type: ignore
raise GraphQLSyntaxError(
source,
position,
u"Invalid character within String: {}.".format(print_char_code(code)),
)
position += 1
if code == 92: # \
append(body[chunk_start : position - 1])
code = char_code_at(body, position)
escaped = ESCAPED_CHAR_CODES.get(code) # type: ignore
if escaped is not None:
append(escaped)
elif code == 117: # u
char_code = uni_char_code(
char_code_at(body, position + 1) or 0,
char_code_at(body, position + 2) or 0,
char_code_at(body, position + 3) or 0,
char_code_at(body, position + 4) or 0,
)
if char_code < 0:
raise GraphQLSyntaxError(
source,
position,
u"Invalid character escape sequence: \\u{}.".format(
body[position + 1 : position + 5]
),
)
append(unichr(char_code))
position += 4
else:
raise GraphQLSyntaxError(
source,
position,
u"Invalid character escape sequence: \\{}.".format(
unichr(code) # type: ignore
),
)
position += 1
chunk_start = position
if code != 34: # Quote (")
raise GraphQLSyntaxError(source, position, "Unterminated string")
append(body[chunk_start:position])
return Token(TokenKind.STRING, start, position + 1, u"".join(value)) | python | def read_string(source, start):
# type: (Source, int) -> Token
body = source.body
body_length = len(body)
position = start + 1
chunk_start = position
code = 0 # type: Optional[int]
value = [] # type: List[str]
append = value.append
while position < body_length:
code = char_code_at(body, position)
if code in (
None,
# LineTerminator
0x000A,
0x000D,
# Quote
34,
):
break
if code < 0x0020 and code != 0x0009: # type: ignore
raise GraphQLSyntaxError(
source,
position,
u"Invalid character within String: {}.".format(print_char_code(code)),
)
position += 1
if code == 92: # \
append(body[chunk_start : position - 1])
code = char_code_at(body, position)
escaped = ESCAPED_CHAR_CODES.get(code) # type: ignore
if escaped is not None:
append(escaped)
elif code == 117: # u
char_code = uni_char_code(
char_code_at(body, position + 1) or 0,
char_code_at(body, position + 2) or 0,
char_code_at(body, position + 3) or 0,
char_code_at(body, position + 4) or 0,
)
if char_code < 0:
raise GraphQLSyntaxError(
source,
position,
u"Invalid character escape sequence: \\u{}.".format(
body[position + 1 : position + 5]
),
)
append(unichr(char_code))
position += 4
else:
raise GraphQLSyntaxError(
source,
position,
u"Invalid character escape sequence: \\{}.".format(
unichr(code) # type: ignore
),
)
position += 1
chunk_start = position
if code != 34: # Quote (")
raise GraphQLSyntaxError(source, position, "Unterminated string")
append(body[chunk_start:position])
return Token(TokenKind.STRING, start, position + 1, u"".join(value)) | [
"def",
"read_string",
"(",
"source",
",",
"start",
")",
":",
"# type: (Source, int) -> Token",
"body",
"=",
"source",
".",
"body",
"body_length",
"=",
"len",
"(",
"body",
")",
"position",
"=",
"start",
"+",
"1",
"chunk_start",
"=",
"position",
"code",
"=",
... | Reads a string token from the source file.
"([^"\\\u000A\u000D\u2028\u2029]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" | [
"Reads",
"a",
"string",
"token",
"from",
"the",
"source",
"file",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/lexer.py#L339-L417 |
236,768 | graphql-python/graphql-core | graphql/language/lexer.py | read_name | def read_name(source, position):
# type: (Source, int) -> Token
"""Reads an alphanumeric + underscore name from the source.
[_A-Za-z][_0-9A-Za-z]*"""
body = source.body
body_length = len(body)
end = position + 1
while end != body_length:
code = char_code_at(body, end)
if not (
code is not None
and (
code == 95
or 48 <= code <= 57 # _
or 65 <= code <= 90 # 0-9
or 97 <= code <= 122 # A-Z # a-z
)
):
break
end += 1
return Token(TokenKind.NAME, position, end, body[position:end]) | python | def read_name(source, position):
# type: (Source, int) -> Token
body = source.body
body_length = len(body)
end = position + 1
while end != body_length:
code = char_code_at(body, end)
if not (
code is not None
and (
code == 95
or 48 <= code <= 57 # _
or 65 <= code <= 90 # 0-9
or 97 <= code <= 122 # A-Z # a-z
)
):
break
end += 1
return Token(TokenKind.NAME, position, end, body[position:end]) | [
"def",
"read_name",
"(",
"source",
",",
"position",
")",
":",
"# type: (Source, int) -> Token",
"body",
"=",
"source",
".",
"body",
"body_length",
"=",
"len",
"(",
"body",
")",
"end",
"=",
"position",
"+",
"1",
"while",
"end",
"!=",
"body_length",
":",
"co... | Reads an alphanumeric + underscore name from the source.
[_A-Za-z][_0-9A-Za-z]* | [
"Reads",
"an",
"alphanumeric",
"+",
"underscore",
"name",
"from",
"the",
"source",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/lexer.py#L451-L475 |
236,769 | graphql-python/graphql-core | graphql/execution/executor.py | complete_value | def complete_value(
exe_context, # type: ExecutionContext
return_type, # type: Any
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Any
"""
Implements the instructions for completeValue as defined in the
"Field entries" section of the spec.
If the field type is Non-Null, then this recursively completes the value for the inner type. It throws a field
error if that completion returns null, as per the "Nullability" section of the spec.
If the field type is a List, then this recursively completes the value for the inner type on each item in the
list.
If the field type is a Scalar or Enum, ensures the completed value is a legal value of the type by calling the
`serialize` method of GraphQL type definition.
If the field is an abstract type, determine the runtime type of the value and then complete based on that type.
Otherwise, the field type expects a sub-selection set, and will complete the value by evaluating all
sub-selections.
"""
# If field type is NonNull, complete for inner type, and throw field error
# if result is null.
if is_thenable(result):
return Promise.resolve(result).then(
lambda resolved: complete_value(
exe_context, return_type, field_asts, info, path, resolved
),
lambda error: Promise.rejected(
GraphQLLocatedError(field_asts, original_error=error, path=path)
),
)
# print return_type, type(result)
if isinstance(result, Exception):
raise GraphQLLocatedError(field_asts, original_error=result, path=path)
if isinstance(return_type, GraphQLNonNull):
return complete_nonnull_value(
exe_context, return_type, field_asts, info, path, result
)
# If result is null-like, return null.
if result is None:
return None
# If field type is List, complete each item in the list with the inner type
if isinstance(return_type, GraphQLList):
return complete_list_value(
exe_context, return_type, field_asts, info, path, result
)
# If field type is Scalar or Enum, serialize to a valid value, returning
# null if coercion is not possible.
if isinstance(return_type, (GraphQLScalarType, GraphQLEnumType)):
return complete_leaf_value(return_type, path, result)
if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)):
return complete_abstract_value(
exe_context, return_type, field_asts, info, path, result
)
if isinstance(return_type, GraphQLObjectType):
return complete_object_value(
exe_context, return_type, field_asts, info, path, result
)
assert False, u'Cannot complete value of unexpected type "{}".'.format(return_type) | python | def complete_value(
exe_context, # type: ExecutionContext
return_type, # type: Any
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Any
# If field type is NonNull, complete for inner type, and throw field error
# if result is null.
if is_thenable(result):
return Promise.resolve(result).then(
lambda resolved: complete_value(
exe_context, return_type, field_asts, info, path, resolved
),
lambda error: Promise.rejected(
GraphQLLocatedError(field_asts, original_error=error, path=path)
),
)
# print return_type, type(result)
if isinstance(result, Exception):
raise GraphQLLocatedError(field_asts, original_error=result, path=path)
if isinstance(return_type, GraphQLNonNull):
return complete_nonnull_value(
exe_context, return_type, field_asts, info, path, result
)
# If result is null-like, return null.
if result is None:
return None
# If field type is List, complete each item in the list with the inner type
if isinstance(return_type, GraphQLList):
return complete_list_value(
exe_context, return_type, field_asts, info, path, result
)
# If field type is Scalar or Enum, serialize to a valid value, returning
# null if coercion is not possible.
if isinstance(return_type, (GraphQLScalarType, GraphQLEnumType)):
return complete_leaf_value(return_type, path, result)
if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)):
return complete_abstract_value(
exe_context, return_type, field_asts, info, path, result
)
if isinstance(return_type, GraphQLObjectType):
return complete_object_value(
exe_context, return_type, field_asts, info, path, result
)
assert False, u'Cannot complete value of unexpected type "{}".'.format(return_type) | [
"def",
"complete_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: Any",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# type: Any",
")",
... | Implements the instructions for completeValue as defined in the
"Field entries" section of the spec.
If the field type is Non-Null, then this recursively completes the value for the inner type. It throws a field
error if that completion returns null, as per the "Nullability" section of the spec.
If the field type is a List, then this recursively completes the value for the inner type on each item in the
list.
If the field type is a Scalar or Enum, ensures the completed value is a legal value of the type by calling the
`serialize` method of GraphQL type definition.
If the field is an abstract type, determine the runtime type of the value and then complete based on that type.
Otherwise, the field type expects a sub-selection set, and will complete the value by evaluating all
sub-selections. | [
"Implements",
"the",
"instructions",
"for",
"completeValue",
"as",
"defined",
"in",
"the",
"Field",
"entries",
"section",
"of",
"the",
"spec",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L498-L571 |
236,770 | graphql-python/graphql-core | graphql/execution/executor.py | complete_list_value | def complete_list_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLList
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> List[Any]
"""
Complete a list value by completing each item in the list with the inner type
"""
assert isinstance(result, Iterable), (
"User Error: expected iterable, but did not find one " + "for field {}.{}."
).format(info.parent_type, info.field_name)
item_type = return_type.of_type
completed_results = []
contains_promise = False
index = 0
for item in result:
completed_item = complete_value_catching_error(
exe_context, item_type, field_asts, info, path + [index], item
)
if not contains_promise and is_thenable(completed_item):
contains_promise = True
completed_results.append(completed_item)
index += 1
return Promise.all(completed_results) if contains_promise else completed_results | python | def complete_list_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLList
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> List[Any]
assert isinstance(result, Iterable), (
"User Error: expected iterable, but did not find one " + "for field {}.{}."
).format(info.parent_type, info.field_name)
item_type = return_type.of_type
completed_results = []
contains_promise = False
index = 0
for item in result:
completed_item = complete_value_catching_error(
exe_context, item_type, field_asts, info, path + [index], item
)
if not contains_promise and is_thenable(completed_item):
contains_promise = True
completed_results.append(completed_item)
index += 1
return Promise.all(completed_results) if contains_promise else completed_results | [
"def",
"complete_list_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: GraphQLList",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# type: An... | Complete a list value by completing each item in the list with the inner type | [
"Complete",
"a",
"list",
"value",
"by",
"completing",
"each",
"item",
"in",
"the",
"list",
"with",
"the",
"inner",
"type"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L574-L605 |
236,771 | graphql-python/graphql-core | graphql/execution/executor.py | complete_leaf_value | def complete_leaf_value(
return_type, # type: Union[GraphQLEnumType, GraphQLScalarType]
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Union[int, str, float, bool]
"""
Complete a Scalar or Enum by serializing to a valid value, returning null if serialization is not possible.
"""
assert hasattr(return_type, "serialize"), "Missing serialize method on type"
serialized_result = return_type.serialize(result)
if serialized_result is None:
raise GraphQLError(
('Expected a value of type "{}" but ' + "received: {}").format(
return_type, result
),
path=path,
)
return serialized_result | python | def complete_leaf_value(
return_type, # type: Union[GraphQLEnumType, GraphQLScalarType]
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Union[int, str, float, bool]
assert hasattr(return_type, "serialize"), "Missing serialize method on type"
serialized_result = return_type.serialize(result)
if serialized_result is None:
raise GraphQLError(
('Expected a value of type "{}" but ' + "received: {}").format(
return_type, result
),
path=path,
)
return serialized_result | [
"def",
"complete_leaf_value",
"(",
"return_type",
",",
"# type: Union[GraphQLEnumType, GraphQLScalarType]",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# type: Any",
")",
":",
"# type: (...) -> Union[int, str, float, bool]",
"assert",
"hasattr",
"(",
"return_typ... | Complete a Scalar or Enum by serializing to a valid value, returning null if serialization is not possible. | [
"Complete",
"a",
"Scalar",
"or",
"Enum",
"by",
"serializing",
"to",
"a",
"valid",
"value",
"returning",
"null",
"if",
"serialization",
"is",
"not",
"possible",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L608-L627 |
236,772 | graphql-python/graphql-core | graphql/execution/executor.py | complete_abstract_value | def complete_abstract_value(
exe_context, # type: ExecutionContext
return_type, # type: Union[GraphQLInterfaceType, GraphQLUnionType]
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Dict[str, Any]
"""
Complete an value of an abstract type by determining the runtime type of that value, then completing based
on that type.
"""
runtime_type = None # type: Union[str, GraphQLObjectType, None]
# Field type must be Object, Interface or Union and expect sub-selections.
if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)):
if return_type.resolve_type:
runtime_type = return_type.resolve_type(result, info)
else:
runtime_type = get_default_resolve_type_fn(result, info, return_type)
if isinstance(runtime_type, string_types):
runtime_type = info.schema.get_type(runtime_type) # type: ignore
if not isinstance(runtime_type, GraphQLObjectType):
raise GraphQLError(
(
"Abstract type {} must resolve to an Object type at runtime "
+ 'for field {}.{} with value "{}", received "{}".'
).format(
return_type, info.parent_type, info.field_name, result, runtime_type
),
field_asts,
)
if not exe_context.schema.is_possible_type(return_type, runtime_type):
raise GraphQLError(
u'Runtime Object type "{}" is not a possible type for "{}".'.format(
runtime_type, return_type
),
field_asts,
)
return complete_object_value(
exe_context, runtime_type, field_asts, info, path, result
) | python | def complete_abstract_value(
exe_context, # type: ExecutionContext
return_type, # type: Union[GraphQLInterfaceType, GraphQLUnionType]
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Dict[str, Any]
runtime_type = None # type: Union[str, GraphQLObjectType, None]
# Field type must be Object, Interface or Union and expect sub-selections.
if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)):
if return_type.resolve_type:
runtime_type = return_type.resolve_type(result, info)
else:
runtime_type = get_default_resolve_type_fn(result, info, return_type)
if isinstance(runtime_type, string_types):
runtime_type = info.schema.get_type(runtime_type) # type: ignore
if not isinstance(runtime_type, GraphQLObjectType):
raise GraphQLError(
(
"Abstract type {} must resolve to an Object type at runtime "
+ 'for field {}.{} with value "{}", received "{}".'
).format(
return_type, info.parent_type, info.field_name, result, runtime_type
),
field_asts,
)
if not exe_context.schema.is_possible_type(return_type, runtime_type):
raise GraphQLError(
u'Runtime Object type "{}" is not a possible type for "{}".'.format(
runtime_type, return_type
),
field_asts,
)
return complete_object_value(
exe_context, runtime_type, field_asts, info, path, result
) | [
"def",
"complete_abstract_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: Union[GraphQLInterfaceType, GraphQLUnionType]",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, st... | Complete an value of an abstract type by determining the runtime type of that value, then completing based
on that type. | [
"Complete",
"an",
"value",
"of",
"an",
"abstract",
"type",
"by",
"determining",
"the",
"runtime",
"type",
"of",
"that",
"value",
"then",
"completing",
"based",
"on",
"that",
"type",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L630-L676 |
236,773 | graphql-python/graphql-core | graphql/execution/executor.py | complete_object_value | def complete_object_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLObjectType
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Dict[str, Any]
"""
Complete an Object value by evaluating all sub-selections.
"""
if return_type.is_type_of and not return_type.is_type_of(result, info):
raise GraphQLError(
u'Expected value of type "{}" but got: {}.'.format(
return_type, type(result).__name__
),
field_asts,
)
# Collect sub-fields to execute to complete this value.
subfield_asts = exe_context.get_sub_fields(return_type, field_asts)
return execute_fields(exe_context, return_type, result, subfield_asts, path, info) | python | def complete_object_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLObjectType
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Dict[str, Any]
if return_type.is_type_of and not return_type.is_type_of(result, info):
raise GraphQLError(
u'Expected value of type "{}" but got: {}.'.format(
return_type, type(result).__name__
),
field_asts,
)
# Collect sub-fields to execute to complete this value.
subfield_asts = exe_context.get_sub_fields(return_type, field_asts)
return execute_fields(exe_context, return_type, result, subfield_asts, path, info) | [
"def",
"complete_object_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: GraphQLObjectType",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# ... | Complete an Object value by evaluating all sub-selections. | [
"Complete",
"an",
"Object",
"value",
"by",
"evaluating",
"all",
"sub",
"-",
"selections",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L692-L714 |
236,774 | graphql-python/graphql-core | graphql/execution/executor.py | complete_nonnull_value | def complete_nonnull_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLNonNull
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Any
"""
Complete a NonNull value by completing the inner type
"""
completed = complete_value(
exe_context, return_type.of_type, field_asts, info, path, result
)
if completed is None:
raise GraphQLError(
"Cannot return null for non-nullable field {}.{}.".format(
info.parent_type, info.field_name
),
field_asts,
path=path,
)
return completed | python | def complete_nonnull_value(
exe_context, # type: ExecutionContext
return_type, # type: GraphQLNonNull
field_asts, # type: List[Field]
info, # type: ResolveInfo
path, # type: List[Union[int, str]]
result, # type: Any
):
# type: (...) -> Any
completed = complete_value(
exe_context, return_type.of_type, field_asts, info, path, result
)
if completed is None:
raise GraphQLError(
"Cannot return null for non-nullable field {}.{}.".format(
info.parent_type, info.field_name
),
field_asts,
path=path,
)
return completed | [
"def",
"complete_nonnull_value",
"(",
"exe_context",
",",
"# type: ExecutionContext",
"return_type",
",",
"# type: GraphQLNonNull",
"field_asts",
",",
"# type: List[Field]",
"info",
",",
"# type: ResolveInfo",
"path",
",",
"# type: List[Union[int, str]]",
"result",
",",
"# ty... | Complete a NonNull value by completing the inner type | [
"Complete",
"a",
"NonNull",
"value",
"by",
"completing",
"the",
"inner",
"type"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/executor.py#L717-L741 |
236,775 | graphql-python/graphql-core | graphql/utils/value_from_ast.py | value_from_ast | def value_from_ast(value_ast, type, variables=None):
# type: (Optional[Node], GraphQLType, Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]) -> Union[List, Dict, int, float, bool, str, None]
"""Given a type and a value AST node known to match this type, build a
runtime value."""
if isinstance(type, GraphQLNonNull):
# Note: we're not checking that the result of coerceValueAST is non-null.
# We're assuming that this query has been validated and the value used here is of the correct type.
return value_from_ast(value_ast, type.of_type, variables)
if value_ast is None:
return None
if isinstance(value_ast, ast.Variable):
variable_name = value_ast.name.value
if not variables or variable_name not in variables:
return None
# Note: we're not doing any checking that this variable is correct. We're assuming that this query
# has been validated and the variable usage here is of the correct type.
return variables.get(variable_name)
if isinstance(type, GraphQLList):
item_type = type.of_type
if isinstance(value_ast, ast.ListValue):
return [
value_from_ast(item_ast, item_type, variables)
for item_ast in value_ast.values
]
else:
return [value_from_ast(value_ast, item_type, variables)]
if isinstance(type, GraphQLInputObjectType):
fields = type.fields
if not isinstance(value_ast, ast.ObjectValue):
return None
field_asts = {}
for field_ast in value_ast.fields:
field_asts[field_ast.name.value] = field_ast
obj = {}
for field_name, field in fields.items():
if field_name not in field_asts:
if field.default_value is not None:
# We use out_name as the output name for the
# dict if exists
obj[field.out_name or field_name] = field.default_value
continue
field_ast = field_asts[field_name]
field_value_ast = field_ast.value
field_value = value_from_ast(field_value_ast, field.type, variables)
# We use out_name as the output name for the
# dict if exists
obj[field.out_name or field_name] = field_value
return type.create_container(obj)
assert isinstance(type, (GraphQLScalarType, GraphQLEnumType)), "Must be input type"
return type.parse_literal(value_ast) | python | def value_from_ast(value_ast, type, variables=None):
# type: (Optional[Node], GraphQLType, Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]) -> Union[List, Dict, int, float, bool, str, None]
if isinstance(type, GraphQLNonNull):
# Note: we're not checking that the result of coerceValueAST is non-null.
# We're assuming that this query has been validated and the value used here is of the correct type.
return value_from_ast(value_ast, type.of_type, variables)
if value_ast is None:
return None
if isinstance(value_ast, ast.Variable):
variable_name = value_ast.name.value
if not variables or variable_name not in variables:
return None
# Note: we're not doing any checking that this variable is correct. We're assuming that this query
# has been validated and the variable usage here is of the correct type.
return variables.get(variable_name)
if isinstance(type, GraphQLList):
item_type = type.of_type
if isinstance(value_ast, ast.ListValue):
return [
value_from_ast(item_ast, item_type, variables)
for item_ast in value_ast.values
]
else:
return [value_from_ast(value_ast, item_type, variables)]
if isinstance(type, GraphQLInputObjectType):
fields = type.fields
if not isinstance(value_ast, ast.ObjectValue):
return None
field_asts = {}
for field_ast in value_ast.fields:
field_asts[field_ast.name.value] = field_ast
obj = {}
for field_name, field in fields.items():
if field_name not in field_asts:
if field.default_value is not None:
# We use out_name as the output name for the
# dict if exists
obj[field.out_name or field_name] = field.default_value
continue
field_ast = field_asts[field_name]
field_value_ast = field_ast.value
field_value = value_from_ast(field_value_ast, field.type, variables)
# We use out_name as the output name for the
# dict if exists
obj[field.out_name or field_name] = field_value
return type.create_container(obj)
assert isinstance(type, (GraphQLScalarType, GraphQLEnumType)), "Must be input type"
return type.parse_literal(value_ast) | [
"def",
"value_from_ast",
"(",
"value_ast",
",",
"type",
",",
"variables",
"=",
"None",
")",
":",
"# type: (Optional[Node], GraphQLType, Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]) -> Union[List, Dict, int, float, bool, str, None]",
"if",
"isinstance",
"(",
"t... | Given a type and a value AST node known to match this type, build a
runtime value. | [
"Given",
"a",
"type",
"and",
"a",
"value",
"AST",
"node",
"known",
"to",
"match",
"this",
"type",
"build",
"a",
"runtime",
"value",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/value_from_ast.py#L17-L81 |
236,776 | graphql-python/graphql-core | graphql/utils/ast_to_code.py | ast_to_code | def ast_to_code(ast, indent=0):
# type: (Any, int) -> str
"""
Converts an ast into a python code representation of the AST.
"""
code = []
def append(line):
# type: (str) -> None
code.append((" " * indent) + line)
if isinstance(ast, Node):
append("ast.{}(".format(ast.__class__.__name__))
indent += 1
for i, k in enumerate(ast._fields, 1):
v = getattr(ast, k)
append("{}={},".format(k, ast_to_code(v, indent)))
if ast.loc:
append("loc={}".format(ast_to_code(ast.loc, indent)))
indent -= 1
append(")")
elif isinstance(ast, Loc):
append("loc({}, {})".format(ast.start, ast.end))
elif isinstance(ast, list):
if ast:
append("[")
indent += 1
for i, it in enumerate(ast, 1):
is_last = i == len(ast)
append(ast_to_code(it, indent) + ("," if not is_last else ""))
indent -= 1
append("]")
else:
append("[]")
else:
append(repr(ast))
return "\n".join(code).strip() | python | def ast_to_code(ast, indent=0):
# type: (Any, int) -> str
code = []
def append(line):
# type: (str) -> None
code.append((" " * indent) + line)
if isinstance(ast, Node):
append("ast.{}(".format(ast.__class__.__name__))
indent += 1
for i, k in enumerate(ast._fields, 1):
v = getattr(ast, k)
append("{}={},".format(k, ast_to_code(v, indent)))
if ast.loc:
append("loc={}".format(ast_to_code(ast.loc, indent)))
indent -= 1
append(")")
elif isinstance(ast, Loc):
append("loc({}, {})".format(ast.start, ast.end))
elif isinstance(ast, list):
if ast:
append("[")
indent += 1
for i, it in enumerate(ast, 1):
is_last = i == len(ast)
append(ast_to_code(it, indent) + ("," if not is_last else ""))
indent -= 1
append("]")
else:
append("[]")
else:
append(repr(ast))
return "\n".join(code).strip() | [
"def",
"ast_to_code",
"(",
"ast",
",",
"indent",
"=",
"0",
")",
":",
"# type: (Any, int) -> str",
"code",
"=",
"[",
"]",
"def",
"append",
"(",
"line",
")",
":",
"# type: (str) -> None",
"code",
".",
"append",
"(",
"(",
"\" \"",
"*",
"indent",
")",
"+"... | Converts an ast into a python code representation of the AST. | [
"Converts",
"an",
"ast",
"into",
"a",
"python",
"code",
"representation",
"of",
"the",
"AST",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/ast_to_code.py#L9-L52 |
236,777 | graphql-python/graphql-core | scripts/casing.py | snake | def snake(s):
"""Convert from title or camelCase to snake_case."""
if len(s) < 2:
return s.lower()
out = s[0].lower()
for c in s[1:]:
if c.isupper():
out += "_"
c = c.lower()
out += c
return out | python | def snake(s):
if len(s) < 2:
return s.lower()
out = s[0].lower()
for c in s[1:]:
if c.isupper():
out += "_"
c = c.lower()
out += c
return out | [
"def",
"snake",
"(",
"s",
")",
":",
"if",
"len",
"(",
"s",
")",
"<",
"2",
":",
"return",
"s",
".",
"lower",
"(",
")",
"out",
"=",
"s",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"for",
"c",
"in",
"s",
"[",
"1",
":",
"]",
":",
"if",
"c",
"... | Convert from title or camelCase to snake_case. | [
"Convert",
"from",
"title",
"or",
"camelCase",
"to",
"snake_case",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/scripts/casing.py#L19-L29 |
236,778 | graphql-python/graphql-core | graphql/backend/quiver_cloud.py | GraphQLQuiverCloudBackend.make_post_request | def make_post_request(self, url, auth, json_payload):
"""This function executes the request with the provided
json payload and return the json response"""
response = requests.post(url, auth=auth, json=json_payload)
return response.json() | python | def make_post_request(self, url, auth, json_payload):
response = requests.post(url, auth=auth, json=json_payload)
return response.json() | [
"def",
"make_post_request",
"(",
"self",
",",
"url",
",",
"auth",
",",
"json_payload",
")",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"auth",
"=",
"auth",
",",
"json",
"=",
"json_payload",
")",
"return",
"response",
".",
"json",
"... | This function executes the request with the provided
json payload and return the json response | [
"This",
"function",
"executes",
"the",
"request",
"with",
"the",
"provided",
"json",
"payload",
"and",
"return",
"the",
"json",
"response"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/backend/quiver_cloud.py#L64-L68 |
236,779 | graphql-python/graphql-core | graphql/utils/get_field_def.py | get_field_def | def get_field_def(
schema, # type: GraphQLSchema
parent_type, # type: Union[GraphQLInterfaceType, GraphQLObjectType]
field_ast, # type: Field
):
# type: (...) -> Optional[GraphQLField]
"""Not exactly the same as the executor's definition of get_field_def, in this
statically evaluated environment we do not always have an Object type,
and need to handle Interface and Union types."""
name = field_ast.name.value
if name == "__schema" and schema.get_query_type() == parent_type:
return SchemaMetaFieldDef
elif name == "__type" and schema.get_query_type() == parent_type:
return TypeMetaFieldDef
elif name == "__typename" and isinstance(
parent_type, (GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType)
):
return TypeNameMetaFieldDef
elif isinstance(parent_type, (GraphQLObjectType, GraphQLInterfaceType)):
return parent_type.fields.get(name) | python | def get_field_def(
schema, # type: GraphQLSchema
parent_type, # type: Union[GraphQLInterfaceType, GraphQLObjectType]
field_ast, # type: Field
):
# type: (...) -> Optional[GraphQLField]
name = field_ast.name.value
if name == "__schema" and schema.get_query_type() == parent_type:
return SchemaMetaFieldDef
elif name == "__type" and schema.get_query_type() == parent_type:
return TypeMetaFieldDef
elif name == "__typename" and isinstance(
parent_type, (GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType)
):
return TypeNameMetaFieldDef
elif isinstance(parent_type, (GraphQLObjectType, GraphQLInterfaceType)):
return parent_type.fields.get(name) | [
"def",
"get_field_def",
"(",
"schema",
",",
"# type: GraphQLSchema",
"parent_type",
",",
"# type: Union[GraphQLInterfaceType, GraphQLObjectType]",
"field_ast",
",",
"# type: Field",
")",
":",
"# type: (...) -> Optional[GraphQLField]",
"name",
"=",
"field_ast",
".",
"name",
".... | Not exactly the same as the executor's definition of get_field_def, in this
statically evaluated environment we do not always have an Object type,
and need to handle Interface and Union types. | [
"Not",
"exactly",
"the",
"same",
"as",
"the",
"executor",
"s",
"definition",
"of",
"get_field_def",
"in",
"this",
"statically",
"evaluated",
"environment",
"we",
"do",
"not",
"always",
"have",
"an",
"Object",
"type",
"and",
"need",
"to",
"handle",
"Interface",... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/utils/get_field_def.py#L16-L38 |
236,780 | graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | _find_conflicts_within_selection_set | def _find_conflicts_within_selection_set(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_type, # type: Union[GraphQLInterfaceType, GraphQLObjectType, None]
selection_set, # type: SelectionSet
):
# type: (...) -> List[Tuple[Tuple[str, str], List[Node], List[Node]]]
"""Find all conflicts found "within" a selection set, including those found via spreading in fragments.
Called when visiting each SelectionSet in the GraphQL Document.
"""
conflicts = [] # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]
field_map, fragment_names = _get_fields_and_fragments_names(
context, cached_fields_and_fragment_names, parent_type, selection_set
)
# (A) Find all conflicts "within" the fields of this selection set.
# Note: this is the *only place* `collect_conflicts_within` is called.
_collect_conflicts_within(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
field_map,
)
# (B) Then collect conflicts between these fields and those represented by
# each spread fragment name found.
for i, fragment_name in enumerate(fragment_names):
_collect_conflicts_between_fields_and_fragment(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
False,
field_map,
fragment_name,
)
# (C) Then compare this fragment with all other fragments found in this
# selection set to collect conflicts within fragments spread together.
# This compares each item in the list of fragment names to every other item
# in that same list (except for itself).
for other_fragment_name in fragment_names[i + 1 :]:
_collect_conflicts_between_fragments(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
False,
fragment_name,
other_fragment_name,
)
return conflicts | python | def _find_conflicts_within_selection_set(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_type, # type: Union[GraphQLInterfaceType, GraphQLObjectType, None]
selection_set, # type: SelectionSet
):
# type: (...) -> List[Tuple[Tuple[str, str], List[Node], List[Node]]]
conflicts = [] # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]
field_map, fragment_names = _get_fields_and_fragments_names(
context, cached_fields_and_fragment_names, parent_type, selection_set
)
# (A) Find all conflicts "within" the fields of this selection set.
# Note: this is the *only place* `collect_conflicts_within` is called.
_collect_conflicts_within(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
field_map,
)
# (B) Then collect conflicts between these fields and those represented by
# each spread fragment name found.
for i, fragment_name in enumerate(fragment_names):
_collect_conflicts_between_fields_and_fragment(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
False,
field_map,
fragment_name,
)
# (C) Then compare this fragment with all other fragments found in this
# selection set to collect conflicts within fragments spread together.
# This compares each item in the list of fragment names to every other item
# in that same list (except for itself).
for other_fragment_name in fragment_names[i + 1 :]:
_collect_conflicts_between_fragments(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
False,
fragment_name,
other_fragment_name,
)
return conflicts | [
"def",
"_find_conflicts_within_selection_set",
"(",
"context",
",",
"# type: ValidationContext",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]",
"compared_fra... | Find all conflicts found "within" a selection set, including those found via spreading in fragments.
Called when visiting each SelectionSet in the GraphQL Document. | [
"Find",
"all",
"conflicts",
"found",
"within",
"a",
"selection",
"set",
"including",
"those",
"found",
"via",
"spreading",
"in",
"fragments",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L167-L222 |
236,781 | graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | _find_conflicts_between_sub_selection_sets | def _find_conflicts_between_sub_selection_sets(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
are_mutually_exclusive, # type: bool
parent_type1, # type: Union[GraphQLInterfaceType, GraphQLObjectType, None]
selection_set1, # type: SelectionSet
parent_type2, # type: Union[GraphQLInterfaceType, GraphQLObjectType, None]
selection_set2, # type: SelectionSet
):
# type: (...) -> List[Tuple[Tuple[str, str], List[Node], List[Node]]]
"""Find all conflicts found between two selection sets.
Includes those found via spreading in fragments. Called when determining if conflicts exist
between the sub-fields of two overlapping fields.
"""
conflicts = [] # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]
field_map1, fragment_names1 = _get_fields_and_fragments_names(
context, cached_fields_and_fragment_names, parent_type1, selection_set1
)
field_map2, fragment_names2 = _get_fields_and_fragments_names(
context, cached_fields_and_fragment_names, parent_type2, selection_set2
)
# (H) First, collect all conflicts between these two collections of field.
_collect_conflicts_between(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
field_map1,
field_map2,
)
# (I) Then collect conflicts between the first collection of fields and
# those referenced by each fragment name associated with the second.
for fragment_name2 in fragment_names2:
_collect_conflicts_between_fields_and_fragment(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
field_map1,
fragment_name2,
)
# (I) Then collect conflicts between the second collection of fields and
# those referenced by each fragment name associated with the first.
for fragment_name1 in fragment_names1:
_collect_conflicts_between_fields_and_fragment(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
field_map2,
fragment_name1,
)
# (J) Also collect conflicts between any fragment names by the first and
# fragment names by the second. This compares each item in the first set of
# names to each item in the second set of names.
for fragment_name1 in fragment_names1:
for fragment_name2 in fragment_names2:
_collect_conflicts_between_fragments(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
fragment_name1,
fragment_name2,
)
return conflicts | python | def _find_conflicts_between_sub_selection_sets(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
are_mutually_exclusive, # type: bool
parent_type1, # type: Union[GraphQLInterfaceType, GraphQLObjectType, None]
selection_set1, # type: SelectionSet
parent_type2, # type: Union[GraphQLInterfaceType, GraphQLObjectType, None]
selection_set2, # type: SelectionSet
):
# type: (...) -> List[Tuple[Tuple[str, str], List[Node], List[Node]]]
conflicts = [] # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]
field_map1, fragment_names1 = _get_fields_and_fragments_names(
context, cached_fields_and_fragment_names, parent_type1, selection_set1
)
field_map2, fragment_names2 = _get_fields_and_fragments_names(
context, cached_fields_and_fragment_names, parent_type2, selection_set2
)
# (H) First, collect all conflicts between these two collections of field.
_collect_conflicts_between(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
field_map1,
field_map2,
)
# (I) Then collect conflicts between the first collection of fields and
# those referenced by each fragment name associated with the second.
for fragment_name2 in fragment_names2:
_collect_conflicts_between_fields_and_fragment(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
field_map1,
fragment_name2,
)
# (I) Then collect conflicts between the second collection of fields and
# those referenced by each fragment name associated with the first.
for fragment_name1 in fragment_names1:
_collect_conflicts_between_fields_and_fragment(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
field_map2,
fragment_name1,
)
# (J) Also collect conflicts between any fragment names by the first and
# fragment names by the second. This compares each item in the first set of
# names to each item in the second set of names.
for fragment_name1 in fragment_names1:
for fragment_name2 in fragment_names2:
_collect_conflicts_between_fragments(
context,
conflicts,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
fragment_name1,
fragment_name2,
)
return conflicts | [
"def",
"_find_conflicts_between_sub_selection_sets",
"(",
"context",
",",
"# type: ValidationContext",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]",
"compar... | Find all conflicts found between two selection sets.
Includes those found via spreading in fragments. Called when determining if conflicts exist
between the sub-fields of two overlapping fields. | [
"Find",
"all",
"conflicts",
"found",
"between",
"two",
"selection",
"sets",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L348-L426 |
236,782 | graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | _find_conflict | def _find_conflict(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_fields_are_mutually_exclusive, # type: bool
response_name, # type: str
field1, # type: Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]
field2, # type: Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]
):
# type: (...) -> Optional[Tuple[Tuple[str, str], List[Node], List[Node]]]
"""Determines if there is a conflict between two particular fields."""
parent_type1, ast1, def1 = field1
parent_type2, ast2, def2 = field2
# If it is known that two fields could not possibly apply at the same
# time, due to the parent types, then it is safe to permit them to diverge
# in aliased field or arguments used as they will not present any ambiguity
# by differing.
# It is known that two parent types could never overlap if they are
# different Object types. Interface or Union types might overlap - if not
# in the current state of the schema, then perhaps in some future version,
# thus may not safely diverge.
are_mutually_exclusive = parent_fields_are_mutually_exclusive or (
parent_type1 != parent_type2
and isinstance(parent_type1, GraphQLObjectType)
and isinstance(parent_type2, GraphQLObjectType)
)
# The return type for each field.
type1 = def1 and def1.type
type2 = def2 and def2.type
if not are_mutually_exclusive:
# Two aliases must refer to the same field.
name1 = ast1.name.value
name2 = ast2.name.value
if name1 != name2:
return (
(response_name, "{} and {} are different fields".format(name1, name2)),
[ast1],
[ast2],
)
# Two field calls must have the same arguments.
if not _same_arguments(ast1.arguments, ast2.arguments):
return ((response_name, "they have differing arguments"), [ast1], [ast2])
if type1 and type2 and do_types_conflict(type1, type2):
return (
(
response_name,
"they return conflicting types {} and {}".format(type1, type2),
),
[ast1],
[ast2],
)
# Collect and compare sub-fields. Use the same "visited fragment names" list
# for both collections so fields in a fragment reference are never
# compared to themselves.
selection_set1 = ast1.selection_set
selection_set2 = ast2.selection_set
if selection_set1 and selection_set2:
conflicts = _find_conflicts_between_sub_selection_sets( # type: ignore
context,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
get_named_type(type1), # type: ignore
selection_set1,
get_named_type(type2), # type: ignore
selection_set2,
)
return _subfield_conflicts(conflicts, response_name, ast1, ast2)
return None | python | def _find_conflict(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_fields_are_mutually_exclusive, # type: bool
response_name, # type: str
field1, # type: Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]
field2, # type: Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]
):
# type: (...) -> Optional[Tuple[Tuple[str, str], List[Node], List[Node]]]
parent_type1, ast1, def1 = field1
parent_type2, ast2, def2 = field2
# If it is known that two fields could not possibly apply at the same
# time, due to the parent types, then it is safe to permit them to diverge
# in aliased field or arguments used as they will not present any ambiguity
# by differing.
# It is known that two parent types could never overlap if they are
# different Object types. Interface or Union types might overlap - if not
# in the current state of the schema, then perhaps in some future version,
# thus may not safely diverge.
are_mutually_exclusive = parent_fields_are_mutually_exclusive or (
parent_type1 != parent_type2
and isinstance(parent_type1, GraphQLObjectType)
and isinstance(parent_type2, GraphQLObjectType)
)
# The return type for each field.
type1 = def1 and def1.type
type2 = def2 and def2.type
if not are_mutually_exclusive:
# Two aliases must refer to the same field.
name1 = ast1.name.value
name2 = ast2.name.value
if name1 != name2:
return (
(response_name, "{} and {} are different fields".format(name1, name2)),
[ast1],
[ast2],
)
# Two field calls must have the same arguments.
if not _same_arguments(ast1.arguments, ast2.arguments):
return ((response_name, "they have differing arguments"), [ast1], [ast2])
if type1 and type2 and do_types_conflict(type1, type2):
return (
(
response_name,
"they return conflicting types {} and {}".format(type1, type2),
),
[ast1],
[ast2],
)
# Collect and compare sub-fields. Use the same "visited fragment names" list
# for both collections so fields in a fragment reference are never
# compared to themselves.
selection_set1 = ast1.selection_set
selection_set2 = ast2.selection_set
if selection_set1 and selection_set2:
conflicts = _find_conflicts_between_sub_selection_sets( # type: ignore
context,
cached_fields_and_fragment_names,
compared_fragments,
are_mutually_exclusive,
get_named_type(type1), # type: ignore
selection_set1,
get_named_type(type2), # type: ignore
selection_set2,
)
return _subfield_conflicts(conflicts, response_name, ast1, ast2)
return None | [
"def",
"_find_conflict",
"(",
"context",
",",
"# type: ValidationContext",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]",
"compared_fragments",
",",
"# t... | Determines if there is a conflict between two particular fields. | [
"Determines",
"if",
"there",
"is",
"a",
"conflict",
"between",
"two",
"particular",
"fields",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L504-L583 |
236,783 | graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | _get_referenced_fields_and_fragment_names | def _get_referenced_fields_and_fragment_names(
context, # ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
fragment, # type: InlineFragment
):
# type: (...) -> Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]
"""Given a reference to a fragment, return the represented collection of fields as well as a list of
nested fragment names referenced via fragment spreads."""
# Short-circuit building a type from the AST if possible.
cached = cached_fields_and_fragment_names.get(fragment.selection_set)
if cached:
return cached
fragment_type = type_from_ast( # type: ignore
context.get_schema(), fragment.type_condition
)
return _get_fields_and_fragments_names( # type: ignore
context, cached_fields_and_fragment_names, fragment_type, fragment.selection_set
) | python | def _get_referenced_fields_and_fragment_names(
context, # ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
fragment, # type: InlineFragment
):
# type: (...) -> Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]
# Short-circuit building a type from the AST if possible.
cached = cached_fields_and_fragment_names.get(fragment.selection_set)
if cached:
return cached
fragment_type = type_from_ast( # type: ignore
context.get_schema(), fragment.type_condition
)
return _get_fields_and_fragments_names( # type: ignore
context, cached_fields_and_fragment_names, fragment_type, fragment.selection_set
) | [
"def",
"_get_referenced_fields_and_fragment_names",
"(",
"context",
",",
"# ValidationContext",
"cached_fields_and_fragment_names",
",",
"# type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]",
"fragment",
... | Given a reference to a fragment, return the represented collection of fields as well as a list of
nested fragment names referenced via fragment spreads. | [
"Given",
"a",
"reference",
"to",
"a",
"fragment",
"return",
"the",
"represented",
"collection",
"of",
"fields",
"as",
"well",
"as",
"a",
"list",
"of",
"nested",
"fragment",
"names",
"referenced",
"via",
"fragment",
"spreads",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L609-L630 |
236,784 | graphql-python/graphql-core | graphql/validation/rules/overlapping_fields_can_be_merged.py | _subfield_conflicts | def _subfield_conflicts(
conflicts, # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]
response_name, # type: str
ast1, # type: Node
ast2, # type: Node
):
# type: (...) -> Optional[Tuple[Tuple[str, str], List[Node], List[Node]]]
"""Given a series of Conflicts which occurred between two sub-fields, generate a single Conflict."""
if conflicts:
return ( # type: ignore
(response_name, [conflict[0] for conflict in conflicts]),
tuple(itertools.chain([ast1], *[conflict[1] for conflict in conflicts])),
tuple(itertools.chain([ast2], *[conflict[2] for conflict in conflicts])),
)
return None | python | def _subfield_conflicts(
conflicts, # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]
response_name, # type: str
ast1, # type: Node
ast2, # type: Node
):
# type: (...) -> Optional[Tuple[Tuple[str, str], List[Node], List[Node]]]
if conflicts:
return ( # type: ignore
(response_name, [conflict[0] for conflict in conflicts]),
tuple(itertools.chain([ast1], *[conflict[1] for conflict in conflicts])),
tuple(itertools.chain([ast2], *[conflict[2] for conflict in conflicts])),
)
return None | [
"def",
"_subfield_conflicts",
"(",
"conflicts",
",",
"# type: List[Tuple[Tuple[str, str], List[Node], List[Node]]]",
"response_name",
",",
"# type: str",
"ast1",
",",
"# type: Node",
"ast2",
",",
"# type: Node",
")",
":",
"# type: (...) -> Optional[Tuple[Tuple[str, str], List[Node]... | Given a series of Conflicts which occurred between two sub-fields, generate a single Conflict. | [
"Given",
"a",
"series",
"of",
"Conflicts",
"which",
"occurred",
"between",
"two",
"sub",
"-",
"fields",
"generate",
"a",
"single",
"Conflict",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/validation/rules/overlapping_fields_can_be_merged.py#L677-L691 |
236,785 | graphql-python/graphql-core | graphql/execution/utils.py | collect_fields | def collect_fields(
ctx, # type: ExecutionContext
runtime_type, # type: GraphQLObjectType
selection_set, # type: SelectionSet
fields, # type: DefaultOrderedDict
prev_fragment_names, # type: Set[str]
):
# type: (...) -> DefaultOrderedDict
"""
Given a selectionSet, adds all of the fields in that selection to
the passed in map of fields, and returns it at the end.
collect_fields requires the "runtime type" of an object. For a field which
returns and Interface or Union type, the "runtime type" will be the actual
Object type returned by that field.
"""
for selection in selection_set.selections:
directives = selection.directives
if isinstance(selection, ast.Field):
if not should_include_node(ctx, directives):
continue
name = get_field_entry_key(selection)
fields[name].append(selection)
elif isinstance(selection, ast.InlineFragment):
if not should_include_node(
ctx, directives
) or not does_fragment_condition_match(ctx, selection, runtime_type):
continue
collect_fields(
ctx, runtime_type, selection.selection_set, fields, prev_fragment_names
)
elif isinstance(selection, ast.FragmentSpread):
frag_name = selection.name.value
if frag_name in prev_fragment_names or not should_include_node(
ctx, directives
):
continue
prev_fragment_names.add(frag_name)
fragment = ctx.fragments[frag_name]
frag_directives = fragment.directives
if (
not fragment
or not should_include_node(ctx, frag_directives)
or not does_fragment_condition_match(ctx, fragment, runtime_type)
):
continue
collect_fields(
ctx, runtime_type, fragment.selection_set, fields, prev_fragment_names
)
return fields | python | def collect_fields(
ctx, # type: ExecutionContext
runtime_type, # type: GraphQLObjectType
selection_set, # type: SelectionSet
fields, # type: DefaultOrderedDict
prev_fragment_names, # type: Set[str]
):
# type: (...) -> DefaultOrderedDict
for selection in selection_set.selections:
directives = selection.directives
if isinstance(selection, ast.Field):
if not should_include_node(ctx, directives):
continue
name = get_field_entry_key(selection)
fields[name].append(selection)
elif isinstance(selection, ast.InlineFragment):
if not should_include_node(
ctx, directives
) or not does_fragment_condition_match(ctx, selection, runtime_type):
continue
collect_fields(
ctx, runtime_type, selection.selection_set, fields, prev_fragment_names
)
elif isinstance(selection, ast.FragmentSpread):
frag_name = selection.name.value
if frag_name in prev_fragment_names or not should_include_node(
ctx, directives
):
continue
prev_fragment_names.add(frag_name)
fragment = ctx.fragments[frag_name]
frag_directives = fragment.directives
if (
not fragment
or not should_include_node(ctx, frag_directives)
or not does_fragment_condition_match(ctx, fragment, runtime_type)
):
continue
collect_fields(
ctx, runtime_type, fragment.selection_set, fields, prev_fragment_names
)
return fields | [
"def",
"collect_fields",
"(",
"ctx",
",",
"# type: ExecutionContext",
"runtime_type",
",",
"# type: GraphQLObjectType",
"selection_set",
",",
"# type: SelectionSet",
"fields",
",",
"# type: DefaultOrderedDict",
"prev_fragment_names",
",",
"# type: Set[str]",
")",
":",
"# type... | Given a selectionSet, adds all of the fields in that selection to
the passed in map of fields, and returns it at the end.
collect_fields requires the "runtime type" of an object. For a field which
returns and Interface or Union type, the "runtime type" will be the actual
Object type returned by that field. | [
"Given",
"a",
"selectionSet",
"adds",
"all",
"of",
"the",
"fields",
"in",
"that",
"selection",
"to",
"the",
"passed",
"in",
"map",
"of",
"fields",
"and",
"returns",
"it",
"at",
"the",
"end",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/utils.py#L224-L282 |
236,786 | graphql-python/graphql-core | graphql/execution/utils.py | should_include_node | def should_include_node(ctx, directives):
# type: (ExecutionContext, Optional[List[Directive]]) -> bool
"""Determines if a field should be included based on the @include and
@skip directives, where @skip has higher precidence than @include."""
# TODO: Refactor based on latest code
if directives:
skip_ast = None
for directive in directives:
if directive.name.value == GraphQLSkipDirective.name:
skip_ast = directive
break
if skip_ast:
args = get_argument_values(
GraphQLSkipDirective.args, skip_ast.arguments, ctx.variable_values
)
if args.get("if") is True:
return False
include_ast = None
for directive in directives:
if directive.name.value == GraphQLIncludeDirective.name:
include_ast = directive
break
if include_ast:
args = get_argument_values(
GraphQLIncludeDirective.args, include_ast.arguments, ctx.variable_values
)
if args.get("if") is False:
return False
return True | python | def should_include_node(ctx, directives):
# type: (ExecutionContext, Optional[List[Directive]]) -> bool
# TODO: Refactor based on latest code
if directives:
skip_ast = None
for directive in directives:
if directive.name.value == GraphQLSkipDirective.name:
skip_ast = directive
break
if skip_ast:
args = get_argument_values(
GraphQLSkipDirective.args, skip_ast.arguments, ctx.variable_values
)
if args.get("if") is True:
return False
include_ast = None
for directive in directives:
if directive.name.value == GraphQLIncludeDirective.name:
include_ast = directive
break
if include_ast:
args = get_argument_values(
GraphQLIncludeDirective.args, include_ast.arguments, ctx.variable_values
)
if args.get("if") is False:
return False
return True | [
"def",
"should_include_node",
"(",
"ctx",
",",
"directives",
")",
":",
"# type: (ExecutionContext, Optional[List[Directive]]) -> bool",
"# TODO: Refactor based on latest code",
"if",
"directives",
":",
"skip_ast",
"=",
"None",
"for",
"directive",
"in",
"directives",
":",
"i... | Determines if a field should be included based on the @include and
@skip directives, where @skip has higher precidence than @include. | [
"Determines",
"if",
"a",
"field",
"should",
"be",
"included",
"based",
"on",
"the"
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/utils.py#L285-L320 |
236,787 | graphql-python/graphql-core | graphql/execution/utils.py | default_resolve_fn | def default_resolve_fn(source, info, **args):
# type: (Any, ResolveInfo, **Any) -> Optional[Any]
"""If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object
of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function."""
name = info.field_name
if isinstance(source, dict):
property = source.get(name)
else:
property = getattr(source, name, None)
if callable(property):
return property()
return property | python | def default_resolve_fn(source, info, **args):
# type: (Any, ResolveInfo, **Any) -> Optional[Any]
name = info.field_name
if isinstance(source, dict):
property = source.get(name)
else:
property = getattr(source, name, None)
if callable(property):
return property()
return property | [
"def",
"default_resolve_fn",
"(",
"source",
",",
"info",
",",
"*",
"*",
"args",
")",
":",
"# type: (Any, ResolveInfo, **Any) -> Optional[Any]",
"name",
"=",
"info",
".",
"field_name",
"if",
"isinstance",
"(",
"source",
",",
"dict",
")",
":",
"property",
"=",
"... | If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object
of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function. | [
"If",
"a",
"resolve",
"function",
"is",
"not",
"given",
"then",
"a",
"default",
"resolve",
"behavior",
"is",
"used",
"which",
"takes",
"the",
"property",
"of",
"the",
"source",
"object",
"of",
"the",
"same",
"name",
"as",
"the",
"field",
"and",
"returns",
... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/utils.py#L351-L362 |
236,788 | graphql-python/graphql-core | graphql/execution/values.py | get_variable_values | def get_variable_values(
schema, # type: GraphQLSchema
definition_asts, # type: List[VariableDefinition]
inputs, # type: Any
):
# type: (...) -> Dict[str, Any]
"""Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input.
If the input cannot be parsed to match the variable definitions, a GraphQLError will be thrown."""
if inputs is None:
inputs = {}
values = {}
for def_ast in definition_asts:
var_name = def_ast.variable.name.value
var_type = type_from_ast(schema, def_ast.type)
value = inputs.get(var_name)
if not is_input_type(var_type):
raise GraphQLError(
'Variable "${var_name}" expected value of type "{var_type}" which cannot be used as an input type.'.format(
var_name=var_name, var_type=print_ast(def_ast.type)
),
[def_ast],
)
elif value is None:
if def_ast.default_value is not None:
values[var_name] = value_from_ast(
def_ast.default_value, var_type
) # type: ignore
if isinstance(var_type, GraphQLNonNull):
raise GraphQLError(
'Variable "${var_name}" of required type "{var_type}" was not provided.'.format(
var_name=var_name, var_type=var_type
),
[def_ast],
)
else:
errors = is_valid_value(value, var_type)
if errors:
message = u"\n" + u"\n".join(errors)
raise GraphQLError(
'Variable "${}" got invalid value {}.{}'.format(
var_name, json.dumps(value, sort_keys=True), message
),
[def_ast],
)
coerced_value = coerce_value(var_type, value)
if coerced_value is None:
raise Exception("Should have reported error.")
values[var_name] = coerced_value
return values | python | def get_variable_values(
schema, # type: GraphQLSchema
definition_asts, # type: List[VariableDefinition]
inputs, # type: Any
):
# type: (...) -> Dict[str, Any]
if inputs is None:
inputs = {}
values = {}
for def_ast in definition_asts:
var_name = def_ast.variable.name.value
var_type = type_from_ast(schema, def_ast.type)
value = inputs.get(var_name)
if not is_input_type(var_type):
raise GraphQLError(
'Variable "${var_name}" expected value of type "{var_type}" which cannot be used as an input type.'.format(
var_name=var_name, var_type=print_ast(def_ast.type)
),
[def_ast],
)
elif value is None:
if def_ast.default_value is not None:
values[var_name] = value_from_ast(
def_ast.default_value, var_type
) # type: ignore
if isinstance(var_type, GraphQLNonNull):
raise GraphQLError(
'Variable "${var_name}" of required type "{var_type}" was not provided.'.format(
var_name=var_name, var_type=var_type
),
[def_ast],
)
else:
errors = is_valid_value(value, var_type)
if errors:
message = u"\n" + u"\n".join(errors)
raise GraphQLError(
'Variable "${}" got invalid value {}.{}'.format(
var_name, json.dumps(value, sort_keys=True), message
),
[def_ast],
)
coerced_value = coerce_value(var_type, value)
if coerced_value is None:
raise Exception("Should have reported error.")
values[var_name] = coerced_value
return values | [
"def",
"get_variable_values",
"(",
"schema",
",",
"# type: GraphQLSchema",
"definition_asts",
",",
"# type: List[VariableDefinition]",
"inputs",
",",
"# type: Any",
")",
":",
"# type: (...) -> Dict[str, Any]",
"if",
"inputs",
"is",
"None",
":",
"inputs",
"=",
"{",
"}",
... | Prepares an object map of variables of the correct type based on the provided variable definitions and arbitrary input.
If the input cannot be parsed to match the variable definitions, a GraphQLError will be thrown. | [
"Prepares",
"an",
"object",
"map",
"of",
"variables",
"of",
"the",
"correct",
"type",
"based",
"on",
"the",
"provided",
"variable",
"definitions",
"and",
"arbitrary",
"input",
".",
"If",
"the",
"input",
"cannot",
"be",
"parsed",
"to",
"match",
"the",
"variab... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/values.py#L34-L86 |
236,789 | graphql-python/graphql-core | graphql/execution/values.py | get_argument_values | def get_argument_values(
arg_defs, # type: Union[Dict[str, GraphQLArgument], Dict]
arg_asts, # type: Optional[List[Argument]]
variables=None, # type: Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]
):
# type: (...) -> Dict[str, Any]
"""Prepares an object map of argument values given a list of argument
definitions and list of argument AST nodes."""
if not arg_defs:
return {}
if arg_asts:
arg_ast_map = {
arg.name.value: arg for arg in arg_asts
} # type: Dict[str, Argument]
else:
arg_ast_map = {}
result = {}
for name, arg_def in arg_defs.items():
arg_type = arg_def.type
arg_ast = arg_ast_map.get(name)
if name not in arg_ast_map:
if arg_def.default_value is not None:
result[arg_def.out_name or name] = arg_def.default_value
continue
elif isinstance(arg_type, GraphQLNonNull):
raise GraphQLError(
'Argument "{name}" of required type {arg_type}" was not provided.'.format(
name=name, arg_type=arg_type
),
arg_asts,
)
elif isinstance(arg_ast.value, ast.Variable): # type: ignore
variable_name = arg_ast.value.name.value # type: ignore
if variables and variable_name in variables:
result[arg_def.out_name or name] = variables[variable_name]
elif arg_def.default_value is not None:
result[arg_def.out_name or name] = arg_def.default_value
elif isinstance(arg_type, GraphQLNonNull):
raise GraphQLError(
'Argument "{name}" of required type {arg_type}" provided the variable "${variable_name}" which was not provided'.format(
name=name, arg_type=arg_type, variable_name=variable_name
),
arg_asts,
)
continue
else:
value = value_from_ast(arg_ast.value, arg_type, variables) # type: ignore
if value is None:
if arg_def.default_value is not None:
value = arg_def.default_value
result[arg_def.out_name or name] = value
else:
# We use out_name as the output name for the
# dict if exists
result[arg_def.out_name or name] = value
return result | python | def get_argument_values(
arg_defs, # type: Union[Dict[str, GraphQLArgument], Dict]
arg_asts, # type: Optional[List[Argument]]
variables=None, # type: Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]
):
# type: (...) -> Dict[str, Any]
if not arg_defs:
return {}
if arg_asts:
arg_ast_map = {
arg.name.value: arg for arg in arg_asts
} # type: Dict[str, Argument]
else:
arg_ast_map = {}
result = {}
for name, arg_def in arg_defs.items():
arg_type = arg_def.type
arg_ast = arg_ast_map.get(name)
if name not in arg_ast_map:
if arg_def.default_value is not None:
result[arg_def.out_name or name] = arg_def.default_value
continue
elif isinstance(arg_type, GraphQLNonNull):
raise GraphQLError(
'Argument "{name}" of required type {arg_type}" was not provided.'.format(
name=name, arg_type=arg_type
),
arg_asts,
)
elif isinstance(arg_ast.value, ast.Variable): # type: ignore
variable_name = arg_ast.value.name.value # type: ignore
if variables and variable_name in variables:
result[arg_def.out_name or name] = variables[variable_name]
elif arg_def.default_value is not None:
result[arg_def.out_name or name] = arg_def.default_value
elif isinstance(arg_type, GraphQLNonNull):
raise GraphQLError(
'Argument "{name}" of required type {arg_type}" provided the variable "${variable_name}" which was not provided'.format(
name=name, arg_type=arg_type, variable_name=variable_name
),
arg_asts,
)
continue
else:
value = value_from_ast(arg_ast.value, arg_type, variables) # type: ignore
if value is None:
if arg_def.default_value is not None:
value = arg_def.default_value
result[arg_def.out_name or name] = value
else:
# We use out_name as the output name for the
# dict if exists
result[arg_def.out_name or name] = value
return result | [
"def",
"get_argument_values",
"(",
"arg_defs",
",",
"# type: Union[Dict[str, GraphQLArgument], Dict]",
"arg_asts",
",",
"# type: Optional[List[Argument]]",
"variables",
"=",
"None",
",",
"# type: Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]]",
")",
":",
"# type:... | Prepares an object map of argument values given a list of argument
definitions and list of argument AST nodes. | [
"Prepares",
"an",
"object",
"map",
"of",
"argument",
"values",
"given",
"a",
"list",
"of",
"argument",
"definitions",
"and",
"list",
"of",
"argument",
"AST",
"nodes",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/values.py#L89-L148 |
236,790 | graphql-python/graphql-core | graphql/execution/values.py | coerce_value | def coerce_value(type, value):
# type: (Any, Any) -> Union[List, Dict, int, float, bool, str, None]
"""Given a type and any value, return a runtime value coerced to match the type."""
if isinstance(type, GraphQLNonNull):
# Note: we're not checking that the result of coerceValue is
# non-null.
# We only call this function after calling isValidValue.
return coerce_value(type.of_type, value)
if value is None:
return None
if isinstance(type, GraphQLList):
item_type = type.of_type
if not isinstance(value, string_types) and isinstance(value, Iterable):
return [coerce_value(item_type, item) for item in value]
else:
return [coerce_value(item_type, value)]
if isinstance(type, GraphQLInputObjectType):
fields = type.fields
obj = {}
for field_name, field in fields.items():
if field_name not in value:
if field.default_value is not None:
field_value = field.default_value
obj[field.out_name or field_name] = field_value
else:
field_value = coerce_value(field.type, value.get(field_name))
obj[field.out_name or field_name] = field_value
return type.create_container(obj)
assert isinstance(type, (GraphQLScalarType, GraphQLEnumType)), "Must be input type"
return type.parse_value(value) | python | def coerce_value(type, value):
# type: (Any, Any) -> Union[List, Dict, int, float, bool, str, None]
if isinstance(type, GraphQLNonNull):
# Note: we're not checking that the result of coerceValue is
# non-null.
# We only call this function after calling isValidValue.
return coerce_value(type.of_type, value)
if value is None:
return None
if isinstance(type, GraphQLList):
item_type = type.of_type
if not isinstance(value, string_types) and isinstance(value, Iterable):
return [coerce_value(item_type, item) for item in value]
else:
return [coerce_value(item_type, value)]
if isinstance(type, GraphQLInputObjectType):
fields = type.fields
obj = {}
for field_name, field in fields.items():
if field_name not in value:
if field.default_value is not None:
field_value = field.default_value
obj[field.out_name or field_name] = field_value
else:
field_value = coerce_value(field.type, value.get(field_name))
obj[field.out_name or field_name] = field_value
return type.create_container(obj)
assert isinstance(type, (GraphQLScalarType, GraphQLEnumType)), "Must be input type"
return type.parse_value(value) | [
"def",
"coerce_value",
"(",
"type",
",",
"value",
")",
":",
"# type: (Any, Any) -> Union[List, Dict, int, float, bool, str, None]",
"if",
"isinstance",
"(",
"type",
",",
"GraphQLNonNull",
")",
":",
"# Note: we're not checking that the result of coerceValue is",
"# non-null.",
"... | Given a type and any value, return a runtime value coerced to match the type. | [
"Given",
"a",
"type",
"and",
"any",
"value",
"return",
"a",
"runtime",
"value",
"coerced",
"to",
"match",
"the",
"type",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/values.py#L151-L186 |
236,791 | graphql-python/graphql-core | graphql/language/parser.py | parse | def parse(source, **kwargs):
# type: (Union[Source, str], **Any) -> Document
"""Given a GraphQL source, parses it into a Document."""
options = {"no_location": False, "no_source": False}
options.update(kwargs)
if isinstance(source, string_types):
source_obj = Source(source) # type: Source
else:
source_obj = source # type: ignore
parser = Parser(source_obj, options)
return parse_document(parser) | python | def parse(source, **kwargs):
# type: (Union[Source, str], **Any) -> Document
options = {"no_location": False, "no_source": False}
options.update(kwargs)
if isinstance(source, string_types):
source_obj = Source(source) # type: Source
else:
source_obj = source # type: ignore
parser = Parser(source_obj, options)
return parse_document(parser) | [
"def",
"parse",
"(",
"source",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Union[Source, str], **Any) -> Document",
"options",
"=",
"{",
"\"no_location\"",
":",
"False",
",",
"\"no_source\"",
":",
"False",
"}",
"options",
".",
"update",
"(",
"kwargs",
")",
"i... | Given a GraphQL source, parses it into a Document. | [
"Given",
"a",
"GraphQL",
"source",
"parses",
"it",
"into",
"a",
"Document",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L52-L64 |
236,792 | graphql-python/graphql-core | graphql/language/parser.py | loc | def loc(parser, start):
# type: (Parser, int) -> Optional[Loc]
"""Returns a location object, used to identify the place in
the source that created a given parsed object."""
if parser.options["no_location"]:
return None
if parser.options["no_source"]:
return Loc(start, parser.prev_end)
return Loc(start, parser.prev_end, parser.source) | python | def loc(parser, start):
# type: (Parser, int) -> Optional[Loc]
if parser.options["no_location"]:
return None
if parser.options["no_source"]:
return Loc(start, parser.prev_end)
return Loc(start, parser.prev_end, parser.source) | [
"def",
"loc",
"(",
"parser",
",",
"start",
")",
":",
"# type: (Parser, int) -> Optional[Loc]",
"if",
"parser",
".",
"options",
"[",
"\"no_location\"",
"]",
":",
"return",
"None",
"if",
"parser",
".",
"options",
"[",
"\"no_source\"",
"]",
":",
"return",
"Loc",
... | Returns a location object, used to identify the place in
the source that created a given parsed object. | [
"Returns",
"a",
"location",
"object",
"used",
"to",
"identify",
"the",
"place",
"in",
"the",
"source",
"that",
"created",
"a",
"given",
"parsed",
"object",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L114-L124 |
236,793 | graphql-python/graphql-core | graphql/language/parser.py | advance | def advance(parser):
# type: (Parser) -> None
"""Moves the internal parser object to the next lexed token."""
prev_end = parser.token.end
parser.prev_end = prev_end
parser.token = parser.lexer.next_token(prev_end) | python | def advance(parser):
# type: (Parser) -> None
prev_end = parser.token.end
parser.prev_end = prev_end
parser.token = parser.lexer.next_token(prev_end) | [
"def",
"advance",
"(",
"parser",
")",
":",
"# type: (Parser) -> None",
"prev_end",
"=",
"parser",
".",
"token",
".",
"end",
"parser",
".",
"prev_end",
"=",
"prev_end",
"parser",
".",
"token",
"=",
"parser",
".",
"lexer",
".",
"next_token",
"(",
"prev_end",
... | Moves the internal parser object to the next lexed token. | [
"Moves",
"the",
"internal",
"parser",
"object",
"to",
"the",
"next",
"lexed",
"token",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L127-L132 |
236,794 | graphql-python/graphql-core | graphql/language/parser.py | skip | def skip(parser, kind):
# type: (Parser, int) -> bool
"""If the next token is of the given kind, return true after advancing
the parser. Otherwise, do not change the parser state
and throw an error."""
match = parser.token.kind == kind
if match:
advance(parser)
return match | python | def skip(parser, kind):
# type: (Parser, int) -> bool
match = parser.token.kind == kind
if match:
advance(parser)
return match | [
"def",
"skip",
"(",
"parser",
",",
"kind",
")",
":",
"# type: (Parser, int) -> bool",
"match",
"=",
"parser",
".",
"token",
".",
"kind",
"==",
"kind",
"if",
"match",
":",
"advance",
"(",
"parser",
")",
"return",
"match"
] | If the next token is of the given kind, return true after advancing
the parser. Otherwise, do not change the parser state
and throw an error. | [
"If",
"the",
"next",
"token",
"is",
"of",
"the",
"given",
"kind",
"return",
"true",
"after",
"advancing",
"the",
"parser",
".",
"Otherwise",
"do",
"not",
"change",
"the",
"parser",
"state",
"and",
"throw",
"an",
"error",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L141-L150 |
236,795 | graphql-python/graphql-core | graphql/language/parser.py | expect | def expect(parser, kind):
# type: (Parser, int) -> Token
"""If the next token is of the given kind, return that token after
advancing the parser. Otherwise, do not change the parser state and
return False."""
token = parser.token
if token.kind == kind:
advance(parser)
return token
raise GraphQLSyntaxError(
parser.source,
token.start,
u"Expected {}, found {}".format(
get_token_kind_desc(kind), get_token_desc(token)
),
) | python | def expect(parser, kind):
# type: (Parser, int) -> Token
token = parser.token
if token.kind == kind:
advance(parser)
return token
raise GraphQLSyntaxError(
parser.source,
token.start,
u"Expected {}, found {}".format(
get_token_kind_desc(kind), get_token_desc(token)
),
) | [
"def",
"expect",
"(",
"parser",
",",
"kind",
")",
":",
"# type: (Parser, int) -> Token",
"token",
"=",
"parser",
".",
"token",
"if",
"token",
".",
"kind",
"==",
"kind",
":",
"advance",
"(",
"parser",
")",
"return",
"token",
"raise",
"GraphQLSyntaxError",
"("... | If the next token is of the given kind, return that token after
advancing the parser. Otherwise, do not change the parser state and
return False. | [
"If",
"the",
"next",
"token",
"is",
"of",
"the",
"given",
"kind",
"return",
"that",
"token",
"after",
"advancing",
"the",
"parser",
".",
"Otherwise",
"do",
"not",
"change",
"the",
"parser",
"state",
"and",
"return",
"False",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L153-L169 |
236,796 | graphql-python/graphql-core | graphql/language/parser.py | expect_keyword | def expect_keyword(parser, value):
# type: (Parser, str) -> Token
"""If the next token is a keyword with the given value, return that
token after advancing the parser. Otherwise, do not change the parser
state and return False."""
token = parser.token
if token.kind == TokenKind.NAME and token.value == value:
advance(parser)
return token
raise GraphQLSyntaxError(
parser.source,
token.start,
u'Expected "{}", found {}'.format(value, get_token_desc(token)),
) | python | def expect_keyword(parser, value):
# type: (Parser, str) -> Token
token = parser.token
if token.kind == TokenKind.NAME and token.value == value:
advance(parser)
return token
raise GraphQLSyntaxError(
parser.source,
token.start,
u'Expected "{}", found {}'.format(value, get_token_desc(token)),
) | [
"def",
"expect_keyword",
"(",
"parser",
",",
"value",
")",
":",
"# type: (Parser, str) -> Token",
"token",
"=",
"parser",
".",
"token",
"if",
"token",
".",
"kind",
"==",
"TokenKind",
".",
"NAME",
"and",
"token",
".",
"value",
"==",
"value",
":",
"advance",
... | If the next token is a keyword with the given value, return that
token after advancing the parser. Otherwise, do not change the parser
state and return False. | [
"If",
"the",
"next",
"token",
"is",
"a",
"keyword",
"with",
"the",
"given",
"value",
"return",
"that",
"token",
"after",
"advancing",
"the",
"parser",
".",
"Otherwise",
"do",
"not",
"change",
"the",
"parser",
"state",
"and",
"return",
"False",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L172-L186 |
236,797 | graphql-python/graphql-core | graphql/language/parser.py | unexpected | def unexpected(parser, at_token=None):
# type: (Parser, Optional[Any]) -> GraphQLSyntaxError
"""Helper function for creating an error when an unexpected lexed token
is encountered."""
token = at_token or parser.token
return GraphQLSyntaxError(
parser.source, token.start, u"Unexpected {}".format(get_token_desc(token))
) | python | def unexpected(parser, at_token=None):
# type: (Parser, Optional[Any]) -> GraphQLSyntaxError
token = at_token or parser.token
return GraphQLSyntaxError(
parser.source, token.start, u"Unexpected {}".format(get_token_desc(token))
) | [
"def",
"unexpected",
"(",
"parser",
",",
"at_token",
"=",
"None",
")",
":",
"# type: (Parser, Optional[Any]) -> GraphQLSyntaxError",
"token",
"=",
"at_token",
"or",
"parser",
".",
"token",
"return",
"GraphQLSyntaxError",
"(",
"parser",
".",
"source",
",",
"token",
... | Helper function for creating an error when an unexpected lexed token
is encountered. | [
"Helper",
"function",
"for",
"creating",
"an",
"error",
"when",
"an",
"unexpected",
"lexed",
"token",
"is",
"encountered",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L189-L196 |
236,798 | graphql-python/graphql-core | graphql/language/parser.py | any | def any(parser, open_kind, parse_fn, close_kind):
# type: (Parser, int, Callable, int) -> Any
"""Returns a possibly empty list of parse nodes, determined by
the parse_fn. This list begins with a lex token of openKind
and ends with a lex token of closeKind. Advances the parser
to the next lex token after the closing token."""
expect(parser, open_kind)
nodes = []
while not skip(parser, close_kind):
nodes.append(parse_fn(parser))
return nodes | python | def any(parser, open_kind, parse_fn, close_kind):
# type: (Parser, int, Callable, int) -> Any
expect(parser, open_kind)
nodes = []
while not skip(parser, close_kind):
nodes.append(parse_fn(parser))
return nodes | [
"def",
"any",
"(",
"parser",
",",
"open_kind",
",",
"parse_fn",
",",
"close_kind",
")",
":",
"# type: (Parser, int, Callable, int) -> Any",
"expect",
"(",
"parser",
",",
"open_kind",
")",
"nodes",
"=",
"[",
"]",
"while",
"not",
"skip",
"(",
"parser",
",",
"c... | Returns a possibly empty list of parse nodes, determined by
the parse_fn. This list begins with a lex token of openKind
and ends with a lex token of closeKind. Advances the parser
to the next lex token after the closing token. | [
"Returns",
"a",
"possibly",
"empty",
"list",
"of",
"parse",
"nodes",
"determined",
"by",
"the",
"parse_fn",
".",
"This",
"list",
"begins",
"with",
"a",
"lex",
"token",
"of",
"openKind",
"and",
"ends",
"with",
"a",
"lex",
"token",
"of",
"closeKind",
".",
... | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L199-L210 |
236,799 | graphql-python/graphql-core | graphql/language/parser.py | parse_name | def parse_name(parser):
# type: (Parser) -> Name
"""Converts a name lex token into a name parse node."""
token = expect(parser, TokenKind.NAME)
return ast.Name(value=token.value, loc=loc(parser, token.start)) | python | def parse_name(parser):
# type: (Parser) -> Name
token = expect(parser, TokenKind.NAME)
return ast.Name(value=token.value, loc=loc(parser, token.start)) | [
"def",
"parse_name",
"(",
"parser",
")",
":",
"# type: (Parser) -> Name",
"token",
"=",
"expect",
"(",
"parser",
",",
"TokenKind",
".",
"NAME",
")",
"return",
"ast",
".",
"Name",
"(",
"value",
"=",
"token",
".",
"value",
",",
"loc",
"=",
"loc",
"(",
"p... | Converts a name lex token into a name parse node. | [
"Converts",
"a",
"name",
"lex",
"token",
"into",
"a",
"name",
"parse",
"node",
"."
] | d8e9d3abe7c209eb2f51cf001402783bfd480596 | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/language/parser.py#L227-L231 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.