Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> """Read cloudtype and flag info from filename.""" ctth = CtthObj() ctype = CtypeObj() cma = CmaObj() ctth.height = patmosx_nc.variables['cld_height_acha'][0, :, :].astype(np.float) ctth.h_nodata = patmosx_nc.variables['cld_height_acha']._FillValue if np.ma.is_mas...
cloudproducts = AllImagerData()
Continue the code snippet: <|code_start|> if ".nc" in filename: return patmosx_read_all_nc(filename, cross, SETTINGS) else: return patmosx_read_all_hdf(filename, cross, SETTINGS) def patmosx_read_all_nc(filename, cross, SETTINGS): """Read geolocation, angles info, ctth, and cma.""" patm...
ctype = CtypeObj()
Based on the snippet: <|code_start|>def patmosx_read_all(filename, cross, SETTINGS): if ".nc" in filename: return patmosx_read_all_nc(filename, cross, SETTINGS) else: return patmosx_read_all_hdf(filename, cross, SETTINGS) def patmosx_read_all_nc(filename, cross, SETTINGS): """Read geolocat...
ctth = CtthObj()
Using the snippet: <|code_start|> return patmosx_read_all_nc(filename, cross, SETTINGS) else: return patmosx_read_all_hdf(filename, cross, SETTINGS) def patmosx_read_all_nc(filename, cross, SETTINGS): """Read geolocation, angles info, ctth, and cma.""" patmosx_nc = netCDF4.Dataset(filename,...
cma = CmaObj()
Next line prediction: <|code_start|> cloudproducts.ctype = ctype logger.info("Not reading surface temperature") logger.info("Not reading cloud microphysical properties") logger.info("Not reading channel data") return cloudproducts def read_patmosx_ctype_cmask_ctth(patmosx_nc): """Read cloudtyp...
angle_obj = ImagerAngObj()
Next line prediction: <|code_start|> @property def cols(self): # self._cols = np.array(self._cols, dtype=np.int64) return np.ma.array(self._cols, mask=self.mask, fill_value=-NODATA, hard_mask=True) @property def time_diff(self): """Time difference in ...
radius_of_influence=0.7*RESOLUTION*1000.0,
Predict the next line for this snippet: <|code_start|># along with atrain_match. If not, see <http://www.gnu.org/licenses/>. """Match TRUTH and IMAGER data.""" # from __future__ import with_statement logger = logging.getLogger(__name__) class MatchMapper(object): """ Map arrays from one swath to another. ...
return np.ma.array(self._rows, mask=self.mask, fill_value=NODATA,
Continue the code snippet: <|code_start|> size=5, mode='constant', cval=-9999999999999) flat_index = np.array(flat_index, dtype=np.int) delta_row, delta_col = np.unravel_index(flat_index, (5, 5)) delta_row = delta...
retv = get_warmest_or_coldest_index(self.t11, self.matched)
Predict the next line for this snippet: <|code_start|>class test_match_lon_lat(unittest.TestCase): def setUp(self): lon = np.array([[999, 10, 15], [-999, 20, 25]]).astype(np.float64) lat = np.array([[999, 10, 15], [-999, 20, 25]]).astype(np.float64) ...
mapper, _ = match.match_lonlat(self.source3, self.target,
Predict the next line after this snippet: <|code_start|> class MOD06Obj: # skeleton container for MODIS Level2 data def __init__(self): self.height = None self.temperature = None self.pressure = None self.cloud_emissivity = None self.cloud_phase = None self.lwp =...
ca_matchup.modis_lvl2.height = get_data_from_array(modis_06.height, index)
Using the snippet: <|code_start|># # You should have received a copy of the GNU General Public License # along with atrain_match. If not, see <http://www.gnu.org/licenses/>. # -*- coding: utf-8 -*- # Program truth_imager_plot.py """Plotting functions to plot CALIOP, CPR (CloudSat) and colocated imager data along trac...
if RESOLUTION == 5 and match_clsat is not None:
Predict the next line after this snippet: <|code_start|> MY_SATELLITES = options.satellites if options.years: MY_YEARS = options.years years_string = "_".join(MY_YEARS) satellites_string = "_".join(MY_SATELLITES) # get cases CASES = [] month_list = ["*"] day_list = ["*"] ...
print(RESOLUTION)
Here is a snippet: <|code_start|> if "MONTH" in SETTINGS.keys() and len(SETTINGS["MONTHS"]) > 0: month_list = ["{:02d}".format(int(ind)) for ind in SETTINGS["MONTHS"]] if options.months: month_list = ["{:02d}".format(int(ind)) for ind in options.months] if "DAY" in SETTINGS.keys() an...
val_dir=_validation_results_dir,
Predict the next line after this snippet: <|code_start|> parser.add_argument('--years', '-y', metavar='YYYY', type=str, nargs='*', required=False, help='List of year to combine, ' 'overrides YEARS in atrain_match.cfg') parser.add_argument('-...
for surface in SURFACES:
Using the snippet: <|code_start|> data = _interpolate_height_and_temperature_from_pressure(obt.imager, 440) setattr(obt.imager, 'segment_nwp_h440', data) data = _interpolate_height_and_temperature_from_pressure(obt.imager, 680) setattr(obt.imager, 'segment_nwp_h680', data) return obt # ------------...
] + OCA_READ_EXTRA # And NN-extra!
Here is a snippet: <|code_start|> seconds = np.float64(pps_nc.variables['time'][::]) # from PPS often 0 if 'seconds' in time_temp: if 'T' in time_temp: time_obj = time.strptime(time_temp, 'seconds since %Y-%m-%dT%H:%M:%S+00:00') elif time_temp == u'seconds since 1970-01-01': ...
do_some_geo_obj_logging(all_imager_obj)
Next line prediction: <|code_start|> class ProvinceAdmin(admin.ModelAdmin): list_display = ('name', 'code', 'order', 'pk', 'enabled') class CityAdmin(admin.ModelAdmin): list_display = ('name', 'province', 'pk', 'enabled') <|code_end|> . Use current file imports: (from django.contrib.gis import admin from an...
admin.site.register(Province, ProvinceAdmin)
Based on the snippet: <|code_start|> class ProvinceAdmin(admin.ModelAdmin): list_display = ('name', 'code', 'order', 'pk', 'enabled') class CityAdmin(admin.ModelAdmin): list_display = ('name', 'province', 'pk', 'enabled') admin.site.register(Province, ProvinceAdmin) <|code_end|> , predict the immediate next ...
admin.site.register(City, CityAdmin)
Continue the code snippet: <|code_start|> class JSTORAPI: DEFAULT_DOI_PREFIX = "10.2307" """Main DOI prefix. Used for real DOIs and non registered pseudo-DOIs with the same format""" def __init__(self, http_service: HTTPService, url): self._jstor_pdf_url = url self._http = http_service ...
url, headers=add_request_headers({"Accept": "application/pdf"})
Next line prediction: <|code_start|> ( param( HTTPUnsupportedMediaType, HTTPUnsupportedMediaType.code, id="Pyramid error", ), param(BlockingIOError, 500, id="Unknown python error"), ), ) def test_values_are_copied...
param(BadURL, BadURL, id="Mapped directly"),
Given the following code snippet before the placeholder: <|code_start|> if should_report: h_pyramid_sentry.report_exception.assert_called_once_with(exception) else: h_pyramid_sentry.report_exception.assert_not_called() @pytest.fixture def pyramid_request(self): r...
exception = GoogleDriveServiceError(
Based on the snippet: <|code_start|> HTTPUnsupportedMediaType, HTTPUnsupportedMediaType.code, id="Pyramid error", ), param(BlockingIOError, 500, id="Unknown python error"), ), ) def test_values_are_copied_from_the_exception( ...
param(BlockingIOError, UnhandledUpstreamException, id="Unmapped"),
Given the code snippet: <|code_start|> ) def test_it_reads_the_urls_from_the_request( self, pyramid_request, get_original_url ): pyramid_request.url = sentinel.request_url values = other_exceptions(ValueError(), pyramid_request) get_original_url.assert_called_once_with(...
(UpstreamServiceError, False),
Predict the next line for this snippet: <|code_start|> values = other_exceptions(exception, pyramid_request) assert values == Any.dict.containing( { "exception": Any.dict.containing( {"class": exception.__class__.__name__, "details": "details string"} ...
EXCEPTION_MAP[mapped_exception]
Given the following code snippet before the placeholder: <|code_start|> ), ) def test_other_exceptions_reporting_to_sentry( self, pyramid_request, h_pyramid_sentry, exception_class, should_report ): exception = exception_class("Oh no") other_exceptions(exception, pyramid_requ...
google_drive_exceptions(exception, pyramid_request)
Given snippet: <|code_start|> class TestOtherExceptions: @pytest.mark.parametrize( "exception_class,status_code", ( param( HTTPUnsupportedMediaType, HTTPUnsupportedMediaType.code, id="Pyramid error", ), param(Bloc...
values = other_exceptions(exception, pyramid_request)
Predict the next line for this snippet: <|code_start|> class TestDebugHeaders: def test_it(self, pyramid_request): pyramid_request.headers = {"Key": "Value"} <|code_end|> with the help of current file imports: from unittest.mock import create_autospec, sentinel from h_matchers import Any from pyramid.t...
response = debug_headers(sentinel.context, pyramid_request)
Predict the next line after this snippet: <|code_start|> @pytest.mark.usefixtures("http_service") def test_it(self, call_view, jstor_api, pyramid_request): response = call_view( "jstor://DOI", view=proxy_jstor_pdf, params={"jstor.ip": "1.1.1.1"} ) assert response.status_code ...
context = QueryURLResource(pyramid_request)
Next line prediction: <|code_start|> "hypothesis_config": sentinel.h_config, } def test_it_builds_the_url( self, call_view, google_drive_api, pdf_url_builder_service ): google_drive_api.parse_file_url.return_value = None call_view("https://example.com/foo/bar.pdf?q=s...
response = proxy_google_drive_file(pyramid_request)
Next line prediction: <|code_start|> def test_it_streams_content(self, http_service, call_view): # Create a generator and a counter of how many times it's been accessed def count_access(i): count_access.value += 1 return i count_access.value = 0 http_service....
"jstor://DOI", view=proxy_jstor_pdf, params={"jstor.ip": "1.1.1.1"}
Predict the next line after this snippet: <|code_start|> google_drive_api.iter_file.return_value = (count_access(i) for i in range(3)) response = proxy_google_drive_file(pyramid_request) # The first and only the first item has been reified from the generator assert count_access.value =...
response = call_view("https://one-drive.com", view=proxy_onedrive_pdf)
Predict the next line after this snippet: <|code_start|>@pytest.mark.usefixtures("secure_link_service", "pdf_url_builder_service") class TestJSTORPDF: @pytest.mark.usefixtures("http_service") def test_it(self, call_view, jstor_api, pyramid_request): response = call_view( "jstor://DOI", view=...
def call_view(url="http://example.com/name.pdf", params=None, view=view_pdf):
Based on the snippet: <|code_start|> ) def test_it( self, content_type, context, expected_cache_control_header, get_url_details, pyramid_request, status_code, via_client_service, http_service, ): pyramid_request.params = {"url": ...
assert_cache_control(
Given the code snippet: <|code_start|> ("HTML", 500, "no-cache"), ("HTML", 501, "no-cache"), ], ) def test_it( self, content_type, context, expected_cache_control_header, get_url_details, pyramid_request, status_code, ...
assert response == temporary_redirect_to(
Next line prediction: <|code_start|> get_url_details, pyramid_request, status_code, via_client_service, http_service, ): pyramid_request.params = {"url": sentinel.url, "foo": "bar"} get_url_details.return_value = (sentinel.mime_type, status_code) via_cl...
return create_autospec(QueryURLResource, spec_set=True, instance=True)
Next line prediction: <|code_start|> @pytest.mark.usefixtures("via_client_service") class TestRouteByContent: @pytest.mark.parametrize( "content_type,status_code,expected_cache_control_header", [ ("PDF", 200, "public, max-age=300, stale-while-revalidate=86400"), ("HTML", 200...
response = route_by_content(context, pyramid_request)
Given snippet: <|code_start|> pyramid_request.registry.settings = { "checkmate_allow_all": sentinel.checkmate_allow_all, "checkmate_ignore_reasons": sentinel.checkmate_ignore_reasons, } pyramid_request.params["via.blocked_for"] = sentinel.via_blocked_for client.ra...
return ViaCheckmateClient(pyramid_request)
Using the snippet: <|code_start|>"""Error views to handle when things go wrong in the app.""" EXCEPTION_MAP = { BadURL: { "title": "The URL isn't valid", "long_description": [ "Parts of the URL could be missing or in the wrong format." ], "stage": "request", "r...
UnhandledUpstreamException: {
Given the code snippet: <|code_start|>"""Error views to handle when things go wrong in the app.""" EXCEPTION_MAP = { BadURL: { "title": "The URL isn't valid", "long_description": [ "Parts of the URL could be missing or in the wrong format." ], "stage": "request", ...
UpstreamServiceError: {
Predict the next line after this snippet: <|code_start|>"""Error views to handle when things go wrong in the app.""" EXCEPTION_MAP = { BadURL: { "title": "The URL isn't valid", "long_description": [ "Parts of the URL could be missing or in the wrong format." ], "stage"...
UpstreamTimeout: {
Predict the next line after this snippet: <|code_start|> except Exception: # pylint: disable=broad-except # Use super broad exceptions so we can't fail here data["text"] = "... cannot retrieve ..." return data @exception_view_config(Exception, renderer="via:templates/exception.ht...
"original": get_original_url(request.context)
Given the following code snippet before the placeholder: <|code_start|> "http://example.com/%D0%BA%D0%B0%D0%BB%D0%BE%D1%88%D0%B8", "http://example.com/%D0%BA%D0%B0%D0%BB%D0%BE%D1%88%D0%B8", ), ] BAD_URLS = ("https://]", "https://%5D") class TestQueryURLResource: @pytest.mark.parametrize("url,e...
with pytest.raises(BadURL):
Based on the snippet: <|code_start|> return QueryURLResource(pyramid_request) class TestPathURLResource: @pytest.mark.parametrize("url,expected", NORMALISED_URLS) def test_url_from_path_returns_url(self, context, pyramid_request, url, expected): pyramid_request.path_qs = f"/{url}" asse...
return PathURLResource(pyramid_request)
Given the following code snippet before the placeholder: <|code_start|>BAD_URLS = ("https://]", "https://%5D") class TestQueryURLResource: @pytest.mark.parametrize("url,expected", NORMALISED_URLS) def test_url_from_query_returns_url(self, context, pyramid_request, url, expected): pyramid_request.param...
return QueryURLResource(pyramid_request)
Using the snippet: <|code_start|> pyramid_request.path_qs = f"/{url}" assert context.url_from_path() == expected @pytest.mark.parametrize("bad_path", ("/", "/ ")) def test_url_from_path_raises_HTTPBadRequest_for_missing_urls( self, context, pyramid_request, bad_path ): pyra...
get_original_url(path_url_resource)
Given snippet: <|code_start|> class TestJSTORAPI: @pytest.mark.parametrize( "url,expected", [(None, False), ("http://jstor-api.com", True)] ) def test_enabled(self, url, expected): assert JSTORAPI(sentinel.http, url).enabled == expected @pytest.mark.parametrize( "url,expected...
expected, headers=add_request_headers({"Accept": "application/pdf"})
Next line prediction: <|code_start|> class TestJSTORAPI: @pytest.mark.parametrize( "url,expected", [(None, False), ("http://jstor-api.com", True)] ) def test_enabled(self, url, expected): <|code_end|> . Use current file imports: (from unittest.mock import sentinel from via.requests_tools.headers...
assert JSTORAPI(sentinel.http, url).enabled == expected
Here is a snippet: <|code_start|> class TestJSTORAPI: @pytest.mark.parametrize( "url,expected", [(None, False), ("http://jstor-api.com", True)] ) def test_enabled(self, url, expected): assert JSTORAPI(sentinel.http, url).enabled == expected @pytest.mark.parametrize( "url,expect...
assert isinstance(factory(sentinel.context, pyramid_request), JSTORAPI)
Next line prediction: <|code_start|>"""Test that content is correctly served via Whitenoise.""" # pylint: disable=no-value-for-parameter # Pylint doesn't seem to understand h_matchers here for some reason class TestStaticContent: @pytest.mark.parametrize( "url,mime_type", ( ("/favic...
assert_cache_control(response.headers, ["public", "max-age=60"])
Next line prediction: <|code_start|> @pytest.mark.parametrize( "existing_header,expected_header", [ (None, "noindex, nofollow"), ("all", "all"), ], ) def test_it( self, existing_header, expected_header, handler, pyramid_request, tween ): if ...
return robots_tween_factory(handler, pyramid_request.registry)
Given the code snippet: <|code_start|> def test_settings_raise_value_error_if_environment_variable_is_not_set(): with pytest.raises(ValueError): load_settings({}) def test_settings_are_configured_from_environment_variables(os, pyramid_settings): expected_settings = pyramid_settings expected_set...
create_app()
Using the snippet: <|code_start|> def test_settings_raise_value_error_if_environment_variable_is_not_set(): with pytest.raises(ValueError): load_settings({}) def test_settings_are_configured_from_environment_variables(os, pyramid_settings): expected_settings = pyramid_settings expected_settings...
{"h_pyramid_sentry.filters": SENTRY_FILTERS}, **pyramid_settings
Given the code snippet: <|code_start|> class TestGetURLDetails: @pytest.mark.parametrize( "content_type,mime_type,status_code", ( ("text/html", "text/html", 501), ("application/pdf", "application/pdf", 200), ("application/pdf; qs=0.001", "application/pdf", 201), ...
result = get_url_details(http_service, url, headers=sentinel.headers)
Predict the next line after this snippet: <|code_start|> def test_request_is_valid_can_fail(self, service, pyramid_request): service._via_secure_url.verify.side_effect = TokenException assert not service.request_is_valid(pyramid_request) @pytest.mark.usefixtures("with_signed_urls_not_required"...
return SecureLinkService(secret="not_a_secret", signed_urls_required=True)
Predict the next line after this snippet: <|code_start|> def test_sign_url(self, service): result = service.sign_url(sentinel.url) service._via_secure_url.create.assert_called_once_with( sentinel.url, max_age=timedelta(hours=25) ) assert result == service._via_secure_url...
service = factory(sentinel.context, pyramid_request)
Next line prediction: <|code_start|> # pylint: disable=protected-access class TestHasSecureURLToken: def test_it_with_valid_token(self, view, pyramid_request, secure_link_service): secure_link_service.request_is_valid.return_value = True <|code_end|> . Use current file imports: (from datetime import t...
result = has_secure_url_token(view)(sentinel.context, pyramid_request)
Given the following code snippet before the placeholder: <|code_start|> "mime_type,is_pdf", [ ("application/x-pdf", True), ("application/pdf", True), ("text/html", False), ], ) def test_is_pdf(self, mime_type, is_pdf, svc): assert svc.is_pdf(mim...
return ViaClientService(via_client)
Based on the snippet: <|code_start|> @pytest.mark.parametrize( "mime_type,expected_content_type", [ ("application/pdf", "pdf"), ("text/html", "html"), (None, "html"), ], ) def test_url_for(self, mime_type, expected_content_type, svc, via_client): ...
service = factory(sentinel.context, pyramid_request)
Predict the next line for this snippet: <|code_start|> class TestStatusRoute: @pytest.mark.parametrize( "include_checkmate,checkmate_fails,expected_status,expected_body", [ (False, False, 200, {"status": "okay"}), (False, True, 200, {"status": "okay"}), (True, F...
result = get_status(pyramid_request)
Next line prediction: <|code_start|> @classmethod def _normalise_url(cls, url): """Return a normalized URL from user input. Take a URL from user input (eg. a URL input field or path parameter) and convert it to a normalized form. """ return Configuration.strip_from_url(...
raise BadURL(str(exc), url=url) from exc
Based on the snippet: <|code_start|> for param, options in PARAMETERS.items(): formatter = options.get("formatter", lambda v: v) value = settings[param] = formatter( settings.get(param, os.environ.get(param.upper())) ) if value is None and options.get("required"): ...
cache_buster = PathCacheBuster(static_path)
Here is a snippet: <|code_start|> if value is None and options.get("required"): raise ValueError(f"Param {param} must be provided.") # Configure sentry settings["h_pyramid_sentry.filters"] = SENTRY_FILTERS return settings def create_app(_=None, **settings): """Configure and return...
config.add_request_method(ViaCheckmateClient, reify=True, name="checkmate")
Continue the code snippet: <|code_start|> "checkmate_ignore_reasons": {}, "checkmate_allow_all": {"formatter": asbool}, "data_directory": {"required": True, "formatter": Path}, "signed_urls_required": {"formatter": asbool}, "enable_front_page": {"formatter": asbool}, "jstor_pdf_url": {}, } def ...
settings["h_pyramid_sentry.filters"] = SENTRY_FILTERS
Given the following code snippet before the placeholder: <|code_start|> class TestViewPDFAPI: @pytest.mark.usefixtures("checkmate_pass") def test_caching_is_disabled(self, test_app): response = test_app.get("/pdf?url=http://example.com/foo.pdf") <|code_end|> , predict the next line using imports from...
assert_cache_control(
Based on the snippet: <|code_start|> class TestCleanHeaders: def test_basics(self): headers = {"Most-Headers": "are passed through", "Preserving": "order"} result = clean_headers(headers) assert result == headers assert list(result.keys()) == ["Most-Headers", "Preserving"] ...
@pytest.mark.parametrize("header_name", BANNED_HEADERS)
Using the snippet: <|code_start|> class TestCleanHeaders: def test_basics(self): headers = {"Most-Headers": "are passed through", "Preserving": "order"} result = clean_headers(headers) assert result == headers assert list(result.keys()) == ["Most-Headers", "Preserving"] ...
@pytest.mark.parametrize("header_name,default_value", HEADER_DEFAULTS.items())
Using the snippet: <|code_start|> headers = {"Most-Headers": "are passed through", "Preserving": "order"} result = clean_headers(headers) assert result == headers assert list(result.keys()) == ["Most-Headers", "Preserving"] assert isinstance(result, OrderedDict) # For the f...
@pytest.mark.parametrize("header_name,mapped_name", HEADER_MAP.items())
Predict the next line for this snippet: <|code_start|> # wise we just end-up copy pasting them here to no real benefit @pytest.mark.parametrize("header_name", BANNED_HEADERS) def test_we_remove_banned_headers(self, header_name): result = clean_headers({header_name: "value"}) assert header_n...
headers = add_request_headers({"X-Existing": "existing"})
Based on the snippet: <|code_start|> class TestCleanHeaders: def test_basics(self): headers = {"Most-Headers": "are passed through", "Preserving": "order"} <|code_end|> , predict the immediate next line with the help of imports: from collections import OrderedDict from via.requests_tools.headers import...
result = clean_headers(headers)
Given the code snippet: <|code_start|>"""Views for debugging.""" @view.view_config(route_name="debug_headers") def debug_headers(_context, request): """Dump the headers as we receive them for debugging.""" if request.GET.get("raw"): headers = OrderedDict(request.headers) else: <|code_end|> , g...
headers = clean_headers(request.headers)
Using the snippet: <|code_start|> class TestProxy: def test_it( self, context, pyramid_request, get_url_details, via_client_service, http_service, ): url = context.url_from_path.return_value = "/https://example.org?a=1" result = proxy(context, ...
return create_autospec(PathURLResource, spec_set=True, instance=True)
Based on the snippet: <|code_start|> class TestProxy: def test_it( self, context, pyramid_request, get_url_details, via_client_service, http_service, ): url = context.url_from_path.return_value = "/https://example.org?a=1" <|code_end|> , predict the im...
result = proxy(context, pyramid_request)
Given snippet: <|code_start|> "via.client.ignoreOtherConfiguration": "1", "via.client.openSidebar": "1", "via.external_link_mode": "new-tab", } @pytest.mark.usefixtures("html_response", "checkmate_pass") def test_proxy_html(self, test_app): target_url = "http://example.com" ...
assert_cache_control(
Given the following code snippet before the placeholder: <|code_start|> ): google_drive_api.parse_file_url.return_value = None pyramid_request.params["jstor.ip"] = "1.1.1.1" pdf_url = svc.get_pdf_url("jstor://DOI") secure_link_service.sign_url.assert_called_once_with( "h...
return PDFURLBuilder(
Predict the next line for this snippet: <|code_start|> class TestNGINXSigner: def test_it( self, svc, quantized_expiry, ): signed_url = svc.sign_url( "https://example.com/foo/bar.pdf?q=s", "/proxy/static/" ) quantized_expiry.assert_called_once_with...
return _NGINXSigner(
Based on the snippet: <|code_start|> @pytest.fixture def svc( self, google_drive_api, secure_link_service, pyramid_request, PatchedNGINXSigner, jstor_api, ): return PDFURLBuilder( pyramid_request, google_drive_api, js...
svc = factory(sentinel.context, pyramid_request)
Here is a snippet: <|code_start|> class TestPathCacheBuster: EXPECTED_HASH = "606e8d07c0af18c736c272a592038742" def test_salt_is_generated_from_dir_hash(self, cache_buster): assert cache_buster.salt == self.EXPECTED_HASH def test_salt_changes_on_new_file(self, static_dir): new_file = st...
assert PathCacheBuster(static_dir).salt != self.EXPECTED_HASH
Here is a snippet: <|code_start|> class TestRequestBasedException: @pytest.mark.parametrize( "error_params,expected_string", ( ( { "status_code": 400, "reason": "Bad request", "json_data": {"test": "data", "more"...
"message", requests_err=make_requests_exception(HTTPError, **error_params)
Continue the code snippet: <|code_start|> class TestRequestBasedException: @pytest.mark.parametrize( "error_params,expected_string", ( ( { "status_code": 400, "reason": "Bad request", "json_data": {"test": "data...
exception = RequestBasedException(
Here is a snippet: <|code_start|> class TestIndexViews: def test_get(self, views): assert views.get() == {} def test_post(self, views, pyramid_request): pyramid_request.params["url"] = "//site.org?q1=value1&q2=value2" redirect = views.post() assert isinstance(redirect, HTTPF...
assert redirect == temporary_redirect_to(
Given the code snippet: <|code_start|> assert redirect == temporary_redirect_to( pyramid_request.route_url(route_name="index") ) def test_post_raises_if_url_invalid(self, views, pyramid_request): # Set a `url` that causes `urlparse` to throw. pyramid_request.params["url"]...
return QueryURLResource(pyramid_request)
Based on the snippet: <|code_start|> class TestIndexViews: def test_get(self, views): assert views.get() == {} def test_post(self, views, pyramid_request): pyramid_request.params["url"] = "//site.org?q1=value1&q2=value2" redirect = views.post() assert isinstance(redirect, HTT...
with pytest.raises(BadURL):
Using the snippet: <|code_start|> assert "url" not in pyramid_request.params redirect = views.post() assert redirect == temporary_redirect_to( pyramid_request.route_url(route_name="index") ) def test_post_raises_if_url_invalid(self, views, pyramid_request): # Se...
return IndexViews(context, pyramid_request)
Predict the next line after this snippet: <|code_start|> @pytest.mark.parametrize( "url,expected_redirect_location", [ # When you submit the form on the front page it redirects you to the # page that will proxy the URL that you entered. ( "https://example.com/foo/", ...
assert response == temporary_redirect_to(expected_redirect_location)
Here is a snippet: <|code_start|> DEFAULT_ERROR_MAP = { exceptions.MissingSchema: BadURL, exceptions.InvalidSchema: BadURL, exceptions.InvalidURL: BadURL, exceptions.URLRequired: BadURL, exceptions.Timeout: UpstreamTimeout, exceptions.ConnectionError: UpstreamServiceError, exceptions.TooMan...
RequestException: UnhandledUpstreamException,
Continue the code snippet: <|code_start|> DEFAULT_ERROR_MAP = { exceptions.MissingSchema: BadURL, exceptions.InvalidSchema: BadURL, exceptions.InvalidURL: BadURL, exceptions.URLRequired: BadURL, exceptions.Timeout: UpstreamTimeout, <|code_end|> . Use current file imports: import requests from requ...
exceptions.ConnectionError: UpstreamServiceError,
Given the code snippet: <|code_start|> DEFAULT_ERROR_MAP = { exceptions.MissingSchema: BadURL, exceptions.InvalidSchema: BadURL, exceptions.InvalidURL: BadURL, exceptions.URLRequired: BadURL, <|code_end|> , generate the next line using the imports in this file: import requests from requests import Req...
exceptions.Timeout: UpstreamTimeout,
Given the following code snippet before the placeholder: <|code_start|> sids : list of values representing simulated internal sids start : start date delta : timedelta between internal events filter : filter to remove the sids """ def __init__(self, data, **kwargs): """ Data...
self.arg_string = hash_args(data, **kwargs)
Based on the snippet: <|code_start|> class DataSource(object): __metaclass__ = ABCMeta @property def event_type(self): <|code_end|> , predict the immediate next line with the help of imports: from abc import ( ABCMeta, abstractproperty ) from alephnull.protocol import DATASOURCE_TYPE from aleph...
return DATASOURCE_TYPE.TRADE
Using the snippet: <|code_start|> """ An iterator that yields the raw datasource, in chronological order of data, one event at a time. """ NotImplemented @abstractproperty def instance_hash(self): """ A hash that represents the unique args to the source. ...
yield Event(self.apply_mapping(row))
Predict the next line for this snippet: <|code_start|># # Copyright 2013 Quantopian, Inc. # # 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 # ...
trade.type = DATASOURCE_TYPE.TRADE
Given snippet: <|code_start|> if self.event_list is not None: # If event_list is provided, extract parameters from there # This isn't really clean and ultimately I think this # class should serve a single purpose (either take an # event_list or autocreate events)....
self.arg_string = hash_args(*args, **kwargs)
Given the following code snippet before the placeholder: <|code_start|> Factory method for self.sid_windows. """ return MovingStandardDevWindow( self.market_aware, self.window_length, self.delta ) def update(self, event): """ Update...
class MovingStandardDevWindow(EventWindow):
Based on the snippet: <|code_start|># # Copyright 2013 Quantopian, Inc. # # 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 ...
__metaclass__ = TransformMeta
Based on the snippet: <|code_start|> This is intended to be wrapped in a partial, so that the slippage and commission models can be enclosed. """ for order, transaction in slippage(event, open_orders): if ( transaction and not zp_math.tolerant_equals(transaction.amount...
self.type = DATASOURCE_TYPE.TRANSACTION
Using the snippet: <|code_start|># you can use a TradingEnvironment in a with clause: # lse = TradingEnvironment(bm_index="^FTSE", exchange_tz="Europe/London") # with lse: # # the code here will have lse as the global trading.environment # algo.run(start, end) # # User code will not norm...
load = load_market_data
Predict the next line for this snippet: <|code_start|> self.fields, self.market_aware, self.window_length, self.delta ) def update(self, event): """ Update the event window for this event's sid. Return a dict from tracked fields to mov...
class MovingAverageEventWindow(EventWindow):
Given the following code snippet before the placeholder: <|code_start|># # Copyright 2013 Quantopian, Inc. # # 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/licens...
__metaclass__ = TransformMeta
Next line prediction: <|code_start|># # Copyright 2013 Quantopian, Inc. # # 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 ...
treasury_curves = trading.environment.treasury_curves
Continue the code snippet: <|code_start|>try: except: #Replace this with source to multiplier get_multiplier = lambda x: 25 log = logbook.Logger('Performance') class FuturesPerformancePeriod(object): def __init__( self, starting_cash, period_open=None, peri...
self.positions = positiondict()