Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> "type": "Pig",
"input_datasource": {
"type": "swift",
"source": "sahara_tests/scenario/defaults/"
"edp-examples/edp-pig/"
... | result = utils.generate_config(['dummyfile.yaml'], None, |
Predict the next line after this snippet: <|code_start|># 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
#
# Unless required by... | cluster_templates.SaharaClusterTemplateCLITest, |
Using the snippet: <|code_start|># 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
#
# Unless required by applicable law or agre... | plugins.SaharaPluginCLITest, |
Given the code snippet: <|code_start|># 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
#
# Unless required by applicable law or... | job_binaries.SaharaJobBinaryCLITest, |
Given the code snippet: <|code_start|># 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
#
# Unless required by applicable law or... | jobs.SaharaJobCLITest, |
Continue the code snippet: <|code_start|># 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
#
# Unless required by applicable law... | job_templates.SaharaJobTemplateCLITest, |
Predict the next line after this snippet: <|code_start|># 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
#
# Unless required by... | data_sources.SaharaDataSourceCLITest, |
Predict the next line after this snippet: <|code_start|> project_name = os.environ.get('OS_PROJECT_NAME', '')
os.environ['OS_USERNAME'] = 'demo_env'
os.environ['OS_PASSWORD'] = 'demopwd_env'
os.environ['OS_AUTH_URL'] = 'http://localhost:5000/v2.0'
os.environ['OS_PROJECT_NAME'] = '... | unit_dir = pkg.resource_filename(version.version_info.package, |
Predict the next line for this snippet: <|code_start|> '%Y%m%d_%H%M%S')
test_info['status'] = CHECK_FAILED_STATUS
test_info['traceback'] = traceback.format_exception(
*sys.exc_info())
if exit_with_error:
raise
... | timeouts.Defaults.init_defaults(self.testcase) |
Next line prediction: <|code_start|> return [job_id, input_id, output_id, configs]
@track_result("Check EDP jobs", False)
def check_run_jobs(self):
batching = self.testcase.get('edp_batching',
len(self.testcase['edp_jobs_flow']))
batching_size = batch... | destination = None if source else utils.rand_name( |
Using the snippet: <|code_start|> self._job_batching(pre_exec)
pre_exec = []
batching = batching_size
self.check_verification(self.cluster_id)
def _job_batching(self, pre_exec):
job_exec_ids = []
for job_exec in pre_exec:
job_exec_i... | 'endpoint': utils_url.url_schema_remover( |
Here is a snippet: <|code_start|> return ([0, ] + throughputs, forecasts)
def _make_recent_history_table(self, throughputs):
recent_history = []
for i in range(0, len(self.filter_summaries)):
summary = self.filter_summaries[i]
recent_history.append(
[s... | generate_dashboard.delay() |
Predict the next line for this snippet: <|code_start|>
class HealthCheck(View):
def get(self, request, *args, **kwargs):
last_access = cache.get('health_access', None)
content = {
'health': 'ok',
'last_access': last_access,
}
cache.set('health_access', dat... | updated = summaries.latest_update() |
Next line prediction: <|code_start|>class Forecast(TemplateView):
template_name = "forecast.html"
def find_summaries_or_404(self, filter_id):
self.filter_summaries = summaries.for_date_range(filter_id, self.start_date)
if not self.filter_summaries:
raise Http404("No filter with id: ... | throughputs = predictions.throughput_history(self.filter_summaries) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-16 13:33
from __future__ import unicode_literals
def migrate_fill_updated_at(apps, schema_editor):
"""Fill the updated_at column if it's not already."""
ProjectSummary = apps.get_model('dashboard', 'ProjectSummar... | summary = fill_updated_at(summary) |
Given the code snippet: <|code_start|>
urlpatterns = [
url(r'^$', Dashboard.as_view(), name="dashboard"),
url(r'^forecast/(?P<filter_id>[0-9]+)/$', Forecast.as_view(), name="forecast"),
url(r'^refresh/$', Refresh.as_view(), name="refresh"),
<|code_end|>
, generate the next line using the imports in this fi... | url(r'^health/$', HealthCheck.as_view(), name="health"), |
Given snippet: <|code_start|>
urlpatterns = [
url(r'^$', Dashboard.as_view(), name="dashboard"),
url(r'^forecast/(?P<filter_id>[0-9]+)/$', Forecast.as_view(), name="forecast"),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url
from .views impo... | url(r'^refresh/$', Refresh.as_view(), name="refresh"), |
Based on the snippet: <|code_start|> return xtras
def _add_forecasts(xtras, summary, logger):
a_month_ago = summary.created_on - relativedelta(days=30)
try:
forecasts = predictions.for_project(filter_id=summary.filter_id, backlog_size=summary.incomplete, start_date=a_month_ago)
except ValueErro... | data = sheets.load_sheet(sheet_id, settings.GOOGLE_SPREADSHEET_AUTH_FILE) |
Here is a snippet: <|code_start|>
def _add_current_jira_summary(xtras, jira_filter_id, logger):
summary_data = jira.summarize_query(jira_filter_id)
logger.debug("Filter {} summarized".format(jira_filter_id))
if summary_data.get('errors', []):
xtras['jira_summary_errors'] = summary_data['errors'... | p = summaries.create( |
Predict the next line for this snippet: <|code_start|> summary_data = jira.summarize_query(jira_filter_id)
logger.debug("Filter {} summarized".format(jira_filter_id))
if summary_data.get('errors', []):
xtras['jira_summary_errors'] = summary_data['errors']
logger.warn("Filter {} summary error"... | forecasts = predictions.for_project(filter_id=summary.filter_id, backlog_size=summary.incomplete, start_date=a_month_ago) |
Using the snippet: <|code_start|>"""Classes and functions for manipulating and storing summaries."""
SAVED = "saved"
UPDATED = "updated"
def fill_updated_at(summary):
"""Set updated_at to created_on at 11:59 pm UTC"""
summary.updated_at = timezone.now().replace(
year=summary.created_on.year,
... | p = ProjectSummary( |
Next line prediction: <|code_start|> if throughput < 0:
throughput = 0
history.append(throughput)
return history
def forecast(throughputs, backlog_size, num_simulations=10000, seed=None):
"""Monte Carlo forecast given the provided backlog and throughput histories.
Args:
... | summaries = for_date_range(filter_id, start_date) |
Next line prediction: <|code_start|>
class CommunityPKProxy(RecordPKProxy):
"""Resolver proxy for a Record entity using the UUID."""
def get_need(self):
"""Return the user need of the community's owner."""
# TODO this may become difficult once there's multiple levels
# of members... | Community, type_key=self.type_id, proxy_cls=CommunityPKProxy) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright (C) 2021 CERN.
# Copyright (C) 2022 Northwestern University.
#
# Invenio-Communities is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Entity resolver for the... | return CommunityNeed(comid) |
Predict the next line for this snippet: <|code_start|> def edit(self, identity, draft=None, record=None, **kwargs):
"""Update draft metadata."""
draft.access = record.access
def new_version(self, identity, draft=None, record=None, **kwargs):
"""Update draft metadata."""
draft.acc... | on_membership_change(identity=identity) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright (C) 2021 CERN.
#
# Invenio-Communities is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
class CommunityRelationMixin:
... | db.ForeignKey(CommunityMetadata.id, ondelete="CASCADE"), |
Based on the snippet: <|code_start|> return
# Cache keys
#
# The cache of communities must be invalidated on:
# 1) on creation of a community (likely this one is modelled via membership
# in the future).
# 2) add/remove/change of membership
#
# We construct the cache key for e... | identity.provides.add(CommunityNeed(c_id)) |
Predict the next line for this snippet: <|code_start|>
@pytest.fixture()
def headers():
"""Default headers for making requests."""
return {
'content-type': 'application/json',
'accept': 'application/json',
}
@pytest.fixture()
def client_with_login(client, users):
"""Log in a user to th... | Community.index.refresh() |
Given the code snippet: <|code_start|> {'text': 'Engineering', 'value': 'engineering'},
{'text': 'Technology', 'value': 'technology'},
{'text': 'History and Archaeology', 'value': 'history_and_archaeology'},
{'text': 'Information and Computing Sciences', 'value': 'information_and_computing_sciences'},
... | 'facet': facets.type, |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-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.
"""Community access system field."""
class Commun... | owners_cls = Owners |
Predict the next line after this snippet: <|code_start|>
class CommunitiesRelationManager:
"""Manager for a record's community relations."""
def __init__(self, m2m_model_cls, record_id, data):
self._m2m_model_cls = m2m_model_cls
self._record_id = record_id
self._default_id = None
... | c = Community.get_record(community_id) |
Next line prediction: <|code_start|># Invenio-Communities is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Invitations Actions."""
class AcceptAction(RequestAction):
"""Accept action."""
status_from = ['open']
status... | current_communities.service.members.create( |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright (C) 2022 Northwestern University.
#
# Invenio-Communities is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Members Service Config."""
class MemberLink(Link):
... | record_cls = Member |
Given snippet: <|code_start|># Copyright (C) 2022 Northwestern University.
#
# Invenio-Communities is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Members Service Config."""
class MemberLink(Link):
"""Link variables setter f... | permission_policy_cls = CommunityMembersPermissionPolicy |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright (C) 2022 Northwestern University.
#
# Invenio-Communities is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Members Service Config."""
class MemberLink(Link... | schema = MemberSchema |
Here is a snippet: <|code_start|> )
@login_required
def communities_new():
"""Communities creation page."""
return render_template(
"invenio_communities/new.html",
form_config=dict(
access=dict(
visibilty=[
{
'text': 'Pu... | @pass_community |
Here is a snippet: <|code_start|>
@login_required
def communities_new():
"""Communities creation page."""
return render_template(
"invenio_communities/new.html",
form_config=dict(
access=dict(
visibilty=[
{
'text': 'Public',... | @pass_community_logo |
Given snippet: <|code_start|> }
]
),
SITE_UI_URL=current_app.config["SITE_UI_URL"]
),
)
@pass_community
@pass_community_logo
def communities_detail(community=None, logo=None, pid_value=None):
"""Community detail page."""
return render_templ... | @require_community_owner |
Predict the next line for this snippet: <|code_start|>"""Example of a record draft API."""
class MockRecord(RecordBase):
"""Example parent record."""
# Configuration
model_cls = MockRecordMetadata
# System fields
schema = ConstantField('$schema', 'local://mocks/mock-v1.0.0.json')
index =... | communities = CommunitiesField(MockRecordCommunity) |
Here is a snippet: <|code_start|>"""Example of a record draft API."""
class MockRecord(RecordBase):
"""Example parent record."""
# Configuration
model_cls = MockRecordMetadata
# System fields
schema = ConstantField('$schema', 'local://mocks/mock-v1.0.0.json')
index = IndexField('mocks-mo... | communities = CommunitiesField(MockRecordCommunity) |
Predict the next line for this snippet: <|code_start|># under the terms of the MIT License; see LICENSE file for more details.
"""Command-line tools for demo module."""
@click.group()
def communities():
"""Invenio communities commands."""
@communities.command('demo')
@with_appcontext
def demo():
"""Creat... | communities_service = current_communities.service |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-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.
"""Command-line tools for demo ... | fake_data = create_fake_community(faker) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-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.
"""Command-line tools for demo module."""
@cl... | create_demo_community.delay(fake_data) |
Next line prediction: <|code_start|> """Register blueprint routes on app."""
routes = app.config.get("COMMUNITIES_ROUTES")
blueprint = Blueprint(
"invenio_communities",
__name__,
template_folder="../templates",
static_folder='../static'
)
# control blueprint endpoint... | view_func=communities_detail, |
Given snippet: <|code_start|> return render_template("invenio_communities/tombstone.html"), 410
def record_permission_denied_error(error):
"""Handle permission denier error on record views."""
if not current_user.is_authenticated:
# trigger the flask-login unauthorized handler
return curren... | view_func=communities_frontpage, |
Given the code snippet: <|code_start|>
#
# Registration
#
def create_ui_blueprint(app):
"""Register blueprint routes on app."""
routes = app.config.get("COMMUNITIES_ROUTES")
blueprint = Blueprint(
"invenio_communities",
__name__,
template_folder="../templates",
static_folder... | view_func=communities_new, |
Given the following code snippet before the placeholder: <|code_start|> if not current_user.is_authenticated:
# trigger the flask-login unauthorized handler
return current_app.login_manager.unauthorized()
return render_template(current_app.config['THEME_403_TEMPLATE']), 403
#
# Registration
#
d... | view_func=communities_search, |
Predict the next line after this snippet: <|code_start|> template_folder="../templates",
static_folder='../static'
)
# control blueprint endpoints registration
if app.config["COMMUNITIES_ENABLED"]:
# Communities URL rules
blueprint.add_url_rule(
routes["frontpage"... | view_func=communities_settings, |
Given the following code snippet before the placeholder: <|code_start|> if app.config["COMMUNITIES_ENABLED"]:
# Communities URL rules
blueprint.add_url_rule(
routes["frontpage"],
view_func=communities_frontpage,
)
blueprint.add_url_rule(
routes["se... | view_func=communities_settings_privileges, |
Using the snippet: <|code_start|># Copyright (C) 2022 Northwestern University.
#
# Invenio-Communities is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Invitation request types."""
# Actions
class AcceptAction(RequestAction):
... | current_communities.service.members.create( |
Using the snippet: <|code_start|>
super().execute(identity, uow)
# Request types
class CommunityMemberInvitation(BaseRequestType):
"""Community member invitation request type."""
type_id = 'community-member-invitation'
name = _('Community Member Invitation')
available_statuses = {
"o... | payload_schema = MemberInvitationPayloadSchema().fields |
Using the snippet: <|code_start|> ]
error_messages = set([item['messages'][0] for item in response.json['errors']])
assert expected == len(set(error_messages_list).intersection(error_messages))
def test_simple_flow(
app, client_with_login, location, minimal_community, headers,
... | Community.index.refresh() |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# Copyright (C) 2022 Northwestern University.
#
# Invenio-Communities is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Member Model."""
class MemberModel(db.Model, Re... | db.ForeignKey(CommunityMetadata.id, ondelete="CASCADE"), |
Given the following code snippet before the placeholder: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015-2018 Digi International Inc... | for fd in dc.filedata.get_filedata(fd_path == "~/"): |
Predict the next line after this snippet: <|code_start|>
PUT_FILE_DATA_COMMAND = """\
<commands>\
<put_file {offset}path="{path}" truncate="{truncate}">\
<data>{data}</data>\
</put_file>\
</commands>\
"""
PUT_FILE_FILE_COMMAND = """\
<commands>\
<put_file {offset}path="{path}" truncate="{truncate}">\
<file>{server_fil... | file1 = FileInfo(self.fss_api, self.dev_id, '/a/path/file1.txt', 1436276773, 7989, |
Continue the code snippet: <|code_start|> et = getcommand.get_etree()
self.assertEqual(et.tag, 'get_file')
self.assertEqual('/a/path/here', et.get('path'))
self.assertEqual('5', et.get('offset', None))
self.assertEqual('10', et.get('length', None))
self.assertEqual(0, len(... | putcommand = PutCommand(path='/a/path/here', file_data=six.b("some file data")) |
Continue the code snippet: <|code_start|> self.assertEqual('/a/path/here', et.get('path'))
self.assertEqual('5', et.get('offset', None))
self.assertEqual('true', et.get('truncate'))
self.assertEqual(1, len(list(et)))
data = et.find('./data')
self.assertEqual(base64.b64enco... | delcommand = DeleteCommand(path='/a/path/here') |
Based on the snippet: <|code_start|>
def test_parse_wrong_response(self):
self.assertRaises(ResponseParseError, PutCommand.parse_response, ET.fromstring('<rm />'))
class TestDeleteCommand(unittest.TestCase):
def test_init(self):
delcommand = DeleteCommand(path='/a/path/here')
et = delc... | command_block = FileSystemServiceCommandBlock() |
Using the snippet: <|code_start|>class TestCommandBlock(unittest.TestCase):
def test_init(self):
command_block = FileSystemServiceCommandBlock()
et = command_block.get_etree()
self.assertEqual(et.tag, 'commands')
self.assertEqual(0, len(list(et)))
self.assertEqual(0, len(et.k... | self.target = AllTarget() |
Given snippet: <|code_start|> self.assertEqual(errinfo.message, "error text")
def test_parse_wrong_response(self):
self.assertRaises(ResponseParseError, DeleteCommand.parse_response, ET.fromstring('<put_file />'))
class TestCommandBlock(unittest.TestCase):
def test_init(self):
command_... | class TestFileSystemServiceAPI(HttpTestBase): |
Here is a snippet: <|code_start|> "resultTotalRows": "0",
"requestedStartRow": "0",
"resultSize": "0",
"requestedSize": "1000",
"remainingSize": "0",
"items": []
}
"""
class TestMonitorAPI(HttpTestBase):
def test_create_tcp_monitor(self):
self.prepare_response("POST", "/ws/Monitor"... | mons = list(self.dc.monitor.get_monitors((MON_TOPIC_ATTR == "DeviceCore") & |
Continue the code snippet: <|code_start|> "requestedStartRow": "0",
"resultSize": "0",
"requestedSize": "1000",
"remainingSize": "0",
"items": []
}
"""
class TestMonitorAPI(HttpTestBase):
def test_create_tcp_monitor(self):
self.prepare_response("POST", "/ws/Monitor", data=CREATE_MONITO... | (MON_TRANSPORT_TYPE_ATTR == "tcp"))) |
Given the code snippet: <|code_start|> "monStatus": "INACTIVE",
"monBatchDuration": "10"
},
{
"monId": "178007",
"cstId": "7603",
"monTopic": "DeviceCore,FileDataCore,FileData,DataPoint",
"monTransportType": "http",
"monF... | class TestMonitorAPI(HttpTestBase): |
Given snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015-2018 Digi International Inc.
"""Provide access to Device Cloud filed... | class FileDataAPI(APIBase): |
Given snippet: <|code_start|>fd_path = Attribute("fdPath")
fd_name = Attribute("fdName")
fd_type = Attribute("fdType")
fd_customer_id = Attribute("customer_id")
fd_created_date = Attribute("fdCreatedDate")
fd_last_modified_date = Attribute("fdLastModifiedDate")
fd_content_type = Attribute("fdContentType")
fd_size = Att... | condition = validate_type(condition, type(None), Expression, *six.string_types) |
Given the code snippet: <|code_start|>
def __init__(self, fdapi, json_data):
self._fdapi = fdapi
self._json_data = json_data
def delete(self):
"""Delete this file or directory"""
return self._fdapi.delete_file(self.get_full_path())
def get_data(self):
"""Get the dat... | return iso8601_to_dt(self._json_data["fdLastModifiedDate"]) |
Continue the code snippet: <|code_start|>fd_path = Attribute("fdPath")
fd_name = Attribute("fdName")
fd_type = Attribute("fdType")
fd_customer_id = Attribute("customer_id")
fd_created_date = Attribute("fdCreatedDate")
fd_last_modified_date = Attribute("fdLastModifiedDate")
fd_content_type = Attribute("fdContentType")
f... | condition = validate_type(condition, type(None), Expression, *six.string_types) |
Given the code snippet: <|code_start|>
class AsyncRequestProxy(object):
"""An object representing an asynychronous SCI request.
Can be used for polling the status of the corresponding request.
:ivar job_id: the ID in device cloud of the job
:ivar response: the response to the request if completed
... | class ServerCommandInterfaceAPI(APIBase): |
Based on the snippet: <|code_start|> :type last_modified: int
:param size: The size of the file
:type size: int
:param hash: The files hash
:param hash_type: The method used to produce the hash
:ivar device_id: The Device ID of the device this file is on
:ivar path: The path to this file on ... | target = DeviceTarget(self.device_id) |
Given the following code snippet before the placeholder: <|code_start|> def parse_response(cls, response, **kwargs):
"""Parse the server response for this put file command
This will parse xml of the following form::
<rm />
or with an error::
<rm>
<err... | class FileSystemServiceAPI(SCIAPIBase): |
Here is a snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015-2018 Digi International Inc.
def show_group_tree(dc):
stats... | (dev_mac == '00:40:9D:50:B0:EA') |
Given the following code snippet before the placeholder: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015-2018 Digi International Inc... | len(list(dc.devicecore.get_devices(group_path == group.get_path()))) |
Based on the snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015-2018 Digi International Inc.
def show_group_tree(dc):
st... | dc = get_authenticated_dc() |
Predict the next line after this snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015-2018 Digi International Inc.
"""Module wi... | value = isoformat(to_none_or_dt(value)) |
Given the code snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2015-2018 Digi International Inc.
"""Module with functionality f... | value = isoformat(to_none_or_dt(value)) |
Predict the next line after this snippet: <|code_start|>#
# Copyright (c) 2015-2018 Digi International Inc.
dev_mac = Attribute('devMac')
group_id = Attribute('grpId')
group_path = Attribute('grpPath')
dev_connectware_id = Attribute('devConnectwareId')
# TODO: Can we support location based device lookups? (e.g. lat... | class DeviceCoreAPI(APIBase): |
Continue the code snippet: <|code_start|> APIBase.__init__(self, conn)
self._sci = sci
def get_devices(self, condition=None, page_size=1000):
"""Iterates over each :class:`Device` for this device cloud account
Examples::
# get a list of all devices
all_devic... | condition = validate_type(condition, type(None), Expression, *six.string_types) |
Given the code snippet: <|code_start|> """Get this device's device id"""
device_json = self.get_device_json(use_cached)
return device_json["id"].get("devId")
def get_ip(self, use_cached=True):
"""Get the last known IP of this device"""
device_json = self.get_device_json(use_c... | return iso8601_to_dt(start_date_iso8601) |
Given the following code snippet before the placeholder: <|code_start|> APIBase.__init__(self, conn)
self._sci = sci
def get_devices(self, condition=None, page_size=1000):
"""Iterates over each :class:`Device` for this device cloud account
Examples::
# get a list of all... | condition = validate_type(condition, type(None), Expression, *six.string_types) |
Predict the next line for this snippet: <|code_start|> random_state : random_state
Set the initial random state.
Returns
-------
numpy.ndarray
Sampled outcome.
"""
return func
class DeltaProdLik(object):
r"""
Product of Kronecker delta likeli... | link = IdentityLink() |
Here is a snippet: <|code_start|> return _aca(x)
@property
def sample_size(self):
r"""Get the number of samples."""
assert self.outcome is not None
return len(self.outcome)
class BernoulliProdLik(object):
r"""
Product of Bernoulli likelihoods.
The product can be wr... | link = LogitLink |
Using the snippet: <|code_start|> r"""Mean of the number of successful trials."""
return self._link.inv(x)
@_sample_doc
def sample(self, x, random_state=None):
p = self.mean(x)
nt = ascontiguousarray(self._ntrials, dtype=int)
return _aca(st.binom(nt, p).rvs(random_state=... | link = LogLink() |
Continue the code snippet: <|code_start|> """
return kron(self.A, self.X)
def value(self):
"""
Kronecker mean function.
Returns
-------
𝐦 : ndarray
(A⊗X)vec(B).
"""
return self.AX @ self._vecB.value
def gradient(self):
... | return unvec(self._vecB.value, (self.X.shape[1], self.A.shape[0])) |
Given the code snippet: <|code_start|> """
Kronecker mean function.
Returns
-------
𝐦 : ndarray
(A⊗X)vec(B).
"""
return self.AX @ self._vecB.value
def gradient(self):
"""
Gradient of the linear mean function.
Returns
... | self._vecB.value = vec(asarray(v, float)) |
Predict the next line after this snippet: <|code_start|>
def test_givencov():
K = RandomState(0).randn(5, 5)
K = K @ K.T
<|code_end|>
using the current file's imports:
from numpy.random import RandomState
from numpy.testing import assert_allclose
from glimix_core.cov import GivenCov
and any relevant contex... | cov = GivenCov(K) |
Given the code snippet: <|code_start|>
def test_probit_link():
link = ProbitLink()
assert_allclose(link.value(link.inv(3.2)), 3.2)
def test_logit_link():
<|code_end|>
, generate the next line using the imports in this file:
from numpy.testing import assert_allclose
from glimix_core.link import LogitLink, L... | link = LogitLink() |
Continue the code snippet: <|code_start|>
def test_probit_link():
link = ProbitLink()
assert_allclose(link.value(link.inv(3.2)), 3.2)
def test_logit_link():
link = LogitLink()
assert_allclose(link.value(link.inv(3.2)), 3.2)
def test_loglink_link():
<|code_end|>
. Use current file imports:
from nu... | link = LogLink() |
Next line prediction: <|code_start|>
@scale.setter
def scale(self, scale):
scale = max(scale, epsilon.tiny)
self._logscale.value = log(scale)
def value(self):
"""
Covariance matrix, s⋅K₀.
Returns
-------
K : ndarray
s⋅K₀.
"""
... | return format_function(self, {"K0": "..."}, [("scale", self.scale)]) |
Using the snippet: <|code_start|> """
Dimension of the matrix, d.
It corresponds to the number of rows and to the number of columns.
"""
return self._I.shape[0]
def value(self):
"""
Covariance matrix.
Returns
-------
K : ndarray
... | return format_function(self, {"dim": self._I.shape[0]}, [("scale", self.scale)]) |
Predict the next line for this snippet: <|code_start|> return K + self._epsilon * eye(K.shape[0])
def gradient(self):
"""
Derivative of the covariance matrix over the parameters of L.
Returns
-------
Lu : ndarray
Derivative of K over the lower triangular ... | return format_function(self, {"dim": self._L.shape[0]}, [("L", self.L)]) |
Here is a snippet: <|code_start|>def test_util_check_economic_qs():
A = ones((3, 2))
B = ones((3, 1))
C = ones(2)
with pytest.raises(ValueError):
check_economic_qs(A)
with pytest.raises(ValueError):
check_economic_qs((A, C))
A[0, 0] = inf
QS = ((A, B), C)
with pytest... | check_covariates(A) |
Predict the next line for this snippet: <|code_start|>
def test_util_check_economic_qs():
A = ones((3, 2))
B = ones((3, 1))
C = ones(2)
with pytest.raises(ValueError):
<|code_end|>
with the help of current file imports:
import pytest
from numpy import array, asarray, block, inf, nan, ones
from num... | check_economic_qs(A) |
Predict the next line for this snippet: <|code_start|> A[0, 0] = inf
QS = ((A, B), C)
with pytest.raises(ValueError):
check_economic_qs(QS)
A[0, 0] = 1
C[0] = nan
with pytest.raises(ValueError):
check_economic_qs(QS)
def test_util_check_covariates():
A = ones(2)
B = o... | check_outcome((y,), "poisson") |
Given the following code snippet before the placeholder: <|code_start|> check_outcome((y,), "poisson")
y[0] = 0.5
want = array([0.5, 1.0, 1.0, 1.0, 1.0])
assert_allclose(check_outcome(y, "poisson"), want)
x = ones(4)
with pytest.raises(ValueError):
check_outcome((y, x), "bernoulli"... | SVD0 = hsvd(A[0, 0], A[0, 1], A[1, 1]) |
Continue the code snippet: <|code_start|>
def test_mean_kron():
random = RandomState(0)
# number of trais
p = 2
# number of covariates
c = 3
# sample size
n = 4
A = random.randn(p, p)
X = random.randn(n, c)
B = random.randn(p, c)
<|code_end|>
. Use current file imports:
fro... | mean = KronMean(A, X) |
Predict the next line after this snippet: <|code_start|> @scale.setter
def scale(self, scale):
scale = max(scale, epsilon.tiny)
self._logscale.value = log(scale)
def value(self):
"""
Covariance matrix.
Returns
-------
K : ndarray
s⋅XXᵀ.
... | return format_function(self, {}, [("scale", self.scale)]) |
Predict the next line after this snippet: <|code_start|> ----------
y : array_like
Outcome variable.
lik : tuple
Likelihood definition. The first item is one of the following likelihood names:
``"Bernoulli"``, ``"Binomial"``, ``"Normal"``, and ``"Poisson"``. For
`Binomial`, th... | self._X = check_covariates(X) |
Predict the next line for this snippet: <|code_start|> Likelihood definition. The first item is one of the following likelihood names:
``"Bernoulli"``, ``"Binomial"``, ``"Normal"``, and ``"Poisson"``. For
`Binomial`, the second item is an array of outcomes.
X : array_like
Covariates.
... | self._QS = check_economic_qs(QS) |
Continue the code snippet: <|code_start|> Parameters
----------
y : array_like
Outcome variable.
lik : tuple
Likelihood definition. The first item is one of the following likelihood names:
``"Bernoulli"``, ``"Binomial"``, ``"Normal"``, and ``"Poisson"``. For
`Binomial`, th... | self._y = check_outcome(y, self._lik) |
Predict the next line for this snippet: <|code_start|> Outcome variable.
lik : tuple
Likelihood definition. The first item is one of the following likelihood names:
``"Bernoulli"``, ``"Binomial"``, ``"Normal"``, and ``"Poisson"``. For
`Binomial`, the second item is an array of outcome... | self._QS = economic_qs_zeros(self._y.shape[0]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.