Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|> deadline=120.0,
),
default_timeout=120.0,
client_info=client_info,
),
self.bind_device_to_gateway: gapic_v1.method.wrap_method(
self.bind_device_to_gateway,
defaul... | [device_manager.CreateDeviceRegistryRequest], |
Given the following code snippet before the placeholder: <|code_start|> ),
default_timeout=120.0,
client_info=client_info,
),
self.bind_device_to_gateway: gapic_v1.method.wrap_method(
self.bind_device_to_gateway,
defa... | Union[resources.DeviceRegistry, Awaitable[resources.DeviceRegistry]], |
Here is a snippet: <|code_start|> "ListDeviceConfigVersionsRequest",
"ListDeviceConfigVersionsResponse",
"ListDeviceStatesRequest",
"ListDeviceStatesResponse",
"SendCommandToDeviceRequest",
"SendCommandToDeviceResponse",
"BindDeviceToGatewayRequest",
"BindD... | proto.MESSAGE, number=2, message=resources.DeviceRegistry, |
Next line prediction: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and... | method: Callable[..., device_manager.ListDeviceRegistriesResponse], |
Using the snippet: <|code_start|> metadata: Sequence[Tuple[str, str]] = ()
):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.iot_v1.types.ListDeviceRegi... | def __iter__(self) -> Iterator[resources.DeviceRegistry]: |
Predict the next line after this snippet: <|code_start|> ``record.myfield = val``). This is opposite to ``__get__()`` which
needs to handle both class and instance access.
"""
raise AttributeError()
def __set_name__(self, owner, name):
"""Inject the class attribute name into ... | return dict_lookup(instance, self.key) |
Continue the code snippet: <|code_start|> """Inject the class attribute name into the field.
This ensures that a field has access to the attribute name used on the
class. In the following example, the attribute name ``schema`` would be
set in the ``ConstantField`` object instance.
... | keys = parse_lookup_key(self.key) |
Continue the code snippet: <|code_start|> return fields
class SystemFieldContext:
"""Base class for a system field context.
A system field context is created once you access a field's attribute on
a class. As the system field may be defined on a super class, this context
allows us to know from whi... | class SystemField(ExtensionMixin): |
Predict the next line after this snippet: <|code_start|> else:
if not isinstance(parent[k], dict):
raise KeyError(
"Expected a dict at subkey '{}'. "
"Found '{}'.".format(
k... | class SystemFieldsExt(RecordExtension): |
Continue the code snippet: <|code_start|>
def pre_create(self, *args, **kwargs):
"""Called after a record is created."""
self._run('pre_create', *args, **kwargs)
def post_create(self, *args, **kwargs):
"""Called after a record is created."""
self._run('post_create', *args, **kwa... | class SystemFieldsMeta(RecordMeta): |
Given the following code snippet before the placeholder: <|code_start|># Copyright (C) 2020 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Relations dumper.
Dumper used to dump/load relations to/from an ElasticSe... | dict_lookup(record, rel_field.key) |
Using the snippet: <|code_start|>#
# This file is part of Invenio.
# Copyright (C) 2020 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Relations dumper.
Dumper used to dump/load relations to/from an ElasticSearch... | dict_set( |
Predict the next line for this snippet: <|code_start|> dump_type):
"""Helper method to load model fields from dump.
:param record_cls: The record class being used for loading.
:param model_field_name: The name of the SQLAlchemy model field on the
record's mo... | if isinstance(systemfield, ModelField): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2020 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Elasticsearch source dumper.
Dumper used to dump/l... | class ElasticsearchDumper(Dumper): |
Given snippet: <|code_start|> def _validate(self, format_checker=None, validator=None, use_model=False):
"""Implementation of the JSONSchema validation."""
# Use the encoder to transform Python dictionary into JSON document
# prior to validation unless we explicitly ask to use the already
... | def clear_none(self, key=None): |
Here is a snippet: <|code_start|> if use_model:
json = self.model.json
else:
json = self.model_cls.encode(dict(self))
if '$schema' in self and self['$schema'] is not None:
# Validate (an error will raise an exception)
_records_state.validate(
... | clear_none(dict_lookup(self, key) if key else self) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2020 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Record API."""
_records_state = LocalPr... | dumper = Dumper() |
Continue the code snippet: <|code_start|> data = apply_patch(dict(self), patch)
return self.__class__(data, model=self.model)
def commit(self, format_checker=None, validator=None, **kwargs):
r"""Store changes of the current record instance in the database.
#. Send a signal :data:`in... | raise MissingModelError() |
Continue the code snippet: <|code_start|> #. Delete or soft-delete the current record.
#. Send a signal :data:`invenio_records.signals.after_record_delete`
with the current deleted record as parameter.
:param force: if ``True``, completely deletes the current record from
... | after_record_delete.send( |
Next line prediction: <|code_start|> format_checker = kwargs.pop('format_checker', None)
validator = kwargs.pop('validator', None)
# Create the record and the model
record = cls(
data,
model=cls.model_cls(id=id_, data=data),
... | after_record_insert.send( |
Based on the snippet: <|code_start|> :returns: The :class:`Record` instance corresponding to the revision id
"""
if self.model is None:
raise MissingModelError()
revision = self.revisions[revision_id]
with db.session.begin_nested():
if self.send_signals:
... | after_record_revert.send( |
Next line prediction: <|code_start|> :func:`~invenio_records.api.RecordBase.validate` for more details.
:returns: The :class:`Record` instance.
"""
if self.model is None or self.model.is_deleted:
raise MissingModelError()
with db.session.begin_nested():
... | after_record_update.send( |
Given the code snippet: <|code_start|> )
return self
def delete(self, force=False):
"""Delete a record.
If `force` is ``False``, the record is soft-deleted: record data will
be deleted but the record identifier and the history of the record will
be kept. This en... | before_record_delete.send( |
Based on the snippet: <|code_start|>
:Keyword Arguments:
* **format_checker** --
An instance of the class :class:`jsonschema.FormatChecker`, which
contains validation rules for formats. See
:func:`~invenio_records.api.RecordBase.validate` for more details.
... | before_record_insert.send( |
Predict the next line after this snippet: <|code_start|> if self.model is None:
raise MissingModelError()
self.model.is_deleted = False
return self
def revert(self, revision_id):
"""Revert the record to a specific revision.
#. Send a signal :data:`invenio_recor... | before_record_revert.send( |
Given the code snippet: <|code_start|> r"""Store changes of the current record instance in the database.
#. Send a signal :data:`invenio_records.signals.before_record_update`
with the current record to be committed as parameter.
#. Validate the current record data.
#. Commit... | before_record_update.send( |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2020 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test of dictiona... | clear_none(d) |
Next line prediction: <|code_start|> 'c': None
},
'd': ['1', None, []],
'e': [{'a': None, 'b': []}],
}
clear_none(d)
# Modifications are done in place, so gotta test after the function call.
assert d == {'d': ['1']}
d = {
'a': None,
'b': [
... | assert dict_lookup(d, 'a') == d['a'] |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2020-2021 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Relations system field."""
class RelationResul... | return dict_lookup(self.record, self.value_key) |
Predict the next line after this snippet: <|code_start|> return self._dereference_one(data, attrs or self.attrs)
except KeyError:
return None
def clean(self, attrs=None):
"""Clean the dereferenced attributes inside the record."""
try:
data = self._lookup_d... | dict_set(new_obj, a, dict_lookup(obj, a)) |
Continue the code snippet: <|code_start|> """Relation access result."""
def __init__(self, field, record):
"""Initialize the relation result."""
self.field = field
self.record = record
def _lookup_id(self):
return dict_lookup(self.record, self.value_key)
def _lookup_dat... | raise InvalidCheckValue(f'Invalid key {key}.') |
Here is a snippet: <|code_start|> for key, value in value_to_check.items():
if key not in object:
raise InvalidCheckValue(f'Invalid key {key}.')
if isinstance(value, dict):
self._value_check(value, object[key])
else:
if not isins... | raise InvalidRelationValue(f'Invalid value {val}.') |
Based on the snippet: <|code_start|>translation_x_loss = []
translation_y_loss = []
scale_loss = []
valid_loss = []
valid_translation_x_loss = []
valid_translation_y_loss = []
valid_scale_loss = []
learning_rate = [0.0001, 0.001, 0.01]
# let's train the model using SGD + momentum (how original).
sgd = SGD(lr=learning_... | printProgress(i, loader.n_iter_train-1, prefix='Progress:', suffix='batch error: %0.5f, ETA: %0.2f sec.'%(np.array(loss_list).mean(), eta), barLength=50) |
Predict the next line for this snippet: <|code_start|>
nb_epoch = 200
early_stopping = True
early_stopping_count = 0
early_stopping_wait = 3
train_loss = []
valid_loss = []
learning_rate = [0.0001, 0.001, 0.01]
# let's train the model using SGD + momentum (how original).
sgd = SGD(lr=learning_rate[-1], decay=1e-6, mom... | printProgress(i, loader.n_iter_train-1, prefix='Progress:', suffix='batch error: %0.5f, ETA: %0.2f sec.'%(np.array(loss_list).mean(), eta), barLength=50) |
Here is a snippet: <|code_start|> string = configFile.read()
j = json.loads(string)
seq = Sequence(**j)
seq.path = os.path.join(os.path.abspath(seq.path), '')
return seq
def save_seq_result(RESULT_SRC, result):
tracker = result.tracker
seqName = result.seqName
evalType = result.evalType... | return [Result(**j) for j in jsonList] |
Given snippet: <|code_start|>
# model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
# loss_weights=[1., 1., 1.])
# load validation data from the h5py file (heavy lifting here)
x_valid, translation_x_class_valid, translation_y_class_valid, y_scale_class_valid =\
loader.get_valid_class... | printProgress(i, loader.n_iter_train-1, prefix='Progress:', |
Here is a snippet: <|code_start|># the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PAR... | routeSelected = QtCore.pyqtSignal(str) |
Given snippet: <|code_start|>
trainSelected = QtCore.pyqtSignal(int)
trainsUnselected = QtCore.pyqtSignal()
def selectionChanged(self, selected, deselected):
"""Called when the user changes the selection. Emits the
trainSelected signal"""
super().selectionChanged(selected, deselecte... | self.setRenderHint(QtGui.QPainter.Antialiasing, False) |
Next line prediction: <|code_start|>
def selectionChanged(self, selected, deselected):
"""Called when the user changes the selection. Emits the
trainSelected signal"""
super().selectionChanged(selected, deselected)
if selected.indexes():
index = selected.indexes()[0]
... | self.setBackgroundBrush(QtGui.QBrush(Qt.black)) |
Predict the next line after this snippet: <|code_start|> """
def __init__(self, parent):
"""Constructor for the TrainTypesEditorView class"""
super().__init__(parent)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
QtWidgets.Q... | self.setItemDelegateForColumn(1, delegates.PropertyValuesDelegate(self)) |
Here is a snippet: <|code_start|> """Editor Trains"""
class FormatException(Exception):
"""File format exception."""
def __init__(self, arg):
"""Constructor of the FormatException class."""
super().__init__(arg)
class MissingDependencyException(Exception):
"""Exception raised when a d... | class DurationProba(QtCore.QObject): |
Predict the next line after this snippet: <|code_start|> hlayout.addWidget(titleLabel)
hlayout.addWidget(titleText)
hlayout.addStretch()
descriptionLabel = QtWidgets.QLabel(self)
descriptionLabel.setText("<u>" +
self.tr("Description:") +
... | @QtCore.pyqtSlot(int) |
Predict the next line after this snippet: <|code_start|> descriptionLabel = QtWidgets.QLabel(self)
descriptionLabel.setText("<u>" +
self.tr("Description:") +
"</u>")
descriptionText = QtWidgets.QTextEdit(self)
descriptionTe... | if checkState == Qt.Checked: |
Continue the code snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 59... | if settings.debug: |
Given the following code snippet before the placeholder: <|code_start|> },
{
"__type__": "SignalState",
"aspectName": "UK_DANGER",
"conditions": {}
}
]
}
}
}"""
class SignalItem(abstract.... | self._berthOrigin = QtCore.QPointF() |
Given the code snippet: <|code_start|> if self._trainId is not None:
return self.simulation.trains[int(self._trainId)].serviceCode
else:
return ""
# ## Methods #########################################################
def getNextSignal(self):
"""Helper function t... | font = QtGui.QFont("Courier New") |
Here is a snippet: <|code_start|>
class SignalItem(abstract.TrackItem):
"""Logical item for signals.
- This class holds the logic of a signal defined by its
:class:`~ts2.scenery.signals.signalitem.SignalType`.
- A signal is the item from and to which routes are created.
"""
SIGNAL_GRAPHIC_IT... | sgi.setCursor(Qt.PointingHandCursor) |
Using the snippet: <|code_start|> "states": [
{
"__type__": "SignalState",
"aspectName": "UK_CLEAR",
"conditions": {
"NEXT_ROUTE_ACTIVE": [],
"TRAIN_NOT_PRESENT_ON_NEXT_ROUTE": [],
... | class SignalItem(abstract.TrackItem): |
Here is a snippet: <|code_start|>}"""
class SignalItem(abstract.TrackItem):
"""Logical item for signals.
- This class holds the logic of a signal defined by its
:class:`~ts2.scenery.signals.signalitem.SignalType`.
- A signal is the item from and to which routes are created.
"""
SIGNAL_GRAP... | sgi = helper.TrackGraphicsItem(self, SignalItem.SIGNAL_GRAPHIC_ITEM) |
Based on the snippet: <|code_start|> """Returns the current aspect of the signal."""
return self._activeAspect
activeAspect = property(_getActiveAspect)
@property
def trainServiceCode(self):
"""Returns the trainServiceCode of this signal. This is for display
only."""
... | elif isinstance(cur, enditem.EndItem): |
Predict the next line for this snippet: <|code_start|># 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
class ServiceInfoModel(QtCore.QAbstractTableModel):
"""Model for displaying a single service information in a view
"""
def __init__(self, simulation):
"""Constructor for the Serv... | def data(self, index, role=Qt.DisplayRole): |
Here is a snippet: <|code_start|>
def for_json(self):
"""Dumps this service line to JSON."""
return {
"__type__": "ServiceLine",
"placeCode": self.placeCode,
"scheduledArrivalTime": self.scheduledArrivalTimeStr,
"scheduledDepartureTime": self.scheduled... | if self.simulation.context == utils.Context.EDITOR_SERVICES: |
Given the code snippet: <|code_start|>\x1a\x7c\xdf\x07\x00\x28\x8a\x22\xc5\x12\x73\xcb\xaf\xa1\x54\x81\
\x5c\x2e\x27\x19\xb3\x6d\x1b\xe3\xf1\x38\x5d\x56\x47\xe4\xf3\xf9\
\xb3\x15\x78\x26\x22\xf2\x7d\x9f\x14\x45\xb9\xf8\x8f\x28\x63\x8c\
\x66\xb3\xd9\xc9\x0a\x70\x03\x55\x1e\xec\xf5\x7a\xa9\x77\x43\x51\
\xa3\xdd\x6e\x87\x... | QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, |
Given the code snippet: <|code_start|>
class TrackPropertiesModel(QtCore.QAbstractTableModel):
"""This class is a model for accessing TrackItem properties in the editor
"""
def __init__(self, trackItems):
"""Constructor for the TrackPropertiesModel class"""
super().__init__()
self.t... | def data(self, index, role=Qt.DisplayRole): |
Using the snippet: <|code_start|> return [(0, -5), (5, -5), (5, 0), (5, 5),
(0, 5), (-5, 5), (-5, 0), (-5, -5)]
class PointsItem(abstract.TrackItem):
"""A ``PointsItem`` is a three-way junction.
The three ends and called:
- common end
- normal end
- reverse end
.. code-block:... | self._commonEnd = QtCore.QPointF() |
Given the code snippet: <|code_start|>
.. code-block:: bash
____________ reverse
/
common ___________/______________normal
- Trains can go from common end to normal or reverse ends depending on the
state of the points.
- They cannot go f... | pgi.setCursor(Qt.PointingHandCursor) |
Given the code snippet: <|code_start|> reverseTiId = self.reverseItem.tiId
else:
reverseTiId = None
jsonData.update({
"x": self._center.x(),
"y": self._center.y(),
"xf": self._commonEnd.x(),
"yf": self._commonEnd.y(),
"xn... | if self.simulation.context == utils.Context.EDITOR_SCENERY: |
Next line prediction: <|code_start|> - common end
- normal end
- reverse end
.. code-block:: bash
____________ reverse
/
common ___________/______________normal
- Trains can go from common end to normal or reverse ends depending on the... | pgi = helper.TrackGraphicsItem(self) |
Given the code snippet: <|code_start|>
translate = QtWidgets.qApp.translate
def getEndNames():
"""
:return: a list of point end names TODO
"""
return [
translate("PointsItem", "N"),
translate("PointsItem", "NE"),
translate("PointsItem", "E"),
translate("PointsItem", "... | class PointsItem(abstract.TrackItem): |
Given the code snippet: <|code_start|> }
def addMessage(self, msgText, msgType=Message.SIMULATION_MSG):
"""Adds a message to the logger."""
row = len(self._messages) - 1
if msgType == Message.SIMULATION_MSG:
msgText = \
self.simulation.currentTime.toString... | return QtGui.QFont("Courier new") |
Given the following code snippet before the placeholder: <|code_start|> if self.simulation.context == utils.Context.GAME:
messages = self._messages
return {
"__type__": "MessageLogger",
"messages": messages
}
def addMessage(self, msgText, msgType=Message.S... | def data(self, index, role=Qt.DisplayRole): |
Continue the code snippet: <|code_start|> return self.msgText
def for_json(self):
"""Dumps this message to JSON."""
return {
"__type__": "Message",
"msgType": self.msgType,
"msgText": self.msgText
}
class MessageLogger(QtCore.QAbstractTableModel)... | if self.simulation.context == utils.Context.GAME: |
Given the code snippet: <|code_start|># This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is dist... | trainSelected = QtCore.pyqtSignal(str) |
Given the code snippet: <|code_start|>#
# Copyright (C) 2008-2015 by Nicolas Piganeau
# npi@m4x.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, o... | self.simulation = None |
Predict the next line after this snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along ... | setattr(self, attr, QtCore.QPointF(x, y)) |
Based on the snippet: <|code_start|> if ti is None or self.tiId != ti.tiId:
return True
else:
return False
def __updateGraphics(self):
for gi in self._gi.values():
gi.update()
def removeAllGraphicsItems(self):
"""Removes all the graphics items... | pen = QtGui.QPen() |
Given the following code snippet before the placeholder: <|code_start|> else:
return False
def __updateGraphics(self):
for gi in self._gi.values():
gi.update()
def removeAllGraphicsItems(self):
"""Removes all the graphics items associated with this TrackItem
... | pen.setJoinStyle(Qt.RoundJoin) |
Given the following code snippet before the placeholder: <|code_start|>#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detail... | if self.simulation.context == utils.Context.EDITOR_SCENERY: |
Using the snippet: <|code_start|> )
self.properties = self.getProperties()
self.multiProperties = self.getMultiProperties()
for gi in self._gi.values():
simulation.registerGraphicsItem(gi)
self.updateGraphics()
def updateData(self, msg):
if "activeRoute" i... | helper.TIProperty("tiTypeStr", |
Given the code snippet: <|code_start|>#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received... | serviceCode = index.model().data(index, Qt.EditRole) |
Using the snippet: <|code_start|> """
def __init__(self, parameters):
"""
:param dict paramaters:
"""
super().__init__(parameters)
self._realLength = BIG
egi = helper.TrackGraphicsItem(self)
egi.setPos(self.origin)
self._gi[0] = egi
def initial... | return QtCore.QPointF(-BIG, -BIG) |
Next line prediction: <|code_start|>
BIG = 1000000000
class EndItem(abstract.TrackItem):
"""End items are invisible items to which the free ends of other
trackitems must be connected to prevent the simulation from crashing.
End items are defined by:
- their titype which is “E”
- and their posi... | self._gi[0].setCursor(Qt.PointingHandCursor) |
Here is a snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple ... | egi = helper.TrackGraphicsItem(self) |
Using the snippet: <|code_start|>#
BIG = 1000000000
class EndItem(abstract.TrackItem):
"""End items are invisible items to which the free ends of other
trackitems must be connected to prevent the simulation from crashing.
End items are defined by:
- their titype which is “E”
- and their posit... | if self.simulation.context in utils.Context.EDITORS: |
Predict the next line after this snippet: <|code_start|> self.setValue("recent", ts2.utils.to_json(lst))
return lst
def getEditorRecent(self):
"""List of recent files
:rtype: lst of str's
"""
s = self.value("editorRecent")
if not s:
return []
... | if isinstance(window, QtWidgets.QDialog): |
Given the following code snippet before the placeholder: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# ... | def data(self, index, role=Qt.DisplayRole): |
Based on the snippet: <|code_start|>
def initialize(self, simulation):
"""Initializes the simulation variable once it is loaded."""
self.simulation = simulation
def for_json(self):
"""Dumps this trainType to JSON"""
return {
"__type__": "TrainType",
"code... | if self.simulation.context == utils.Context.EDITOR_TRAINTYPES: |
Given the code snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 59 Te... | align=Qt.AlignRight) |
Given snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, ... | headerLabel = widgets.HeaderLabel(text=self.tr("User Settings"), |
Given the code snippet: <|code_start|> self.txtServerDir.setEnabled(False)
grid.addWidget(self.txtServerDir, row, 1, 1, 1)
butt = QtWidgets.QToolButton()
butt.setText(self.tr("Default"))
grid.addWidget(butt, row, 2, 1, 1)
# Sims dir
row += 1
grid.addWidge... | if path.isfile(settings.serverLoc): |
Predict the next line for this snippet: <|code_start|># Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
class EditorSceneBackground(QtWidgets.QGraphicsRectItem):
"""The EditorSceneBackground is a graphics item set at the background of
the editor scene to hand... | clickPos = QtCore.QPointF(float(ox), float(oy)) |
Here is a snippet: <|code_start|> super().__init__(x, y, width, height)
self.setZValue(-100)
self.setAcceptDrops(True)
self.editor = editor
# pen = QtGui.QPen(Qt.cyan)
# self.setPen(pen)
def dragEnterEvent(self, event):
"""dragEnterEvent handler for the Editor... | event.setDropAction(Qt.CopyAction) |
Given the code snippet: <|code_start|>
translate = QtWidgets.qApp.translate
class C:
name = 0
file_name = 1
description = 2
file_path = 3
class NAV:
sims = 0
recent = 1
filesystem = 2
network = 3
class OpenDialog(QtWidgets.QDialog):
"""Open sim file dialog"""
<|code_end|>
,... | openFile = QtCore.pyqtSignal(str) |
Continue the code snippet: <|code_start|>
tbNetworkBarLayout.addWidget(QtWidgets.QLabel(self.tr("Host:")))
self.networkServer = QtWidgets.QLineEdit(self)
self.networkServer.setText("localhost")
tbNetworkBarLayout.addWidget(self.networkServer, 2)
tbNetworkBarLayout.addWidget(QtWid... | QtWidgets.qApp.setOverrideCursor(Qt.WaitCursor) |
Continue the code snippet: <|code_start|> labelLayout = QtWidgets.QHBoxLayout()
labelLayout.addStretch(1)
labelLayout.addWidget(networkLabel)
labelLayout.addStretch(1)
self.networkLayout.addLayout(labelLayout)
tbNetworkBarLayout = QtWidgets.QHBoxLayout()
self.netw... | if settings.debug: |
Predict the next line for this snippet: <|code_start|> networkLabel = QtWidgets.QLabel(self.tr("Connect to simulation server"))
networkLabel.setStyleSheet("font-size: 15px; font-weight: bold;")
labelLayout = QtWidgets.QHBoxLayout()
labelLayout.addStretch(1)
labelLayout.addWidget(n... | self.statusBar = widgets.StatusBar() |
Given snippet: <|code_start|># the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICU... | @QtCore.pyqtSlot(QtCore.QTime) |
Using the snippet: <|code_start|> """Constructor for the ClockWidget class."""
super().__init__(parent)
self.setFrameShape(QtWidgets.QFrame.NoFrame)
self.setFrameShadow(QtWidgets.QFrame.Plain)
self.setSegmentStyle(QtWidgets.QLCDNumber.Flat)
self.setNumDigits(8)
se... | self.slider = QtWidgets.QSlider(Qt.Horizontal, self) |
Predict the next line for this snippet: <|code_start|>#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You shou... | self._line = QtCore.QLineF() |
Using the snippet: <|code_start|> # Library item in editor
lx -= 15
rx += 15
ty -= 20
by += 20
self._boundingRect = QtCore.QRectF(lx, ty, rx - lx, by - ty)
@QtCore.pyqtSlot()
def updateGraphics(self):
"""Updates the TrackGraphicsItem ow... | path = QtGui.QPainterPath(self._boundingRect.topLeft()) |
Based on the snippet: <|code_start|> def __init__(self, parameters):
"""Constructor for the LineItem class"""
self._placeCode = ""
self._trackCode = ""
self._realLength = ""
super().__init__(parameters)
self.defaultZValue = 1
self._line = QtCore.QLineF()
... | self._gi[0].setCursor(Qt.PointingHandCursor) |
Using the snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple ... | gli = helper.TrackGraphicsItem(self) |
Given the code snippet: <|code_start|>
if __name__ == "__main__":
try:
config_path = sys.argv[1]
except:
config_path = 'config.json'
<|code_end|>
, generate the next line using the imports in this file:
import sys
from watashi import Watashi
and context (functions, classes, or occasionally co... | bot = Watashi(config_path) |
Based on the snippet: <|code_start|># Copyright 2017 Bo Shao. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | predictor = BotPredictor(sess, corpus_dir=corp_dir, knbase_dir=knbs_dir, |
Predict the next line after this snippet: <|code_start|> complexType += '</%s:complexType>\n'%prefix
complexType += '<%s:element name="%s" type="tns:%sParams"/>\n'%(prefix,name,name)
return complexType
class Array:
""" Create arrays of xml elements.
Here an example:
@webservices(_params=xmltypes.Ar... | type = complextypes.createPythonType2XMLType(self._type.__name__) |
Given the code snippet: <|code_start|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on ... | corp_dir = os.path.join(PROJECT_ROOT, 'Data', 'Corpus') |
Using the snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# li... | predictor = BotPredictor(sess, corpus_dir=corp_dir, knbase_dir=knbs_dir, |
Using the snippet: <|code_start|> types += '<xsd:schema targetNamespace="%s">\n'%self._namespace
namespace = 'xsd'
types_list = []
ltype = []
for wsdl_data in self._methods:
self._arguments = wsdl_data['args']
self._elementNameInput = wsdl_data['input'][0]
self._elementInput = wsdl_data['input'][1]
... | elif isinstance(self._elementInput,xmltypes.Array): |
Given the code snippet: <|code_start|> """
def __init__(self,nameservice=None,targetNamespace=None,methods=None,location=None):
self._nameservice = nameservice
self._namespace = targetNamespace
self._methods = methods
self._location = location
def createWsdl(self):
""" Method that allows create the wsdl ... | if inspect.isclass(self._elementInput) and issubclass(self._elementInput,complextypes.ComplexType): |
Based on the snippet: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ====================================... | self.hparams = HParams(corpus_dir).hparams |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.