Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Next line prediction: <|code_start|> def url(self, route="/", query={}, **route_args): """Returns the URL of the remote Igord server with the given route """ _route = route if route_args: _route = re.sub("<([^>:]*)(:[^>]*)?>", "{\\1}", _route) _route = _route....
return self.route_request(routes.jobs)
Given snippet: <|code_start|> self.filename = filename self.size = size self.format = format class Layout(DiskImage): ''' An image specififcation for a VMHost. This are actually params for truncate and parted. Parameters ---------- size : int-like Size in GB ...
self.filename = run("mktemp --tmpdir='%s' 'vmimage-XXXX.img'" %
Predict the next line for this snippet: <|code_start|> def follow_events(server, port): r = redis.Redis(host=server, port=int(port)) p = r.pubsub() p.subscribe(common.REDIS_EVENTS_PUBSUB_CHANNEL_NAME) for obj in p.listen(): event = None xmlstr = str(obj["data"]).strip() if not x...
xsltfile = reports.TRANSFORM_MAP["job-junit"]
Continue the code snippet: <|code_start|># # Copyright (C) 2013 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation; either version 2.1 of the License, or # (at your option) a...
p.subscribe(common.REDIS_EVENTS_PUBSUB_CHANNEL_NAME)
Next line prediction: <|code_start|> """Returns the source of this testcase """ src = None with open(self.filename, "r") as f: src = f.read() return src def __str__(self): return "%s (%s, %s)" % (self.name, self.filename, self.timeout) def __to_dict__...
run("chmod -R a+X '%s'" % self.dirname)
Using the snippet: <|code_start|> self.variables["planid"] = self.id logger.debug("Replacing vars in spec %s: %s" % (self.name, self.variables)) for layout in self.job_layouts: """A generator is used (yield), because a followup s...
update_properties_only(item, kwargs)
Predict the next line after this snippet: <|code_start|> job = self.__igorapi().job(_args.sessionid) def job_reportxml_cb(updated_sessiondid): if updated_sessiondid == _args.sessionid: # Only update screen if "our" job changed return job.report_junit() ...
builder = junitless.LogBuilder()
Continue the code snippet: <|code_start|> _args = self._parse_do_args("watch_testplan", line, pargs) testplan = self.__igorapi().testplan(_args.testplanname) def job_reportxml_cb(updated_sessiondid): return testplan.report_junit() return self.watch_events(job_reportxml_cb) ...
for ev in event.follow_events(remote, event_port):
Using the snippet: <|code_start|> return True def do_env(self, args): """env Get environment variables """ env = self.ctx.__dict__ print("\n".join("%s: %s" % i for i in env.items())) print("(%d variables)" % len(env)) def _parse_do_args(self, prog, line, ...
return IgordAPI(remote, port)
Using the snippet: <|code_start|> if category == "host": origins += [("files", HostsOrigin(CONFIG["hosts"]["paths"]))] return origins class Host(main.Host): """Represents a real server. Wich is currently just specified by a name and it's MAC address. """ name = No...
(self.get_name(), utils.run(self.poweron_script)))
Continue the code snippet: <|code_start|> logger = log.getLogger(__name__) def initialize_origins(category, CONFIG): origins = [] superorigin = TestDraftSuperOrigin(tempfile.mkdtemp()) if category == "testplan": origins += [("draft-files", superorigin.get_testplans_origin(...
class Host(main.Host):
Given snippet: <|code_start|># # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of t...
run("pvcreate -ff -y -v '%s'" % dev)
Given the code snippet: <|code_start|> class ConfigParser: ''' Class that contains functions to constuct the config map from the config file ''' configContent={} def __init__(self,fileName): ''' constructor that generates the map of the config file @param fileName: file conta...
configFile=FileCacheManager(fileName)
Given the code snippet: <|code_start|> print "algo=", algo data1 = fileToTuples(infile1,delimiter) data2 = fileToTuples(infile2,delimiter) if algo == 'toposort': #dependency verification as multiple topo ordering possible depen_map = dict() for entry in data1: vid = int(entry[0]) val = int(en...
if(CommonDefs.INT_MAX in data1[i] or CommonDefs.INT_MAX in data2[i]):
Continue the code snippet: <|code_start|> #!/usr/bin/python def main(argv): inputfile = '' outputfile = '' print inputfile, outputfile try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print 'test.py -i <inputfile> -o <outputfile>' sys.exit(2) for o...
grail=Grail(inputfile)
Based on the snippet: <|code_start|> PKEY_FILENAME = os.path.sep.join([os.path.dirname(__file__), 'unit_test_key']) PUB_FILE = "%s.pub" % (PKEY_FILENAME,) class SSH2TestCase(unittest.TestCase): @classmethod def setUpClass(cls): _mask = int('0600') if version_info <= (2,) else 0o600 os.chmod...
cls.server = OpenSSHServer()
Given snippet: <|code_start|> cpython = platform.python_implementation() == 'CPython' try: except ImportError: USING_CYTHON = False else: USING_CYTHON = True ON_RTD = os.environ.get('READTHEDOCS') == 'True' SYSTEM_LIBSSH2 = bool(os.environ.get('SYSTEM_LIBSSH2', 0)) or ON_RTD # Only build libssh if running...
build_ssh2()
Given snippet: <|code_start|> login_manager = LoginManager() @login_manager.user_loader def load_user(user_id): <|code_end|> , continue by predicting the next line. Consider current file imports: from flask_login import LoginManager from websitemixer.models import User and context: # Path: websitemixer/models.py # ...
return User.get_by_id(user_id)
Here is a snippet: <|code_start|> def first_paragraph(content=""): # take content and return just the first <p></p> content, # used in blog loop template soup = BeautifulSoup(content, "html.parser") thespan = soup.find('p') if thespan is None: return '' else: return thespan.stri...
check = User.query.filter_by(id=session['user_id']).first()
Given snippet: <|code_start|>""" This module is used to translate Events from Marathon's EventBus system. See: * https://mesosphere.github.io/marathon/docs/event-bus.html * https://github.com/mesosphere/marathon/blob/master/src/main/scala/mesosphere/marathon/core/event/Events.scala """ <|code_end|> , continue by pre...
class MarathonEvent(MarathonObject):
Using the snippet: <|code_start|>""" This module is used to translate Events from Marathon's EventBus system. See: * https://mesosphere.github.io/marathon/docs/event-bus.html * https://github.com/mesosphere/marathon/blob/master/src/main/scala/mesosphere/marathon/core/event/Events.scala """ class MarathonEvent(Marath...
'health_check': MarathonHealthCheck,
Next line prediction: <|code_start|>""" This module is used to translate Events from Marathon's EventBus system. See: * https://mesosphere.github.io/marathon/docs/event-bus.html * https://github.com/mesosphere/marathon/blob/master/src/main/scala/mesosphere/marathon/core/event/Events.scala """ class MarathonEvent(Mar...
'ip_address': MarathonIpAddress,
Based on the snippet: <|code_start|>""" This module is used to translate Events from Marathon's EventBus system. See: * https://mesosphere.github.io/marathon/docs/event-bus.html * https://github.com/mesosphere/marathon/blob/master/src/main/scala/mesosphere/marathon/core/event/Events.scala """ class MarathonEvent(Mar...
'plan': MarathonDeploymentPlan,
Continue the code snippet: <|code_start|> :param str version: version id :param str affected_pods: list of strings """ def __init__(self, affected_apps=None, current_actions=None, current_step=None, id=None, steps=None, total_steps=None, version=None, affected_pods=None): self.a...
class MarathonDeploymentAction(MarathonObject):
Using the snippet: <|code_start|> self.steps = [self.parse_deployment_step(step) for step in (steps or [])] self.total_steps = total_steps self.version = version self.affected_pods = affected_pods def parse_deployment_step(self, step): if step.__class__ == dict: #...
self.app = assert_valid_path(app)
Given the code snippet: <|code_start|> class MarathonEventTest(unittest.TestCase): def test_event_factory(self): self.assertEqual( <|code_end|> , generate the next line using the imports in this file: from marathon.models.events import EventFactory, MarathonStatusUpdateEvent from marathon.models.task imp...
set(EventFactory.event_to_class.keys()),
Given snippet: <|code_start|> class MarathonEventTest(unittest.TestCase): def test_event_factory(self): self.assertEqual( set(EventFactory.event_to_class.keys()), set(EventFactory.class_to_event.values()), ) def test_marathon_event(self): """Test that we can pro...
expected_event = MarathonStatusUpdateEvent(
Using the snippet: <|code_start|> "slaveId": "slave-01", "taskId": "task-01", "taskStatus": "TASK_RUNNING", "message": "Some message", "appId": "/foo/bar", "host": "host-01", "ipAddresses": [ {"ip_address": "127.0.0.1", "...
MarathonIpAddress(ip_address="127.0.0.1", protocol="tcp"),
Based on the snippet: <|code_start|> class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, ...
obj = MarathonObject()
Here is a snippet: <|code_start|> class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, ...
obj = MarathonResource()
Predict the next line after this snippet: <|code_start|> def _apply_on_pairs(f): # this strategy is used to have the assertion stack trace # point to the right pair of strings in case of test failure f('foo', 'foo') f('foo42', 'foo42') f('fooBar', 'foo_bar') f('f0o42Bar', 'f0o42_bar') f('fo...
assert to_camel_case(snake) == camel
Next line prediction: <|code_start|> def _apply_on_pairs(f): # this strategy is used to have the assertion stack trace # point to the right pair of strings in case of test failure f('foo', 'foo') f('foo42', 'foo42') f('fooBar', 'foo_bar') f('f0o42Bar', 'f0o42_bar') f('fooBarBaz', 'foo_bar_b...
assert to_snake_case(camel) == snake
Continue the code snippet: <|code_start|> def _apply_on_pairs(f): # this strategy is used to have the assertion stack trace # point to the right pair of strings in case of test failure f('foo', 'foo') f('foo42', 'foo42') f('fooBar', 'foo_bar') f('f0o42Bar', 'f0o42_bar') f('fooBarBaz', 'foo_b...
assert to_datetime("2017-09-28T00:31:55Z") == datetime(2017, 9, 28, 0, 31, 55, tzinfo=timezone.utc)
Next line prediction: <|code_start|> class MarathonObject: """Base Marathon object.""" def __repr__(self): return "{clazz}::{obj}".format(clazz=self.__class__.__name__, obj=self.to_json(minimal=False)) def __eq__(self, other): try: return self.__dict__ == other.__dict__ ...
return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)}
Given snippet: <|code_start|> def __eq__(self, other): try: return self.__dict__ == other.__dict__ except Exception: return False def __hash__(self): # Technically this class shouldn't be hashable because it often # contains mutable fields, but in practice...
return cls(**{to_snake_case(k): v for k, v in attributes.items()})
Next line prediction: <|code_start|> def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict """ if minimal: ...
return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True)
Continue the code snippet: <|code_start|> return hash(self.to_json()) def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: di...
return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True)
Given snippet: <|code_start|> def test_400_error(): fake_response = requests.Response() fake_message = "Invalid JSON" fake_details = [{"path": "/taskKillGracePeriodSeconds", "errors": ["error.expected.jsnumber"]}] fake_response._content = json.dumps({"message": fake_message, "details": fake_details})...
exc = MarathonHttpError(fake_response)
Based on the snippet: <|code_start|> def test_400_error(): fake_response = requests.Response() fake_message = "Invalid JSON" fake_details = [{"path": "/taskKillGracePeriodSeconds", "errors": ["error.expected.jsnumber"]}] fake_response._content = json.dumps({"message": fake_message, "details": fake_det...
exc = InternalServerError(fake_response)
Continue the code snippet: <|code_start|> def __init__(self, app_id=None, health_check_results=None, host=None, id=None, ports=None, service_ports=None, slave_id=None, staged_at=None, started_at=None, version=None, ip_addresses=[], state=None, local_volumes=None, region=None, zone=...
class MarathonIpAddress(MarathonObject):
Given the following code snippet before the placeholder: <|code_start|> :param staged_at: when this task was staged :type staged_at: datetime or str :param started_at: when this task was started :type started_at: datetime or str :param str version: app version with which this task was started :ty...
self.staged_at = to_datetime(staged_at)
Predict the next line after this snippet: <|code_start|> class MarathonGroupTest(unittest.TestCase): def test_from_json_parses_root_group(self): data = { "id": "/", "groups": [ {"id": "/foo", "apps": []}, {"id": "/bla", "a...
group = MarathonGroup().from_json(data)
Predict the next line after this snippet: <|code_start|> class MarathonDeploymentTest(unittest.TestCase): def test_env_defaults_to_empty_dict(self): """ é testé """ deployment_json = { "id": "ID", "version": "2020-05-30T07:35:04.695Z", ...
deployment = MarathonDeployment.from_json(deployment_json)
Next line prediction: <|code_start|> class MarathonContainer(MarathonObject): """Marathon health check. See https://mesosphere.github.io/marathon/docs/native-docker.html :param docker: docker field (e.g., {"image": "mygroup/myimage"})' :type docker: :class:`marathon.models.container.MarathonDockerCo...
raise InvalidChoiceError('type', type, self.TYPES)
Given the code snippet: <|code_start|> :type http_config: :class:`marathon.models.info.MarathonHttpConfig` or dict :param event_subscriber: :type event_subscriber: :class`marathon.models.info.MarathonEventSubscriber` or dict :param bool elected: :param str buildref: """ def __init__(self, ev...
class MarathonConfig(MarathonObject):
Predict the next line after this snippet: <|code_start|> if atomic_species is not None: new_atomic_species = set(dataset.get('atomicSpecies', {})) new_atomic_species.update(atomic_species) if atomic_species is not None: updates.setdefault('$set', {})['atomicSpe...
atomic_number = ELEMENT_SYMBOLS_LOWER.index(element.lower())
Continue the code snippet: <|code_start|> for s in species: if len(s) <= _chars_left(): prefix.append(s) prefix += ['X'] * _chars_left() return ''.join(prefix) def _generate_mdb_id_postfix(self, prefix): # Search for existing datasets with this prefix ...
species = [ELEMENT_SYMBOLS[n] for n in species]
Using the snippet: <|code_start|> elif "rdf" in bits[0]: return "rdf_" + bits[1] elif "model-qualifiers" in bits[0]: return "bqmodel_" + bits[1] elif "biology-qualifiers" in bits[0]: return "bqbiol_" + bits[1] else: return "%s:%s" % (bits[0], bits[1]) class LEMSXMLNode: ...
class LEMSFileParser(LEMSBase):
Next line prediction: <|code_start|> if tag == "": t = node.ltag else: t = tag.lower() for child in node.children: self.xml_node_stack = [child] + self.xml_node_stack ctagl = child.ltag if ctagl in self.tag_parse_table and ctagl in se...
raise ParseError(
Predict the next line after this snippet: <|code_start|> component = Component(id_, type_) if self.current_component: component.set_parent_id(self.current_component.id) self.current_component.add_child(component) else: self.model.add_component(component) ...
id_ = make_id()
Given the code snippet: <|code_start|>""" Simulation. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> , generate the next line using the imports in this file: from lems.base.base import LEMSBase from lems.base.errors import SimError import heapq and context...
class Simulation(LEMSBase):
Based on the snippet: <|code_start|> debug = False def __init__(self): """ Constructor. """ self.runnables = {} """ Dictionary of runnable components in this simulation. :type: dict(string -> lems.sim.runnable.Runnable) """ self.run_queue = [] "...
raise SimError("Duplicate runnable component {0}".format(runnable.id))
Next line prediction: <|code_start|>""" Simulation specification classes. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> . Use current file imports: (from lems.base.base import LEMSBase from lems.base.errors import ModelError from lems.base.map import Map) ...
class Run(LEMSBase):
Predict the next line after this snippet: <|code_start|> def add_event_writer(self, event_writer): """ Adds an event writer to this simulation section. :param event_writer: event writer to be added. :type event_writer: lems.model.simulation.EventWriter """ self.event...
raise ModelError("Unsupported child element")
Given the following code snippet before the placeholder: <|code_start|> self.format = format """ Text parameter to be used for the format :type: string """ def toxml(self): """ Exports this object into a LEMS XML object """ return '<EventWriter path="{0}" fi...
self.runs = Map()
Continue the code snippet: <|code_start|>""" Dimension and Unit definitions in terms of the fundamental SI units. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> . Use current file imports: from lems.base.base import LEMSBase and context (classes, functions,...
class Include(LEMSBase):
Here is a snippet: <|code_start|>""" Base class for runnable components. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ # import math # class Ex1(Exception): # pass # def exp(x): # try: # return math.exp(x) # except Exception as e: # print('ERROR...
class Reflective(LEMSBase):
Predict the next line after this snippet: <|code_start|>class Regime: def __init__(self, name): self.name = name self.update_state_variables = None self.update_derived_variables = None self.run_startup_event_handlers = None self.run_preprocessing_event_handlers = None ...
self.state_stack = Stack()
Predict the next line for this snippet: <|code_start|> def add_child_typeref(self, typename, runnable): self.__dict__[typename] = runnable def add_child_to_group(self, group_name, child): # print("add_child_to_group in %s; grp: %s; child: %s "%(self.id, group_name, child)) if group_name ...
raise SimBuildError(
Given the code snippet: <|code_start|> if child in self.children: childobj = self.children[child] if idx == -1: childobj.add_variable_recorder2( data_output, recorder, new_path, full_path ) else: ...
Recording(path, full_path, data_output, recorder)
Continue the code snippet: <|code_start|> model = lems.Model() model.add(lems.Dimension("voltage", m=1, l=3, t=-3, i=-1)) model.add(lems.Dimension("time", t=1)) model.add(lems.Dimension("capacitance", m=-1, l=-2, t=4, i=2)) model.add(lems.Unit("milliVolt", "mV", "voltage", -3)) model.add(lems.Unit("milliSecond", "ms"...
validate_lems(fn)
Given the following code snippet before the placeholder: <|code_start|>""" Map class. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> , predict the next line using imports from the current file: from lems.base.base import LEMSBase and context including class...
class Map(dict, LEMSBase):
Using the snippet: <|code_start|> iaf1.add(lems.Parameter("threshold", "voltage")) iaf1.add(lems.Parameter("reset", "voltage")) iaf1.add(lems.Parameter("refractoryPeriod", "time")) iaf1.add(lems.Parameter("capacitance", "capacitance")) iaf1.add(lems.Exposure("vexp", "voltage")) dp = lems.DerivedParameter("range", "thre...
validate_lems(fn)
Given the code snippet: <|code_start|> """<Lems> <!-- regression test data for https://github.com/LEMS/pylems/issues/20 --> <Target component="sim1"/> <Include file="Simulation.xml"/> <Include file="Cells.xml"/> <Include file="{}"/> <Simulation id="sim1" leng...
lems_run(xml_file.name, include_dirs=[coretype_files_dir])
Given the following code snippet before the placeholder: <|code_start|> iaf1.add(lems.Parameter("threshold", "voltage")) iaf1.add(lems.Parameter("reset", "voltage")) iaf1.add(lems.Parameter("refractoryPeriod", "time")) iaf1.add(lems.Parameter("capacitance", "capacitance")) iaf1.add(lems.Exposure("vexp", "voltage")) dp ...
validate_lems(fn)
Based on the snippet: <|code_start|>""" Stack class. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> , predict the immediate next line with the help of imports: from lems.base.base import LEMSBase from lems.base.errors import StackError and context (classes,...
class Stack(LEMSBase):
Using the snippet: <|code_start|> self.stack = [] """ List used to store the stack contents. :type: list """ def push(self, val): """ Pushed a value onto the stack. :param val: Value to be pushed. :type val: * """ self.stack = [val] + self.s...
raise StackError("Stack empty")
Predict the next line after this snippet: <|code_start|>""" Recording class(es). :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> using the current file's imports: from lems.base.base import LEMSBase and any relevant context from other files: # Path: lems/b...
class Recording(LEMSBase):
Given snippet: <|code_start|>""" Expression parser :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ known_functions = [ "exp", "log", "sqrt", "sin", "cos", "tan", "sinh", "cosh", "tanh", "abs", "ceil", "factorial", "random"...
class ExprNode(LEMSBase):
Given the code snippet: <|code_start|> print( "4> op stack: %s, val stack: %s, node stack: %s" % (self.op_stack, self.val_stack, self.node_stack) ) if self.debug: print("<<<<< Depth: %s, returning: %s" % (ExprParser.depth, ret)) ExprPars...
self.op_stack = Stack()
Based on the snippet: <|code_start|>""" Structural properties of component types. :author: Gautham Ganapathy :organization: LEMS (https://github.com/organizations/LEMS) """ <|code_end|> , predict the immediate next line with the help of imports: from lems.base.base import LEMSBase from lems.base.map import Map fro...
class With(LEMSBase):
Given the following code snippet before the placeholder: <|code_start|> self.event_connections.append(ec) def toxml(self): """ Exports this object into a LEMS XML object """ chxmlstr = "" for event_connection in self.event_connections: chxmlstr += event_...
self.withs = Map()
Continue the code snippet: <|code_start|> self.assignments = [] """ List of assignments included in MultiInstantiate. :type: list(Assign) """ def __eq__(self, o): if self.component: flag = self.component == o.component and self.number == o.number else: ...
raise ModelError("Unsupported child element")
Given the following code snippet before the placeholder: <|code_start|> DIRECTORIES = [ 'build', 'buildtools', 'mojo', # TODO(kjellander): Remove, see webrtc:5629. 'native_client', 'net', 'testing', 'third_party/binutils', 'third_party/drmemory', 'third_party/instrumented_libraries', 'third_party/l...
target_os = get_target_os_list()
Here is a snippet: <|code_start|> class EventAdmin(admin.ModelAdmin): list_display = ['title', 'start', 'end', 'slug'] date_hierarchy = 'start' list_filter = ('source',) class SourceAdmin(admin.ModelAdmin): list_display = ['name', 'url', 'is_active'] list_filter = ['is_active'] <|code_end|> . ...
admin.site.register(Event, EventAdmin)
Predict the next line after this snippet: <|code_start|> class EventAdmin(admin.ModelAdmin): list_display = ['title', 'start', 'end', 'slug'] date_hierarchy = 'start' list_filter = ('source',) class SourceAdmin(admin.ModelAdmin): list_display = ['name', 'url', 'is_active'] list_filter = ['is_act...
admin.site.register(Source, SourceAdmin)
Based on the snippet: <|code_start|> item = models.NewsItem() item.title = ('123456789 123456789 123456789 123456789 123456789 ' '123456789 123456789 123456789 123456789 123456789 ' '123456789 123456789 123456789 123456789') self.assertEquals(item.as_tw...
news_tags.news_url(item))
Predict the next line for this snippet: <|code_start|> urlpatterns = patterns('', url(r'^(?:(?P<year>\d{4})/(?:(?P<month>\d{2})/(?:(?P<day>\d{2})/)?)?)?$', news_list, name='news_list'), # url(r'^(?:(?P<year>\d{4})/)?$', news_list, # name='news_list'), <|code_end|> with the help of current fil...
url(r'^(?P<slug>.*)-(?P<pk>.*)/$', news_detail, name='news_detail'),
Here is a snippet: <|code_start|>""" zeusproject.testsuite.tests ~~~~~~~~~~~~~~~~~~~~~~ Who tests the tests? :copyright: (c) 2016 by the Lab804 Team. :license: BSD, see LICENSE for more details. """ @pytest.mark.test_module class TestModule(): """Testing Module.""" project_f = os.path.jo...
module = commands.Module(name_project=project_f,
Using the snippet: <|code_start|>np.random.seed(1) ## observation points ##################################################################### pos_geo = np.array([[-83.74,42.28,0.0], [-83.08,42.33,0.0], [-83.33,41.94,0.0]]) Nx = len(pos_geo) bm = make_basemap(pos_geo[:,0],pos_...
start_time = mjd('2015-07-01','%Y-%m-%d')
Using the snippet: <|code_start|>dzdxdt = dzdx[None,:]*b[:,None] dudydt = dudy[None,:]*b[:,None] dvdydt = dvdy[None,:]*b[:,None] dzdydt = dzdy[None,:]*b[:,None] # add noise su = 0.0005*np.ones((Nt,Nx)) sv = 0.0005*np.ones((Nt,Nx)) sz = 0.0005*np.ones((Nt,Nx)) u += np.random.normal(0.0,su) v += np.random.normal(0.0,sv...
text_from_dict('data.csv',data)
Given the code snippet: <|code_start|>np.random.seed(1) ## observation points ##################################################################### pos_geo = np.array([[-83.74,42.28,0.0], [-83.08,42.33,0.0], [-83.33,41.94,0.0]]) Nx = len(pos_geo) <|code_end|> , generate the ne...
bm = make_basemap(pos_geo[:,0],pos_geo[:,1])
Next line prediction: <|code_start|> def check_unique_stations(data): ''' makes sure each station id is unique ''' unique_ids = list(set(data['id'])) if len(data['id']) != len(unique_ids): # there are duplicate stations, now find them duplicates = [] for i in unique_ids: if sum(data[...
duplicates += [mjd_inv(i,'%Y-%m-%d')]
Given the code snippet: <|code_start|># This script generates the synthetic data file data.csv np.random.seed(1) def make_data(pos,times): ''' 1 microstrain per year = 3 * 10^-9 strain per day ''' ms = 2.737e-9 x,y = pos.T _,xg = np.meshgrid(times,x,indexing='ij') tg,yg = np.meshgrid(times,y,indexing...
bm = make_basemap(lon,lat)
Predict the next line after this snippet: <|code_start|># This script generates the synthetic data file data.csv np.random.seed(1) def make_data(pos,times): ''' 1 microstrain per year = 3 * 10^-9 strain per day ''' ms = 2.737e-9 x,y = pos.T _,xg = np.meshgrid(times,x,indexing='ij') tg,yg = np.meshgri...
start_date = mjd('2000-01-01','%Y-%m-%d')
Continue the code snippet: <|code_start|>lon = np.array([-83.3,-82.75,-85.26,-83.36]) lat = np.array([42.31,42.91,45.20,42.92]) id = np.array(['STA1','STA2','STA3','STA4']) bm = make_basemap(lon,lat) x,y = bm(lon,lat) xy = np.array([x,y]).T start_date = mjd('2000-01-01','%Y-%m-%d') stop_date = mjd('2000-02-01','%Y-%m-%...
text_from_dict('data.csv',data)
Given snippet: <|code_start|> # CALL THIS AFTER *_init_image* # if len(self.data_sets) < 2: self.scatter = None return sm = ScalarMappable(norm=self.cbar.norm,cmap=self.cbar.get_cmap()) # use scatter points to show z for second data set colors = sm.to_rgba(self.data_sets[1][self.ti...
q = Quiver(self.map_ax,self.x[:,0],self.x[:,1],
Continue the code snippet: <|code_start|>def mat32(sigma,cls): ''' Matern covariance function with nu=3/2 ''' return gauss.gpiso(rbf.basis.mat32,(0.0,sigma**2,cls),dim=2) def mat52(sigma,cls): ''' Matern space covariance function with nu=5/2 ''' return gauss.gpiso(rbf.basis.mat52,(0.0,sigma**2,cls),...
@set_units(['mm','yr','km'])
Continue the code snippet: <|code_start|> def wen32(sigma,cls): ''' Wendland space covariance function ''' return gauss.gpiso(rbf.basis.wen32,(0.0,sigma**2,cls),dim=2) def spwen32(sigma,cls): ''' Sparse Wendland space covariance function ''' return gauss.gpiso(rbf.basis.spwen32,(0.0,sigma**2,cls),d...
return kernel_product(tgp,sgp)
Given the code snippet: <|code_start|> return gauss.gpiso(rbf.basis.mat52,(0.0,sigma**2,cls),dim=2) def wen32(sigma,cls): ''' Wendland space covariance function ''' return gauss.gpiso(rbf.basis.wen32,(0.0,sigma**2,cls),dim=2) def spwen32(sigma,cls): ''' Sparse Wendland space covariance function ''...
tgp = gpstation.se(sigma,cts,convert=False)
Next line prediction: <|code_start|> # matrix dense out = np.zeros((N1,N2)) out[rows,cols] = data else: # otherwise make it csc sparse out = sp.csc_matrix((data,(rows,cols)),(N1,N2),dtype=float) if N1 > chunk_size: logger.debug( 'Building covariance matrix ...
args = [a*conv(u,time='day',space='m') for a,u in zip(args,units)]
Using the snippet: <|code_start|>''' Module for converting between hdf5 files, text files and data dictionaries. ''' logger = logging.getLogger(__name__) ## Write files from DataDict instances ##################################################################### def _write_csv(data): ''' Write data for a single ...
out += 'begin date, %s\n' % mjd_inv(time[0],'%Y-%m-%d')
Continue the code snippet: <|code_start|> out += 'latitude, %s N\n' % data['latitude'] out += ('units, meters**%s days**%s\n' % (data['space_exponent'],data['time_exponent'])) out += ('date, north, east, vertical, north std. deviation, ' 'east std. deviation, vertical std. deviation\n') # co...
check_data(data)
Next line prediction: <|code_start|> fout.close() return ## Load DataDict instances from files ##################################################################### def dict_from_text(infile,parser='csv'): ''' Loads a data dictionary from a text file. Parameters ---------- infile : str Input fil...
dicts = [PARSER_DICT[parser](s) for s in strs]
Given the following code snippet before the placeholder: <|code_start|> # split by delimiter lst = line.split(delim) # find the index containing field for i,j in enumerate(lst): if field in j: field_idx = i break # entry after the one containing field if (field_idx + 1) >= len(lst): ra...
return float(mjd(date_str,fmt))
Here is a snippet: <|code_start|> def remove_id(response, obj): obj.pop(response.model.pk_field.name) return obj class FormatedApp(ApiApp): def __init__(self, *args, **kwargs): super(FormatedApp, self).__init__(*args, **kwargs) self.view.formaters.append(remove_id) class TestApiView(T...
client = Client(WSGIDispatcher([ApiApp]),
Given snippet: <|code_start|>""" Fields type used with models """ class Field(object): """ The base field class. A Field is part of a Model class. It define an aspect of a ressource. """ __metaclass__ = ABCMeta def __init__(self, name, **options): self.name = name self.optio...
validators = [IntegerValidator()]
Given snippet: <|code_start|> class Field(object): """ The base field class. A Field is part of a Model class. It define an aspect of a ressource. """ __metaclass__ = ABCMeta def __init__(self, name, **options): self.name = name self.options = options class IntegerField(Fiel...
validators = [StringValidator()]
Here is a snippet: <|code_start|> base_type = "integer" example = 42 class StringForeingKey(ForeignKeyField, Field): """ A type of string and a Foreign key to check """ base_type = "string" example = "hackme" def __init__(self, name, **options): super(StringForeingKey, self).__...
validators = [FloatValidator()]
Predict the next line for this snippet: <|code_start|> base_type = "integer" validators = [IntegerValidator()] example = 42 class StringField(Field): """ An string field. python type basestring (either str or basestring), with StringValidator """ base_type = "string" validators = [S...
self.validators = [SQLiteForeign(**options), IntegerValidator()]