text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tt_comp(self, sampled_topics):
""" Compute term-topic matrix from sampled_topics. """ |
samples = sampled_topics.shape[0]
tt = np.zeros((self.V, self.K, samples))
for s in range(samples):
tt[:, :, s] = \
samplers_lda.tt_comp(self.tokens, sampled_topics[s, :],
self.N, self.V, self.K, self.beta)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def topic_content(self, W, output_file="topic_description.csv"):
""" Print top W words in each topic to file. """ |
topic_top_probs = []
topic_top_words = []
tt = self.tt_avg(False)
for t in range(self.K):
top_word_indices = list(tt[:, t].argsort()[-W:][::-1])
topic_top_probs.append(np.round(np.sort(tt[:, t])[-W:][::-1], 3))
topic_top_words.append([l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def perplexity(self):
""" Compute perplexity for each sample. """ |
return samplers_lda.perplexity_comp(self.docid, self.tokens,
self.tt, self.dt, self.N,
self.K, self.samples) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def samples_keep(self, index):
""" Keep subset of samples. If index is an integer, keep last N=index samples. If index is a list, keep the samples corresponding ... |
try:
if isinstance(index, (int, long)):
index = range(self.samples)[-index:]
except(NameError):
if isinstance(index,int):
index = range(self.samples)[-index:]
self.sampled_topics = np.take(self.sampled_topics, index, axis=0)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tt_avg(self, print_output=True, output_file="tt.csv"):
""" Compute average term-topic matrix, and print to file if print_output=True. """ |
avg = self.tt.mean(axis=2)
if print_output:
np.savetxt(output_file, avg, delimiter=",")
return avg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dict_print(self, output_file="dict.csv"):
""" Print mapping from tokens to numeric indices. """ |
with codecs.open(output_file, "w", encoding='utf-8') as f:
for (v, k) in self.token_key.items():
f.write("%s,%d\n" % (v, k)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, query_samples):
""" Query docs with query_samples number of Gibbs sampling iterations. """ |
self.sampled_topics = np.zeros((self.samples, self.N),
dtype=np.int)
for s in range(self.samples):
self.sampled_topics[s, :] = \
samplers_lda.sampler_query(self.docid, self.tokens,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dt_avg(self, print_output=True, output_file="dt_query.csv"):
""" Compute average document-topic matrix, and print to file if print_output=True. """ |
avg = self.dt.mean(axis=2)
if print_output:
np.savetxt(output_file, avg, delimiter=",")
return avg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def phrase_replace(self, replace_dict):
""" Replace phrases with single token, mapping defined in replace_dict """ |
def r(tokens):
text = ' ' + ' '.join(tokens)
for k, v in replace_dict.items():
text = text.replace(" " + k + " ", " " + v + " ")
return text.split()
self.stems = list(map(r, self.stems)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stem(self):
""" Stem tokens with Porter Stemmer. """ |
def s(tokens):
return [PorterStemmer().stem(t) for t in tokens]
self.stems = list(map(s, self.tokens)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bigram(self, items):
""" generate bigrams of either items = "tokens" or "stems" """ |
def bigram_join(tok_list):
text = nltk.bigrams(tok_list)
return list(map(lambda x: x[0] + '.' + x[1], text))
if items == "tokens":
self.bigrams = list(map(bigram_join, self.tokens))
elif items == "stems":
self.bigrams = list(map(bigram_join, sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def E_step(self):
""" compute type probabilities given current parameter estimates. """ |
# on the first iteration of estimation, this will be called
if not hasattr(self, 'type_prob'):
self.type_prob = np.empty((self.N, self.K))
temp_probs = np.zeros((self.N, self.K))
for i in range(self.N):
for k in range(self.K):
temp_probs[i,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def M_step(self):
""" generate new parameter estimates given updated type distribution """ |
for k in range(self.K):
self.rho[k] = self.type_prob[:, k].sum() / self.N
for k in range(self.K):
for m in range(self.M):
temp_prob = np.dot(self.type_prob[:, k],
self.feature_counts[:, m])
if temp_prob < 1e-99... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def estimate(self, maxiter=250, convergence=1e-7):
""" run EM algorithm until convergence, or until maxiter reached """ |
self.loglik = np.zeros(maxiter)
iter = 0
while iter < maxiter:
self.loglik[iter] = self.E_step()
if np.isnan(self.loglik[iter]):
print("undefined log-likelihood")
break
self.M_step()
if self.loglik[iter... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_content(path):
"""Get content of file.""" |
with codecs.open(abs_path(path), encoding='utf-8') as f:
return f.read() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sanitize_dataframe(df):
"""Sanitize a DataFrame to prepare it for serialization. * Make a copy * Raise ValueError if it has a hierarchical index. * Convert c... |
import pandas as pd
import numpy as np
df = df.copy()
if isinstance(df.index, pd.core.index.MultiIndex):
raise ValueError('Hierarchical indices not supported')
if isinstance(df.columns, pd.core.index.MultiIndex):
raise ValueError('Hierarchical indices not supported')
def to_l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_spec(spec, data=None):
"""Prepare a Vega-Lite spec for sending to the frontend. This allows data to be passed in either as part of the spec or separa... |
import pandas as pd
if isinstance(data, pd.DataFrame):
# We have to do the isinstance test first because we can't
# compare a DataFrame to None.
data = sanitize_dataframe(data)
spec['data'] = {'values': data.to_dict(orient='records')}
elif data is None:
# Assume dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _repr_mimebundle_(self, include=None, exclude=None):
"""Display the visualization in the Jupyter notebook.""" |
id = uuid.uuid4()
return (
{'application/javascript': self._generate_js(id)},
{'jupyter-vega': '#{0}'.format(id)},
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pass_creds_to_nylas():
""" This view loads the credentials from Google and passes them to Nylas, to set up native authentication. """ |
# If you haven't already connected with Google, this won't work.
if not google.authorized:
return "Error: not yet connected with Google!", 400
if "refresh_token" not in google.token:
# We're missing the refresh token from Google, and the only way to get
# a new one is to force reau... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pass_creds_to_nylas(name, email, password, server_host=None):
""" Passes Exchange credentials to Nylas, to set up native authentication. """ |
# Start the connection process by looking up all the information that
# Nylas needs in order to connect, and sending it to the authorize API.
nylas_authorize_data = {
"client_id": app.config["NYLAS_OAUTH_CLIENT_ID"],
"name": name,
"email_address": email,
"provider": "exchang... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_resource_raw( self, cls, id, extra=None, headers=None, stream=False, **filters ):
"""Get an individual REST resource""" |
headers = headers or {}
headers.update(self.session.headers)
postfix = "/{}".format(extra) if extra else ""
if cls.api_root != "a":
url = "{}/{}/{}{}".format(self.api_server, cls.collection_name, id, postfix)
else:
url = "{}/a/{}/{}/{}{}".format(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_datetimes_to_timestamps(data, datetime_attrs):
""" Given a dictionary of data, and a dictionary of datetime attributes, return a new dictionary that ... |
if not data:
return data
new_data = {}
for key, value in data.items():
if key in datetime_attrs and isinstance(value, datetime):
new_key = datetime_attrs[key]
new_data[new_key] = timestamp_from_dt(value)
else:
new_data[key] = value
return ne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_signature(message, key, signature):
""" This function will verify the authenticity of a digital signature. For security purposes, Nylas includes a dig... |
digest = hmac.new(key, msg=message, digestmod=hashlib.sha256).hexdigest()
return digest == signature |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_delta(delta):
""" This is the part of the code where you would process the information from the webhook notification. Each delta is one change that h... |
kwargs = {
"type": delta["type"],
"date": datetime.datetime.utcfromtimestamp(delta["date"]),
"object_id": delta["object_data"]["id"],
}
print(" * {type} at {date} with ID {object_id}".format(**kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error_respond(self):
"""Converts the error to an error response object. :return: An error response object ready to be serialized and sent to the client. :rty... |
response = JSONRPCErrorResponse()
response.error = self.message
response.unique_id = None
response._jsonrpc_error_code = self.jsonrpc_error_code
if hasattr(self, 'data'):
response.data = self.data
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error_respond(self, error):
"""Create an error response to this request. When processing the request produces an error condition this method can be used to c... |
if self.unique_id is None:
return None
response = JSONRPCErrorResponse()
response.unique_id = None if self.one_way else self.unique_id
code, msg, data = _get_code_message_and_data(error)
response.error = msg
response._jsonrpc_error_code = code
if d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def respond(self, result):
"""Create a response to this request. When processing the request completed successfully this method can be used to create a response ... |
if self.one_way or self.unique_id is None:
return None
response = JSONRPCSuccessResponse()
response.result = result
response.unique_id = self.unique_id
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_reply(self, data):
"""Deserializes and validates a response. Called by the client to reconstruct the serialized :py:class:`JSONRPCResponse`. :param byt... |
if isinstance(data, bytes):
data = data.decode()
try:
rep = json.loads(data)
except Exception as e:
raise InvalidReplyError(e)
for k in rep.keys():
if not k in self._ALLOWED_REPLY_KEYS:
raise InvalidReplyError('Key not al... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_request(self, data):
"""Deserializes and validates a request. Called by the server to reconstruct the serialized :py:class:`JSONRPCRequest`. :param byt... |
if isinstance(data, bytes):
data = data.decode()
try:
req = json.loads(data)
except Exception as e:
raise JSONRPCParseError()
if isinstance(req, list):
# batch request
requests = JSONRPCBatchRequest()
for subreq i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raise_error(self, error):
"""Recreates the exception. Creates a :py:class:`~tinyrpc.protocols.jsonrpc.JSONRPCError` instance and raises it. This allows the e... |
exc = JSONRPCError(error)
if self.raises_errors:
raise exc
return exc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle(self, environ, start_response):
"""WSGI handler function. The transport will serve a request by reading the message and putting it into an internal bu... |
request = Request(environ)
request.max_content_length = self.max_content_length
access_control_headers = {
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Origin': self.allow_origin,
'Access-Control-Allow-Headers': \
'Content-Ty... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def receive_one_message(self):
"""Handle a single request. Polls the transport for a new message. After a new message has arrived :py:meth:`_spawn` is called wit... |
context, message = self.transport.receive_message()
if callable(self.trace):
self.trace('-->', context, message)
# assuming protocol is threadsafe and dispatcher is theadsafe, as
# long as its immutable
def handle_message(context, message):
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raise_error(self, error):
"""Raises the exception in the client. Called by the client to convert the :py:class:`RPCErrorResponse` into an Exception and raise... |
ex = exc.RPCError('Error calling remote procedure: %s' % error.error['message'])
if self.raises_errors:
raise ex
return ex |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, zmq_context, endpoint):
"""Create new server transport. Instead of creating the socket yourself, you can call this function and merely pass the :... |
socket = zmq_context.socket(zmq.ROUTER)
socket.bind(endpoint)
return cls(socket) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, zmq_context, endpoint):
"""Create new client transport. Instead of creating the socket yourself, you can call this function and merely pass the :... |
socket = zmq_context.socket(zmq.REQ)
socket.connect(endpoint)
return cls(socket) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def receive_message(self):
"""Receive a message from the transport. Blocks until a message has been received. May return a context opaque to clients that should ... |
if not ('REQUEST_METHOD' in os.environ
and os.environ['REQUEST_METHOD'] == 'POST'):
print("Status: 405 Method not Allowed; only POST is accepted")
exit(0)
# POST
content_length = int(os.environ['CONTENT_LENGTH'])
request_json = sys.stdin.read(co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_reply(self, context, reply):
"""Sends a reply to a client. The client is usually identified by passing ``context`` as returned from the original :py:fun... |
# context isn't used with cgi
# Using sys.stdout.buffer.write() fails as stdout is on occasion monkey patched
# to AsyncFile which doesn't support the buffer attribute.
print("Status: 200 OK")
print("Content-Type: application/json")
print("Cache-Control: no-cache")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _spawn(self, func, *args, **kwargs):
"""Spawn a handler function. Spawns the supplied ``func`` with ``*args`` and ``**kwargs`` as a gevent greenlet. :param f... |
gevent.spawn(func, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, method, args, kwargs, one_way=False):
"""Calls the requested method and returns the result. If an error occured, an :py:class:`~tinyrpc.exc.RPCErr... |
req = self.protocol.create_request(method, args, kwargs, one_way)
rep = self._send_and_handle_reply(req, one_way)
if one_way:
return
return rep.result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_all(self, requests):
"""Calls the methods in the request in parallel. When the :py:mod:`gevent` module is already loaded it is assumed to be correctly i... |
threads = []
if 'gevent' in sys.modules:
# assume that gevent is available and functional, make calls in parallel
import gevent
for r in requests:
req = self.protocol.create_request(r.method, r.args, r.kwargs)
tr = r.transport.transpo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def batch_call(self, calls):
"""Experimental, use at your own peril.""" |
req = self.protocol.create_batch_request()
for call_args in calls:
req.append(self.protocol.create_request(*call_args))
return self._send_and_handle_reply(req) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def public(name=None):
"""Decorator. Mark a method as eligible for registration by a dispatcher. The dispatchers :py:func:`~tinyrpc.dispatch.RPCDispatcher.regist... |
if callable(name):
f = name
f._rpc_public_name = f.__name__
return f
def _(f):
f._rpc_public_name = name or f.__name__
return f
return _ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def public(self, name=None):
"""Convenient decorator. Allows easy registering of functions to this dispatcher. Example: .. code-block:: python dispatch = RPCDisp... |
if callable(name):
self.add_method(name)
return name
def _(f):
self.add_method(f, name=name)
return f
return _ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_subdispatch(self, dispatcher, prefix=''):
"""Adds a subdispatcher, possibly in its own namespace. :param dispatcher: The dispatcher to add as a subdispat... |
self.subdispatchers.setdefault(prefix, []).append(dispatcher) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_method(self, name):
"""Retrieve a previously registered method. Checks if a method matching ``name`` has been registered. If :py:func:`get_method` cannot... |
if name in self.method_map:
return self.method_map[name]
for prefix, subdispatchers in self.subdispatchers.items():
if name.startswith(prefix):
for sd in subdispatchers:
try:
return sd.get_method(name[len(prefix):])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_instance(self, obj, prefix=''):
"""Create new subdispatcher and register all public object methods on it. To be used in conjunction with the :py:fun... |
dispatch = self.__class__()
for name, f in inspect.getmembers(
obj, lambda f: callable(f) and hasattr(f, '_rpc_public_name')):
dispatch.add_method(f, f._rpc_public_name)
# add to dispatchers
self.add_subdispatch(dispatch, prefix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch(self, request):
"""Fully handle request. The dispatch method determines which method to call, calls it and returns a response containing a result. N... |
if hasattr(request, 'create_batch_response'):
results = [self._dispatch(req) for req in request]
response = request.create_batch_response()
if response is not None:
response.extend(results)
return response
else:
return self._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop(self, key, default=None):
""" Get item from the dict and remove it. Return default if expired or does not exist. Never raise KeyError. """ |
with self.lock:
try:
item = OrderedDict.__getitem__(self, key)
del self[key]
return item[0]
except KeyError:
return default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get(self, key, default=None, with_age=False):
" Return the value for key if key is in the dictionary, else default. "
try:
return self.__getitem__(key, with_age)
except KeyError:
if with_age:
return default, None
else:
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload(self, callback=None, errback=None):
""" Reload record data from the API. """ |
return self.load(reload=True, callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, callback=None, errback=None, reload=False):
""" Load record data from the API. """ |
if not reload and self.data:
raise RecordException('record already loaded')
def success(result, *args):
self._parseModel(result)
if callback:
return callback(self)
else:
return self
return self._rest.retrieve(self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, callback=None, errback=None):
""" Delete the record from the zone, including all advanced configuration, meta data, etc. """ |
if not self.data:
raise RecordException('record not loaded')
def success(result, *args):
if callback:
return callback(result)
else:
return result
return self._rest.delete(self.parentZone.zone,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qps(self, callback=None, errback=None):
""" Return the current QPS for this record :rtype: dict :return: QPS information """ |
if not self.data:
raise RecordException('record not loaded')
stats = Stats(self.parentZone.config)
return stats.qps(zone=self.parentZone.zone,
domain=self.domain,
type=self.type,
callback=callback,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addAnswers(self, answers, callback=None, errback=None, **kwargs):
""" Add answers to the record. :param answers: answers structure. See the class note on ans... |
if not self.data:
raise RecordException('record not loaded')
orig_answers = self.data['answers']
new_answers = self._rest._getAnswersForBody(answers)
orig_answers.extend(new_answers)
return self.update(answers=orig_answers, callback=callback,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createFromAPIKey(self, apikey, maybeWriteDefault=False):
""" Create a basic config from a single API key :param str apikey: NS1 API Key, as created in the NS... |
self._data = {
'default_key': 'default',
'keys': {
'default': {
'key': apikey,
'desc': 'imported API key'
}
}
}
self._keyID = 'default'
self._doDefaults()
if maybeWriteDef... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadFromFile(self, path):
""" Load JSON config file from disk at the given path :param str path: path to config file """ |
if '~' in path:
path = os.path.expanduser(path)
f = open(path)
body = f.read()
f.close()
self._path = path
self.loadFromString(body) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, path=None):
""" Write config data to disk. If this config object already has a path, it will write to it. If it doesn't, one must be passed durin... |
if not self._path and not path:
raise ConfigException('no config path given')
if path:
self._path = path
if '~' in self._path:
self._path = os.path.expanduser(self._path)
f = open(self._path, 'w')
f.write(json.dumps(self._data))
f.clos... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def useKeyID(self, keyID):
""" Use the given API key config specified by `keyID` during subsequent API calls :param str keyID: an index into the 'keys' maintaine... |
if keyID not in self._data['keys']:
raise ConfigException('keyID does not exist: %s' % keyID)
self._keyID = keyID |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getKeyConfig(self, keyID=None):
""" Get key configuration specified by `keyID`, or current keyID. :param str keyID: optional keyID to retrieve, or current if... |
k = keyID if keyID is not None else self._keyID
if not k or k not in self._data['keys']:
raise ConfigException('request key does not exist: %s' % k)
return self._data['keys'][k] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isKeyWriteLocked(self, keyID=None):
""" Determine if a key config is write locked. :param str keyID: optional keyID to retrieve, or current if not passed :re... |
kcfg = self.getKeyConfig(keyID)
return 'writeLock' in kcfg and kcfg['writeLock'] is True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAPIKey(self, keyID=None):
""" Retrieve the NS1 API Key for the given keyID :param str keyID: optional keyID to retrieve, or current if not passed :return:... |
kcfg = self.getKeyConfig(keyID)
if 'key' not in kcfg:
raise ConfigException('invalid config: missing api key')
return kcfg['key'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getEndpoint(self):
""" Retrieve the NS1 API Endpoint URL that will be used for requests. :return: URL of the NS1 API that will be used for requests """ |
port = ''
endpoint = ''
keyConfig = self.getKeyConfig()
if 'port' in keyConfig:
port = ':' + keyConfig['port']
elif self._data['port'] != self.PORT:
port = ':' + self._data['port']
if 'endpoint' in keyConfig:
endpoint = keyConfig['endp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, callback=None, errback=None, reload=False):
""" Load network data from the API. """ |
if not reload and self.data:
raise NetworkException('Network already loaded')
def success(result, *args):
self.data = result
self.id = result['id']
self.name = result['name']
self.report = self._rest.report(self.id)
if callback:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, callback=None, errback=None):
""" Delete the Network and all associated addresses """ |
return self._rest.delete(self.id, callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_address(self, prefix, type, callback=None, errback=None, **kwargs):
""" Create a new address space in this Network :param str prefix: The CIDR prefix of ... |
if not self.data:
raise NetworkException('Network not loaded')
return Address(self.config, prefix, type, self).create(**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, callback=None, errback=None, reload=False):
""" Load address data from the API. """ |
if not reload and self.data:
raise AddressException('Address already loaded')
def success(result, *args):
self.data = result
self.id = result['id']
self.prefix = result['prefix']
self.type = result['type']
self.network = Network(s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, callback=None, errback=None, reload=False):
""" Load Scopegroup data from the API. """ |
if not reload and self.data:
raise ScopegroupException('Scope Group already loaded')
def success(result, *args):
self.data = result
self.id = result['id']
self.dhcp4 = result['dhcp4']
self.dhcp6 = result['dhcp6']
self.name = resul... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, q=None, has_geo=False, callback=None, errback=None):
""" Search within a zone for specific metadata. Zone must already be loaded. """ |
if not self.data:
raise ZoneException('zone not loaded')
return self._rest.search(self.zone, q, has_geo, callback, errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, callback=None, errback=None):
""" Delete the zone and ALL records it contains. """ |
return self._rest.delete(self.zone, callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createLinkToSelf(self, new_zone, callback=None, errback=None, **kwargs):
""" Create a new linked zone, linking to ourselves. All records in this zone will th... |
zone = Zone(self.config, new_zone)
kwargs['link'] = self.data['zone']
return zone.create(callback=callback, errback=errback, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cloneRecord(self, existing_domain, new_domain, rtype, zone=None, callback=None, errback=None):
""" Clone the given record to a new record such that their con... |
if zone is None:
zone = self.zone
if not new_domain.endswith(zone):
new_domain = new_domain + '.' + zone
def onSaveNewRecord(new_data):
if zone != self.zone:
pZone = Zone(self.config, zone)
else:
pZone = self
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadRecord(self, domain, rtype, callback=None, errback=None):
""" Load a high level Record object from a domain within this Zone. :param str domain: The name... |
rec = Record(self, domain, rtype)
return rec.load(callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qps(self, callback=None, errback=None):
""" Return the current QPS for this zone :rtype: dict :return: QPS information """ |
stats = Stats(self.config)
return stats.qps(zone=self.zone, callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def usage(self, callback=None, errback=None, **kwargs):
""" Return the current usage information for this zone :rtype: dict :return: usage information """ |
stats = Stats(self.config)
return stats.usage(zone=self.zone, callback=callback, errback=errback,
**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, callback=None, errback=None, reload=False):
""" Load monitor data from the API. """ |
if not reload and self.data:
raise MonitorException('monitor already loaded')
def success(result, *args):
self.data = result
if callback:
return callback(self)
else:
return self
return self._rest.retrieve(self.dat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, callback=None, errback=None):
""" Delete the monitor """ |
return self._rest.delete(self.data['id'], callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, callback=None, errback=None, **kwargs):
""" Update monitor configuration. Pass a list of keywords and their values to update. """ |
if not self.data:
raise MonitorException('monitor not loaded')
def success(result, *args):
self.data = result
if callback:
return callback(self)
else:
return self
return self._rest.update(self.data['id'], {}, call... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zones(self):
""" Return a new raw REST interface to zone resources :rtype: :py:class:`ns1.rest.zones.Zones` """ |
import ns1.rest.zones
return ns1.rest.zones.Zones(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def records(self):
""" Return a new raw REST interface to record resources :rtype: :py:class:`ns1.rest.records.Records` """ |
import ns1.rest.records
return ns1.rest.records.Records(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addresses(self):
""" Return a new raw REST interface to address resources :rtype: :py:class:`ns1.rest.ipam.Adresses` """ |
import ns1.rest.ipam
return ns1.rest.ipam.Addresses(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def networks(self):
""" Return a new raw REST interface to network resources :rtype: :py:class:`ns1.rest.ipam.Networks` """ |
import ns1.rest.ipam
return ns1.rest.ipam.Networks(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scope_groups(self):
""" Return a new raw REST interface to scope_group resources :rtype: :py:class:`ns1.rest.ipam.Scopegroups` """ |
import ns1.rest.ipam
return ns1.rest.ipam.Scopegroups(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stats(self):
""" Return a new raw REST interface to stats resources :rtype: :py:class:`ns1.rest.stats.Stats` """ |
import ns1.rest.stats
return ns1.rest.stats.Stats(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datasource(self):
""" Return a new raw REST interface to datasource resources :rtype: :py:class:`ns1.rest.data.Source` """ |
import ns1.rest.data
return ns1.rest.data.Source(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datafeed(self):
""" Return a new raw REST interface to feed resources :rtype: :py:class:`ns1.rest.data.Feed` """ |
import ns1.rest.data
return ns1.rest.data.Feed(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def monitors(self):
""" Return a new raw REST interface to monitors resources :rtype: :py:class:`ns1.rest.monitoring.Monitors` """ |
import ns1.rest.monitoring
return ns1.rest.monitoring.Monitors(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notifylists(self):
""" Return a new raw REST interface to notify list resources :rtype: :py:class:`ns1.rest.monitoring.NotifyLists` """ |
import ns1.rest.monitoring
return ns1.rest.monitoring.NotifyLists(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plan(self):
""" Return a new raw REST interface to account plan :rtype: :py:class:`ns1.rest.account.Plan` """ |
import ns1.rest.account
return ns1.rest.account.Plan(self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadZone(self, zone, callback=None, errback=None):
""" Load an existing zone into a high level Zone object. :param str zone: zone name, like 'example.com' :r... |
import ns1.zones
zone = ns1.zones.Zone(self.config, zone)
return zone.load(callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createZone(self, zone, zoneFile=None, callback=None, errback=None, **kwargs):
""" Create a new zone, and return an associated high level Zone object. Several... |
import ns1.zones
zone = ns1.zones.Zone(self.config, zone)
return zone.create(zoneFile=zoneFile, callback=callback,
errback=errback, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadRecord(self, domain, type, zone=None, callback=None, errback=None, **kwargs):
""" Load an existing record into a high level Record object. :param str dom... |
import ns1.zones
if zone is None:
# extract from record string
parts = domain.split('.')
if len(parts) <= 2:
zone = '.'.join(parts)
else:
zone = '.'.join(parts[1:])
z = ns1.zones.Zone(self.config, zone)
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadMonitors(self, callback=None, errback=None, **kwargs):
""" Load all monitors """ |
import ns1.monitoring
monitors_list = self.monitors().list(callback, errback)
return [ns1.monitoring.Monitor(self.config, m) for m in monitors_list] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createMonitor(self, callback=None, errback=None, **kwargs):
""" Create a monitor """ |
import ns1.monitoring
monitor = ns1.monitoring.Monitor(self.config)
return monitor.create(callback=callback, errback=errback, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadNetworkbyID(self, id, callback=None, errback=None):
""" Load an existing Network by ID into a high level Network object :param int id: id of an existing ... |
import ns1.ipam
network = ns1.ipam.Network(self.config, id=id)
return network.load(callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadNetworkbyName(self, name, callback=None, errback=None):
""" Load an existing Network by name into a high level Network object :param str name: Name of an... |
import ns1.ipam
network = ns1.ipam.Network(self.config, name=name)
return network.load(callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadAddressbyID(self, id, callback=None, errback=None):
""" Load an existing address by ID into a high level Address object :param int id: id of an existing ... |
import ns1.ipam
address = ns1.ipam.Address(self.config, id=id)
return address.load(callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadAddressbyPrefix(self, prefix, type, network_id, callback=None, errback=None):
""" Load an existing address by prefix, type and network into a high level ... |
import ns1.ipam
network = ns1.ipam.Network(self.config, id=network_id).load()
address = ns1.ipam.Address(self.config, prefix=prefix, type=type, network=network)
return address.load(callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadScopeGroupbyID(self, id, callback=None, errback=None):
""" Load an existing Scope Group by ID into a high level Scope Group object :param int id: id of a... |
import ns1.ipam
scope_group = ns1.ipam.Scopegroup(self.config, id=id)
return scope_group.load(callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadScopeGroupbyName(self, name, service_group_id, callback=None, errback=None):
""" Load an existing Scope Group by name and service group id into a high le... |
import ns1.ipam
scope_group = ns1.ipam.Scopegroup(self.config, name=name, service_group_id=service_group_id)
return scope_group.load(callback=callback, errback=errback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generateDHCPOptionsTemplate(self, address_family):
""" Generate boilerplate dictionary to hold dhcp options :param str address_family: dhcpv4 or dhcpv6 :retu... |
from ns1.ipam import DHCPOptions
options = {}
for option in DHCPOptions.OPTIONS[address_family]:
options[option] = ""
return options |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.