text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate(self, overwrite=False):
"""Generate service files and returns a list of them. Note that env var names will be capitalized using a Jinja filter. This... |
super(SystemD, self).generate(overwrite=overwrite)
self._validate_init_system_specific_params()
svc_file_template = self.template_prefix + '.service'
env_file_template = self.template_prefix
self.svc_file_path = self.generate_into_prefix + '.service'
self.env_file_path ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install(self):
"""Install the service on the local machine This is where we deploy the service files to their relevant locations and perform any other requir... |
super(SystemD, self).install()
self.deploy_service_file(self.svc_file_path, self.svc_file_dest)
self.deploy_service_file(self.env_file_path, self.env_file_dest)
sh.systemctl.enable(self.name)
sh.systemctl('daemon-reload') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Stop the service. """ |
try:
sh.systemctl.stop(self.name)
except sh.ErrorReturnCode_5:
self.logger.debug('Service not running.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uninstall(self):
"""Uninstall the service. This is supposed to perform any cleanup operations required to remove the service. Files, links, whatever else sho... |
sh.systemctl.disable(self.name)
sh.systemctl('daemon-reload')
if os.path.isfile(self.svc_file_dest):
os.remove(self.svc_file_dest)
if os.path.isfile(self.env_file_dest):
os.remove(self.env_file_dest) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(self, name=''):
"""Return a list of the statuses of the `name` service, or if name is omitted, a list of the status of all services for this specific ... |
super(SystemD, self).status(name=name)
svc_list = sh.systemctl('--no-legend', '--no-pager', t='service')
svcs_info = [self._parse_service_info(svc) for svc in svc_list]
if name:
names = (name, name + '.service')
# return list of one item for specific service
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort(self, *sort):
""" Sort the results. Define how the results should be sorted. The arguments should be tuples of string defining the key and direction to ... |
self.add_get_param('sort', FILTER_DELIMITER.join(
[ELEMENT_DELIMITER.join(elements) for elements in sort]))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def where(self, *where):
""" Filter the results. Filter the results by provided rules. The rules should be tuples that look like this:: ('<key>', '<operator>', '... |
filters = list()
for key, operator, value in where:
filters.append(ELEMENT_DELIMITER.join((key, operator, value)))
self.add_get_param('where', FILTER_DELIMITER.join(filters))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self):
""" Run the request and fetch the results. This method will compile the request, send it to the SpaceGDN endpoint defined with the `SpaceGDN` ob... |
response = Response()
has_next = True
while has_next:
resp = self._fetch(default_path='v2')
results = None
if resp.success:
results = resp.data['results']
self.add_get_param('page', resp.data['pagination']['page'] + 1)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def singleton(cls):
""" Decorator function that turns a class into a singleton. """ |
import inspect
# Create a structure to store instances of any singletons that get
# created.
instances = {}
# Make sure that the constructor for this class doesn't take any
# arguments. Since singletons can only be instantiated once, it doesn't
# make any sense for the constructor to tak... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dict(doc):
"""Create a model output file object from a dictionary. """ |
if 'path' in doc:
path = doc['path']
else:
path = None
return ModelOutputFile(
doc['filename'],
doc['mimeType'],
path=path
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dict(doc):
"""Create a model output object from a dictionary. """ |
return ModelOutputs(
ModelOutputFile.from_dict(doc['prediction']),
[ModelOutputFile.from_dict(a) for a in doc['attachments']]
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self, model):
"""Create a dictionary serialization for a model. Parameters model : ModelHandle Returns ------- dict Dictionary serialization for a mo... |
# Get the basic Json object from the super class
obj = super(ModelRegistry, self).to_dict(model)
# Add model parameter
obj['parameters'] = [
para.to_dict() for para in model.parameters
]
obj['outputs'] = model.outputs.to_dict()
obj['connector'] = mode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _snake_to_camel(name, strict=False):
"""Converts parameter names from snake_case to camelCase. Args: name, str. Snake case. strict: bool, default True. If Tr... |
if strict:
name = name.lower()
terms = name.split('_')
return terms[0] + ''.join([term.capitalize() for term in terms[1:]]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_default_attr(self, default_attr):
"""Sets default attributes when None. Args: default_attr: dict. Key-val of attr, default-value. """ |
for attr, val in six.iteritems(default_attr):
if getattr(self, attr, None) is None:
setattr(self, attr, val) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(self, drop_null=True, camel=False, indent=None, sort_keys=False):
"""Serialize self as JSON Args: drop_null: bool, default True. Remove 'empty' attri... |
return json.dumps(self.to_dict(drop_null, camel), indent=indent,
sort_keys=sort_keys) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self, drop_null=True, camel=False):
"""Serialize self as dict. Args: drop_null: bool, default True. Remove 'empty' attributes. camel: bool, default T... |
#return _to_dict(self, drop_null, camel)
def to_dict(obj, drop_null, camel):
"""Recursively constructs the dict."""
if isinstance(obj, (Body, BodyChild)):
obj = obj.__dict__
if isinstance(obj, dict):
data = {}
for attr,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, body):
"""Parse JSON request, storing content in object attributes. Args: body: str. HTTP request body. Returns: self """ |
if isinstance(body, six.string_types):
body = json.loads(body)
# version
version = body['version']
self.version = version
# session
session = body['session']
self.session.new = session['new']
self.session.session_id = session['sessionId']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_speech_text(self, text):
"""Set response output speech as plain text type. Args: text: str. Response speech used when type is 'PlainText'. Cannot exceed ... |
self.response.outputSpeech.type = 'PlainText'
self.response.outputSpeech.text = text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_speech_ssml(self, ssml):
"""Set response output speech as SSML type. Args: ssml: str. Response speech used when type is 'SSML', should be formatted with ... |
self.response.outputSpeech.type = 'SSML'
self.response.outputSpeech.ssml = ssml |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_card_simple(self, title, content):
"""Set response card as simple type. title and content cannot exceed 8,000 characters. Args: title: str. Title of Simp... |
self.response.card.type = 'Simple'
self.response.card.title = title
self.response.card.content = content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_card_standard(self, title, text, smallImageUrl=None, largeImageUrl=None):
"""Set response card as standard type. title, text, and image cannot exceed 8,0... |
self.response.card.type = 'Standard'
self.response.card.title = title
self.response.card.text = text
if smallImageUrl:
self.response.card.image.smallImageUrl = smallImageUrl
if largeImageUrl:
self.response.card.image.largeImageUrl = largeImageUrl |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_reprompt_text(self, text):
"""Set response reprompt output speech as plain text type. Args: text: str. Response speech used when type is 'PlainText'. Can... |
self.response.reprompt.outputSpeech.type = 'PlainText'
self.response.reprompt.outputSpeech.text = text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_reprompt_ssml(self, ssml):
"""Set response reprompt output speech as SSML type. Args: ssml: str. Response speech used when type is 'SSML', should be form... |
self.response.reprompt.outputSpeech.type = 'SSML'
self.response.reprompt.outputSpeech.ssml = ssml |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def flush(self):
'''
Flushes the buffer to socket. Only call when the write is done. Calling flush after each write will prevent the buffer to act as efficiently as possible
'''
# return if empty
if self.__bufferidx == 0:
return
# send here the data
s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def close(self):
'''
Closes the stream to output. It destroys the buffer and the buffer pointer. However, it will not close the the client connection
'''
#write all that is remained in buffer
self.flush()
# delete buffer
self.__buffer = None
#reset buffer ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_ui(self):
'''
Create UI elements and connect signals.
'''
box = Gtk.Box()
rotate_left = Gtk.Button('Rotate left')
rotate_right = Gtk.Button('Rotate right')
flip_horizontal = Gtk.Button('Flip horizontal')
flip_vertical = Gtk.Button('Flip vertical... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def save(self):
'''
Save warp projection settings to HDF file.
'''
response = pu.open(title='Save perspective warp', patterns=['*.h5'])
if response is not None:
self.warp_actor.save(response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load(self):
'''
Load warp projection settings from HDF file.
'''
response = pu.open(title='Load perspective warp', patterns=['*.h5'])
if response is not None:
self.warp_actor.load(response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simple_logger(**kwargs):
""" Creates a simple logger :param int base_level: Lowest level allowed to log (Default: DEBUG) :param str log_format: Logging forma... |
# Args
logger_name = kwargs.get('name')
base_level = kwargs.get('base_level', logging.DEBUG)
should_stdout = kwargs.get('should_stdout', True)
should_http = kwargs.get('should_http', False)
# Generate base logger
logger = logging.getLogger(logger_name)
logger.setLevel(base_level)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compare_dicts(d1, d2):
""" Returns a diff string of the two dicts. """ |
a = json.dumps(d1, indent=4, sort_keys=True)
b = json.dumps(d2, indent=4, sort_keys=True)
# stolen from cpython
# https://github.com/python/cpython/blob/01fd68752e2d2d0a5f90ae8944ca35df0a5ddeaa/Lib/unittest/case.py#L1091
diff = ('\n' + '\n'.join(difflib.ndiff(
a.splitlines(),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diff_analysis(using):
""" Returns a diff string comparing the analysis defined in ES, with the analysis defined in Python land for the connection `using` """ |
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
return compare_dicts(es_analysis, python_analysis) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_analysis(using):
""" generate the analysis settings from Python land """ |
python_analysis = defaultdict(dict)
for index in registry.indexes_for_connection(using):
python_analysis.update(index._doc_type.mapping._collect_analysis())
return stringer(python_analysis) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def existing_analysis(using):
""" Get the existing analysis for the `using` Elasticsearch connection """ |
es = connections.get_connection(using)
index_name = settings.ELASTICSEARCH_CONNECTIONS[using]['index_name']
if es.indices.exists(index=index_name):
return stringer(es.indices.get_settings(index=index_name)[index_name]['settings']['index'].get('analysis', {}))
return DOES_NOT_EXIST |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_analysis_compatible(using):
""" Returns True if the analysis defined in Python land and ES for the connection `using` are compatible """ |
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
if es_analysis == DOES_NOT_EXIST:
return True
# we want to ensure everything defined in Python land is exactly matched in ES land
for section in python_analysis:
# there is an analysis section (analysi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combined_analysis(using):
""" Combine the analysis in ES with the analysis defined in Python. The one in Python takes precedence """ |
python_analysis = collect_analysis(using)
es_analysis = existing_analysis(using)
if es_analysis == DOES_NOT_EXIST:
return python_analysis
# we want to ensure everything defined in Python land is added, or
# overrides the things defined in ES
for section in python_analysis:
if s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flaskify(response, headers=None, encoder=None):
"""Format the response to be consumeable by flask. The api returns mostly JSON responses. The format method c... |
status_code = response.status
data = response.errors or response.message
mimetype = 'text/plain'
if isinstance(data, list) or isinstance(data, dict):
mimetype = 'application/json'
data = json.dumps(data, cls=encoder)
return flask.Response(
response=data, status=status_cod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
"""Ask politely, first, with SIGINT and SIGQUIT.""" |
if hasattr(self, 'process'):
if self.process is not None:
try:
is_running = self.process.poll() is None
except AttributeError:
is_running = False
if is_running:
self.bundle_engine.logline("S... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill(self):
"""Murder the children of this service in front of it, and then murder the service itself.""" |
if not self.is_dead():
self.bundle_engine.warnline("{0} did not shut down cleanly, killing.".format(self.service.name))
try:
if hasattr(self.process, 'pid'):
for child in psutil.Process(self.process.pid).children(recursive=True):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def cascade_delete(self, name):
"this fails under diamond inheritance"
for child in self[name].child_tables:
self.cascade_delete(child.name)
del self[name] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create(self, ex):
"helper for apply_sql in CreateX case"
if ex.name in self:
if ex.nexists: return
raise ValueError('table_exists',ex.name)
if any(c.pkey for c in ex.cols):
if ex.pkey:
raise sqparse2.SQLSyntaxError("don't mix table-level and column-level pkeys",ex)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def drop(self, ex):
"helper for apply_sql in DropX case"
# todo: factor out inheritance logic (for readability)
if ex.name not in self:
if ex.ifexists: return
raise KeyError(ex.name)
table_ = self[ex.name]
parent = table_.parent_table
if table_.child_tables:
if not ex.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_uri(self, path, query_params={}):
""" Prepares a full URI with the selected information. ``path``: Path can be in one of two formats: - If :attr:`se... |
query_str = urllib.urlencode(query_params)
# If we have a relative path (as opposed to a full URL), build it of
# the connection info
if path.startswith('/') and self.server:
protocol = self.protocol
server = self.server
else:
protocol, serve... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retrieve_page(self, method, path, post_params={}, headers={}, status=200, username=None, password=None, *args, **kwargs):
""" Makes the actual request. This ... |
# Copy headers so that making changes here won't affect the original
headers = headers.copy()
# Update basic auth information
basicauth = self._prepare_basicauth(username, password)
if basicauth:
headers.update([basicauth])
# If this is a POST or PUT, we ca... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_track_token(request):
"""Returns ``TrackToken``. ``TrackToken' contains request and user making changes. It can be passed to ``TrackedModel.save`` ins... |
from tracked_model.models import RequestInfo
request_pk = RequestInfo.create_or_get_from_request(request).pk
user_pk = None
if request.user.is_authenticated():
user_pk = request.user.pk
return TrackToken(request_pk=request_pk, user_pk=user_pk) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, *args, **kwargs):
"""Saves changes made on model instance if ``request`` or ``track_token`` keyword are provided. """ |
from tracked_model.models import History, RequestInfo
if self.pk:
action = ActionType.UPDATE
changes = None
else:
action = ActionType.CREATE
changes = serializer.dump_model(self)
request = kwargs.pop('request', None)
track_token =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _tracked_model_diff(self):
"""Returns changes made to model instance. Returns None if no changes were made. """ |
initial_state = self._tracked_model_initial_state
current_state = serializer.dump_model(self)
if current_state == initial_state:
return None
change_log = {}
for field in initial_state:
old_value = initial_state[field][Field.VALUE]
new_value =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tracked_model_history(self):
"""Returns history of a tracked object""" |
from tracked_model.models import History
return History.objects.filter(
table_name=self._meta.db_table, table_id=self.pk) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def replace_placeholders(path: Path, properties: Dict[str, str]):
'''Replace placeholders in a file with the values from the mapping.'''
with open(path, encoding='utf8') as file:
file_content = Template(file.read())
with open(path, 'w', encoding='utf8') as file:
file.write(file_content.saf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate(self, document):
'''Check if the selected template exists.'''
template = document.text
if template not in self.builtin_templates:
raise ValidationError(
message=f'Template {template} not found. '
+ f'Available templates are: {", ".join(s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_start_of_line(self):
"""Return index of start of last line stored in self.buf. This function never fetches more data from the file; therefore, if it retu... |
if self.newline in ('\r', '\n', '\r\n'):
return self.buf.rfind(self.newline.encode('ascii'), 0, -1) + 1
if self.newline:
raise ValueError(r"ropen newline argument must be one of "
r"None, '', '\r', '\n', '\r\n'.")
# self.newline is None or '... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_next_into_buf(self):
"""Read data from the file in self.bufsize chunks until we're certain we have a full line in the buffer. """ |
file_pos = self.fileobject.tell()
if (file_pos == 0) and (self.buf == b''):
raise StopIteration
while file_pos and (self.get_start_of_line() == 0):
bytes_to_read = min(self.bufsize, file_pos)
file_pos = file_pos - bytes_to_read
self.fileobject.see... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_to(self, db, index, item, default=OOSet):
""" Add `item` to `db` under `index`. If `index` is not yet in `db`, create it using `default`. Args: db (dict... |
row = db.get(index, None)
if row is None:
row = default()
db[index] = row
row.add(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_tree(self, tree, parent=None):
""" Add `tree` into database. Args: tree (obj):
:class:`.Tree` instance. parent (ref, default None):
Reference to parent... |
if tree.path in self.path_db:
self.remove_tree_by_path(tree.path)
# index all indexable attributes
for index in tree.indexes:
if not getattr(tree, index):
continue
self._add_to(
getattr(self, index + "_db"),
g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_tree_by_path(self, path):
""" Remove the tree from database by given `path`. Args: path (str):
Path of the tree. """ |
with transaction.manager:
trees = self.path_db.get(path, None)
if not trees:
return
for tree in trees:
return self._remove_tree(tree) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _remove_from(self, db, index, item):
""" Remove `item` from `db` at `index`. Note: This function is inverse to :meth:`._add_to`. Args: db (dict-obj):
Dict-l... |
with transaction.manager:
row = db.get(index, None)
if row is None:
return
with transaction.manager:
if item in row:
row.remove(item)
with transaction.manager:
if not row:
del db[index] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _remove_tree(self, tree, parent=None):
""" Really remove the tree identified by `tree` instance from all indexes from database. Args: tree (obj):
:class:`.T... |
# remove sub-trees
for sub_tree in tree.sub_trees:
self._remove_tree(sub_tree, parent=tree)
# remove itself
for index in tree.indexes:
if not getattr(tree, index):
continue
self._remove_from(
getattr(self, index + "_d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trees_by_issn(self, issn):
""" Search trees by `issn`. Args: issn (str):
:attr:`.Tree.issn` property of :class:`.Tree`. Returns: set: Set of matching :class... |
return set(
self.issn_db.get(issn, OOSet()).keys()
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trees_by_path(self, path):
""" Search trees by `path`. Args: path (str):
:attr:`.Tree.path` property of :class:`.Tree`. Returns: set: Set of matching :class... |
return set(
self.path_db.get(path, OOSet()).keys()
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_parent(self, tree, alt=None):
""" Get parent for given `tree` or `alt` if not found. Args: tree (obj):
:class:`.Tree` instance, which is already stored ... |
parent = self.parent_db.get(tree.path)
if not parent:
return alt
return list(parent)[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yearfrac_365q(d1, d2):
"""date difference "d1-d2" as year fractional""" |
# import modules
from datetime import date
from oxyba import date_to_datetime
# define yearfrac formula
# toyf = lambda a,b: (a - b).days / 365.2425
def toyf(a, b):
a = date_to_datetime(a) if isinstance(a, date) else a
b = date_to_datetime(b) if isinstance(b, date) else b
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, name, value, unit=None):
"""Add symbolic link to Dynamic Number list. name -- name of the symbolic link value -- value of the link (if not a string... |
# check if unit provided
if unit is not None:
add_unit = True
unit = str(unit)
else:
add_unit = False
# convert value to string
value = str(value)
# write to file
f = open(self.file_dir, 'a')
if add_unit:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_zeo():
""" Start asyncore thread. """ |
if not _ASYNCORE_RUNNING:
def _run_asyncore_loop():
asyncore.loop()
thread.start_new_thread(_run_asyncore_loop, ())
global _ASYNCORE_RUNNING
_ASYNCORE_RUNNING = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retry_and_reset(fn):
""" Decorator used to make sure, that operation on ZEO object will be retried, if there is ``ConnectionStateError`` exception. """ |
@wraps(fn)
def retry_and_reset_decorator(*args, **kwargs):
obj = kwargs.get("self", None)
if not obj:
obj = args[0]
try:
return fn(*args, **kwargs)
except ConnectionStateError:
obj._on_close_callback()
return fn(*args, **kwargs)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_zeo_root(self, attempts=3):
""" Get and initialize the ZEO root object. Args: attempts (int, default 3):
How many times to try, if the connection was ... |
try:
db_root = self._connection.root()
except ConnectionStateError:
if attempts <= 0:
raise
self._open_connection()
return self._init_zeo_root(attempts=attempts-1)
# init the root, if it wasn't already declared
if self.pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_dataclass_loader(cls, registry, field_getters):
"""create a loader for a dataclass type""" |
fields = cls.__dataclass_fields__
item_loaders = map(registry, map(attrgetter('type'), fields.values()))
getters = map(field_getters.__getitem__, fields)
loaders = list(starmap(compose, zip(item_loaders, getters)))
def dloader(obj):
return cls(*(g(obj) for g in loaders))
return dloade... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rand_block(minimum, scale, maximum=1):
""" block current thread at random pareto time ``minimum < block < 15`` and return the sleep time ``seconds`` :param m... |
t = min(rand_pareto_float(minimum, scale), maximum)
time.sleep(t)
return t |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _print_divide(self):
"""Prints all those table line dividers.""" |
for space in self.AttributesLength:
self.StrTable += "+ " + "- " * space
self.StrTable += "+" + "\n" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_table(self):
""" Creates a pretty-printed string representation of the table as ``self.StrTable``. """ |
self.StrTable = ""
self.AttributesLength = []
self.Lines_num = 0
# Prepare some values..
for col in self.Table:
# Updates the table line count if necessary
values = list(col.values())[0]
self.Lines_num = max(self.Lines_num, len(values))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _print_head(self):
"""Generates the table header.""" |
self._print_divide()
self.StrTable += "| "
for colwidth, attr in zip(self.AttributesLength, self.Attributes):
self.StrTable += self._pad_string(attr, colwidth * 2)
self.StrTable += "| "
self.StrTable += '\n'
self._print_divide() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _print_value(self):
"""Generates the table values.""" |
for line in range(self.Lines_num):
for col, length in zip(self.Table, self.AttributesLength):
vals = list(col.values())[0]
val = vals[line] if len(vals) != 0 and line < len(vals) else ''
self.StrTable += "| "
self.StrTable += self._pad... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pad_string(self, str, colwidth):
"""Center-pads a string to the given column width using spaces.""" |
width = self._disp_width(str)
prefix = (colwidth - 1 - width) // 2
suffix = colwidth - prefix - width
return ' ' * prefix + str + ' ' * suffix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def basic_auth_string(username, password):
""" Encode a username and password for use in an HTTP Basic Authentication header """ |
b64 = base64.encodestring('%s:%s' % (username, password)).strip()
return 'Basic %s' % b64 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def equivalent_relshell_type(val):
"""Returns `val`'s relshell compatible type. :param val: value to check relshell equivalent type :raises: `NotImplementedError... |
builtin_type = type(val)
if builtin_type not in Type._typemap:
raise NotImplementedError("builtin type %s is not convertible to relshell type" %
(builtin_type))
relshell_type_str = Type._typemap[builtin_type]
return Type(relshell_type_st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self, *args, **kwargs):
""" Set the arguments for the callback function and start the thread """ |
self.runArgs = args
self.runKwargs = kwargs
Thread.start(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(name, languages, run):
"""Initializes your CONFIG_FILE for the current submission""" |
contents = [file_name for file_name in glob.glob("*.*") if file_name != "brains.yaml"]
with open(CONFIG_FILE, "w") as output:
output.write(yaml.safe_dump({
"run": run,
"name": name,
"languages": languages,
# automatically insert all root files into conte... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push(description, datasets, wait, verbose):
"""Publish your submission to brains""" |
# Loading config
config = _get_config()
file_patterns = config["contents"]
if not isinstance(file_patterns, type([])):
# put it into an array so we can iterate it, if it isn't already an array
file_patterns = [file_patterns]
if datasets:
datasets_string = datasets.split(',')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(dataset):
"""Run brain locally""" |
config = _get_config()
if dataset:
_print("getting dataset from brains...")
cprint("done", 'green')
# check dataset cache for dataset
# if not exists
# r = requests.get('https://api.github.com/events', stream=True)
# with open(filename, 'wb') as fd:
# ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def diskMonitor(self):
'''Primitive monitor which checks whether new data is added to disk.'''
while self.loop():
try:
newest = max(glob.iglob("%s/*" % (self.kwargs.directory)), key=os.path.getmtime)
except Exception:
pass
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, **kwargs):
""" Update selected objects with the given keyword parameters and mark them as changed """ |
super(ModelQuerySet, self).update(_changed=True, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(cls):
""" Update rows to include known network interfaces """ |
ifaddrs = getifaddrs()
# Create new interfaces
for ifname in ifaddrs.keys():
if filter(ifname.startswith, cls.NAME_FILTER):
cls.objects.get_or_create(name=ifname)
# Delete no longer existing ones
cls.objects.exclude(name__in=ifaddrs.keys()).delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def admin_page_ordering(request):
""" Updates the ordering of pages via AJAX from within the admin. """ |
def get_id(s):
s = s.split("_")[-1]
return int(s) if s.isdigit() else None
page = get_object_or_404(Page, id=get_id(request.POST['id']))
old_parent_id = page.parent_id
new_parent_id = get_id(request.POST['parent_id'])
new_parent = Page.objects.get(id=new_parent_id) if new_parent_id... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page(request, slug, template=u"pages/page.html", extra_context=None):
""" Select a template for a page and render it. The request object should have a ``page... |
from yacms.pages.middleware import PageMiddleware
if not PageMiddleware.installed():
raise ImproperlyConfigured("yacms.pages.middleware.PageMiddleware "
"(or a subclass of it) is missing from " +
"settings.MIDDLEWARE_CLASSES or " +
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vector_unit_nonull(v):
"""Return unit vectors. Any null vectors raise an Exception. Parameters Cartesian vectors, with last axis indexing the dimension. Retu... |
if v.size == 0:
return v
return v / vector_mag(v)[..., np.newaxis] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vector_unit_nullnull(v):
"""Return unit vectors. Any null vectors remain null vectors. Parameters Cartesian vectors, with last axis indexing the dimension. R... |
if v.size == 0:
return v
mag = vector_mag(v)
v_new = v.copy()
v_new[mag > 0.0] /= mag[mag > 0.0][..., np.newaxis]
return v_new |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vector_unit_nullrand(v, rng=None):
"""Return unit vectors. Any null vectors are mapped to a uniformly picked unit vector. Parameters Cartesian vectors, with ... |
if v.size == 0:
return v
mag = vector_mag(v)
v_new = v.copy()
v_new[mag == 0.0] = sphere_pick(v.shape[-1], (mag == 0.0).sum(), rng)
v_new[mag > 0.0] /= mag[mag > 0.0][..., np.newaxis]
return v_new |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def polar_to_cart(arr_p):
"""Return polar vectors in their cartesian representation. Parameters Polar vectors, with last axis indexing the dimension, using (radi... |
if arr_p.shape[-1] == 1:
arr_c = arr_p.copy()
elif arr_p.shape[-1] == 2:
arr_c = np.empty_like(arr_p)
arr_c[..., 0] = arr_p[..., 0] * np.cos(arr_p[..., 1])
arr_c[..., 1] = arr_p[..., 0] * np.sin(arr_p[..., 1])
elif arr_p.shape[-1] == 3:
arr_c = np.empty_like(arr_p)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cart_to_polar(arr_c):
"""Return cartesian vectors in their polar representation. Parameters Cartesian vectors, with last axis indexing the dimension. Returns... |
if arr_c.shape[-1] == 1:
arr_p = arr_c.copy()
elif arr_c.shape[-1] == 2:
arr_p = np.empty_like(arr_c)
arr_p[..., 0] = vector_mag(arr_c)
arr_p[..., 1] = np.arctan2(arr_c[..., 1], arr_c[..., 0])
elif arr_c.shape[-1] == 3:
arr_p = np.empty_like(arr_c)
arr_p[...,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sphere_pick_polar(d, n=1, rng=None):
"""Return vectors uniformly picked on the unit sphere. Vectors are in a polar representation. Parameters d: float The nu... |
if rng is None:
rng = np.random
a = np.empty([n, d])
if d == 1:
a[:, 0] = rng.randint(2, size=n) * 2 - 1
elif d == 2:
a[:, 0] = 1.0
a[:, 1] = rng.uniform(-np.pi, +np.pi, n)
elif d == 3:
u, v = rng.uniform(0.0, 1.0, (2, n))
a[:, 0] = 1.0
a[:, 1... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rejection_pick(L, n, d, valid, rng=None):
"""Return cartesian vectors uniformly picked in a space with an arbitrary number of dimensions, which is fully encl... |
if rng is None:
rng = np.random
rs = []
while len(rs) < n:
r = rng.uniform(-L / 2.0, L / 2.0, size=d)
if valid(r):
rs.append(r)
return np.array(rs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ball_pick(n, d, rng=None):
"""Return cartesian vectors uniformly picked on the unit ball in an arbitrary number of dimensions. The unit ball is the space enc... |
def valid(r):
return vector_mag_sq(r) < 1.0
return rejection_pick(L=2.0, n=n, d=d, valid=valid, rng=rng) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disk_pick_polar(n=1, rng=None):
"""Return vectors uniformly picked on the unit disk. The unit disk is the space enclosed by the unit circle. Vectors are in a... |
if rng is None:
rng = np.random
a = np.zeros([n, 2], dtype=np.float)
a[:, 0] = np.sqrt(rng.uniform(size=n))
a[:, 1] = rng.uniform(0.0, 2.0 * np.pi, size=n)
return a |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def smallest_signed_angle(source, target):
"""Find the smallest angle going from angle `source` to angle `target`.""" |
dth = target - source
dth = (dth + np.pi) % (2.0 * np.pi) - np.pi
return dth |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, vpn_id: int) -> Vpn: """ Updates the Vpn Resource with the name. """ |
vpn = self._get_or_abort(vpn_id)
self.update(vpn)
session.commit()
return vpn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self) -> Vpn: """ Creates the vpn with the given data. """ |
vpn = Vpn()
session.add(vpn)
self.update(vpn)
session.flush()
session.commit()
return vpn, 201, {
'Location': url_for('vpn', vpn_id=vpn.id)
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_token(cls, parser, token):
"""Class method to parse render_comment_list and return a Node.""" |
tokens = token.contents.split()
if tokens[1] != 'for':
raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])
# {% render_comment_list for obj %}
if len(tokens) == 3:
return cls(object_expr=parser.compile_filter(tokens[2]))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_current_data(self):
"""Return the calibration data for the current IMU, if any.""" |
if self.current_imuid in self.calibration_data:
return self.calibration_data[self.current_imuid]
return {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_battery(self):
"""Updates the battery level in the UI for the connected SK8, if any""" |
if self.sk8 is None:
return
battery = self.sk8.get_battery_level()
self.lblBattery.setText('Battery: {}%'.format(battery)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def imu_changed(self, val):
"""Handle clicks on the IMU index spinner.""" |
self.current_imuid = '{}_IMU{}'.format(self.sk8.get_device_name(), val)
self.update_data_display(self.get_current_data()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accel_calibration(self):
"""Perform accelerometer calibration for current IMU.""" |
self.calibration_state = self.CAL_ACC
self.acc_dialog = SK8AccDialog(self.sk8.get_imu(self.spinIMU.value()), self)
if self.acc_dialog.exec_() == QDialog.Rejected:
return
self.calculate_acc_calibration(self.acc_dialog.samples) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gyro_calibration(self):
"""Perform gyroscope calibration for current IMU.""" |
QtWidgets.QMessageBox.information(self, 'Gyro calibration', 'Ensure the selected IMU is in a stable, unmoving position, then click OK. Don\'t move the the IMU for a few seconds')
self.calibration_state = self.CAL_GYRO
self.gyro_dialog = SK8GyroDialog(self.sk8.get_imu(self.spinIMU.value()), self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.