Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
Scattermapbox.__init__
( self, arg=None, below=None, connectgaps=None, customdata=None, customdatasrc=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legendgroup=None, line=None, lon=None, lonsrc=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textfont=None, textposition=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, **kwargs )
Construct a new Scattermapbox object The data visualized as scatter point, lines or marker symbols on a Mapbox GL geographic map is provided by longitude/latitude pairs in `lon` and `lat`. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.Scattermapbox` below Determines if this scattermapbox trace's layers are to be inserted before the layer with the specified ID. By default, scattermapbox layers are inserted above all the base layers. To place the scattermapbox layers above every other layer, set `below` to "''". connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scattermapbox.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for lat . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scattermapbox.Line` instance or dict with compatible properties lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for lon . marker :class:`plotly.graph_objects.scattermapbox.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. selected :class:`plotly.graph_objects.scattermapbox.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scattermapbox.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a mapbox subplot. If "mapbox" (the default value), the data refer to `layout.mapbox`. If "mapbox2", the data refer to `layout.mapbox2`, and so on. text Sets text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the icon text font (color=mapbox.layer.paint.text- color, size=mapbox.layer.layout.text-size). Has an effect only when `type` is set to "symbol". textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `lat`, `lon` and `text`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scattermapbox.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). Returns ------- Scattermapbox
Construct a new Scattermapbox object The data visualized as scatter point, lines or marker symbols on a Mapbox GL geographic map is provided by longitude/latitude pairs in `lon` and `lat`.
def __init__( self, arg=None, below=None, connectgaps=None, customdata=None, customdatasrc=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legendgroup=None, line=None, lon=None, lonsrc=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textfont=None, textposition=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, **kwargs ): """ Construct a new Scattermapbox object The data visualized as scatter point, lines or marker symbols on a Mapbox GL geographic map is provided by longitude/latitude pairs in `lon` and `lat`. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.Scattermapbox` below Determines if this scattermapbox trace's layers are to be inserted before the layer with the specified ID. By default, scattermapbox layers are inserted above all the base layers. To place the scattermapbox layers above every other layer, set `below` to "''". connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scattermapbox.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for lat . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scattermapbox.Line` instance or dict with compatible properties lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for lon . marker :class:`plotly.graph_objects.scattermapbox.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. selected :class:`plotly.graph_objects.scattermapbox.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scattermapbox.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a mapbox subplot. If "mapbox" (the default value), the data refer to `layout.mapbox`. If "mapbox2", the data refer to `layout.mapbox2`, and so on. text Sets text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the icon text font (color=mapbox.layer.paint.text- color, size=mapbox.layer.layout.text-size). Has an effect only when `type` is set to "symbol". textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api- reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `lat`, `lon` and `text`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scattermapbox.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). Returns ------- Scattermapbox """ super(Scattermapbox, self).__init__("scattermapbox") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.Scattermapbox constructor must be a dict or an instance of :class:`plotly.graph_objs.Scattermapbox`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("below", None) _v = below if below is not None else _v if _v is not None: self["below"] = _v _v = arg.pop("connectgaps", None) _v = connectgaps if connectgaps is not None else _v if _v is not None: self["connectgaps"] = _v _v = arg.pop("customdata", None) _v = customdata if customdata is not None else _v if _v is not None: self["customdata"] = _v _v = arg.pop("customdatasrc", None) _v = customdatasrc if customdatasrc is not None else _v if _v is not None: self["customdatasrc"] = _v _v = arg.pop("fill", None) _v = fill if fill is not None else _v if _v is not None: self["fill"] = _v _v = arg.pop("fillcolor", None) _v = fillcolor if fillcolor is not None else _v if _v is not None: self["fillcolor"] = _v _v = arg.pop("hoverinfo", None) _v = hoverinfo if hoverinfo is not None else _v if _v is not None: self["hoverinfo"] = _v _v = arg.pop("hoverinfosrc", None) _v = hoverinfosrc if hoverinfosrc is not None else _v if _v is not None: self["hoverinfosrc"] = _v _v = arg.pop("hoverlabel", None) _v = hoverlabel if hoverlabel is not None else _v if _v is not None: self["hoverlabel"] = _v _v = arg.pop("hovertemplate", None) _v = hovertemplate if hovertemplate is not None else _v if _v is not None: self["hovertemplate"] = _v _v = arg.pop("hovertemplatesrc", None) _v = hovertemplatesrc if hovertemplatesrc is not None else _v if _v is not None: self["hovertemplatesrc"] = _v _v = arg.pop("hovertext", None) _v = hovertext if hovertext is not None else _v if _v is not None: self["hovertext"] = _v _v = arg.pop("hovertextsrc", None) _v = hovertextsrc if hovertextsrc is not None else _v if _v is not None: self["hovertextsrc"] = _v _v = arg.pop("ids", None) _v = ids if ids is not None else _v if _v is not None: self["ids"] = _v _v = arg.pop("idssrc", None) _v = idssrc if idssrc is not None else _v if _v is not None: self["idssrc"] = _v _v = arg.pop("lat", None) _v = lat if lat is not None else _v if _v is not None: self["lat"] = _v _v = arg.pop("latsrc", None) _v = latsrc if latsrc is not None else _v if _v is not None: self["latsrc"] = _v _v = arg.pop("legendgroup", None) _v = legendgroup if legendgroup is not None else _v if _v is not None: self["legendgroup"] = _v _v = arg.pop("line", None) _v = line if line is not None else _v if _v is not None: self["line"] = _v _v = arg.pop("lon", None) _v = lon if lon is not None else _v if _v is not None: self["lon"] = _v _v = arg.pop("lonsrc", None) _v = lonsrc if lonsrc is not None else _v if _v is not None: self["lonsrc"] = _v _v = arg.pop("marker", None) _v = marker if marker is not None else _v if _v is not None: self["marker"] = _v _v = arg.pop("meta", None) _v = meta if meta is not None else _v if _v is not None: self["meta"] = _v _v = arg.pop("metasrc", None) _v = metasrc if metasrc is not None else _v if _v is not None: self["metasrc"] = _v _v = arg.pop("mode", None) _v = mode if mode is not None else _v if _v is not None: self["mode"] = _v _v = arg.pop("name", None) _v = name if name is not None else _v if _v is not None: self["name"] = _v _v = arg.pop("opacity", None) _v = opacity if opacity is not None else _v if _v is not None: self["opacity"] = _v _v = arg.pop("selected", None) _v = selected if selected is not None else _v if _v is not None: self["selected"] = _v _v = arg.pop("selectedpoints", None) _v = selectedpoints if selectedpoints is not None else _v if _v is not None: self["selectedpoints"] = _v _v = arg.pop("showlegend", None) _v = showlegend if showlegend is not None else _v if _v is not None: self["showlegend"] = _v _v = arg.pop("stream", None) _v = stream if stream is not None else _v if _v is not None: self["stream"] = _v _v = arg.pop("subplot", None) _v = subplot if subplot is not None else _v if _v is not None: self["subplot"] = _v _v = arg.pop("text", None) _v = text if text is not None else _v if _v is not None: self["text"] = _v _v = arg.pop("textfont", None) _v = textfont if textfont is not None else _v if _v is not None: self["textfont"] = _v _v = arg.pop("textposition", None) _v = textposition if textposition is not None else _v if _v is not None: self["textposition"] = _v _v = arg.pop("textsrc", None) _v = textsrc if textsrc is not None else _v if _v is not None: self["textsrc"] = _v _v = arg.pop("texttemplate", None) _v = texttemplate if texttemplate is not None else _v if _v is not None: self["texttemplate"] = _v _v = arg.pop("texttemplatesrc", None) _v = texttemplatesrc if texttemplatesrc is not None else _v if _v is not None: self["texttemplatesrc"] = _v _v = arg.pop("uid", None) _v = uid if uid is not None else _v if _v is not None: self["uid"] = _v _v = arg.pop("uirevision", None) _v = uirevision if uirevision is not None else _v if _v is not None: self["uirevision"] = _v _v = arg.pop("unselected", None) _v = unselected if unselected is not None else _v if _v is not None: self["unselected"] = _v _v = arg.pop("visible", None) _v = visible if visible is not None else _v if _v is not None: self["visible"] = _v # Read-only literals # ------------------ self._props["type"] = "scattermapbox" arg.pop("type", None) # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "below", "=", "None", ",", "connectgaps", "=", "None", ",", "customdata", "=", "None", ",", "customdatasrc", "=", "None", ",", "fill", "=", "None", ",", "fillcolor", "=", "None", ",", "hoverinfo", "=", "None", ",", "hoverinfosrc", "=", "None", ",", "hoverlabel", "=", "None", ",", "hovertemplate", "=", "None", ",", "hovertemplatesrc", "=", "None", ",", "hovertext", "=", "None", ",", "hovertextsrc", "=", "None", ",", "ids", "=", "None", ",", "idssrc", "=", "None", ",", "lat", "=", "None", ",", "latsrc", "=", "None", ",", "legendgroup", "=", "None", ",", "line", "=", "None", ",", "lon", "=", "None", ",", "lonsrc", "=", "None", ",", "marker", "=", "None", ",", "meta", "=", "None", ",", "metasrc", "=", "None", ",", "mode", "=", "None", ",", "name", "=", "None", ",", "opacity", "=", "None", ",", "selected", "=", "None", ",", "selectedpoints", "=", "None", ",", "showlegend", "=", "None", ",", "stream", "=", "None", ",", "subplot", "=", "None", ",", "text", "=", "None", ",", "textfont", "=", "None", ",", "textposition", "=", "None", ",", "textsrc", "=", "None", ",", "texttemplate", "=", "None", ",", "texttemplatesrc", "=", "None", ",", "uid", "=", "None", ",", "uirevision", "=", "None", ",", "unselected", "=", "None", ",", "visible", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Scattermapbox", ",", "self", ")", ".", "__init__", "(", "\"scattermapbox\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.Scattermapbox \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.Scattermapbox`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"below\"", ",", "None", ")", "_v", "=", "below", "if", "below", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"below\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"connectgaps\"", ",", "None", ")", "_v", "=", "connectgaps", "if", "connectgaps", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"connectgaps\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"customdata\"", ",", "None", ")", "_v", "=", "customdata", "if", "customdata", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"customdata\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"customdatasrc\"", ",", "None", ")", "_v", "=", "customdatasrc", "if", "customdatasrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"customdatasrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"fill\"", ",", "None", ")", "_v", "=", "fill", "if", "fill", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"fill\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"fillcolor\"", ",", "None", ")", "_v", "=", "fillcolor", "if", "fillcolor", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"fillcolor\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"hoverinfo\"", ",", "None", ")", "_v", "=", "hoverinfo", "if", "hoverinfo", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"hoverinfo\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"hoverinfosrc\"", ",", "None", ")", "_v", "=", "hoverinfosrc", "if", "hoverinfosrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"hoverinfosrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"hoverlabel\"", ",", "None", ")", "_v", "=", "hoverlabel", "if", "hoverlabel", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"hoverlabel\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"hovertemplate\"", ",", "None", ")", "_v", "=", "hovertemplate", "if", "hovertemplate", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"hovertemplate\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"hovertemplatesrc\"", ",", "None", ")", "_v", "=", "hovertemplatesrc", "if", "hovertemplatesrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"hovertemplatesrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"hovertext\"", ",", "None", ")", "_v", "=", "hovertext", "if", "hovertext", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"hovertext\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"hovertextsrc\"", ",", "None", ")", "_v", "=", "hovertextsrc", "if", "hovertextsrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"hovertextsrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"ids\"", ",", "None", ")", "_v", "=", "ids", "if", "ids", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"ids\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"idssrc\"", ",", "None", ")", "_v", "=", "idssrc", "if", "idssrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"idssrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"lat\"", ",", "None", ")", "_v", "=", "lat", "if", "lat", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"lat\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"latsrc\"", ",", "None", ")", "_v", "=", "latsrc", "if", "latsrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"latsrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"legendgroup\"", ",", "None", ")", "_v", "=", "legendgroup", "if", "legendgroup", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"legendgroup\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"line\"", ",", "None", ")", "_v", "=", "line", "if", "line", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"line\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"lon\"", ",", "None", ")", "_v", "=", "lon", "if", "lon", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"lon\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"lonsrc\"", ",", "None", ")", "_v", "=", "lonsrc", "if", "lonsrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"lonsrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"marker\"", ",", "None", ")", "_v", "=", "marker", "if", "marker", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"marker\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"meta\"", ",", "None", ")", "_v", "=", "meta", "if", "meta", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"meta\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"metasrc\"", ",", "None", ")", "_v", "=", "metasrc", "if", "metasrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"metasrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"mode\"", ",", "None", ")", "_v", "=", "mode", "if", "mode", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"mode\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"name\"", ",", "None", ")", "_v", "=", "name", "if", "name", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"name\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"opacity\"", ",", "None", ")", "_v", "=", "opacity", "if", "opacity", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"opacity\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"selected\"", ",", "None", ")", "_v", "=", "selected", "if", "selected", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"selected\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"selectedpoints\"", ",", "None", ")", "_v", "=", "selectedpoints", "if", "selectedpoints", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"selectedpoints\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"showlegend\"", ",", "None", ")", "_v", "=", "showlegend", "if", "showlegend", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"showlegend\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"stream\"", ",", "None", ")", "_v", "=", "stream", "if", "stream", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"stream\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"subplot\"", ",", "None", ")", "_v", "=", "subplot", "if", "subplot", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"subplot\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"text\"", ",", "None", ")", "_v", "=", "text", "if", "text", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"text\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"textfont\"", ",", "None", ")", "_v", "=", "textfont", "if", "textfont", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"textfont\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"textposition\"", ",", "None", ")", "_v", "=", "textposition", "if", "textposition", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"textposition\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"textsrc\"", ",", "None", ")", "_v", "=", "textsrc", "if", "textsrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"textsrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"texttemplate\"", ",", "None", ")", "_v", "=", "texttemplate", "if", "texttemplate", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"texttemplate\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"texttemplatesrc\"", ",", "None", ")", "_v", "=", "texttemplatesrc", "if", "texttemplatesrc", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"texttemplatesrc\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"uid\"", ",", "None", ")", "_v", "=", "uid", "if", "uid", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"uid\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"uirevision\"", ",", "None", ")", "_v", "=", "uirevision", "if", "uirevision", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"uirevision\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"unselected\"", ",", "None", ")", "_v", "=", "unselected", "if", "unselected", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"unselected\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"visible\"", ",", "None", ")", "_v", "=", "visible", "if", "visible", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"visible\"", "]", "=", "_v", "# Read-only literals", "# ------------------", "self", ".", "_props", "[", "\"type\"", "]", "=", "\"scattermapbox\"", "arg", ".", "pop", "(", "\"type\"", ",", "None", ")", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 1527, 4 ]
[ 2016, 34 ]
python
en
['en', 'error', 'th']
False
Unselected.marker
(self)
The 'marker' property is an instance of Marker that may be specified as: - An instance of :class:`plotly.graph_objs.bar.unselected.Marker` - A dict of string/value properties that will be passed to the Marker constructor Supported dict properties: color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. Returns ------- plotly.graph_objs.bar.unselected.Marker
The 'marker' property is an instance of Marker that may be specified as: - An instance of :class:`plotly.graph_objs.bar.unselected.Marker` - A dict of string/value properties that will be passed to the Marker constructor Supported dict properties: color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists.
def marker(self): """ The 'marker' property is an instance of Marker that may be specified as: - An instance of :class:`plotly.graph_objs.bar.unselected.Marker` - A dict of string/value properties that will be passed to the Marker constructor Supported dict properties: color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. Returns ------- plotly.graph_objs.bar.unselected.Marker """ return self["marker"]
[ "def", "marker", "(", "self", ")", ":", "return", "self", "[", "\"marker\"", "]" ]
[ 15, 4 ]
[ 36, 29 ]
python
en
['en', 'error', 'th']
False
Unselected.textfont
(self)
The 'textfont' property is an instance of Textfont that may be specified as: - An instance of :class:`plotly.graph_objs.bar.unselected.Textfont` - A dict of string/value properties that will be passed to the Textfont constructor Supported dict properties: color Sets the text font color of unselected points, applied only when a selection exists. Returns ------- plotly.graph_objs.bar.unselected.Textfont
The 'textfont' property is an instance of Textfont that may be specified as: - An instance of :class:`plotly.graph_objs.bar.unselected.Textfont` - A dict of string/value properties that will be passed to the Textfont constructor Supported dict properties: color Sets the text font color of unselected points, applied only when a selection exists.
def textfont(self): """ The 'textfont' property is an instance of Textfont that may be specified as: - An instance of :class:`plotly.graph_objs.bar.unselected.Textfont` - A dict of string/value properties that will be passed to the Textfont constructor Supported dict properties: color Sets the text font color of unselected points, applied only when a selection exists. Returns ------- plotly.graph_objs.bar.unselected.Textfont """ return self["textfont"]
[ "def", "textfont", "(", "self", ")", ":", "return", "self", "[", "\"textfont\"", "]" ]
[ 45, 4 ]
[ 63, 31 ]
python
en
['en', 'error', 'th']
False
Unselected.__init__
(self, arg=None, marker=None, textfont=None, **kwargs)
Construct a new Unselected object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.bar.Unselected` marker :class:`plotly.graph_objects.bar.unselected.Marker` instance or dict with compatible properties textfont :class:`plotly.graph_objects.bar.unselected.Textfont` instance or dict with compatible properties Returns ------- Unselected
Construct a new Unselected object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.bar.Unselected` marker :class:`plotly.graph_objects.bar.unselected.Marker` instance or dict with compatible properties textfont :class:`plotly.graph_objects.bar.unselected.Textfont` instance or dict with compatible properties
def __init__(self, arg=None, marker=None, textfont=None, **kwargs): """ Construct a new Unselected object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.bar.Unselected` marker :class:`plotly.graph_objects.bar.unselected.Marker` instance or dict with compatible properties textfont :class:`plotly.graph_objects.bar.unselected.Textfont` instance or dict with compatible properties Returns ------- Unselected """ super(Unselected, self).__init__("unselected") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.bar.Unselected constructor must be a dict or an instance of :class:`plotly.graph_objs.bar.Unselected`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("marker", None) _v = marker if marker is not None else _v if _v is not None: self["marker"] = _v _v = arg.pop("textfont", None) _v = textfont if textfont is not None else _v if _v is not None: self["textfont"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "marker", "=", "None", ",", "textfont", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Unselected", ",", "self", ")", ".", "__init__", "(", "\"unselected\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.bar.Unselected \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.bar.Unselected`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"marker\"", ",", "None", ")", "_v", "=", "marker", "if", "marker", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"marker\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"textfont\"", ",", "None", ")", "_v", "=", "textfont", "if", "textfont", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"textfont\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 82, 4 ]
[ 147, 34 ]
python
en
['en', 'error', 'th']
False
roll_init
(character)
Rolls a number between 1-1000 to determine initiative. Args: character (obj): The character to determine initiative for Returns: initiative (int): The character's place in initiative - higher numbers go first. Notes: By default, does not reference the character and simply returns a random integer from 1 to 1000. Since the character is passed to this function, you can easily reference a character's stats to determine an initiative roll - for example, if your character has a 'dexterity' attribute, you can use it to give that character an advantage in turn order, like so: return (randint(1,20)) + character.db.dexterity This way, characters with a higher dexterity will go first more often.
Rolls a number between 1-1000 to determine initiative.
def roll_init(character): """ Rolls a number between 1-1000 to determine initiative. Args: character (obj): The character to determine initiative for Returns: initiative (int): The character's place in initiative - higher numbers go first. Notes: By default, does not reference the character and simply returns a random integer from 1 to 1000. Since the character is passed to this function, you can easily reference a character's stats to determine an initiative roll - for example, if your character has a 'dexterity' attribute, you can use it to give that character an advantage in turn order, like so: return (randint(1,20)) + character.db.dexterity This way, characters with a higher dexterity will go first more often. """ return randint(1, 1000)
[ "def", "roll_init", "(", "character", ")", ":", "return", "randint", "(", "1", ",", "1000", ")" ]
[ 104, 0 ]
[ 128, 27 ]
python
en
['en', 'error', 'th']
False
get_attack
(attacker, defender)
Returns a value for an attack roll. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: attack_value (int): Attack roll value, compared against a defense value to determine whether an attack hits or misses. Notes: This is where conditions affecting attack rolls are applied, as well. Accuracy Up and Accuracy Down are also accounted for in itemfunc_attack(), so that attack items' accuracy is affected as well.
Returns a value for an attack roll.
def get_attack(attacker, defender): """ Returns a value for an attack roll. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: attack_value (int): Attack roll value, compared against a defense value to determine whether an attack hits or misses. Notes: This is where conditions affecting attack rolls are applied, as well. Accuracy Up and Accuracy Down are also accounted for in itemfunc_attack(), so that attack items' accuracy is affected as well. """ # For this example, just return a random integer up to 100. attack_value = randint(1, 100) # Add to the roll if the attacker has the "Accuracy Up" condition. if "Accuracy Up" in attacker.db.conditions: attack_value += ACC_UP_MOD # Subtract from the roll if the attack has the "Accuracy Down" condition. if "Accuracy Down" in attacker.db.conditions: attack_value += ACC_DOWN_MOD return attack_value
[ "def", "get_attack", "(", "attacker", ",", "defender", ")", ":", "# For this example, just return a random integer up to 100.", "attack_value", "=", "randint", "(", "1", ",", "100", ")", "# Add to the roll if the attacker has the \"Accuracy Up\" condition.", "if", "\"Accuracy Up\"", "in", "attacker", ".", "db", ".", "conditions", ":", "attack_value", "+=", "ACC_UP_MOD", "# Subtract from the roll if the attack has the \"Accuracy Down\" condition.", "if", "\"Accuracy Down\"", "in", "attacker", ".", "db", ".", "conditions", ":", "attack_value", "+=", "ACC_DOWN_MOD", "return", "attack_value" ]
[ 131, 0 ]
[ 156, 23 ]
python
en
['en', 'error', 'th']
False
get_defense
(attacker, defender)
Returns a value for defense, which an attack roll must equal or exceed in order for an attack to hit. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: defense_value (int): Defense value, compared against an attack roll to determine whether an attack hits or misses. Notes: This is where conditions affecting defense are accounted for.
Returns a value for defense, which an attack roll must equal or exceed in order for an attack to hit.
def get_defense(attacker, defender): """ Returns a value for defense, which an attack roll must equal or exceed in order for an attack to hit. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: defense_value (int): Defense value, compared against an attack roll to determine whether an attack hits or misses. Notes: This is where conditions affecting defense are accounted for. """ # For this example, just return 50, for about a 50/50 chance of hit. defense_value = 50 # Add to defense if the defender has the "Defense Up" condition. if "Defense Up" in defender.db.conditions: defense_value += DEF_UP_MOD # Subtract from defense if the defender has the "Defense Down" condition. if "Defense Down" in defender.db.conditions: defense_value += DEF_DOWN_MOD return defense_value
[ "def", "get_defense", "(", "attacker", ",", "defender", ")", ":", "# For this example, just return 50, for about a 50/50 chance of hit.", "defense_value", "=", "50", "# Add to defense if the defender has the \"Defense Up\" condition.", "if", "\"Defense Up\"", "in", "defender", ".", "db", ".", "conditions", ":", "defense_value", "+=", "DEF_UP_MOD", "# Subtract from defense if the defender has the \"Defense Down\" condition.", "if", "\"Defense Down\"", "in", "defender", ".", "db", ".", "conditions", ":", "defense_value", "+=", "DEF_DOWN_MOD", "return", "defense_value" ]
[ 159, 0 ]
[ 183, 24 ]
python
en
['en', 'error', 'th']
False
get_damage
(attacker, defender)
Returns a value for damage to be deducted from the defender's HP after abilities successful hit. Args: attacker (obj): Character doing the attacking defender (obj): Character being damaged Returns: damage_value (int): Damage value, which is to be deducted from the defending character's HP. Notes: This is where conditions affecting damage are accounted for. Since attack items roll their own damage in itemfunc_attack(), their damage is unaffected by any conditions.
Returns a value for damage to be deducted from the defender's HP after abilities successful hit.
def get_damage(attacker, defender): """ Returns a value for damage to be deducted from the defender's HP after abilities successful hit. Args: attacker (obj): Character doing the attacking defender (obj): Character being damaged Returns: damage_value (int): Damage value, which is to be deducted from the defending character's HP. Notes: This is where conditions affecting damage are accounted for. Since attack items roll their own damage in itemfunc_attack(), their damage is unaffected by any conditions. """ # For this example, just generate a number between 15 and 25. damage_value = randint(15, 25) # Add to damage roll if attacker has the "Damage Up" condition. if "Damage Up" in attacker.db.conditions: damage_value += DMG_UP_MOD # Subtract from the roll if the attacker has the "Damage Down" condition. if "Damage Down" in attacker.db.conditions: damage_value += DMG_DOWN_MOD return damage_value
[ "def", "get_damage", "(", "attacker", ",", "defender", ")", ":", "# For this example, just generate a number between 15 and 25.", "damage_value", "=", "randint", "(", "15", ",", "25", ")", "# Add to damage roll if attacker has the \"Damage Up\" condition.", "if", "\"Damage Up\"", "in", "attacker", ".", "db", ".", "conditions", ":", "damage_value", "+=", "DMG_UP_MOD", "# Subtract from the roll if the attacker has the \"Damage Down\" condition.", "if", "\"Damage Down\"", "in", "attacker", ".", "db", ".", "conditions", ":", "damage_value", "+=", "DMG_DOWN_MOD", "return", "damage_value" ]
[ 186, 0 ]
[ 212, 23 ]
python
en
['en', 'error', 'th']
False
apply_damage
(defender, damage)
Applies damage to a target, reducing their HP by the damage amount to a minimum of 0. Args: defender (obj): Character taking damage damage (int): Amount of damage being taken
Applies damage to a target, reducing their HP by the damage amount to a minimum of 0.
def apply_damage(defender, damage): """ Applies damage to a target, reducing their HP by the damage amount to a minimum of 0. Args: defender (obj): Character taking damage damage (int): Amount of damage being taken """ defender.db.hp -= damage # Reduce defender's HP by the damage dealt. # If this reduces it to 0 or less, set HP to 0. if defender.db.hp <= 0: defender.db.hp = 0
[ "def", "apply_damage", "(", "defender", ",", "damage", ")", ":", "defender", ".", "db", ".", "hp", "-=", "damage", "# Reduce defender's HP by the damage dealt.", "# If this reduces it to 0 or less, set HP to 0.", "if", "defender", ".", "db", ".", "hp", "<=", "0", ":", "defender", ".", "db", ".", "hp", "=", "0" ]
[ 215, 0 ]
[ 227, 26 ]
python
en
['en', 'error', 'th']
False
at_defeat
(defeated)
Announces the defeat of a fighter in combat. Args: defeated (obj): Fighter that's been defeated. Notes: All this does is announce a defeat message by default, but if you want anything else to happen to defeated fighters (like putting them into a dying state or something similar) then this is the place to do it.
Announces the defeat of a fighter in combat.
def at_defeat(defeated): """ Announces the defeat of a fighter in combat. Args: defeated (obj): Fighter that's been defeated. Notes: All this does is announce a defeat message by default, but if you want anything else to happen to defeated fighters (like putting them into a dying state or something similar) then this is the place to do it. """ defeated.location.msg_contents("%s has been defeated!" % defeated)
[ "def", "at_defeat", "(", "defeated", ")", ":", "defeated", ".", "location", ".", "msg_contents", "(", "\"%s has been defeated!\"", "%", "defeated", ")" ]
[ 229, 0 ]
[ 242, 70 ]
python
en
['en', 'error', 'th']
False
resolve_attack
(attacker, defender, attack_value=None, defense_value=None, damage_value=None, inflict_condition=[])
Resolves an attack and outputs the result. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Options: attack_value (int): Override for attack roll defense_value (int): Override for defense value damage_value (int): Override for damage value inflict_condition (list): Conditions to inflict upon hit, a list of tuples formated as (condition(str), duration(int)) Notes: This function is called by normal attacks as well as attacks made with items.
Resolves an attack and outputs the result.
def resolve_attack(attacker, defender, attack_value=None, defense_value=None, damage_value=None, inflict_condition=[]): """ Resolves an attack and outputs the result. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Options: attack_value (int): Override for attack roll defense_value (int): Override for defense value damage_value (int): Override for damage value inflict_condition (list): Conditions to inflict upon hit, a list of tuples formated as (condition(str), duration(int)) Notes: This function is called by normal attacks as well as attacks made with items. """ # Get an attack roll from the attacker. if not attack_value: attack_value = get_attack(attacker, defender) # Get a defense value from the defender. if not defense_value: defense_value = get_defense(attacker, defender) # If the attack value is lower than the defense value, miss. Otherwise, hit. if attack_value < defense_value: attacker.location.msg_contents("%s's attack misses %s!" % (attacker, defender)) else: if not damage_value: damage_value = get_damage(attacker, defender) # Calculate damage value. # Announce damage dealt and apply damage. attacker.location.msg_contents("%s hits %s for %i damage!" % (attacker, defender, damage_value)) apply_damage(defender, damage_value) # Inflict conditions on hit, if any specified for condition in inflict_condition: add_condition(defender, attacker, condition[0], condition[1]) # If defender HP is reduced to 0 or less, call at_defeat. if defender.db.hp <= 0: at_defeat(defender)
[ "def", "resolve_attack", "(", "attacker", ",", "defender", ",", "attack_value", "=", "None", ",", "defense_value", "=", "None", ",", "damage_value", "=", "None", ",", "inflict_condition", "=", "[", "]", ")", ":", "# Get an attack roll from the attacker.", "if", "not", "attack_value", ":", "attack_value", "=", "get_attack", "(", "attacker", ",", "defender", ")", "# Get a defense value from the defender.", "if", "not", "defense_value", ":", "defense_value", "=", "get_defense", "(", "attacker", ",", "defender", ")", "# If the attack value is lower than the defense value, miss. Otherwise, hit.", "if", "attack_value", "<", "defense_value", ":", "attacker", ".", "location", ".", "msg_contents", "(", "\"%s's attack misses %s!\"", "%", "(", "attacker", ",", "defender", ")", ")", "else", ":", "if", "not", "damage_value", ":", "damage_value", "=", "get_damage", "(", "attacker", ",", "defender", ")", "# Calculate damage value.", "# Announce damage dealt and apply damage.", "attacker", ".", "location", ".", "msg_contents", "(", "\"%s hits %s for %i damage!\"", "%", "(", "attacker", ",", "defender", ",", "damage_value", ")", ")", "apply_damage", "(", "defender", ",", "damage_value", ")", "# Inflict conditions on hit, if any specified", "for", "condition", "in", "inflict_condition", ":", "add_condition", "(", "defender", ",", "attacker", ",", "condition", "[", "0", "]", ",", "condition", "[", "1", "]", ")", "# If defender HP is reduced to 0 or less, call at_defeat.", "if", "defender", ".", "db", ".", "hp", "<=", "0", ":", "at_defeat", "(", "defender", ")" ]
[ 244, 0 ]
[ 284, 31 ]
python
en
['en', 'error', 'th']
False
combat_cleanup
(character)
Cleans up all the temporary combat-related attributes on a character. Args: character (obj): Character to have their combat attributes removed Notes: Any attribute whose key begins with 'combat_' is temporary and no longer needed once a fight ends.
Cleans up all the temporary combat-related attributes on a character.
def combat_cleanup(character): """ Cleans up all the temporary combat-related attributes on a character. Args: character (obj): Character to have their combat attributes removed Notes: Any attribute whose key begins with 'combat_' is temporary and no longer needed once a fight ends. """ for attr in character.attributes.all(): if attr.key[:7] == "combat_": # If the attribute name starts with 'combat_'... character.attributes.remove(key=attr.key)
[ "def", "combat_cleanup", "(", "character", ")", ":", "for", "attr", "in", "character", ".", "attributes", ".", "all", "(", ")", ":", "if", "attr", ".", "key", "[", ":", "7", "]", "==", "\"combat_\"", ":", "# If the attribute name starts with 'combat_'...", "character", ".", "attributes", ".", "remove", "(", "key", "=", "attr", ".", "key", ")" ]
[ 286, 0 ]
[ 299, 53 ]
python
en
['en', 'error', 'th']
False
is_in_combat
(character)
Returns true if the given character is in combat. Args: character (obj): Character to determine if is in combat or not Returns: (bool): True if in combat or False if not in combat
Returns true if the given character is in combat.
def is_in_combat(character): """ Returns true if the given character is in combat. Args: character (obj): Character to determine if is in combat or not Returns: (bool): True if in combat or False if not in combat """ return bool(character.db.combat_turnhandler)
[ "def", "is_in_combat", "(", "character", ")", ":", "return", "bool", "(", "character", ".", "db", ".", "combat_turnhandler", ")" ]
[ 302, 0 ]
[ 312, 48 ]
python
en
['en', 'error', 'th']
False
is_turn
(character)
Returns true if it's currently the given character's turn in combat. Args: character (obj): Character to determine if it is their turn or not Returns: (bool): True if it is their turn or False otherwise
Returns true if it's currently the given character's turn in combat.
def is_turn(character): """ Returns true if it's currently the given character's turn in combat. Args: character (obj): Character to determine if it is their turn or not Returns: (bool): True if it is their turn or False otherwise """ turnhandler = character.db.combat_turnhandler currentchar = turnhandler.db.fighters[turnhandler.db.turn] return bool(character == currentchar)
[ "def", "is_turn", "(", "character", ")", ":", "turnhandler", "=", "character", ".", "db", ".", "combat_turnhandler", "currentchar", "=", "turnhandler", ".", "db", ".", "fighters", "[", "turnhandler", ".", "db", ".", "turn", "]", "return", "bool", "(", "character", "==", "currentchar", ")" ]
[ 315, 0 ]
[ 327, 41 ]
python
en
['en', 'error', 'th']
False
spend_action
(character, actions, action_name=None)
Spends a character's available combat actions and checks for end of turn. Args: character (obj): Character spending the action actions (int) or 'all': Number of actions to spend, or 'all' to spend all actions Kwargs: action_name (str or None): If a string is given, sets character's last action in combat to provided string
Spends a character's available combat actions and checks for end of turn.
def spend_action(character, actions, action_name=None): """ Spends a character's available combat actions and checks for end of turn. Args: character (obj): Character spending the action actions (int) or 'all': Number of actions to spend, or 'all' to spend all actions Kwargs: action_name (str or None): If a string is given, sets character's last action in combat to provided string """ if action_name: character.db.combat_lastaction = action_name if actions == 'all': # If spending all actions character.db.combat_actionsleft = 0 # Set actions to 0 else: character.db.combat_actionsleft -= actions # Use up actions. if character.db.combat_actionsleft < 0: character.db.combat_actionsleft = 0 # Can't have fewer than 0 actions character.db.combat_turnhandler.turn_end_check(character)
[ "def", "spend_action", "(", "character", ",", "actions", ",", "action_name", "=", "None", ")", ":", "if", "action_name", ":", "character", ".", "db", ".", "combat_lastaction", "=", "action_name", "if", "actions", "==", "'all'", ":", "# If spending all actions", "character", ".", "db", ".", "combat_actionsleft", "=", "0", "# Set actions to 0", "else", ":", "character", ".", "db", ".", "combat_actionsleft", "-=", "actions", "# Use up actions.", "if", "character", ".", "db", ".", "combat_actionsleft", "<", "0", ":", "character", ".", "db", ".", "combat_actionsleft", "=", "0", "# Can't have fewer than 0 actions", "character", ".", "db", ".", "combat_turnhandler", ".", "turn_end_check", "(", "character", ")" ]
[ 330, 0 ]
[ 350, 61 ]
python
en
['en', 'error', 'th']
False
spend_item_use
(item, user)
Spends one use on an item with limited uses. Args: item (obj): Item being used user (obj): Character using the item Notes: If item.db.item_consumable is 'True', the item is destroyed if it runs out of uses - if it's a string instead of 'True', it will also spawn a new object as residue, using the value of item.db.item_consumable as the name of the prototype to spawn.
Spends one use on an item with limited uses.
def spend_item_use(item, user): """ Spends one use on an item with limited uses. Args: item (obj): Item being used user (obj): Character using the item Notes: If item.db.item_consumable is 'True', the item is destroyed if it runs out of uses - if it's a string instead of 'True', it will also spawn a new object as residue, using the value of item.db.item_consumable as the name of the prototype to spawn. """ item.db.item_uses -= 1 # Spend one use if item.db.item_uses > 0: # Has uses remaining # Inform the player user.msg("%s has %i uses remaining." % (item.key.capitalize(), item.db.item_uses)) else: # All uses spent if not item.db.item_consumable: # Item isn't consumable # Just inform the player that the uses are gone user.msg("%s has no uses remaining." % item.key.capitalize()) else: # If item is consumable if item.db.item_consumable == True: # If the value is 'True', just destroy the item user.msg("%s has been consumed." % item.key.capitalize()) item.delete() # Delete the spent item else: # If a string, use value of item_consumable to spawn an object in its place residue = spawn({"prototype":item.db.item_consumable})[0] # Spawn the residue residue.location = item.location # Move the residue to the same place as the item user.msg("After using %s, you are left with %s." % (item, residue)) item.delete()
[ "def", "spend_item_use", "(", "item", ",", "user", ")", ":", "item", ".", "db", ".", "item_uses", "-=", "1", "# Spend one use", "if", "item", ".", "db", ".", "item_uses", ">", "0", ":", "# Has uses remaining", "# Inform the player", "user", ".", "msg", "(", "\"%s has %i uses remaining.\"", "%", "(", "item", ".", "key", ".", "capitalize", "(", ")", ",", "item", ".", "db", ".", "item_uses", ")", ")", "else", ":", "# All uses spent", "if", "not", "item", ".", "db", ".", "item_consumable", ":", "# Item isn't consumable", "# Just inform the player that the uses are gone", "user", ".", "msg", "(", "\"%s has no uses remaining.\"", "%", "item", ".", "key", ".", "capitalize", "(", ")", ")", "else", ":", "# If item is consumable", "if", "item", ".", "db", ".", "item_consumable", "==", "True", ":", "# If the value is 'True', just destroy the item", "user", ".", "msg", "(", "\"%s has been consumed.\"", "%", "item", ".", "key", ".", "capitalize", "(", ")", ")", "item", ".", "delete", "(", ")", "# Delete the spent item", "else", ":", "# If a string, use value of item_consumable to spawn an object in its place", "residue", "=", "spawn", "(", "{", "\"prototype\"", ":", "item", ".", "db", ".", "item_consumable", "}", ")", "[", "0", "]", "# Spawn the residue", "residue", ".", "location", "=", "item", ".", "location", "# Move the residue to the same place as the item", "user", ".", "msg", "(", "\"After using %s, you are left with %s.\"", "%", "(", "item", ",", "residue", ")", ")", "item", ".", "delete", "(", ")" ]
[ 352, 0 ]
[ 387, 29 ]
python
en
['en', 'error', 'th']
False
use_item
(user, item, target)
Performs the action of using an item. Args: user (obj): Character using the item item (obj): Item being used target (obj): Target of the item use
Performs the action of using an item.
def use_item(user, item, target): """ Performs the action of using an item. Args: user (obj): Character using the item item (obj): Item being used target (obj): Target of the item use """ # If item is self only and no target given, set target to self. if item.db.item_selfonly and target == None: target = user # If item is self only, abort use if used on others. if item.db.item_selfonly and user != target: user.msg("%s can only be used on yourself." % item) return # Set kwargs to pass to item_func kwargs = {} if item.db.item_kwargs: kwargs = item.db.item_kwargs # Match item_func string to function try: item_func = ITEMFUNCS[item.db.item_func] except KeyError: # If item_func string doesn't match to a function in ITEMFUNCS user.msg("ERROR: %s not defined in ITEMFUNCS" % item.db.item_func) return # Call the item function - abort if it returns False, indicating an error. # This performs the actual action of using the item. # Regardless of what the function returns (if anything), it's still executed. if item_func(item, user, target, **kwargs) == False: return # If we haven't returned yet, we assume the item was used successfully. # Spend one use if item has limited uses if item.db.item_uses: spend_item_use(item, user) # Spend an action if in combat if is_in_combat(user): spend_action(user, 1, action_name="item")
[ "def", "use_item", "(", "user", ",", "item", ",", "target", ")", ":", "# If item is self only and no target given, set target to self.", "if", "item", ".", "db", ".", "item_selfonly", "and", "target", "==", "None", ":", "target", "=", "user", "# If item is self only, abort use if used on others.", "if", "item", ".", "db", ".", "item_selfonly", "and", "user", "!=", "target", ":", "user", ".", "msg", "(", "\"%s can only be used on yourself.\"", "%", "item", ")", "return", "# Set kwargs to pass to item_func", "kwargs", "=", "{", "}", "if", "item", ".", "db", ".", "item_kwargs", ":", "kwargs", "=", "item", ".", "db", ".", "item_kwargs", "# Match item_func string to function", "try", ":", "item_func", "=", "ITEMFUNCS", "[", "item", ".", "db", ".", "item_func", "]", "except", "KeyError", ":", "# If item_func string doesn't match to a function in ITEMFUNCS", "user", ".", "msg", "(", "\"ERROR: %s not defined in ITEMFUNCS\"", "%", "item", ".", "db", ".", "item_func", ")", "return", "# Call the item function - abort if it returns False, indicating an error.", "# This performs the actual action of using the item.", "# Regardless of what the function returns (if anything), it's still executed.", "if", "item_func", "(", "item", ",", "user", ",", "target", ",", "*", "*", "kwargs", ")", "==", "False", ":", "return", "# If we haven't returned yet, we assume the item was used successfully.", "# Spend one use if item has limited uses", "if", "item", ".", "db", ".", "item_uses", ":", "spend_item_use", "(", "item", ",", "user", ")", "# Spend an action if in combat", "if", "is_in_combat", "(", "user", ")", ":", "spend_action", "(", "user", ",", "1", ",", "action_name", "=", "\"item\"", ")" ]
[ 389, 0 ]
[ 432, 49 ]
python
en
['en', 'error', 'th']
False
condition_tickdown
(character, turnchar)
Ticks down the duration of conditions on a character at the start of a given character's turn. Args: character (obj): Character to tick down the conditions of turnchar (obj): Character whose turn it currently is Notes: In combat, this is called on every fighter at the start of every character's turn. Out of combat, it's instead called when a character's at_update() hook is called, which is every 30 seconds by default.
Ticks down the duration of conditions on a character at the start of a given character's turn.
def condition_tickdown(character, turnchar): """ Ticks down the duration of conditions on a character at the start of a given character's turn. Args: character (obj): Character to tick down the conditions of turnchar (obj): Character whose turn it currently is Notes: In combat, this is called on every fighter at the start of every character's turn. Out of combat, it's instead called when a character's at_update() hook is called, which is every 30 seconds by default. """ for key in character.db.conditions: # The first value is the remaining turns - the second value is whose turn to count down on. condition_duration = character.db.conditions[key][0] condition_turnchar = character.db.conditions[key][1] # If the duration is 'True', then the condition doesn't tick down - it lasts indefinitely. if not condition_duration is True: # Count down if the given turn character matches the condition's turn character. if condition_turnchar == turnchar: character.db.conditions[key][0] -= 1 if character.db.conditions[key][0] <= 0: # If the duration is brought down to 0, remove the condition and inform everyone. character.location.msg_contents("%s no longer has the '%s' condition." % (str(character), str(key))) del character.db.conditions[key]
[ "def", "condition_tickdown", "(", "character", ",", "turnchar", ")", ":", "for", "key", "in", "character", ".", "db", ".", "conditions", ":", "# The first value is the remaining turns - the second value is whose turn to count down on.", "condition_duration", "=", "character", ".", "db", ".", "conditions", "[", "key", "]", "[", "0", "]", "condition_turnchar", "=", "character", ".", "db", ".", "conditions", "[", "key", "]", "[", "1", "]", "# If the duration is 'True', then the condition doesn't tick down - it lasts indefinitely.", "if", "not", "condition_duration", "is", "True", ":", "# Count down if the given turn character matches the condition's turn character.", "if", "condition_turnchar", "==", "turnchar", ":", "character", ".", "db", ".", "conditions", "[", "key", "]", "[", "0", "]", "-=", "1", "if", "character", ".", "db", ".", "conditions", "[", "key", "]", "[", "0", "]", "<=", "0", ":", "# If the duration is brought down to 0, remove the condition and inform everyone.", "character", ".", "location", ".", "msg_contents", "(", "\"%s no longer has the '%s' condition.\"", "%", "(", "str", "(", "character", ")", ",", "str", "(", "key", ")", ")", ")", "del", "character", ".", "db", ".", "conditions", "[", "key", "]" ]
[ 434, 0 ]
[ 460, 48 ]
python
en
['en', 'error', 'th']
False
add_condition
(character, turnchar, condition, duration)
Adds a condition to a fighter. Args: character (obj): Character to give the condition to turnchar (obj): Character whose turn to tick down the condition on in combat condition (str): Name of the condition duration (int or True): Number of turns the condition lasts, or True for indefinite
Adds a condition to a fighter.
def add_condition(character, turnchar, condition, duration): """ Adds a condition to a fighter. Args: character (obj): Character to give the condition to turnchar (obj): Character whose turn to tick down the condition on in combat condition (str): Name of the condition duration (int or True): Number of turns the condition lasts, or True for indefinite """ # The first value is the remaining turns - the second value is whose turn to count down on. character.db.conditions.update({condition:[duration, turnchar]}) # Tell everyone! character.location.msg_contents("%s gains the '%s' condition." % (character, condition))
[ "def", "add_condition", "(", "character", ",", "turnchar", ",", "condition", ",", "duration", ")", ":", "# The first value is the remaining turns - the second value is whose turn to count down on.", "character", ".", "db", ".", "conditions", ".", "update", "(", "{", "condition", ":", "[", "duration", ",", "turnchar", "]", "}", ")", "# Tell everyone!", "character", ".", "location", ".", "msg_contents", "(", "\"%s gains the '%s' condition.\"", "%", "(", "character", ",", "condition", ")", ")" ]
[ 462, 0 ]
[ 475, 92 ]
python
en
['en', 'error', 'th']
False
itemfunc_heal
(item, user, target, **kwargs)
Item function that heals HP. kwargs: min_healing(int): Minimum amount of HP recovered max_healing(int): Maximum amount of HP recovered
Item function that heals HP.
def itemfunc_heal(item, user, target, **kwargs): """ Item function that heals HP. kwargs: min_healing(int): Minimum amount of HP recovered max_healing(int): Maximum amount of HP recovered """ if not target: target = user # Target user if none specified if not target.attributes.has("max_hp"): # Has no HP to speak of user.msg("You can't use %s on that." % item) return False # Returning false aborts the item use if target.db.hp >= target.db.max_hp: user.msg("%s is already at full health." % target) return False min_healing = 20 max_healing = 40 # Retrieve healing range from kwargs, if present if "healing_range" in kwargs: min_healing = kwargs["healing_range"][0] max_healing = kwargs["healing_range"][1] to_heal = randint(min_healing, max_healing) # Restore 20 to 40 hp if target.db.hp + to_heal > target.db.max_hp: to_heal = target.db.max_hp - target.db.hp # Cap healing to max HP target.db.hp += to_heal user.location.msg_contents("%s uses %s! %s regains %i HP!" % (user, item, target, to_heal))
[ "def", "itemfunc_heal", "(", "item", ",", "user", ",", "target", ",", "*", "*", "kwargs", ")", ":", "if", "not", "target", ":", "target", "=", "user", "# Target user if none specified", "if", "not", "target", ".", "attributes", ".", "has", "(", "\"max_hp\"", ")", ":", "# Has no HP to speak of", "user", ".", "msg", "(", "\"You can't use %s on that.\"", "%", "item", ")", "return", "False", "# Returning false aborts the item use", "if", "target", ".", "db", ".", "hp", ">=", "target", ".", "db", ".", "max_hp", ":", "user", ".", "msg", "(", "\"%s is already at full health.\"", "%", "target", ")", "return", "False", "min_healing", "=", "20", "max_healing", "=", "40", "# Retrieve healing range from kwargs, if present", "if", "\"healing_range\"", "in", "kwargs", ":", "min_healing", "=", "kwargs", "[", "\"healing_range\"", "]", "[", "0", "]", "max_healing", "=", "kwargs", "[", "\"healing_range\"", "]", "[", "1", "]", "to_heal", "=", "randint", "(", "min_healing", ",", "max_healing", ")", "# Restore 20 to 40 hp", "if", "target", ".", "db", ".", "hp", "+", "to_heal", ">", "target", ".", "db", ".", "max_hp", ":", "to_heal", "=", "target", ".", "db", ".", "max_hp", "-", "target", ".", "db", ".", "hp", "# Cap healing to max HP", "target", ".", "db", ".", "hp", "+=", "to_heal", "user", ".", "location", ".", "msg_contents", "(", "\"%s uses %s! %s regains %i HP!\"", "%", "(", "user", ",", "item", ",", "target", ",", "to_heal", ")", ")" ]
[ 1103, 0 ]
[ 1135, 95 ]
python
en
['en', 'error', 'th']
False
itemfunc_add_condition
(item, user, target, **kwargs)
Item function that gives the target one or more conditions. kwargs: conditions (list): Conditions added by the item formatted as a list of tuples: (condition (str), duration (int or True)) Notes: Should mostly be used for beneficial conditions - use itemfunc_attack for an item that can give an enemy a harmful condition.
Item function that gives the target one or more conditions.
def itemfunc_add_condition(item, user, target, **kwargs): """ Item function that gives the target one or more conditions. kwargs: conditions (list): Conditions added by the item formatted as a list of tuples: (condition (str), duration (int or True)) Notes: Should mostly be used for beneficial conditions - use itemfunc_attack for an item that can give an enemy a harmful condition. """ conditions = [("Regeneration", 5)] if not target: target = user # Target user if none specified if not target.attributes.has("max_hp"): # Is not a fighter user.msg("You can't use %s on that." % item) return False # Returning false aborts the item use # Retrieve condition / duration from kwargs, if present if "conditions" in kwargs: conditions = kwargs["conditions"] user.location.msg_contents("%s uses %s!" % (user, item)) # Add conditions to the target for condition in conditions: add_condition(target, user, condition[0], condition[1])
[ "def", "itemfunc_add_condition", "(", "item", ",", "user", ",", "target", ",", "*", "*", "kwargs", ")", ":", "conditions", "=", "[", "(", "\"Regeneration\"", ",", "5", ")", "]", "if", "not", "target", ":", "target", "=", "user", "# Target user if none specified", "if", "not", "target", ".", "attributes", ".", "has", "(", "\"max_hp\"", ")", ":", "# Is not a fighter", "user", ".", "msg", "(", "\"You can't use %s on that.\"", "%", "item", ")", "return", "False", "# Returning false aborts the item use", "# Retrieve condition / duration from kwargs, if present", "if", "\"conditions\"", "in", "kwargs", ":", "conditions", "=", "kwargs", "[", "\"conditions\"", "]", "user", ".", "location", ".", "msg_contents", "(", "\"%s uses %s!\"", "%", "(", "user", ",", "item", ")", ")", "# Add conditions to the target", "for", "condition", "in", "conditions", ":", "add_condition", "(", "target", ",", "user", ",", "condition", "[", "0", "]", ",", "condition", "[", "1", "]", ")" ]
[ 1137, 0 ]
[ 1166, 63 ]
python
en
['en', 'error', 'th']
False
itemfunc_cure_condition
(item, user, target, **kwargs)
Item function that'll remove given conditions from a target. kwargs: to_cure(list): List of conditions (str) that the item cures when used
Item function that'll remove given conditions from a target.
def itemfunc_cure_condition(item, user, target, **kwargs): """ Item function that'll remove given conditions from a target. kwargs: to_cure(list): List of conditions (str) that the item cures when used """ to_cure = ["Poisoned"] if not target: target = user # Target user if none specified if not target.attributes.has("max_hp"): # Is not a fighter user.msg("You can't use %s on that." % item) return False # Returning false aborts the item use # Retrieve condition(s) to cure from kwargs, if present if "to_cure" in kwargs: to_cure = kwargs["to_cure"] item_msg = "%s uses %s! " % (user, item) for key in target.db.conditions: if key in to_cure: # If condition specified in to_cure, remove it. item_msg += "%s no longer has the '%s' condition. " % (str(target), str(key)) del target.db.conditions[key] user.location.msg_contents(item_msg)
[ "def", "itemfunc_cure_condition", "(", "item", ",", "user", ",", "target", ",", "*", "*", "kwargs", ")", ":", "to_cure", "=", "[", "\"Poisoned\"", "]", "if", "not", "target", ":", "target", "=", "user", "# Target user if none specified", "if", "not", "target", ".", "attributes", ".", "has", "(", "\"max_hp\"", ")", ":", "# Is not a fighter", "user", ".", "msg", "(", "\"You can't use %s on that.\"", "%", "item", ")", "return", "False", "# Returning false aborts the item use", "# Retrieve condition(s) to cure from kwargs, if present", "if", "\"to_cure\"", "in", "kwargs", ":", "to_cure", "=", "kwargs", "[", "\"to_cure\"", "]", "item_msg", "=", "\"%s uses %s! \"", "%", "(", "user", ",", "item", ")", "for", "key", "in", "target", ".", "db", ".", "conditions", ":", "if", "key", "in", "to_cure", ":", "# If condition specified in to_cure, remove it.", "item_msg", "+=", "\"%s no longer has the '%s' condition. \"", "%", "(", "str", "(", "target", ")", ",", "str", "(", "key", ")", ")", "del", "target", ".", "db", ".", "conditions", "[", "key", "]", "user", ".", "location", ".", "msg_contents", "(", "item_msg", ")" ]
[ 1168, 0 ]
[ 1196, 40 ]
python
en
['en', 'error', 'th']
False
itemfunc_attack
(item, user, target, **kwargs)
Item function that attacks a target. kwargs: min_damage(int): Minimum damage dealt by the attack max_damage(int): Maximum damage dealth by the attack accuracy(int): Bonus / penalty to attack accuracy roll inflict_condition(list): List of conditions inflicted on hit, formatted as a (str, int) tuple containing condition name and duration. Notes: Calls resolve_attack at the end.
Item function that attacks a target.
def itemfunc_attack(item, user, target, **kwargs): """ Item function that attacks a target. kwargs: min_damage(int): Minimum damage dealt by the attack max_damage(int): Maximum damage dealth by the attack accuracy(int): Bonus / penalty to attack accuracy roll inflict_condition(list): List of conditions inflicted on hit, formatted as a (str, int) tuple containing condition name and duration. Notes: Calls resolve_attack at the end. """ if not is_in_combat(user): user.msg("You can only use that in combat.") return False # Returning false aborts the item use if not target: user.msg("You have to specify a target to use %s! (use <item> = <target>)" % item) return False if target == user: user.msg("You can't attack yourself!") return False if not target.db.hp: # Has no HP user.msg("You can't use %s on that." % item) return False min_damage = 20 max_damage = 40 accuracy = 0 inflict_condition = [] # Retrieve values from kwargs, if present if "damage_range" in kwargs: min_damage = kwargs["damage_range"][0] max_damage = kwargs["damage_range"][1] if "accuracy" in kwargs: accuracy = kwargs["accuracy"] if "inflict_condition" in kwargs: inflict_condition = kwargs["inflict_condition"] # Roll attack and damage attack_value = randint(1, 100) + accuracy damage_value = randint(min_damage, max_damage) # Account for "Accuracy Up" and "Accuracy Down" conditions if "Accuracy Up" in user.db.conditions: attack_value += 25 if "Accuracy Down" in user.db.conditions: attack_value -= 25 user.location.msg_contents("%s attacks %s with %s!" % (user, target, item)) resolve_attack(user, target, attack_value=attack_value, damage_value=damage_value, inflict_condition=inflict_condition)
[ "def", "itemfunc_attack", "(", "item", ",", "user", ",", "target", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_in_combat", "(", "user", ")", ":", "user", ".", "msg", "(", "\"You can only use that in combat.\"", ")", "return", "False", "# Returning false aborts the item use", "if", "not", "target", ":", "user", ".", "msg", "(", "\"You have to specify a target to use %s! (use <item> = <target>)\"", "%", "item", ")", "return", "False", "if", "target", "==", "user", ":", "user", ".", "msg", "(", "\"You can't attack yourself!\"", ")", "return", "False", "if", "not", "target", ".", "db", ".", "hp", ":", "# Has no HP", "user", ".", "msg", "(", "\"You can't use %s on that.\"", "%", "item", ")", "return", "False", "min_damage", "=", "20", "max_damage", "=", "40", "accuracy", "=", "0", "inflict_condition", "=", "[", "]", "# Retrieve values from kwargs, if present", "if", "\"damage_range\"", "in", "kwargs", ":", "min_damage", "=", "kwargs", "[", "\"damage_range\"", "]", "[", "0", "]", "max_damage", "=", "kwargs", "[", "\"damage_range\"", "]", "[", "1", "]", "if", "\"accuracy\"", "in", "kwargs", ":", "accuracy", "=", "kwargs", "[", "\"accuracy\"", "]", "if", "\"inflict_condition\"", "in", "kwargs", ":", "inflict_condition", "=", "kwargs", "[", "\"inflict_condition\"", "]", "# Roll attack and damage", "attack_value", "=", "randint", "(", "1", ",", "100", ")", "+", "accuracy", "damage_value", "=", "randint", "(", "min_damage", ",", "max_damage", ")", "# Account for \"Accuracy Up\" and \"Accuracy Down\" conditions", "if", "\"Accuracy Up\"", "in", "user", ".", "db", ".", "conditions", ":", "attack_value", "+=", "25", "if", "\"Accuracy Down\"", "in", "user", ".", "db", ".", "conditions", ":", "attack_value", "-=", "25", "user", ".", "location", ".", "msg_contents", "(", "\"%s attacks %s with %s!\"", "%", "(", "user", ",", "target", ",", "item", ")", ")", "resolve_attack", "(", "user", ",", "target", ",", "attack_value", "=", "attack_value", ",", "damage_value", "=", "damage_value", ",", "inflict_condition", "=", "inflict_condition", ")" ]
[ 1198, 0 ]
[ 1255, 82 ]
python
en
['en', 'error', 'th']
False
TBItemsCharacter.at_object_creation
(self)
Called once, when this object is first created. This is the normal hook to overload for most object types.
Called once, when this object is first created. This is the normal hook to overload for most object types.
def at_object_creation(self): """ Called once, when this object is first created. This is the normal hook to overload for most object types. """ self.db.max_hp = 100 # Set maximum HP to 100 self.db.hp = self.db.max_hp # Set current HP to maximum self.db.conditions = {} # Set empty dict for conditions # Subscribe character to the ticker handler tickerhandler.add(NONCOMBAT_TURN_TIME, self.at_update, idstring="update") """ Adds attributes for a character's current and maximum HP. We're just going to set this value at '100' by default. An empty dictionary is created to store conditions later, and the character is subscribed to the Ticker Handler, which will call at_update() on the character, with the interval specified by NONCOMBAT_TURN_TIME above. This is used to tick down conditions out of combat. You may want to expand this to include various 'stats' that can be changed at creation and factor into combat calculations. """
[ "def", "at_object_creation", "(", "self", ")", ":", "self", ".", "db", ".", "max_hp", "=", "100", "# Set maximum HP to 100", "self", ".", "db", ".", "hp", "=", "self", ".", "db", ".", "max_hp", "# Set current HP to maximum", "self", ".", "db", ".", "conditions", "=", "{", "}", "# Set empty dict for conditions", "# Subscribe character to the ticker handler", "tickerhandler", ".", "add", "(", "NONCOMBAT_TURN_TIME", ",", "self", ".", "at_update", ",", "idstring", "=", "\"update\"", ")", "\"\"\"\n Adds attributes for a character's current and maximum HP.\n We're just going to set this value at '100' by default.\n\n An empty dictionary is created to store conditions later,\n and the character is subscribed to the Ticker Handler, which\n will call at_update() on the character, with the interval\n specified by NONCOMBAT_TURN_TIME above. This is used to tick\n down conditions out of combat.\n\n You may want to expand this to include various 'stats' that\n can be changed at creation and factor into combat calculations.\n \"\"\"" ]
[ 490, 4 ]
[ 512, 11 ]
python
en
['en', 'error', 'th']
False
TBItemsCharacter.at_before_move
(self, destination)
Called just before starting to move this object to destination. Args: destination (Object): The object we are moving to Returns: shouldmove (bool): If we should move or not. Notes: If this method returns False/None, the move is cancelled before it is even started.
Called just before starting to move this object to destination.
def at_before_move(self, destination): """ Called just before starting to move this object to destination. Args: destination (Object): The object we are moving to Returns: shouldmove (bool): If we should move or not. Notes: If this method returns False/None, the move is cancelled before it is even started. """ # Keep the character from moving if at 0 HP or in combat. if is_in_combat(self): self.msg("You can't exit a room while in combat!") return False # Returning false keeps the character from moving. if self.db.HP <= 0: self.msg("You can't move, you've been defeated!") return False return True
[ "def", "at_before_move", "(", "self", ",", "destination", ")", ":", "# Keep the character from moving if at 0 HP or in combat.", "if", "is_in_combat", "(", "self", ")", ":", "self", ".", "msg", "(", "\"You can't exit a room while in combat!\"", ")", "return", "False", "# Returning false keeps the character from moving.", "if", "self", ".", "db", ".", "HP", "<=", "0", ":", "self", ".", "msg", "(", "\"You can't move, you've been defeated!\"", ")", "return", "False", "return", "True" ]
[ 514, 4 ]
[ 537, 19 ]
python
en
['en', 'error', 'th']
False
TBItemsCharacter.at_turn_start
(self)
Hook called at the beginning of this character's turn in combat.
Hook called at the beginning of this character's turn in combat.
def at_turn_start(self): """ Hook called at the beginning of this character's turn in combat. """ # Prompt the character for their turn and give some information. self.msg("|wIt's your turn! You have %i HP remaining.|n" % self.db.hp) # Apply conditions that fire at the start of each turn. self.apply_turn_conditions()
[ "def", "at_turn_start", "(", "self", ")", ":", "# Prompt the character for their turn and give some information.", "self", ".", "msg", "(", "\"|wIt's your turn! You have %i HP remaining.|n\"", "%", "self", ".", "db", ".", "hp", ")", "# Apply conditions that fire at the start of each turn.", "self", ".", "apply_turn_conditions", "(", ")" ]
[ 539, 4 ]
[ 547, 36 ]
python
en
['en', 'error', 'th']
False
TBItemsCharacter.apply_turn_conditions
(self)
Applies the effect of conditions that occur at the start of each turn in combat, or every 30 seconds out of combat.
Applies the effect of conditions that occur at the start of each turn in combat, or every 30 seconds out of combat.
def apply_turn_conditions(self): """ Applies the effect of conditions that occur at the start of each turn in combat, or every 30 seconds out of combat. """ # Regeneration: restores 4 to 8 HP at the start of character's turn if "Regeneration" in self.db.conditions: to_heal = randint(REGEN_RATE[0], REGEN_RAGE[1]) # Restore HP if self.db.hp + to_heal > self.db.max_hp: to_heal = self.db.max_hp - self.db.hp # Cap healing to max HP self.db.hp += to_heal self.location.msg_contents("%s regains %i HP from Regeneration." % (self, to_heal)) # Poisoned: does 4 to 8 damage at the start of character's turn if "Poisoned" in self.db.conditions: to_hurt = randint(POISON_RATE[0], POISON_RATE[1]) # Deal damage apply_damage(self, to_hurt) self.location.msg_contents("%s takes %i damage from being Poisoned." % (self, to_hurt)) if self.db.hp <= 0: # Call at_defeat if poison defeats the character at_defeat(self) # Haste: Gain an extra action in combat. if is_in_combat(self) and "Haste" in self.db.conditions: self.db.combat_actionsleft += 1 self.msg("You gain an extra action this turn from Haste!") # Paralyzed: Have no actions in combat. if is_in_combat(self) and "Paralyzed" in self.db.conditions: self.db.combat_actionsleft = 0 self.location.msg_contents("%s is Paralyzed, and can't act this turn!" % self) self.db.combat_turnhandler.turn_end_check(self)
[ "def", "apply_turn_conditions", "(", "self", ")", ":", "# Regeneration: restores 4 to 8 HP at the start of character's turn", "if", "\"Regeneration\"", "in", "self", ".", "db", ".", "conditions", ":", "to_heal", "=", "randint", "(", "REGEN_RATE", "[", "0", "]", ",", "REGEN_RAGE", "[", "1", "]", ")", "# Restore HP", "if", "self", ".", "db", ".", "hp", "+", "to_heal", ">", "self", ".", "db", ".", "max_hp", ":", "to_heal", "=", "self", ".", "db", ".", "max_hp", "-", "self", ".", "db", ".", "hp", "# Cap healing to max HP", "self", ".", "db", ".", "hp", "+=", "to_heal", "self", ".", "location", ".", "msg_contents", "(", "\"%s regains %i HP from Regeneration.\"", "%", "(", "self", ",", "to_heal", ")", ")", "# Poisoned: does 4 to 8 damage at the start of character's turn", "if", "\"Poisoned\"", "in", "self", ".", "db", ".", "conditions", ":", "to_hurt", "=", "randint", "(", "POISON_RATE", "[", "0", "]", ",", "POISON_RATE", "[", "1", "]", ")", "# Deal damage", "apply_damage", "(", "self", ",", "to_hurt", ")", "self", ".", "location", ".", "msg_contents", "(", "\"%s takes %i damage from being Poisoned.\"", "%", "(", "self", ",", "to_hurt", ")", ")", "if", "self", ".", "db", ".", "hp", "<=", "0", ":", "# Call at_defeat if poison defeats the character", "at_defeat", "(", "self", ")", "# Haste: Gain an extra action in combat.", "if", "is_in_combat", "(", "self", ")", "and", "\"Haste\"", "in", "self", ".", "db", ".", "conditions", ":", "self", ".", "db", ".", "combat_actionsleft", "+=", "1", "self", ".", "msg", "(", "\"You gain an extra action this turn from Haste!\"", ")", "# Paralyzed: Have no actions in combat.", "if", "is_in_combat", "(", "self", ")", "and", "\"Paralyzed\"", "in", "self", ".", "db", ".", "conditions", ":", "self", ".", "db", ".", "combat_actionsleft", "=", "0", "self", ".", "location", ".", "msg_contents", "(", "\"%s is Paralyzed, and can't act this turn!\"", "%", "self", ")", "self", ".", "db", ".", "combat_turnhandler", ".", "turn_end_check", "(", "self", ")" ]
[ 549, 4 ]
[ 580, 59 ]
python
en
['en', 'error', 'th']
False
TBItemsCharacter.at_update
(self)
Fires every 30 seconds.
Fires every 30 seconds.
def at_update(self): """ Fires every 30 seconds. """ if not is_in_combat(self): # Not in combat # Change all conditions to update on character's turn. for key in self.db.conditions: self.db.conditions[key][1] = self # Apply conditions that fire every turn self.apply_turn_conditions() # Tick down condition durations condition_tickdown(self, self)
[ "def", "at_update", "(", "self", ")", ":", "if", "not", "is_in_combat", "(", "self", ")", ":", "# Not in combat", "# Change all conditions to update on character's turn.", "for", "key", "in", "self", ".", "db", ".", "conditions", ":", "self", ".", "db", ".", "conditions", "[", "key", "]", "[", "1", "]", "=", "self", "# Apply conditions that fire every turn", "self", ".", "apply_turn_conditions", "(", ")", "# Tick down condition durations", "condition_tickdown", "(", "self", ",", "self", ")" ]
[ 582, 4 ]
[ 593, 42 ]
python
en
['en', 'error', 'th']
False
TBItemsTurnHandler.at_script_creation
(self)
Called once, when the script is created.
Called once, when the script is created.
def at_script_creation(self): """ Called once, when the script is created. """ self.key = "Combat Turn Handler" self.interval = 5 # Once every 5 seconds self.persistent = True self.db.fighters = [] # Add all fighters in the room with at least 1 HP to the combat." for thing in self.obj.contents: if thing.db.hp: self.db.fighters.append(thing) # Initialize each fighter for combat for fighter in self.db.fighters: self.initialize_for_combat(fighter) # Add a reference to this script to the room self.obj.db.combat_turnhandler = self # Roll initiative and sort the list of fighters depending on who rolls highest to determine turn order. # The initiative roll is determined by the roll_init function and can be customized easily. ordered_by_roll = sorted(self.db.fighters, key=roll_init, reverse=True) self.db.fighters = ordered_by_roll # Announce the turn order. self.obj.msg_contents("Turn order is: %s " % ", ".join(obj.key for obj in self.db.fighters)) # Start first fighter's turn. self.start_turn(self.db.fighters[0]) # Set up the current turn and turn timeout delay. self.db.turn = 0 self.db.timer = TURN_TIMEOUT
[ "def", "at_script_creation", "(", "self", ")", ":", "self", ".", "key", "=", "\"Combat Turn Handler\"", "self", ".", "interval", "=", "5", "# Once every 5 seconds", "self", ".", "persistent", "=", "True", "self", ".", "db", ".", "fighters", "=", "[", "]", "# Add all fighters in the room with at least 1 HP to the combat.\"", "for", "thing", "in", "self", ".", "obj", ".", "contents", ":", "if", "thing", ".", "db", ".", "hp", ":", "self", ".", "db", ".", "fighters", ".", "append", "(", "thing", ")", "# Initialize each fighter for combat", "for", "fighter", "in", "self", ".", "db", ".", "fighters", ":", "self", ".", "initialize_for_combat", "(", "fighter", ")", "# Add a reference to this script to the room", "self", ".", "obj", ".", "db", ".", "combat_turnhandler", "=", "self", "# Roll initiative and sort the list of fighters depending on who rolls highest to determine turn order.", "# The initiative roll is determined by the roll_init function and can be customized easily.", "ordered_by_roll", "=", "sorted", "(", "self", ".", "db", ".", "fighters", ",", "key", "=", "roll_init", ",", "reverse", "=", "True", ")", "self", ".", "db", ".", "fighters", "=", "ordered_by_roll", "# Announce the turn order.", "self", ".", "obj", ".", "msg_contents", "(", "\"Turn order is: %s \"", "%", "\", \"", ".", "join", "(", "obj", ".", "key", "for", "obj", "in", "self", ".", "db", ".", "fighters", ")", ")", "# Start first fighter's turn.", "self", ".", "start_turn", "(", "self", ".", "db", ".", "fighters", "[", "0", "]", ")", "# Set up the current turn and turn timeout delay.", "self", ".", "db", ".", "turn", "=", "0", "self", ".", "db", ".", "timer", "=", "TURN_TIMEOUT" ]
[ 625, 4 ]
[ 659, 36 ]
python
en
['en', 'error', 'th']
False
TBItemsTurnHandler.at_stop
(self)
Called at script termination.
Called at script termination.
def at_stop(self): """ Called at script termination. """ for fighter in self.db.fighters: combat_cleanup(fighter) # Clean up the combat attributes for every fighter. self.obj.db.combat_turnhandler = None
[ "def", "at_stop", "(", "self", ")", ":", "for", "fighter", "in", "self", ".", "db", ".", "fighters", ":", "combat_cleanup", "(", "fighter", ")", "# Clean up the combat attributes for every fighter.", "self", ".", "obj", ".", "db", ".", "combat_turnhandler", "=", "None" ]
[ 661, 4 ]
[ 667, 45 ]
python
en
['en', 'error', 'th']
False
TBItemsTurnHandler.at_repeat
(self)
Called once every self.interval seconds.
Called once every self.interval seconds.
def at_repeat(self): """ Called once every self.interval seconds. """ currentchar = self.db.fighters[self.db.turn] # Note the current character in the turn order. self.db.timer -= self.interval # Count down the timer. if self.db.timer <= 0: # Force current character to disengage if timer runs out. self.obj.msg_contents("%s's turn timed out!" % currentchar) spend_action(currentchar, 'all', action_name="disengage") # Spend all remaining actions. return elif self.db.timer <= 10 and not self.db.timeout_warning_given: # 10 seconds left # Warn the current character if they're about to time out. currentchar.msg("WARNING: About to time out!") self.db.timeout_warning_given = True
[ "def", "at_repeat", "(", "self", ")", ":", "currentchar", "=", "self", ".", "db", ".", "fighters", "[", "self", ".", "db", ".", "turn", "]", "# Note the current character in the turn order.", "self", ".", "db", ".", "timer", "-=", "self", ".", "interval", "# Count down the timer.", "if", "self", ".", "db", ".", "timer", "<=", "0", ":", "# Force current character to disengage if timer runs out.", "self", ".", "obj", ".", "msg_contents", "(", "\"%s's turn timed out!\"", "%", "currentchar", ")", "spend_action", "(", "currentchar", ",", "'all'", ",", "action_name", "=", "\"disengage\"", ")", "# Spend all remaining actions.", "return", "elif", "self", ".", "db", ".", "timer", "<=", "10", "and", "not", "self", ".", "db", ".", "timeout_warning_given", ":", "# 10 seconds left", "# Warn the current character if they're about to time out.", "currentchar", ".", "msg", "(", "\"WARNING: About to time out!\"", ")", "self", ".", "db", ".", "timeout_warning_given", "=", "True" ]
[ 669, 4 ]
[ 684, 48 ]
python
en
['en', 'error', 'th']
False
TBItemsTurnHandler.initialize_for_combat
(self, character)
Prepares a character for combat when starting or entering a fight. Args: character (obj): Character to initialize for combat.
Prepares a character for combat when starting or entering a fight.
def initialize_for_combat(self, character): """ Prepares a character for combat when starting or entering a fight. Args: character (obj): Character to initialize for combat. """ combat_cleanup(character) # Clean up leftover combat attributes beforehand, just in case. character.db.combat_actionsleft = 0 # Actions remaining - start of turn adds to this, turn ends when it reaches 0 character.db.combat_turnhandler = self # Add a reference to this turn handler script to the character character.db.combat_lastaction = "null"
[ "def", "initialize_for_combat", "(", "self", ",", "character", ")", ":", "combat_cleanup", "(", "character", ")", "# Clean up leftover combat attributes beforehand, just in case.", "character", ".", "db", ".", "combat_actionsleft", "=", "0", "# Actions remaining - start of turn adds to this, turn ends when it reaches 0", "character", ".", "db", ".", "combat_turnhandler", "=", "self", "# Add a reference to this turn handler script to the character", "character", ".", "db", ".", "combat_lastaction", "=", "\"null\"" ]
[ 686, 4 ]
[ 696, 47 ]
python
en
['en', 'error', 'th']
False
TBItemsTurnHandler.start_turn
(self, character)
Readies a character for the start of their turn by replenishing their available actions and notifying them that their turn has come up. Args: character (obj): Character to be readied. Notes: Here, you only get one action per turn, but you might want to allow more than one per turn, or even grant a number of actions based on a character's attributes. You can even add multiple different kinds of actions, I.E. actions separated for movement, by adding "character.db.combat_movesleft = 3" or something similar.
Readies a character for the start of their turn by replenishing their available actions and notifying them that their turn has come up.
def start_turn(self, character): """ Readies a character for the start of their turn by replenishing their available actions and notifying them that their turn has come up. Args: character (obj): Character to be readied. Notes: Here, you only get one action per turn, but you might want to allow more than one per turn, or even grant a number of actions based on a character's attributes. You can even add multiple different kinds of actions, I.E. actions separated for movement, by adding "character.db.combat_movesleft = 3" or something similar. """ character.db.combat_actionsleft = ACTIONS_PER_TURN # Replenish actions # Call character's at_turn_start() hook. character.at_turn_start()
[ "def", "start_turn", "(", "self", ",", "character", ")", ":", "character", ".", "db", ".", "combat_actionsleft", "=", "ACTIONS_PER_TURN", "# Replenish actions", "# Call character's at_turn_start() hook.", "character", ".", "at_turn_start", "(", ")" ]
[ 698, 4 ]
[ 715, 33 ]
python
en
['en', 'error', 'th']
False
TBItemsTurnHandler.next_turn
(self)
Advances to the next character in the turn order.
Advances to the next character in the turn order.
def next_turn(self): """ Advances to the next character in the turn order. """ # Check to see if every character disengaged as their last action. If so, end combat. disengage_check = True for fighter in self.db.fighters: if fighter.db.combat_lastaction != "disengage": # If a character has done anything but disengage disengage_check = False if disengage_check: # All characters have disengaged self.obj.msg_contents("All fighters have disengaged! Combat is over!") self.stop() # Stop this script and end combat. return # Check to see if only one character is left standing. If so, end combat. defeated_characters = 0 for fighter in self.db.fighters: if fighter.db.HP == 0: defeated_characters += 1 # Add 1 for every fighter with 0 HP left (defeated) if defeated_characters == (len(self.db.fighters) - 1): # If only one character isn't defeated for fighter in self.db.fighters: if fighter.db.HP != 0: LastStanding = fighter # Pick the one fighter left with HP remaining self.obj.msg_contents("Only %s remains! Combat is over!" % LastStanding) self.stop() # Stop this script and end combat. return # Cycle to the next turn. currentchar = self.db.fighters[self.db.turn] self.db.turn += 1 # Go to the next in the turn order. if self.db.turn > len(self.db.fighters) - 1: self.db.turn = 0 # Go back to the first in the turn order once you reach the end. newchar = self.db.fighters[self.db.turn] # Note the new character self.db.timer = TURN_TIMEOUT + self.time_until_next_repeat() # Reset the timer. self.db.timeout_warning_given = False # Reset the timeout warning. self.obj.msg_contents("%s's turn ends - %s's turn begins!" % (currentchar, newchar)) self.start_turn(newchar) # Start the new character's turn. # Count down condition timers. for fighter in self.db.fighters: condition_tickdown(fighter, newchar)
[ "def", "next_turn", "(", "self", ")", ":", "# Check to see if every character disengaged as their last action. If so, end combat.", "disengage_check", "=", "True", "for", "fighter", "in", "self", ".", "db", ".", "fighters", ":", "if", "fighter", ".", "db", ".", "combat_lastaction", "!=", "\"disengage\"", ":", "# If a character has done anything but disengage", "disengage_check", "=", "False", "if", "disengage_check", ":", "# All characters have disengaged", "self", ".", "obj", ".", "msg_contents", "(", "\"All fighters have disengaged! Combat is over!\"", ")", "self", ".", "stop", "(", ")", "# Stop this script and end combat.", "return", "# Check to see if only one character is left standing. If so, end combat.", "defeated_characters", "=", "0", "for", "fighter", "in", "self", ".", "db", ".", "fighters", ":", "if", "fighter", ".", "db", ".", "HP", "==", "0", ":", "defeated_characters", "+=", "1", "# Add 1 for every fighter with 0 HP left (defeated)", "if", "defeated_characters", "==", "(", "len", "(", "self", ".", "db", ".", "fighters", ")", "-", "1", ")", ":", "# If only one character isn't defeated", "for", "fighter", "in", "self", ".", "db", ".", "fighters", ":", "if", "fighter", ".", "db", ".", "HP", "!=", "0", ":", "LastStanding", "=", "fighter", "# Pick the one fighter left with HP remaining", "self", ".", "obj", ".", "msg_contents", "(", "\"Only %s remains! Combat is over!\"", "%", "LastStanding", ")", "self", ".", "stop", "(", ")", "# Stop this script and end combat.", "return", "# Cycle to the next turn.", "currentchar", "=", "self", ".", "db", ".", "fighters", "[", "self", ".", "db", ".", "turn", "]", "self", ".", "db", ".", "turn", "+=", "1", "# Go to the next in the turn order.", "if", "self", ".", "db", ".", "turn", ">", "len", "(", "self", ".", "db", ".", "fighters", ")", "-", "1", ":", "self", ".", "db", ".", "turn", "=", "0", "# Go back to the first in the turn order once you reach the end.", "newchar", "=", "self", ".", "db", ".", "fighters", "[", "self", ".", "db", ".", "turn", "]", "# Note the new character", "self", ".", "db", ".", "timer", "=", "TURN_TIMEOUT", "+", "self", ".", "time_until_next_repeat", "(", ")", "# Reset the timer.", "self", ".", "db", ".", "timeout_warning_given", "=", "False", "# Reset the timeout warning.", "self", ".", "obj", ".", "msg_contents", "(", "\"%s's turn ends - %s's turn begins!\"", "%", "(", "currentchar", ",", "newchar", ")", ")", "self", ".", "start_turn", "(", "newchar", ")", "# Start the new character's turn.", "# Count down condition timers.", "for", "fighter", "in", "self", ".", "db", ".", "fighters", ":", "condition_tickdown", "(", "fighter", ",", "newchar", ")" ]
[ 717, 4 ]
[ 760, 48 ]
python
en
['en', 'error', 'th']
False
TBItemsTurnHandler.turn_end_check
(self, character)
Tests to see if a character's turn is over, and cycles to the next turn if it is. Args: character (obj): Character to test for end of turn
Tests to see if a character's turn is over, and cycles to the next turn if it is.
def turn_end_check(self, character): """ Tests to see if a character's turn is over, and cycles to the next turn if it is. Args: character (obj): Character to test for end of turn """ if not character.db.combat_actionsleft: # Character has no actions remaining self.next_turn() return
[ "def", "turn_end_check", "(", "self", ",", "character", ")", ":", "if", "not", "character", ".", "db", ".", "combat_actionsleft", ":", "# Character has no actions remaining", "self", ".", "next_turn", "(", ")", "return" ]
[ 762, 4 ]
[ 771, 18 ]
python
en
['en', 'error', 'th']
False
TBItemsTurnHandler.join_fight
(self, character)
Adds a new character to a fight already in progress. Args: character (obj): Character to be added to the fight.
Adds a new character to a fight already in progress.
def join_fight(self, character): """ Adds a new character to a fight already in progress. Args: character (obj): Character to be added to the fight. """ # Inserts the fighter to the turn order, right behind whoever's turn it currently is. self.db.fighters.insert(self.db.turn, character) # Tick the turn counter forward one to compensate. self.db.turn += 1 # Initialize the character like you do at the start. self.initialize_for_combat(character)
[ "def", "join_fight", "(", "self", ",", "character", ")", ":", "# Inserts the fighter to the turn order, right behind whoever's turn it currently is.", "self", ".", "db", ".", "fighters", ".", "insert", "(", "self", ".", "db", ".", "turn", ",", "character", ")", "# Tick the turn counter forward one to compensate.", "self", ".", "db", ".", "turn", "+=", "1", "# Initialize the character like you do at the start.", "self", ".", "initialize_for_combat", "(", "character", ")" ]
[ 773, 4 ]
[ 785, 45 ]
python
en
['en', 'error', 'th']
False
CmdFight.func
(self)
This performs the actual command.
This performs the actual command.
def func(self): """ This performs the actual command. """ here = self.caller.location fighters = [] if not self.caller.db.hp: # If you don't have any hp self.caller.msg("You can't start a fight if you've been defeated!") return if is_in_combat(self.caller): # Already in a fight self.caller.msg("You're already in a fight!") return for thing in here.contents: # Test everything in the room to add it to the fight. if thing.db.HP: # If the object has HP... fighters.append(thing) # ...then add it to the fight. if len(fighters) <= 1: # If you're the only able fighter in the room self.caller.msg("There's nobody here to fight!") return if here.db.combat_turnhandler: # If there's already a fight going on... here.msg_contents("%s joins the fight!" % self.caller) here.db.combat_turnhandler.join_fight(self.caller) # Join the fight! return here.msg_contents("%s starts a fight!" % self.caller) # Add a turn handler script to the room, which starts combat. here.scripts.add("contrib.turnbattle.tb_items.TBItemsTurnHandler")
[ "def", "func", "(", "self", ")", ":", "here", "=", "self", ".", "caller", ".", "location", "fighters", "=", "[", "]", "if", "not", "self", ".", "caller", ".", "db", ".", "hp", ":", "# If you don't have any hp", "self", ".", "caller", ".", "msg", "(", "\"You can't start a fight if you've been defeated!\"", ")", "return", "if", "is_in_combat", "(", "self", ".", "caller", ")", ":", "# Already in a fight", "self", ".", "caller", ".", "msg", "(", "\"You're already in a fight!\"", ")", "return", "for", "thing", "in", "here", ".", "contents", ":", "# Test everything in the room to add it to the fight.", "if", "thing", ".", "db", ".", "HP", ":", "# If the object has HP...", "fighters", ".", "append", "(", "thing", ")", "# ...then add it to the fight.", "if", "len", "(", "fighters", ")", "<=", "1", ":", "# If you're the only able fighter in the room", "self", ".", "caller", ".", "msg", "(", "\"There's nobody here to fight!\"", ")", "return", "if", "here", ".", "db", ".", "combat_turnhandler", ":", "# If there's already a fight going on...", "here", ".", "msg_contents", "(", "\"%s joins the fight!\"", "%", "self", ".", "caller", ")", "here", ".", "db", ".", "combat_turnhandler", ".", "join_fight", "(", "self", ".", "caller", ")", "# Join the fight!", "return", "here", ".", "msg_contents", "(", "\"%s starts a fight!\"", "%", "self", ".", "caller", ")", "# Add a turn handler script to the room, which starts combat.", "here", ".", "scripts", ".", "add", "(", "\"contrib.turnbattle.tb_items.TBItemsTurnHandler\"", ")" ]
[ 809, 4 ]
[ 834, 74 ]
python
en
['en', 'error', 'th']
False
CmdAttack.func
(self)
This performs the actual command.
This performs the actual command.
def func(self): "This performs the actual command." "Set the attacker to the caller and the defender to the target." if not is_in_combat(self.caller): # If not in combat, can't attack. self.caller.msg("You can only do that in combat. (see: help fight)") return if not is_turn(self.caller): # If it's not your turn, can't attack. self.caller.msg("You can only do that on your turn.") return if not self.caller.db.hp: # Can't attack if you have no HP. self.caller.msg("You can't attack, you've been defeated.") return if "Frightened" in self.caller.db.conditions: # Can't attack if frightened self.caller.msg("You're too frightened to attack!") return attacker = self.caller defender = self.caller.search(self.args) if not defender: # No valid target given. return if not defender.db.hp: # Target object has no HP left or to begin with self.caller.msg("You can't fight that!") return if attacker == defender: # Target and attacker are the same self.caller.msg("You can't attack yourself!") return "If everything checks out, call the attack resolving function." resolve_attack(attacker, defender) spend_action(self.caller, 1, action_name="attack")
[ "def", "func", "(", "self", ")", ":", "\"Set the attacker to the caller and the defender to the target.\"", "if", "not", "is_in_combat", "(", "self", ".", "caller", ")", ":", "# If not in combat, can't attack.", "self", ".", "caller", ".", "msg", "(", "\"You can only do that in combat. (see: help fight)\"", ")", "return", "if", "not", "is_turn", "(", "self", ".", "caller", ")", ":", "# If it's not your turn, can't attack.", "self", ".", "caller", ".", "msg", "(", "\"You can only do that on your turn.\"", ")", "return", "if", "not", "self", ".", "caller", ".", "db", ".", "hp", ":", "# Can't attack if you have no HP.", "self", ".", "caller", ".", "msg", "(", "\"You can't attack, you've been defeated.\"", ")", "return", "if", "\"Frightened\"", "in", "self", ".", "caller", ".", "db", ".", "conditions", ":", "# Can't attack if frightened", "self", ".", "caller", ".", "msg", "(", "\"You're too frightened to attack!\"", ")", "return", "attacker", "=", "self", ".", "caller", "defender", "=", "self", ".", "caller", ".", "search", "(", "self", ".", "args", ")", "if", "not", "defender", ":", "# No valid target given.", "return", "if", "not", "defender", ".", "db", ".", "hp", ":", "# Target object has no HP left or to begin with", "self", ".", "caller", ".", "msg", "(", "\"You can't fight that!\"", ")", "return", "if", "attacker", "==", "defender", ":", "# Target and attacker are the same", "self", ".", "caller", ".", "msg", "(", "\"You can't attack yourself!\"", ")", "return", "\"If everything checks out, call the attack resolving function.\"", "resolve_attack", "(", "attacker", ",", "defender", ")", "spend_action", "(", "self", ".", "caller", ",", "1", ",", "action_name", "=", "\"attack\"", ")" ]
[ 852, 4 ]
[ 888, 58 ]
python
en
['en', 'en', 'en']
True
CmdPass.func
(self)
This performs the actual command.
This performs the actual command.
def func(self): """ This performs the actual command. """ if not is_in_combat(self.caller): # Can only pass a turn in combat. self.caller.msg("You can only do that in combat. (see: help fight)") return if not is_turn(self.caller): # Can only pass if it's your turn. self.caller.msg("You can only do that on your turn.") return self.caller.location.msg_contents("%s takes no further action, passing the turn." % self.caller) spend_action(self.caller, 'all', action_name="pass")
[ "def", "func", "(", "self", ")", ":", "if", "not", "is_in_combat", "(", "self", ".", "caller", ")", ":", "# Can only pass a turn in combat.", "self", ".", "caller", ".", "msg", "(", "\"You can only do that in combat. (see: help fight)\"", ")", "return", "if", "not", "is_turn", "(", "self", ".", "caller", ")", ":", "# Can only pass if it's your turn.", "self", ".", "caller", ".", "msg", "(", "\"You can only do that on your turn.\"", ")", "return", "self", ".", "caller", ".", "location", ".", "msg_contents", "(", "\"%s takes no further action, passing the turn.\"", "%", "self", ".", "caller", ")", "spend_action", "(", "self", ".", "caller", ",", "'all'", ",", "action_name", "=", "\"pass\"", ")" ]
[ 906, 4 ]
[ 919, 60 ]
python
en
['en', 'error', 'th']
False
CmdDisengage.func
(self)
This performs the actual command.
This performs the actual command.
def func(self): """ This performs the actual command. """ if not is_in_combat(self.caller): # If you're not in combat self.caller.msg("You can only do that in combat. (see: help fight)") return if not is_turn(self.caller): # If it's not your turn self.caller.msg("You can only do that on your turn.") return self.caller.location.msg_contents("%s disengages, ready to stop fighting." % self.caller) spend_action(self.caller, 'all', action_name="disengage") # Spend all remaining actions. """ The action_name kwarg sets the character's last action to "disengage", which is checked by the turn handler script to see if all fighters have disengaged. """
[ "def", "func", "(", "self", ")", ":", "if", "not", "is_in_combat", "(", "self", ".", "caller", ")", ":", "# If you're not in combat", "self", ".", "caller", ".", "msg", "(", "\"You can only do that in combat. (see: help fight)\"", ")", "return", "if", "not", "is_turn", "(", "self", ".", "caller", ")", ":", "# If it's not your turn", "self", ".", "caller", ".", "msg", "(", "\"You can only do that on your turn.\"", ")", "return", "self", ".", "caller", ".", "location", ".", "msg_contents", "(", "\"%s disengages, ready to stop fighting.\"", "%", "self", ".", "caller", ")", "spend_action", "(", "self", ".", "caller", ",", "'all'", ",", "action_name", "=", "\"disengage\"", ")", "# Spend all remaining actions.", "\"\"\"\n The action_name kwarg sets the character's last action to \"disengage\", which is checked by\n the turn handler script to see if all fighters have disengaged.\n \"\"\"" ]
[ 938, 4 ]
[ 955, 11 ]
python
en
['en', 'error', 'th']
False
CmdRest.func
(self)
This performs the actual command.
This performs the actual command.
def func(self): "This performs the actual command." if is_in_combat(self.caller): # If you're in combat self.caller.msg("You can't rest while you're in combat.") return self.caller.db.hp = self.caller.db.max_hp # Set current HP to maximum self.caller.location.msg_contents("%s rests to recover HP." % self.caller) """ You'll probably want to replace this with your own system for recovering HP. """
[ "def", "func", "(", "self", ")", ":", "if", "is_in_combat", "(", "self", ".", "caller", ")", ":", "# If you're in combat", "self", ".", "caller", ".", "msg", "(", "\"You can't rest while you're in combat.\"", ")", "return", "self", ".", "caller", ".", "db", ".", "hp", "=", "self", ".", "caller", ".", "db", ".", "max_hp", "# Set current HP to maximum", "self", ".", "caller", ".", "location", ".", "msg_contents", "(", "\"%s rests to recover HP.\"", "%", "self", ".", "caller", ")", "\"\"\"\n You'll probably want to replace this with your own system for recovering HP.\n \"\"\"" ]
[ 972, 4 ]
[ 983, 11 ]
python
en
['en', 'en', 'en']
True
CmdUse.func
(self)
This performs the actual command.
This performs the actual command.
def func(self): """ This performs the actual command. """ # Search for item item = self.caller.search(self.lhs, candidates=self.caller.contents) if not item: return # Search for target, if any is given target = None if self.rhs: target = self.caller.search(self.rhs) if not target: return # If in combat, can only use items on your turn if is_in_combat(self.caller): if not is_turn(self.caller): self.caller.msg("You can only use items on your turn.") return if not item.db.item_func: # Object has no item_func, not usable self.caller.msg("'%s' is not a usable item." % item.key.capitalize()) return if item.attributes.has("item_uses"): # Item has limited uses if item.db.item_uses <= 0: # Limited uses are spent self.caller.msg("'%s' has no uses remaining." % item.key.capitalize()) return # If everything checks out, call the use_item function use_item(self.caller, item, target)
[ "def", "func", "(", "self", ")", ":", "# Search for item", "item", "=", "self", ".", "caller", ".", "search", "(", "self", ".", "lhs", ",", "candidates", "=", "self", ".", "caller", ".", "contents", ")", "if", "not", "item", ":", "return", "# Search for target, if any is given", "target", "=", "None", "if", "self", ".", "rhs", ":", "target", "=", "self", ".", "caller", ".", "search", "(", "self", ".", "rhs", ")", "if", "not", "target", ":", "return", "# If in combat, can only use items on your turn", "if", "is_in_combat", "(", "self", ".", "caller", ")", ":", "if", "not", "is_turn", "(", "self", ".", "caller", ")", ":", "self", ".", "caller", ".", "msg", "(", "\"You can only use items on your turn.\"", ")", "return", "if", "not", "item", ".", "db", ".", "item_func", ":", "# Object has no item_func, not usable", "self", ".", "caller", ".", "msg", "(", "\"'%s' is not a usable item.\"", "%", "item", ".", "key", ".", "capitalize", "(", ")", ")", "return", "if", "item", ".", "attributes", ".", "has", "(", "\"item_uses\"", ")", ":", "# Item has limited uses", "if", "item", ".", "db", ".", "item_uses", "<=", "0", ":", "# Limited uses are spent", "self", ".", "caller", ".", "msg", "(", "\"'%s' has no uses remaining.\"", "%", "item", ".", "key", ".", "capitalize", "(", ")", ")", "return", "# If everything checks out, call the use_item function", "use_item", "(", "self", ".", "caller", ",", "item", ",", "target", ")" ]
[ 1027, 4 ]
[ 1059, 43 ]
python
en
['en', 'error', 'th']
False
BattleCmdSet.at_cmdset_creation
(self)
Populates the cmdset
Populates the cmdset
def at_cmdset_creation(self): """ Populates the cmdset """ self.add(CmdFight()) self.add(CmdAttack()) self.add(CmdRest()) self.add(CmdPass()) self.add(CmdDisengage()) self.add(CmdCombatHelp()) self.add(CmdUse())
[ "def", "at_cmdset_creation", "(", "self", ")", ":", "self", ".", "add", "(", "CmdFight", "(", ")", ")", "self", ".", "add", "(", "CmdAttack", "(", ")", ")", "self", ".", "add", "(", "CmdRest", "(", ")", ")", "self", ".", "add", "(", "CmdPass", "(", ")", ")", "self", ".", "add", "(", "CmdDisengage", "(", ")", ")", "self", ".", "add", "(", "CmdCombatHelp", "(", ")", ")", "self", ".", "add", "(", "CmdUse", "(", ")", ")" ]
[ 1068, 4 ]
[ 1078, 26 ]
python
en
['en', 'error', 'th']
False
CharacterCmdSet.at_cmdset_creation
(self)
Populates the cmdset
Populates the cmdset
def at_cmdset_creation(self): "Populates the cmdset" # The general commands self.add(general.CmdLook()) self.add(general.CmdHome()) self.add(general.CmdInventory()) self.add(general.CmdPose()) self.add(general.CmdNick()) self.add(general.CmdSetDesc()) self.add(general.CmdGet()) self.add(general.CmdDrop()) self.add(general.CmdGive()) self.add(general.CmdSay()) self.add(general.CmdWhisper()) self.add(general.CmdAccess()) # The help system self.add(help.CmdHelp()) self.add(help.CmdSetHelp()) # System commands self.add(system.CmdPy()) self.add(system.CmdScripts()) self.add(system.CmdObjects()) self.add(system.CmdAccounts()) self.add(system.CmdService()) self.add(system.CmdAbout()) self.add(system.CmdTime()) self.add(system.CmdServerLoad()) # self.add(system.CmdPs()) self.add(system.CmdTickers()) # Admin commands self.add(admin.CmdBoot()) self.add(admin.CmdBan()) self.add(admin.CmdUnban()) self.add(admin.CmdEmit()) self.add(admin.CmdPerm()) self.add(admin.CmdWall()) # Building and world manipulation self.add(building.CmdTeleport()) self.add(building.CmdSetObjAlias()) self.add(building.CmdListCmdSets()) self.add(building.CmdWipe()) self.add(building.CmdSetAttribute()) self.add(building.CmdName()) self.add(building.CmdDesc()) self.add(building.CmdCpAttr()) self.add(building.CmdMvAttr()) self.add(building.CmdCopy()) self.add(building.CmdFind()) self.add(building.CmdOpen()) self.add(building.CmdLink()) self.add(building.CmdUnLink()) self.add(building.CmdCreate()) self.add(building.CmdDig()) self.add(building.CmdTunnel()) self.add(building.CmdDestroy()) self.add(building.CmdExamine()) self.add(building.CmdTypeclass()) self.add(building.CmdLock()) self.add(building.CmdScript()) self.add(building.CmdSetHome()) self.add(building.CmdTag()) self.add(building.CmdSpawn()) # Batchprocessor commands self.add(batchprocess.CmdBatchCommands()) self.add(batchprocess.CmdBatchCode())
[ "def", "at_cmdset_creation", "(", "self", ")", ":", "# The general commands", "self", ".", "add", "(", "general", ".", "CmdLook", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdHome", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdInventory", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdPose", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdNick", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdSetDesc", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdGet", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdDrop", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdGive", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdSay", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdWhisper", "(", ")", ")", "self", ".", "add", "(", "general", ".", "CmdAccess", "(", ")", ")", "# The help system", "self", ".", "add", "(", "help", ".", "CmdHelp", "(", ")", ")", "self", ".", "add", "(", "help", ".", "CmdSetHelp", "(", ")", ")", "# System commands", "self", ".", "add", "(", "system", ".", "CmdPy", "(", ")", ")", "self", ".", "add", "(", "system", ".", "CmdScripts", "(", ")", ")", "self", ".", "add", "(", "system", ".", "CmdObjects", "(", ")", ")", "self", ".", "add", "(", "system", ".", "CmdAccounts", "(", ")", ")", "self", ".", "add", "(", "system", ".", "CmdService", "(", ")", ")", "self", ".", "add", "(", "system", ".", "CmdAbout", "(", ")", ")", "self", ".", "add", "(", "system", ".", "CmdTime", "(", ")", ")", "self", ".", "add", "(", "system", ".", "CmdServerLoad", "(", ")", ")", "# self.add(system.CmdPs())", "self", ".", "add", "(", "system", ".", "CmdTickers", "(", ")", ")", "# Admin commands", "self", ".", "add", "(", "admin", ".", "CmdBoot", "(", ")", ")", "self", ".", "add", "(", "admin", ".", "CmdBan", "(", ")", ")", "self", ".", "add", "(", "admin", ".", "CmdUnban", "(", ")", ")", "self", ".", "add", "(", "admin", ".", "CmdEmit", "(", ")", ")", "self", ".", "add", "(", "admin", ".", "CmdPerm", "(", ")", ")", "self", ".", "add", "(", "admin", ".", "CmdWall", "(", ")", ")", "# Building and world manipulation", "self", ".", "add", "(", "building", ".", "CmdTeleport", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdSetObjAlias", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdListCmdSets", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdWipe", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdSetAttribute", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdName", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdDesc", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdCpAttr", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdMvAttr", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdCopy", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdFind", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdOpen", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdLink", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdUnLink", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdCreate", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdDig", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdTunnel", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdDestroy", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdExamine", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdTypeclass", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdLock", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdScript", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdSetHome", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdTag", "(", ")", ")", "self", ".", "add", "(", "building", ".", "CmdSpawn", "(", ")", ")", "# Batchprocessor commands", "self", ".", "add", "(", "batchprocess", ".", "CmdBatchCommands", "(", ")", ")", "self", ".", "add", "(", "batchprocess", ".", "CmdBatchCode", "(", ")", ")" ]
[ 19, 4 ]
[ 89, 45 ]
python
en
['en', 'sr', 'en']
True
SetEnvVar
(env_var, value)
Sets the env variable to 'value'; unsets it when 'value' is None.
Sets the env variable to 'value'; unsets it when 'value' is None.
def SetEnvVar(env_var, value): """Sets the env variable to 'value'; unsets it when 'value' is None.""" if value is not None: os.environ[env_var] = value elif env_var in os.environ: del os.environ[env_var]
[ "def", "SetEnvVar", "(", "env_var", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "os", ".", "environ", "[", "env_var", "]", "=", "value", "elif", "env_var", "in", "os", ".", "environ", ":", "del", "os", ".", "environ", "[", "env_var", "]" ]
[ 46, 0 ]
[ 52, 27 ]
python
en
['en', 'en', 'en']
True
UsesColor
(term, color_env_var, color_flag)
Runs gtest_color_test_ and returns its exit code.
Runs gtest_color_test_ and returns its exit code.
def UsesColor(term, color_env_var, color_flag): """Runs gtest_color_test_ and returns its exit code.""" SetEnvVar('TERM', term) SetEnvVar(COLOR_ENV_VAR, color_env_var) if color_flag is None: args = [] else: args = ['--%s=%s' % (COLOR_FLAG, color_flag)] p = gtest_test_utils.Subprocess([COMMAND] + args) return not p.exited or p.exit_code
[ "def", "UsesColor", "(", "term", ",", "color_env_var", ",", "color_flag", ")", ":", "SetEnvVar", "(", "'TERM'", ",", "term", ")", "SetEnvVar", "(", "COLOR_ENV_VAR", ",", "color_env_var", ")", "if", "color_flag", "is", "None", ":", "args", "=", "[", "]", "else", ":", "args", "=", "[", "'--%s=%s'", "%", "(", "COLOR_FLAG", ",", "color_flag", ")", "]", "p", "=", "gtest_test_utils", ".", "Subprocess", "(", "[", "COMMAND", "]", "+", "args", ")", "return", "not", "p", ".", "exited", "or", "p", ".", "exit_code" ]
[ 55, 0 ]
[ 66, 36 ]
python
en
['en', 'en', 'en']
True
GTestColorTest.testNoEnvVarNoFlag
(self)
Tests the case when there's neither GTEST_COLOR nor --gtest_color.
Tests the case when there's neither GTEST_COLOR nor --gtest_color.
def testNoEnvVarNoFlag(self): """Tests the case when there's neither GTEST_COLOR nor --gtest_color.""" if not IS_WINDOWS: self.assert_(not UsesColor('dumb', None, None)) self.assert_(not UsesColor('emacs', None, None)) self.assert_(not UsesColor('xterm-mono', None, None)) self.assert_(not UsesColor('unknown', None, None)) self.assert_(not UsesColor(None, None, None)) self.assert_(UsesColor('linux', None, None)) self.assert_(UsesColor('cygwin', None, None)) self.assert_(UsesColor('xterm', None, None)) self.assert_(UsesColor('xterm-color', None, None)) self.assert_(UsesColor('xterm-256color', None, None))
[ "def", "testNoEnvVarNoFlag", "(", "self", ")", ":", "if", "not", "IS_WINDOWS", ":", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'dumb'", ",", "None", ",", "None", ")", ")", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'emacs'", ",", "None", ",", "None", ")", ")", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'xterm-mono'", ",", "None", ",", "None", ")", ")", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'unknown'", ",", "None", ",", "None", ")", ")", "self", ".", "assert_", "(", "not", "UsesColor", "(", "None", ",", "None", ",", "None", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'linux'", ",", "None", ",", "None", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'cygwin'", ",", "None", ",", "None", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'xterm'", ",", "None", ",", "None", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'xterm-color'", ",", "None", ",", "None", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'xterm-256color'", ",", "None", ",", "None", ")", ")" ]
[ 70, 2 ]
[ 83, 57 ]
python
en
['en', 'en', 'en']
True
GTestColorTest.testFlagOnly
(self)
Tests the case when there's --gtest_color but not GTEST_COLOR.
Tests the case when there's --gtest_color but not GTEST_COLOR.
def testFlagOnly(self): """Tests the case when there's --gtest_color but not GTEST_COLOR.""" self.assert_(not UsesColor('dumb', None, 'no')) self.assert_(not UsesColor('xterm-color', None, 'no')) if not IS_WINDOWS: self.assert_(not UsesColor('emacs', None, 'auto')) self.assert_(UsesColor('xterm', None, 'auto')) self.assert_(UsesColor('dumb', None, 'yes')) self.assert_(UsesColor('xterm', None, 'yes'))
[ "def", "testFlagOnly", "(", "self", ")", ":", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'dumb'", ",", "None", ",", "'no'", ")", ")", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'xterm-color'", ",", "None", ",", "'no'", ")", ")", "if", "not", "IS_WINDOWS", ":", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'emacs'", ",", "None", ",", "'auto'", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'xterm'", ",", "None", ",", "'auto'", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'dumb'", ",", "None", ",", "'yes'", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'xterm'", ",", "None", ",", "'yes'", ")", ")" ]
[ 85, 2 ]
[ 94, 49 ]
python
en
['en', 'en', 'en']
True
GTestColorTest.testEnvVarOnly
(self)
Tests the case when there's GTEST_COLOR but not --gtest_color.
Tests the case when there's GTEST_COLOR but not --gtest_color.
def testEnvVarOnly(self): """Tests the case when there's GTEST_COLOR but not --gtest_color.""" self.assert_(not UsesColor('dumb', 'no', None)) self.assert_(not UsesColor('xterm-color', 'no', None)) if not IS_WINDOWS: self.assert_(not UsesColor('dumb', 'auto', None)) self.assert_(UsesColor('xterm-color', 'auto', None)) self.assert_(UsesColor('dumb', 'yes', None)) self.assert_(UsesColor('xterm-color', 'yes', None))
[ "def", "testEnvVarOnly", "(", "self", ")", ":", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'dumb'", ",", "'no'", ",", "None", ")", ")", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'xterm-color'", ",", "'no'", ",", "None", ")", ")", "if", "not", "IS_WINDOWS", ":", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'dumb'", ",", "'auto'", ",", "None", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'xterm-color'", ",", "'auto'", ",", "None", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'dumb'", ",", "'yes'", ",", "None", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'xterm-color'", ",", "'yes'", ",", "None", ")", ")" ]
[ 96, 2 ]
[ 105, 55 ]
python
en
['en', 'en', 'en']
True
GTestColorTest.testEnvVarAndFlag
(self)
Tests the case when there are both GTEST_COLOR and --gtest_color.
Tests the case when there are both GTEST_COLOR and --gtest_color.
def testEnvVarAndFlag(self): """Tests the case when there are both GTEST_COLOR and --gtest_color.""" self.assert_(not UsesColor('xterm-color', 'no', 'no')) self.assert_(UsesColor('dumb', 'no', 'yes')) self.assert_(UsesColor('xterm-color', 'no', 'auto'))
[ "def", "testEnvVarAndFlag", "(", "self", ")", ":", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'xterm-color'", ",", "'no'", ",", "'no'", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'dumb'", ",", "'no'", ",", "'yes'", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'xterm-color'", ",", "'no'", ",", "'auto'", ")", ")" ]
[ 107, 2 ]
[ 112, 56 ]
python
en
['en', 'en', 'en']
True
GTestColorTest.testAliasesOfYesAndNo
(self)
Tests using aliases in specifying --gtest_color.
Tests using aliases in specifying --gtest_color.
def testAliasesOfYesAndNo(self): """Tests using aliases in specifying --gtest_color.""" self.assert_(UsesColor('dumb', None, 'true')) self.assert_(UsesColor('dumb', None, 'YES')) self.assert_(UsesColor('dumb', None, 'T')) self.assert_(UsesColor('dumb', None, '1')) self.assert_(not UsesColor('xterm', None, 'f')) self.assert_(not UsesColor('xterm', None, 'false')) self.assert_(not UsesColor('xterm', None, '0')) self.assert_(not UsesColor('xterm', None, 'unknown'))
[ "def", "testAliasesOfYesAndNo", "(", "self", ")", ":", "self", ".", "assert_", "(", "UsesColor", "(", "'dumb'", ",", "None", ",", "'true'", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'dumb'", ",", "None", ",", "'YES'", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'dumb'", ",", "None", ",", "'T'", ")", ")", "self", ".", "assert_", "(", "UsesColor", "(", "'dumb'", ",", "None", ",", "'1'", ")", ")", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'xterm'", ",", "None", ",", "'f'", ")", ")", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'xterm'", ",", "None", ",", "'false'", ")", ")", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'xterm'", ",", "None", ",", "'0'", ")", ")", "self", ".", "assert_", "(", "not", "UsesColor", "(", "'xterm'", ",", "None", ",", "'unknown'", ")", ")" ]
[ 114, 2 ]
[ 125, 57 ]
python
en
['en', 'en', 'en']
True
TestForwardInvitation.test_init
(self)
Test initialization.
Test initialization.
def test_init(self): """Test initialization.""" assert self.invitation.invitation == self.connection_invitation assert self.invitation.message == self.test_message
[ "def", "test_init", "(", "self", ")", ":", "assert", "self", ".", "invitation", ".", "invitation", "==", "self", ".", "connection_invitation", "assert", "self", ".", "invitation", ".", "message", "==", "self", ".", "test_message" ]
[ 28, 4 ]
[ 31, 59 ]
python
co
['es', 'co', 'en']
False
TestForwardInvitation.test_deserialize
(self, mock_invitation_schema_load)
Test deserialization.
Test deserialization.
def test_deserialize(self, mock_invitation_schema_load): """ Test deserialization. """ obj = {"obj": "obj"} invitation = ForwardInvitation.deserialize(obj) mock_invitation_schema_load.assert_called_once_with(obj) assert invitation is mock_invitation_schema_load.return_value
[ "def", "test_deserialize", "(", "self", ",", "mock_invitation_schema_load", ")", ":", "obj", "=", "{", "\"obj\"", ":", "\"obj\"", "}", "invitation", "=", "ForwardInvitation", ".", "deserialize", "(", "obj", ")", "mock_invitation_schema_load", ".", "assert_called_once_with", "(", "obj", ")", "assert", "invitation", "is", "mock_invitation_schema_load", ".", "return_value" ]
[ 41, 4 ]
[ 50, 69 ]
python
en
['en', 'error', 'th']
False
TestForwardInvitation.test_serialize
(self, mock_invitation_schema_dump)
Test serialization.
Test serialization.
def test_serialize(self, mock_invitation_schema_dump): """ Test serialization. """ invitation_dict = self.invitation.serialize() mock_invitation_schema_dump.assert_called_once_with(self.invitation) assert invitation_dict is mock_invitation_schema_dump.return_value
[ "def", "test_serialize", "(", "self", ",", "mock_invitation_schema_dump", ")", ":", "invitation_dict", "=", "self", ".", "invitation", ".", "serialize", "(", ")", "mock_invitation_schema_dump", ".", "assert_called_once_with", "(", "self", ".", "invitation", ")", "assert", "invitation_dict", "is", "mock_invitation_schema_dump", ".", "return_value" ]
[ 56, 4 ]
[ 63, 74 ]
python
en
['en', 'error', 'th']
False
test_init_state_from_ledger
(write_manager, db_manager, constraint_serializer, prepare_request)
Add txn to ledger
Add txn to ledger
def test_init_state_from_ledger(write_manager, db_manager, constraint_serializer, prepare_request): reset_state(db_manager, CONFIG_LEDGER_ID) req_count = 1 action, constraint, request = prepare_request txn = reqToTxn(request) txn[TXN_METADATA][TXN_METADATA_SEQ_NO] = 1 """Add txn to ledger""" db_manager.get_ledger(CONFIG_LEDGER_ID).appendTxns([txn]) db_manager.get_ledger(CONFIG_LEDGER_ID).commitTxns(req_count) # ToDo: ugly fix... Refactor this on pluggable req handler integration phase init_state_from_ledger = functools.partial( LedgersBootstrap._init_state_from_ledger, FakeSomething( db_manager=db_manager, write_manager=write_manager, _update_txn_with_extra_data=lambda txn: txn)) """Check that txn is not exist in state""" assert db_manager.get_state(CONFIG_LEDGER_ID).get(config.make_state_path_for_auth_rule(action.get_action_id()), isCommitted=False) is None assert db_manager.get_state(CONFIG_LEDGER_ID).get(config.make_state_path_for_auth_rule(action.get_action_id()), isCommitted=True) is None txns_from_ledger = [t for t in db_manager.get_ledger(CONFIG_LEDGER_ID).getAllTxn()] """Check, that txn exist in ledger""" assert len(txns_from_ledger) == 1 assert get_payload_data(txns_from_ledger[0][1]) == get_payload_data(txn) """Emulating node starting""" init_state_from_ledger(CONFIG_LEDGER_ID) """Check that txn was added into state""" from_state = db_manager.get_state(CONFIG_LEDGER_ID) .get( config.make_state_path_for_auth_rule(action.get_action_id()), isCommitted=True) assert constraint_serializer.deserialize(from_state) == constraint
[ "def", "test_init_state_from_ledger", "(", "write_manager", ",", "db_manager", ",", "constraint_serializer", ",", "prepare_request", ")", ":", "reset_state", "(", "db_manager", ",", "CONFIG_LEDGER_ID", ")", "req_count", "=", "1", "action", ",", "constraint", ",", "request", "=", "prepare_request", "txn", "=", "reqToTxn", "(", "request", ")", "txn", "[", "TXN_METADATA", "]", "[", "TXN_METADATA_SEQ_NO", "]", "=", "1", "db_manager", ".", "get_ledger", "(", "CONFIG_LEDGER_ID", ")", ".", "appendTxns", "(", "[", "txn", "]", ")", "db_manager", ".", "get_ledger", "(", "CONFIG_LEDGER_ID", ")", ".", "commitTxns", "(", "req_count", ")", "# ToDo: ugly fix... Refactor this on pluggable req handler integration phase", "init_state_from_ledger", "=", "functools", ".", "partial", "(", "LedgersBootstrap", ".", "_init_state_from_ledger", ",", "FakeSomething", "(", "db_manager", "=", "db_manager", ",", "write_manager", "=", "write_manager", ",", "_update_txn_with_extra_data", "=", "lambda", "txn", ":", "txn", ")", ")", "\"\"\"Check that txn is not exist in state\"\"\"", "assert", "db_manager", ".", "get_state", "(", "CONFIG_LEDGER_ID", ")", ".", "get", "(", "config", ".", "make_state_path_for_auth_rule", "(", "action", ".", "get_action_id", "(", ")", ")", ",", "isCommitted", "=", "False", ")", "is", "None", "assert", "db_manager", ".", "get_state", "(", "CONFIG_LEDGER_ID", ")", ".", "get", "(", "config", ".", "make_state_path_for_auth_rule", "(", "action", ".", "get_action_id", "(", ")", ")", ",", "isCommitted", "=", "True", ")", "is", "None", "txns_from_ledger", "=", "[", "t", "for", "t", "in", "db_manager", ".", "get_ledger", "(", "CONFIG_LEDGER_ID", ")", ".", "getAllTxn", "(", ")", "]", "\"\"\"Check, that txn exist in ledger\"\"\"", "assert", "len", "(", "txns_from_ledger", ")", "==", "1", "assert", "get_payload_data", "(", "txns_from_ledger", "[", "0", "]", "[", "1", "]", ")", "==", "get_payload_data", "(", "txn", ")", "\"\"\"Emulating node starting\"\"\"", "init_state_from_ledger", "(", "CONFIG_LEDGER_ID", ")", "\"\"\"Check that txn was added into state\"\"\"", "from_state", "=", "db_manager", ".", "get_state", "(", "CONFIG_LEDGER_ID", ")", ".", "get", "(", "config", ".", "make_state_path_for_auth_rule", "(", "action", ".", "get_action_id", "(", ")", ")", ",", "isCommitted", "=", "True", ")", "assert", "constraint_serializer", ".", "deserialize", "(", "from_state", ")", "==", "constraint" ]
[ 79, 0 ]
[ 113, 70 ]
python
en
['en', 'ht', 'en']
True
Marker.color
(self)
Sets the marker color of unselected points, applied only when a selection exists. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str
Sets the marker color of unselected points, applied only when a selection exists. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen
def color(self): """ Sets the marker color of unselected points, applied only when a selection exists. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["color"]
[ "def", "color", "(", "self", ")", ":", "return", "self", "[", "\"color\"", "]" ]
[ 15, 4 ]
[ 66, 28 ]
python
en
['en', 'error', 'th']
False
Marker.opacity
(self)
Sets the marker opacity of unselected points, applied only when a selection exists. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float
Sets the marker opacity of unselected points, applied only when a selection exists. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1]
def opacity(self): """ Sets the marker opacity of unselected points, applied only when a selection exists. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["opacity"]
[ "def", "opacity", "(", "self", ")", ":", "return", "self", "[", "\"opacity\"", "]" ]
[ 75, 4 ]
[ 87, 30 ]
python
en
['en', 'error', 'th']
False
Marker.__init__
(self, arg=None, color=None, opacity=None, **kwargs)
Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.histogram.unselected.Marker` color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. Returns ------- Marker
Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.histogram.unselected.Marker` color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists.
def __init__(self, arg=None, color=None, opacity=None, **kwargs): """ Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.histogram.unselected.Marker` color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. Returns ------- Marker """ super(Marker, self).__init__("marker") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.histogram.unselected.Marker constructor must be a dict or an instance of :class:`plotly.graph_objs.histogram.unselected.Marker`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _v _v = arg.pop("opacity", None) _v = opacity if opacity is not None else _v if _v is not None: self["opacity"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "color", "=", "None", ",", "opacity", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Marker", ",", "self", ")", ".", "__init__", "(", "\"marker\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.histogram.unselected.Marker \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.histogram.unselected.Marker`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"color\"", ",", "None", ")", "_v", "=", "color", "if", "color", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"color\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"opacity\"", ",", "None", ")", "_v", "=", "opacity", "if", "opacity", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"opacity\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 106, 4 ]
[ 171, 34 ]
python
en
['en', 'error', 'th']
False
_draw_points
(points, vis, points_size=2, point_color=(0.5, 0.5, 0.5), mode='xyz')
Draw points on visualizer. Args: points (numpy.array | torch.tensor, shape=[N, 3+C]): points to visualize. vis (:obj:`open3d.visualization.Visualizer`): open3d visualizer. points_size (int): the size of points to show on visualizer. Default: 2. point_color (tuple[float]): the color of points. Default: (0.5, 0.5, 0.5). mode (str): indicate type of the input points, avaliable mode ['xyz', 'xyzrgb']. Default: 'xyz'. Returns: tuple: points, color of each point.
Draw points on visualizer.
def _draw_points(points, vis, points_size=2, point_color=(0.5, 0.5, 0.5), mode='xyz'): """Draw points on visualizer. Args: points (numpy.array | torch.tensor, shape=[N, 3+C]): points to visualize. vis (:obj:`open3d.visualization.Visualizer`): open3d visualizer. points_size (int): the size of points to show on visualizer. Default: 2. point_color (tuple[float]): the color of points. Default: (0.5, 0.5, 0.5). mode (str): indicate type of the input points, avaliable mode ['xyz', 'xyzrgb']. Default: 'xyz'. Returns: tuple: points, color of each point. """ vis.get_render_option().point_size = points_size # set points size if isinstance(points, torch.Tensor): points = points.cpu().numpy() points = points.copy() pcd = geometry.PointCloud() if mode == 'xyz': pcd.points = o3d.utility.Vector3dVector(points[:, :3]) points_colors = np.tile(np.array(point_color), (points.shape[0], 1)) elif mode == 'xyzrgb': pcd.points = o3d.utility.Vector3dVector(points[:, :3]) points_colors = points[:, 3:6] else: raise NotImplementedError pcd.colors = o3d.utility.Vector3dVector(points_colors) vis.add_geometry(pcd) return pcd, points_colors
[ "def", "_draw_points", "(", "points", ",", "vis", ",", "points_size", "=", "2", ",", "point_color", "=", "(", "0.5", ",", "0.5", ",", "0.5", ")", ",", "mode", "=", "'xyz'", ")", ":", "vis", ".", "get_render_option", "(", ")", ".", "point_size", "=", "points_size", "# set points size", "if", "isinstance", "(", "points", ",", "torch", ".", "Tensor", ")", ":", "points", "=", "points", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "points", "=", "points", ".", "copy", "(", ")", "pcd", "=", "geometry", ".", "PointCloud", "(", ")", "if", "mode", "==", "'xyz'", ":", "pcd", ".", "points", "=", "o3d", ".", "utility", ".", "Vector3dVector", "(", "points", "[", ":", ",", ":", "3", "]", ")", "points_colors", "=", "np", ".", "tile", "(", "np", ".", "array", "(", "point_color", ")", ",", "(", "points", ".", "shape", "[", "0", "]", ",", "1", ")", ")", "elif", "mode", "==", "'xyzrgb'", ":", "pcd", ".", "points", "=", "o3d", ".", "utility", ".", "Vector3dVector", "(", "points", "[", ":", ",", ":", "3", "]", ")", "points_colors", "=", "points", "[", ":", ",", "3", ":", "6", "]", "else", ":", "raise", "NotImplementedError", "pcd", ".", "colors", "=", "o3d", ".", "utility", ".", "Vector3dVector", "(", "points_colors", ")", "vis", ".", "add_geometry", "(", "pcd", ")", "return", "pcd", ",", "points_colors" ]
[ 13, 0 ]
[ 52, 29 ]
python
en
['en', 'en', 'en']
True
_draw_bboxes
(bbox3d, vis, points_colors, pcd=None, bbox_color=(0, 1, 0), points_in_box_color=(1, 0, 0), rot_axis=2, center_mode='lidar_bottom', mode='xyz')
Draw bbox on visualizer and change the color of points inside bbox3d. Args: bbox3d (numpy.array | torch.tensor, shape=[M, 7]): 3d bbox (x, y, z, dx, dy, dz, yaw) to visualize. vis (:obj:`open3d.visualization.Visualizer`): open3d visualizer. points_colors (numpy.array): color of each points. pcd (:obj:`open3d.geometry.PointCloud`): point cloud. Default: None. bbox_color (tuple[float]): the color of bbox. Default: (0, 1, 0). points_in_box_color (tuple[float]): the color of points inside bbox3d. Default: (1, 0, 0). rot_axis (int): rotation axis of bbox. Default: 2. center_mode (bool): indicate the center of bbox is bottom center or gravity center. avaliable mode ['lidar_bottom', 'camera_bottom']. Default: 'lidar_bottom'. mode (str): indicate type of the input points, avaliable mode ['xyz', 'xyzrgb']. Default: 'xyz'.
Draw bbox on visualizer and change the color of points inside bbox3d.
def _draw_bboxes(bbox3d, vis, points_colors, pcd=None, bbox_color=(0, 1, 0), points_in_box_color=(1, 0, 0), rot_axis=2, center_mode='lidar_bottom', mode='xyz'): """Draw bbox on visualizer and change the color of points inside bbox3d. Args: bbox3d (numpy.array | torch.tensor, shape=[M, 7]): 3d bbox (x, y, z, dx, dy, dz, yaw) to visualize. vis (:obj:`open3d.visualization.Visualizer`): open3d visualizer. points_colors (numpy.array): color of each points. pcd (:obj:`open3d.geometry.PointCloud`): point cloud. Default: None. bbox_color (tuple[float]): the color of bbox. Default: (0, 1, 0). points_in_box_color (tuple[float]): the color of points inside bbox3d. Default: (1, 0, 0). rot_axis (int): rotation axis of bbox. Default: 2. center_mode (bool): indicate the center of bbox is bottom center or gravity center. avaliable mode ['lidar_bottom', 'camera_bottom']. Default: 'lidar_bottom'. mode (str): indicate type of the input points, avaliable mode ['xyz', 'xyzrgb']. Default: 'xyz'. """ if isinstance(bbox3d, torch.Tensor): bbox3d = bbox3d.cpu().numpy() bbox3d = bbox3d.copy() in_box_color = np.array(points_in_box_color) for i in range(len(bbox3d)): center = bbox3d[i, 0:3] dim = bbox3d[i, 3:6] yaw = np.zeros(3) yaw[rot_axis] = -bbox3d[i, 6] rot_mat = geometry.get_rotation_matrix_from_xyz(yaw) if center_mode == 'lidar_bottom': center[rot_axis] += dim[ rot_axis] / 2 # bottom center to gravity center elif center_mode == 'camera_bottom': center[rot_axis] -= dim[ rot_axis] / 2 # bottom center to gravity center box3d = geometry.OrientedBoundingBox(center, rot_mat, dim) line_set = geometry.LineSet.create_from_oriented_bounding_box(box3d) line_set.paint_uniform_color(bbox_color) # draw bboxes on visualizer vis.add_geometry(line_set) # change the color of points which are in box if pcd is not None and mode == 'xyz': indices = box3d.get_point_indices_within_bounding_box(pcd.points) points_colors[indices] = in_box_color # update points colors if pcd is not None: pcd.colors = o3d.utility.Vector3dVector(points_colors) vis.update_geometry(pcd)
[ "def", "_draw_bboxes", "(", "bbox3d", ",", "vis", ",", "points_colors", ",", "pcd", "=", "None", ",", "bbox_color", "=", "(", "0", ",", "1", ",", "0", ")", ",", "points_in_box_color", "=", "(", "1", ",", "0", ",", "0", ")", ",", "rot_axis", "=", "2", ",", "center_mode", "=", "'lidar_bottom'", ",", "mode", "=", "'xyz'", ")", ":", "if", "isinstance", "(", "bbox3d", ",", "torch", ".", "Tensor", ")", ":", "bbox3d", "=", "bbox3d", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "bbox3d", "=", "bbox3d", ".", "copy", "(", ")", "in_box_color", "=", "np", ".", "array", "(", "points_in_box_color", ")", "for", "i", "in", "range", "(", "len", "(", "bbox3d", ")", ")", ":", "center", "=", "bbox3d", "[", "i", ",", "0", ":", "3", "]", "dim", "=", "bbox3d", "[", "i", ",", "3", ":", "6", "]", "yaw", "=", "np", ".", "zeros", "(", "3", ")", "yaw", "[", "rot_axis", "]", "=", "-", "bbox3d", "[", "i", ",", "6", "]", "rot_mat", "=", "geometry", ".", "get_rotation_matrix_from_xyz", "(", "yaw", ")", "if", "center_mode", "==", "'lidar_bottom'", ":", "center", "[", "rot_axis", "]", "+=", "dim", "[", "rot_axis", "]", "/", "2", "# bottom center to gravity center", "elif", "center_mode", "==", "'camera_bottom'", ":", "center", "[", "rot_axis", "]", "-=", "dim", "[", "rot_axis", "]", "/", "2", "# bottom center to gravity center", "box3d", "=", "geometry", ".", "OrientedBoundingBox", "(", "center", ",", "rot_mat", ",", "dim", ")", "line_set", "=", "geometry", ".", "LineSet", ".", "create_from_oriented_bounding_box", "(", "box3d", ")", "line_set", ".", "paint_uniform_color", "(", "bbox_color", ")", "# draw bboxes on visualizer", "vis", ".", "add_geometry", "(", "line_set", ")", "# change the color of points which are in box", "if", "pcd", "is", "not", "None", "and", "mode", "==", "'xyz'", ":", "indices", "=", "box3d", ".", "get_point_indices_within_bounding_box", "(", "pcd", ".", "points", ")", "points_colors", "[", "indices", "]", "=", "in_box_color", "# update points colors", "if", "pcd", "is", "not", "None", ":", "pcd", ".", "colors", "=", "o3d", ".", "utility", ".", "Vector3dVector", "(", "points_colors", ")", "vis", ".", "update_geometry", "(", "pcd", ")" ]
[ 55, 0 ]
[ 115, 32 ]
python
en
['en', 'en', 'en']
True
show_pts_boxes
(points, bbox3d=None, show=True, save_path=None, points_size=2, point_color=(0.5, 0.5, 0.5), bbox_color=(0, 1, 0), points_in_box_color=(1, 0, 0), rot_axis=2, center_mode='lidar_bottom', mode='xyz')
Draw bbox and points on visualizer. Args: points (numpy.array | torch.tensor, shape=[N, 3+C]): points to visualize. bbox3d (numpy.array | torch.tensor, shape=[M, 7]): 3d bbox (x, y, z, dx, dy, dz, yaw) to visualize. Default: None. show (bool): whether to show the visualization results. Default: True. save_path (str): path to save visualized results. Default: None. points_size (int): the size of points to show on visualizer. Default: 2. point_color (tuple[float]): the color of points. Default: (0.5, 0.5, 0.5). bbox_color (tuple[float]): the color of bbox. Default: (0, 1, 0). points_in_box_color (tuple[float]): the color of points which are in bbox3d. Default: (1, 0, 0). rot_axis (int): rotation axis of bbox. Default: 2. center_mode (bool): indicate the center of bbox is bottom center or gravity center. avaliable mode ['lidar_bottom', 'camera_bottom']. Default: 'lidar_bottom'. mode (str): indicate type of the input points, avaliable mode ['xyz', 'xyzrgb']. Default: 'xyz'.
Draw bbox and points on visualizer.
def show_pts_boxes(points, bbox3d=None, show=True, save_path=None, points_size=2, point_color=(0.5, 0.5, 0.5), bbox_color=(0, 1, 0), points_in_box_color=(1, 0, 0), rot_axis=2, center_mode='lidar_bottom', mode='xyz'): """Draw bbox and points on visualizer. Args: points (numpy.array | torch.tensor, shape=[N, 3+C]): points to visualize. bbox3d (numpy.array | torch.tensor, shape=[M, 7]): 3d bbox (x, y, z, dx, dy, dz, yaw) to visualize. Default: None. show (bool): whether to show the visualization results. Default: True. save_path (str): path to save visualized results. Default: None. points_size (int): the size of points to show on visualizer. Default: 2. point_color (tuple[float]): the color of points. Default: (0.5, 0.5, 0.5). bbox_color (tuple[float]): the color of bbox. Default: (0, 1, 0). points_in_box_color (tuple[float]): the color of points which are in bbox3d. Default: (1, 0, 0). rot_axis (int): rotation axis of bbox. Default: 2. center_mode (bool): indicate the center of bbox is bottom center or gravity center. avaliable mode ['lidar_bottom', 'camera_bottom']. Default: 'lidar_bottom'. mode (str): indicate type of the input points, avaliable mode ['xyz', 'xyzrgb']. Default: 'xyz'. """ # TODO: support score and class info assert 0 <= rot_axis <= 2 # init visualizer vis = o3d.visualization.Visualizer() vis.create_window() mesh_frame = geometry.TriangleMesh.create_coordinate_frame( size=1, origin=[0, 0, 0]) # create coordinate frame vis.add_geometry(mesh_frame) # draw points pcd, points_colors = _draw_points(points, vis, points_size, point_color, mode) # draw boxes if bbox3d is not None: _draw_bboxes(bbox3d, vis, points_colors, pcd, bbox_color, points_in_box_color, rot_axis, center_mode, mode) if show: vis.run() if save_path is not None: vis.capture_screen_image(save_path) vis.destroy_window()
[ "def", "show_pts_boxes", "(", "points", ",", "bbox3d", "=", "None", ",", "show", "=", "True", ",", "save_path", "=", "None", ",", "points_size", "=", "2", ",", "point_color", "=", "(", "0.5", ",", "0.5", ",", "0.5", ")", ",", "bbox_color", "=", "(", "0", ",", "1", ",", "0", ")", ",", "points_in_box_color", "=", "(", "1", ",", "0", ",", "0", ")", ",", "rot_axis", "=", "2", ",", "center_mode", "=", "'lidar_bottom'", ",", "mode", "=", "'xyz'", ")", ":", "# TODO: support score and class info", "assert", "0", "<=", "rot_axis", "<=", "2", "# init visualizer", "vis", "=", "o3d", ".", "visualization", ".", "Visualizer", "(", ")", "vis", ".", "create_window", "(", ")", "mesh_frame", "=", "geometry", ".", "TriangleMesh", ".", "create_coordinate_frame", "(", "size", "=", "1", ",", "origin", "=", "[", "0", ",", "0", ",", "0", "]", ")", "# create coordinate frame", "vis", ".", "add_geometry", "(", "mesh_frame", ")", "# draw points", "pcd", ",", "points_colors", "=", "_draw_points", "(", "points", ",", "vis", ",", "points_size", ",", "point_color", ",", "mode", ")", "# draw boxes", "if", "bbox3d", "is", "not", "None", ":", "_draw_bboxes", "(", "bbox3d", ",", "vis", ",", "points_colors", ",", "pcd", ",", "bbox_color", ",", "points_in_box_color", ",", "rot_axis", ",", "center_mode", ",", "mode", ")", "if", "show", ":", "vis", ".", "run", "(", ")", "if", "save_path", "is", "not", "None", ":", "vis", ".", "capture_screen_image", "(", "save_path", ")", "vis", ".", "destroy_window", "(", ")" ]
[ 118, 0 ]
[ 177, 24 ]
python
en
['en', 'en', 'en']
True
_draw_bboxes_ind
(bbox3d, vis, indices, points_colors, pcd=None, bbox_color=(0, 1, 0), points_in_box_color=(1, 0, 0), rot_axis=2, center_mode='lidar_bottom', mode='xyz')
Draw bbox on visualizer and change the color or points inside bbox3d with indices. Args: bbox3d (numpy.array | torch.tensor, shape=[M, 7]): 3d bbox (x, y, z, dx, dy, dz, yaw) to visualize. vis (:obj:`open3d.visualization.Visualizer`): open3d visualizer. indices (numpy.array | torch.tensor, shape=[N, M]): indicate which bbox3d that each point lies in. points_colors (numpy.array): color of each points. pcd (:obj:`open3d.geometry.PointCloud`): point cloud. Default: None. bbox_color (tuple[float]): the color of bbox. Default: (0, 1, 0). points_in_box_color (tuple[float]): the color of points which are in bbox3d. Default: (1, 0, 0). rot_axis (int): rotation axis of bbox. Default: 2. center_mode (bool): indicate the center of bbox is bottom center or gravity center. avaliable mode ['lidar_bottom', 'camera_bottom']. Default: 'lidar_bottom'. mode (str): indicate type of the input points, avaliable mode ['xyz', 'xyzrgb']. Default: 'xyz'.
Draw bbox on visualizer and change the color or points inside bbox3d with indices.
def _draw_bboxes_ind(bbox3d, vis, indices, points_colors, pcd=None, bbox_color=(0, 1, 0), points_in_box_color=(1, 0, 0), rot_axis=2, center_mode='lidar_bottom', mode='xyz'): """Draw bbox on visualizer and change the color or points inside bbox3d with indices. Args: bbox3d (numpy.array | torch.tensor, shape=[M, 7]): 3d bbox (x, y, z, dx, dy, dz, yaw) to visualize. vis (:obj:`open3d.visualization.Visualizer`): open3d visualizer. indices (numpy.array | torch.tensor, shape=[N, M]): indicate which bbox3d that each point lies in. points_colors (numpy.array): color of each points. pcd (:obj:`open3d.geometry.PointCloud`): point cloud. Default: None. bbox_color (tuple[float]): the color of bbox. Default: (0, 1, 0). points_in_box_color (tuple[float]): the color of points which are in bbox3d. Default: (1, 0, 0). rot_axis (int): rotation axis of bbox. Default: 2. center_mode (bool): indicate the center of bbox is bottom center or gravity center. avaliable mode ['lidar_bottom', 'camera_bottom']. Default: 'lidar_bottom'. mode (str): indicate type of the input points, avaliable mode ['xyz', 'xyzrgb']. Default: 'xyz'. """ if isinstance(bbox3d, torch.Tensor): bbox3d = bbox3d.cpu().numpy() if isinstance(indices, torch.Tensor): indices = indices.cpu().numpy() bbox3d = bbox3d.copy() in_box_color = np.array(points_in_box_color) for i in range(len(bbox3d)): center = bbox3d[i, 0:3] dim = bbox3d[i, 3:6] yaw = np.zeros(3) # TODO: fix problem of current coordinate system # dim[0], dim[1] = dim[1], dim[0] # for current coordinate # yaw[rot_axis] = -(bbox3d[i, 6] - 0.5 * np.pi) yaw[rot_axis] = -bbox3d[i, 6] rot_mat = geometry.get_rotation_matrix_from_xyz(yaw) if center_mode == 'lidar_bottom': center[rot_axis] += dim[ rot_axis] / 2 # bottom center to gravity center elif center_mode == 'camera_bottom': center[rot_axis] -= dim[ rot_axis] / 2 # bottom center to gravity center box3d = geometry.OrientedBoundingBox(center, rot_mat, dim) line_set = geometry.LineSet.create_from_oriented_bounding_box(box3d) line_set.paint_uniform_color(bbox_color) # draw bboxes on visualizer vis.add_geometry(line_set) # change the color of points which are in box if pcd is not None and mode == 'xyz': points_colors[indices[:, i].astype(np.bool)] = in_box_color # update points colors if pcd is not None: pcd.colors = o3d.utility.Vector3dVector(points_colors) vis.update_geometry(pcd)
[ "def", "_draw_bboxes_ind", "(", "bbox3d", ",", "vis", ",", "indices", ",", "points_colors", ",", "pcd", "=", "None", ",", "bbox_color", "=", "(", "0", ",", "1", ",", "0", ")", ",", "points_in_box_color", "=", "(", "1", ",", "0", ",", "0", ")", ",", "rot_axis", "=", "2", ",", "center_mode", "=", "'lidar_bottom'", ",", "mode", "=", "'xyz'", ")", ":", "if", "isinstance", "(", "bbox3d", ",", "torch", ".", "Tensor", ")", ":", "bbox3d", "=", "bbox3d", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "if", "isinstance", "(", "indices", ",", "torch", ".", "Tensor", ")", ":", "indices", "=", "indices", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "bbox3d", "=", "bbox3d", ".", "copy", "(", ")", "in_box_color", "=", "np", ".", "array", "(", "points_in_box_color", ")", "for", "i", "in", "range", "(", "len", "(", "bbox3d", ")", ")", ":", "center", "=", "bbox3d", "[", "i", ",", "0", ":", "3", "]", "dim", "=", "bbox3d", "[", "i", ",", "3", ":", "6", "]", "yaw", "=", "np", ".", "zeros", "(", "3", ")", "# TODO: fix problem of current coordinate system", "# dim[0], dim[1] = dim[1], dim[0] # for current coordinate", "# yaw[rot_axis] = -(bbox3d[i, 6] - 0.5 * np.pi)", "yaw", "[", "rot_axis", "]", "=", "-", "bbox3d", "[", "i", ",", "6", "]", "rot_mat", "=", "geometry", ".", "get_rotation_matrix_from_xyz", "(", "yaw", ")", "if", "center_mode", "==", "'lidar_bottom'", ":", "center", "[", "rot_axis", "]", "+=", "dim", "[", "rot_axis", "]", "/", "2", "# bottom center to gravity center", "elif", "center_mode", "==", "'camera_bottom'", ":", "center", "[", "rot_axis", "]", "-=", "dim", "[", "rot_axis", "]", "/", "2", "# bottom center to gravity center", "box3d", "=", "geometry", ".", "OrientedBoundingBox", "(", "center", ",", "rot_mat", ",", "dim", ")", "line_set", "=", "geometry", ".", "LineSet", ".", "create_from_oriented_bounding_box", "(", "box3d", ")", "line_set", ".", "paint_uniform_color", "(", "bbox_color", ")", "# draw bboxes on visualizer", "vis", ".", "add_geometry", "(", "line_set", ")", "# change the color of points which are in box", "if", "pcd", "is", "not", "None", "and", "mode", "==", "'xyz'", ":", "points_colors", "[", "indices", "[", ":", ",", "i", "]", ".", "astype", "(", "np", ".", "bool", ")", "]", "=", "in_box_color", "# update points colors", "if", "pcd", "is", "not", "None", ":", "pcd", ".", "colors", "=", "o3d", ".", "utility", ".", "Vector3dVector", "(", "points_colors", ")", "vis", ".", "update_geometry", "(", "pcd", ")" ]
[ 180, 0 ]
[ 247, 32 ]
python
en
['en', 'en', 'en']
True
show_pts_index_boxes
(points, bbox3d=None, show=True, indices=None, save_path=None, points_size=2, point_color=(0.5, 0.5, 0.5), bbox_color=(0, 1, 0), points_in_box_color=(1, 0, 0), rot_axis=2, center_mode='lidar_bottom', mode='xyz')
Draw bbox and points on visualizer with indices that indicate which bbox3d that each point lies in. Args: points (numpy.array | torch.tensor, shape=[N, 3+C]): points to visualize. bbox3d (numpy.array | torch.tensor, shape=[M, 7]): 3d bbox (x, y, z, dx, dy, dz, yaw) to visualize. Default: None. show (bool): whether to show the visualization results. Default: True. indices (numpy.array | torch.tensor, shape=[N, M]): indicate which bbox3d that each point lies in. Default: None. save_path (str): path to save visualized results. Default: None. points_size (int): the size of points to show on visualizer. Default: 2. point_color (tuple[float]): the color of points. Default: (0.5, 0.5, 0.5). bbox_color (tuple[float]): the color of bbox. Default: (0, 1, 0). points_in_box_color (tuple[float]): the color of points which are in bbox3d. Default: (1, 0, 0). rot_axis (int): rotation axis of bbox. Default: 2. center_mode (bool): indicate the center of bbox is bottom center or gravity center. avaliable mode ['lidar_bottom', 'camera_bottom']. Default: 'lidar_bottom'. mode (str): indicate type of the input points, avaliable mode ['xyz', 'xyzrgb']. Default: 'xyz'.
Draw bbox and points on visualizer with indices that indicate which bbox3d that each point lies in.
def show_pts_index_boxes(points, bbox3d=None, show=True, indices=None, save_path=None, points_size=2, point_color=(0.5, 0.5, 0.5), bbox_color=(0, 1, 0), points_in_box_color=(1, 0, 0), rot_axis=2, center_mode='lidar_bottom', mode='xyz'): """Draw bbox and points on visualizer with indices that indicate which bbox3d that each point lies in. Args: points (numpy.array | torch.tensor, shape=[N, 3+C]): points to visualize. bbox3d (numpy.array | torch.tensor, shape=[M, 7]): 3d bbox (x, y, z, dx, dy, dz, yaw) to visualize. Default: None. show (bool): whether to show the visualization results. Default: True. indices (numpy.array | torch.tensor, shape=[N, M]): indicate which bbox3d that each point lies in. Default: None. save_path (str): path to save visualized results. Default: None. points_size (int): the size of points to show on visualizer. Default: 2. point_color (tuple[float]): the color of points. Default: (0.5, 0.5, 0.5). bbox_color (tuple[float]): the color of bbox. Default: (0, 1, 0). points_in_box_color (tuple[float]): the color of points which are in bbox3d. Default: (1, 0, 0). rot_axis (int): rotation axis of bbox. Default: 2. center_mode (bool): indicate the center of bbox is bottom center or gravity center. avaliable mode ['lidar_bottom', 'camera_bottom']. Default: 'lidar_bottom'. mode (str): indicate type of the input points, avaliable mode ['xyz', 'xyzrgb']. Default: 'xyz'. """ # TODO: support score and class info assert 0 <= rot_axis <= 2 # init visualizer vis = o3d.visualization.Visualizer() vis.create_window() mesh_frame = geometry.TriangleMesh.create_coordinate_frame( size=1, origin=[0, 0, 0]) # create coordinate frame vis.add_geometry(mesh_frame) # draw points pcd, points_colors = _draw_points(points, vis, points_size, point_color, mode) # draw boxes if bbox3d is not None: _draw_bboxes_ind(bbox3d, vis, indices, points_colors, pcd, bbox_color, points_in_box_color, rot_axis, center_mode, mode) if show: vis.run() if save_path is not None: vis.capture_screen_image(save_path) vis.destroy_window()
[ "def", "show_pts_index_boxes", "(", "points", ",", "bbox3d", "=", "None", ",", "show", "=", "True", ",", "indices", "=", "None", ",", "save_path", "=", "None", ",", "points_size", "=", "2", ",", "point_color", "=", "(", "0.5", ",", "0.5", ",", "0.5", ")", ",", "bbox_color", "=", "(", "0", ",", "1", ",", "0", ")", ",", "points_in_box_color", "=", "(", "1", ",", "0", ",", "0", ")", ",", "rot_axis", "=", "2", ",", "center_mode", "=", "'lidar_bottom'", ",", "mode", "=", "'xyz'", ")", ":", "# TODO: support score and class info", "assert", "0", "<=", "rot_axis", "<=", "2", "# init visualizer", "vis", "=", "o3d", ".", "visualization", ".", "Visualizer", "(", ")", "vis", ".", "create_window", "(", ")", "mesh_frame", "=", "geometry", ".", "TriangleMesh", ".", "create_coordinate_frame", "(", "size", "=", "1", ",", "origin", "=", "[", "0", ",", "0", ",", "0", "]", ")", "# create coordinate frame", "vis", ".", "add_geometry", "(", "mesh_frame", ")", "# draw points", "pcd", ",", "points_colors", "=", "_draw_points", "(", "points", ",", "vis", ",", "points_size", ",", "point_color", ",", "mode", ")", "# draw boxes", "if", "bbox3d", "is", "not", "None", ":", "_draw_bboxes_ind", "(", "bbox3d", ",", "vis", ",", "indices", ",", "points_colors", ",", "pcd", ",", "bbox_color", ",", "points_in_box_color", ",", "rot_axis", ",", "center_mode", ",", "mode", ")", "if", "show", ":", "vis", ".", "run", "(", ")", "if", "save_path", "is", "not", "None", ":", "vis", ".", "capture_screen_image", "(", "save_path", ")", "vis", ".", "destroy_window", "(", ")" ]
[ 250, 0 ]
[ 313, 24 ]
python
en
['en', 'en', 'en']
True
project_pts_on_img
(points, raw_img, lidar2img_rt, max_distance=70, thickness=-1)
Project the 3D points cloud on 2D image. Args: points (numpy.array): 3D points cloud (x, y, z) to visualize. raw_img (numpy.array): The numpy array of image. lidar2img_rt (numpy.array, shape=[4, 4]): The projection matrix according to the camera intrinsic parameters. max_distance (float): the max distance of the points cloud. Default: 70. thickness (int, optional): The thickness of 2D points. Default: -1.
Project the 3D points cloud on 2D image.
def project_pts_on_img(points, raw_img, lidar2img_rt, max_distance=70, thickness=-1): """Project the 3D points cloud on 2D image. Args: points (numpy.array): 3D points cloud (x, y, z) to visualize. raw_img (numpy.array): The numpy array of image. lidar2img_rt (numpy.array, shape=[4, 4]): The projection matrix according to the camera intrinsic parameters. max_distance (float): the max distance of the points cloud. Default: 70. thickness (int, optional): The thickness of 2D points. Default: -1. """ img = raw_img.copy() num_points = points.shape[0] pts_4d = np.concatenate([points[:, :3], np.ones((num_points, 1))], axis=-1) pts_2d = pts_4d @ lidar2img_rt.T # cam_points is Tensor of Nx4 whose last column is 1 # transform camera coordinate to image coordinate pts_2d[:, 2] = np.clip(pts_2d[:, 2], a_min=1e-5, a_max=99999) pts_2d[:, 0] /= pts_2d[:, 2] pts_2d[:, 1] /= pts_2d[:, 2] fov_inds = ((pts_2d[:, 0] < img.shape[1]) & (pts_2d[:, 0] >= 0) & (pts_2d[:, 1] < img.shape[0]) & (pts_2d[:, 1] >= 0)) imgfov_pts_2d = pts_2d[fov_inds, :3] # u, v, d cmap = plt.cm.get_cmap('hsv', 256) cmap = np.array([cmap(i) for i in range(256)])[:, :3] * 255 for i in range(imgfov_pts_2d.shape[0]): depth = imgfov_pts_2d[i, 2] color = cmap[np.clip(int(max_distance * 10 / depth), 0, 255), :] cv2.circle( img, center=(int(np.round(imgfov_pts_2d[i, 0])), int(np.round(imgfov_pts_2d[i, 1]))), radius=1, color=tuple(color), thickness=thickness, ) cv2.imshow('project_pts_img', img) cv2.waitKey(100)
[ "def", "project_pts_on_img", "(", "points", ",", "raw_img", ",", "lidar2img_rt", ",", "max_distance", "=", "70", ",", "thickness", "=", "-", "1", ")", ":", "img", "=", "raw_img", ".", "copy", "(", ")", "num_points", "=", "points", ".", "shape", "[", "0", "]", "pts_4d", "=", "np", ".", "concatenate", "(", "[", "points", "[", ":", ",", ":", "3", "]", ",", "np", ".", "ones", "(", "(", "num_points", ",", "1", ")", ")", "]", ",", "axis", "=", "-", "1", ")", "pts_2d", "=", "pts_4d", "@", "lidar2img_rt", ".", "T", "# cam_points is Tensor of Nx4 whose last column is 1", "# transform camera coordinate to image coordinate", "pts_2d", "[", ":", ",", "2", "]", "=", "np", ".", "clip", "(", "pts_2d", "[", ":", ",", "2", "]", ",", "a_min", "=", "1e-5", ",", "a_max", "=", "99999", ")", "pts_2d", "[", ":", ",", "0", "]", "/=", "pts_2d", "[", ":", ",", "2", "]", "pts_2d", "[", ":", ",", "1", "]", "/=", "pts_2d", "[", ":", ",", "2", "]", "fov_inds", "=", "(", "(", "pts_2d", "[", ":", ",", "0", "]", "<", "img", ".", "shape", "[", "1", "]", ")", "&", "(", "pts_2d", "[", ":", ",", "0", "]", ">=", "0", ")", "&", "(", "pts_2d", "[", ":", ",", "1", "]", "<", "img", ".", "shape", "[", "0", "]", ")", "&", "(", "pts_2d", "[", ":", ",", "1", "]", ">=", "0", ")", ")", "imgfov_pts_2d", "=", "pts_2d", "[", "fov_inds", ",", ":", "3", "]", "# u, v, d", "cmap", "=", "plt", ".", "cm", ".", "get_cmap", "(", "'hsv'", ",", "256", ")", "cmap", "=", "np", ".", "array", "(", "[", "cmap", "(", "i", ")", "for", "i", "in", "range", "(", "256", ")", "]", ")", "[", ":", ",", ":", "3", "]", "*", "255", "for", "i", "in", "range", "(", "imgfov_pts_2d", ".", "shape", "[", "0", "]", ")", ":", "depth", "=", "imgfov_pts_2d", "[", "i", ",", "2", "]", "color", "=", "cmap", "[", "np", ".", "clip", "(", "int", "(", "max_distance", "*", "10", "/", "depth", ")", ",", "0", ",", "255", ")", ",", ":", "]", "cv2", ".", "circle", "(", "img", ",", "center", "=", "(", "int", "(", "np", ".", "round", "(", "imgfov_pts_2d", "[", "i", ",", "0", "]", ")", ")", ",", "int", "(", "np", ".", "round", "(", "imgfov_pts_2d", "[", "i", ",", "1", "]", ")", ")", ")", ",", "radius", "=", "1", ",", "color", "=", "tuple", "(", "color", ")", ",", "thickness", "=", "thickness", ",", ")", "cv2", ".", "imshow", "(", "'project_pts_img'", ",", "img", ")", "cv2", ".", "waitKey", "(", "100", ")" ]
[ 316, 0 ]
[ 364, 20 ]
python
en
['en', 'fr', 'en']
True
project_bbox3d_on_img
(bboxes3d, raw_img, lidar2img_rt, color=(0, 255, 0), thickness=1)
Project the 3D bbox on 2D image. Args: bboxes3d (numpy.array, shape=[M, 7]): 3d bbox (x, y, z, dx, dy, dz, yaw) to visualize. raw_img (numpy.array): The numpy array of image. lidar2img_rt (numpy.array, shape=[4, 4]): The projection matrix according to the camera intrinsic parameters. color (tuple[int]): the color to draw bboxes. Default: (0, 255, 0). thickness (int, optional): The thickness of bboxes. Default: 1.
Project the 3D bbox on 2D image.
def project_bbox3d_on_img(bboxes3d, raw_img, lidar2img_rt, color=(0, 255, 0), thickness=1): """Project the 3D bbox on 2D image. Args: bboxes3d (numpy.array, shape=[M, 7]): 3d bbox (x, y, z, dx, dy, dz, yaw) to visualize. raw_img (numpy.array): The numpy array of image. lidar2img_rt (numpy.array, shape=[4, 4]): The projection matrix according to the camera intrinsic parameters. color (tuple[int]): the color to draw bboxes. Default: (0, 255, 0). thickness (int, optional): The thickness of bboxes. Default: 1. """ img = raw_img.copy() corners_3d = bboxes3d.corners num_bbox = corners_3d.shape[0] pts_4d = np.concatenate( [corners_3d.reshape(-1, 3), np.ones((num_bbox * 8, 1))], axis=-1) pts_2d = pts_4d @ lidar2img_rt.T pts_2d[:, 2] = np.clip(pts_2d[:, 2], a_min=1e-5, a_max=1e5) pts_2d[:, 0] /= pts_2d[:, 2] pts_2d[:, 1] /= pts_2d[:, 2] imgfov_pts_2d = pts_2d[..., :2].reshape(num_bbox, 8, 2) line_indices = ((0, 1), (0, 3), (0, 4), (1, 2), (1, 5), (3, 2), (3, 7), (4, 5), (4, 7), (2, 6), (5, 6), (6, 7)) for i in range(num_bbox): corners = imgfov_pts_2d[i].astype(np.int) for start, end in line_indices: cv2.line(img, (corners[start, 0], corners[start, 1]), (corners[end, 0], corners[end, 1]), color, thickness, cv2.LINE_AA) cv2.imshow('project_bbox3d_img', img) cv2.waitKey(0)
[ "def", "project_bbox3d_on_img", "(", "bboxes3d", ",", "raw_img", ",", "lidar2img_rt", ",", "color", "=", "(", "0", ",", "255", ",", "0", ")", ",", "thickness", "=", "1", ")", ":", "img", "=", "raw_img", ".", "copy", "(", ")", "corners_3d", "=", "bboxes3d", ".", "corners", "num_bbox", "=", "corners_3d", ".", "shape", "[", "0", "]", "pts_4d", "=", "np", ".", "concatenate", "(", "[", "corners_3d", ".", "reshape", "(", "-", "1", ",", "3", ")", ",", "np", ".", "ones", "(", "(", "num_bbox", "*", "8", ",", "1", ")", ")", "]", ",", "axis", "=", "-", "1", ")", "pts_2d", "=", "pts_4d", "@", "lidar2img_rt", ".", "T", "pts_2d", "[", ":", ",", "2", "]", "=", "np", ".", "clip", "(", "pts_2d", "[", ":", ",", "2", "]", ",", "a_min", "=", "1e-5", ",", "a_max", "=", "1e5", ")", "pts_2d", "[", ":", ",", "0", "]", "/=", "pts_2d", "[", ":", ",", "2", "]", "pts_2d", "[", ":", ",", "1", "]", "/=", "pts_2d", "[", ":", ",", "2", "]", "imgfov_pts_2d", "=", "pts_2d", "[", "...", ",", ":", "2", "]", ".", "reshape", "(", "num_bbox", ",", "8", ",", "2", ")", "line_indices", "=", "(", "(", "0", ",", "1", ")", ",", "(", "0", ",", "3", ")", ",", "(", "0", ",", "4", ")", ",", "(", "1", ",", "2", ")", ",", "(", "1", ",", "5", ")", ",", "(", "3", ",", "2", ")", ",", "(", "3", ",", "7", ")", ",", "(", "4", ",", "5", ")", ",", "(", "4", ",", "7", ")", ",", "(", "2", ",", "6", ")", ",", "(", "5", ",", "6", ")", ",", "(", "6", ",", "7", ")", ")", "for", "i", "in", "range", "(", "num_bbox", ")", ":", "corners", "=", "imgfov_pts_2d", "[", "i", "]", ".", "astype", "(", "np", ".", "int", ")", "for", "start", ",", "end", "in", "line_indices", ":", "cv2", ".", "line", "(", "img", ",", "(", "corners", "[", "start", ",", "0", "]", ",", "corners", "[", "start", ",", "1", "]", ")", ",", "(", "corners", "[", "end", ",", "0", "]", ",", "corners", "[", "end", ",", "1", "]", ")", ",", "color", ",", "thickness", ",", "cv2", ".", "LINE_AA", ")", "cv2", ".", "imshow", "(", "'project_bbox3d_img'", ",", "img", ")", "cv2", ".", "waitKey", "(", "0", ")" ]
[ 367, 0 ]
[ 406, 18 ]
python
en
['en', 'en', 'en']
True
Visualizer.add_bboxes
(self, bbox3d, bbox_color=None, points_in_box_color=None)
Add bounding box to visualizer. Args: bbox3d (numpy.array, shape=[M, 7]): 3D bbox (x, y, z, dx, dy, dz, yaw) to be visualized. The 3d bbox is in mode of Box3DMode.DEPTH with gravity_center (please refer to core.structures.box_3d_mode). bbox_color (tuple[float]): the color of bbox. Defaule: None. points_in_box_color (tuple[float]): the color of points which are in bbox3d. Defaule: None.
Add bounding box to visualizer.
def add_bboxes(self, bbox3d, bbox_color=None, points_in_box_color=None): """Add bounding box to visualizer. Args: bbox3d (numpy.array, shape=[M, 7]): 3D bbox (x, y, z, dx, dy, dz, yaw) to be visualized. The 3d bbox is in mode of Box3DMode.DEPTH with gravity_center (please refer to core.structures.box_3d_mode). bbox_color (tuple[float]): the color of bbox. Defaule: None. points_in_box_color (tuple[float]): the color of points which are in bbox3d. Defaule: None. """ if bbox_color is None: bbox_color = self.bbox_color if points_in_box_color is None: points_in_box_color = self.points_in_box_color _draw_bboxes(bbox3d, self.o3d_visualizer, self.points_colors, self.pcd, bbox_color, points_in_box_color, self.rot_axis, self.center_mode, self.mode)
[ "def", "add_bboxes", "(", "self", ",", "bbox3d", ",", "bbox_color", "=", "None", ",", "points_in_box_color", "=", "None", ")", ":", "if", "bbox_color", "is", "None", ":", "bbox_color", "=", "self", ".", "bbox_color", "if", "points_in_box_color", "is", "None", ":", "points_in_box_color", "=", "self", ".", "points_in_box_color", "_draw_bboxes", "(", "bbox3d", ",", "self", ".", "o3d_visualizer", ",", "self", ".", "points_colors", ",", "self", ".", "pcd", ",", "bbox_color", ",", "points_in_box_color", ",", "self", ".", "rot_axis", ",", "self", ".", "center_mode", ",", "self", ".", "mode", ")" ]
[ 476, 4 ]
[ 494, 49 ]
python
en
['en', 'ny', 'en']
True
Visualizer.show
(self, save_path=None)
Visualize the points cloud. Args: save_path (str): path to save image. Default: None.
Visualize the points cloud.
def show(self, save_path=None): """Visualize the points cloud. Args: save_path (str): path to save image. Default: None. """ self.o3d_visualizer.run() if save_path is not None: self.o3d_visualizer.capture_screen_image(save_path) self.o3d_visualizer.destroy_window() return
[ "def", "show", "(", "self", ",", "save_path", "=", "None", ")", ":", "self", ".", "o3d_visualizer", ".", "run", "(", ")", "if", "save_path", "is", "not", "None", ":", "self", ".", "o3d_visualizer", ".", "capture_screen_image", "(", "save_path", ")", "self", ".", "o3d_visualizer", ".", "destroy_window", "(", ")", "return" ]
[ 496, 4 ]
[ 509, 14 ]
python
en
['en', 'en', 'en']
True
Lobby.antiraid
(self, ctx)
Enable antiraid to prevent new users from accessing the rest of the server.
Enable antiraid to prevent new users from accessing the rest of the server.
async def antiraid(self, ctx): """Enable antiraid to prevent new users from accessing the rest of the server.""" try: await ctx.message.delete() except discord.errors.NotFound: pass channel = discord.utils.get(ctx.guild.channels, name=self.lobby_channel) overwrite = dict(channel.overwrites)[ctx.guild.default_role] overwrite.send_messages = False await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite, reason='AntiRaid Enabled') await ctx.send('AntiRaid enabled.')
[ "async", "def", "antiraid", "(", "self", ",", "ctx", ")", ":", "try", ":", "await", "ctx", ".", "message", ".", "delete", "(", ")", "except", "discord", ".", "errors", ".", "NotFound", ":", "pass", "channel", "=", "discord", ".", "utils", ".", "get", "(", "ctx", ".", "guild", ".", "channels", ",", "name", "=", "self", ".", "lobby_channel", ")", "overwrite", "=", "dict", "(", "channel", ".", "overwrites", ")", "[", "ctx", ".", "guild", ".", "default_role", "]", "overwrite", ".", "send_messages", "=", "False", "await", "channel", ".", "set_permissions", "(", "ctx", ".", "guild", ".", "default_role", ",", "overwrite", "=", "overwrite", ",", "reason", "=", "'AntiRaid Enabled'", ")", "await", "ctx", ".", "send", "(", "'AntiRaid enabled.'", ")" ]
[ 58, 4 ]
[ 72, 43 ]
python
en
['en', 'en', 'en']
True
Lobby.antiraid_off
(self, ctx)
Disable antiraid.
Disable antiraid.
async def antiraid_off(self, ctx): """Disable antiraid.""" try: await ctx.message.delete() except discord.errors.NotFound: pass channel = discord.utils.get(ctx.guild.channels, name=self.lobby_channel) overwrite = dict(channel.overwrites)[ctx.guild.default_role] overwrite.send_messages = True await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite, reason='AntiRaid Disabled') await ctx.send('AntiRaid disabled.')
[ "async", "def", "antiraid_off", "(", "self", ",", "ctx", ")", ":", "try", ":", "await", "ctx", ".", "message", ".", "delete", "(", ")", "except", "discord", ".", "errors", ".", "NotFound", ":", "pass", "channel", "=", "discord", ".", "utils", ".", "get", "(", "ctx", ".", "guild", ".", "channels", ",", "name", "=", "self", ".", "lobby_channel", ")", "overwrite", "=", "dict", "(", "channel", ".", "overwrites", ")", "[", "ctx", ".", "guild", ".", "default_role", "]", "overwrite", ".", "send_messages", "=", "True", "await", "channel", ".", "set_permissions", "(", "ctx", ".", "guild", ".", "default_role", ",", "overwrite", "=", "overwrite", ",", "reason", "=", "'AntiRaid Disabled'", ")", "await", "ctx", ".", "send", "(", "'AntiRaid disabled.'", ")" ]
[ 78, 4 ]
[ 92, 44 ]
python
en
['en', 'gd', 'en']
False
send_notification
(line)
Send a message to IRC channel via HTTP bridge. Ars: line (str): message to send
Send a message to IRC channel via HTTP bridge.
def send_notification(line): """Send a message to IRC channel via HTTP bridge. Ars: line (str): message to send """ print('> ' + line) try: response = requests.post(SERENITY_BOT, data={'msg': line}) except BaseException as e: print('Notification failed: {}: {}'.format(type(e), e)) else: print('Notification result: HTTP {}'.format(response.status_code))
[ "def", "send_notification", "(", "line", ")", ":", "print", "(", "'> '", "+", "line", ")", "try", ":", "response", "=", "requests", ".", "post", "(", "SERENITY_BOT", ",", "data", "=", "{", "'msg'", ":", "line", "}", ")", "except", "BaseException", "as", "e", ":", "print", "(", "'Notification failed: {}: {}'", ".", "format", "(", "type", "(", "e", ")", ",", "e", ")", ")", "else", ":", "print", "(", "'Notification result: HTTP {}'", ".", "format", "(", "response", ".", "status_code", ")", ")" ]
[ 84, 0 ]
[ 97, 74 ]
python
en
['en', 'fr', 'en']
True
FastAcuteExecutor.__init__
(self, args: DictConfig, model_config: Optional[Dict[str, Any]] = None)
Pass in model_config directly to override the model config file, args.mephisto.blueprint, that would be read in otherwise.
Pass in model_config directly to override the model config file, args.mephisto.blueprint, that would be read in otherwise.
def __init__(self, args: DictConfig, model_config: Optional[Dict[str, Any]] = None): """ Pass in model_config directly to override the model config file, args.mephisto.blueprint, that would be read in otherwise. """ self.args = args self.fast_acute_args = self.args.mephisto.blueprint # Load configs for models if model_config is not None: self.model_config = model_config else: with open(self.fast_acute_args.config_path) as f: self.model_config = json.load(f) # models + task self._build_model_pairs() self.task: str = self.fast_acute_args.task # keep track of chat files per model self.chat_files: Dict[str, str] = {} # question config for running ACUTE self.question_config: Dict[str, str] = ACUTE_EVAL_TYPES[ self.fast_acute_args.acute_eval_type ] self.run_id = self.args.mephisto.task.task_name
[ "def", "__init__", "(", "self", ",", "args", ":", "DictConfig", ",", "model_config", ":", "Optional", "[", "Dict", "[", "str", ",", "Any", "]", "]", "=", "None", ")", ":", "self", ".", "args", "=", "args", "self", ".", "fast_acute_args", "=", "self", ".", "args", ".", "mephisto", ".", "blueprint", "# Load configs for models", "if", "model_config", "is", "not", "None", ":", "self", ".", "model_config", "=", "model_config", "else", ":", "with", "open", "(", "self", ".", "fast_acute_args", ".", "config_path", ")", "as", "f", ":", "self", ".", "model_config", "=", "json", ".", "load", "(", "f", ")", "# models + task", "self", ".", "_build_model_pairs", "(", ")", "self", ".", "task", ":", "str", "=", "self", ".", "fast_acute_args", ".", "task", "# keep track of chat files per model", "self", ".", "chat_files", ":", "Dict", "[", "str", ",", "str", "]", "=", "{", "}", "# question config for running ACUTE", "self", ".", "question_config", ":", "Dict", "[", "str", ",", "str", "]", "=", "ACUTE_EVAL_TYPES", "[", "self", ".", "fast_acute_args", ".", "acute_eval_type", "]", "self", ".", "run_id", "=", "self", ".", "args", ".", "mephisto", ".", "task", ".", "task_name" ]
[ 78, 4 ]
[ 106, 55 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._build_model_pairs
(self)
Generate self.models and self.combos from self.args.
Generate self.models and self.combos from self.args.
def _build_model_pairs(self): """ Generate self.models and self.combos from self.args. """ choices = self.model_config.keys() combos: Set[Tuple[str, str]] = set() models: Set[str] = set() if ( self.fast_acute_args.models is None and self.fast_acute_args.model_pairs is None ): raise RuntimeError( 'Either models or model-pairs should be set for comparision.' ) if self.fast_acute_args.model_pairs is not None: model_pairs = self.fast_acute_args.model_pairs.split(',') combos = [model_pair.split(':') for model_pair in model_pairs] for model_pair in combos: models.add(model_pair[0]) models.add(model_pair[1]) else: models = set(self.fast_acute_args.models.split(',')) combos = set(combinations(models, 2)) self.models: List[str] = list(models) self.models.sort() self.combos: List[Tuple[str, str]] = [] for combo in combos: # Sort the two model names for consistency self.combos.append(tuple(sorted(combo))) # verify that models are contained in the config: for model in self.models: if model not in choices: raise RuntimeError(f'Model {model} not specified in the config.') assert len(self.models) > 1, 'Must specify least 2 models'
[ "def", "_build_model_pairs", "(", "self", ")", ":", "choices", "=", "self", ".", "model_config", ".", "keys", "(", ")", "combos", ":", "Set", "[", "Tuple", "[", "str", ",", "str", "]", "]", "=", "set", "(", ")", "models", ":", "Set", "[", "str", "]", "=", "set", "(", ")", "if", "(", "self", ".", "fast_acute_args", ".", "models", "is", "None", "and", "self", ".", "fast_acute_args", ".", "model_pairs", "is", "None", ")", ":", "raise", "RuntimeError", "(", "'Either models or model-pairs should be set for comparision.'", ")", "if", "self", ".", "fast_acute_args", ".", "model_pairs", "is", "not", "None", ":", "model_pairs", "=", "self", ".", "fast_acute_args", ".", "model_pairs", ".", "split", "(", "','", ")", "combos", "=", "[", "model_pair", ".", "split", "(", "':'", ")", "for", "model_pair", "in", "model_pairs", "]", "for", "model_pair", "in", "combos", ":", "models", ".", "add", "(", "model_pair", "[", "0", "]", ")", "models", ".", "add", "(", "model_pair", "[", "1", "]", ")", "else", ":", "models", "=", "set", "(", "self", ".", "fast_acute_args", ".", "models", ".", "split", "(", "','", ")", ")", "combos", "=", "set", "(", "combinations", "(", "models", ",", "2", ")", ")", "self", ".", "models", ":", "List", "[", "str", "]", "=", "list", "(", "models", ")", "self", ".", "models", ".", "sort", "(", ")", "self", ".", "combos", ":", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", "=", "[", "]", "for", "combo", "in", "combos", ":", "# Sort the two model names for consistency", "self", ".", "combos", ".", "append", "(", "tuple", "(", "sorted", "(", "combo", ")", ")", ")", "# verify that models are contained in the config:", "for", "model", "in", "self", ".", "models", ":", "if", "model", "not", "in", "choices", ":", "raise", "RuntimeError", "(", "f'Model {model} not specified in the config.'", ")", "assert", "len", "(", "self", ".", "models", ")", ">", "1", ",", "'Must specify least 2 models'" ]
[ 111, 4 ]
[ 144, 66 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._print_progress
(self, msg: str)
Format a msg to print to stdout well. :param msg: message to print
Format a msg to print to stdout well.
def _print_progress(self, msg: str): """ Format a msg to print to stdout well. :param msg: message to print """ print(f"\n{'-' * 60}\n {msg} \n {'-' * 60}")
[ "def", "_print_progress", "(", "self", ",", "msg", ":", "str", ")", ":", "print", "(", "f\"\\n{'-' * 60}\\n {msg} \\n {'-' * 60}\"", ")" ]
[ 146, 4 ]
[ 153, 52 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._get_selfchat_config
(self, model: str)
Return config for selfchat. :param model: model string :return config: dict config for self-chat
Return config for selfchat.
def _get_selfchat_config(self, model: str) -> Dict[str, Any]: """ Return config for selfchat. :param model: model string :return config: dict config for self-chat """ outfile = self._get_selfchat_log_path(model) config = self.model_config[model] config.update( { 'task': self.task, 'outfile': outfile, 'num_self_chats': self.fast_acute_args.num_self_chats, 'selfchat_max_turns': self.fast_acute_args.selfchat_max_turns, 'display_examples': False, 'log_every_n_secs': -1, 'indent': -1, } ) return config
[ "def", "_get_selfchat_config", "(", "self", ",", "model", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "outfile", "=", "self", ".", "_get_selfchat_log_path", "(", "model", ")", "config", "=", "self", ".", "model_config", "[", "model", "]", "config", ".", "update", "(", "{", "'task'", ":", "self", ".", "task", ",", "'outfile'", ":", "outfile", ",", "'num_self_chats'", ":", "self", ".", "fast_acute_args", ".", "num_self_chats", ",", "'selfchat_max_turns'", ":", "self", ".", "fast_acute_args", ".", "selfchat_max_turns", ",", "'display_examples'", ":", "False", ",", "'log_every_n_secs'", ":", "-", "1", ",", "'indent'", ":", "-", "1", ",", "}", ")", "return", "config" ]
[ 155, 4 ]
[ 178, 21 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._get_task_conversion_config
(self, model: str)
Return config for task conversion to conversation format.
Return config for task conversion to conversation format.
def _get_task_conversion_config(self, model: str) -> Dict[str, Any]: """ Return config for task conversion to conversation format. """ outfile = self._get_task_data_path(model) config = self.model_config[model] config.update( { 'outfile': outfile, 'num_episodes': self.fast_acute_args.num_task_data_episodes, 'speaker_0_id': f'{model}_as_human', 'speaker_1_id': model, } ) return config
[ "def", "_get_task_conversion_config", "(", "self", ",", "model", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "outfile", "=", "self", ".", "_get_task_data_path", "(", "model", ")", "config", "=", "self", ".", "model_config", "[", "model", "]", "config", ".", "update", "(", "{", "'outfile'", ":", "outfile", ",", "'num_episodes'", ":", "self", ".", "fast_acute_args", ".", "num_task_data_episodes", ",", "'speaker_0_id'", ":", "f'{model}_as_human'", ",", "'speaker_1_id'", ":", "model", ",", "}", ")", "return", "config" ]
[ 180, 4 ]
[ 194, 21 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor.get_relative_selfchat_log_path
(root_dir: str, model: str, task: str)
Return path to selfchat log for a given model, given inputs. Useful for getting selfchat log path without instantiating the exector.
Return path to selfchat log for a given model, given inputs.
def get_relative_selfchat_log_path(root_dir: str, model: str, task: str) -> str: """ Return path to selfchat log for a given model, given inputs. Useful for getting selfchat log path without instantiating the exector. """ self_chats_folder = os.path.join(root_dir, 'self_chats') os.makedirs(self_chats_folder, exist_ok=True) return os.path.join( self_chats_folder, f"{model}.{task.replace(':', '_')}.jsonl" )
[ "def", "get_relative_selfchat_log_path", "(", "root_dir", ":", "str", ",", "model", ":", "str", ",", "task", ":", "str", ")", "->", "str", ":", "self_chats_folder", "=", "os", ".", "path", ".", "join", "(", "root_dir", ",", "'self_chats'", ")", "os", ".", "makedirs", "(", "self_chats_folder", ",", "exist_ok", "=", "True", ")", "return", "os", ".", "path", ".", "join", "(", "self_chats_folder", ",", "f\"{model}.{task.replace(':', '_')}.jsonl\"", ")" ]
[ 197, 4 ]
[ 207, 9 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._get_log_path
(self, model: str)
Return path to chat logs for the given model.
Return path to chat logs for the given model.
def _get_log_path(self, model: str) -> str: """ Return path to chat logs for the given model. """ config = self.model_config[model] if 'log_path' in config: path = config['log_path'] assert os.path.exists( path ), f'Path provided in log_path for {model} does not exist' elif 'task' in config: path = self._get_task_data_path(model) elif 'model' in config: path = self._get_selfchat_log_path(model) else: raise ValueError(f'Invalid config for {model}') return path
[ "def", "_get_log_path", "(", "self", ",", "model", ":", "str", ")", "->", "str", ":", "config", "=", "self", ".", "model_config", "[", "model", "]", "if", "'log_path'", "in", "config", ":", "path", "=", "config", "[", "'log_path'", "]", "assert", "os", ".", "path", ".", "exists", "(", "path", ")", ",", "f'Path provided in log_path for {model} does not exist'", "elif", "'task'", "in", "config", ":", "path", "=", "self", ".", "_get_task_data_path", "(", "model", ")", "elif", "'model'", "in", "config", ":", "path", "=", "self", ".", "_get_selfchat_log_path", "(", "model", ")", "else", ":", "raise", "ValueError", "(", "f'Invalid config for {model}'", ")", "return", "path" ]
[ 209, 4 ]
[ 226, 19 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._get_task_data_path
(self, model: str)
Return path to task data as conversations for given task.
Return path to task data as conversations for given task.
def _get_task_data_path(self, model: str) -> str: """ Return path to task data as conversations for given task. """ task_data_dir = os.path.join( self.fast_acute_args.root_dir, 'tasks_as_conversations' ) os.makedirs(task_data_dir, exist_ok=True) return os.path.join(task_data_dir, f"{model}.jsonl")
[ "def", "_get_task_data_path", "(", "self", ",", "model", ":", "str", ")", "->", "str", ":", "task_data_dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "fast_acute_args", ".", "root_dir", ",", "'tasks_as_conversations'", ")", "os", ".", "makedirs", "(", "task_data_dir", ",", "exist_ok", "=", "True", ")", "return", "os", ".", "path", ".", "join", "(", "task_data_dir", ",", "f\"{model}.jsonl\"", ")" ]
[ 228, 4 ]
[ 236, 60 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._get_selfchat_log_path
(self, model: str)
Return path to selfchat log for a given model. :param model: model string
Return path to selfchat log for a given model.
def _get_selfchat_log_path(self, model: str) -> str: """ Return path to selfchat log for a given model. :param model: model string """ return self.get_relative_selfchat_log_path( root_dir=self.fast_acute_args.root_dir, model=model, task=self.task )
[ "def", "_get_selfchat_log_path", "(", "self", ",", "model", ":", "str", ")", "->", "str", ":", "return", "self", ".", "get_relative_selfchat_log_path", "(", "root_dir", "=", "self", ".", "fast_acute_args", ".", "root_dir", ",", "model", "=", "model", ",", "task", "=", "self", ".", "task", ")" ]
[ 238, 4 ]
[ 247, 9 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._acutify_convo
( self, dialogue_dict: Dict[str, Any], model: str )
Format world-logged conversation to be ACUTE format. :param dialogue_dict: dictionary containing the dialogue for a model :param model: model string :return conversation: An ACUTE-Readable conversation
Format world-logged conversation to be ACUTE format.
def _acutify_convo( self, dialogue_dict: Dict[str, Any], model: str ) -> Dict[str, List]: """ Format world-logged conversation to be ACUTE format. :param dialogue_dict: dictionary containing the dialogue for a model :param model: model string :return conversation: An ACUTE-Readable conversation """ is_selfchat = 'model' in self.model_config[model] or self.model_config[ model ].get('is_selfchat', False) # It's a self-chat if one of the following are true: # (1) a model is specified in the config, meaning that we're collecting # self-chats with that model # (2) we manually set 'is_selfchat' to True in the config conversation = {'context': [], 'dialogue': [], 'speakers': []} dialog = dialogue_dict['dialog'] for act_pair in dialog: for i, ex in enumerate(act_pair): if ex['id'] == 'context': conversation['context'].append(ex) continue if is_selfchat: speaker_id = model if i == 0 else f'other_speaker' else: speaker_id = ex['id'] if speaker_id not in conversation['speakers']: conversation['speakers'].append(speaker_id) conversation['dialogue'].append( {'id': speaker_id, 'text': normalize_reply(ex['text'])} ) return conversation
[ "def", "_acutify_convo", "(", "self", ",", "dialogue_dict", ":", "Dict", "[", "str", ",", "Any", "]", ",", "model", ":", "str", ")", "->", "Dict", "[", "str", ",", "List", "]", ":", "is_selfchat", "=", "'model'", "in", "self", ".", "model_config", "[", "model", "]", "or", "self", ".", "model_config", "[", "model", "]", ".", "get", "(", "'is_selfchat'", ",", "False", ")", "# It's a self-chat if one of the following are true:", "# (1) a model is specified in the config, meaning that we're collecting", "# self-chats with that model", "# (2) we manually set 'is_selfchat' to True in the config", "conversation", "=", "{", "'context'", ":", "[", "]", ",", "'dialogue'", ":", "[", "]", ",", "'speakers'", ":", "[", "]", "}", "dialog", "=", "dialogue_dict", "[", "'dialog'", "]", "for", "act_pair", "in", "dialog", ":", "for", "i", ",", "ex", "in", "enumerate", "(", "act_pair", ")", ":", "if", "ex", "[", "'id'", "]", "==", "'context'", ":", "conversation", "[", "'context'", "]", ".", "append", "(", "ex", ")", "continue", "if", "is_selfchat", ":", "speaker_id", "=", "model", "if", "i", "==", "0", "else", "f'other_speaker'", "else", ":", "speaker_id", "=", "ex", "[", "'id'", "]", "if", "speaker_id", "not", "in", "conversation", "[", "'speakers'", "]", ":", "conversation", "[", "'speakers'", "]", ".", "append", "(", "speaker_id", ")", "conversation", "[", "'dialogue'", "]", ".", "append", "(", "{", "'id'", ":", "speaker_id", ",", "'text'", ":", "normalize_reply", "(", "ex", "[", "'text'", "]", ")", "}", ")", "return", "conversation" ]
[ 249, 4 ]
[ 286, 27 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._load_selfchats
(self)
Load selfchats for models. :return conversations: A dictionary mapping model_id to self-chat dialogues
Load selfchats for models.
def _load_selfchats(self) -> Dict[str, List[Dict[str, Any]]]: """ Load selfchats for models. :return conversations: A dictionary mapping model_id to self-chat dialogues """ conversations = {} for m in self.models: model_fp = self.chat_files[m] conversations[m] = [] with open(model_fp) as f_read: for line in f_read: conversations[m].append(json.loads(line.strip())) return conversations
[ "def", "_load_selfchats", "(", "self", ")", "->", "Dict", "[", "str", ",", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", "]", ":", "conversations", "=", "{", "}", "for", "m", "in", "self", ".", "models", ":", "model_fp", "=", "self", ".", "chat_files", "[", "m", "]", "conversations", "[", "m", "]", "=", "[", "]", "with", "open", "(", "model_fp", ")", "as", "f_read", ":", "for", "line", "in", "f_read", ":", "conversations", "[", "m", "]", ".", "append", "(", "json", ".", "loads", "(", "line", ".", "strip", "(", ")", ")", ")", "return", "conversations" ]
[ 288, 4 ]
[ 302, 28 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._build_conversation_pairs
( self, conversations: Dict[str, List[Dict[str, Any]]] )
Build a conversation pair to show during ACUTE Eval. :param conversations: A dictionary mapping model_id to self-chat dialogues :return pairs: A list of conversation pairs
Build a conversation pair to show during ACUTE Eval.
def _build_conversation_pairs( self, conversations: Dict[str, List[Dict[str, Any]]] ) -> List[Dict[str, Any]]: """ Build a conversation pair to show during ACUTE Eval. :param conversations: A dictionary mapping model_id to self-chat dialogues :return pairs: A list of conversation pairs """ self._assign_unique_ids(conversations) # TODO: make it so that we don't necessarily have to evaluate # every possible pairing between models pairs = [] pairs_per_model = ( self.fast_acute_args.matchups_per_pair * self.fast_acute_args.sufficient_matchups_multiplier ) # Write random pairs of conversations for model_pair in self.combos: for _ in range(pairs_per_model): conversation_indices = [ random.choice(range(len(conversations[m]))) for m in model_pair ] pair = [] pair_ids = [] for i, c_id in enumerate(conversation_indices): model = model_pair[i] pair.append(self._acutify_convo(conversations[model][c_id], model)) pair_ids.append(conversations[model][c_id]['unique_id']) pairs.append( { "is_onboarding": False, "speakers_to_eval": model_pair, "dialogue_dicts": pair, "dialogue_ids": pair_ids, } ) return pairs
[ "def", "_build_conversation_pairs", "(", "self", ",", "conversations", ":", "Dict", "[", "str", ",", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", "]", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "self", ".", "_assign_unique_ids", "(", "conversations", ")", "# TODO: make it so that we don't necessarily have to evaluate", "# every possible pairing between models", "pairs", "=", "[", "]", "pairs_per_model", "=", "(", "self", ".", "fast_acute_args", ".", "matchups_per_pair", "*", "self", ".", "fast_acute_args", ".", "sufficient_matchups_multiplier", ")", "# Write random pairs of conversations", "for", "model_pair", "in", "self", ".", "combos", ":", "for", "_", "in", "range", "(", "pairs_per_model", ")", ":", "conversation_indices", "=", "[", "random", ".", "choice", "(", "range", "(", "len", "(", "conversations", "[", "m", "]", ")", ")", ")", "for", "m", "in", "model_pair", "]", "pair", "=", "[", "]", "pair_ids", "=", "[", "]", "for", "i", ",", "c_id", "in", "enumerate", "(", "conversation_indices", ")", ":", "model", "=", "model_pair", "[", "i", "]", "pair", ".", "append", "(", "self", ".", "_acutify_convo", "(", "conversations", "[", "model", "]", "[", "c_id", "]", ",", "model", ")", ")", "pair_ids", ".", "append", "(", "conversations", "[", "model", "]", "[", "c_id", "]", "[", "'unique_id'", "]", ")", "pairs", ".", "append", "(", "{", "\"is_onboarding\"", ":", "False", ",", "\"speakers_to_eval\"", ":", "model_pair", ",", "\"dialogue_dicts\"", ":", "pair", ",", "\"dialogue_ids\"", ":", "pair_ids", ",", "}", ")", "return", "pairs" ]
[ 311, 4 ]
[ 351, 20 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._build_pairings_file
(self, pairings_filepath: str)
Build and save pairings to pairings file.
Build and save pairings to pairings file.
def _build_pairings_file(self, pairings_filepath: str): """ Build and save pairings to pairings file. """ if self.fast_acute_args.onboarding_path is not None: onboarding_path = self.fast_acute_args.onboarding_path else: # Default onboarding location onboarding_path = os.path.join( self.fast_acute_args.root_dir, 'onboarding.json' ) with open(onboarding_path) as f: onboarding_convo_pair: Dict[str, Any] = json.load(f) self._print_progress(f'building pairings file, saving at {pairings_filepath}') conversations = self._load_selfchats() pairs = self._build_conversation_pairs(conversations) with open(pairings_filepath, 'w') as f: # Write the onboarding convo f.write(json.dumps(onboarding_convo_pair) + "\n") for pair in pairs: f.write(json.dumps(pair) + "\n")
[ "def", "_build_pairings_file", "(", "self", ",", "pairings_filepath", ":", "str", ")", ":", "if", "self", ".", "fast_acute_args", ".", "onboarding_path", "is", "not", "None", ":", "onboarding_path", "=", "self", ".", "fast_acute_args", ".", "onboarding_path", "else", ":", "# Default onboarding location", "onboarding_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "fast_acute_args", ".", "root_dir", ",", "'onboarding.json'", ")", "with", "open", "(", "onboarding_path", ")", "as", "f", ":", "onboarding_convo_pair", ":", "Dict", "[", "str", ",", "Any", "]", "=", "json", ".", "load", "(", "f", ")", "self", ".", "_print_progress", "(", "f'building pairings file, saving at {pairings_filepath}'", ")", "conversations", "=", "self", ".", "_load_selfchats", "(", ")", "pairs", "=", "self", ".", "_build_conversation_pairs", "(", "conversations", ")", "with", "open", "(", "pairings_filepath", ",", "'w'", ")", "as", "f", ":", "# Write the onboarding convo", "f", ".", "write", "(", "json", ".", "dumps", "(", "onboarding_convo_pair", ")", "+", "\"\\n\"", ")", "for", "pair", "in", "pairs", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "pair", ")", "+", "\"\\n\"", ")" ]
[ 353, 4 ]
[ 376, 48 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._load_pairings_file
(self)
Build the pairings file for the two models. If a pairings file already exists, we ask the user whether they would like to overwrite the pairings file.
Build the pairings file for the two models.
def _load_pairings_file(self): """ Build the pairings file for the two models. If a pairings file already exists, we ask the user whether they would like to overwrite the pairings file. """ pairings_filepath = get_hashed_combo_path( root_dir=self.fast_acute_args.root_dir, subdir='pairings_files', task=self.task, combos=self.combos, ) if not os.path.exists(pairings_filepath): self._build_pairings_file(pairings_filepath) else: modify_time = os.path.getmtime(pairings_filepath) self._print_progress( f'Pairings already exist {pairings_filepath}. Last modified {time.ctime(modify_time)}' ) if not self.fast_acute_args.use_existing_self_chat_files: answer = '' while answer.lower().strip() != 'y' and answer.lower().strip() != 'o': answer = input('Enter y to use, o to overwrite:') if answer.lower().strip() == 'o': self._build_pairings_file(pairings_filepath) self._print_progress(f'loading pairings file from {pairings_filepath}') self.pairings_filepath = pairings_filepath
[ "def", "_load_pairings_file", "(", "self", ")", ":", "pairings_filepath", "=", "get_hashed_combo_path", "(", "root_dir", "=", "self", ".", "fast_acute_args", ".", "root_dir", ",", "subdir", "=", "'pairings_files'", ",", "task", "=", "self", ".", "task", ",", "combos", "=", "self", ".", "combos", ",", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "pairings_filepath", ")", ":", "self", ".", "_build_pairings_file", "(", "pairings_filepath", ")", "else", ":", "modify_time", "=", "os", ".", "path", ".", "getmtime", "(", "pairings_filepath", ")", "self", ".", "_print_progress", "(", "f'Pairings already exist {pairings_filepath}. Last modified {time.ctime(modify_time)}'", ")", "if", "not", "self", ".", "fast_acute_args", ".", "use_existing_self_chat_files", ":", "answer", "=", "''", "while", "answer", ".", "lower", "(", ")", ".", "strip", "(", ")", "!=", "'y'", "and", "answer", ".", "lower", "(", ")", ".", "strip", "(", ")", "!=", "'o'", ":", "answer", "=", "input", "(", "'Enter y to use, o to overwrite:'", ")", "if", "answer", ".", "lower", "(", ")", ".", "strip", "(", ")", "==", "'o'", ":", "self", ".", "_build_pairings_file", "(", "pairings_filepath", ")", "self", ".", "_print_progress", "(", "f'loading pairings file from {pairings_filepath}'", ")", "self", ".", "pairings_filepath", "=", "pairings_filepath" ]
[ 378, 4 ]
[ 406, 50 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor._convert_task_to_conversations
(self, model: str)
Convert task data to conversations format.
Convert task data to conversations format.
def _convert_task_to_conversations(self, model: str): """ Convert task data to conversations format. """ self._print_progress( f'Converting task data to conversations format for {model}' ) config = self._get_task_conversion_config(model) with capture_output(): parser = convert_task_setup_args() parser.set_params(**config) opt = parser.parse_args(args=[]) convert_task_data(opt)
[ "def", "_convert_task_to_conversations", "(", "self", ",", "model", ":", "str", ")", ":", "self", ".", "_print_progress", "(", "f'Converting task data to conversations format for {model}'", ")", "config", "=", "self", ".", "_get_task_conversion_config", "(", "model", ")", "with", "capture_output", "(", ")", ":", "parser", "=", "convert_task_setup_args", "(", ")", "parser", ".", "set_params", "(", "*", "*", "config", ")", "opt", "=", "parser", ".", "parse_args", "(", "args", "=", "[", "]", ")", "convert_task_data", "(", "opt", ")" ]
[ 408, 4 ]
[ 421, 30 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor.compile_chat_logs
(self)
Compile chat logs. Logs are generated depending on what is specified in the config for the model: 1. If a `model` is provided, run selfchat for model 2. If a `log_path` is provided, simply load the log path 3. If a `task` is provided, convert the task to ACUTE format and load that.
Compile chat logs.
def compile_chat_logs(self): """ Compile chat logs. Logs are generated depending on what is specified in the config for the model: 1. If a `model` is provided, run selfchat for model 2. If a `log_path` is provided, simply load the log path 3. If a `task` is provided, convert the task to ACUTE format and load that. """ for model in self.models: try: torch.cuda.empty_cache() except Exception: pass self._print_progress(f'Running self-chat for {model}') outfile = self._get_log_path(model) if not os.path.exists(outfile): if 'model' in self.model_config[model]: config = self._get_selfchat_config(model) with capture_output(): parser = self_chat_setup_args() parser.set_params(**config) opt = parser.parse_args(args=[]) self_chat(opt) elif 'task' in self.model_config[model]: self._convert_task_to_conversations(model) else: raise RuntimeError( f'Path must exist if log_path specified for {model}' ) if os.path.exists(outfile): self._print_progress(f'Chats saved to {outfile} for {model}') self._print_progress(f'Chats already exist in {outfile}, moving on...') self.chat_files[model] = outfile
[ "def", "compile_chat_logs", "(", "self", ")", ":", "for", "model", "in", "self", ".", "models", ":", "try", ":", "torch", ".", "cuda", ".", "empty_cache", "(", ")", "except", "Exception", ":", "pass", "self", ".", "_print_progress", "(", "f'Running self-chat for {model}'", ")", "outfile", "=", "self", ".", "_get_log_path", "(", "model", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "outfile", ")", ":", "if", "'model'", "in", "self", ".", "model_config", "[", "model", "]", ":", "config", "=", "self", ".", "_get_selfchat_config", "(", "model", ")", "with", "capture_output", "(", ")", ":", "parser", "=", "self_chat_setup_args", "(", ")", "parser", ".", "set_params", "(", "*", "*", "config", ")", "opt", "=", "parser", ".", "parse_args", "(", "args", "=", "[", "]", ")", "self_chat", "(", "opt", ")", "elif", "'task'", "in", "self", ".", "model_config", "[", "model", "]", ":", "self", ".", "_convert_task_to_conversations", "(", "model", ")", "else", ":", "raise", "RuntimeError", "(", "f'Path must exist if log_path specified for {model}'", ")", "if", "os", ".", "path", ".", "exists", "(", "outfile", ")", ":", "self", ".", "_print_progress", "(", "f'Chats saved to {outfile} for {model}'", ")", "self", ".", "_print_progress", "(", "f'Chats already exist in {outfile}, moving on...'", ")", "self", ".", "chat_files", "[", "model", "]", "=", "outfile" ]
[ 426, 4 ]
[ 462, 44 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor.run_acute_eval
(self)
Run ACUTE Eval.
Run ACUTE Eval.
def run_acute_eval(self): """ Run ACUTE Eval. """ self.set_up_acute_eval() db, cfg = load_db_and_process_config(self.args) print(f'*** RUN ID: {cfg.mephisto.task.task_name} ***') operator = Operator(db) operator.validate_and_run_config(run_config=cfg.mephisto, shared_state=None) operator.wait_for_runs_then_shutdown( skip_input=True, log_rate=cfg.monitoring_log_rate )
[ "def", "run_acute_eval", "(", "self", ")", ":", "self", ".", "set_up_acute_eval", "(", ")", "db", ",", "cfg", "=", "load_db_and_process_config", "(", "self", ".", "args", ")", "print", "(", "f'*** RUN ID: {cfg.mephisto.task.task_name} ***'", ")", "operator", "=", "Operator", "(", "db", ")", "operator", ".", "validate_and_run_config", "(", "run_config", "=", "cfg", ".", "mephisto", ",", "shared_state", "=", "None", ")", "operator", ".", "wait_for_runs_then_shutdown", "(", "skip_input", "=", "True", ",", "log_rate", "=", "cfg", ".", "monitoring_log_rate", ")" ]
[ 464, 4 ]
[ 475, 9 ]
python
en
['en', 'error', 'th']
False
FastAcuteExecutor.analyze_results
(self, args: Optional[str] = None)
Analyze results of ACUTE Eval run, using the optional input args. Save results to appropriate filepath.
Analyze results of ACUTE Eval run, using the optional input args.
def analyze_results(self, args: Optional[str] = None): """ Analyze results of ACUTE Eval run, using the optional input args. Save results to appropriate filepath. """ self._print_progress(f'Analyzing Results for run id {self.run_id}') parser = analysis_setup_args() if args is not None: arg_string = args.split() else: arg_string = [] opt = parser.parse_args(arg_string) today = datetime.date.today().isoformat() self.results_path = get_hashed_combo_path( root_dir=self.fast_acute_args.root_dir, subdir=f'acute_results/{today}/', task=self.task, combos=self.combos, ) opt.update( { 'model_strings': ','.join(self.models), 'run_ids': self.run_id, 'root_dir': self.fast_acute_args.root_dir, 'outdir': self.results_path, 'task': self.task, } ) analyzer = AcuteAnalyzer(opt) self.results = analyzer.get_matchup_totals_with_significance() analyzer.save_results() self._print_progress(f'ACUTE Results: {self.results}') self._print_progress(f'ACUTE results saved to {self.results_path}')
[ "def", "analyze_results", "(", "self", ",", "args", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "self", ".", "_print_progress", "(", "f'Analyzing Results for run id {self.run_id}'", ")", "parser", "=", "analysis_setup_args", "(", ")", "if", "args", "is", "not", "None", ":", "arg_string", "=", "args", ".", "split", "(", ")", "else", ":", "arg_string", "=", "[", "]", "opt", "=", "parser", ".", "parse_args", "(", "arg_string", ")", "today", "=", "datetime", ".", "date", ".", "today", "(", ")", ".", "isoformat", "(", ")", "self", ".", "results_path", "=", "get_hashed_combo_path", "(", "root_dir", "=", "self", ".", "fast_acute_args", ".", "root_dir", ",", "subdir", "=", "f'acute_results/{today}/'", ",", "task", "=", "self", ".", "task", ",", "combos", "=", "self", ".", "combos", ",", ")", "opt", ".", "update", "(", "{", "'model_strings'", ":", "','", ".", "join", "(", "self", ".", "models", ")", ",", "'run_ids'", ":", "self", ".", "run_id", ",", "'root_dir'", ":", "self", ".", "fast_acute_args", ".", "root_dir", ",", "'outdir'", ":", "self", ".", "results_path", ",", "'task'", ":", "self", ".", "task", ",", "}", ")", "analyzer", "=", "AcuteAnalyzer", "(", "opt", ")", "self", ".", "results", "=", "analyzer", ".", "get_matchup_totals_with_significance", "(", ")", "analyzer", ".", "save_results", "(", ")", "self", ".", "_print_progress", "(", "f'ACUTE Results: {self.results}'", ")", "self", ".", "_print_progress", "(", "f'ACUTE results saved to {self.results_path}'", ")" ]
[ 501, 4 ]
[ 536, 75 ]
python
en
['en', 'error', 'th']
False
Title.font
(self)
Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.treemap.marker.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- plotly.graph_objs.treemap.marker.colorbar.title.Font
Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.treemap.marker.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size
def font(self): """ Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.treemap.marker.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- plotly.graph_objs.treemap.marker.colorbar.title.Font """ return self["font"]
[ "def", "font", "(", "self", ")", ":", "return", "self", "[", "\"font\"", "]" ]
[ 15, 4 ]
[ 53, 27 ]
python
en
['en', 'error', 'th']
False
Title.side
(self)
Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any
Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom']
def side(self): """ Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any """ return self["side"]
[ "def", "side", "(", "self", ")", ":", "return", "self", "[", "\"side\"", "]" ]
[ 62, 4 ]
[ 76, 27 ]
python
en
['en', 'error', 'th']
False
Title.text
(self)
Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string
def text(self): """ Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"]
[ "def", "text", "(", "self", ")", ":", "return", "self", "[", "\"text\"", "]" ]
[ 85, 4 ]
[ 99, 27 ]
python
en
['en', 'error', 'th']
False
Title.__init__
(self, arg=None, font=None, side=None, text=None, **kwargs)
Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.treemap.marker .colorbar.Title` font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. Returns ------- Title
Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.treemap.marker .colorbar.Title` font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated.
def __init__(self, arg=None, font=None, side=None, text=None, **kwargs): """ Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.treemap.marker .colorbar.Title` font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. Returns ------- Title """ super(Title, self).__init__("title") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.treemap.marker.colorbar.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.treemap.marker.colorbar.Title`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("font", None) _v = font if font is not None else _v if _v is not None: self["font"] = _v _v = arg.pop("side", None) _v = side if side is not None else _v if _v is not None: self["side"] = _v _v = arg.pop("text", None) _v = text if text is not None else _v if _v is not None: self["text"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "font", "=", "None", ",", "side", "=", "None", ",", "text", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Title", ",", "self", ")", ".", "__init__", "(", "\"title\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.treemap.marker.colorbar.Title \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.treemap.marker.colorbar.Title`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"font\"", ",", "None", ")", "_v", "=", "font", "if", "font", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"font\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"side\"", ",", "None", ")", "_v", "=", "side", "if", "side", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"side\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"text\"", ",", "None", ")", "_v", "=", "text", "if", "text", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"text\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 126, 4 ]
[ 203, 34 ]
python
en
['en', 'error', 'th']
False
Title.font
(self)
Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.choropleth.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- plotly.graph_objs.choropleth.colorbar.title.Font
Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.choropleth.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size
def font(self): """ Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.choropleth.colorbar.title.Font` - A dict of string/value properties that will be passed to the Font constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- plotly.graph_objs.choropleth.colorbar.title.Font """ return self["font"]
[ "def", "font", "(", "self", ")", ":", "return", "self", "[", "\"font\"", "]" ]
[ 15, 4 ]
[ 53, 27 ]
python
en
['en', 'error', 'th']
False
Title.side
(self)
Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any
Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom']
def side(self): """ Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any """ return self["side"]
[ "def", "side", "(", "self", ")", ":", "return", "self", "[", "\"side\"", "]" ]
[ 62, 4 ]
[ 76, 27 ]
python
en
['en', 'error', 'th']
False
Title.text
(self)
Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str
Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string
def text(self): """ Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"]
[ "def", "text", "(", "self", ")", ":", "return", "self", "[", "\"text\"", "]" ]
[ 85, 4 ]
[ 99, 27 ]
python
en
['en', 'error', 'th']
False
Title.__init__
(self, arg=None, font=None, side=None, text=None, **kwargs)
Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.choropleth.colorbar.Title` font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. Returns ------- Title
Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.choropleth.colorbar.Title` font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated.
def __init__(self, arg=None, font=None, side=None, text=None, **kwargs): """ Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.choropleth.colorbar.Title` font Sets this color bar's title font. Note that the title's font used to be set by the now deprecated `titlefont` attribute. side Determines the location of color bar's title with respect to the color bar. Note that the title's location used to be set by the now deprecated `titleside` attribute. text Sets the title of the color bar. Note that before the existence of `title.text`, the title's contents used to be defined as the `title` attribute itself. This behavior has been deprecated. Returns ------- Title """ super(Title, self).__init__("title") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.choropleth.colorbar.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.choropleth.colorbar.Title`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("font", None) _v = font if font is not None else _v if _v is not None: self["font"] = _v _v = arg.pop("side", None) _v = side if side is not None else _v if _v is not None: self["side"] = _v _v = arg.pop("text", None) _v = text if text is not None else _v if _v is not None: self["text"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "font", "=", "None", ",", "side", "=", "None", ",", "text", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Title", ",", "self", ")", ".", "__init__", "(", "\"title\"", ")", "if", "\"_parent\"", "in", "kwargs", ":", "self", ".", "_parent", "=", "kwargs", "[", "\"_parent\"", "]", "return", "# Validate arg", "# ------------", "if", "arg", "is", "None", ":", "arg", "=", "{", "}", "elif", "isinstance", "(", "arg", ",", "self", ".", "__class__", ")", ":", "arg", "=", "arg", ".", "to_plotly_json", "(", ")", "elif", "isinstance", "(", "arg", ",", "dict", ")", ":", "arg", "=", "_copy", ".", "copy", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"\\\nThe first argument to the plotly.graph_objs.choropleth.colorbar.Title \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.choropleth.colorbar.Title`\"\"\"", ")", "# Handle skip_invalid", "# -------------------", "self", ".", "_skip_invalid", "=", "kwargs", ".", "pop", "(", "\"skip_invalid\"", ",", "False", ")", "self", ".", "_validate", "=", "kwargs", ".", "pop", "(", "\"_validate\"", ",", "True", ")", "# Populate data dict with properties", "# ----------------------------------", "_v", "=", "arg", ".", "pop", "(", "\"font\"", ",", "None", ")", "_v", "=", "font", "if", "font", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"font\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"side\"", ",", "None", ")", "_v", "=", "side", "if", "side", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"side\"", "]", "=", "_v", "_v", "=", "arg", ".", "pop", "(", "\"text\"", ",", "None", ")", "_v", "=", "text", "if", "text", "is", "not", "None", "else", "_v", "if", "_v", "is", "not", "None", ":", "self", "[", "\"text\"", "]", "=", "_v", "# Process unknown kwargs", "# ----------------------", "self", ".", "_process_kwargs", "(", "*", "*", "dict", "(", "arg", ",", "*", "*", "kwargs", ")", ")", "# Reset skip_invalid", "# ------------------", "self", ".", "_skip_invalid", "=", "False" ]
[ 126, 4 ]
[ 203, 34 ]
python
en
['en', 'error', 'th']
False
SelfFeedingAgent.add_cmdline_args
( cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None )
Add command-line arguments specifically for this agent.
Add command-line arguments specifically for this agent.
def add_cmdline_args( cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None ) -> ParlaiParser: """ Add command-line arguments specifically for this agent. """ super().add_cmdline_args(parser, partial_opt=partial_opt) SelfFeedingModel.add_cmdline_args(parser, partial_opt=partial_opt) agent = parser.add_argument_group('Self-feeding Agent') agent.add_argument( '--request-rating', type='bool', default=False, help="If True, ocassionally request ratings", ) agent.add_argument( '--rating-frequency', type=float, default=0.01, help="The fraction of the time that a rating will be " "randomly requested, regardless of classifier confidence", ) agent.add_argument( '--rating-gap', type=float, default=0.05, help="A positivity rating must be within this amount of " "the rating-threshold to trigger the confidence-based " "rating request", ) agent.add_argument( '--request-feedback', type='bool', default=False, help="If True, recognize mistakes and request feedback", ) agent.add_argument( '--rating-threshold', type=float, default=0.5, help="Treat feedback below this threshold as negative", ) agent.add_argument( '--display-sat-estimate', type='bool', default=False, help="If True, print estimated satisfaction after each response", ) agent.add_argument( '--target-class', type=int, default=0, help="The label (in [0,1]) to treat as the target rarer " "class when calculating tp/fp/tn/fn", ) agent.add_argument( '--freeze-base', type='bool', default=False, help="If True, freeze all but the satisfaction linear layer", ) agent.add_argument( '--partial-load', type='bool', default=False, help="If True, allow a model to be partially loaded (i.e., " "a model need not be a perfect match to be loaded", ) agent.add_argument( '-subtasks', '--subtasks', type=str, help="A comma-separated list of active subtasks", ) agent.add_argument( '--dia-weight', type=float, default=1.0, help="The dialog task loss is multiplied by this", ) agent.add_argument( '--fee-weight', type=float, default=1.0, help="The feedback task loss is multiplied by this", ) agent.add_argument( '--sat-weight', type=float, default=1.0, help="The satisfaction task loss is multiplied by this", ) agent.add_argument( '--prev-response-negatives', type='bool', default=False, help="If True, during training add the previous agent response as a " "negative candidate for the current response (as a way to " "organically teach the model to not repeat itself). This option is " "ignored when candidate set is 'fixed' or 'vocab', as these already " "include all candidates", ) agent.add_argument( '--prev-response-filter', type='bool', default=False, help="If True and --interactive=True, do not allow the model to output its " "previous response. This is a hackier solution than using " "--prev-response-negatives, but MUCH faster/simpler", ) agent.add_argument( '--interactive', type='bool', default=False, help="Mark as true if you are in a setting where you are only doing " "evaluation, and always with the same fixed candidate set.", ) agent.add_argument( '--add-double-person-tokens', type='bool', default=False, help="For backwards compatibility with old models only. For new " "models, this should always be False.", ) agent.set_defaults(person_tokens=False) # add these in a special way variants = parser.add_argument_group('Self-feeding Variants') variants.add_argument( '-rgx', '--regex', type='bool', default=False, help="If True, classify satisfaction using regexes instead " "of model", ) variants.add_argument( '-up', '--uncertainty-predictor', type='bool', default=False, help="If True, classify satisfaction using uncertainty of " "dialog models predictions instead of classifer" "model", ) variants.add_argument( '-ut', '--uncertainty-threshold', type=float, default=0.5, help="If model confidence is smaller than this number and" " --uncertainty-predictor=True, classify as bot mistake", ) variants.add_argument( '-us', '--uncertainty-style', type=str, default='gap', choices=['gap', 'mag'], help="Whether the uncertainty threshold measures the " "magnitude of the top confidence, or the gap between the " "two most confident answers", ) return agent
[ "def", "add_cmdline_args", "(", "cls", ",", "parser", ":", "ParlaiParser", ",", "partial_opt", ":", "Optional", "[", "Opt", "]", "=", "None", ")", "->", "ParlaiParser", ":", "super", "(", ")", ".", "add_cmdline_args", "(", "parser", ",", "partial_opt", "=", "partial_opt", ")", "SelfFeedingModel", ".", "add_cmdline_args", "(", "parser", ",", "partial_opt", "=", "partial_opt", ")", "agent", "=", "parser", ".", "add_argument_group", "(", "'Self-feeding Agent'", ")", "agent", ".", "add_argument", "(", "'--request-rating'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"If True, ocassionally request ratings\"", ",", ")", "agent", ".", "add_argument", "(", "'--rating-frequency'", ",", "type", "=", "float", ",", "default", "=", "0.01", ",", "help", "=", "\"The fraction of the time that a rating will be \"", "\"randomly requested, regardless of classifier confidence\"", ",", ")", "agent", ".", "add_argument", "(", "'--rating-gap'", ",", "type", "=", "float", ",", "default", "=", "0.05", ",", "help", "=", "\"A positivity rating must be within this amount of \"", "\"the rating-threshold to trigger the confidence-based \"", "\"rating request\"", ",", ")", "agent", ".", "add_argument", "(", "'--request-feedback'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"If True, recognize mistakes and request feedback\"", ",", ")", "agent", ".", "add_argument", "(", "'--rating-threshold'", ",", "type", "=", "float", ",", "default", "=", "0.5", ",", "help", "=", "\"Treat feedback below this threshold as negative\"", ",", ")", "agent", ".", "add_argument", "(", "'--display-sat-estimate'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"If True, print estimated satisfaction after each response\"", ",", ")", "agent", ".", "add_argument", "(", "'--target-class'", ",", "type", "=", "int", ",", "default", "=", "0", ",", "help", "=", "\"The label (in [0,1]) to treat as the target rarer \"", "\"class when calculating tp/fp/tn/fn\"", ",", ")", "agent", ".", "add_argument", "(", "'--freeze-base'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"If True, freeze all but the satisfaction linear layer\"", ",", ")", "agent", ".", "add_argument", "(", "'--partial-load'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"If True, allow a model to be partially loaded (i.e., \"", "\"a model need not be a perfect match to be loaded\"", ",", ")", "agent", ".", "add_argument", "(", "'-subtasks'", ",", "'--subtasks'", ",", "type", "=", "str", ",", "help", "=", "\"A comma-separated list of active subtasks\"", ",", ")", "agent", ".", "add_argument", "(", "'--dia-weight'", ",", "type", "=", "float", ",", "default", "=", "1.0", ",", "help", "=", "\"The dialog task loss is multiplied by this\"", ",", ")", "agent", ".", "add_argument", "(", "'--fee-weight'", ",", "type", "=", "float", ",", "default", "=", "1.0", ",", "help", "=", "\"The feedback task loss is multiplied by this\"", ",", ")", "agent", ".", "add_argument", "(", "'--sat-weight'", ",", "type", "=", "float", ",", "default", "=", "1.0", ",", "help", "=", "\"The satisfaction task loss is multiplied by this\"", ",", ")", "agent", ".", "add_argument", "(", "'--prev-response-negatives'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"If True, during training add the previous agent response as a \"", "\"negative candidate for the current response (as a way to \"", "\"organically teach the model to not repeat itself). This option is \"", "\"ignored when candidate set is 'fixed' or 'vocab', as these already \"", "\"include all candidates\"", ",", ")", "agent", ".", "add_argument", "(", "'--prev-response-filter'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"If True and --interactive=True, do not allow the model to output its \"", "\"previous response. This is a hackier solution than using \"", "\"--prev-response-negatives, but MUCH faster/simpler\"", ",", ")", "agent", ".", "add_argument", "(", "'--interactive'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"Mark as true if you are in a setting where you are only doing \"", "\"evaluation, and always with the same fixed candidate set.\"", ",", ")", "agent", ".", "add_argument", "(", "'--add-double-person-tokens'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"For backwards compatibility with old models only. For new \"", "\"models, this should always be False.\"", ",", ")", "agent", ".", "set_defaults", "(", "person_tokens", "=", "False", ")", "# add these in a special way", "variants", "=", "parser", ".", "add_argument_group", "(", "'Self-feeding Variants'", ")", "variants", ".", "add_argument", "(", "'-rgx'", ",", "'--regex'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"If True, classify satisfaction using regexes instead \"", "\"of model\"", ",", ")", "variants", ".", "add_argument", "(", "'-up'", ",", "'--uncertainty-predictor'", ",", "type", "=", "'bool'", ",", "default", "=", "False", ",", "help", "=", "\"If True, classify satisfaction using uncertainty of \"", "\"dialog models predictions instead of classifer\"", "\"model\"", ",", ")", "variants", ".", "add_argument", "(", "'-ut'", ",", "'--uncertainty-threshold'", ",", "type", "=", "float", ",", "default", "=", "0.5", ",", "help", "=", "\"If model confidence is smaller than this number and\"", "\" --uncertainty-predictor=True, classify as bot mistake\"", ",", ")", "variants", ".", "add_argument", "(", "'-us'", ",", "'--uncertainty-style'", ",", "type", "=", "str", ",", "default", "=", "'gap'", ",", "choices", "=", "[", "'gap'", ",", "'mag'", "]", ",", "help", "=", "\"Whether the uncertainty threshold measures the \"", "\"magnitude of the top confidence, or the gap between the \"", "\"two most confident answers\"", ",", ")", "return", "agent" ]
[ 60, 4 ]
[ 229, 20 ]
python
en
['en', 'error', 'th']
False
SelfFeedingAgent.upgrade_opt
(cls, opt_on_disk)
Upgrade opts from older model files.
Upgrade opts from older model files.
def upgrade_opt(cls, opt_on_disk): """ Upgrade opts from older model files. """ super(SelfFeedingAgent, cls).upgrade_opt(opt_on_disk) # 2019-06-25: previous versions of the model did not add a CLS token # to the beginning of text_vec. if 'add_double_person_tokens' not in opt_on_disk: warn_once('Old model: overriding `add_double_person_tokens` to True.') opt_on_disk['add_double_person_tokens'] = True return opt_on_disk
[ "def", "upgrade_opt", "(", "cls", ",", "opt_on_disk", ")", ":", "super", "(", "SelfFeedingAgent", ",", "cls", ")", ".", "upgrade_opt", "(", "opt_on_disk", ")", "# 2019-06-25: previous versions of the model did not add a CLS token", "# to the beginning of text_vec.", "if", "'add_double_person_tokens'", "not", "in", "opt_on_disk", ":", "warn_once", "(", "'Old model: overriding `add_double_person_tokens` to True.'", ")", "opt_on_disk", "[", "'add_double_person_tokens'", "]", "=", "True", "return", "opt_on_disk" ]
[ 289, 4 ]
[ 301, 26 ]
python
en
['en', 'error', 'th']
False
SelfFeedingAgent.observe
(self, observation)
Add to history, concatenate history-size utterances, and add person tokens.
Add to history, concatenate history-size utterances, and add person tokens.
def observe(self, observation): """ Add to history, concatenate history-size utterances, and add person tokens. """ # If their response is a response to a rating request, no work required if self.status == RATING_REQUESTED: self.last_rating = observation['text'] return super().observe(observation)
[ "def", "observe", "(", "self", ",", "observation", ")", ":", "# If their response is a response to a rating request, no work required", "if", "self", ".", "status", "==", "RATING_REQUESTED", ":", "self", ".", "last_rating", "=", "observation", "[", "'text'", "]", "return", "super", "(", ")", ".", "observe", "(", "observation", ")" ]
[ 368, 4 ]
[ 377, 43 ]
python
en
['en', 'error', 'th']
False
SelfFeedingAgent._set_text_vec
(self, obs, history, truncate)
Set the 'text_vec' field in the observation.
Set the 'text_vec' field in the observation.
def _set_text_vec(self, obs, history, truncate): """ Set the 'text_vec' field in the observation. """ if 'text' not in obs: return obs if 'text_vec' not in obs: obs['text_vec'] = self.history.parse(obs["text"]) # check truncation if 'text_vec' in obs: if self.opt.get('add_double_person_tokens'): # backwards compatibility madness, handle the fact that __p1__ was # accidentally inserted into the training data of some old models on # disk obs['text_vec'].insert(0, self.dict['__p1__']) obs.force_set( 'text_vec', torch.LongTensor(self._check_truncate(obs['text_vec'], truncate, True)), ) return obs
[ "def", "_set_text_vec", "(", "self", ",", "obs", ",", "history", ",", "truncate", ")", ":", "if", "'text'", "not", "in", "obs", ":", "return", "obs", "if", "'text_vec'", "not", "in", "obs", ":", "obs", "[", "'text_vec'", "]", "=", "self", ".", "history", ".", "parse", "(", "obs", "[", "\"text\"", "]", ")", "# check truncation", "if", "'text_vec'", "in", "obs", ":", "if", "self", ".", "opt", ".", "get", "(", "'add_double_person_tokens'", ")", ":", "# backwards compatibility madness, handle the fact that __p1__ was", "# accidentally inserted into the training data of some old models on", "# disk", "obs", "[", "'text_vec'", "]", ".", "insert", "(", "0", ",", "self", ".", "dict", "[", "'__p1__'", "]", ")", "obs", ".", "force_set", "(", "'text_vec'", ",", "torch", ".", "LongTensor", "(", "self", ".", "_check_truncate", "(", "obs", "[", "'text_vec'", "]", ",", "truncate", ",", "True", ")", ")", ",", ")", "return", "obs" ]
[ 390, 4 ]
[ 412, 18 ]
python
en
['en', 'error', 'th']
False