id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
222,900 | 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):
"""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 | [
"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 |
222,901 | 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):
"""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() | [
"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 |
222,902 | 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):
"""Packs the scrollbar.
"""
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 |
222,903 | 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
"""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) | [
"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 |
222,904 | 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
"""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) | [
"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 |
222,905 | 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):
"""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() | [
"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 |
222,906 | 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):
"""Show the tray icon menu.
"""
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 |
222,907 | 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):
"""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() | [
"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 |
222,908 | 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):
"""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') | [
"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 |
222,909 | 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):
"""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() | [
"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 |
222,910 | 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):
""""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') | [
"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 |
222,911 | 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):
"""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() | [
"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 |
222,912 | 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
"""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 | [
"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 |
222,913 | 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):
"""Callback to zoom in.
"""
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 |
222,914 | 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):
"""Callback to zoom out.
"""
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 |
222,915 | 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):
"""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 | [
"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 |
222,916 | 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):
"""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 | [
"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 |
222,917 | 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):
"""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 | [
"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 |
222,918 | 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):
"""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 | [
"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 |
222,919 | 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):
"""Callback to toggle transparency.
"""
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 |
222,920 | 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):
"""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 | [
"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 |
222,921 | 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):
"""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 | [
"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 |
222,922 | 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
""" 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 | [
"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 |
222,923 | 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
""" 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 | [
"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 |
222,924 | 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):
"""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 | [
"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 |
222,925 | 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):
"""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 | [
"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 |
222,926 | 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):
"""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) | [
"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 |
222,927 | 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):
"""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) | [
"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 |
222,928 | 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):
"""Closes the current tab.
"""
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 |
222,929 | 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):
"""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) | [
"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 |
222,930 | 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
"""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()) | [
"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 |
222,931 | 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):
"""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 | [
"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 |
222,932 | 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):
"""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) | [
"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 |
222,933 | 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):
"""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)] | [
"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 |
222,934 | 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):
"""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) | [
"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 |
222,935 | 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]]:
"""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) | [
"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 |
222,936 | 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):
"""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] | [
"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 |
222,937 | 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):
"""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 | [
"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 |
222,938 | 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
"""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 | [
"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 |
222,939 | 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
"""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] | [
"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 |
222,940 | 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
"""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] | [
"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 |
222,941 | 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
"""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)) | [
"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 |
222,942 | 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):
"""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 [] | [
"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 |
222,943 | 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):
"""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 [] | [
"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 |
222,944 | 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
"""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 | [
"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 |
222,945 | 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):
"""
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]
) | [
"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 |
222,946 | 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):
"""
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)] | [
"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 |
222,947 | 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):
"""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 | [
"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 |
222,948 | 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
"""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))
) | [
"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 |
222,949 | 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
"""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 | [
"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 |
222,950 | 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 |
222,951 | 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
"""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)) | [
"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 |
222,952 | 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
"""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]) | [
"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 |
222,953 | 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
"""
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) | [
"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 |
222,954 | 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]
"""
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 | [
"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 |
222,955 | 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]
"""
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 | [
"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 |
222,956 | 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]
"""
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
) | [
"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 |
222,957 | 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]
"""
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) | [
"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 |
222,958 | 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
"""
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 | [
"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 |
222,959 | 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]
"""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) | [
"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 |
222,960 | 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
"""
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() | [
"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 |
222,961 | 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):
"""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 | [
"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 |
222,962 | 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):
"""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() | [
"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 |
222,963 | 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]
"""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) | [
"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 |
222,964 | 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]]]
"""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 | [
"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 |
222,965 | 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]]]
"""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 | [
"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 |
222,966 | 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]]]
"""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 | [
"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 |
222,967 | 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]]
"""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
) | [
"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 |
222,968 | 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]]]
"""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 | [
"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 |
222,969 | 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
"""
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 | [
"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 |
222,970 | 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
"""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 | [
"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 |
222,971 | 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]
"""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 | [
"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 |
222,972 | 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]
"""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 | [
"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 |
222,973 | 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]
"""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 | [
"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 |
222,974 | 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]
"""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) | [
"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 |
222,975 | 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
"""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) | [
"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 |
222,976 | 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]
"""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) | [
"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 |
222,977 | 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
"""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) | [
"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 |
222,978 | 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
"""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 | [
"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 |
222,979 | 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
"""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)
),
) | [
"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 |
222,980 | 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
"""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)),
) | [
"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 |
222,981 | 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
"""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))
) | [
"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 |
222,982 | 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
"""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 | [
"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 |
222,983 | 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
"""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)) | [
"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 |
222,984 | kieferk/dfply | dfply/summary_functions.py | mean | def mean(series):
"""
Returns the mean of a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.mean()
else:
return np.nan | python | def mean(series):
"""
Returns the mean of a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.mean()
else:
return np.nan | [
"def",
"mean",
"(",
"series",
")",
":",
"if",
"np",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"np",
".",
"number",
")",
":",
"return",
"series",
".",
"mean",
"(",
")",
"else",
":",
"return",
"np",
".",
"nan"
] | Returns the mean of a series.
Args:
series (pandas.Series): column to summarize. | [
"Returns",
"the",
"mean",
"of",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L11-L22 |
222,985 | kieferk/dfply | dfply/summary_functions.py | first | def first(series, order_by=None):
"""
Returns the first value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization.
"""
if order_by is not None:
series = order_series_by(series, order_by)
first_s = series.iloc[0]
return first_s | python | def first(series, order_by=None):
"""
Returns the first value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization.
"""
if order_by is not None:
series = order_series_by(series, order_by)
first_s = series.iloc[0]
return first_s | [
"def",
"first",
"(",
"series",
",",
"order_by",
"=",
"None",
")",
":",
"if",
"order_by",
"is",
"not",
"None",
":",
"series",
"=",
"order_series_by",
"(",
"series",
",",
"order_by",
")",
"first_s",
"=",
"series",
".",
"iloc",
"[",
"0",
"]",
"return",
... | Returns the first value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization. | [
"Returns",
"the",
"first",
"value",
"of",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L26-L41 |
222,986 | kieferk/dfply | dfply/summary_functions.py | last | def last(series, order_by=None):
"""
Returns the last value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization.
"""
if order_by is not None:
series = order_series_by(series, order_by)
last_s = series.iloc[series.size - 1]
return last_s | python | def last(series, order_by=None):
"""
Returns the last value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization.
"""
if order_by is not None:
series = order_series_by(series, order_by)
last_s = series.iloc[series.size - 1]
return last_s | [
"def",
"last",
"(",
"series",
",",
"order_by",
"=",
"None",
")",
":",
"if",
"order_by",
"is",
"not",
"None",
":",
"series",
"=",
"order_series_by",
"(",
"series",
",",
"order_by",
")",
"last_s",
"=",
"series",
".",
"iloc",
"[",
"series",
".",
"size",
... | Returns the last value of a series.
Args:
series (pandas.Series): column to summarize.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization. | [
"Returns",
"the",
"last",
"value",
"of",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L45-L60 |
222,987 | kieferk/dfply | dfply/summary_functions.py | nth | def nth(series, n, order_by=None):
"""
Returns the nth value of a series.
Args:
series (pandas.Series): column to summarize.
n (integer): position of desired value. Returns `NaN` if out of range.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization.
"""
if order_by is not None:
series = order_series_by(series, order_by)
try:
return series.iloc[n]
except:
return np.nan | python | def nth(series, n, order_by=None):
"""
Returns the nth value of a series.
Args:
series (pandas.Series): column to summarize.
n (integer): position of desired value. Returns `NaN` if out of range.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization.
"""
if order_by is not None:
series = order_series_by(series, order_by)
try:
return series.iloc[n]
except:
return np.nan | [
"def",
"nth",
"(",
"series",
",",
"n",
",",
"order_by",
"=",
"None",
")",
":",
"if",
"order_by",
"is",
"not",
"None",
":",
"series",
"=",
"order_series_by",
"(",
"series",
",",
"order_by",
")",
"try",
":",
"return",
"series",
".",
"iloc",
"[",
"n",
... | Returns the nth value of a series.
Args:
series (pandas.Series): column to summarize.
n (integer): position of desired value. Returns `NaN` if out of range.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarization. | [
"Returns",
"the",
"nth",
"value",
"of",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L64-L82 |
222,988 | kieferk/dfply | dfply/summary_functions.py | median | def median(series):
"""
Returns the median value of a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.median()
else:
return np.nan | python | def median(series):
"""
Returns the median value of a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.median()
else:
return np.nan | [
"def",
"median",
"(",
"series",
")",
":",
"if",
"np",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"np",
".",
"number",
")",
":",
"return",
"series",
".",
"median",
"(",
")",
"else",
":",
"return",
"np",
".",
"nan"
] | Returns the median value of a series.
Args:
series (pandas.Series): column to summarize. | [
"Returns",
"the",
"median",
"value",
"of",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L153-L164 |
222,989 | kieferk/dfply | dfply/summary_functions.py | var | def var(series):
"""
Returns the variance of values in a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.var()
else:
return np.nan | python | def var(series):
"""
Returns the variance of values in a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.var()
else:
return np.nan | [
"def",
"var",
"(",
"series",
")",
":",
"if",
"np",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"np",
".",
"number",
")",
":",
"return",
"series",
".",
"var",
"(",
")",
"else",
":",
"return",
"np",
".",
"nan"
] | Returns the variance of values in a series.
Args:
series (pandas.Series): column to summarize. | [
"Returns",
"the",
"variance",
"of",
"values",
"in",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L168-L178 |
222,990 | kieferk/dfply | dfply/summary_functions.py | sd | def sd(series):
"""
Returns the standard deviation of values in a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.std()
else:
return np.nan | python | def sd(series):
"""
Returns the standard deviation of values in a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.std()
else:
return np.nan | [
"def",
"sd",
"(",
"series",
")",
":",
"if",
"np",
".",
"issubdtype",
"(",
"series",
".",
"dtype",
",",
"np",
".",
"number",
")",
":",
"return",
"series",
".",
"std",
"(",
")",
"else",
":",
"return",
"np",
".",
"nan"
] | Returns the standard deviation of values in a series.
Args:
series (pandas.Series): column to summarize. | [
"Returns",
"the",
"standard",
"deviation",
"of",
"values",
"in",
"a",
"series",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L182-L193 |
222,991 | kieferk/dfply | dfply/join.py | get_join_parameters | def get_join_parameters(join_kwargs):
"""
Convenience function to determine the columns to join the right and
left DataFrames on, as well as any suffixes for the columns.
"""
by = join_kwargs.get('by', None)
suffixes = join_kwargs.get('suffixes', ('_x', '_y'))
if isinstance(by, tuple):
left_on, right_on = by
elif isinstance(by, list):
by = [x if isinstance(x, tuple) else (x, x) for x in by]
left_on, right_on = (list(x) for x in zip(*by))
else:
left_on, right_on = by, by
return left_on, right_on, suffixes | python | def get_join_parameters(join_kwargs):
"""
Convenience function to determine the columns to join the right and
left DataFrames on, as well as any suffixes for the columns.
"""
by = join_kwargs.get('by', None)
suffixes = join_kwargs.get('suffixes', ('_x', '_y'))
if isinstance(by, tuple):
left_on, right_on = by
elif isinstance(by, list):
by = [x if isinstance(x, tuple) else (x, x) for x in by]
left_on, right_on = (list(x) for x in zip(*by))
else:
left_on, right_on = by, by
return left_on, right_on, suffixes | [
"def",
"get_join_parameters",
"(",
"join_kwargs",
")",
":",
"by",
"=",
"join_kwargs",
".",
"get",
"(",
"'by'",
",",
"None",
")",
"suffixes",
"=",
"join_kwargs",
".",
"get",
"(",
"'suffixes'",
",",
"(",
"'_x'",
",",
"'_y'",
")",
")",
"if",
"isinstance",
... | Convenience function to determine the columns to join the right and
left DataFrames on, as well as any suffixes for the columns. | [
"Convenience",
"function",
"to",
"determine",
"the",
"columns",
"to",
"join",
"the",
"right",
"and",
"left",
"DataFrames",
"on",
"as",
"well",
"as",
"any",
"suffixes",
"for",
"the",
"columns",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/join.py#L8-L23 |
222,992 | kieferk/dfply | dfply/join.py | inner_join | def inner_join(df, other, **kwargs):
"""
Joins on values present in both DataFrames.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
on that column. If a list of lists which contain strings or
integers, the right/left columns to join on.
suffixes (list): String suffixes to append to column names in left
and right DataFrames.
Example:
a >> inner_join(b, by='x1')
x1 x2 x3
0 A 1 True
1 B 2 False
"""
left_on, right_on, suffixes = get_join_parameters(kwargs)
joined = df.merge(other, how='inner', left_on=left_on,
right_on=right_on, suffixes=suffixes)
return joined | python | def inner_join(df, other, **kwargs):
"""
Joins on values present in both DataFrames.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
on that column. If a list of lists which contain strings or
integers, the right/left columns to join on.
suffixes (list): String suffixes to append to column names in left
and right DataFrames.
Example:
a >> inner_join(b, by='x1')
x1 x2 x3
0 A 1 True
1 B 2 False
"""
left_on, right_on, suffixes = get_join_parameters(kwargs)
joined = df.merge(other, how='inner', left_on=left_on,
right_on=right_on, suffixes=suffixes)
return joined | [
"def",
"inner_join",
"(",
"df",
",",
"other",
",",
"*",
"*",
"kwargs",
")",
":",
"left_on",
",",
"right_on",
",",
"suffixes",
"=",
"get_join_parameters",
"(",
"kwargs",
")",
"joined",
"=",
"df",
".",
"merge",
"(",
"other",
",",
"how",
"=",
"'inner'",
... | Joins on values present in both DataFrames.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
on that column. If a list of lists which contain strings or
integers, the right/left columns to join on.
suffixes (list): String suffixes to append to column names in left
and right DataFrames.
Example:
a >> inner_join(b, by='x1')
x1 x2 x3
0 A 1 True
1 B 2 False | [
"Joins",
"on",
"values",
"present",
"in",
"both",
"DataFrames",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/join.py#L27-L53 |
222,993 | kieferk/dfply | dfply/join.py | anti_join | def anti_join(df, other, **kwargs):
"""
Returns all of the rows in the left DataFrame that do not have a
match in the right DataFrame.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
on that column. If a list of lists which contain strings or
integers, the right/left columns to join on.
Example:
a >> anti_join(b, by='x1')
x1 x2
2 C 3
"""
left_on, right_on, suffixes = get_join_parameters(kwargs)
if not right_on:
right_on = [col_name for col_name in df.columns.values.tolist() if col_name in other.columns.values.tolist()]
left_on = right_on
elif not isinstance(right_on, (list, tuple)):
right_on = [right_on]
other_reduced = other[right_on].drop_duplicates()
joined = df.merge(other_reduced, how='left', left_on=left_on,
right_on=right_on, suffixes=('', '_y'),
indicator=True).query('_merge=="left_only"')[df.columns.values.tolist()]
return joined | python | def anti_join(df, other, **kwargs):
"""
Returns all of the rows in the left DataFrame that do not have a
match in the right DataFrame.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
on that column. If a list of lists which contain strings or
integers, the right/left columns to join on.
Example:
a >> anti_join(b, by='x1')
x1 x2
2 C 3
"""
left_on, right_on, suffixes = get_join_parameters(kwargs)
if not right_on:
right_on = [col_name for col_name in df.columns.values.tolist() if col_name in other.columns.values.tolist()]
left_on = right_on
elif not isinstance(right_on, (list, tuple)):
right_on = [right_on]
other_reduced = other[right_on].drop_duplicates()
joined = df.merge(other_reduced, how='left', left_on=left_on,
right_on=right_on, suffixes=('', '_y'),
indicator=True).query('_merge=="left_only"')[df.columns.values.tolist()]
return joined | [
"def",
"anti_join",
"(",
"df",
",",
"other",
",",
"*",
"*",
"kwargs",
")",
":",
"left_on",
",",
"right_on",
",",
"suffixes",
"=",
"get_join_parameters",
"(",
"kwargs",
")",
"if",
"not",
"right_on",
":",
"right_on",
"=",
"[",
"col_name",
"for",
"col_name"... | Returns all of the rows in the left DataFrame that do not have a
match in the right DataFrame.
Args:
df (pandas.DataFrame): Left DataFrame (passed in via pipe)
other (pandas.DataFrame): Right DataFrame
Kwargs:
by (str or list): Columns to join on. If a single string, will join
on that column. If a list of lists which contain strings or
integers, the right/left columns to join on.
Example:
a >> anti_join(b, by='x1')
x1 x2
2 C 3 | [
"Returns",
"all",
"of",
"the",
"rows",
"in",
"the",
"left",
"DataFrame",
"that",
"do",
"not",
"have",
"a",
"match",
"in",
"the",
"right",
"DataFrame",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/join.py#L219-L250 |
222,994 | kieferk/dfply | dfply/join.py | bind_rows | def bind_rows(df, other, join='outer', ignore_index=False):
"""
Binds DataFrames "vertically", stacking them together. This is equivalent
to `pd.concat` with `axis=0`.
Args:
df (pandas.DataFrame): Top DataFrame (passed in via pipe).
other (pandas.DataFrame): Bottom DataFrame.
Kwargs:
join (str): One of `"outer"` or `"inner"`. Outer join will preserve
columns not present in both DataFrames, whereas inner joining will
drop them.
ignore_index (bool): Indicates whether to consider pandas indices as
part of the concatenation (defaults to `False`).
"""
df = pd.concat([df, other], join=join, ignore_index=ignore_index, axis=0)
return df | python | def bind_rows(df, other, join='outer', ignore_index=False):
"""
Binds DataFrames "vertically", stacking them together. This is equivalent
to `pd.concat` with `axis=0`.
Args:
df (pandas.DataFrame): Top DataFrame (passed in via pipe).
other (pandas.DataFrame): Bottom DataFrame.
Kwargs:
join (str): One of `"outer"` or `"inner"`. Outer join will preserve
columns not present in both DataFrames, whereas inner joining will
drop them.
ignore_index (bool): Indicates whether to consider pandas indices as
part of the concatenation (defaults to `False`).
"""
df = pd.concat([df, other], join=join, ignore_index=ignore_index, axis=0)
return df | [
"def",
"bind_rows",
"(",
"df",
",",
"other",
",",
"join",
"=",
"'outer'",
",",
"ignore_index",
"=",
"False",
")",
":",
"df",
"=",
"pd",
".",
"concat",
"(",
"[",
"df",
",",
"other",
"]",
",",
"join",
"=",
"join",
",",
"ignore_index",
"=",
"ignore_in... | Binds DataFrames "vertically", stacking them together. This is equivalent
to `pd.concat` with `axis=0`.
Args:
df (pandas.DataFrame): Top DataFrame (passed in via pipe).
other (pandas.DataFrame): Bottom DataFrame.
Kwargs:
join (str): One of `"outer"` or `"inner"`. Outer join will preserve
columns not present in both DataFrames, whereas inner joining will
drop them.
ignore_index (bool): Indicates whether to consider pandas indices as
part of the concatenation (defaults to `False`). | [
"Binds",
"DataFrames",
"vertically",
"stacking",
"them",
"together",
".",
"This",
"is",
"equivalent",
"to",
"pd",
".",
"concat",
"with",
"axis",
"=",
"0",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/join.py#L258-L276 |
222,995 | kieferk/dfply | dfply/reshape.py | arrange | def arrange(df, *args, **kwargs):
"""Calls `pandas.DataFrame.sort_values` to sort a DataFrame according to
criteria.
See:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
For a list of specific keyword arguments for sort_values (which will be
the same in arrange).
Args:
*args: Symbolic, string, integer or lists of those types indicating
columns to sort the DataFrame by.
Kwargs:
**kwargs: Any keyword arguments will be passed through to the pandas
`DataFrame.sort_values` function.
"""
flat_args = [a for a in flatten(args)]
series = [df[arg] if isinstance(arg, str) else
df.iloc[:, arg] if isinstance(arg, int) else
pd.Series(arg) for arg in flat_args]
sorter = pd.concat(series, axis=1).reset_index(drop=True)
sorter = sorter.sort_values(sorter.columns.tolist(), **kwargs)
return df.iloc[sorter.index, :] | python | def arrange(df, *args, **kwargs):
"""Calls `pandas.DataFrame.sort_values` to sort a DataFrame according to
criteria.
See:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
For a list of specific keyword arguments for sort_values (which will be
the same in arrange).
Args:
*args: Symbolic, string, integer or lists of those types indicating
columns to sort the DataFrame by.
Kwargs:
**kwargs: Any keyword arguments will be passed through to the pandas
`DataFrame.sort_values` function.
"""
flat_args = [a for a in flatten(args)]
series = [df[arg] if isinstance(arg, str) else
df.iloc[:, arg] if isinstance(arg, int) else
pd.Series(arg) for arg in flat_args]
sorter = pd.concat(series, axis=1).reset_index(drop=True)
sorter = sorter.sort_values(sorter.columns.tolist(), **kwargs)
return df.iloc[sorter.index, :] | [
"def",
"arrange",
"(",
"df",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"flat_args",
"=",
"[",
"a",
"for",
"a",
"in",
"flatten",
"(",
"args",
")",
"]",
"series",
"=",
"[",
"df",
"[",
"arg",
"]",
"if",
"isinstance",
"(",
"arg",
",",
... | Calls `pandas.DataFrame.sort_values` to sort a DataFrame according to
criteria.
See:
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html
For a list of specific keyword arguments for sort_values (which will be
the same in arrange).
Args:
*args: Symbolic, string, integer or lists of those types indicating
columns to sort the DataFrame by.
Kwargs:
**kwargs: Any keyword arguments will be passed through to the pandas
`DataFrame.sort_values` function. | [
"Calls",
"pandas",
".",
"DataFrame",
".",
"sort_values",
"to",
"sort",
"a",
"DataFrame",
"according",
"to",
"criteria",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L10-L37 |
222,996 | kieferk/dfply | dfply/reshape.py | rename | def rename(df, **kwargs):
"""Renames columns, where keyword argument values are the current names
of columns and keys are the new names.
Args:
df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe.
Kwargs:
**kwargs: key:value pairs where keys are new names for columns and
values are current names of columns.
"""
return df.rename(columns={v: k for k, v in kwargs.items()}) | python | def rename(df, **kwargs):
"""Renames columns, where keyword argument values are the current names
of columns and keys are the new names.
Args:
df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe.
Kwargs:
**kwargs: key:value pairs where keys are new names for columns and
values are current names of columns.
"""
return df.rename(columns={v: k for k, v in kwargs.items()}) | [
"def",
"rename",
"(",
"df",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"df",
".",
"rename",
"(",
"columns",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"}",
")"
] | Renames columns, where keyword argument values are the current names
of columns and keys are the new names.
Args:
df (:obj:`pandas.DataFrame`): DataFrame passed in via `>>` pipe.
Kwargs:
**kwargs: key:value pairs where keys are new names for columns and
values are current names of columns. | [
"Renames",
"columns",
"where",
"keyword",
"argument",
"values",
"are",
"the",
"current",
"names",
"of",
"columns",
"and",
"keys",
"are",
"the",
"new",
"names",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L46-L58 |
222,997 | kieferk/dfply | dfply/reshape.py | convert_type | def convert_type(df, columns):
"""
Helper function that attempts to convert columns into their appropriate
data type.
"""
# taken in part from the dplython package
out_df = df.copy()
for col in columns:
column_values = pd.Series(out_df[col].unique())
column_values = column_values[~column_values.isnull()]
# empty
if len(column_values) == 0:
continue
# boolean
if set(column_values.values) < {'True', 'False'}:
out_df[col] = out_df[col].map({'True': True, 'False': False})
continue
# numeric
if pd.to_numeric(column_values, errors='coerce').isnull().sum() == 0:
out_df[col] = pd.to_numeric(out_df[col], errors='ignore')
continue
# datetime
if pd.to_datetime(column_values, errors='coerce').isnull().sum() == 0:
out_df[col] = pd.to_datetime(out_df[col], errors='ignore',
infer_datetime_format=True)
continue
return out_df | python | def convert_type(df, columns):
"""
Helper function that attempts to convert columns into their appropriate
data type.
"""
# taken in part from the dplython package
out_df = df.copy()
for col in columns:
column_values = pd.Series(out_df[col].unique())
column_values = column_values[~column_values.isnull()]
# empty
if len(column_values) == 0:
continue
# boolean
if set(column_values.values) < {'True', 'False'}:
out_df[col] = out_df[col].map({'True': True, 'False': False})
continue
# numeric
if pd.to_numeric(column_values, errors='coerce').isnull().sum() == 0:
out_df[col] = pd.to_numeric(out_df[col], errors='ignore')
continue
# datetime
if pd.to_datetime(column_values, errors='coerce').isnull().sum() == 0:
out_df[col] = pd.to_datetime(out_df[col], errors='ignore',
infer_datetime_format=True)
continue
return out_df | [
"def",
"convert_type",
"(",
"df",
",",
"columns",
")",
":",
"# taken in part from the dplython package",
"out_df",
"=",
"df",
".",
"copy",
"(",
")",
"for",
"col",
"in",
"columns",
":",
"column_values",
"=",
"pd",
".",
"Series",
"(",
"out_df",
"[",
"col",
"... | Helper function that attempts to convert columns into their appropriate
data type. | [
"Helper",
"function",
"that",
"attempts",
"to",
"convert",
"columns",
"into",
"their",
"appropriate",
"data",
"type",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L111-L138 |
222,998 | kieferk/dfply | dfply/reshape.py | spread | def spread(df, key, values, convert=False):
"""
Transforms a "long" DataFrame into a "wide" format using a key and value
column.
If you have a mixed datatype column in your long-format DataFrame then the
default behavior is for the spread columns to be of type `object`, or
string. If you want to try to convert dtypes when spreading, you can set
the convert keyword argument in spread to True.
Args:
key (str, int, or symbolic): Label for the key column.
values (str, int, or symbolic): Label for the values column.
Kwargs:
convert (bool): Boolean indicating whether or not to try and convert
the spread columns to more appropriate data types.
Example:
widened = elongated >> spread(X.variable, X.value)
widened >> head(5)
_ID carat clarity color cut depth price table x y z
0 0 0.23 SI2 E Ideal 61.5 326 55 3.95 3.98 2.43
1 1 0.21 SI1 E Premium 59.8 326 61 3.89 3.84 2.31
2 10 0.3 SI1 J Good 64 339 55 4.25 4.28 2.73
3 100 0.75 SI1 D Very Good 63.2 2760 56 5.8 5.75 3.65
4 1000 0.75 SI1 D Ideal 62.3 2898 55 5.83 5.8 3.62
"""
# Taken mostly from dplython package
columns = df.columns.tolist()
id_cols = [col for col in columns if not col in [key, values]]
temp_index = ['' for i in range(len(df))]
for id_col in id_cols:
temp_index += df[id_col].map(str)
out_df = df.assign(temp_index=temp_index)
out_df = out_df.set_index('temp_index')
spread_data = out_df[[key, values]]
if not all(spread_data.groupby([spread_data.index, key]).agg(
'count').reset_index()[values] < 2):
raise ValueError('Duplicate identifiers')
spread_data = spread_data.pivot(columns=key, values=values)
if convert and (out_df[values].dtype.kind in 'OSaU'):
columns_to_convert = [col for col in spread_data if col not in columns]
spread_data = convert_type(spread_data, columns_to_convert)
out_df = out_df[id_cols].drop_duplicates()
out_df = out_df.merge(spread_data, left_index=True, right_index=True).reset_index(drop=True)
out_df = (out_df >> arrange(id_cols)).reset_index(drop=True)
return out_df | python | def spread(df, key, values, convert=False):
"""
Transforms a "long" DataFrame into a "wide" format using a key and value
column.
If you have a mixed datatype column in your long-format DataFrame then the
default behavior is for the spread columns to be of type `object`, or
string. If you want to try to convert dtypes when spreading, you can set
the convert keyword argument in spread to True.
Args:
key (str, int, or symbolic): Label for the key column.
values (str, int, or symbolic): Label for the values column.
Kwargs:
convert (bool): Boolean indicating whether or not to try and convert
the spread columns to more appropriate data types.
Example:
widened = elongated >> spread(X.variable, X.value)
widened >> head(5)
_ID carat clarity color cut depth price table x y z
0 0 0.23 SI2 E Ideal 61.5 326 55 3.95 3.98 2.43
1 1 0.21 SI1 E Premium 59.8 326 61 3.89 3.84 2.31
2 10 0.3 SI1 J Good 64 339 55 4.25 4.28 2.73
3 100 0.75 SI1 D Very Good 63.2 2760 56 5.8 5.75 3.65
4 1000 0.75 SI1 D Ideal 62.3 2898 55 5.83 5.8 3.62
"""
# Taken mostly from dplython package
columns = df.columns.tolist()
id_cols = [col for col in columns if not col in [key, values]]
temp_index = ['' for i in range(len(df))]
for id_col in id_cols:
temp_index += df[id_col].map(str)
out_df = df.assign(temp_index=temp_index)
out_df = out_df.set_index('temp_index')
spread_data = out_df[[key, values]]
if not all(spread_data.groupby([spread_data.index, key]).agg(
'count').reset_index()[values] < 2):
raise ValueError('Duplicate identifiers')
spread_data = spread_data.pivot(columns=key, values=values)
if convert and (out_df[values].dtype.kind in 'OSaU'):
columns_to_convert = [col for col in spread_data if col not in columns]
spread_data = convert_type(spread_data, columns_to_convert)
out_df = out_df[id_cols].drop_duplicates()
out_df = out_df.merge(spread_data, left_index=True, right_index=True).reset_index(drop=True)
out_df = (out_df >> arrange(id_cols)).reset_index(drop=True)
return out_df | [
"def",
"spread",
"(",
"df",
",",
"key",
",",
"values",
",",
"convert",
"=",
"False",
")",
":",
"# Taken mostly from dplython package",
"columns",
"=",
"df",
".",
"columns",
".",
"tolist",
"(",
")",
"id_cols",
"=",
"[",
"col",
"for",
"col",
"in",
"columns... | Transforms a "long" DataFrame into a "wide" format using a key and value
column.
If you have a mixed datatype column in your long-format DataFrame then the
default behavior is for the spread columns to be of type `object`, or
string. If you want to try to convert dtypes when spreading, you can set
the convert keyword argument in spread to True.
Args:
key (str, int, or symbolic): Label for the key column.
values (str, int, or symbolic): Label for the values column.
Kwargs:
convert (bool): Boolean indicating whether or not to try and convert
the spread columns to more appropriate data types.
Example:
widened = elongated >> spread(X.variable, X.value)
widened >> head(5)
_ID carat clarity color cut depth price table x y z
0 0 0.23 SI2 E Ideal 61.5 326 55 3.95 3.98 2.43
1 1 0.21 SI1 E Premium 59.8 326 61 3.89 3.84 2.31
2 10 0.3 SI1 J Good 64 339 55 4.25 4.28 2.73
3 100 0.75 SI1 D Very Good 63.2 2760 56 5.8 5.75 3.65
4 1000 0.75 SI1 D Ideal 62.3 2898 55 5.83 5.8 3.62 | [
"Transforms",
"a",
"long",
"DataFrame",
"into",
"a",
"wide",
"format",
"using",
"a",
"key",
"and",
"value",
"column",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L143-L201 |
222,999 | kieferk/dfply | dfply/reshape.py | separate | def separate(df, column, into, sep="[\W_]+", remove=True, convert=False,
extra='drop', fill='right'):
"""
Splits columns into multiple columns.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
column (str, symbolic): Label of column to split.
into (list): List of string names for new columns.
Kwargs:
sep (str or list): If a string, the regex string used to split the
column. If a list, a list of integer positions to split strings
on.
remove (bool): Boolean indicating whether to remove the original column.
convert (bool): Boolean indicating whether the new columns should be
converted to the appropriate type.
extra (str): either `'drop'`, where split pieces beyond the specified
new columns are dropped, or `'merge'`, where the final split piece
contains the remainder of the original column.
fill (str): either `'right'`, where `np.nan` values are filled in the
right-most columns for missing pieces, or `'left'` where `np.nan`
values are filled in the left-most columns.
"""
assert isinstance(into, (tuple, list))
if isinstance(sep, (tuple, list)):
inds = [0] + list(sep)
if len(inds) > len(into):
if extra == 'drop':
inds = inds[:len(into) + 1]
elif extra == 'merge':
inds = inds[:len(into)] + [None]
else:
inds = inds + [None]
splits = df[column].map(lambda x: [str(x)[slice(inds[i], inds[i + 1])]
if i < len(inds) - 1 else np.nan
for i in range(len(into))])
else:
maxsplit = len(into) - 1 if extra == 'merge' else 0
splits = df[column].map(lambda x: re.split(sep, x, maxsplit))
right_filler = lambda x: x + [np.nan for i in range(len(into) - len(x))]
left_filler = lambda x: [np.nan for i in range(len(into) - len(x))] + x
if fill == 'right':
splits = [right_filler(x) for x in splits]
elif fill == 'left':
splits = [left_filler(x) for x in splits]
for i, split_col in enumerate(into):
df[split_col] = [x[i] if not x[i] == '' else np.nan for x in splits]
if convert:
df = convert_type(df, into)
if remove:
df.drop(column, axis=1, inplace=True)
return df | python | def separate(df, column, into, sep="[\W_]+", remove=True, convert=False,
extra='drop', fill='right'):
"""
Splits columns into multiple columns.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
column (str, symbolic): Label of column to split.
into (list): List of string names for new columns.
Kwargs:
sep (str or list): If a string, the regex string used to split the
column. If a list, a list of integer positions to split strings
on.
remove (bool): Boolean indicating whether to remove the original column.
convert (bool): Boolean indicating whether the new columns should be
converted to the appropriate type.
extra (str): either `'drop'`, where split pieces beyond the specified
new columns are dropped, or `'merge'`, where the final split piece
contains the remainder of the original column.
fill (str): either `'right'`, where `np.nan` values are filled in the
right-most columns for missing pieces, or `'left'` where `np.nan`
values are filled in the left-most columns.
"""
assert isinstance(into, (tuple, list))
if isinstance(sep, (tuple, list)):
inds = [0] + list(sep)
if len(inds) > len(into):
if extra == 'drop':
inds = inds[:len(into) + 1]
elif extra == 'merge':
inds = inds[:len(into)] + [None]
else:
inds = inds + [None]
splits = df[column].map(lambda x: [str(x)[slice(inds[i], inds[i + 1])]
if i < len(inds) - 1 else np.nan
for i in range(len(into))])
else:
maxsplit = len(into) - 1 if extra == 'merge' else 0
splits = df[column].map(lambda x: re.split(sep, x, maxsplit))
right_filler = lambda x: x + [np.nan for i in range(len(into) - len(x))]
left_filler = lambda x: [np.nan for i in range(len(into) - len(x))] + x
if fill == 'right':
splits = [right_filler(x) for x in splits]
elif fill == 'left':
splits = [left_filler(x) for x in splits]
for i, split_col in enumerate(into):
df[split_col] = [x[i] if not x[i] == '' else np.nan for x in splits]
if convert:
df = convert_type(df, into)
if remove:
df.drop(column, axis=1, inplace=True)
return df | [
"def",
"separate",
"(",
"df",
",",
"column",
",",
"into",
",",
"sep",
"=",
"\"[\\W_]+\"",
",",
"remove",
"=",
"True",
",",
"convert",
"=",
"False",
",",
"extra",
"=",
"'drop'",
",",
"fill",
"=",
"'right'",
")",
":",
"assert",
"isinstance",
"(",
"into... | Splits columns into multiple columns.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
column (str, symbolic): Label of column to split.
into (list): List of string names for new columns.
Kwargs:
sep (str or list): If a string, the regex string used to split the
column. If a list, a list of integer positions to split strings
on.
remove (bool): Boolean indicating whether to remove the original column.
convert (bool): Boolean indicating whether the new columns should be
converted to the appropriate type.
extra (str): either `'drop'`, where split pieces beyond the specified
new columns are dropped, or `'merge'`, where the final split piece
contains the remainder of the original column.
fill (str): either `'right'`, where `np.nan` values are filled in the
right-most columns for missing pieces, or `'left'` where `np.nan`
values are filled in the left-most columns. | [
"Splits",
"columns",
"into",
"multiple",
"columns",
"."
] | 6a858f066602735a90f8b6b85106bc39ceadc282 | https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/reshape.py#L210-L272 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.