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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
dddomodossola/remi | examples/svgplot_app.py | SvgComposedPoly.add_coord | def add_coord(self, x, y):
""" Adds a coord to the polyline and creates another circle
"""
x = x*self.x_factor
y = y*self.y_factor
self.plotData.add_coord(x, y)
self.circles_list.append(gui.SvgCircle(x, y, self.circle_radius))
self.append(self.circles_list[-1])
if len(self.circles_list) > self.maxlen:
self.remove_child(self.circles_list[0])
del self.circles_list[0] | python | def add_coord(self, x, y):
""" Adds a coord to the polyline and creates another circle
"""
x = x*self.x_factor
y = y*self.y_factor
self.plotData.add_coord(x, y)
self.circles_list.append(gui.SvgCircle(x, y, self.circle_radius))
self.append(self.circles_list[-1])
if len(self.circles_list) > self.maxlen:
self.remove_child(self.circles_list[0])
del self.circles_list[0] | [
"def",
"add_coord",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"x",
"=",
"x",
"*",
"self",
".",
"x_factor",
"y",
"=",
"y",
"*",
"self",
".",
"y_factor",
"self",
".",
"plotData",
".",
"add_coord",
"(",
"x",
",",
"y",
")",
"self",
".",
"circles_l... | Adds a coord to the polyline and creates another circle | [
"Adds",
"a",
"coord",
"to",
"the",
"polyline",
"and",
"creates",
"another",
"circle"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/svgplot_app.py#L39-L49 | train | 214,300 |
dddomodossola/remi | examples/examples_from_contributors/Display_TreeTable.py | MyApp.My_TreeTable | def My_TreeTable(self, table, heads, heads2=None):
''' Define and display a table
in which the values in first column form one or more trees.
'''
self.Define_TreeTable(heads, heads2)
self.Display_TreeTable(table) | python | def My_TreeTable(self, table, heads, heads2=None):
''' Define and display a table
in which the values in first column form one or more trees.
'''
self.Define_TreeTable(heads, heads2)
self.Display_TreeTable(table) | [
"def",
"My_TreeTable",
"(",
"self",
",",
"table",
",",
"heads",
",",
"heads2",
"=",
"None",
")",
":",
"self",
".",
"Define_TreeTable",
"(",
"heads",
",",
"heads2",
")",
"self",
".",
"Display_TreeTable",
"(",
"table",
")"
] | Define and display a table
in which the values in first column form one or more trees. | [
"Define",
"and",
"display",
"a",
"table",
"in",
"which",
"the",
"values",
"in",
"first",
"column",
"form",
"one",
"or",
"more",
"trees",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/examples_from_contributors/Display_TreeTable.py#L26-L31 | train | 214,301 |
dddomodossola/remi | examples/examples_from_contributors/Display_TreeTable.py | MyApp.Define_TreeTable | def Define_TreeTable(self, heads, heads2=None):
''' Define a TreeTable with a heading row
and optionally a second heading row.
'''
display_heads = []
display_heads.append(tuple(heads[2:]))
self.tree_table = TreeTable()
self.tree_table.append_from_list(display_heads, fill_title=True)
if heads2 is not None:
heads2_color = heads2[1]
row_widget = gui.TableRow()
for index, field in enumerate(heads2[2:]):
row_item = gui.TableItem(text=field,
style={'background-color': heads2_color})
row_widget.append(row_item, field)
self.tree_table.append(row_widget, heads2[0])
self.wid.append(self.tree_table) | python | def Define_TreeTable(self, heads, heads2=None):
''' Define a TreeTable with a heading row
and optionally a second heading row.
'''
display_heads = []
display_heads.append(tuple(heads[2:]))
self.tree_table = TreeTable()
self.tree_table.append_from_list(display_heads, fill_title=True)
if heads2 is not None:
heads2_color = heads2[1]
row_widget = gui.TableRow()
for index, field in enumerate(heads2[2:]):
row_item = gui.TableItem(text=field,
style={'background-color': heads2_color})
row_widget.append(row_item, field)
self.tree_table.append(row_widget, heads2[0])
self.wid.append(self.tree_table) | [
"def",
"Define_TreeTable",
"(",
"self",
",",
"heads",
",",
"heads2",
"=",
"None",
")",
":",
"display_heads",
"=",
"[",
"]",
"display_heads",
".",
"append",
"(",
"tuple",
"(",
"heads",
"[",
"2",
":",
"]",
")",
")",
"self",
".",
"tree_table",
"=",
"Tre... | Define a TreeTable with a heading row
and optionally a second heading row. | [
"Define",
"a",
"TreeTable",
"with",
"a",
"heading",
"row",
"and",
"optionally",
"a",
"second",
"heading",
"row",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/examples_from_contributors/Display_TreeTable.py#L33-L49 | train | 214,302 |
dddomodossola/remi | examples/gauge_app.py | InputGauge.confirm_value | def confirm_value(self, widget, x, y):
"""event called clicking on the gauge and so changing its value.
propagates the new value
"""
self.gauge.onmousedown(self.gauge, x, y)
params = (self.gauge.value)
return params | python | def confirm_value(self, widget, x, y):
"""event called clicking on the gauge and so changing its value.
propagates the new value
"""
self.gauge.onmousedown(self.gauge, x, y)
params = (self.gauge.value)
return params | [
"def",
"confirm_value",
"(",
"self",
",",
"widget",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"gauge",
".",
"onmousedown",
"(",
"self",
".",
"gauge",
",",
"x",
",",
"y",
")",
"params",
"=",
"(",
"self",
".",
"gauge",
".",
"value",
")",
"return",... | event called clicking on the gauge and so changing its value.
propagates the new value | [
"event",
"called",
"clicking",
"on",
"the",
"gauge",
"and",
"so",
"changing",
"its",
"value",
".",
"propagates",
"the",
"new",
"value"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/gauge_app.py#L40-L46 | train | 214,303 |
dddomodossola/remi | editor/editor.py | Editor.configure_widget_for_editing | def configure_widget_for_editing(self, widget):
""" A widget have to be added to the editor, it is configured here in order to be conformant
to the editor
"""
if not 'editor_varname' in widget.attributes:
return
widget.onclick.do(self.on_widget_selection)
#setup of the on_dropped function of the widget in order to manage the dragNdrop
widget.__class__.on_dropped = on_dropped
#drag properties
#widget.style['resize'] = 'both'
widget.style['overflow'] = 'auto'
widget.attributes['draggable'] = 'true'
widget.attributes['tabindex']=str(self.tabindex)
#if not 'position' in widget.style.keys():
# widget.style['position'] = 'absolute'
#if not 'left' in widget.style.keys():
# widget.style['left'] = '1px'
#if not 'top' in widget.style.keys():
# widget.style['top'] = '1px'
self.tabindex += 1 | python | def configure_widget_for_editing(self, widget):
""" A widget have to be added to the editor, it is configured here in order to be conformant
to the editor
"""
if not 'editor_varname' in widget.attributes:
return
widget.onclick.do(self.on_widget_selection)
#setup of the on_dropped function of the widget in order to manage the dragNdrop
widget.__class__.on_dropped = on_dropped
#drag properties
#widget.style['resize'] = 'both'
widget.style['overflow'] = 'auto'
widget.attributes['draggable'] = 'true'
widget.attributes['tabindex']=str(self.tabindex)
#if not 'position' in widget.style.keys():
# widget.style['position'] = 'absolute'
#if not 'left' in widget.style.keys():
# widget.style['left'] = '1px'
#if not 'top' in widget.style.keys():
# widget.style['top'] = '1px'
self.tabindex += 1 | [
"def",
"configure_widget_for_editing",
"(",
"self",
",",
"widget",
")",
":",
"if",
"not",
"'editor_varname'",
"in",
"widget",
".",
"attributes",
":",
"return",
"widget",
".",
"onclick",
".",
"do",
"(",
"self",
".",
"on_widget_selection",
")",
"#setup of the on_d... | A widget have to be added to the editor, it is configured here in order to be conformant
to the editor | [
"A",
"widget",
"have",
"to",
"be",
"added",
"to",
"the",
"editor",
"it",
"is",
"configured",
"here",
"in",
"order",
"to",
"be",
"conformant",
"to",
"the",
"editor"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/editor/editor.py#L656-L680 | train | 214,304 |
dddomodossola/remi | examples/minefield_app.py | Cell.on_right_click | def on_right_click(self, widget):
""" Here with right click the change of cell is changed """
if self.opened:
return
self.state = (self.state + 1) % 3
self.set_icon()
self.game.check_if_win() | python | def on_right_click(self, widget):
""" Here with right click the change of cell is changed """
if self.opened:
return
self.state = (self.state + 1) % 3
self.set_icon()
self.game.check_if_win() | [
"def",
"on_right_click",
"(",
"self",
",",
"widget",
")",
":",
"if",
"self",
".",
"opened",
":",
"return",
"self",
".",
"state",
"=",
"(",
"self",
".",
"state",
"+",
"1",
")",
"%",
"3",
"self",
".",
"set_icon",
"(",
")",
"self",
".",
"game",
".",... | Here with right click the change of cell is changed | [
"Here",
"with",
"right",
"click",
"the",
"change",
"of",
"cell",
"is",
"changed"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/minefield_app.py#L49-L55 | train | 214,305 |
dddomodossola/remi | examples/minefield_app.py | MyApp.build_mine_matrix | def build_mine_matrix(self, w, h, minenum):
"""random fill cells with mines and increments nearest mines num in adiacent cells"""
self.minecount = 0
matrix = [[Cell(30, 30, x, y, self) for x in range(w)] for y in range(h)]
for i in range(0, minenum):
x = random.randint(0, w - 1)
y = random.randint(0, h - 1)
if matrix[y][x].has_mine:
continue
self.minecount += 1
matrix[y][x].has_mine = True
for coord in [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]:
_x, _y = coord
if not self.coord_in_map(x + _x, y + _y, w, h):
continue
matrix[y + _y][x + _x].add_nearest_mine()
return matrix | python | def build_mine_matrix(self, w, h, minenum):
"""random fill cells with mines and increments nearest mines num in adiacent cells"""
self.minecount = 0
matrix = [[Cell(30, 30, x, y, self) for x in range(w)] for y in range(h)]
for i in range(0, minenum):
x = random.randint(0, w - 1)
y = random.randint(0, h - 1)
if matrix[y][x].has_mine:
continue
self.minecount += 1
matrix[y][x].has_mine = True
for coord in [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]:
_x, _y = coord
if not self.coord_in_map(x + _x, y + _y, w, h):
continue
matrix[y + _y][x + _x].add_nearest_mine()
return matrix | [
"def",
"build_mine_matrix",
"(",
"self",
",",
"w",
",",
"h",
",",
"minenum",
")",
":",
"self",
".",
"minecount",
"=",
"0",
"matrix",
"=",
"[",
"[",
"Cell",
"(",
"30",
",",
"30",
",",
"x",
",",
"y",
",",
"self",
")",
"for",
"x",
"in",
"range",
... | random fill cells with mines and increments nearest mines num in adiacent cells | [
"random",
"fill",
"cells",
"with",
"mines",
"and",
"increments",
"nearest",
"mines",
"num",
"in",
"adiacent",
"cells"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/minefield_app.py#L184-L201 | train | 214,306 |
dddomodossola/remi | examples/minefield_app.py | MyApp.check_if_win | def check_if_win(self):
"""Here are counted the flags. Is checked if the user win."""
self.flagcount = 0
win = True
for x in range(0, len(self.mine_matrix[0])):
for y in range(0, len(self.mine_matrix)):
if self.mine_matrix[y][x].state == 1:
self.flagcount += 1
if not self.mine_matrix[y][x].has_mine:
win = False
elif self.mine_matrix[y][x].has_mine:
win = False
self.lblMineCount.set_text("%s" % self.minecount)
self.lblFlagCount.set_text("%s" % self.flagcount)
if win:
self.dialog = gui.GenericDialog(title='You Win!', message='Game done in %s seconds' % self.time_count)
self.dialog.confirm_dialog.do(self.new_game)
self.dialog.cancel_dialog.do(self.new_game)
self.dialog.show(self) | python | def check_if_win(self):
"""Here are counted the flags. Is checked if the user win."""
self.flagcount = 0
win = True
for x in range(0, len(self.mine_matrix[0])):
for y in range(0, len(self.mine_matrix)):
if self.mine_matrix[y][x].state == 1:
self.flagcount += 1
if not self.mine_matrix[y][x].has_mine:
win = False
elif self.mine_matrix[y][x].has_mine:
win = False
self.lblMineCount.set_text("%s" % self.minecount)
self.lblFlagCount.set_text("%s" % self.flagcount)
if win:
self.dialog = gui.GenericDialog(title='You Win!', message='Game done in %s seconds' % self.time_count)
self.dialog.confirm_dialog.do(self.new_game)
self.dialog.cancel_dialog.do(self.new_game)
self.dialog.show(self) | [
"def",
"check_if_win",
"(",
"self",
")",
":",
"self",
".",
"flagcount",
"=",
"0",
"win",
"=",
"True",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"mine_matrix",
"[",
"0",
"]",
")",
")",
":",
"for",
"y",
"in",
"range",
"("... | Here are counted the flags. Is checked if the user win. | [
"Here",
"are",
"counted",
"the",
"flags",
".",
"Is",
"checked",
"if",
"the",
"user",
"win",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/minefield_app.py#L209-L227 | train | 214,307 |
dddomodossola/remi | examples/session_app.py | LoginManager.renew_session | def renew_session(self):
"""Have to be called on user actions to check and renew session
"""
if ((not 'user_uid' in self.cookieInterface.cookies) or self.cookieInterface.cookies['user_uid']!=self.session_uid) and (not self.expired):
self.on_session_expired()
if self.expired:
self.session_uid = str(random.randint(1,999999999))
self.cookieInterface.set_cookie('user_uid', self.session_uid, str(self.session_timeout_seconds))
#here we renew the internal timeout timer
if self.timeout_timer:
self.timeout_timer.cancel()
self.timeout_timer = threading.Timer(self.session_timeout_seconds, self.on_session_expired)
self.expired = False
self.timeout_timer.start() | python | def renew_session(self):
"""Have to be called on user actions to check and renew session
"""
if ((not 'user_uid' in self.cookieInterface.cookies) or self.cookieInterface.cookies['user_uid']!=self.session_uid) and (not self.expired):
self.on_session_expired()
if self.expired:
self.session_uid = str(random.randint(1,999999999))
self.cookieInterface.set_cookie('user_uid', self.session_uid, str(self.session_timeout_seconds))
#here we renew the internal timeout timer
if self.timeout_timer:
self.timeout_timer.cancel()
self.timeout_timer = threading.Timer(self.session_timeout_seconds, self.on_session_expired)
self.expired = False
self.timeout_timer.start() | [
"def",
"renew_session",
"(",
"self",
")",
":",
"if",
"(",
"(",
"not",
"'user_uid'",
"in",
"self",
".",
"cookieInterface",
".",
"cookies",
")",
"or",
"self",
".",
"cookieInterface",
".",
"cookies",
"[",
"'user_uid'",
"]",
"!=",
"self",
".",
"session_uid",
... | Have to be called on user actions to check and renew session | [
"Have",
"to",
"be",
"called",
"on",
"user",
"actions",
"to",
"check",
"and",
"renew",
"session"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/session_app.py#L146-L162 | train | 214,308 |
dddomodossola/remi | remi/gui.py | decorate_event_js | def decorate_event_js(js_code):
"""setup a method as an event, adding also javascript code to generate
Args:
js_code (str): javascript code to generate the event client-side.
js_code is added to the widget html as
widget.attributes['onclick'] = js_code%{'emitter_identifier':widget.identifier, 'event_name':'onclick'}
"""
def add_annotation(method):
setattr(method, "__is_event", True )
setattr(method, "_js_code", js_code )
return method
return add_annotation | python | def decorate_event_js(js_code):
"""setup a method as an event, adding also javascript code to generate
Args:
js_code (str): javascript code to generate the event client-side.
js_code is added to the widget html as
widget.attributes['onclick'] = js_code%{'emitter_identifier':widget.identifier, 'event_name':'onclick'}
"""
def add_annotation(method):
setattr(method, "__is_event", True )
setattr(method, "_js_code", js_code )
return method
return add_annotation | [
"def",
"decorate_event_js",
"(",
"js_code",
")",
":",
"def",
"add_annotation",
"(",
"method",
")",
":",
"setattr",
"(",
"method",
",",
"\"__is_event\"",
",",
"True",
")",
"setattr",
"(",
"method",
",",
"\"_js_code\"",
",",
"js_code",
")",
"return",
"method",... | setup a method as an event, adding also javascript code to generate
Args:
js_code (str): javascript code to generate the event client-side.
js_code is added to the widget html as
widget.attributes['onclick'] = js_code%{'emitter_identifier':widget.identifier, 'event_name':'onclick'} | [
"setup",
"a",
"method",
"as",
"an",
"event",
"adding",
"also",
"javascript",
"code",
"to",
"generate"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L128-L140 | train | 214,309 |
dddomodossola/remi | remi/gui.py | decorate_set_on_listener | def decorate_set_on_listener(prototype):
""" Private decorator for use in the editor.
Allows the Editor to create listener methods.
Args:
params (str): The list of parameters for the listener
method (es. "(self, new_value)")
"""
# noinspection PyDictCreation,PyProtectedMember
def add_annotation(method):
method._event_info = {}
method._event_info['name'] = method.__name__
method._event_info['prototype'] = prototype
return method
return add_annotation | python | def decorate_set_on_listener(prototype):
""" Private decorator for use in the editor.
Allows the Editor to create listener methods.
Args:
params (str): The list of parameters for the listener
method (es. "(self, new_value)")
"""
# noinspection PyDictCreation,PyProtectedMember
def add_annotation(method):
method._event_info = {}
method._event_info['name'] = method.__name__
method._event_info['prototype'] = prototype
return method
return add_annotation | [
"def",
"decorate_set_on_listener",
"(",
"prototype",
")",
":",
"# noinspection PyDictCreation,PyProtectedMember",
"def",
"add_annotation",
"(",
"method",
")",
":",
"method",
".",
"_event_info",
"=",
"{",
"}",
"method",
".",
"_event_info",
"[",
"'name'",
"]",
"=",
... | Private decorator for use in the editor.
Allows the Editor to create listener methods.
Args:
params (str): The list of parameters for the listener
method (es. "(self, new_value)") | [
"Private",
"decorator",
"for",
"use",
"in",
"the",
"editor",
".",
"Allows",
"the",
"Editor",
"to",
"create",
"listener",
"methods",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L143-L158 | train | 214,310 |
dddomodossola/remi | remi/gui.py | ClassEventConnector.do | def do(self, callback, *userdata):
""" The callback and userdata gets stored, and if there is some javascript to add
the js code is appended as attribute for the event source
"""
if hasattr(self.event_method_bound, '_js_code'):
self.event_source_instance.attributes[self.event_name] = self.event_method_bound._js_code%{
'emitter_identifier':self.event_source_instance.identifier, 'event_name':self.event_name}
self.callback = callback
self.userdata = userdata | python | def do(self, callback, *userdata):
""" The callback and userdata gets stored, and if there is some javascript to add
the js code is appended as attribute for the event source
"""
if hasattr(self.event_method_bound, '_js_code'):
self.event_source_instance.attributes[self.event_name] = self.event_method_bound._js_code%{
'emitter_identifier':self.event_source_instance.identifier, 'event_name':self.event_name}
self.callback = callback
self.userdata = userdata | [
"def",
"do",
"(",
"self",
",",
"callback",
",",
"*",
"userdata",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"event_method_bound",
",",
"'_js_code'",
")",
":",
"self",
".",
"event_source_instance",
".",
"attributes",
"[",
"self",
".",
"event_name",
"]",
... | The callback and userdata gets stored, and if there is some javascript to add
the js code is appended as attribute for the event source | [
"The",
"callback",
"and",
"userdata",
"gets",
"stored",
"and",
"if",
"there",
"is",
"some",
"javascript",
"to",
"add",
"the",
"js",
"code",
"is",
"appended",
"as",
"attribute",
"for",
"the",
"event",
"source"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L98-L106 | train | 214,311 |
dddomodossola/remi | remi/gui.py | Tag.add_child | def add_child(self, key, value):
"""Adds a child to the Tag
To retrieve the child call get_child or access to the Tag.children[key] dictionary.
Args:
key (str): Unique child's identifier, or iterable of keys
value (Tag, str): can be a Tag, an iterable of Tag or a str. In case of iterable
of Tag is a dict, each item's key is set as 'key' param
"""
if type(value) in (list, tuple, dict):
if type(value)==dict:
for k in value.keys():
self.add_child(k, value[k])
return
i = 0
for child in value:
self.add_child(key[i], child)
i = i + 1
return
if hasattr(value, 'attributes'):
value.attributes['data-parent-widget'] = self.identifier
value._parent = self
if key in self.children:
self._render_children_list.remove(key)
self._render_children_list.append(key)
self.children[key] = value | python | def add_child(self, key, value):
"""Adds a child to the Tag
To retrieve the child call get_child or access to the Tag.children[key] dictionary.
Args:
key (str): Unique child's identifier, or iterable of keys
value (Tag, str): can be a Tag, an iterable of Tag or a str. In case of iterable
of Tag is a dict, each item's key is set as 'key' param
"""
if type(value) in (list, tuple, dict):
if type(value)==dict:
for k in value.keys():
self.add_child(k, value[k])
return
i = 0
for child in value:
self.add_child(key[i], child)
i = i + 1
return
if hasattr(value, 'attributes'):
value.attributes['data-parent-widget'] = self.identifier
value._parent = self
if key in self.children:
self._render_children_list.remove(key)
self._render_children_list.append(key)
self.children[key] = value | [
"def",
"add_child",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"in",
"(",
"list",
",",
"tuple",
",",
"dict",
")",
":",
"if",
"type",
"(",
"value",
")",
"==",
"dict",
":",
"for",
"k",
"in",
"value",
".",
... | Adds a child to the Tag
To retrieve the child call get_child or access to the Tag.children[key] dictionary.
Args:
key (str): Unique child's identifier, or iterable of keys
value (Tag, str): can be a Tag, an iterable of Tag or a str. In case of iterable
of Tag is a dict, each item's key is set as 'key' param | [
"Adds",
"a",
"child",
"to",
"the",
"Tag"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L380-L409 | train | 214,312 |
dddomodossola/remi | remi/gui.py | Tag.empty | def empty(self):
"""remove all children from the widget"""
for k in list(self.children.keys()):
self.remove_child(self.children[k]) | python | def empty(self):
"""remove all children from the widget"""
for k in list(self.children.keys()):
self.remove_child(self.children[k]) | [
"def",
"empty",
"(",
"self",
")",
":",
"for",
"k",
"in",
"list",
"(",
"self",
".",
"children",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"remove_child",
"(",
"self",
".",
"children",
"[",
"k",
"]",
")"
] | remove all children from the widget | [
"remove",
"all",
"children",
"from",
"the",
"widget"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L425-L428 | train | 214,313 |
dddomodossola/remi | remi/gui.py | Tag.remove_child | def remove_child(self, child):
"""Removes a child instance from the Tag's children.
Args:
child (Tag): The child to be removed.
"""
if child in self.children.values() and hasattr(child, 'identifier'):
for k in self.children.keys():
if hasattr(self.children[k], 'identifier'):
if self.children[k].identifier == child.identifier:
if k in self._render_children_list:
self._render_children_list.remove(k)
self.children.pop(k)
# when the child is removed we stop the iteration
# this implies that a child replication should not be allowed
break | python | def remove_child(self, child):
"""Removes a child instance from the Tag's children.
Args:
child (Tag): The child to be removed.
"""
if child in self.children.values() and hasattr(child, 'identifier'):
for k in self.children.keys():
if hasattr(self.children[k], 'identifier'):
if self.children[k].identifier == child.identifier:
if k in self._render_children_list:
self._render_children_list.remove(k)
self.children.pop(k)
# when the child is removed we stop the iteration
# this implies that a child replication should not be allowed
break | [
"def",
"remove_child",
"(",
"self",
",",
"child",
")",
":",
"if",
"child",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
"and",
"hasattr",
"(",
"child",
",",
"'identifier'",
")",
":",
"for",
"k",
"in",
"self",
".",
"children",
".",
"keys",
... | Removes a child instance from the Tag's children.
Args:
child (Tag): The child to be removed. | [
"Removes",
"a",
"child",
"instance",
"from",
"the",
"Tag",
"s",
"children",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L430-L445 | train | 214,314 |
dddomodossola/remi | remi/gui.py | Widget.set_size | def set_size(self, width, height):
"""Set the widget size.
Args:
width (int or str): An optional width for the widget (es. width=10 or width='10px' or width='10%').
height (int or str): An optional height for the widget (es. height=10 or height='10px' or height='10%').
"""
if width is not None:
try:
width = to_pix(int(width))
except ValueError:
# now we know w has 'px or % in it'
pass
self.style['width'] = width
if height is not None:
try:
height = to_pix(int(height))
except ValueError:
# now we know w has 'px or % in it'
pass
self.style['height'] = height | python | def set_size(self, width, height):
"""Set the widget size.
Args:
width (int or str): An optional width for the widget (es. width=10 or width='10px' or width='10%').
height (int or str): An optional height for the widget (es. height=10 or height='10px' or height='10%').
"""
if width is not None:
try:
width = to_pix(int(width))
except ValueError:
# now we know w has 'px or % in it'
pass
self.style['width'] = width
if height is not None:
try:
height = to_pix(int(height))
except ValueError:
# now we know w has 'px or % in it'
pass
self.style['height'] = height | [
"def",
"set_size",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"if",
"width",
"is",
"not",
"None",
":",
"try",
":",
"width",
"=",
"to_pix",
"(",
"int",
"(",
"width",
")",
")",
"except",
"ValueError",
":",
"# now we know w has 'px or % in it'",
"p... | Set the widget size.
Args:
width (int or str): An optional width for the widget (es. width=10 or width='10px' or width='10%').
height (int or str): An optional height for the widget (es. height=10 or height='10px' or height='10%'). | [
"Set",
"the",
"widget",
"size",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L548-L569 | train | 214,315 |
dddomodossola/remi | remi/gui.py | Widget.repr | def repr(self, changed_widgets=None):
"""Represents the widget as HTML format, packs all the attributes, children and so on.
Args:
client (App): Client instance.
changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated.
The Widget that have to be updated is the key, and the value is its textual repr.
"""
if changed_widgets is None:
changed_widgets={}
return super(Widget, self).repr(changed_widgets) | python | def repr(self, changed_widgets=None):
"""Represents the widget as HTML format, packs all the attributes, children and so on.
Args:
client (App): Client instance.
changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated.
The Widget that have to be updated is the key, and the value is its textual repr.
"""
if changed_widgets is None:
changed_widgets={}
return super(Widget, self).repr(changed_widgets) | [
"def",
"repr",
"(",
"self",
",",
"changed_widgets",
"=",
"None",
")",
":",
"if",
"changed_widgets",
"is",
"None",
":",
"changed_widgets",
"=",
"{",
"}",
"return",
"super",
"(",
"Widget",
",",
"self",
")",
".",
"repr",
"(",
"changed_widgets",
")"
] | Represents the widget as HTML format, packs all the attributes, children and so on.
Args:
client (App): Client instance.
changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated.
The Widget that have to be updated is the key, and the value is its textual repr. | [
"Represents",
"the",
"widget",
"as",
"HTML",
"format",
"packs",
"all",
"the",
"attributes",
"children",
"and",
"so",
"on",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L583-L593 | train | 214,316 |
dddomodossola/remi | remi/gui.py | HEAD.set_icon_file | def set_icon_file(self, filename, rel="icon"):
""" Allows to define an icon for the App
Args:
filename (str): the resource file name (ie. "/res:myicon.png")
rel (str): leave it unchanged (standard "icon")
"""
mimetype, encoding = mimetypes.guess_type(filename)
self.add_child("favicon", '<link rel="%s" href="%s" type="%s" />'%(rel, filename, mimetype)) | python | def set_icon_file(self, filename, rel="icon"):
""" Allows to define an icon for the App
Args:
filename (str): the resource file name (ie. "/res:myicon.png")
rel (str): leave it unchanged (standard "icon")
"""
mimetype, encoding = mimetypes.guess_type(filename)
self.add_child("favicon", '<link rel="%s" href="%s" type="%s" />'%(rel, filename, mimetype)) | [
"def",
"set_icon_file",
"(",
"self",
",",
"filename",
",",
"rel",
"=",
"\"icon\"",
")",
":",
"mimetype",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"self",
".",
"add_child",
"(",
"\"favicon\"",
",",
"'<link rel=\"%s\" href=\"%s... | Allows to define an icon for the App
Args:
filename (str): the resource file name (ie. "/res:myicon.png")
rel (str): leave it unchanged (standard "icon") | [
"Allows",
"to",
"define",
"an",
"icon",
"for",
"the",
"App"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L981-L989 | train | 214,317 |
dddomodossola/remi | remi/gui.py | BODY.onerror | def onerror(self, message, source, lineno, colno):
"""Called when an error occurs."""
return (message, source, lineno, colno) | python | def onerror(self, message, source, lineno, colno):
"""Called when an error occurs."""
return (message, source, lineno, colno) | [
"def",
"onerror",
"(",
"self",
",",
"message",
",",
"source",
",",
"lineno",
",",
"colno",
")",
":",
"return",
"(",
"message",
",",
"source",
",",
"lineno",
",",
"colno",
")"
] | Called when an error occurs. | [
"Called",
"when",
"an",
"error",
"occurs",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1306-L1308 | train | 214,318 |
dddomodossola/remi | remi/gui.py | GridBox.set_column_sizes | def set_column_sizes(self, values):
"""Sets the size value for each column
Args:
values (iterable of int or str): values are treated as percentage.
"""
self.style['grid-template-columns'] = ' '.join(map(lambda value: (str(value) if str(value).endswith('%') else str(value) + '%') , values)) | python | def set_column_sizes(self, values):
"""Sets the size value for each column
Args:
values (iterable of int or str): values are treated as percentage.
"""
self.style['grid-template-columns'] = ' '.join(map(lambda value: (str(value) if str(value).endswith('%') else str(value) + '%') , values)) | [
"def",
"set_column_sizes",
"(",
"self",
",",
"values",
")",
":",
"self",
".",
"style",
"[",
"'grid-template-columns'",
"]",
"=",
"' '",
".",
"join",
"(",
"map",
"(",
"lambda",
"value",
":",
"(",
"str",
"(",
"value",
")",
"if",
"str",
"(",
"value",
")... | Sets the size value for each column
Args:
values (iterable of int or str): values are treated as percentage. | [
"Sets",
"the",
"size",
"value",
"for",
"each",
"column"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1406-L1412 | train | 214,319 |
dddomodossola/remi | remi/gui.py | GridBox.set_column_gap | def set_column_gap(self, value):
"""Sets the gap value between columns
Args:
value (int or str): gap value (i.e. 10 or "10px")
"""
value = str(value) + 'px'
value = value.replace('pxpx', 'px')
self.style['grid-column-gap'] = value | python | def set_column_gap(self, value):
"""Sets the gap value between columns
Args:
value (int or str): gap value (i.e. 10 or "10px")
"""
value = str(value) + 'px'
value = value.replace('pxpx', 'px')
self.style['grid-column-gap'] = value | [
"def",
"set_column_gap",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"+",
"'px'",
"value",
"=",
"value",
".",
"replace",
"(",
"'pxpx'",
",",
"'px'",
")",
"self",
".",
"style",
"[",
"'grid-column-gap'",
"]",
"=",
"valu... | Sets the gap value between columns
Args:
value (int or str): gap value (i.e. 10 or "10px") | [
"Sets",
"the",
"gap",
"value",
"between",
"columns"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1422-L1430 | train | 214,320 |
dddomodossola/remi | remi/gui.py | GridBox.set_row_gap | def set_row_gap(self, value):
"""Sets the gap value between rows
Args:
value (int or str): gap value (i.e. 10 or "10px")
"""
value = str(value) + 'px'
value = value.replace('pxpx', 'px')
self.style['grid-row-gap'] = value | python | def set_row_gap(self, value):
"""Sets the gap value between rows
Args:
value (int or str): gap value (i.e. 10 or "10px")
"""
value = str(value) + 'px'
value = value.replace('pxpx', 'px')
self.style['grid-row-gap'] = value | [
"def",
"set_row_gap",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"+",
"'px'",
"value",
"=",
"value",
".",
"replace",
"(",
"'pxpx'",
",",
"'px'",
")",
"self",
".",
"style",
"[",
"'grid-row-gap'",
"]",
"=",
"value"
] | Sets the gap value between rows
Args:
value (int or str): gap value (i.e. 10 or "10px") | [
"Sets",
"the",
"gap",
"value",
"between",
"rows"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1432-L1440 | train | 214,321 |
dddomodossola/remi | remi/gui.py | TabBox.select_by_widget | def select_by_widget(self, widget):
""" shows a tab identified by the contained widget """
for a, li, holder in self._tabs.values():
if holder.children['content'] == widget:
self._on_tab_pressed(a, li, holder)
return | python | def select_by_widget(self, widget):
""" shows a tab identified by the contained widget """
for a, li, holder in self._tabs.values():
if holder.children['content'] == widget:
self._on_tab_pressed(a, li, holder)
return | [
"def",
"select_by_widget",
"(",
"self",
",",
"widget",
")",
":",
"for",
"a",
",",
"li",
",",
"holder",
"in",
"self",
".",
"_tabs",
".",
"values",
"(",
")",
":",
"if",
"holder",
".",
"children",
"[",
"'content'",
"]",
"==",
"widget",
":",
"self",
".... | shows a tab identified by the contained widget | [
"shows",
"a",
"tab",
"identified",
"by",
"the",
"contained",
"widget"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1573-L1578 | train | 214,322 |
dddomodossola/remi | remi/gui.py | TabBox.select_by_name | def select_by_name(self, name):
""" shows a tab identified by the name """
for a, li, holder in self._tabs.values():
if a.children['text'] == name:
self._on_tab_pressed(a, li, holder)
return | python | def select_by_name(self, name):
""" shows a tab identified by the name """
for a, li, holder in self._tabs.values():
if a.children['text'] == name:
self._on_tab_pressed(a, li, holder)
return | [
"def",
"select_by_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"a",
",",
"li",
",",
"holder",
"in",
"self",
".",
"_tabs",
".",
"values",
"(",
")",
":",
"if",
"a",
".",
"children",
"[",
"'text'",
"]",
"==",
"name",
":",
"self",
".",
"_on_tab_... | shows a tab identified by the name | [
"shows",
"a",
"tab",
"identified",
"by",
"the",
"name"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1580-L1585 | train | 214,323 |
dddomodossola/remi | remi/gui.py | TextInput.set_value | def set_value(self, text):
"""Sets the text content.
Args:
text (str): The string content that have to be appended as standard child identified by the key 'text'
"""
if self.single_line:
text = text.replace('\n', '')
self.set_text(text) | python | def set_value(self, text):
"""Sets the text content.
Args:
text (str): The string content that have to be appended as standard child identified by the key 'text'
"""
if self.single_line:
text = text.replace('\n', '')
self.set_text(text) | [
"def",
"set_value",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"single_line",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"self",
".",
"set_text",
"(",
"text",
")"
] | Sets the text content.
Args:
text (str): The string content that have to be appended as standard child identified by the key 'text' | [
"Sets",
"the",
"text",
"content",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1711-L1719 | train | 214,324 |
dddomodossola/remi | remi/gui.py | TextInput.onchange | def onchange(self, new_value):
"""Called when the user changes the TextInput content.
With single_line=True it fires in case of focus lost and Enter key pressed.
With single_line=False it fires at each key released.
Args:
new_value (str): the new string content of the TextInput.
"""
self.disable_refresh()
self.set_value(new_value)
self.enable_refresh()
return (new_value, ) | python | def onchange(self, new_value):
"""Called when the user changes the TextInput content.
With single_line=True it fires in case of focus lost and Enter key pressed.
With single_line=False it fires at each key released.
Args:
new_value (str): the new string content of the TextInput.
"""
self.disable_refresh()
self.set_value(new_value)
self.enable_refresh()
return (new_value, ) | [
"def",
"onchange",
"(",
"self",
",",
"new_value",
")",
":",
"self",
".",
"disable_refresh",
"(",
")",
"self",
".",
"set_value",
"(",
"new_value",
")",
"self",
".",
"enable_refresh",
"(",
")",
"return",
"(",
"new_value",
",",
")"
] | Called when the user changes the TextInput content.
With single_line=True it fires in case of focus lost and Enter key pressed.
With single_line=False it fires at each key released.
Args:
new_value (str): the new string content of the TextInput. | [
"Called",
"when",
"the",
"user",
"changes",
"the",
"TextInput",
"content",
".",
"With",
"single_line",
"=",
"True",
"it",
"fires",
"in",
"case",
"of",
"focus",
"lost",
"and",
"Enter",
"key",
"pressed",
".",
"With",
"single_line",
"=",
"False",
"it",
"fires... | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1730-L1741 | train | 214,325 |
dddomodossola/remi | remi/gui.py | GenericDialog.add_field_with_label | def add_field_with_label(self, key, label_description, field):
"""
Adds a field to the dialog together with a descriptive label and a unique identifier.
Note: You can access to the fields content calling the function GenericDialog.get_field(key).
Args:
key (str): The unique identifier for the field.
label_description (str): The string content of the description label.
field (Widget): The instance of the field Widget. It can be for example a TextInput or maybe
a custom widget.
"""
self.inputs[key] = field
label = Label(label_description)
label.style['margin'] = '0px 5px'
label.style['min-width'] = '30%'
container = HBox()
container.style.update({'justify-content':'space-between', 'overflow':'auto', 'padding':'3px'})
container.append(label, key='lbl' + key)
container.append(self.inputs[key], key=key)
self.container.append(container, key=key) | python | def add_field_with_label(self, key, label_description, field):
"""
Adds a field to the dialog together with a descriptive label and a unique identifier.
Note: You can access to the fields content calling the function GenericDialog.get_field(key).
Args:
key (str): The unique identifier for the field.
label_description (str): The string content of the description label.
field (Widget): The instance of the field Widget. It can be for example a TextInput or maybe
a custom widget.
"""
self.inputs[key] = field
label = Label(label_description)
label.style['margin'] = '0px 5px'
label.style['min-width'] = '30%'
container = HBox()
container.style.update({'justify-content':'space-between', 'overflow':'auto', 'padding':'3px'})
container.append(label, key='lbl' + key)
container.append(self.inputs[key], key=key)
self.container.append(container, key=key) | [
"def",
"add_field_with_label",
"(",
"self",
",",
"key",
",",
"label_description",
",",
"field",
")",
":",
"self",
".",
"inputs",
"[",
"key",
"]",
"=",
"field",
"label",
"=",
"Label",
"(",
"label_description",
")",
"label",
".",
"style",
"[",
"'margin'",
... | Adds a field to the dialog together with a descriptive label and a unique identifier.
Note: You can access to the fields content calling the function GenericDialog.get_field(key).
Args:
key (str): The unique identifier for the field.
label_description (str): The string content of the description label.
field (Widget): The instance of the field Widget. It can be for example a TextInput or maybe
a custom widget. | [
"Adds",
"a",
"field",
"to",
"the",
"dialog",
"together",
"with",
"a",
"descriptive",
"label",
"and",
"a",
"unique",
"identifier",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1894-L1914 | train | 214,326 |
dddomodossola/remi | remi/gui.py | GenericDialog.add_field | def add_field(self, key, field):
"""
Adds a field to the dialog with a unique identifier.
Note: You can access to the fields content calling the function GenericDialog.get_field(key).
Args:
key (str): The unique identifier for the field.
field (Widget): The widget to be added to the dialog, TextInput or any Widget for example.
"""
self.inputs[key] = field
container = HBox()
container.style.update({'justify-content':'space-between', 'overflow':'auto', 'padding':'3px'})
container.append(self.inputs[key], key=key)
self.container.append(container, key=key) | python | def add_field(self, key, field):
"""
Adds a field to the dialog with a unique identifier.
Note: You can access to the fields content calling the function GenericDialog.get_field(key).
Args:
key (str): The unique identifier for the field.
field (Widget): The widget to be added to the dialog, TextInput or any Widget for example.
"""
self.inputs[key] = field
container = HBox()
container.style.update({'justify-content':'space-between', 'overflow':'auto', 'padding':'3px'})
container.append(self.inputs[key], key=key)
self.container.append(container, key=key) | [
"def",
"add_field",
"(",
"self",
",",
"key",
",",
"field",
")",
":",
"self",
".",
"inputs",
"[",
"key",
"]",
"=",
"field",
"container",
"=",
"HBox",
"(",
")",
"container",
".",
"style",
".",
"update",
"(",
"{",
"'justify-content'",
":",
"'space-between... | Adds a field to the dialog with a unique identifier.
Note: You can access to the fields content calling the function GenericDialog.get_field(key).
Args:
key (str): The unique identifier for the field.
field (Widget): The widget to be added to the dialog, TextInput or any Widget for example. | [
"Adds",
"a",
"field",
"to",
"the",
"dialog",
"with",
"a",
"unique",
"identifier",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L1916-L1930 | train | 214,327 |
dddomodossola/remi | remi/gui.py | InputDialog.on_keydown_listener | def on_keydown_listener(self, widget, value, keycode):
"""event called pressing on ENTER key.
propagates the string content of the input field
"""
if keycode=="13":
self.hide()
self.inputText.set_text(value)
self.confirm_value(self) | python | def on_keydown_listener(self, widget, value, keycode):
"""event called pressing on ENTER key.
propagates the string content of the input field
"""
if keycode=="13":
self.hide()
self.inputText.set_text(value)
self.confirm_value(self) | [
"def",
"on_keydown_listener",
"(",
"self",
",",
"widget",
",",
"value",
",",
"keycode",
")",
":",
"if",
"keycode",
"==",
"\"13\"",
":",
"self",
".",
"hide",
"(",
")",
"self",
".",
"inputText",
".",
"set_text",
"(",
"value",
")",
"self",
".",
"confirm_v... | event called pressing on ENTER key.
propagates the string content of the input field | [
"event",
"called",
"pressing",
"on",
"ENTER",
"key",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2001-L2009 | train | 214,328 |
dddomodossola/remi | remi/gui.py | ListView.new_from_list | def new_from_list(cls, items, **kwargs):
"""Populates the ListView with a string list.
Args:
items (list): list of strings to fill the widget with.
"""
obj = cls(**kwargs)
for item in items:
obj.append(ListItem(item))
return obj | python | def new_from_list(cls, items, **kwargs):
"""Populates the ListView with a string list.
Args:
items (list): list of strings to fill the widget with.
"""
obj = cls(**kwargs)
for item in items:
obj.append(ListItem(item))
return obj | [
"def",
"new_from_list",
"(",
"cls",
",",
"items",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"cls",
"(",
"*",
"*",
"kwargs",
")",
"for",
"item",
"in",
"items",
":",
"obj",
".",
"append",
"(",
"ListItem",
"(",
"item",
")",
")",
"return",
"obj"... | Populates the ListView with a string list.
Args:
items (list): list of strings to fill the widget with. | [
"Populates",
"the",
"ListView",
"with",
"a",
"string",
"list",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2041-L2050 | train | 214,329 |
dddomodossola/remi | remi/gui.py | ListView.empty | def empty(self):
"""Removes all children from the list"""
self._selected_item = None
self._selected_key = None
super(ListView, self).empty() | python | def empty(self):
"""Removes all children from the list"""
self._selected_item = None
self._selected_key = None
super(ListView, self).empty() | [
"def",
"empty",
"(",
"self",
")",
":",
"self",
".",
"_selected_item",
"=",
"None",
"self",
".",
"_selected_key",
"=",
"None",
"super",
"(",
"ListView",
",",
"self",
")",
".",
"empty",
"(",
")"
] | Removes all children from the list | [
"Removes",
"all",
"children",
"from",
"the",
"list"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2077-L2081 | train | 214,330 |
dddomodossola/remi | remi/gui.py | ListView.onselection | def onselection(self, widget):
"""Called when a new item gets selected in the list."""
self._selected_key = None
for k in self.children:
if self.children[k] == widget: # widget is the selected ListItem
self._selected_key = k
if (self._selected_item is not None) and self._selectable:
self._selected_item.attributes['selected'] = False
self._selected_item = self.children[self._selected_key]
if self._selectable:
self._selected_item.attributes['selected'] = True
break
return (self._selected_key,) | python | def onselection(self, widget):
"""Called when a new item gets selected in the list."""
self._selected_key = None
for k in self.children:
if self.children[k] == widget: # widget is the selected ListItem
self._selected_key = k
if (self._selected_item is not None) and self._selectable:
self._selected_item.attributes['selected'] = False
self._selected_item = self.children[self._selected_key]
if self._selectable:
self._selected_item.attributes['selected'] = True
break
return (self._selected_key,) | [
"def",
"onselection",
"(",
"self",
",",
"widget",
")",
":",
"self",
".",
"_selected_key",
"=",
"None",
"for",
"k",
"in",
"self",
".",
"children",
":",
"if",
"self",
".",
"children",
"[",
"k",
"]",
"==",
"widget",
":",
"# widget is the selected ListItem",
... | Called when a new item gets selected in the list. | [
"Called",
"when",
"a",
"new",
"item",
"gets",
"selected",
"in",
"the",
"list",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2085-L2097 | train | 214,331 |
dddomodossola/remi | remi/gui.py | ListView.select_by_key | def select_by_key(self, key):
"""Selects an item by its key.
Args:
key (str): The unique string identifier of the item that have to be selected.
"""
self._selected_key = None
self._selected_item = None
for item in self.children.values():
item.attributes['selected'] = False
if key in self.children:
self.children[key].attributes['selected'] = True
self._selected_key = key
self._selected_item = self.children[key] | python | def select_by_key(self, key):
"""Selects an item by its key.
Args:
key (str): The unique string identifier of the item that have to be selected.
"""
self._selected_key = None
self._selected_item = None
for item in self.children.values():
item.attributes['selected'] = False
if key in self.children:
self.children[key].attributes['selected'] = True
self._selected_key = key
self._selected_item = self.children[key] | [
"def",
"select_by_key",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_selected_key",
"=",
"None",
"self",
".",
"_selected_item",
"=",
"None",
"for",
"item",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"item",
".",
"attributes",
"["... | Selects an item by its key.
Args:
key (str): The unique string identifier of the item that have to be selected. | [
"Selects",
"an",
"item",
"by",
"its",
"key",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2122-L2136 | train | 214,332 |
dddomodossola/remi | remi/gui.py | ListView.select_by_value | def select_by_value(self, value):
"""Selects an item by the text content of the child.
Args:
value (str): Text content of the item that have to be selected.
"""
self._selected_key = None
self._selected_item = None
for k in self.children:
item = self.children[k]
item.attributes['selected'] = False
if value == item.get_value():
self._selected_key = k
self._selected_item = item
self._selected_item.attributes['selected'] = True | python | def select_by_value(self, value):
"""Selects an item by the text content of the child.
Args:
value (str): Text content of the item that have to be selected.
"""
self._selected_key = None
self._selected_item = None
for k in self.children:
item = self.children[k]
item.attributes['selected'] = False
if value == item.get_value():
self._selected_key = k
self._selected_item = item
self._selected_item.attributes['selected'] = True | [
"def",
"select_by_value",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_selected_key",
"=",
"None",
"self",
".",
"_selected_item",
"=",
"None",
"for",
"k",
"in",
"self",
".",
"children",
":",
"item",
"=",
"self",
".",
"children",
"[",
"k",
"]",
... | Selects an item by the text content of the child.
Args:
value (str): Text content of the item that have to be selected. | [
"Selects",
"an",
"item",
"by",
"the",
"text",
"content",
"of",
"the",
"child",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2141-L2155 | train | 214,333 |
dddomodossola/remi | remi/gui.py | DropDown.select_by_key | def select_by_key(self, key):
"""Selects an item by its unique string identifier.
Args:
key (str): Unique string identifier of the DropDownItem that have to be selected.
"""
for item in self.children.values():
if 'selected' in item.attributes:
del item.attributes['selected']
self.children[key].attributes['selected'] = 'selected'
self._selected_key = key
self._selected_item = self.children[key] | python | def select_by_key(self, key):
"""Selects an item by its unique string identifier.
Args:
key (str): Unique string identifier of the DropDownItem that have to be selected.
"""
for item in self.children.values():
if 'selected' in item.attributes:
del item.attributes['selected']
self.children[key].attributes['selected'] = 'selected'
self._selected_key = key
self._selected_item = self.children[key] | [
"def",
"select_by_key",
"(",
"self",
",",
"key",
")",
":",
"for",
"item",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
":",
"if",
"'selected'",
"in",
"item",
".",
"attributes",
":",
"del",
"item",
".",
"attributes",
"[",
"'selected'",
"]",
... | Selects an item by its unique string identifier.
Args:
key (str): Unique string identifier of the DropDownItem that have to be selected. | [
"Selects",
"an",
"item",
"by",
"its",
"unique",
"string",
"identifier",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2235-L2246 | train | 214,334 |
dddomodossola/remi | remi/gui.py | DropDown.select_by_value | def select_by_value(self, value):
"""Selects a DropDownItem by means of the contained text-
Args:
value (str): Textual content of the DropDownItem that have to be selected.
"""
self._selected_key = None
self._selected_item = None
for k in self.children:
item = self.children[k]
if item.get_text() == value:
item.attributes['selected'] = 'selected'
self._selected_key = k
self._selected_item = item
else:
if 'selected' in item.attributes:
del item.attributes['selected'] | python | def select_by_value(self, value):
"""Selects a DropDownItem by means of the contained text-
Args:
value (str): Textual content of the DropDownItem that have to be selected.
"""
self._selected_key = None
self._selected_item = None
for k in self.children:
item = self.children[k]
if item.get_text() == value:
item.attributes['selected'] = 'selected'
self._selected_key = k
self._selected_item = item
else:
if 'selected' in item.attributes:
del item.attributes['selected'] | [
"def",
"select_by_value",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_selected_key",
"=",
"None",
"self",
".",
"_selected_item",
"=",
"None",
"for",
"k",
"in",
"self",
".",
"children",
":",
"item",
"=",
"self",
".",
"children",
"[",
"k",
"]",
... | Selects a DropDownItem by means of the contained text-
Args:
value (str): Textual content of the DropDownItem that have to be selected. | [
"Selects",
"a",
"DropDownItem",
"by",
"means",
"of",
"the",
"contained",
"text",
"-"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2251-L2267 | train | 214,335 |
dddomodossola/remi | remi/gui.py | DropDown.onchange | def onchange(self, value):
"""Called when a new DropDownItem gets selected.
"""
log.debug('combo box. selected %s' % value)
self.select_by_value(value)
return (value, ) | python | def onchange(self, value):
"""Called when a new DropDownItem gets selected.
"""
log.debug('combo box. selected %s' % value)
self.select_by_value(value)
return (value, ) | [
"def",
"onchange",
"(",
"self",
",",
"value",
")",
":",
"log",
".",
"debug",
"(",
"'combo box. selected %s'",
"%",
"value",
")",
"self",
".",
"select_by_value",
"(",
"value",
")",
"return",
"(",
"value",
",",
")"
] | Called when a new DropDownItem gets selected. | [
"Called",
"when",
"a",
"new",
"DropDownItem",
"gets",
"selected",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2294-L2299 | train | 214,336 |
dddomodossola/remi | remi/gui.py | Table.append_from_list | def append_from_list(self, content, fill_title=False):
"""
Appends rows created from the data contained in the provided
list of tuples of strings. The first tuple of the list can be
set as table title.
Args:
content (list): list of tuples of strings. Each tuple is a row.
fill_title (bool): if true, the first tuple in the list will
be set as title.
"""
row_index = 0
for row in content:
tr = TableRow()
column_index = 0
for item in row:
if row_index == 0 and fill_title:
ti = TableTitle(item)
else:
ti = TableItem(item)
tr.append(ti, str(column_index))
column_index = column_index + 1
self.append(tr, str(row_index))
row_index = row_index + 1 | python | def append_from_list(self, content, fill_title=False):
"""
Appends rows created from the data contained in the provided
list of tuples of strings. The first tuple of the list can be
set as table title.
Args:
content (list): list of tuples of strings. Each tuple is a row.
fill_title (bool): if true, the first tuple in the list will
be set as title.
"""
row_index = 0
for row in content:
tr = TableRow()
column_index = 0
for item in row:
if row_index == 0 and fill_title:
ti = TableTitle(item)
else:
ti = TableItem(item)
tr.append(ti, str(column_index))
column_index = column_index + 1
self.append(tr, str(row_index))
row_index = row_index + 1 | [
"def",
"append_from_list",
"(",
"self",
",",
"content",
",",
"fill_title",
"=",
"False",
")",
":",
"row_index",
"=",
"0",
"for",
"row",
"in",
"content",
":",
"tr",
"=",
"TableRow",
"(",
")",
"column_index",
"=",
"0",
"for",
"item",
"in",
"row",
":",
... | Appends rows created from the data contained in the provided
list of tuples of strings. The first tuple of the list can be
set as table title.
Args:
content (list): list of tuples of strings. Each tuple is a row.
fill_title (bool): if true, the first tuple in the list will
be set as title. | [
"Appends",
"rows",
"created",
"from",
"the",
"data",
"contained",
"in",
"the",
"provided",
"list",
"of",
"tuples",
"of",
"strings",
".",
"The",
"first",
"tuple",
"of",
"the",
"list",
"can",
"be",
"set",
"as",
"table",
"title",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2377-L2400 | train | 214,337 |
dddomodossola/remi | remi/gui.py | TableWidget.item_at | def item_at(self, row, column):
"""Returns the TableItem instance at row, column cordinates
Args:
row (int): zero based index
column (int): zero based index
"""
return self.children[str(row)].children[str(column)] | python | def item_at(self, row, column):
"""Returns the TableItem instance at row, column cordinates
Args:
row (int): zero based index
column (int): zero based index
"""
return self.children[str(row)].children[str(column)] | [
"def",
"item_at",
"(",
"self",
",",
"row",
",",
"column",
")",
":",
"return",
"self",
".",
"children",
"[",
"str",
"(",
"row",
")",
"]",
".",
"children",
"[",
"str",
"(",
"column",
")",
"]"
] | Returns the TableItem instance at row, column cordinates
Args:
row (int): zero based index
column (int): zero based index | [
"Returns",
"the",
"TableItem",
"instance",
"at",
"row",
"column",
"cordinates"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2468-L2475 | train | 214,338 |
dddomodossola/remi | remi/gui.py | TableWidget.set_row_count | def set_row_count(self, count):
"""Sets the table row count.
Args:
count (int): number of rows
"""
current_row_count = self.row_count()
current_column_count = self.column_count()
if count > current_row_count:
cl = TableEditableItem if self._editable else TableItem
for i in range(current_row_count, count):
tr = TableRow()
for c in range(0, current_column_count):
tr.append(cl(), str(c))
if self._editable:
tr.children[str(c)].onchange.connect(
self.on_item_changed, int(i), int(c))
self.append(tr, str(i))
self._update_first_row()
elif count < current_row_count:
for i in range(count, current_row_count):
self.remove_child(self.children[str(i)]) | python | def set_row_count(self, count):
"""Sets the table row count.
Args:
count (int): number of rows
"""
current_row_count = self.row_count()
current_column_count = self.column_count()
if count > current_row_count:
cl = TableEditableItem if self._editable else TableItem
for i in range(current_row_count, count):
tr = TableRow()
for c in range(0, current_column_count):
tr.append(cl(), str(c))
if self._editable:
tr.children[str(c)].onchange.connect(
self.on_item_changed, int(i), int(c))
self.append(tr, str(i))
self._update_first_row()
elif count < current_row_count:
for i in range(count, current_row_count):
self.remove_child(self.children[str(i)]) | [
"def",
"set_row_count",
"(",
"self",
",",
"count",
")",
":",
"current_row_count",
"=",
"self",
".",
"row_count",
"(",
")",
"current_column_count",
"=",
"self",
".",
"column_count",
"(",
")",
"if",
"count",
">",
"current_row_count",
":",
"cl",
"=",
"TableEdit... | Sets the table row count.
Args:
count (int): number of rows | [
"Sets",
"the",
"table",
"row",
"count",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2500-L2521 | train | 214,339 |
dddomodossola/remi | remi/gui.py | TableWidget.set_column_count | def set_column_count(self, count):
"""Sets the table column count.
Args:
count (int): column of rows
"""
current_row_count = self.row_count()
current_column_count = self.column_count()
if count > current_column_count:
cl = TableEditableItem if self._editable else TableItem
for r_key in self.children.keys():
row = self.children[r_key]
for i in range(current_column_count, count):
row.append(cl(), str(i))
if self._editable:
row.children[str(i)].onchange.connect(
self.on_item_changed, int(r_key), int(i))
self._update_first_row()
elif count < current_column_count:
for row in self.children.values():
for i in range(count, current_column_count):
row.remove_child(row.children[str(i)])
self._column_count = count | python | def set_column_count(self, count):
"""Sets the table column count.
Args:
count (int): column of rows
"""
current_row_count = self.row_count()
current_column_count = self.column_count()
if count > current_column_count:
cl = TableEditableItem if self._editable else TableItem
for r_key in self.children.keys():
row = self.children[r_key]
for i in range(current_column_count, count):
row.append(cl(), str(i))
if self._editable:
row.children[str(i)].onchange.connect(
self.on_item_changed, int(r_key), int(i))
self._update_first_row()
elif count < current_column_count:
for row in self.children.values():
for i in range(count, current_column_count):
row.remove_child(row.children[str(i)])
self._column_count = count | [
"def",
"set_column_count",
"(",
"self",
",",
"count",
")",
":",
"current_row_count",
"=",
"self",
".",
"row_count",
"(",
")",
"current_column_count",
"=",
"self",
".",
"column_count",
"(",
")",
"if",
"count",
">",
"current_column_count",
":",
"cl",
"=",
"Tab... | Sets the table column count.
Args:
count (int): column of rows | [
"Sets",
"the",
"table",
"column",
"count",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2523-L2545 | train | 214,340 |
dddomodossola/remi | remi/gui.py | TableWidget.on_item_changed | def on_item_changed(self, item, new_value, row, column):
"""Event for the item change.
Args:
emitter (TableWidget): The emitter of the event.
item (TableItem): The TableItem instance.
new_value (str): New text content.
row (int): row index.
column (int): column index.
"""
return (item, new_value, row, column) | python | def on_item_changed(self, item, new_value, row, column):
"""Event for the item change.
Args:
emitter (TableWidget): The emitter of the event.
item (TableItem): The TableItem instance.
new_value (str): New text content.
row (int): row index.
column (int): column index.
"""
return (item, new_value, row, column) | [
"def",
"on_item_changed",
"(",
"self",
",",
"item",
",",
"new_value",
",",
"row",
",",
"column",
")",
":",
"return",
"(",
"item",
",",
"new_value",
",",
"row",
",",
"column",
")"
] | Event for the item change.
Args:
emitter (TableWidget): The emitter of the event.
item (TableItem): The TableItem instance.
new_value (str): New text content.
row (int): row index.
column (int): column index. | [
"Event",
"for",
"the",
"item",
"change",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2549-L2559 | train | 214,341 |
dddomodossola/remi | remi/gui.py | Svg.set_viewbox | def set_viewbox(self, x, y, w, h):
"""Sets the origin and size of the viewbox, describing a virtual view area.
Args:
x (int): x coordinate of the viewbox origin
y (int): y coordinate of the viewbox origin
w (int): width of the viewbox
h (int): height of the viewbox
"""
self.attributes['viewBox'] = "%s %s %s %s" % (x, y, w, h)
self.attributes['preserveAspectRatio'] = 'none' | python | def set_viewbox(self, x, y, w, h):
"""Sets the origin and size of the viewbox, describing a virtual view area.
Args:
x (int): x coordinate of the viewbox origin
y (int): y coordinate of the viewbox origin
w (int): width of the viewbox
h (int): height of the viewbox
"""
self.attributes['viewBox'] = "%s %s %s %s" % (x, y, w, h)
self.attributes['preserveAspectRatio'] = 'none' | [
"def",
"set_viewbox",
"(",
"self",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
":",
"self",
".",
"attributes",
"[",
"'viewBox'",
"]",
"=",
"\"%s %s %s %s\"",
"%",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
"self",
".",
"attributes",
"[",
"'p... | Sets the origin and size of the viewbox, describing a virtual view area.
Args:
x (int): x coordinate of the viewbox origin
y (int): y coordinate of the viewbox origin
w (int): width of the viewbox
h (int): height of the viewbox | [
"Sets",
"the",
"origin",
"and",
"size",
"of",
"the",
"viewbox",
"describing",
"a",
"virtual",
"view",
"area",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L3396-L3406 | train | 214,342 |
dddomodossola/remi | remi/gui.py | SvgShape.set_position | def set_position(self, x, y):
"""Sets the shape position.
Args:
x (int): the x coordinate
y (int): the y coordinate
"""
self.attributes['x'] = str(x)
self.attributes['y'] = str(y) | python | def set_position(self, x, y):
"""Sets the shape position.
Args:
x (int): the x coordinate
y (int): the y coordinate
"""
self.attributes['x'] = str(x)
self.attributes['y'] = str(y) | [
"def",
"set_position",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"attributes",
"[",
"'x'",
"]",
"=",
"str",
"(",
"x",
")",
"self",
".",
"attributes",
"[",
"'y'",
"]",
"=",
"str",
"(",
"y",
")"
] | Sets the shape position.
Args:
x (int): the x coordinate
y (int): the y coordinate | [
"Sets",
"the",
"shape",
"position",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L3423-L3431 | train | 214,343 |
dddomodossola/remi | remi/gui.py | SvgRectangle.set_size | def set_size(self, w, h):
""" Sets the rectangle size.
Args:
w (int): width of the rectangle
h (int): height of the rectangle
"""
self.attributes['width'] = str(w)
self.attributes['height'] = str(h) | python | def set_size(self, w, h):
""" Sets the rectangle size.
Args:
w (int): width of the rectangle
h (int): height of the rectangle
"""
self.attributes['width'] = str(w)
self.attributes['height'] = str(h) | [
"def",
"set_size",
"(",
"self",
",",
"w",
",",
"h",
")",
":",
"self",
".",
"attributes",
"[",
"'width'",
"]",
"=",
"str",
"(",
"w",
")",
"self",
".",
"attributes",
"[",
"'height'",
"]",
"=",
"str",
"(",
"h",
")"
] | Sets the rectangle size.
Args:
w (int): width of the rectangle
h (int): height of the rectangle | [
"Sets",
"the",
"rectangle",
"size",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L3478-L3486 | train | 214,344 |
dddomodossola/remi | remi/server.py | start | def start(main_gui_class, **kwargs):
"""This method starts the webserver with a specific App subclass."""
debug = kwargs.pop('debug', False)
standalone = kwargs.pop('standalone', False)
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO,
format='%(name)-16s %(levelname)-8s %(message)s')
logging.getLogger('remi').setLevel(
level=logging.DEBUG if debug else logging.INFO)
if standalone:
s = StandaloneServer(main_gui_class, start=True, **kwargs)
else:
s = Server(main_gui_class, start=True, **kwargs) | python | def start(main_gui_class, **kwargs):
"""This method starts the webserver with a specific App subclass."""
debug = kwargs.pop('debug', False)
standalone = kwargs.pop('standalone', False)
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO,
format='%(name)-16s %(levelname)-8s %(message)s')
logging.getLogger('remi').setLevel(
level=logging.DEBUG if debug else logging.INFO)
if standalone:
s = StandaloneServer(main_gui_class, start=True, **kwargs)
else:
s = Server(main_gui_class, start=True, **kwargs) | [
"def",
"start",
"(",
"main_gui_class",
",",
"*",
"*",
"kwargs",
")",
":",
"debug",
"=",
"kwargs",
".",
"pop",
"(",
"'debug'",
",",
"False",
")",
"standalone",
"=",
"kwargs",
".",
"pop",
"(",
"'standalone'",
",",
"False",
")",
"logging",
".",
"basicConf... | This method starts the webserver with a specific App subclass. | [
"This",
"method",
"starts",
"the",
"webserver",
"with",
"a",
"specific",
"App",
"subclass",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/server.py#L877-L890 | train | 214,345 |
dddomodossola/remi | remi/server.py | App._instance | def _instance(self):
global clients
global runtimeInstances
"""
This method is used to get the Application instance previously created
managing on this, it is possible to switch to "single instance for
multiple clients" or "multiple instance for multiple clients" execution way
"""
self.session = 0
#checking previously defined session
if 'cookie' in self.headers:
self.session = parse_session_cookie(self.headers['cookie'])
#if not a valid session id
if self.session == None:
self.session = 0
if not self.session in clients.keys():
self.session = 0
#if no session id
if self.session == 0:
if self.server.multiple_instance:
self.session = int(time.time()*1000)
#send session to browser
del self.headers['cookie']
#if the client instance doesn't exist
if not(self.session in clients):
self.update_interval = self.server.update_interval
from remi import gui
head = gui.HEAD(self.server.title)
# use the default css, but append a version based on its hash, to stop browser caching
head.add_child('internal_css', "<link href='/res:style.css' rel='stylesheet' />\n")
body = gui.BODY()
body.onload.connect(self.onload)
body.onerror.connect(self.onerror)
body.ononline.connect(self.ononline)
body.onpagehide.connect(self.onpagehide)
body.onpageshow.connect(self.onpageshow)
body.onresize.connect(self.onresize)
self.page = gui.HTML()
self.page.add_child('head', head)
self.page.add_child('body', body)
if not hasattr(self, 'websockets'):
self.websockets = []
self.update_lock = threading.RLock()
if not hasattr(self, '_need_update_flag'):
self._need_update_flag = False
self._stop_update_flag = False
if self.update_interval > 0:
self._update_thread = threading.Thread(target=self._idle_loop)
self._update_thread.setDaemon(True)
self._update_thread.start()
runtimeInstances[str(id(self))] = self
clients[self.session] = self
else:
#restore instance attributes
client = clients[self.session]
self.websockets = client.websockets
self.page = client.page
self.update_lock = client.update_lock
self.update_interval = client.update_interval
self._need_update_flag = client._need_update_flag
if hasattr(client, '_update_thread'):
self._update_thread = client._update_thread
net_interface_ip = self.headers.get('Host', "%s:%s"%(self.connection.getsockname()[0],self.server.server_address[1]))
websocket_timeout_timer_ms = str(self.server.websocket_timeout_timer_ms)
pending_messages_queue_length = str(self.server.pending_messages_queue_length)
self.page.children['head'].set_internal_js(net_interface_ip, pending_messages_queue_length, websocket_timeout_timer_ms) | python | def _instance(self):
global clients
global runtimeInstances
"""
This method is used to get the Application instance previously created
managing on this, it is possible to switch to "single instance for
multiple clients" or "multiple instance for multiple clients" execution way
"""
self.session = 0
#checking previously defined session
if 'cookie' in self.headers:
self.session = parse_session_cookie(self.headers['cookie'])
#if not a valid session id
if self.session == None:
self.session = 0
if not self.session in clients.keys():
self.session = 0
#if no session id
if self.session == 0:
if self.server.multiple_instance:
self.session = int(time.time()*1000)
#send session to browser
del self.headers['cookie']
#if the client instance doesn't exist
if not(self.session in clients):
self.update_interval = self.server.update_interval
from remi import gui
head = gui.HEAD(self.server.title)
# use the default css, but append a version based on its hash, to stop browser caching
head.add_child('internal_css', "<link href='/res:style.css' rel='stylesheet' />\n")
body = gui.BODY()
body.onload.connect(self.onload)
body.onerror.connect(self.onerror)
body.ononline.connect(self.ononline)
body.onpagehide.connect(self.onpagehide)
body.onpageshow.connect(self.onpageshow)
body.onresize.connect(self.onresize)
self.page = gui.HTML()
self.page.add_child('head', head)
self.page.add_child('body', body)
if not hasattr(self, 'websockets'):
self.websockets = []
self.update_lock = threading.RLock()
if not hasattr(self, '_need_update_flag'):
self._need_update_flag = False
self._stop_update_flag = False
if self.update_interval > 0:
self._update_thread = threading.Thread(target=self._idle_loop)
self._update_thread.setDaemon(True)
self._update_thread.start()
runtimeInstances[str(id(self))] = self
clients[self.session] = self
else:
#restore instance attributes
client = clients[self.session]
self.websockets = client.websockets
self.page = client.page
self.update_lock = client.update_lock
self.update_interval = client.update_interval
self._need_update_flag = client._need_update_flag
if hasattr(client, '_update_thread'):
self._update_thread = client._update_thread
net_interface_ip = self.headers.get('Host', "%s:%s"%(self.connection.getsockname()[0],self.server.server_address[1]))
websocket_timeout_timer_ms = str(self.server.websocket_timeout_timer_ms)
pending_messages_queue_length = str(self.server.pending_messages_queue_length)
self.page.children['head'].set_internal_js(net_interface_ip, pending_messages_queue_length, websocket_timeout_timer_ms) | [
"def",
"_instance",
"(",
"self",
")",
":",
"global",
"clients",
"global",
"runtimeInstances",
"self",
".",
"session",
"=",
"0",
"#checking previously defined session",
"if",
"'cookie'",
"in",
"self",
".",
"headers",
":",
"self",
".",
"session",
"=",
"parse_sessi... | This method is used to get the Application instance previously created
managing on this, it is possible to switch to "single instance for
multiple clients" or "multiple instance for multiple clients" execution way | [
"This",
"method",
"is",
"used",
"to",
"get",
"the",
"Application",
"instance",
"previously",
"created",
"managing",
"on",
"this",
"it",
"is",
"possible",
"to",
"switch",
"to",
"single",
"instance",
"for",
"multiple",
"clients",
"or",
"multiple",
"instance",
"f... | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/server.py#L318-L397 | train | 214,346 |
dddomodossola/remi | remi/server.py | App.do_gui_update | def do_gui_update(self):
""" This method gets called also by Timer, a new thread, and so needs to lock the update
"""
with self.update_lock:
changed_widget_dict = {}
self.root.repr(changed_widget_dict)
for widget in changed_widget_dict.keys():
html = changed_widget_dict[widget]
__id = str(widget.identifier)
self._send_spontaneous_websocket_message(_MSG_UPDATE + __id + ',' + to_websocket(html))
self._need_update_flag = False | python | def do_gui_update(self):
""" This method gets called also by Timer, a new thread, and so needs to lock the update
"""
with self.update_lock:
changed_widget_dict = {}
self.root.repr(changed_widget_dict)
for widget in changed_widget_dict.keys():
html = changed_widget_dict[widget]
__id = str(widget.identifier)
self._send_spontaneous_websocket_message(_MSG_UPDATE + __id + ',' + to_websocket(html))
self._need_update_flag = False | [
"def",
"do_gui_update",
"(",
"self",
")",
":",
"with",
"self",
".",
"update_lock",
":",
"changed_widget_dict",
"=",
"{",
"}",
"self",
".",
"root",
".",
"repr",
"(",
"changed_widget_dict",
")",
"for",
"widget",
"in",
"changed_widget_dict",
".",
"keys",
"(",
... | This method gets called also by Timer, a new thread, and so needs to lock the update | [
"This",
"method",
"gets",
"called",
"also",
"by",
"Timer",
"a",
"new",
"thread",
"and",
"so",
"needs",
"to",
"lock",
"the",
"update"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/server.py#L436-L446 | train | 214,347 |
dddomodossola/remi | remi/server.py | App.do_GET | def do_GET(self):
# check here request header to identify the type of req, if http or ws
# if this is a ws req, instance a ws handler, add it to App's ws list, return
if "Upgrade" in self.headers:
if self.headers['Upgrade'] == 'websocket':
#passing arguments to websocket handler, otherwise it will lost the last message,
# and will be unable to handshake
ws = WebSocketsHandler(self.headers, self.request, self.client_address, self.server)
return
"""Handler for the GET requests."""
do_process = False
if self.server.auth is None:
do_process = True
else:
if not ('Authorization' in self.headers) or self.headers['Authorization'] is None:
self._log.info("Authenticating")
self.do_AUTHHEAD()
self.wfile.write(encode_text('no auth header received'))
elif self.headers['Authorization'] == 'Basic ' + self.server.auth.decode():
do_process = True
else:
self.do_AUTHHEAD()
self.wfile.write(encode_text(self.headers['Authorization']))
self.wfile.write(encode_text('not authenticated'))
if do_process:
path = str(unquote(self.path))
# noinspection PyBroadException
try:
self._instance()
# build the page (call main()) in user code, if not built yet
with self.update_lock:
# build the root page once if necessary
if not 'root' in self.page.children['body'].children.keys():
self._log.info('built UI (path=%s)' % path)
self.set_root_widget(self.main(*self.server.userdata))
self._process_all(path)
except:
self._log.error('error processing GET request', exc_info=True) | python | def do_GET(self):
# check here request header to identify the type of req, if http or ws
# if this is a ws req, instance a ws handler, add it to App's ws list, return
if "Upgrade" in self.headers:
if self.headers['Upgrade'] == 'websocket':
#passing arguments to websocket handler, otherwise it will lost the last message,
# and will be unable to handshake
ws = WebSocketsHandler(self.headers, self.request, self.client_address, self.server)
return
"""Handler for the GET requests."""
do_process = False
if self.server.auth is None:
do_process = True
else:
if not ('Authorization' in self.headers) or self.headers['Authorization'] is None:
self._log.info("Authenticating")
self.do_AUTHHEAD()
self.wfile.write(encode_text('no auth header received'))
elif self.headers['Authorization'] == 'Basic ' + self.server.auth.decode():
do_process = True
else:
self.do_AUTHHEAD()
self.wfile.write(encode_text(self.headers['Authorization']))
self.wfile.write(encode_text('not authenticated'))
if do_process:
path = str(unquote(self.path))
# noinspection PyBroadException
try:
self._instance()
# build the page (call main()) in user code, if not built yet
with self.update_lock:
# build the root page once if necessary
if not 'root' in self.page.children['body'].children.keys():
self._log.info('built UI (path=%s)' % path)
self.set_root_widget(self.main(*self.server.userdata))
self._process_all(path)
except:
self._log.error('error processing GET request', exc_info=True) | [
"def",
"do_GET",
"(",
"self",
")",
":",
"# check here request header to identify the type of req, if http or ws",
"# if this is a ws req, instance a ws handler, add it to App's ws list, return",
"if",
"\"Upgrade\"",
"in",
"self",
".",
"headers",
":",
"if",
"self",
".",
"headers",... | Handler for the GET requests. | [
"Handler",
"for",
"the",
"GET",
"requests",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/server.py#L551-L590 | train | 214,348 |
dddomodossola/remi | remi/server.py | App.on_close | def on_close(self):
""" Called by the server when the App have to be terminated
"""
self._stop_update_flag = True
for ws in self.websockets:
ws.close() | python | def on_close(self):
""" Called by the server when the App have to be terminated
"""
self._stop_update_flag = True
for ws in self.websockets:
ws.close() | [
"def",
"on_close",
"(",
"self",
")",
":",
"self",
".",
"_stop_update_flag",
"=",
"True",
"for",
"ws",
"in",
"self",
".",
"websockets",
":",
"ws",
".",
"close",
"(",
")"
] | Called by the server when the App have to be terminated | [
"Called",
"by",
"the",
"server",
"when",
"the",
"App",
"have",
"to",
"be",
"terminated"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/server.py#L680-L685 | train | 214,349 |
dddomodossola/remi | editor/editor_widgets.py | SignalConnectionManager.update | def update(self, widget, widget_tree):
""" for the selected widget are listed the relative signals
for each signal there is a dropdown containing all the widgets
the user will select the widget that have to listen a specific event
"""
self.listeners_list = []
self.build_widget_list_from_tree(widget_tree)
self.label.set_text('Signal connections: ' + widget.attributes['editor_varname'])
#del self.container
self.container = gui.VBox(width='100%', height='90%')
self.container.style['justify-content'] = 'flex-start'
self.container.style['overflow-y'] = 'scroll'
self.append(self.container, 'container')
##for all the events of this widget
#isclass instead of ismethod because event methods are replaced with ClassEventConnector
for (setOnEventListenerFuncname,setOnEventListenerFunc) in inspect.getmembers(widget):
#if the member is decorated by decorate_set_on_listener and the function is referred to this event
if hasattr(setOnEventListenerFunc, '_event_info'):
self.container.append( SignalConnection(widget,
self.listeners_list,
setOnEventListenerFuncname,
setOnEventListenerFunc,
width='100%') ) | python | def update(self, widget, widget_tree):
""" for the selected widget are listed the relative signals
for each signal there is a dropdown containing all the widgets
the user will select the widget that have to listen a specific event
"""
self.listeners_list = []
self.build_widget_list_from_tree(widget_tree)
self.label.set_text('Signal connections: ' + widget.attributes['editor_varname'])
#del self.container
self.container = gui.VBox(width='100%', height='90%')
self.container.style['justify-content'] = 'flex-start'
self.container.style['overflow-y'] = 'scroll'
self.append(self.container, 'container')
##for all the events of this widget
#isclass instead of ismethod because event methods are replaced with ClassEventConnector
for (setOnEventListenerFuncname,setOnEventListenerFunc) in inspect.getmembers(widget):
#if the member is decorated by decorate_set_on_listener and the function is referred to this event
if hasattr(setOnEventListenerFunc, '_event_info'):
self.container.append( SignalConnection(widget,
self.listeners_list,
setOnEventListenerFuncname,
setOnEventListenerFunc,
width='100%') ) | [
"def",
"update",
"(",
"self",
",",
"widget",
",",
"widget_tree",
")",
":",
"self",
".",
"listeners_list",
"=",
"[",
"]",
"self",
".",
"build_widget_list_from_tree",
"(",
"widget_tree",
")",
"self",
".",
"label",
".",
"set_text",
"(",
"'Signal connections: '",
... | for the selected widget are listed the relative signals
for each signal there is a dropdown containing all the widgets
the user will select the widget that have to listen a specific event | [
"for",
"the",
"selected",
"widget",
"are",
"listed",
"the",
"relative",
"signals",
"for",
"each",
"signal",
"there",
"is",
"a",
"dropdown",
"containing",
"all",
"the",
"widgets",
"the",
"user",
"will",
"select",
"the",
"widget",
"that",
"have",
"to",
"listen... | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/editor/editor_widgets.py#L183-L206 | train | 214,350 |
dddomodossola/remi | editor/editor_widgets.py | ProjectConfigurationDialog.confirm_dialog | def confirm_dialog(self, emitter):
"""event called pressing on OK button.
"""
#here the user input is transferred to the dict, ready to use
self.from_fields_to_dict()
return super(ProjectConfigurationDialog,self).confirm_dialog(self) | python | def confirm_dialog(self, emitter):
"""event called pressing on OK button.
"""
#here the user input is transferred to the dict, ready to use
self.from_fields_to_dict()
return super(ProjectConfigurationDialog,self).confirm_dialog(self) | [
"def",
"confirm_dialog",
"(",
"self",
",",
"emitter",
")",
":",
"#here the user input is transferred to the dict, ready to use",
"self",
".",
"from_fields_to_dict",
"(",
")",
"return",
"super",
"(",
"ProjectConfigurationDialog",
",",
"self",
")",
".",
"confirm_dialog",
... | event called pressing on OK button. | [
"event",
"called",
"pressing",
"on",
"OK",
"button",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/editor/editor_widgets.py#L256-L261 | train | 214,351 |
dddomodossola/remi | editor/editor_widgets.py | ProjectConfigurationDialog.show | def show(self, baseAppInstance):
"""Allows to show the widget as root window"""
self.from_dict_to_fields(self.configDict)
super(ProjectConfigurationDialog, self).show(baseAppInstance) | python | def show(self, baseAppInstance):
"""Allows to show the widget as root window"""
self.from_dict_to_fields(self.configDict)
super(ProjectConfigurationDialog, self).show(baseAppInstance) | [
"def",
"show",
"(",
"self",
",",
"baseAppInstance",
")",
":",
"self",
".",
"from_dict_to_fields",
"(",
"self",
".",
"configDict",
")",
"super",
"(",
"ProjectConfigurationDialog",
",",
"self",
")",
".",
"show",
"(",
"baseAppInstance",
")"
] | Allows to show the widget as root window | [
"Allows",
"to",
"show",
"the",
"widget",
"as",
"root",
"window"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/editor/editor_widgets.py#L263-L266 | train | 214,352 |
dddomodossola/remi | editor/editor_widgets.py | CssSizeInput.set_value | def set_value(self, value):
"""The value have to be in the form '10px' or '10%', so numeric value plus measure unit
"""
v = 0
measure_unit = 'px'
try:
v = int(float(value.replace('px', '')))
except ValueError:
try:
v = int(float(value.replace('%', '')))
measure_unit = '%'
except ValueError:
pass
self.numInput.set_value(v)
self.dropMeasureUnit.set_value(measure_unit) | python | def set_value(self, value):
"""The value have to be in the form '10px' or '10%', so numeric value plus measure unit
"""
v = 0
measure_unit = 'px'
try:
v = int(float(value.replace('px', '')))
except ValueError:
try:
v = int(float(value.replace('%', '')))
measure_unit = '%'
except ValueError:
pass
self.numInput.set_value(v)
self.dropMeasureUnit.set_value(measure_unit) | [
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"v",
"=",
"0",
"measure_unit",
"=",
"'px'",
"try",
":",
"v",
"=",
"int",
"(",
"float",
"(",
"value",
".",
"replace",
"(",
"'px'",
",",
"''",
")",
")",
")",
"except",
"ValueError",
":",
"try... | The value have to be in the form '10px' or '10%', so numeric value plus measure unit | [
"The",
"value",
"have",
"to",
"be",
"in",
"the",
"form",
"10px",
"or",
"10%",
"so",
"numeric",
"value",
"plus",
"measure",
"unit"
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/editor/editor_widgets.py#L629-L643 | train | 214,353 |
dddomodossola/remi | examples/examples_from_contributors/remi_ext.py | SingleRowSelectionTable.on_table_row_click | def on_table_row_click(self, row, item):
''' Highlight selected row.'''
if hasattr(self, "last_clicked_row"):
del self.last_clicked_row.style['outline']
self.last_clicked_row = row
self.last_clicked_row.style['outline'] = "2px dotted blue"
return (row, item) | python | def on_table_row_click(self, row, item):
''' Highlight selected row.'''
if hasattr(self, "last_clicked_row"):
del self.last_clicked_row.style['outline']
self.last_clicked_row = row
self.last_clicked_row.style['outline'] = "2px dotted blue"
return (row, item) | [
"def",
"on_table_row_click",
"(",
"self",
",",
"row",
",",
"item",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"last_clicked_row\"",
")",
":",
"del",
"self",
".",
"last_clicked_row",
".",
"style",
"[",
"'outline'",
"]",
"self",
".",
"last_clicked_row",
... | Highlight selected row. | [
"Highlight",
"selected",
"row",
"."
] | 85206f62220662bb7ecd471042268def71ccad28 | https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/examples/examples_from_contributors/remi_ext.py#L11-L17 | train | 214,354 |
RaRe-Technologies/smart_open | smart_open/doctools.py | extract_kwargs | def extract_kwargs(docstring):
"""Extract keyword argument documentation from a function's docstring.
Parameters
----------
docstring: str
The docstring to extract keyword arguments from.
Returns
-------
list of (str, str, list str)
str
The name of the keyword argument.
str
Its type.
str
Its documentation as a list of lines.
Notes
-----
The implementation is rather fragile. It expects the following:
1. The parameters are under an underlined Parameters section
2. Keyword parameters have the literal ", optional" after the type
3. Names and types are not indented
4. Descriptions are indented with 4 spaces
5. The Parameters section ends with an empty line.
Examples
--------
>>> docstring = '''The foo function.
... Parameters
... ----------
... bar: str, optional
... This parameter is the bar.
... baz: int, optional
... This parameter is the baz.
...
... '''
>>> kwargs = extract_kwargs(docstring)
>>> kwargs[0]
('bar', 'str, optional', ['This parameter is the bar.'])
"""
lines = inspect.cleandoc(docstring).split('\n')
retval = []
#
# 1. Find the underlined 'Parameters' section
# 2. Once there, continue parsing parameters until we hit an empty line
#
while lines[0] != 'Parameters':
lines.pop(0)
lines.pop(0)
lines.pop(0)
while lines and lines[0]:
name, type_ = lines.pop(0).split(':', 1)
description = []
while lines and lines[0].startswith(' '):
description.append(lines.pop(0).strip())
if 'optional' in type_:
retval.append((name.strip(), type_.strip(), description))
return retval | python | def extract_kwargs(docstring):
"""Extract keyword argument documentation from a function's docstring.
Parameters
----------
docstring: str
The docstring to extract keyword arguments from.
Returns
-------
list of (str, str, list str)
str
The name of the keyword argument.
str
Its type.
str
Its documentation as a list of lines.
Notes
-----
The implementation is rather fragile. It expects the following:
1. The parameters are under an underlined Parameters section
2. Keyword parameters have the literal ", optional" after the type
3. Names and types are not indented
4. Descriptions are indented with 4 spaces
5. The Parameters section ends with an empty line.
Examples
--------
>>> docstring = '''The foo function.
... Parameters
... ----------
... bar: str, optional
... This parameter is the bar.
... baz: int, optional
... This parameter is the baz.
...
... '''
>>> kwargs = extract_kwargs(docstring)
>>> kwargs[0]
('bar', 'str, optional', ['This parameter is the bar.'])
"""
lines = inspect.cleandoc(docstring).split('\n')
retval = []
#
# 1. Find the underlined 'Parameters' section
# 2. Once there, continue parsing parameters until we hit an empty line
#
while lines[0] != 'Parameters':
lines.pop(0)
lines.pop(0)
lines.pop(0)
while lines and lines[0]:
name, type_ = lines.pop(0).split(':', 1)
description = []
while lines and lines[0].startswith(' '):
description.append(lines.pop(0).strip())
if 'optional' in type_:
retval.append((name.strip(), type_.strip(), description))
return retval | [
"def",
"extract_kwargs",
"(",
"docstring",
")",
":",
"lines",
"=",
"inspect",
".",
"cleandoc",
"(",
"docstring",
")",
".",
"split",
"(",
"'\\n'",
")",
"retval",
"=",
"[",
"]",
"#",
"# 1. Find the underlined 'Parameters' section",
"# 2. Once there, continue parsing p... | Extract keyword argument documentation from a function's docstring.
Parameters
----------
docstring: str
The docstring to extract keyword arguments from.
Returns
-------
list of (str, str, list str)
str
The name of the keyword argument.
str
Its type.
str
Its documentation as a list of lines.
Notes
-----
The implementation is rather fragile. It expects the following:
1. The parameters are under an underlined Parameters section
2. Keyword parameters have the literal ", optional" after the type
3. Names and types are not indented
4. Descriptions are indented with 4 spaces
5. The Parameters section ends with an empty line.
Examples
--------
>>> docstring = '''The foo function.
... Parameters
... ----------
... bar: str, optional
... This parameter is the bar.
... baz: int, optional
... This parameter is the baz.
...
... '''
>>> kwargs = extract_kwargs(docstring)
>>> kwargs[0]
('bar', 'str, optional', ['This parameter is the bar.']) | [
"Extract",
"keyword",
"argument",
"documentation",
"from",
"a",
"function",
"s",
"docstring",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/doctools.py#L20-L86 | train | 214,355 |
RaRe-Technologies/smart_open | smart_open/doctools.py | to_docstring | def to_docstring(kwargs, lpad=''):
"""Reconstruct a docstring from keyword argument info.
Basically reverses :func:`extract_kwargs`.
Parameters
----------
kwargs: list
Output from the extract_kwargs function
lpad: str, optional
Padding string (from the left).
Returns
-------
str
The docstring snippet documenting the keyword arguments.
Examples
--------
>>> kwargs = [
... ('bar', 'str, optional', ['This parameter is the bar.']),
... ('baz', 'int, optional', ['This parameter is the baz.']),
... ]
>>> print(to_docstring(kwargs), end='')
bar: str, optional
This parameter is the bar.
baz: int, optional
This parameter is the baz.
"""
buf = io.StringIO()
for name, type_, description in kwargs:
buf.write('%s%s: %s\n' % (lpad, name, type_))
for line in description:
buf.write('%s %s\n' % (lpad, line))
return buf.getvalue() | python | def to_docstring(kwargs, lpad=''):
"""Reconstruct a docstring from keyword argument info.
Basically reverses :func:`extract_kwargs`.
Parameters
----------
kwargs: list
Output from the extract_kwargs function
lpad: str, optional
Padding string (from the left).
Returns
-------
str
The docstring snippet documenting the keyword arguments.
Examples
--------
>>> kwargs = [
... ('bar', 'str, optional', ['This parameter is the bar.']),
... ('baz', 'int, optional', ['This parameter is the baz.']),
... ]
>>> print(to_docstring(kwargs), end='')
bar: str, optional
This parameter is the bar.
baz: int, optional
This parameter is the baz.
"""
buf = io.StringIO()
for name, type_, description in kwargs:
buf.write('%s%s: %s\n' % (lpad, name, type_))
for line in description:
buf.write('%s %s\n' % (lpad, line))
return buf.getvalue() | [
"def",
"to_docstring",
"(",
"kwargs",
",",
"lpad",
"=",
"''",
")",
":",
"buf",
"=",
"io",
".",
"StringIO",
"(",
")",
"for",
"name",
",",
"type_",
",",
"description",
"in",
"kwargs",
":",
"buf",
".",
"write",
"(",
"'%s%s: %s\\n'",
"%",
"(",
"lpad",
... | Reconstruct a docstring from keyword argument info.
Basically reverses :func:`extract_kwargs`.
Parameters
----------
kwargs: list
Output from the extract_kwargs function
lpad: str, optional
Padding string (from the left).
Returns
-------
str
The docstring snippet documenting the keyword arguments.
Examples
--------
>>> kwargs = [
... ('bar', 'str, optional', ['This parameter is the bar.']),
... ('baz', 'int, optional', ['This parameter is the baz.']),
... ]
>>> print(to_docstring(kwargs), end='')
bar: str, optional
This parameter is the bar.
baz: int, optional
This parameter is the baz. | [
"Reconstruct",
"a",
"docstring",
"from",
"keyword",
"argument",
"info",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/doctools.py#L89-L125 | train | 214,356 |
RaRe-Technologies/smart_open | smart_open/doctools.py | extract_examples_from_readme_rst | def extract_examples_from_readme_rst(indent=' '):
"""Extract examples from this project's README.rst file.
Parameters
----------
indent: str
Prepend each line with this string. Should contain some number of spaces.
Returns
-------
str
The examples.
Notes
-----
Quite fragile, depends on named labels inside the README.rst file.
"""
curr_dir = os.path.dirname(os.path.abspath(__file__))
readme_path = os.path.join(curr_dir, '..', 'README.rst')
try:
with open(readme_path) as fin:
lines = list(fin)
start = lines.index('.. _doctools_before_examples:\n')
end = lines.index(".. _doctools_after_examples:\n")
lines = lines[start+4:end-2]
return ''.join([indent + re.sub('^ ', '', l) for l in lines])
except Exception:
return indent + 'See README.rst' | python | def extract_examples_from_readme_rst(indent=' '):
"""Extract examples from this project's README.rst file.
Parameters
----------
indent: str
Prepend each line with this string. Should contain some number of spaces.
Returns
-------
str
The examples.
Notes
-----
Quite fragile, depends on named labels inside the README.rst file.
"""
curr_dir = os.path.dirname(os.path.abspath(__file__))
readme_path = os.path.join(curr_dir, '..', 'README.rst')
try:
with open(readme_path) as fin:
lines = list(fin)
start = lines.index('.. _doctools_before_examples:\n')
end = lines.index(".. _doctools_after_examples:\n")
lines = lines[start+4:end-2]
return ''.join([indent + re.sub('^ ', '', l) for l in lines])
except Exception:
return indent + 'See README.rst' | [
"def",
"extract_examples_from_readme_rst",
"(",
"indent",
"=",
"' '",
")",
":",
"curr_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"readme_path",
"=",
"os",
".",
"path",
".",
"join",
... | Extract examples from this project's README.rst file.
Parameters
----------
indent: str
Prepend each line with this string. Should contain some number of spaces.
Returns
-------
str
The examples.
Notes
-----
Quite fragile, depends on named labels inside the README.rst file. | [
"Extract",
"examples",
"from",
"this",
"project",
"s",
"README",
".",
"rst",
"file",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/doctools.py#L128-L155 | train | 214,357 |
RaRe-Technologies/smart_open | smart_open/s3.py | open | def open(
bucket_id,
key_id,
mode,
buffer_size=DEFAULT_BUFFER_SIZE,
min_part_size=DEFAULT_MIN_PART_SIZE,
session=None,
resource_kwargs=None,
multipart_upload_kwargs=None,
):
"""Open an S3 object for reading or writing.
Parameters
----------
bucket_id: str
The name of the bucket this object resides in.
key_id: str
The name of the key within the bucket.
mode: str
The mode for opening the object. Must be either "rb" or "wb".
buffer_size: int, optional
The buffer size to use when performing I/O.
min_part_size: int, optional
The minimum part size for multipart uploads. For writing only.
session: object, optional
The S3 session to use when working with boto3.
resource_kwargs: dict, optional
Keyword arguments to use when accessing the S3 resource for reading or writing.
multipart_upload_kwargs: dict, optional
Additional parameters to pass to boto3's initiate_multipart_upload function.
For writing only.
"""
logger.debug('%r', locals())
if mode not in MODES:
raise NotImplementedError('bad mode: %r expected one of %r' % (mode, MODES))
if resource_kwargs is None:
resource_kwargs = {}
if multipart_upload_kwargs is None:
multipart_upload_kwargs = {}
if mode == READ_BINARY:
fileobj = SeekableBufferedInputBase(
bucket_id,
key_id,
buffer_size=buffer_size,
session=session,
resource_kwargs=resource_kwargs,
)
elif mode == WRITE_BINARY:
fileobj = BufferedOutputBase(
bucket_id,
key_id,
min_part_size=min_part_size,
session=session,
multipart_upload_kwargs=multipart_upload_kwargs,
resource_kwargs=resource_kwargs,
)
else:
assert False, 'unexpected mode: %r' % mode
return fileobj | python | def open(
bucket_id,
key_id,
mode,
buffer_size=DEFAULT_BUFFER_SIZE,
min_part_size=DEFAULT_MIN_PART_SIZE,
session=None,
resource_kwargs=None,
multipart_upload_kwargs=None,
):
"""Open an S3 object for reading or writing.
Parameters
----------
bucket_id: str
The name of the bucket this object resides in.
key_id: str
The name of the key within the bucket.
mode: str
The mode for opening the object. Must be either "rb" or "wb".
buffer_size: int, optional
The buffer size to use when performing I/O.
min_part_size: int, optional
The minimum part size for multipart uploads. For writing only.
session: object, optional
The S3 session to use when working with boto3.
resource_kwargs: dict, optional
Keyword arguments to use when accessing the S3 resource for reading or writing.
multipart_upload_kwargs: dict, optional
Additional parameters to pass to boto3's initiate_multipart_upload function.
For writing only.
"""
logger.debug('%r', locals())
if mode not in MODES:
raise NotImplementedError('bad mode: %r expected one of %r' % (mode, MODES))
if resource_kwargs is None:
resource_kwargs = {}
if multipart_upload_kwargs is None:
multipart_upload_kwargs = {}
if mode == READ_BINARY:
fileobj = SeekableBufferedInputBase(
bucket_id,
key_id,
buffer_size=buffer_size,
session=session,
resource_kwargs=resource_kwargs,
)
elif mode == WRITE_BINARY:
fileobj = BufferedOutputBase(
bucket_id,
key_id,
min_part_size=min_part_size,
session=session,
multipart_upload_kwargs=multipart_upload_kwargs,
resource_kwargs=resource_kwargs,
)
else:
assert False, 'unexpected mode: %r' % mode
return fileobj | [
"def",
"open",
"(",
"bucket_id",
",",
"key_id",
",",
"mode",
",",
"buffer_size",
"=",
"DEFAULT_BUFFER_SIZE",
",",
"min_part_size",
"=",
"DEFAULT_MIN_PART_SIZE",
",",
"session",
"=",
"None",
",",
"resource_kwargs",
"=",
"None",
",",
"multipart_upload_kwargs",
"=",
... | Open an S3 object for reading or writing.
Parameters
----------
bucket_id: str
The name of the bucket this object resides in.
key_id: str
The name of the key within the bucket.
mode: str
The mode for opening the object. Must be either "rb" or "wb".
buffer_size: int, optional
The buffer size to use when performing I/O.
min_part_size: int, optional
The minimum part size for multipart uploads. For writing only.
session: object, optional
The S3 session to use when working with boto3.
resource_kwargs: dict, optional
Keyword arguments to use when accessing the S3 resource for reading or writing.
multipart_upload_kwargs: dict, optional
Additional parameters to pass to boto3's initiate_multipart_upload function.
For writing only. | [
"Open",
"an",
"S3",
"object",
"for",
"reading",
"or",
"writing",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/s3.py#L69-L131 | train | 214,358 |
RaRe-Technologies/smart_open | smart_open/s3.py | BufferedInputBase.read | def read(self, size=-1):
"""Read up to size bytes from the object and return them."""
if size == 0:
return b''
elif size < 0:
from_buf = self._read_from_buffer()
self._current_pos = self._content_length
return from_buf + self._raw_reader.read()
#
# Return unused data first
#
if len(self._buffer) >= size:
return self._read_from_buffer(size)
#
# If the stream is finished, return what we have.
#
if self._eof:
return self._read_from_buffer()
#
# Fill our buffer to the required size.
#
# logger.debug('filling %r byte-long buffer up to %r bytes', len(self._buffer), size)
self._fill_buffer(size)
return self._read_from_buffer(size) | python | def read(self, size=-1):
"""Read up to size bytes from the object and return them."""
if size == 0:
return b''
elif size < 0:
from_buf = self._read_from_buffer()
self._current_pos = self._content_length
return from_buf + self._raw_reader.read()
#
# Return unused data first
#
if len(self._buffer) >= size:
return self._read_from_buffer(size)
#
# If the stream is finished, return what we have.
#
if self._eof:
return self._read_from_buffer()
#
# Fill our buffer to the required size.
#
# logger.debug('filling %r byte-long buffer up to %r bytes', len(self._buffer), size)
self._fill_buffer(size)
return self._read_from_buffer(size) | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"==",
"0",
":",
"return",
"b''",
"elif",
"size",
"<",
"0",
":",
"from_buf",
"=",
"self",
".",
"_read_from_buffer",
"(",
")",
"self",
".",
"_current_pos",
"=",
"self",
... | Read up to size bytes from the object and return them. | [
"Read",
"up",
"to",
"size",
"bytes",
"from",
"the",
"object",
"and",
"return",
"them",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/s3.py#L240-L266 | train | 214,359 |
RaRe-Technologies/smart_open | smart_open/s3.py | BufferedInputBase.readline | def readline(self, limit=-1):
"""Read up to and including the next newline. Returns the bytes read."""
if limit != -1:
raise NotImplementedError('limits other than -1 not implemented yet')
the_line = io.BytesIO()
while not (self._eof and len(self._buffer) == 0):
#
# In the worst case, we're reading the unread part of self._buffer
# twice here, once in the if condition and once when calling index.
#
# This is sub-optimal, but better than the alternative: wrapping
# .index in a try..except, because that is slower.
#
remaining_buffer = self._buffer.peek()
if self._line_terminator in remaining_buffer:
next_newline = remaining_buffer.index(self._line_terminator)
the_line.write(self._read_from_buffer(next_newline + 1))
break
else:
the_line.write(self._read_from_buffer())
self._fill_buffer()
return the_line.getvalue() | python | def readline(self, limit=-1):
"""Read up to and including the next newline. Returns the bytes read."""
if limit != -1:
raise NotImplementedError('limits other than -1 not implemented yet')
the_line = io.BytesIO()
while not (self._eof and len(self._buffer) == 0):
#
# In the worst case, we're reading the unread part of self._buffer
# twice here, once in the if condition and once when calling index.
#
# This is sub-optimal, but better than the alternative: wrapping
# .index in a try..except, because that is slower.
#
remaining_buffer = self._buffer.peek()
if self._line_terminator in remaining_buffer:
next_newline = remaining_buffer.index(self._line_terminator)
the_line.write(self._read_from_buffer(next_newline + 1))
break
else:
the_line.write(self._read_from_buffer())
self._fill_buffer()
return the_line.getvalue() | [
"def",
"readline",
"(",
"self",
",",
"limit",
"=",
"-",
"1",
")",
":",
"if",
"limit",
"!=",
"-",
"1",
":",
"raise",
"NotImplementedError",
"(",
"'limits other than -1 not implemented yet'",
")",
"the_line",
"=",
"io",
".",
"BytesIO",
"(",
")",
"while",
"no... | Read up to and including the next newline. Returns the bytes read. | [
"Read",
"up",
"to",
"and",
"including",
"the",
"next",
"newline",
".",
"Returns",
"the",
"bytes",
"read",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/s3.py#L281-L302 | train | 214,360 |
RaRe-Technologies/smart_open | smart_open/s3.py | BufferedInputBase._read_from_buffer | def _read_from_buffer(self, size=-1):
"""Remove at most size bytes from our buffer and return them."""
# logger.debug('reading %r bytes from %r byte-long buffer', size, len(self._buffer))
size = size if size >= 0 else len(self._buffer)
part = self._buffer.read(size)
self._current_pos += len(part)
# logger.debug('part: %r', part)
return part | python | def _read_from_buffer(self, size=-1):
"""Remove at most size bytes from our buffer and return them."""
# logger.debug('reading %r bytes from %r byte-long buffer', size, len(self._buffer))
size = size if size >= 0 else len(self._buffer)
part = self._buffer.read(size)
self._current_pos += len(part)
# logger.debug('part: %r', part)
return part | [
"def",
"_read_from_buffer",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"# logger.debug('reading %r bytes from %r byte-long buffer', size, len(self._buffer))",
"size",
"=",
"size",
"if",
"size",
">=",
"0",
"else",
"len",
"(",
"self",
".",
"_buffer",
")",
"p... | Remove at most size bytes from our buffer and return them. | [
"Remove",
"at",
"most",
"size",
"bytes",
"from",
"our",
"buffer",
"and",
"return",
"them",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/s3.py#L311-L318 | train | 214,361 |
RaRe-Technologies/smart_open | smart_open/ssh.py | open | def open(path, mode='r', host=None, user=None, port=DEFAULT_PORT):
"""Open a file on a remote machine over SSH.
Expects authentication to be already set up via existing keys on the local machine.
Parameters
----------
path: str
The path to the file to open on the remote machine.
mode: str, optional
The mode to use for opening the file.
host: str, optional
The hostname of the remote machine. May not be None.
user: str, optional
The username to use to login to the remote machine.
If None, defaults to the name of the current user.
port: int, optional
The port to connect to.
Returns
-------
A file-like object.
Important
---------
If you specify a previously unseen host, then its host key will be added to
the local ~/.ssh/known_hosts *automatically*.
"""
if not host:
raise ValueError('you must specify the host to connect to')
if not user:
user = getpass.getuser()
conn = _connect(host, user, port)
sftp_client = conn.get_transport().open_sftp_client()
return sftp_client.open(path, mode) | python | def open(path, mode='r', host=None, user=None, port=DEFAULT_PORT):
"""Open a file on a remote machine over SSH.
Expects authentication to be already set up via existing keys on the local machine.
Parameters
----------
path: str
The path to the file to open on the remote machine.
mode: str, optional
The mode to use for opening the file.
host: str, optional
The hostname of the remote machine. May not be None.
user: str, optional
The username to use to login to the remote machine.
If None, defaults to the name of the current user.
port: int, optional
The port to connect to.
Returns
-------
A file-like object.
Important
---------
If you specify a previously unseen host, then its host key will be added to
the local ~/.ssh/known_hosts *automatically*.
"""
if not host:
raise ValueError('you must specify the host to connect to')
if not user:
user = getpass.getuser()
conn = _connect(host, user, port)
sftp_client = conn.get_transport().open_sftp_client()
return sftp_client.open(path, mode) | [
"def",
"open",
"(",
"path",
",",
"mode",
"=",
"'r'",
",",
"host",
"=",
"None",
",",
"user",
"=",
"None",
",",
"port",
"=",
"DEFAULT_PORT",
")",
":",
"if",
"not",
"host",
":",
"raise",
"ValueError",
"(",
"'you must specify the host to connect to'",
")",
"... | Open a file on a remote machine over SSH.
Expects authentication to be already set up via existing keys on the local machine.
Parameters
----------
path: str
The path to the file to open on the remote machine.
mode: str, optional
The mode to use for opening the file.
host: str, optional
The hostname of the remote machine. May not be None.
user: str, optional
The username to use to login to the remote machine.
If None, defaults to the name of the current user.
port: int, optional
The port to connect to.
Returns
-------
A file-like object.
Important
---------
If you specify a previously unseen host, then its host key will be added to
the local ~/.ssh/known_hosts *automatically*. | [
"Open",
"a",
"file",
"on",
"a",
"remote",
"machine",
"over",
"SSH",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/ssh.py#L62-L97 | train | 214,362 |
RaRe-Technologies/smart_open | smart_open/http.py | open | def open(uri, mode, kerberos=False, user=None, password=None):
"""Implement streamed reader from a web site.
Supports Kerberos and Basic HTTP authentication.
Parameters
----------
url: str
The URL to open.
mode: str
The mode to open using.
kerberos: boolean, optional
If True, will attempt to use the local Kerberos credentials
user: str, optional
The username for authenticating over HTTP
password: str, optional
The password for authenticating over HTTP
Note
----
If neither kerberos or (user, password) are set, will connect unauthenticated.
"""
if mode == 'rb':
return BufferedInputBase(uri, mode, kerberos=kerberos, user=user, password=password)
else:
raise NotImplementedError('http support for mode %r not implemented' % mode) | python | def open(uri, mode, kerberos=False, user=None, password=None):
"""Implement streamed reader from a web site.
Supports Kerberos and Basic HTTP authentication.
Parameters
----------
url: str
The URL to open.
mode: str
The mode to open using.
kerberos: boolean, optional
If True, will attempt to use the local Kerberos credentials
user: str, optional
The username for authenticating over HTTP
password: str, optional
The password for authenticating over HTTP
Note
----
If neither kerberos or (user, password) are set, will connect unauthenticated.
"""
if mode == 'rb':
return BufferedInputBase(uri, mode, kerberos=kerberos, user=user, password=password)
else:
raise NotImplementedError('http support for mode %r not implemented' % mode) | [
"def",
"open",
"(",
"uri",
",",
"mode",
",",
"kerberos",
"=",
"False",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"mode",
"==",
"'rb'",
":",
"return",
"BufferedInputBase",
"(",
"uri",
",",
"mode",
",",
"kerberos",
"=",
... | Implement streamed reader from a web site.
Supports Kerberos and Basic HTTP authentication.
Parameters
----------
url: str
The URL to open.
mode: str
The mode to open using.
kerberos: boolean, optional
If True, will attempt to use the local Kerberos credentials
user: str, optional
The username for authenticating over HTTP
password: str, optional
The password for authenticating over HTTP
Note
----
If neither kerberos or (user, password) are set, will connect unauthenticated. | [
"Implement",
"streamed",
"reader",
"from",
"a",
"web",
"site",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/http.py#L25-L51 | train | 214,363 |
RaRe-Technologies/smart_open | smart_open/http.py | BufferedInputBase.read | def read(self, size=-1):
"""
Mimics the read call to a filehandle object.
"""
logger.debug("reading with size: %d", size)
if self.response is None:
return b''
if size == 0:
return b''
elif size < 0 and len(self._read_buffer) == 0:
retval = self.response.raw.read()
elif size < 0:
retval = self._read_buffer.read() + self.response.raw.read()
else:
while len(self._read_buffer) < size:
logger.debug("http reading more content at current_pos: %d with size: %d", self._current_pos, size)
bytes_read = self._read_buffer.fill(self._read_iter)
if bytes_read == 0:
# Oops, ran out of data early.
retval = self._read_buffer.read()
self._current_pos += len(retval)
return retval
# If we got here, it means we have enough data in the buffer
# to return to the caller.
retval = self._read_buffer.read(size)
self._current_pos += len(retval)
return retval | python | def read(self, size=-1):
"""
Mimics the read call to a filehandle object.
"""
logger.debug("reading with size: %d", size)
if self.response is None:
return b''
if size == 0:
return b''
elif size < 0 and len(self._read_buffer) == 0:
retval = self.response.raw.read()
elif size < 0:
retval = self._read_buffer.read() + self.response.raw.read()
else:
while len(self._read_buffer) < size:
logger.debug("http reading more content at current_pos: %d with size: %d", self._current_pos, size)
bytes_read = self._read_buffer.fill(self._read_iter)
if bytes_read == 0:
# Oops, ran out of data early.
retval = self._read_buffer.read()
self._current_pos += len(retval)
return retval
# If we got here, it means we have enough data in the buffer
# to return to the caller.
retval = self._read_buffer.read(size)
self._current_pos += len(retval)
return retval | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"logger",
".",
"debug",
"(",
"\"reading with size: %d\"",
",",
"size",
")",
"if",
"self",
".",
"response",
"is",
"None",
":",
"return",
"b''",
"if",
"size",
"==",
"0",
":",
"return",
... | Mimics the read call to a filehandle object. | [
"Mimics",
"the",
"read",
"call",
"to",
"a",
"filehandle",
"object",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/http.py#L104-L134 | train | 214,364 |
RaRe-Technologies/smart_open | smart_open/bytebuffer.py | ByteBuffer.read | def read(self, size=-1):
"""Read bytes from the buffer and advance the read position. Returns
the bytes in a bytestring.
Parameters
----------
size: int, optional
Maximum number of bytes to read. If negative or not supplied, read
all unread bytes in the buffer.
Returns
-------
bytes
"""
part = self.peek(size)
self._pos += len(part)
return part | python | def read(self, size=-1):
"""Read bytes from the buffer and advance the read position. Returns
the bytes in a bytestring.
Parameters
----------
size: int, optional
Maximum number of bytes to read. If negative or not supplied, read
all unread bytes in the buffer.
Returns
-------
bytes
"""
part = self.peek(size)
self._pos += len(part)
return part | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"part",
"=",
"self",
".",
"peek",
"(",
"size",
")",
"self",
".",
"_pos",
"+=",
"len",
"(",
"part",
")",
"return",
"part"
] | Read bytes from the buffer and advance the read position. Returns
the bytes in a bytestring.
Parameters
----------
size: int, optional
Maximum number of bytes to read. If negative or not supplied, read
all unread bytes in the buffer.
Returns
-------
bytes | [
"Read",
"bytes",
"from",
"the",
"buffer",
"and",
"advance",
"the",
"read",
"position",
".",
"Returns",
"the",
"bytes",
"in",
"a",
"bytestring",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/bytebuffer.py#L67-L83 | train | 214,365 |
RaRe-Technologies/smart_open | smart_open/bytebuffer.py | ByteBuffer.peek | def peek(self, size=-1):
"""Get bytes from the buffer without advancing the read position.
Returns the bytes in a bytestring.
Parameters
----------
size: int, optional
Maximum number of bytes to return. If negative or not supplied,
return all unread bytes in the buffer.
Returns
-------
bytes
"""
if size < 0 or size > len(self):
size = len(self)
part = self._bytes[self._pos:self._pos+size]
return part | python | def peek(self, size=-1):
"""Get bytes from the buffer without advancing the read position.
Returns the bytes in a bytestring.
Parameters
----------
size: int, optional
Maximum number of bytes to return. If negative or not supplied,
return all unread bytes in the buffer.
Returns
-------
bytes
"""
if size < 0 or size > len(self):
size = len(self)
part = self._bytes[self._pos:self._pos+size]
return part | [
"def",
"peek",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"<",
"0",
"or",
"size",
">",
"len",
"(",
"self",
")",
":",
"size",
"=",
"len",
"(",
"self",
")",
"part",
"=",
"self",
".",
"_bytes",
"[",
"self",
".",
"_pos",
"... | Get bytes from the buffer without advancing the read position.
Returns the bytes in a bytestring.
Parameters
----------
size: int, optional
Maximum number of bytes to return. If negative or not supplied,
return all unread bytes in the buffer.
Returns
-------
bytes | [
"Get",
"bytes",
"from",
"the",
"buffer",
"without",
"advancing",
"the",
"read",
"position",
".",
"Returns",
"the",
"bytes",
"in",
"a",
"bytestring",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/bytebuffer.py#L85-L103 | train | 214,366 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | register_compressor | def register_compressor(ext, callback):
"""Register a callback for transparently decompressing files with a specific extension.
Parameters
----------
ext: str
The extension.
callback: callable
The callback. It must accept two position arguments, file_obj and mode.
Examples
--------
Instruct smart_open to use the identity function whenever opening a file
with a .xz extension (see README.rst for the complete example showing I/O):
>>> def _handle_xz(file_obj, mode):
... import lzma
... return lzma.LZMAFile(filename=file_obj, mode=mode, format=lzma.FORMAT_XZ)
>>>
>>> register_compressor('.xz', _handle_xz)
"""
if not (ext and ext[0] == '.'):
raise ValueError('ext must be a string starting with ., not %r' % ext)
if ext in _COMPRESSOR_REGISTRY:
logger.warning('overriding existing compression handler for %r', ext)
_COMPRESSOR_REGISTRY[ext] = callback | python | def register_compressor(ext, callback):
"""Register a callback for transparently decompressing files with a specific extension.
Parameters
----------
ext: str
The extension.
callback: callable
The callback. It must accept two position arguments, file_obj and mode.
Examples
--------
Instruct smart_open to use the identity function whenever opening a file
with a .xz extension (see README.rst for the complete example showing I/O):
>>> def _handle_xz(file_obj, mode):
... import lzma
... return lzma.LZMAFile(filename=file_obj, mode=mode, format=lzma.FORMAT_XZ)
>>>
>>> register_compressor('.xz', _handle_xz)
"""
if not (ext and ext[0] == '.'):
raise ValueError('ext must be a string starting with ., not %r' % ext)
if ext in _COMPRESSOR_REGISTRY:
logger.warning('overriding existing compression handler for %r', ext)
_COMPRESSOR_REGISTRY[ext] = callback | [
"def",
"register_compressor",
"(",
"ext",
",",
"callback",
")",
":",
"if",
"not",
"(",
"ext",
"and",
"ext",
"[",
"0",
"]",
"==",
"'.'",
")",
":",
"raise",
"ValueError",
"(",
"'ext must be a string starting with ., not %r'",
"%",
"ext",
")",
"if",
"ext",
"i... | Register a callback for transparently decompressing files with a specific extension.
Parameters
----------
ext: str
The extension.
callback: callable
The callback. It must accept two position arguments, file_obj and mode.
Examples
--------
Instruct smart_open to use the identity function whenever opening a file
with a .xz extension (see README.rst for the complete example showing I/O):
>>> def _handle_xz(file_obj, mode):
... import lzma
... return lzma.LZMAFile(filename=file_obj, mode=mode, format=lzma.FORMAT_XZ)
>>>
>>> register_compressor('.xz', _handle_xz) | [
"Register",
"a",
"callback",
"for",
"transparently",
"decompressing",
"files",
"with",
"a",
"specific",
"extension",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L70-L97 | train | 214,367 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | _check_kwargs | def _check_kwargs(kallable, kwargs):
"""Check which keyword arguments the callable supports.
Parameters
----------
kallable: callable
A function or method to test
kwargs: dict
The keyword arguments to check. If the callable doesn't support any
of these, a warning message will get printed.
Returns
-------
dict
A dictionary of argument names and values supported by the callable.
"""
supported_keywords = sorted(_inspect_kwargs(kallable))
unsupported_keywords = [k for k in sorted(kwargs) if k not in supported_keywords]
supported_kwargs = {k: v for (k, v) in kwargs.items() if k in supported_keywords}
if unsupported_keywords:
logger.warning('ignoring unsupported keyword arguments: %r', unsupported_keywords)
return supported_kwargs | python | def _check_kwargs(kallable, kwargs):
"""Check which keyword arguments the callable supports.
Parameters
----------
kallable: callable
A function or method to test
kwargs: dict
The keyword arguments to check. If the callable doesn't support any
of these, a warning message will get printed.
Returns
-------
dict
A dictionary of argument names and values supported by the callable.
"""
supported_keywords = sorted(_inspect_kwargs(kallable))
unsupported_keywords = [k for k in sorted(kwargs) if k not in supported_keywords]
supported_kwargs = {k: v for (k, v) in kwargs.items() if k in supported_keywords}
if unsupported_keywords:
logger.warning('ignoring unsupported keyword arguments: %r', unsupported_keywords)
return supported_kwargs | [
"def",
"_check_kwargs",
"(",
"kallable",
",",
"kwargs",
")",
":",
"supported_keywords",
"=",
"sorted",
"(",
"_inspect_kwargs",
"(",
"kallable",
")",
")",
"unsupported_keywords",
"=",
"[",
"k",
"for",
"k",
"in",
"sorted",
"(",
"kwargs",
")",
"if",
"k",
"not... | Check which keyword arguments the callable supports.
Parameters
----------
kallable: callable
A function or method to test
kwargs: dict
The keyword arguments to check. If the callable doesn't support any
of these, a warning message will get printed.
Returns
-------
dict
A dictionary of argument names and values supported by the callable. | [
"Check",
"which",
"keyword",
"arguments",
"the",
"callable",
"supports",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L172-L195 | train | 214,368 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | open | def open(
uri,
mode='r',
buffering=-1,
encoding=None,
errors=None,
newline=None,
closefd=True,
opener=None,
ignore_ext=False,
transport_params=None,
):
r"""Open the URI object, returning a file-like object.
The URI is usually a string in a variety of formats:
1. a URI for the local filesystem: `./lines.txt`, `/home/joe/lines.txt.gz`, `file:///home/joe/lines.txt.bz2`
2. a URI for HDFS: `hdfs:///some/path/lines.txt`
3. a URI for Amazon's S3 (can also supply credentials inside the URI):
`s3://my_bucket/lines.txt`, `s3://my_aws_key_id:key_secret@my_bucket/lines.txt`
The URI may also be one of:
- an instance of the pathlib.Path class
- a stream (anything that implements io.IOBase-like functionality)
This function supports transparent compression and decompression using the
following codec:
- ``.gz``
- ``.bz2``
The function depends on the file extension to determine the appropriate codec.
Parameters
----------
uri: str or object
The object to open.
mode: str, optional
Mimicks built-in open parameter of the same name.
buffering: int, optional
Mimicks built-in open parameter of the same name.
encoding: str, optional
Mimicks built-in open parameter of the same name.
errors: str, optional
Mimicks built-in open parameter of the same name.
newline: str, optional
Mimicks built-in open parameter of the same name.
closefd: boolean, optional
Mimicks built-in open parameter of the same name. Ignored.
opener: object, optional
Mimicks built-in open parameter of the same name. Ignored.
ignore_ext: boolean, optional
Disable transparent compression/decompression based on the file extension.
transport_params: dict, optional
Additional parameters for the transport layer (see notes below).
Returns
-------
A file-like object.
Notes
-----
smart_open has several implementations for its transport layer (e.g. S3, HTTP).
Each transport layer has a different set of keyword arguments for overriding
default behavior. If you specify a keyword argument that is *not* supported
by the transport layer being used, smart_open will ignore that argument and
log a warning message.
S3 (for details, see :mod:`smart_open.s3` and :func:`smart_open.s3.open`):
%(s3)s
HTTP (for details, see :mod:`smart_open.http` and :func:`smart_open.http.open`):
%(http)s
WebHDFS (for details, see :mod:`smart_open.webhdfs` and :func:`smart_open.webhdfs.open`):
%(webhdfs)s
SSH (for details, see :mod:`smart_open.ssh` and :func:`smart_open.ssh.open`):
%(ssh)s
Examples
--------
%(examples)s
See Also
--------
- `Standard library reference <https://docs.python.org/3.7/library/functions.html#open>`__
- `smart_open README.rst <https://github.com/RaRe-Technologies/smart_open/blob/master/README.rst>`__
"""
logger.debug('%r', locals())
if not isinstance(mode, six.string_types):
raise TypeError('mode should be a string')
if transport_params is None:
transport_params = {}
fobj = _shortcut_open(
uri,
mode,
ignore_ext=ignore_ext,
buffering=buffering,
encoding=encoding,
errors=errors,
)
if fobj is not None:
return fobj
#
# This is a work-around for the problem described in Issue #144.
# If the user has explicitly specified an encoding, then assume they want
# us to open the destination in text mode, instead of the default binary.
#
# If we change the default mode to be text, and match the normal behavior
# of Py2 and 3, then the above assumption will be unnecessary.
#
if encoding is not None and 'b' in mode:
mode = mode.replace('b', '')
# Support opening ``pathlib.Path`` objects by casting them to strings.
if PATHLIB_SUPPORT and isinstance(uri, pathlib.Path):
uri = str(uri)
explicit_encoding = encoding
encoding = explicit_encoding if explicit_encoding else SYSTEM_ENCODING
#
# This is how we get from the filename to the end result. Decompression is
# optional, but it always accepts bytes and returns bytes.
#
# Decoding is also optional, accepts bytes and returns text. The diagram
# below is for reading, for writing, the flow is from right to left, but
# the code is identical.
#
# open as binary decompress? decode?
# filename ---------------> bytes -------------> bytes ---------> text
# binary decompressed decode
#
try:
binary_mode = {'r': 'rb', 'r+': 'rb+',
'w': 'wb', 'w+': 'wb+',
'a': 'ab', 'a+': 'ab+'}[mode]
except KeyError:
binary_mode = mode
binary, filename = _open_binary_stream(uri, binary_mode, transport_params)
if ignore_ext:
decompressed = binary
else:
decompressed = _compression_wrapper(binary, filename, mode)
if 'b' not in mode or explicit_encoding is not None:
decoded = _encoding_wrapper(decompressed, mode, encoding=encoding, errors=errors)
else:
decoded = decompressed
return decoded | python | def open(
uri,
mode='r',
buffering=-1,
encoding=None,
errors=None,
newline=None,
closefd=True,
opener=None,
ignore_ext=False,
transport_params=None,
):
r"""Open the URI object, returning a file-like object.
The URI is usually a string in a variety of formats:
1. a URI for the local filesystem: `./lines.txt`, `/home/joe/lines.txt.gz`, `file:///home/joe/lines.txt.bz2`
2. a URI for HDFS: `hdfs:///some/path/lines.txt`
3. a URI for Amazon's S3 (can also supply credentials inside the URI):
`s3://my_bucket/lines.txt`, `s3://my_aws_key_id:key_secret@my_bucket/lines.txt`
The URI may also be one of:
- an instance of the pathlib.Path class
- a stream (anything that implements io.IOBase-like functionality)
This function supports transparent compression and decompression using the
following codec:
- ``.gz``
- ``.bz2``
The function depends on the file extension to determine the appropriate codec.
Parameters
----------
uri: str or object
The object to open.
mode: str, optional
Mimicks built-in open parameter of the same name.
buffering: int, optional
Mimicks built-in open parameter of the same name.
encoding: str, optional
Mimicks built-in open parameter of the same name.
errors: str, optional
Mimicks built-in open parameter of the same name.
newline: str, optional
Mimicks built-in open parameter of the same name.
closefd: boolean, optional
Mimicks built-in open parameter of the same name. Ignored.
opener: object, optional
Mimicks built-in open parameter of the same name. Ignored.
ignore_ext: boolean, optional
Disable transparent compression/decompression based on the file extension.
transport_params: dict, optional
Additional parameters for the transport layer (see notes below).
Returns
-------
A file-like object.
Notes
-----
smart_open has several implementations for its transport layer (e.g. S3, HTTP).
Each transport layer has a different set of keyword arguments for overriding
default behavior. If you specify a keyword argument that is *not* supported
by the transport layer being used, smart_open will ignore that argument and
log a warning message.
S3 (for details, see :mod:`smart_open.s3` and :func:`smart_open.s3.open`):
%(s3)s
HTTP (for details, see :mod:`smart_open.http` and :func:`smart_open.http.open`):
%(http)s
WebHDFS (for details, see :mod:`smart_open.webhdfs` and :func:`smart_open.webhdfs.open`):
%(webhdfs)s
SSH (for details, see :mod:`smart_open.ssh` and :func:`smart_open.ssh.open`):
%(ssh)s
Examples
--------
%(examples)s
See Also
--------
- `Standard library reference <https://docs.python.org/3.7/library/functions.html#open>`__
- `smart_open README.rst <https://github.com/RaRe-Technologies/smart_open/blob/master/README.rst>`__
"""
logger.debug('%r', locals())
if not isinstance(mode, six.string_types):
raise TypeError('mode should be a string')
if transport_params is None:
transport_params = {}
fobj = _shortcut_open(
uri,
mode,
ignore_ext=ignore_ext,
buffering=buffering,
encoding=encoding,
errors=errors,
)
if fobj is not None:
return fobj
#
# This is a work-around for the problem described in Issue #144.
# If the user has explicitly specified an encoding, then assume they want
# us to open the destination in text mode, instead of the default binary.
#
# If we change the default mode to be text, and match the normal behavior
# of Py2 and 3, then the above assumption will be unnecessary.
#
if encoding is not None and 'b' in mode:
mode = mode.replace('b', '')
# Support opening ``pathlib.Path`` objects by casting them to strings.
if PATHLIB_SUPPORT and isinstance(uri, pathlib.Path):
uri = str(uri)
explicit_encoding = encoding
encoding = explicit_encoding if explicit_encoding else SYSTEM_ENCODING
#
# This is how we get from the filename to the end result. Decompression is
# optional, but it always accepts bytes and returns bytes.
#
# Decoding is also optional, accepts bytes and returns text. The diagram
# below is for reading, for writing, the flow is from right to left, but
# the code is identical.
#
# open as binary decompress? decode?
# filename ---------------> bytes -------------> bytes ---------> text
# binary decompressed decode
#
try:
binary_mode = {'r': 'rb', 'r+': 'rb+',
'w': 'wb', 'w+': 'wb+',
'a': 'ab', 'a+': 'ab+'}[mode]
except KeyError:
binary_mode = mode
binary, filename = _open_binary_stream(uri, binary_mode, transport_params)
if ignore_ext:
decompressed = binary
else:
decompressed = _compression_wrapper(binary, filename, mode)
if 'b' not in mode or explicit_encoding is not None:
decoded = _encoding_wrapper(decompressed, mode, encoding=encoding, errors=errors)
else:
decoded = decompressed
return decoded | [
"def",
"open",
"(",
"uri",
",",
"mode",
"=",
"'r'",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
",",
"closefd",
"=",
"True",
",",
"opener",
"=",
"None",
",",
"ignore_ext",
... | r"""Open the URI object, returning a file-like object.
The URI is usually a string in a variety of formats:
1. a URI for the local filesystem: `./lines.txt`, `/home/joe/lines.txt.gz`, `file:///home/joe/lines.txt.bz2`
2. a URI for HDFS: `hdfs:///some/path/lines.txt`
3. a URI for Amazon's S3 (can also supply credentials inside the URI):
`s3://my_bucket/lines.txt`, `s3://my_aws_key_id:key_secret@my_bucket/lines.txt`
The URI may also be one of:
- an instance of the pathlib.Path class
- a stream (anything that implements io.IOBase-like functionality)
This function supports transparent compression and decompression using the
following codec:
- ``.gz``
- ``.bz2``
The function depends on the file extension to determine the appropriate codec.
Parameters
----------
uri: str or object
The object to open.
mode: str, optional
Mimicks built-in open parameter of the same name.
buffering: int, optional
Mimicks built-in open parameter of the same name.
encoding: str, optional
Mimicks built-in open parameter of the same name.
errors: str, optional
Mimicks built-in open parameter of the same name.
newline: str, optional
Mimicks built-in open parameter of the same name.
closefd: boolean, optional
Mimicks built-in open parameter of the same name. Ignored.
opener: object, optional
Mimicks built-in open parameter of the same name. Ignored.
ignore_ext: boolean, optional
Disable transparent compression/decompression based on the file extension.
transport_params: dict, optional
Additional parameters for the transport layer (see notes below).
Returns
-------
A file-like object.
Notes
-----
smart_open has several implementations for its transport layer (e.g. S3, HTTP).
Each transport layer has a different set of keyword arguments for overriding
default behavior. If you specify a keyword argument that is *not* supported
by the transport layer being used, smart_open will ignore that argument and
log a warning message.
S3 (for details, see :mod:`smart_open.s3` and :func:`smart_open.s3.open`):
%(s3)s
HTTP (for details, see :mod:`smart_open.http` and :func:`smart_open.http.open`):
%(http)s
WebHDFS (for details, see :mod:`smart_open.webhdfs` and :func:`smart_open.webhdfs.open`):
%(webhdfs)s
SSH (for details, see :mod:`smart_open.ssh` and :func:`smart_open.ssh.open`):
%(ssh)s
Examples
--------
%(examples)s
See Also
--------
- `Standard library reference <https://docs.python.org/3.7/library/functions.html#open>`__
- `smart_open README.rst <https://github.com/RaRe-Technologies/smart_open/blob/master/README.rst>`__ | [
"r",
"Open",
"the",
"URI",
"object",
"returning",
"a",
"file",
"-",
"like",
"object",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L201-L359 | train | 214,369 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | smart_open | def smart_open(uri, mode="rb", **kw):
"""Deprecated, use smart_open.open instead."""
logger.warning('this function is deprecated, use smart_open.open instead')
#
# The new function uses a shorter name for this parameter, handle it separately.
#
ignore_extension = kw.pop('ignore_extension', False)
expected_kwargs = _inspect_kwargs(open)
scrubbed_kwargs = {}
transport_params = {}
#
# Handle renamed keyword arguments. This is required to maintain backward
# compatibility. See test_smart_open_old.py for tests.
#
if 'host' in kw or 's3_upload' in kw:
transport_params['multipart_upload_kwargs'] = {}
transport_params['resource_kwargs'] = {}
if 'host' in kw:
url = kw.pop('host')
if not url.startswith('http'):
url = 'http://' + url
transport_params['resource_kwargs'].update(endpoint_url=url)
if 's3_upload' in kw and kw['s3_upload']:
transport_params['multipart_upload_kwargs'].update(**kw.pop('s3_upload'))
#
# Providing the entire Session object as opposed to just the profile name
# is more flexible and powerful, and thus preferable in the case of
# conflict.
#
if 'profile_name' in kw and 's3_session' in kw:
logger.error('profile_name and s3_session are mutually exclusive, ignoring the former')
if 'profile_name' in kw:
transport_params['session'] = boto3.Session(profile_name=kw.pop('profile_name'))
if 's3_session' in kw:
transport_params['session'] = kw.pop('s3_session')
for key, value in kw.items():
if key in expected_kwargs:
scrubbed_kwargs[key] = value
else:
#
# Assume that anything not explicitly supported by the new function
# is a transport layer keyword argument. This is safe, because if
# the argument ends up being unsupported in the transport layer,
# it will only cause a logging warning, not a crash.
#
transport_params[key] = value
return open(uri, mode, ignore_ext=ignore_extension, transport_params=transport_params, **scrubbed_kwargs) | python | def smart_open(uri, mode="rb", **kw):
"""Deprecated, use smart_open.open instead."""
logger.warning('this function is deprecated, use smart_open.open instead')
#
# The new function uses a shorter name for this parameter, handle it separately.
#
ignore_extension = kw.pop('ignore_extension', False)
expected_kwargs = _inspect_kwargs(open)
scrubbed_kwargs = {}
transport_params = {}
#
# Handle renamed keyword arguments. This is required to maintain backward
# compatibility. See test_smart_open_old.py for tests.
#
if 'host' in kw or 's3_upload' in kw:
transport_params['multipart_upload_kwargs'] = {}
transport_params['resource_kwargs'] = {}
if 'host' in kw:
url = kw.pop('host')
if not url.startswith('http'):
url = 'http://' + url
transport_params['resource_kwargs'].update(endpoint_url=url)
if 's3_upload' in kw and kw['s3_upload']:
transport_params['multipart_upload_kwargs'].update(**kw.pop('s3_upload'))
#
# Providing the entire Session object as opposed to just the profile name
# is more flexible and powerful, and thus preferable in the case of
# conflict.
#
if 'profile_name' in kw and 's3_session' in kw:
logger.error('profile_name and s3_session are mutually exclusive, ignoring the former')
if 'profile_name' in kw:
transport_params['session'] = boto3.Session(profile_name=kw.pop('profile_name'))
if 's3_session' in kw:
transport_params['session'] = kw.pop('s3_session')
for key, value in kw.items():
if key in expected_kwargs:
scrubbed_kwargs[key] = value
else:
#
# Assume that anything not explicitly supported by the new function
# is a transport layer keyword argument. This is safe, because if
# the argument ends up being unsupported in the transport layer,
# it will only cause a logging warning, not a crash.
#
transport_params[key] = value
return open(uri, mode, ignore_ext=ignore_extension, transport_params=transport_params, **scrubbed_kwargs) | [
"def",
"smart_open",
"(",
"uri",
",",
"mode",
"=",
"\"rb\"",
",",
"*",
"*",
"kw",
")",
":",
"logger",
".",
"warning",
"(",
"'this function is deprecated, use smart_open.open instead'",
")",
"#",
"# The new function uses a shorter name for this parameter, handle it separatel... | Deprecated, use smart_open.open instead. | [
"Deprecated",
"use",
"smart_open",
".",
"open",
"instead",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L383-L439 | train | 214,370 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | _shortcut_open | def _shortcut_open(
uri,
mode,
ignore_ext=False,
buffering=-1,
encoding=None,
errors=None,
):
"""Try to open the URI using the standard library io.open function.
This can be much faster than the alternative of opening in binary mode and
then decoding.
This is only possible under the following conditions:
1. Opening a local file
2. Ignore extension is set to True
If it is not possible to use the built-in open for the specified URI, returns None.
:param str uri: A string indicating what to open.
:param str mode: The mode to pass to the open function.
:param dict kw:
:returns: The opened file
:rtype: file
"""
if not isinstance(uri, six.string_types):
return None
parsed_uri = _parse_uri(uri)
if parsed_uri.scheme != 'file':
return None
_, extension = P.splitext(parsed_uri.uri_path)
if extension in _COMPRESSOR_REGISTRY and not ignore_ext:
return None
open_kwargs = {}
if encoding is not None:
open_kwargs['encoding'] = encoding
mode = mode.replace('b', '')
#
# binary mode of the builtin/stdlib open function doesn't take an errors argument
#
if errors and 'b' not in mode:
open_kwargs['errors'] = errors
#
# Under Py3, the built-in open accepts kwargs, and it's OK to use that.
# Under Py2, the built-in open _doesn't_ accept kwargs, but we still use it
# whenever possible (see issue #207). If we're under Py2 and have to use
# kwargs, then we have no option other to use io.open.
#
if six.PY3:
return _builtin_open(parsed_uri.uri_path, mode, buffering=buffering, **open_kwargs)
elif not open_kwargs:
return _builtin_open(parsed_uri.uri_path, mode, buffering=buffering)
return io.open(parsed_uri.uri_path, mode, buffering=buffering, **open_kwargs) | python | def _shortcut_open(
uri,
mode,
ignore_ext=False,
buffering=-1,
encoding=None,
errors=None,
):
"""Try to open the URI using the standard library io.open function.
This can be much faster than the alternative of opening in binary mode and
then decoding.
This is only possible under the following conditions:
1. Opening a local file
2. Ignore extension is set to True
If it is not possible to use the built-in open for the specified URI, returns None.
:param str uri: A string indicating what to open.
:param str mode: The mode to pass to the open function.
:param dict kw:
:returns: The opened file
:rtype: file
"""
if not isinstance(uri, six.string_types):
return None
parsed_uri = _parse_uri(uri)
if parsed_uri.scheme != 'file':
return None
_, extension = P.splitext(parsed_uri.uri_path)
if extension in _COMPRESSOR_REGISTRY and not ignore_ext:
return None
open_kwargs = {}
if encoding is not None:
open_kwargs['encoding'] = encoding
mode = mode.replace('b', '')
#
# binary mode of the builtin/stdlib open function doesn't take an errors argument
#
if errors and 'b' not in mode:
open_kwargs['errors'] = errors
#
# Under Py3, the built-in open accepts kwargs, and it's OK to use that.
# Under Py2, the built-in open _doesn't_ accept kwargs, but we still use it
# whenever possible (see issue #207). If we're under Py2 and have to use
# kwargs, then we have no option other to use io.open.
#
if six.PY3:
return _builtin_open(parsed_uri.uri_path, mode, buffering=buffering, **open_kwargs)
elif not open_kwargs:
return _builtin_open(parsed_uri.uri_path, mode, buffering=buffering)
return io.open(parsed_uri.uri_path, mode, buffering=buffering, **open_kwargs) | [
"def",
"_shortcut_open",
"(",
"uri",
",",
"mode",
",",
"ignore_ext",
"=",
"False",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
")",
":",
"if",
"not",
"isinstance",
"(",
"uri",
",",
"six",
".",
"st... | Try to open the URI using the standard library io.open function.
This can be much faster than the alternative of opening in binary mode and
then decoding.
This is only possible under the following conditions:
1. Opening a local file
2. Ignore extension is set to True
If it is not possible to use the built-in open for the specified URI, returns None.
:param str uri: A string indicating what to open.
:param str mode: The mode to pass to the open function.
:param dict kw:
:returns: The opened file
:rtype: file | [
"Try",
"to",
"open",
"the",
"URI",
"using",
"the",
"standard",
"library",
"io",
".",
"open",
"function",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L442-L501 | train | 214,371 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | _open_binary_stream | def _open_binary_stream(uri, mode, transport_params):
"""Open an arbitrary URI in the specified binary mode.
Not all modes are supported for all protocols.
:arg uri: The URI to open. May be a string, or something else.
:arg str mode: The mode to open with. Must be rb, wb or ab.
:arg transport_params: Keyword argumens for the transport layer.
:returns: A file object and the filename
:rtype: tuple
"""
if mode not in ('rb', 'rb+', 'wb', 'wb+', 'ab', 'ab+'):
#
# This should really be a ValueError, but for the sake of compatibility
# with older versions, which raise NotImplementedError, we do the same.
#
raise NotImplementedError('unsupported mode: %r' % mode)
if isinstance(uri, six.string_types):
# this method just routes the request to classes handling the specific storage
# schemes, depending on the URI protocol in `uri`
filename = uri.split('/')[-1]
parsed_uri = _parse_uri(uri)
unsupported = "%r mode not supported for %r scheme" % (mode, parsed_uri.scheme)
if parsed_uri.scheme == "file":
fobj = io.open(parsed_uri.uri_path, mode)
return fobj, filename
elif parsed_uri.scheme in smart_open_ssh.SCHEMES:
fobj = smart_open_ssh.open(
parsed_uri.uri_path,
mode,
host=parsed_uri.host,
user=parsed_uri.user,
port=parsed_uri.port,
)
return fobj, filename
elif parsed_uri.scheme in smart_open_s3.SUPPORTED_SCHEMES:
return _s3_open_uri(parsed_uri, mode, transport_params), filename
elif parsed_uri.scheme == "hdfs":
_check_kwargs(smart_open_hdfs.open, transport_params)
return smart_open_hdfs.open(parsed_uri.uri_path, mode), filename
elif parsed_uri.scheme == "webhdfs":
kw = _check_kwargs(smart_open_webhdfs.open, transport_params)
return smart_open_webhdfs.open(parsed_uri.uri_path, mode, **kw), filename
elif parsed_uri.scheme.startswith('http'):
#
# The URI may contain a query string and fragments, which interfere
# with our compressed/uncompressed estimation, so we strip them.
#
filename = P.basename(urlparse.urlparse(uri).path)
kw = _check_kwargs(smart_open_http.open, transport_params)
return smart_open_http.open(uri, mode, **kw), filename
else:
raise NotImplementedError("scheme %r is not supported", parsed_uri.scheme)
elif hasattr(uri, 'read'):
# simply pass-through if already a file-like
# we need to return something as the file name, but we don't know what
# so we probe for uri.name (e.g., this works with open() or tempfile.NamedTemporaryFile)
# if the value ends with COMPRESSED_EXT, we will note it in _compression_wrapper()
# if there is no such an attribute, we return "unknown" - this effectively disables any compression
filename = getattr(uri, 'name', 'unknown')
return uri, filename
else:
raise TypeError("don't know how to handle uri %r" % uri) | python | def _open_binary_stream(uri, mode, transport_params):
"""Open an arbitrary URI in the specified binary mode.
Not all modes are supported for all protocols.
:arg uri: The URI to open. May be a string, or something else.
:arg str mode: The mode to open with. Must be rb, wb or ab.
:arg transport_params: Keyword argumens for the transport layer.
:returns: A file object and the filename
:rtype: tuple
"""
if mode not in ('rb', 'rb+', 'wb', 'wb+', 'ab', 'ab+'):
#
# This should really be a ValueError, but for the sake of compatibility
# with older versions, which raise NotImplementedError, we do the same.
#
raise NotImplementedError('unsupported mode: %r' % mode)
if isinstance(uri, six.string_types):
# this method just routes the request to classes handling the specific storage
# schemes, depending on the URI protocol in `uri`
filename = uri.split('/')[-1]
parsed_uri = _parse_uri(uri)
unsupported = "%r mode not supported for %r scheme" % (mode, parsed_uri.scheme)
if parsed_uri.scheme == "file":
fobj = io.open(parsed_uri.uri_path, mode)
return fobj, filename
elif parsed_uri.scheme in smart_open_ssh.SCHEMES:
fobj = smart_open_ssh.open(
parsed_uri.uri_path,
mode,
host=parsed_uri.host,
user=parsed_uri.user,
port=parsed_uri.port,
)
return fobj, filename
elif parsed_uri.scheme in smart_open_s3.SUPPORTED_SCHEMES:
return _s3_open_uri(parsed_uri, mode, transport_params), filename
elif parsed_uri.scheme == "hdfs":
_check_kwargs(smart_open_hdfs.open, transport_params)
return smart_open_hdfs.open(parsed_uri.uri_path, mode), filename
elif parsed_uri.scheme == "webhdfs":
kw = _check_kwargs(smart_open_webhdfs.open, transport_params)
return smart_open_webhdfs.open(parsed_uri.uri_path, mode, **kw), filename
elif parsed_uri.scheme.startswith('http'):
#
# The URI may contain a query string and fragments, which interfere
# with our compressed/uncompressed estimation, so we strip them.
#
filename = P.basename(urlparse.urlparse(uri).path)
kw = _check_kwargs(smart_open_http.open, transport_params)
return smart_open_http.open(uri, mode, **kw), filename
else:
raise NotImplementedError("scheme %r is not supported", parsed_uri.scheme)
elif hasattr(uri, 'read'):
# simply pass-through if already a file-like
# we need to return something as the file name, but we don't know what
# so we probe for uri.name (e.g., this works with open() or tempfile.NamedTemporaryFile)
# if the value ends with COMPRESSED_EXT, we will note it in _compression_wrapper()
# if there is no such an attribute, we return "unknown" - this effectively disables any compression
filename = getattr(uri, 'name', 'unknown')
return uri, filename
else:
raise TypeError("don't know how to handle uri %r" % uri) | [
"def",
"_open_binary_stream",
"(",
"uri",
",",
"mode",
",",
"transport_params",
")",
":",
"if",
"mode",
"not",
"in",
"(",
"'rb'",
",",
"'rb+'",
",",
"'wb'",
",",
"'wb+'",
",",
"'ab'",
",",
"'ab+'",
")",
":",
"#",
"# This should really be a ValueError, but fo... | Open an arbitrary URI in the specified binary mode.
Not all modes are supported for all protocols.
:arg uri: The URI to open. May be a string, or something else.
:arg str mode: The mode to open with. Must be rb, wb or ab.
:arg transport_params: Keyword argumens for the transport layer.
:returns: A file object and the filename
:rtype: tuple | [
"Open",
"an",
"arbitrary",
"URI",
"in",
"the",
"specified",
"binary",
"mode",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L504-L568 | train | 214,372 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | _my_urlsplit | def _my_urlsplit(url):
"""This is a hack to prevent the regular urlsplit from splitting around question marks.
A question mark (?) in a URL typically indicates the start of a
querystring, and the standard library's urlparse function handles the
querystring separately. Unfortunately, question marks can also appear
_inside_ the actual URL for some schemas like S3.
Replaces question marks with newlines prior to splitting. This is safe because:
1. The standard library's urlsplit completely ignores newlines
2. Raw newlines will never occur in innocuous URLs. They are always URL-encoded.
See Also
--------
https://github.com/python/cpython/blob/3.7/Lib/urllib/parse.py
https://github.com/RaRe-Technologies/smart_open/issues/285
"""
if '?' not in url:
return urlsplit(url, allow_fragments=False)
sr = urlsplit(url.replace('?', '\n'), allow_fragments=False)
SplitResult = collections.namedtuple('SplitResult', 'scheme netloc path query fragment')
return SplitResult(sr.scheme, sr.netloc, sr.path.replace('\n', '?'), '', '') | python | def _my_urlsplit(url):
"""This is a hack to prevent the regular urlsplit from splitting around question marks.
A question mark (?) in a URL typically indicates the start of a
querystring, and the standard library's urlparse function handles the
querystring separately. Unfortunately, question marks can also appear
_inside_ the actual URL for some schemas like S3.
Replaces question marks with newlines prior to splitting. This is safe because:
1. The standard library's urlsplit completely ignores newlines
2. Raw newlines will never occur in innocuous URLs. They are always URL-encoded.
See Also
--------
https://github.com/python/cpython/blob/3.7/Lib/urllib/parse.py
https://github.com/RaRe-Technologies/smart_open/issues/285
"""
if '?' not in url:
return urlsplit(url, allow_fragments=False)
sr = urlsplit(url.replace('?', '\n'), allow_fragments=False)
SplitResult = collections.namedtuple('SplitResult', 'scheme netloc path query fragment')
return SplitResult(sr.scheme, sr.netloc, sr.path.replace('\n', '?'), '', '') | [
"def",
"_my_urlsplit",
"(",
"url",
")",
":",
"if",
"'?'",
"not",
"in",
"url",
":",
"return",
"urlsplit",
"(",
"url",
",",
"allow_fragments",
"=",
"False",
")",
"sr",
"=",
"urlsplit",
"(",
"url",
".",
"replace",
"(",
"'?'",
",",
"'\\n'",
")",
",",
"... | This is a hack to prevent the regular urlsplit from splitting around question marks.
A question mark (?) in a URL typically indicates the start of a
querystring, and the standard library's urlparse function handles the
querystring separately. Unfortunately, question marks can also appear
_inside_ the actual URL for some schemas like S3.
Replaces question marks with newlines prior to splitting. This is safe because:
1. The standard library's urlsplit completely ignores newlines
2. Raw newlines will never occur in innocuous URLs. They are always URL-encoded.
See Also
--------
https://github.com/python/cpython/blob/3.7/Lib/urllib/parse.py
https://github.com/RaRe-Technologies/smart_open/issues/285 | [
"This",
"is",
"a",
"hack",
"to",
"prevent",
"the",
"regular",
"urlsplit",
"from",
"splitting",
"around",
"question",
"marks",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L632-L655 | train | 214,373 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | _parse_uri | def _parse_uri(uri_as_string):
"""
Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI examples::
* s3://my_bucket/my_key
* s3://my_key:my_secret@my_bucket/my_key
* s3://my_key:my_secret@my_server:my_port@my_bucket/my_key
* hdfs:///path/file
* hdfs://path/file
* webhdfs://host:port/path/file
* ./local/path/file
* ~/local/path/file
* local/path/file
* ./local/path/file.gz
* file:///home/user/file
* file:///home/user/file.bz2
* [ssh|scp|sftp]://username@host//path/file
* [ssh|scp|sftp]://username@host/path/file
"""
if os.name == 'nt':
# urlsplit doesn't work on Windows -- it parses the drive as the scheme...
if '://' not in uri_as_string:
# no protocol given => assume a local file
uri_as_string = 'file://' + uri_as_string
parsed_uri = _my_urlsplit(uri_as_string)
if parsed_uri.scheme == "hdfs":
return _parse_uri_hdfs(parsed_uri)
elif parsed_uri.scheme == "webhdfs":
return _parse_uri_webhdfs(parsed_uri)
elif parsed_uri.scheme in smart_open_s3.SUPPORTED_SCHEMES:
return _parse_uri_s3x(parsed_uri)
elif parsed_uri.scheme == 'file':
return _parse_uri_file(parsed_uri.netloc + parsed_uri.path)
elif parsed_uri.scheme in ('', None):
return _parse_uri_file(uri_as_string)
elif parsed_uri.scheme.startswith('http'):
return Uri(scheme=parsed_uri.scheme, uri_path=uri_as_string)
elif parsed_uri.scheme in smart_open_ssh.SCHEMES:
return _parse_uri_ssh(parsed_uri)
else:
raise NotImplementedError(
"unknown URI scheme %r in %r" % (parsed_uri.scheme, uri_as_string)
) | python | def _parse_uri(uri_as_string):
"""
Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI examples::
* s3://my_bucket/my_key
* s3://my_key:my_secret@my_bucket/my_key
* s3://my_key:my_secret@my_server:my_port@my_bucket/my_key
* hdfs:///path/file
* hdfs://path/file
* webhdfs://host:port/path/file
* ./local/path/file
* ~/local/path/file
* local/path/file
* ./local/path/file.gz
* file:///home/user/file
* file:///home/user/file.bz2
* [ssh|scp|sftp]://username@host//path/file
* [ssh|scp|sftp]://username@host/path/file
"""
if os.name == 'nt':
# urlsplit doesn't work on Windows -- it parses the drive as the scheme...
if '://' not in uri_as_string:
# no protocol given => assume a local file
uri_as_string = 'file://' + uri_as_string
parsed_uri = _my_urlsplit(uri_as_string)
if parsed_uri.scheme == "hdfs":
return _parse_uri_hdfs(parsed_uri)
elif parsed_uri.scheme == "webhdfs":
return _parse_uri_webhdfs(parsed_uri)
elif parsed_uri.scheme in smart_open_s3.SUPPORTED_SCHEMES:
return _parse_uri_s3x(parsed_uri)
elif parsed_uri.scheme == 'file':
return _parse_uri_file(parsed_uri.netloc + parsed_uri.path)
elif parsed_uri.scheme in ('', None):
return _parse_uri_file(uri_as_string)
elif parsed_uri.scheme.startswith('http'):
return Uri(scheme=parsed_uri.scheme, uri_path=uri_as_string)
elif parsed_uri.scheme in smart_open_ssh.SCHEMES:
return _parse_uri_ssh(parsed_uri)
else:
raise NotImplementedError(
"unknown URI scheme %r in %r" % (parsed_uri.scheme, uri_as_string)
) | [
"def",
"_parse_uri",
"(",
"uri_as_string",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# urlsplit doesn't work on Windows -- it parses the drive as the scheme...",
"if",
"'://'",
"not",
"in",
"uri_as_string",
":",
"# no protocol given => assume a local file",
"ur... | Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI examples::
* s3://my_bucket/my_key
* s3://my_key:my_secret@my_bucket/my_key
* s3://my_key:my_secret@my_server:my_port@my_bucket/my_key
* hdfs:///path/file
* hdfs://path/file
* webhdfs://host:port/path/file
* ./local/path/file
* ~/local/path/file
* local/path/file
* ./local/path/file.gz
* file:///home/user/file
* file:///home/user/file.bz2
* [ssh|scp|sftp]://username@host//path/file
* [ssh|scp|sftp]://username@host/path/file | [
"Parse",
"the",
"given",
"URI",
"from",
"a",
"string",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L658-L719 | train | 214,374 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | _parse_uri_ssh | def _parse_uri_ssh(unt):
"""Parse a Uri from a urllib namedtuple."""
if '@' in unt.netloc:
user, host_port = unt.netloc.split('@', 1)
else:
user, host_port = None, unt.netloc
if ':' in host_port:
host, port = host_port.split(':', 1)
else:
host, port = host_port, None
if not user:
user = None
if not port:
port = smart_open_ssh.DEFAULT_PORT
else:
port = int(port)
return Uri(scheme=unt.scheme, uri_path=unt.path, user=user, host=host, port=port) | python | def _parse_uri_ssh(unt):
"""Parse a Uri from a urllib namedtuple."""
if '@' in unt.netloc:
user, host_port = unt.netloc.split('@', 1)
else:
user, host_port = None, unt.netloc
if ':' in host_port:
host, port = host_port.split(':', 1)
else:
host, port = host_port, None
if not user:
user = None
if not port:
port = smart_open_ssh.DEFAULT_PORT
else:
port = int(port)
return Uri(scheme=unt.scheme, uri_path=unt.path, user=user, host=host, port=port) | [
"def",
"_parse_uri_ssh",
"(",
"unt",
")",
":",
"if",
"'@'",
"in",
"unt",
".",
"netloc",
":",
"user",
",",
"host_port",
"=",
"unt",
".",
"netloc",
".",
"split",
"(",
"'@'",
",",
"1",
")",
"else",
":",
"user",
",",
"host_port",
"=",
"None",
",",
"u... | Parse a Uri from a urllib namedtuple. | [
"Parse",
"a",
"Uri",
"from",
"a",
"urllib",
"namedtuple",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L807-L826 | train | 214,375 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | _need_to_buffer | def _need_to_buffer(file_obj, mode, ext):
"""Returns True if we need to buffer the whole file in memory in order to proceed."""
try:
is_seekable = file_obj.seekable()
except AttributeError:
#
# Under Py2, built-in file objects returned by open do not have
# .seekable, but have a .seek method instead.
#
is_seekable = hasattr(file_obj, 'seek')
return six.PY2 and mode.startswith('r') and ext in _COMPRESSOR_REGISTRY and not is_seekable | python | def _need_to_buffer(file_obj, mode, ext):
"""Returns True if we need to buffer the whole file in memory in order to proceed."""
try:
is_seekable = file_obj.seekable()
except AttributeError:
#
# Under Py2, built-in file objects returned by open do not have
# .seekable, but have a .seek method instead.
#
is_seekable = hasattr(file_obj, 'seek')
return six.PY2 and mode.startswith('r') and ext in _COMPRESSOR_REGISTRY and not is_seekable | [
"def",
"_need_to_buffer",
"(",
"file_obj",
",",
"mode",
",",
"ext",
")",
":",
"try",
":",
"is_seekable",
"=",
"file_obj",
".",
"seekable",
"(",
")",
"except",
"AttributeError",
":",
"#",
"# Under Py2, built-in file objects returned by open do not have",
"# .seekable, ... | Returns True if we need to buffer the whole file in memory in order to proceed. | [
"Returns",
"True",
"if",
"we",
"need",
"to",
"buffer",
"the",
"whole",
"file",
"in",
"memory",
"in",
"order",
"to",
"proceed",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L829-L839 | train | 214,376 |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | _encoding_wrapper | def _encoding_wrapper(fileobj, mode, encoding=None, errors=None):
"""Decode bytes into text, if necessary.
If mode specifies binary access, does nothing, unless the encoding is
specified. A non-null encoding implies text mode.
:arg fileobj: must quack like a filehandle object.
:arg str mode: is the mode which was originally requested by the user.
:arg str encoding: The text encoding to use. If mode is binary, overrides mode.
:arg str errors: The method to use when handling encoding/decoding errors.
:returns: a file object
"""
logger.debug('encoding_wrapper: %r', locals())
#
# If the mode is binary, but the user specified an encoding, assume they
# want text. If we don't make this assumption, ignore the encoding and
# return bytes, smart_open behavior will diverge from the built-in open:
#
# open(filename, encoding='utf-8') returns a text stream in Py3
# smart_open(filename, encoding='utf-8') would return a byte stream
# without our assumption, because the default mode is rb.
#
if 'b' in mode and encoding is None:
return fileobj
if encoding is None:
encoding = SYSTEM_ENCODING
kw = {'errors': errors} if errors else {}
if mode[0] == 'r' or mode.endswith('+'):
fileobj = codecs.getreader(encoding)(fileobj, **kw)
if mode[0] in ('w', 'a') or mode.endswith('+'):
fileobj = codecs.getwriter(encoding)(fileobj, **kw)
return fileobj | python | def _encoding_wrapper(fileobj, mode, encoding=None, errors=None):
"""Decode bytes into text, if necessary.
If mode specifies binary access, does nothing, unless the encoding is
specified. A non-null encoding implies text mode.
:arg fileobj: must quack like a filehandle object.
:arg str mode: is the mode which was originally requested by the user.
:arg str encoding: The text encoding to use. If mode is binary, overrides mode.
:arg str errors: The method to use when handling encoding/decoding errors.
:returns: a file object
"""
logger.debug('encoding_wrapper: %r', locals())
#
# If the mode is binary, but the user specified an encoding, assume they
# want text. If we don't make this assumption, ignore the encoding and
# return bytes, smart_open behavior will diverge from the built-in open:
#
# open(filename, encoding='utf-8') returns a text stream in Py3
# smart_open(filename, encoding='utf-8') would return a byte stream
# without our assumption, because the default mode is rb.
#
if 'b' in mode and encoding is None:
return fileobj
if encoding is None:
encoding = SYSTEM_ENCODING
kw = {'errors': errors} if errors else {}
if mode[0] == 'r' or mode.endswith('+'):
fileobj = codecs.getreader(encoding)(fileobj, **kw)
if mode[0] in ('w', 'a') or mode.endswith('+'):
fileobj = codecs.getwriter(encoding)(fileobj, **kw)
return fileobj | [
"def",
"_encoding_wrapper",
"(",
"fileobj",
",",
"mode",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'encoding_wrapper: %r'",
",",
"locals",
"(",
")",
")",
"#",
"# If the mode is binary, but the user specifie... | Decode bytes into text, if necessary.
If mode specifies binary access, does nothing, unless the encoding is
specified. A non-null encoding implies text mode.
:arg fileobj: must quack like a filehandle object.
:arg str mode: is the mode which was originally requested by the user.
:arg str encoding: The text encoding to use. If mode is binary, overrides mode.
:arg str errors: The method to use when handling encoding/decoding errors.
:returns: a file object | [
"Decode",
"bytes",
"into",
"text",
"if",
"necessary",
"."
] | 2dc8d60f223fc7b00a2000c56362a7bd6cd0850e | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L869-L903 | train | 214,377 |
cossacklabs/acra | examples/python/example_with_zone.py | get_zone | def get_zone():
"""make http response to AcraServer api to generate new zone and return tuple
of zone id and public key
"""
response = urlopen('{}/getNewZone'.format(ACRA_CONNECTOR_API_ADDRESS))
json_data = response.read().decode('utf-8')
zone_data = json.loads(json_data)
return zone_data['id'], b64decode(zone_data['public_key']) | python | def get_zone():
"""make http response to AcraServer api to generate new zone and return tuple
of zone id and public key
"""
response = urlopen('{}/getNewZone'.format(ACRA_CONNECTOR_API_ADDRESS))
json_data = response.read().decode('utf-8')
zone_data = json.loads(json_data)
return zone_data['id'], b64decode(zone_data['public_key']) | [
"def",
"get_zone",
"(",
")",
":",
"response",
"=",
"urlopen",
"(",
"'{}/getNewZone'",
".",
"format",
"(",
"ACRA_CONNECTOR_API_ADDRESS",
")",
")",
"json_data",
"=",
"response",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"zone_data",
"=",
"js... | make http response to AcraServer api to generate new zone and return tuple
of zone id and public key | [
"make",
"http",
"response",
"to",
"AcraServer",
"api",
"to",
"generate",
"new",
"zone",
"and",
"return",
"tuple",
"of",
"zone",
"id",
"and",
"public",
"key"
] | e30741e2dfb2f3320a08ff78450c618afcb195e4 | https://github.com/cossacklabs/acra/blob/e30741e2dfb2f3320a08ff78450c618afcb195e4/examples/python/example_with_zone.py#L34-L41 | train | 214,378 |
has2k1/plotnine | plotnine/stats/binning.py | iqr | def iqr(a):
"""
Calculate the IQR for an array of numbers.
"""
a = np.asarray(a)
q1 = stats.scoreatpercentile(a, 25)
q3 = stats.scoreatpercentile(a, 75)
return q3 - q1 | python | def iqr(a):
"""
Calculate the IQR for an array of numbers.
"""
a = np.asarray(a)
q1 = stats.scoreatpercentile(a, 25)
q3 = stats.scoreatpercentile(a, 75)
return q3 - q1 | [
"def",
"iqr",
"(",
"a",
")",
":",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"q1",
"=",
"stats",
".",
"scoreatpercentile",
"(",
"a",
",",
"25",
")",
"q3",
"=",
"stats",
".",
"scoreatpercentile",
"(",
"a",
",",
"75",
")",
"return",
"q3",
"-"... | Calculate the IQR for an array of numbers. | [
"Calculate",
"the",
"IQR",
"for",
"an",
"array",
"of",
"numbers",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/binning.py#L14-L21 | train | 214,379 |
has2k1/plotnine | plotnine/stats/binning.py | freedman_diaconis_bins | def freedman_diaconis_bins(a):
"""
Calculate number of hist bins using Freedman-Diaconis rule.
"""
# From http://stats.stackexchange.com/questions/798/
a = np.asarray(a)
h = 2 * iqr(a) / (len(a) ** (1 / 3))
# fall back to sqrt(a) bins if iqr is 0
if h == 0:
bins = np.ceil(np.sqrt(a.size))
else:
bins = np.ceil((np.nanmax(a) - np.nanmin(a)) / h)
return np.int(bins) | python | def freedman_diaconis_bins(a):
"""
Calculate number of hist bins using Freedman-Diaconis rule.
"""
# From http://stats.stackexchange.com/questions/798/
a = np.asarray(a)
h = 2 * iqr(a) / (len(a) ** (1 / 3))
# fall back to sqrt(a) bins if iqr is 0
if h == 0:
bins = np.ceil(np.sqrt(a.size))
else:
bins = np.ceil((np.nanmax(a) - np.nanmin(a)) / h)
return np.int(bins) | [
"def",
"freedman_diaconis_bins",
"(",
"a",
")",
":",
"# From http://stats.stackexchange.com/questions/798/",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"h",
"=",
"2",
"*",
"iqr",
"(",
"a",
")",
"/",
"(",
"len",
"(",
"a",
")",
"**",
"(",
"1",
"/",
... | Calculate number of hist bins using Freedman-Diaconis rule. | [
"Calculate",
"number",
"of",
"hist",
"bins",
"using",
"Freedman",
"-",
"Diaconis",
"rule",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/binning.py#L24-L38 | train | 214,380 |
has2k1/plotnine | plotnine/stats/binning.py | assign_bins | def assign_bins(x, breaks, weight=None, pad=False, closed='right'):
"""
Assign value in x to bins demacated by the break points
Parameters
----------
x : array_like
Values to be binned.
breaks : array_like
Sequence of break points.
weight : array_like
Weight of each value in `x`. Used in creating the frequency
table. If `None`, then each value in `x` has a weight of 1.
pad : bool
If `True`, add empty bins at either end of `x`.
closed : str in ``['right', 'left']``
Whether the right or left edges of the bins are part of the
bin.
Returns
-------
out : dataframe
Bin count and density information.
"""
right = closed == 'right'
# If weight not supplied to, use one (no weight)
if weight is None:
weight = np.ones(len(x))
else:
weight = np.asarray(weight)
weight[np.isnan(weight)] = 0
bin_idx = pd.cut(x, bins=breaks, labels=False,
right=right, include_lowest=True)
bin_widths = np.diff(breaks)
bin_x = (breaks[:-1] + breaks[1:]) * 0.5
# Create a dataframe with two columns:
# - the bins to which each x is assigned
# - the weight of each x value
# Then create a weighted frequency table
df = pd.DataFrame({'bin_idx': bin_idx, 'weight': weight})
wftable = df.pivot_table(
'weight', index=['bin_idx'], aggfunc=np.sum)['weight']
# Empty bins get no value in the computed frequency table.
# We need to add the zeros and since frequency table is a
# Series object, we need to keep it ordered
if len(wftable) < len(bin_x):
empty_bins = set(range(len(bin_x))) - set(bin_idx)
for b in empty_bins:
wftable.loc[b] = 0
wftable = wftable.sort_index()
bin_count = wftable.tolist()
if pad:
bw0 = bin_widths[0]
bwn = bin_widths[-1]
bin_count = np.hstack([0, bin_count, 0])
bin_widths = np.hstack([bw0, bin_widths, bwn])
bin_x = np.hstack([bin_x[0]-bw0, bin_x, bin_x[-1]+bwn])
return result_dataframe(bin_count, bin_x, bin_widths) | python | def assign_bins(x, breaks, weight=None, pad=False, closed='right'):
"""
Assign value in x to bins demacated by the break points
Parameters
----------
x : array_like
Values to be binned.
breaks : array_like
Sequence of break points.
weight : array_like
Weight of each value in `x`. Used in creating the frequency
table. If `None`, then each value in `x` has a weight of 1.
pad : bool
If `True`, add empty bins at either end of `x`.
closed : str in ``['right', 'left']``
Whether the right or left edges of the bins are part of the
bin.
Returns
-------
out : dataframe
Bin count and density information.
"""
right = closed == 'right'
# If weight not supplied to, use one (no weight)
if weight is None:
weight = np.ones(len(x))
else:
weight = np.asarray(weight)
weight[np.isnan(weight)] = 0
bin_idx = pd.cut(x, bins=breaks, labels=False,
right=right, include_lowest=True)
bin_widths = np.diff(breaks)
bin_x = (breaks[:-1] + breaks[1:]) * 0.5
# Create a dataframe with two columns:
# - the bins to which each x is assigned
# - the weight of each x value
# Then create a weighted frequency table
df = pd.DataFrame({'bin_idx': bin_idx, 'weight': weight})
wftable = df.pivot_table(
'weight', index=['bin_idx'], aggfunc=np.sum)['weight']
# Empty bins get no value in the computed frequency table.
# We need to add the zeros and since frequency table is a
# Series object, we need to keep it ordered
if len(wftable) < len(bin_x):
empty_bins = set(range(len(bin_x))) - set(bin_idx)
for b in empty_bins:
wftable.loc[b] = 0
wftable = wftable.sort_index()
bin_count = wftable.tolist()
if pad:
bw0 = bin_widths[0]
bwn = bin_widths[-1]
bin_count = np.hstack([0, bin_count, 0])
bin_widths = np.hstack([bw0, bin_widths, bwn])
bin_x = np.hstack([bin_x[0]-bw0, bin_x, bin_x[-1]+bwn])
return result_dataframe(bin_count, bin_x, bin_widths) | [
"def",
"assign_bins",
"(",
"x",
",",
"breaks",
",",
"weight",
"=",
"None",
",",
"pad",
"=",
"False",
",",
"closed",
"=",
"'right'",
")",
":",
"right",
"=",
"closed",
"==",
"'right'",
"# If weight not supplied to, use one (no weight)",
"if",
"weight",
"is",
"... | Assign value in x to bins demacated by the break points
Parameters
----------
x : array_like
Values to be binned.
breaks : array_like
Sequence of break points.
weight : array_like
Weight of each value in `x`. Used in creating the frequency
table. If `None`, then each value in `x` has a weight of 1.
pad : bool
If `True`, add empty bins at either end of `x`.
closed : str in ``['right', 'left']``
Whether the right or left edges of the bins are part of the
bin.
Returns
-------
out : dataframe
Bin count and density information. | [
"Assign",
"value",
"in",
"x",
"to",
"bins",
"demacated",
"by",
"the",
"break",
"points"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/binning.py#L120-L182 | train | 214,381 |
has2k1/plotnine | plotnine/stats/binning.py | result_dataframe | def result_dataframe(count, x, width, xmin=None, xmax=None):
"""
Create a dataframe to hold bin information
"""
if xmin is None:
xmin = x-width/2
if xmax is None:
xmax = x+width/2
# Eliminate any numerical roundoff discrepancies
# between the edges
xmin[1:] = xmax[:-1]
density = (count/width) / np.sum(np.abs(count))
out = pd.DataFrame({
'count': count,
'x': x,
'xmin': xmin,
'xmax': xmax,
'width': width,
'density': density,
'ncount': count/np.max(np.abs(count)),
'ndensity': count/np.max(np.abs(density))})
return out | python | def result_dataframe(count, x, width, xmin=None, xmax=None):
"""
Create a dataframe to hold bin information
"""
if xmin is None:
xmin = x-width/2
if xmax is None:
xmax = x+width/2
# Eliminate any numerical roundoff discrepancies
# between the edges
xmin[1:] = xmax[:-1]
density = (count/width) / np.sum(np.abs(count))
out = pd.DataFrame({
'count': count,
'x': x,
'xmin': xmin,
'xmax': xmax,
'width': width,
'density': density,
'ncount': count/np.max(np.abs(count)),
'ndensity': count/np.max(np.abs(density))})
return out | [
"def",
"result_dataframe",
"(",
"count",
",",
"x",
",",
"width",
",",
"xmin",
"=",
"None",
",",
"xmax",
"=",
"None",
")",
":",
"if",
"xmin",
"is",
"None",
":",
"xmin",
"=",
"x",
"-",
"width",
"/",
"2",
"if",
"xmax",
"is",
"None",
":",
"xmax",
"... | Create a dataframe to hold bin information | [
"Create",
"a",
"dataframe",
"to",
"hold",
"bin",
"information"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/binning.py#L185-L209 | train | 214,382 |
has2k1/plotnine | plotnine/stats/binning.py | fuzzybreaks | def fuzzybreaks(scale, breaks=None, boundary=None,
binwidth=None, bins=30, right=True):
"""
Compute fuzzy breaks
For a continuous scale, fuzzybreaks "preserve" the range of
the scale. The fuzzing is close to numerical roundoff and
is visually imperceptible.
Parameters
----------
scale : scale
Scale
breaks : array_like
Sequence of break points. If provided and the scale is not
discrete, they are returned.
boundary : float
First break. If `None` a suitable on is computed using
the range of the scale and the binwidth.
binwidth : float
Separation between the breaks
bins : int
Number of bins
right : bool
If `True` the right edges of the bins are part of the
bin. If `False` then the left edges of the bins are part
of the bin.
Returns
-------
out : array_like
"""
# Bins for categorical data should take the width
# of one level, and should show up centered over
# their tick marks. All other parameters are ignored.
if isinstance(scale, scale_discrete):
breaks = scale.get_breaks()
return -0.5 + np.arange(1, len(breaks)+2)
else:
if breaks is not None:
breaks = scale.transform(breaks)
if breaks is not None:
return breaks
recompute_bins = binwidth is not None
srange = scale.limits
if binwidth is None or np.isnan(binwidth):
binwidth = (srange[1]-srange[0]) / bins
if boundary is None or np.isnan(boundary):
boundary = round_any(srange[0], binwidth, np.floor)
if recompute_bins:
bins = np.int(np.ceil((srange[1]-boundary)/binwidth))
# To minimise precision errors, we do not pass the boundary and
# binwidth into np.arange as params. The resulting breaks
# can then be adjusted with finer(epsilon based rather than
# some arbitrary small number) precision.
breaks = np.arange(boundary, srange[1]+binwidth, binwidth)
return _adjust_breaks(breaks, right) | python | def fuzzybreaks(scale, breaks=None, boundary=None,
binwidth=None, bins=30, right=True):
"""
Compute fuzzy breaks
For a continuous scale, fuzzybreaks "preserve" the range of
the scale. The fuzzing is close to numerical roundoff and
is visually imperceptible.
Parameters
----------
scale : scale
Scale
breaks : array_like
Sequence of break points. If provided and the scale is not
discrete, they are returned.
boundary : float
First break. If `None` a suitable on is computed using
the range of the scale and the binwidth.
binwidth : float
Separation between the breaks
bins : int
Number of bins
right : bool
If `True` the right edges of the bins are part of the
bin. If `False` then the left edges of the bins are part
of the bin.
Returns
-------
out : array_like
"""
# Bins for categorical data should take the width
# of one level, and should show up centered over
# their tick marks. All other parameters are ignored.
if isinstance(scale, scale_discrete):
breaks = scale.get_breaks()
return -0.5 + np.arange(1, len(breaks)+2)
else:
if breaks is not None:
breaks = scale.transform(breaks)
if breaks is not None:
return breaks
recompute_bins = binwidth is not None
srange = scale.limits
if binwidth is None or np.isnan(binwidth):
binwidth = (srange[1]-srange[0]) / bins
if boundary is None or np.isnan(boundary):
boundary = round_any(srange[0], binwidth, np.floor)
if recompute_bins:
bins = np.int(np.ceil((srange[1]-boundary)/binwidth))
# To minimise precision errors, we do not pass the boundary and
# binwidth into np.arange as params. The resulting breaks
# can then be adjusted with finer(epsilon based rather than
# some arbitrary small number) precision.
breaks = np.arange(boundary, srange[1]+binwidth, binwidth)
return _adjust_breaks(breaks, right) | [
"def",
"fuzzybreaks",
"(",
"scale",
",",
"breaks",
"=",
"None",
",",
"boundary",
"=",
"None",
",",
"binwidth",
"=",
"None",
",",
"bins",
"=",
"30",
",",
"right",
"=",
"True",
")",
":",
"# Bins for categorical data should take the width",
"# of one level, and sho... | Compute fuzzy breaks
For a continuous scale, fuzzybreaks "preserve" the range of
the scale. The fuzzing is close to numerical roundoff and
is visually imperceptible.
Parameters
----------
scale : scale
Scale
breaks : array_like
Sequence of break points. If provided and the scale is not
discrete, they are returned.
boundary : float
First break. If `None` a suitable on is computed using
the range of the scale and the binwidth.
binwidth : float
Separation between the breaks
bins : int
Number of bins
right : bool
If `True` the right edges of the bins are part of the
bin. If `False` then the left edges of the bins are part
of the bin.
Returns
-------
out : array_like | [
"Compute",
"fuzzy",
"breaks"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/binning.py#L212-L274 | train | 214,383 |
has2k1/plotnine | plotnine/guides/guides.py | guides.build | def build(self, plot):
"""
Build the guides
Parameters
----------
plot : ggplot
ggplot object being drawn
Returns
-------
box : matplotlib.offsetbox.Offsetbox | None
A box that contains all the guides for the plot.
If there are no guides, **None** is returned.
"""
get_property = plot.theme.themeables.property
# by default, guide boxes are vertically aligned
with suppress(KeyError):
self.box_direction = get_property('legend_box')
if self.box_direction is None:
self.box_direction = 'vertical'
with suppress(KeyError):
self.position = get_property('legend_position')
if self.position == 'none':
return
# justification of legend boxes
with suppress(KeyError):
self.box_align = get_property('legend_box_just')
if self.box_align is None:
if self.position in {'left', 'right'}:
tmp = 'left'
else:
tmp = 'center'
self.box_align = tmp
with suppress(KeyError):
self.box_margin = get_property('legend_box_margin')
if self.box_margin is None:
self.box_margin = 10
with suppress(KeyError):
self.spacing = get_property('legend_spacing')
if self.spacing is None:
self.spacing = 10
gdefs = self.train(plot)
if not gdefs:
return
gdefs = self.merge(gdefs)
gdefs = self.create_geoms(gdefs, plot)
if not gdefs:
return
gboxes = self.draw(gdefs, plot.theme)
bigbox = self.assemble(gboxes, gdefs, plot.theme)
return bigbox | python | def build(self, plot):
"""
Build the guides
Parameters
----------
plot : ggplot
ggplot object being drawn
Returns
-------
box : matplotlib.offsetbox.Offsetbox | None
A box that contains all the guides for the plot.
If there are no guides, **None** is returned.
"""
get_property = plot.theme.themeables.property
# by default, guide boxes are vertically aligned
with suppress(KeyError):
self.box_direction = get_property('legend_box')
if self.box_direction is None:
self.box_direction = 'vertical'
with suppress(KeyError):
self.position = get_property('legend_position')
if self.position == 'none':
return
# justification of legend boxes
with suppress(KeyError):
self.box_align = get_property('legend_box_just')
if self.box_align is None:
if self.position in {'left', 'right'}:
tmp = 'left'
else:
tmp = 'center'
self.box_align = tmp
with suppress(KeyError):
self.box_margin = get_property('legend_box_margin')
if self.box_margin is None:
self.box_margin = 10
with suppress(KeyError):
self.spacing = get_property('legend_spacing')
if self.spacing is None:
self.spacing = 10
gdefs = self.train(plot)
if not gdefs:
return
gdefs = self.merge(gdefs)
gdefs = self.create_geoms(gdefs, plot)
if not gdefs:
return
gboxes = self.draw(gdefs, plot.theme)
bigbox = self.assemble(gboxes, gdefs, plot.theme)
return bigbox | [
"def",
"build",
"(",
"self",
",",
"plot",
")",
":",
"get_property",
"=",
"plot",
".",
"theme",
".",
"themeables",
".",
"property",
"# by default, guide boxes are vertically aligned",
"with",
"suppress",
"(",
"KeyError",
")",
":",
"self",
".",
"box_direction",
"=... | Build the guides
Parameters
----------
plot : ggplot
ggplot object being drawn
Returns
-------
box : matplotlib.offsetbox.Offsetbox | None
A box that contains all the guides for the plot.
If there are no guides, **None** is returned. | [
"Build",
"the",
"guides"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guides.py#L85-L146 | train | 214,384 |
has2k1/plotnine | plotnine/guides/guides.py | guides.train | def train(self, plot):
"""
Compute all the required guides
Parameters
----------
plot : ggplot
ggplot object
Returns
-------
gdefs : list
Guides for the plots
"""
gdefs = []
for scale in plot.scales:
for output in scale.aesthetics:
# The guide for aesthetic 'xxx' is stored
# in plot.guides['xxx']. The priority for
# the guides depends on how they are created
# 1. ... + guides(xxx=guide_blah())
# 2. ... + scale_xxx(guide=guide_blah())
# 3. default(either guide_legend or guide_colorbar
# depending on the scale type)
# output = scale.aesthetics[0]
guide = self.get(output, scale.guide)
if guide is None or guide is False:
continue
# check the validity of guide.
# if guide is character, then find the guide object
guide = self.validate(guide)
# check the consistency of the guide and scale.
if (guide.available_aes != 'any' and
scale.aesthetics[0] not in guide.available_aes):
raise PlotnineError(
"{} cannot be used for {}".format(
guide.__class__.__name__, scale.aesthetics))
# title
if is_waive(guide.title):
if scale.name:
guide.title = scale.name
else:
try:
guide.title = str(plot.labels[output])
except KeyError:
warn("Cannot generate legend for the {!r} "
"aesthetic. Make sure you have mapped a "
"variable to it".format(output),
PlotnineWarning)
continue
# each guide object trains scale within the object,
# so Guides (i.e., the container of guides)
# need not to know about them
guide = guide.train(scale, output)
if guide is not None:
gdefs.append(guide)
return gdefs | python | def train(self, plot):
"""
Compute all the required guides
Parameters
----------
plot : ggplot
ggplot object
Returns
-------
gdefs : list
Guides for the plots
"""
gdefs = []
for scale in plot.scales:
for output in scale.aesthetics:
# The guide for aesthetic 'xxx' is stored
# in plot.guides['xxx']. The priority for
# the guides depends on how they are created
# 1. ... + guides(xxx=guide_blah())
# 2. ... + scale_xxx(guide=guide_blah())
# 3. default(either guide_legend or guide_colorbar
# depending on the scale type)
# output = scale.aesthetics[0]
guide = self.get(output, scale.guide)
if guide is None or guide is False:
continue
# check the validity of guide.
# if guide is character, then find the guide object
guide = self.validate(guide)
# check the consistency of the guide and scale.
if (guide.available_aes != 'any' and
scale.aesthetics[0] not in guide.available_aes):
raise PlotnineError(
"{} cannot be used for {}".format(
guide.__class__.__name__, scale.aesthetics))
# title
if is_waive(guide.title):
if scale.name:
guide.title = scale.name
else:
try:
guide.title = str(plot.labels[output])
except KeyError:
warn("Cannot generate legend for the {!r} "
"aesthetic. Make sure you have mapped a "
"variable to it".format(output),
PlotnineWarning)
continue
# each guide object trains scale within the object,
# so Guides (i.e., the container of guides)
# need not to know about them
guide = guide.train(scale, output)
if guide is not None:
gdefs.append(guide)
return gdefs | [
"def",
"train",
"(",
"self",
",",
"plot",
")",
":",
"gdefs",
"=",
"[",
"]",
"for",
"scale",
"in",
"plot",
".",
"scales",
":",
"for",
"output",
"in",
"scale",
".",
"aesthetics",
":",
"# The guide for aesthetic 'xxx' is stored",
"# in plot.guides['xxx']. The prior... | Compute all the required guides
Parameters
----------
plot : ggplot
ggplot object
Returns
-------
gdefs : list
Guides for the plots | [
"Compute",
"all",
"the",
"required",
"guides"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guides.py#L148-L211 | train | 214,385 |
has2k1/plotnine | plotnine/guides/guides.py | guides.validate | def validate(self, guide):
"""
Validate guide object
"""
if is_string(guide):
guide = Registry['guide_{}'.format(guide)]()
if not isinstance(guide, guide_class):
raise PlotnineError(
"Unknown guide: {}".format(guide))
return guide | python | def validate(self, guide):
"""
Validate guide object
"""
if is_string(guide):
guide = Registry['guide_{}'.format(guide)]()
if not isinstance(guide, guide_class):
raise PlotnineError(
"Unknown guide: {}".format(guide))
return guide | [
"def",
"validate",
"(",
"self",
",",
"guide",
")",
":",
"if",
"is_string",
"(",
"guide",
")",
":",
"guide",
"=",
"Registry",
"[",
"'guide_{}'",
".",
"format",
"(",
"guide",
")",
"]",
"(",
")",
"if",
"not",
"isinstance",
"(",
"guide",
",",
"guide_clas... | Validate guide object | [
"Validate",
"guide",
"object"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guides.py#L213-L223 | train | 214,386 |
has2k1/plotnine | plotnine/guides/guides.py | guides.create_geoms | def create_geoms(self, gdefs, plot):
"""
Add geoms to the guide definitions
"""
new_gdefs = []
for gdef in gdefs:
gdef = gdef.create_geoms(plot)
if gdef:
new_gdefs.append(gdef)
return new_gdefs | python | def create_geoms(self, gdefs, plot):
"""
Add geoms to the guide definitions
"""
new_gdefs = []
for gdef in gdefs:
gdef = gdef.create_geoms(plot)
if gdef:
new_gdefs.append(gdef)
return new_gdefs | [
"def",
"create_geoms",
"(",
"self",
",",
"gdefs",
",",
"plot",
")",
":",
"new_gdefs",
"=",
"[",
"]",
"for",
"gdef",
"in",
"gdefs",
":",
"gdef",
"=",
"gdef",
".",
"create_geoms",
"(",
"plot",
")",
"if",
"gdef",
":",
"new_gdefs",
".",
"append",
"(",
... | Add geoms to the guide definitions | [
"Add",
"geoms",
"to",
"the",
"guide",
"definitions"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guides.py#L255-L265 | train | 214,387 |
has2k1/plotnine | plotnine/guides/guides.py | guides.draw | def draw(self, gdefs, theme):
"""
Draw out each guide definition
Parameters
----------
gdefs : list of guide_legend|guide_colorbar
guide definitions
theme : theme
Plot theme
Returns
-------
out : list of matplotlib.offsetbox.Offsetbox
A drawing of each legend
"""
for g in gdefs:
g.theme = theme
g._set_defaults()
return [g.draw() for g in gdefs] | python | def draw(self, gdefs, theme):
"""
Draw out each guide definition
Parameters
----------
gdefs : list of guide_legend|guide_colorbar
guide definitions
theme : theme
Plot theme
Returns
-------
out : list of matplotlib.offsetbox.Offsetbox
A drawing of each legend
"""
for g in gdefs:
g.theme = theme
g._set_defaults()
return [g.draw() for g in gdefs] | [
"def",
"draw",
"(",
"self",
",",
"gdefs",
",",
"theme",
")",
":",
"for",
"g",
"in",
"gdefs",
":",
"g",
".",
"theme",
"=",
"theme",
"g",
".",
"_set_defaults",
"(",
")",
"return",
"[",
"g",
".",
"draw",
"(",
")",
"for",
"g",
"in",
"gdefs",
"]"
] | Draw out each guide definition
Parameters
----------
gdefs : list of guide_legend|guide_colorbar
guide definitions
theme : theme
Plot theme
Returns
-------
out : list of matplotlib.offsetbox.Offsetbox
A drawing of each legend | [
"Draw",
"out",
"each",
"guide",
"definition"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guides.py#L267-L286 | train | 214,388 |
has2k1/plotnine | plotnine/guides/guides.py | guides.assemble | def assemble(self, gboxes, gdefs, theme):
"""
Put together all the guide boxes
Parameters
----------
gboxes : list
List of :class:`~matplotlib.offsetbox.Offsetbox`,
where each item is a legend for a single aesthetic.
gdefs : list of guide_legend|guide_colorbar
guide definitions
theme : theme
Plot theme
Returns
-------
box : OffsetBox
A box than can be placed onto a plot
"""
# place the guides according to the guide.order
# 0 do not sort
# 1-99 sort
for gdef in gdefs:
if gdef.order == 0:
gdef.order = 100
elif not 0 <= gdef.order <= 99:
raise PlotnineError(
"'order' for a guide should be "
"between 0 and 99")
orders = [gdef.order for gdef in gdefs]
idx = np.argsort(orders)
gboxes = [gboxes[i] for i in idx]
# direction when more than legend
if self.box_direction == 'vertical':
packer = VPacker
elif self.box_direction == 'horizontal':
packer = HPacker
else:
raise PlotnineError(
"'legend_box' should be either "
"'vertical' or 'horizontal'")
box = packer(children=gboxes, align=self.box_align,
pad=self.box_margin, sep=self.spacing)
return box | python | def assemble(self, gboxes, gdefs, theme):
"""
Put together all the guide boxes
Parameters
----------
gboxes : list
List of :class:`~matplotlib.offsetbox.Offsetbox`,
where each item is a legend for a single aesthetic.
gdefs : list of guide_legend|guide_colorbar
guide definitions
theme : theme
Plot theme
Returns
-------
box : OffsetBox
A box than can be placed onto a plot
"""
# place the guides according to the guide.order
# 0 do not sort
# 1-99 sort
for gdef in gdefs:
if gdef.order == 0:
gdef.order = 100
elif not 0 <= gdef.order <= 99:
raise PlotnineError(
"'order' for a guide should be "
"between 0 and 99")
orders = [gdef.order for gdef in gdefs]
idx = np.argsort(orders)
gboxes = [gboxes[i] for i in idx]
# direction when more than legend
if self.box_direction == 'vertical':
packer = VPacker
elif self.box_direction == 'horizontal':
packer = HPacker
else:
raise PlotnineError(
"'legend_box' should be either "
"'vertical' or 'horizontal'")
box = packer(children=gboxes, align=self.box_align,
pad=self.box_margin, sep=self.spacing)
return box | [
"def",
"assemble",
"(",
"self",
",",
"gboxes",
",",
"gdefs",
",",
"theme",
")",
":",
"# place the guides according to the guide.order",
"# 0 do not sort",
"# 1-99 sort",
"for",
"gdef",
"in",
"gdefs",
":",
"if",
"gdef",
".",
"order",
"==",
"0",
":",
"gdef",
"."... | Put together all the guide boxes
Parameters
----------
gboxes : list
List of :class:`~matplotlib.offsetbox.Offsetbox`,
where each item is a legend for a single aesthetic.
gdefs : list of guide_legend|guide_colorbar
guide definitions
theme : theme
Plot theme
Returns
-------
box : OffsetBox
A box than can be placed onto a plot | [
"Put",
"together",
"all",
"the",
"guide",
"boxes"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guides.py#L288-L333 | train | 214,389 |
has2k1/plotnine | doc/sphinxext/examples_and_gallery.py | add_entries_to_gallery | def add_entries_to_gallery(app, doctree, docname):
"""
Add entries to the gallery node
Should happen when all the doctrees have been read
and the gallery entries have been collected. i.e at
doctree-resolved time.
"""
if docname != 'gallery':
return
if not has_gallery(app.builder.name):
return
# Find gallery node
try:
node = doctree.traverse(gallery)[0]
except TypeError:
return
content = []
for entry in app.env.gallery_entries:
raw_html_node = nodes.raw('', text=entry.html, format='html')
content.append(raw_html_node)
# Even when content is empty, we want the gallery node replaced
node.replace_self(content) | python | def add_entries_to_gallery(app, doctree, docname):
"""
Add entries to the gallery node
Should happen when all the doctrees have been read
and the gallery entries have been collected. i.e at
doctree-resolved time.
"""
if docname != 'gallery':
return
if not has_gallery(app.builder.name):
return
# Find gallery node
try:
node = doctree.traverse(gallery)[0]
except TypeError:
return
content = []
for entry in app.env.gallery_entries:
raw_html_node = nodes.raw('', text=entry.html, format='html')
content.append(raw_html_node)
# Even when content is empty, we want the gallery node replaced
node.replace_self(content) | [
"def",
"add_entries_to_gallery",
"(",
"app",
",",
"doctree",
",",
"docname",
")",
":",
"if",
"docname",
"!=",
"'gallery'",
":",
"return",
"if",
"not",
"has_gallery",
"(",
"app",
".",
"builder",
".",
"name",
")",
":",
"return",
"# Find gallery node",
"try",
... | Add entries to the gallery node
Should happen when all the doctrees have been read
and the gallery entries have been collected. i.e at
doctree-resolved time. | [
"Add",
"entries",
"to",
"the",
"gallery",
"node"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/doc/sphinxext/examples_and_gallery.py#L289-L315 | train | 214,390 |
has2k1/plotnine | doc/sphinxext/examples_and_gallery.py | GalleryEntry.html | def html(self):
"""
Return html for a the entry
"""
# No empty tooltips
if self.description:
tooltip = 'tooltip="{}"'.format(self.description)
else:
tooltip = ''
return entry_html(
title=self.title,
thumbnail=self.thumbnail,
link=self.html_link,
tooltip=tooltip) | python | def html(self):
"""
Return html for a the entry
"""
# No empty tooltips
if self.description:
tooltip = 'tooltip="{}"'.format(self.description)
else:
tooltip = ''
return entry_html(
title=self.title,
thumbnail=self.thumbnail,
link=self.html_link,
tooltip=tooltip) | [
"def",
"html",
"(",
"self",
")",
":",
"# No empty tooltips",
"if",
"self",
".",
"description",
":",
"tooltip",
"=",
"'tooltip=\"{}\"'",
".",
"format",
"(",
"self",
".",
"description",
")",
"else",
":",
"tooltip",
"=",
"''",
"return",
"entry_html",
"(",
"ti... | Return html for a the entry | [
"Return",
"html",
"for",
"a",
"the",
"entry"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/doc/sphinxext/examples_and_gallery.py#L103-L117 | train | 214,391 |
has2k1/plotnine | plotnine/geoms/annotation_logticks.py | _geom_logticks._check_log_scale | def _check_log_scale(base, sides, scales, coord):
"""
Check the log transforms
Parameters
----------
base : float or None
Base of the logarithm in which the ticks will be
calculated. If ``None``, the base of the log transform
the scale will be used.
sides : str (default: bl)
Sides onto which to draw the marks. Any combination
chosen from the characters ``btlr``, for *bottom*, *top*,
*left* or *right* side marks. If ``coord_flip()`` is used,
these are the sides *after* the flip.
scales : SimpleNamespace
``x`` and ``y`` scales.
coord : coord
Coordinate (e.g. coord_cartesian) system of the geom.
Returns
-------
out : tuple
The bases (base_x, base_y) to use when generating the ticks.
"""
def is_log(trans):
return (trans.__class__.__name__.startswith('log') and
hasattr(trans, 'base'))
base_x, base_y = base, base
x_is_log = is_log(scales.x.trans)
y_is_log = is_log(scales.y.trans)
if isinstance(coord, coord_flip):
x_is_log, y_is_log = y_is_log, x_is_log
if 't' in sides or 'b' in sides:
if base_x is None:
base_x = scales.x.trans.base
if not x_is_log:
warnings.warn(
"annotation_logticks for x-axis which does not have "
"a log scale. The logticks may not make sense.",
PlotnineWarning)
elif x_is_log and base_x != scales.x.trans.base:
warnings.warn(
"The x-axis is log transformed in base {} ,"
"but the annotation_logticks are computed in base {}"
"".format(base_x, scales.x.trans.base),
PlotnineWarning)
if 'l' in sides or 'r' in sides:
if base_y is None:
base_y = scales.y.trans.base
if not y_is_log:
warnings.warn(
"annotation_logticks for y-axis which does not have "
"a log scale. The logticks may not make sense.",
PlotnineWarning)
elif y_is_log and base_y != scales.x.trans.base:
warnings.warn(
"The y-axis is log transformed in base {} ,"
"but the annotation_logticks are computed in base {}"
"".format(base_y, scales.x.trans.base),
PlotnineWarning)
return base_x, base_y | python | def _check_log_scale(base, sides, scales, coord):
"""
Check the log transforms
Parameters
----------
base : float or None
Base of the logarithm in which the ticks will be
calculated. If ``None``, the base of the log transform
the scale will be used.
sides : str (default: bl)
Sides onto which to draw the marks. Any combination
chosen from the characters ``btlr``, for *bottom*, *top*,
*left* or *right* side marks. If ``coord_flip()`` is used,
these are the sides *after* the flip.
scales : SimpleNamespace
``x`` and ``y`` scales.
coord : coord
Coordinate (e.g. coord_cartesian) system of the geom.
Returns
-------
out : tuple
The bases (base_x, base_y) to use when generating the ticks.
"""
def is_log(trans):
return (trans.__class__.__name__.startswith('log') and
hasattr(trans, 'base'))
base_x, base_y = base, base
x_is_log = is_log(scales.x.trans)
y_is_log = is_log(scales.y.trans)
if isinstance(coord, coord_flip):
x_is_log, y_is_log = y_is_log, x_is_log
if 't' in sides or 'b' in sides:
if base_x is None:
base_x = scales.x.trans.base
if not x_is_log:
warnings.warn(
"annotation_logticks for x-axis which does not have "
"a log scale. The logticks may not make sense.",
PlotnineWarning)
elif x_is_log and base_x != scales.x.trans.base:
warnings.warn(
"The x-axis is log transformed in base {} ,"
"but the annotation_logticks are computed in base {}"
"".format(base_x, scales.x.trans.base),
PlotnineWarning)
if 'l' in sides or 'r' in sides:
if base_y is None:
base_y = scales.y.trans.base
if not y_is_log:
warnings.warn(
"annotation_logticks for y-axis which does not have "
"a log scale. The logticks may not make sense.",
PlotnineWarning)
elif y_is_log and base_y != scales.x.trans.base:
warnings.warn(
"The y-axis is log transformed in base {} ,"
"but the annotation_logticks are computed in base {}"
"".format(base_y, scales.x.trans.base),
PlotnineWarning)
return base_x, base_y | [
"def",
"_check_log_scale",
"(",
"base",
",",
"sides",
",",
"scales",
",",
"coord",
")",
":",
"def",
"is_log",
"(",
"trans",
")",
":",
"return",
"(",
"trans",
".",
"__class__",
".",
"__name__",
".",
"startswith",
"(",
"'log'",
")",
"and",
"hasattr",
"("... | Check the log transforms
Parameters
----------
base : float or None
Base of the logarithm in which the ticks will be
calculated. If ``None``, the base of the log transform
the scale will be used.
sides : str (default: bl)
Sides onto which to draw the marks. Any combination
chosen from the characters ``btlr``, for *bottom*, *top*,
*left* or *right* side marks. If ``coord_flip()`` is used,
these are the sides *after* the flip.
scales : SimpleNamespace
``x`` and ``y`` scales.
coord : coord
Coordinate (e.g. coord_cartesian) system of the geom.
Returns
-------
out : tuple
The bases (base_x, base_y) to use when generating the ticks. | [
"Check",
"the",
"log",
"transforms"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/geoms/annotation_logticks.py#L25-L91 | train | 214,392 |
has2k1/plotnine | plotnine/geoms/annotation_logticks.py | _geom_logticks._calc_ticks | def _calc_ticks(value_range, base):
"""
Calculate tick marks within a range
Parameters
----------
value_range: tuple
Range for which to calculate ticks.
Returns
-------
out: tuple
(major, middle, minor) tick locations
"""
def _minor(x, mid_idx):
return np.hstack([x[1:mid_idx], x[mid_idx+1:-1]])
# * Calculate the low and high powers,
# * Generate for all intervals in along the low-high power range
# The intervals are in normal space
# * Calculate evenly spaced breaks in normal space, then convert
# them to log space.
low = np.floor(value_range[0])
high = np.ceil(value_range[1])
arr = base ** np.arange(low, float(high+1))
n_ticks = base - 1
breaks = [log(np.linspace(b1, b2, n_ticks+1), base)
for (b1, b2) in list(zip(arr, arr[1:]))]
# Partition the breaks in the 3 groups
major = np.array([x[0] for x in breaks] + [breaks[-1][-1]])
if n_ticks % 2:
mid_idx = n_ticks // 2
middle = [x[mid_idx] for x in breaks]
minor = np.hstack([_minor(x, mid_idx) for x in breaks])
else:
middle = []
minor = np.hstack([x[1:-1] for x in breaks])
return major, middle, minor | python | def _calc_ticks(value_range, base):
"""
Calculate tick marks within a range
Parameters
----------
value_range: tuple
Range for which to calculate ticks.
Returns
-------
out: tuple
(major, middle, minor) tick locations
"""
def _minor(x, mid_idx):
return np.hstack([x[1:mid_idx], x[mid_idx+1:-1]])
# * Calculate the low and high powers,
# * Generate for all intervals in along the low-high power range
# The intervals are in normal space
# * Calculate evenly spaced breaks in normal space, then convert
# them to log space.
low = np.floor(value_range[0])
high = np.ceil(value_range[1])
arr = base ** np.arange(low, float(high+1))
n_ticks = base - 1
breaks = [log(np.linspace(b1, b2, n_ticks+1), base)
for (b1, b2) in list(zip(arr, arr[1:]))]
# Partition the breaks in the 3 groups
major = np.array([x[0] for x in breaks] + [breaks[-1][-1]])
if n_ticks % 2:
mid_idx = n_ticks // 2
middle = [x[mid_idx] for x in breaks]
minor = np.hstack([_minor(x, mid_idx) for x in breaks])
else:
middle = []
minor = np.hstack([x[1:-1] for x in breaks])
return major, middle, minor | [
"def",
"_calc_ticks",
"(",
"value_range",
",",
"base",
")",
":",
"def",
"_minor",
"(",
"x",
",",
"mid_idx",
")",
":",
"return",
"np",
".",
"hstack",
"(",
"[",
"x",
"[",
"1",
":",
"mid_idx",
"]",
",",
"x",
"[",
"mid_idx",
"+",
"1",
":",
"-",
"1"... | Calculate tick marks within a range
Parameters
----------
value_range: tuple
Range for which to calculate ticks.
Returns
-------
out: tuple
(major, middle, minor) tick locations | [
"Calculate",
"tick",
"marks",
"within",
"a",
"range"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/geoms/annotation_logticks.py#L94-L133 | train | 214,393 |
has2k1/plotnine | plotnine/options.py | get_option | def get_option(name):
"""
Get package option
Parameters
----------
name : str
Name of the option
"""
d = globals()
if name in {'get_option', 'set_option'} or name not in d:
from ..exceptions import PlotnineError
raise PlotnineError("Unknown option {}".format(name))
return d[name] | python | def get_option(name):
"""
Get package option
Parameters
----------
name : str
Name of the option
"""
d = globals()
if name in {'get_option', 'set_option'} or name not in d:
from ..exceptions import PlotnineError
raise PlotnineError("Unknown option {}".format(name))
return d[name] | [
"def",
"get_option",
"(",
"name",
")",
":",
"d",
"=",
"globals",
"(",
")",
"if",
"name",
"in",
"{",
"'get_option'",
",",
"'set_option'",
"}",
"or",
"name",
"not",
"in",
"d",
":",
"from",
".",
".",
"exceptions",
"import",
"PlotnineError",
"raise",
"Plot... | Get package option
Parameters
----------
name : str
Name of the option | [
"Get",
"package",
"option"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/options.py#L18-L33 | train | 214,394 |
has2k1/plotnine | plotnine/options.py | set_option | def set_option(name, value):
"""
Set package option
Parameters
----------
name : str
Name of the option
value : object
New value of the option
Returns
-------
old : object
Old value of the option
"""
d = globals()
if name in {'get_option', 'set_option'} or name not in d:
from ..exceptions import PlotnineError
raise PlotnineError("Unknown option {}".format(name))
old = d[name]
d[name] = value
return old | python | def set_option(name, value):
"""
Set package option
Parameters
----------
name : str
Name of the option
value : object
New value of the option
Returns
-------
old : object
Old value of the option
"""
d = globals()
if name in {'get_option', 'set_option'} or name not in d:
from ..exceptions import PlotnineError
raise PlotnineError("Unknown option {}".format(name))
old = d[name]
d[name] = value
return old | [
"def",
"set_option",
"(",
"name",
",",
"value",
")",
":",
"d",
"=",
"globals",
"(",
")",
"if",
"name",
"in",
"{",
"'get_option'",
",",
"'set_option'",
"}",
"or",
"name",
"not",
"in",
"d",
":",
"from",
".",
".",
"exceptions",
"import",
"PlotnineError",
... | Set package option
Parameters
----------
name : str
Name of the option
value : object
New value of the option
Returns
-------
old : object
Old value of the option | [
"Set",
"package",
"option"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/options.py#L36-L60 | train | 214,395 |
has2k1/plotnine | plotnine/scales/limits.py | expand_limits | def expand_limits(**kwargs):
"""
Expand the limits any aesthetic using data
Parameters
----------
kwargs : dict or dataframe
Data to use in expanding the limits.
The keys should be aesthetic names
e.g. *x*, *y*, *colour*, ...
"""
def as_list(key):
with suppress(KeyError):
if isinstance(kwargs[key], (int, float, str)):
kwargs[key] = [kwargs[key]]
if isinstance(kwargs, dict):
as_list('x')
as_list('y')
data = pd.DataFrame(kwargs)
else:
data = kwargs
mapping = {}
for ae in set(kwargs) & all_aesthetics:
mapping[ae] = ae
return geom_blank(mapping=mapping, data=data, inherit_aes=False) | python | def expand_limits(**kwargs):
"""
Expand the limits any aesthetic using data
Parameters
----------
kwargs : dict or dataframe
Data to use in expanding the limits.
The keys should be aesthetic names
e.g. *x*, *y*, *colour*, ...
"""
def as_list(key):
with suppress(KeyError):
if isinstance(kwargs[key], (int, float, str)):
kwargs[key] = [kwargs[key]]
if isinstance(kwargs, dict):
as_list('x')
as_list('y')
data = pd.DataFrame(kwargs)
else:
data = kwargs
mapping = {}
for ae in set(kwargs) & all_aesthetics:
mapping[ae] = ae
return geom_blank(mapping=mapping, data=data, inherit_aes=False) | [
"def",
"expand_limits",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"as_list",
"(",
"key",
")",
":",
"with",
"suppress",
"(",
"KeyError",
")",
":",
"if",
"isinstance",
"(",
"kwargs",
"[",
"key",
"]",
",",
"(",
"int",
",",
"float",
",",
"str",
")",
... | Expand the limits any aesthetic using data
Parameters
----------
kwargs : dict or dataframe
Data to use in expanding the limits.
The keys should be aesthetic names
e.g. *x*, *y*, *colour*, ... | [
"Expand",
"the",
"limits",
"any",
"aesthetic",
"using",
"data"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/limits.py#L188-L215 | train | 214,396 |
has2k1/plotnine | plotnine/scales/limits.py | _lim.get_scale | def get_scale(self, gg):
"""
Create a scale
"""
# This method does some introspection to save users from
# scale mismatch error. This could happen when the
# aesthetic is mapped to a categorical but the limits
# are not provided in categorical form. We only handle
# the case where the mapping uses an expression to
# conver to categorical e.g `aes(color='factor(cyl)')`.
# However if `'cyl'` column is a categorical and the
# mapping is `aes(color='cyl')`, that will result in
# an error. If later case proves common enough then we
# could inspect the data and be clever based on that too!!
ae = self.aesthetic
series = self.limits_series
ae_values = []
# Look through all the mappings for this aesthetic,
# if we detect any factor stuff then we convert the
# limits data to categorical so that the right scale
# can be choosen. This should take care of the most
# common use cases.
for layer in gg.layers:
with suppress(KeyError):
value = layer.mapping[ae]
if isinstance(value, str):
ae_values.append(value)
for value in ae_values:
if ('factor(' in value or
'Categorical(' in value):
series = pd.Categorical(self.limits_series)
break
return make_scale(self.aesthetic,
series,
limits=self.limits,
trans=self.trans) | python | def get_scale(self, gg):
"""
Create a scale
"""
# This method does some introspection to save users from
# scale mismatch error. This could happen when the
# aesthetic is mapped to a categorical but the limits
# are not provided in categorical form. We only handle
# the case where the mapping uses an expression to
# conver to categorical e.g `aes(color='factor(cyl)')`.
# However if `'cyl'` column is a categorical and the
# mapping is `aes(color='cyl')`, that will result in
# an error. If later case proves common enough then we
# could inspect the data and be clever based on that too!!
ae = self.aesthetic
series = self.limits_series
ae_values = []
# Look through all the mappings for this aesthetic,
# if we detect any factor stuff then we convert the
# limits data to categorical so that the right scale
# can be choosen. This should take care of the most
# common use cases.
for layer in gg.layers:
with suppress(KeyError):
value = layer.mapping[ae]
if isinstance(value, str):
ae_values.append(value)
for value in ae_values:
if ('factor(' in value or
'Categorical(' in value):
series = pd.Categorical(self.limits_series)
break
return make_scale(self.aesthetic,
series,
limits=self.limits,
trans=self.trans) | [
"def",
"get_scale",
"(",
"self",
",",
"gg",
")",
":",
"# This method does some introspection to save users from",
"# scale mismatch error. This could happen when the",
"# aesthetic is mapped to a categorical but the limits",
"# are not provided in categorical form. We only handle",
"# the ca... | Create a scale | [
"Create",
"a",
"scale"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/limits.py#L46-L83 | train | 214,397 |
has2k1/plotnine | plotnine/geoms/geom.py | geom.from_stat | def from_stat(stat):
"""
Return an instantiated geom object
geoms should not override this method.
Parameters
----------
stat : stat
`stat`
Returns
-------
out : geom
A geom object
Raises
------
:class:`PlotnineError` if unable to create a `geom`.
"""
name = stat.params['geom']
if issubclass(type(name), geom):
return name
if isinstance(name, type) and issubclass(name, geom):
klass = name
elif is_string(name):
if not name.startswith('geom_'):
name = 'geom_{}'.format(name)
klass = Registry[name]
else:
raise PlotnineError(
'Unknown geom of type {}'.format(type(name)))
return klass(stat=stat, **stat._kwargs) | python | def from_stat(stat):
"""
Return an instantiated geom object
geoms should not override this method.
Parameters
----------
stat : stat
`stat`
Returns
-------
out : geom
A geom object
Raises
------
:class:`PlotnineError` if unable to create a `geom`.
"""
name = stat.params['geom']
if issubclass(type(name), geom):
return name
if isinstance(name, type) and issubclass(name, geom):
klass = name
elif is_string(name):
if not name.startswith('geom_'):
name = 'geom_{}'.format(name)
klass = Registry[name]
else:
raise PlotnineError(
'Unknown geom of type {}'.format(type(name)))
return klass(stat=stat, **stat._kwargs) | [
"def",
"from_stat",
"(",
"stat",
")",
":",
"name",
"=",
"stat",
".",
"params",
"[",
"'geom'",
"]",
"if",
"issubclass",
"(",
"type",
"(",
"name",
")",
",",
"geom",
")",
":",
"return",
"name",
"if",
"isinstance",
"(",
"name",
",",
"type",
")",
"and",... | Return an instantiated geom object
geoms should not override this method.
Parameters
----------
stat : stat
`stat`
Returns
-------
out : geom
A geom object
Raises
------
:class:`PlotnineError` if unable to create a `geom`. | [
"Return",
"an",
"instantiated",
"geom",
"object"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/geoms/geom.py#L50-L84 | train | 214,398 |
has2k1/plotnine | plotnine/geoms/geom.py | geom.aesthetics | def aesthetics(cls):
"""
Return all the aesthetics for this geom
geoms should not override this method.
"""
main = cls.DEFAULT_AES.keys() | cls.REQUIRED_AES
other = {'group'}
# Need to recognize both spellings
if 'color' in main:
other.add('colour')
if 'outlier_color' in main:
other.add('outlier_colour')
return main | other | python | def aesthetics(cls):
"""
Return all the aesthetics for this geom
geoms should not override this method.
"""
main = cls.DEFAULT_AES.keys() | cls.REQUIRED_AES
other = {'group'}
# Need to recognize both spellings
if 'color' in main:
other.add('colour')
if 'outlier_color' in main:
other.add('outlier_colour')
return main | other | [
"def",
"aesthetics",
"(",
"cls",
")",
":",
"main",
"=",
"cls",
".",
"DEFAULT_AES",
".",
"keys",
"(",
")",
"|",
"cls",
".",
"REQUIRED_AES",
"other",
"=",
"{",
"'group'",
"}",
"# Need to recognize both spellings",
"if",
"'color'",
"in",
"main",
":",
"other",... | Return all the aesthetics for this geom
geoms should not override this method. | [
"Return",
"all",
"the",
"aesthetics",
"for",
"this",
"geom"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/geoms/geom.py#L87-L100 | train | 214,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.