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 read_config(self):
""" Read config from file """ |
try:
with open(self.config_file, 'r') as f:
self.config = json.loads(f.read())
f.close()
except IOError:
return False
return 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 post_note(self):
""" Post note and return the URL of the posted note """ |
if self.args.note_title:
note_title = self.args.note_title
else:
note_title = None
note_content = self.args.note_content
mynote = self.pump.Note(display_name=note_title, content=note_content)
mynote.to = self.pump.me.followers
mynote.cc = self.pu... |
<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_obj_id(self, item):
""" Get the id of a PumpObject. :param item: id string or PumpObject """ |
if item is not None:
if isinstance(item, six.string_types):
return item
elif hasattr(item, 'id'):
return item.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 get_page(self, url):
""" Get a page of items from API """ |
if url:
data = self.feed._request(url, offset=self._offset, since=self._since, before=self._before)
# set values to False to avoid using them for next request
self._before = False if self._before is not None else None
self._since = False if self._since is not No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def done(self):
""" Check if we should stop returning objects """ |
if self._done:
return self._done
if self._limit is None:
self._done = False
elif self.itemcount >= self._limit:
self._done = True
return self._done |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_cache(self):
""" Build a list of objects from feed's cached items or API page""" |
self.cache = []
if self.done:
return
for i in (self.get_cached() if self._cached else self.get_page(self.url)):
if not self._cached:
# some objects don't have objectType set (inbox activities)
if not i.get("objectType"):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def items(self, offset=None, limit=20, since=None, before=None, *args, **kwargs):
""" Get a feed's items. :param offset: Amount of items to skip before returning... |
return ItemList(self, offset=offset, limit=limit, since=since, before=before, cached=self.is_cached) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def direct(self):
""" Direct inbox feed, contains activities addressed directly to the owner of the inbox. """ |
url = self._subfeed("direct")
if "direct" in self.url or "major" in self.url or "minor" in self.url:
return self
if self._direct is None:
self._direct = self.__class__(url, pypump=self._pump)
return self._direct |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def major(self):
""" Major inbox feed, contains major activities such as notes and images. """ |
url = self._subfeed("major")
if "major" in self.url or "minor" in self.url:
return self
if self._major is None:
self._major = self.__class__(url, pypump=self._pump)
return self._major |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def minor(self):
""" Minor inbox feed, contains minor activities such as likes, shares and follows. """ |
url = self._subfeed("minor")
if "minor" in self.url or "major" in self.url:
return self
if self._minor is None:
self._minor = self.__class__(url, pypump=self._pump)
return self._minor |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self):
""" Converts the post to something compatible with `json.dumps` """ |
data = super(Note, self).serialize()
data.update({
"verb": "post",
"object": {
"objectType": self.object_type,
"content": self.content,
}
})
if self.display_name:
data["object"]["displayName"] = self.display... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def context(self):
""" Provides request context """ |
type = "client_associate" if self.key is None else "client_update"
data = {
"type": type,
"application_type": self.type,
}
# is this an update?
if self.key:
data["client_id"] = self.key
data["client_secret"] = self.secret
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, server=None):
""" Sends the request """ |
request = {
"headers": {"Content-Type": "application/json"},
"timeout": self._pump.timeout,
"data": self.context,
}
url = "{proto}://{server}/{endpoint}".format(
proto=self._pump.protocol,
server=server or self.server,
end... |
<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(self, server=None):
""" Registers the client with the Pump API retrieving the id and secret """ |
if (self.key or self.secret):
return self.update()
server_data = self.request(server)
self.key = server_data["client_id"]
self.secret = server_data["client_secret"]
self.expirey = server_data["expires_at"] |
<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):
""" Updates the information the Pump server has about the client """ |
error = ""
if self.key is None:
error = "To update a client you need to provide a key"
if self.secret is None:
error = "To update a client you need to provide the secret"
if error:
raise ClientException(error)
self.request()
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 compile_extensions(macros, compat=False):
""" Compiler subroutine to test whether some functions are available on the target system. Since the rrdtool header... |
import distutils.sysconfig
import distutils.ccompiler
import tempfile
import shutil
from textwrap import dedent
# common vars
libraries = ['rrd']
include_dirs = [package_dir, '/usr/local/include']
library_dirs = ['/usr/local/lib']
compiler_args = dict(
libraries=librar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, obj):
""" Adds a member to the collection. :param obj: Object to add. Example: """ |
activity = {
"verb": "add",
"object": {
"objectType": obj.object_type,
"id": obj.id
},
"target": {
"objectType": self.object_type,
"id": self.id
}
}
self._post_activity(a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, obj):
""" Removes a member from the collection. :param obj: Object to remove. Example: """ |
activity = {
"verb": "remove",
"object": {
"objectType": obj.object_type,
"id": obj.id
},
"target": {
"objectType": self.object_type,
"id": self.id
}
}
self._post_activit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _post_activity(self, activity, unserialize=True):
""" Posts a activity to feed """ |
# I think we always want to post to feed
feed_url = "{proto}://{server}/api/user/{username}/feed".format(
proto=self._pump.protocol,
server=self._pump.client.server,
username=self._pump.client.nickname
)
data = self._pump.request(feed_url, method="PO... |
<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_links(self, links, key="href", proxy_key="proxyURL", endpoints=None):
""" Parses and adds block of links """ |
if endpoints is None:
endpoints = ["likes", "replies", "shares", "self", "followers",
"following", "lists", "favorites", "members"]
if links.get("links"):
for endpoint in links['links']:
# It would seem occasionally the links["links"][en... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_people(self, people):
""" Sets who the object is sent to """ |
if hasattr(people, "object_type"):
people = [people]
elif hasattr(people, "__iter__"):
people = list(people)
return people |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(self, filename):
""" Uploads a file from a filename on your system. :param filename: Path to file on your system. Example: """ |
mimetype = mimetypes.guess_type(filename)[0] or "application/octal-stream"
headers = {
"Content-Type": mimetype,
"Content-Length": str(os.path.getsize(filename)),
}
# upload file
file_data = self._pump.request(
"/api/user/{0}/uploads".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 unserialize(self, data):
""" From JSON -> Activity object """ |
# copy activity attributes into object
if "author" not in data["object"]:
data["object"]["author"] = data["actor"]
for key in ["to", "cc", "bto", "bcc"]:
if key not in data["object"] and key in data:
data["object"][key] = data[key]
Mapper(pypump... |
<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_store(self):
""" Creates store object """ |
if self.store_class is not None:
return self.store_class.load(self.client.webfinger, self)
raise NotImplementedError("You need to specify PyPump.store_class or override PyPump.create_store method.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _build_url(self, endpoint):
""" Returns a fully qualified URL """ |
server = None
if "://" in endpoint:
# looks like an url, let's break it down
server, endpoint = self._deconstruct_url(endpoint)
endpoint = endpoint.lstrip("/")
url = "{proto}://{server}/{endpoint}".format(
proto=self.protocol,
server=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 _deconstruct_url(self, url):
""" Breaks down URL and returns server and endpoint """ |
url = url.split("://", 1)[-1]
server, endpoint = url.split("/", 1)
return (server, endpoint) |
<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_client(self, url, key=None, secret=None):
""" Creates Client object with key and secret for server and adds it to _server_cache if it doesnt already exi... |
if "://" in url:
server, endpoint = self._deconstruct_url(url)
else:
server = url
if server not in self._server_cache:
if not (key and secret):
client = Client(
webfinger=self.client.webfinger,
name=se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, endpoint, method="GET", data="", raw=False, params=None, retries=None, client=None, headers=None, timeout=None, **kwargs):
""" Make request to ... |
retries = self.retries if retries is None else retries
timeout = self.timeout if timeout is None else timeout
# check client has been setup
if client is None:
client = self.setup_oauth_client(endpoint)
c = client.client
fnc = OAuth1Session(c.client_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def oauth_request(self):
""" Makes a oauth connection """ |
# get tokens from server and make a dict of them.
self._server_tokens = self.request_token()
self.store["oauth-request-token"] = self._server_tokens["token"]
self.store["oauth-request-secret"] = self._server_tokens["token_secret"]
# now we need the user to authorize me to use ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def construct_oauth_url(self):
""" Constructs verifier OAuth URL """ |
response = self._requester(requests.head,
"{0}://{1}/".format(self.protocol, self.client.server),
allow_redirects=False
)
if response.is_redirect:
server = response.headers['location']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_oauth_client(self, url=None):
""" Sets up client for requests to pump """ |
if url and "://" in url:
server, endpoint = self._deconstruct_url(url)
else:
server = self.client.server
if server not in self._server_cache:
self._add_client(server)
if server == self.client.server:
self.oauth = OAuth1(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_token(self):
""" Gets OAuth request token """ |
client = OAuth1(
client_key=self._server_cache[self.client.server].key,
client_secret=self._server_cache[self.client.server].secret,
callback_uri=self.callback,
)
request = {"auth": client}
response = self._requester(
requests.post,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_access(self, verifier):
""" Get OAuth access token so we can make requests """ |
client = OAuth1(
client_key=self._server_cache[self.client.server].key,
client_secret=self._server_cache[self.client.server].secret,
resource_owner_key=self.store["oauth-request-token"],
resource_owner_secret=self.store["oauth-request-secret"],
verifi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logged_in(self):
""" Return boolean if is logged in """ |
if "oauth-access-token" not in self.store:
return False
response = self.request("/api/whoami", allow_redirects=False)
# It should response with a redirect to our profile if it's logged in
if response.status_code != 302:
return False
# the location shou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnCreate():
""" Initialize cuDNN. Initializes cuDNN and returns a handle to the cuDNN context. Returns ------- handle : cudnnHandle cuDNN context """ |
handle = ctypes.c_void_p()
status = _libcudnn.cudnnCreate(ctypes.byref(handle))
cudnnCheckStatus(status)
return handle.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnDestroy(handle):
""" Release cuDNN resources. Release hardware resources used by cuDNN. Parameters handle : cudnnHandle cuDNN context. """ |
status = _libcudnn.cudnnDestroy(ctypes.c_void_p(handle))
cudnnCheckStatus(status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnSetStream(handle, id):
""" Set current cuDNN library stream. Parameters handle : cudnnHandle cuDNN context. id : cudaStream Stream Id. """ |
status = _libcudnn.cudnnSetStream(handle, id)
cudnnCheckStatus(status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnGetStream(handle):
""" Get current cuDNN library stream. Parameters handle : int cuDNN context. Returns ------- id : int Stream ID. """ |
id = ctypes.c_void_p()
status = _libcudnn.cudnnGetStream(handle, ctypes.byref(id))
cudnnCheckStatus(status)
return id.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnCreateTensorDescriptor():
""" Create a Tensor descriptor object. Allocates a cudnnTensorDescriptor_t structure and returns a pointer to it. Returns ----... |
tensor = ctypes.c_void_p()
status = _libcudnn.cudnnCreateTensorDescriptor(ctypes.byref(tensor))
cudnnCheckStatus(status)
return tensor.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnSetTensor4dDescriptor(tensorDesc, format, dataType, n, c, h, w):
""" Initialize a previously created Tensor 4D object. This function initializes a previ... |
status = _libcudnn.cudnnSetTensor4dDescriptor(tensorDesc, format, dataType,
n, c, h, w)
cudnnCheckStatus(status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnSetTensor4dDescriptorEx(tensorDesc, dataType, n, c, h, w, nStride, cStride, hStride, wStride):
"""" Initialize a Tensor descriptor object with strides. ... |
status = _libcudnn.cudnnSetTensor4dDescriptorEx(tensorDesc, dataType, n, c, h, w,
nStride, cStride, hStride, wStride)
cudnnCheckStatus(status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnGetTensor4dDescriptor(tensorDesc):
"""" Get parameters of a Tensor descriptor object. This function queries the parameters of the previouly initialized ... |
dataType = ctypes.c_int()
n = ctypes.c_int()
c = ctypes.c_int()
h = ctypes.c_int()
w = ctypes.c_int()
nStride = ctypes.c_int()
cStride = ctypes.c_int()
hStride = ctypes.c_int()
wStride = ctypes.c_int()
status = _libcudnn.cudnnGetTensor4dDescriptor(tensorDesc, ctypes.byref(data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnCreateFilterDescriptor():
"""" Create a filter descriptor. This function creates a filter descriptor object by allocating the memory needed to hold its ... |
wDesc = ctypes.c_void_p()
status = _libcudnn.cudnnCreateFilterDescriptor(ctypes.byref(wDesc))
cudnnCheckStatus(status)
return wDesc.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnSetFilter4dDescriptor(wDesc, dataType, format, k, c, h, w):
"""" Initialize a filter descriptor. This function initializes a previously created filter d... |
status = _libcudnn.cudnnSetFilter4dDescriptor(wDesc, dataType, format, k, c, h, w)
cudnnCheckStatus(status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnGetFilter4dDescriptor(wDesc):
"""" Get parameters of filter descriptor. This function queries the parameters of the previouly initialized filter descrip... |
dataType = ctypes.c_int()
format = ctypes.c_int()
k = ctypes.c_int()
c = ctypes.c_int()
h = ctypes.c_int()
w = ctypes.c_int()
status = _libcudnn.cudnnGetFilter4dDescriptor(wDesc, ctypes.byref(dataType),
ctypes.byref(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 cudnnCreateConvolutionDescriptor():
"""" Create a convolution descriptor. This function creates a convolution descriptor object by allocating the memory need... |
convDesc = ctypes.c_void_p()
status = _libcudnn.cudnnCreateConvolutionDescriptor(ctypes.byref(convDesc))
cudnnCheckStatus(status)
return convDesc.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnSetConvolution2dDescriptor(convDesc, pad_h, pad_w, u, v, dilation_h, dilation_w, mode, computeType):
"""" Initialize a convolution descriptor. This func... |
status = _libcudnn.cudnnSetConvolution2dDescriptor(convDesc, pad_h, pad_w, u, v,
dilation_h, dilation_w, mode,
computeType)
cudnnCheckStatus(status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnGetConvolution2dDescriptor(convDesc):
"""" Get a convolution descriptor. This function queries a previously initialized 2D convolution descriptor object... |
pad_h = ctypes.c_int()
pad_w = ctypes.c_int()
u = ctypes.c_int()
v = ctypes.c_int()
dilation_h = ctypes.c_int()
dilation_w = ctypes.c_int()
mode = ctypes.c_int()
computeType = ctypes.c_int()
status = _libcudnn.cudnnGetConvolution2dDescriptor(convDesc, ctypes.byref(pad_h),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc, wDesc):
"""" Return the dimensions of the output tensor given a convolution descriptor. This... |
n = ctypes.c_int()
c = ctypes.c_int()
h = ctypes.c_int()
w = ctypes.c_int()
status = _libcudnn.cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc,
wDesc, ctypes.byref(n),
ctypes.byref(c),... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnGetConvolutionForwardAlgorithm(handle, srcDesc, wDesc, convDesc, destDesc, preference, memoryLimitInbytes):
"""" This function returns the best algorith... |
algo = ctypes.c_int()
status = _libcudnn.cudnnGetConvolutionForwardAlgorithm(handle, srcDesc, wDesc,
convDesc, destDesc, preference,
ctypes.c_size_t(memoryLimitInbytes),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnGetConvolutionForwardWorkspaceSize(handle, srcDesc, wDesc, convDesc, destDesc, algo):
"""" This function returns the amount of GPU memory workspace the ... |
sizeInBytes = ctypes.c_size_t()
status = _libcudnn.cudnnGetConvolutionForwardWorkspaceSize(handle, srcDesc, wDesc,
convDesc, destDesc, algo,
ctypes.byref(sizeInBytes))
cudnnCheckStatus(status)
return sizeInB... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnSoftmaxForward(handle, algorithm, mode, alpha, srcDesc, srcData, beta, destDesc, destData):
"""" This routing computes the softmax function Parameters h... |
dataType = cudnnGetTensor4dDescriptor(destDesc)[0]
if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']:
alphaRef = ctypes.byref(ctypes.c_double(alpha))
betaRef = ctypes.byref(ctypes.c_double(beta))
else:
alphaRef = ctypes.byref(ctypes.c_float(alpha))
betaRef = ctypes.byref(ct... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnCreatePoolingDescriptor():
"""" Create pooling descriptor. This function creates a pooling descriptor object by allocating the memory needed to hold its... |
poolingDesc = ctypes.c_void_p()
status = _libcudnn.cudnnCreatePoolingDescriptor(ctypes.byref(poolingDesc))
cudnnCheckStatus(status)
return poolingDesc.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnSetPooling2dDescriptor(poolingDesc, mode, windowHeight, windowWidth, verticalPadding, horizontalPadding, verticalStride, horizontalStride):
"""" Initial... |
status = _libcudnn.cudnnSetPooling2dDescriptor(poolingDesc, mode, windowHeight,
windowWidth, verticalPadding, horizontalPadding,
verticalStride, horizontalStride)
cudnnCheckStatus(status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnGetPooling2dDescriptor(poolingDesc):
"""" This function queries a previously created pooling descriptor object. Parameters poolingDesc : cudnnPoolingDes... |
mode = ctypes.c_int()
windowHeight = ctypes.c_int()
windowWidth = ctypes.c_int()
verticalPadding = ctypes.c_int()
horizontalPadding = ctypes.c_int()
verticalStride = ctypes.c_int()
horizontalStride = ctypes.c_int()
status = _libcudnn.cudnnGetPooling2dDescriptor(poolingDesc, ctypes.byr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cudnnActivationBackward(handle, mode, alpha, srcDesc, srcData, srcDiffDesc, srcDiffData, destDesc, destData, beta, destDiffDesc, destDiffData):
"""" Gradient... |
dataType = cudnnGetTensor4dDescriptor(destDesc)[0]
if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']:
alphaRef = ctypes.byref(ctypes.c_double(alpha))
betaRef = ctypes.byref(ctypes.c_double(beta))
else:
alphaRef = ctypes.byref(ctypes.c_float(alpha))
betaRef = ctypes.byref(ct... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __prefix_key(self, key):
""" This will add the prefix to the key if one exists on the store """ |
# If there isn't a prefix don't bother
if self.prefix is None:
return key
# Don't prefix key if it already has it
if key.startswith(self.prefix + "-"):
return key
return "{0}-{1}".format(self.prefix, 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 export(self):
""" Exports as dictionary """ |
data = {}
for key, value in self.items():
data[key] = value
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
""" Saves dictionary to disk in JSON format. """ |
if self.filename is None:
raise StoreException("Filename must be set to write store to disk")
# We need an atomic way of re-writing the settings, we also need to
# prevent only overwriting part of the settings file (see bug #116).
# Create a temp file and only then re-name ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_filename(cls):
""" Gets filename of store on disk """ |
config_home = os.environ.get("XDG_CONFIG_HOME", "~/.config")
config_home = os.path.expanduser(config_home)
base_path = os.path.join(config_home, "PyPump")
if not os.path.isdir(base_path):
os.makedirs(base_path)
return os.path.join(base_path, "credentials.json") |
<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(cls, webfinger, pypump):
""" Load JSON from disk into store object """ |
filename = cls.get_filename()
if os.path.isfile(filename):
data = open(filename).read()
data = json.loads(data)
store = cls(data, filename=filename)
else:
store = cls(filename=filename)
store.prefix = webfinger
return store |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pause(message='Press any key to continue . . . '):
""" Prints the specified message if it's not None and waits for a keypress. """ |
if message is not None:
print(message, end='')
sys.stdout.flush()
getch()
print() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def covalent_bonds(atoms, threshold=1.1):
"""Returns all the covalent bonds in a list of `Atom` pairs. Notes ----- Uses information `element_data`, which can be ... |
bonds=[]
for a, b in atoms:
bond_distance=(
element_data[a.element.title()]['atomic radius'] + element_data[
b.element.title()]['atomic radius']) / 100
dist=distance(a._vector, b._vector)
if dist <= bond_distance * threshold:
bonds.append(Cova... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_covalent_bonds(ampal, max_range=2.2, threshold=1.1, tag=True):
"""Finds all covalent bonds in the AMPAL object. Parameters ampal : AMPAL Object Any AMPA... |
sectors=gen_sectors(ampal.get_atoms(), max_range * 1.1)
bonds=[]
for sector in sectors.values():
atoms=itertools.combinations(sector, 2)
bonds.extend(covalent_bonds(atoms, threshold=threshold))
bond_set=list(set(bonds))
if tag:
for bond in bond_set:
a, b=bond.a, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_covalent_bond_graph(covalent_bonds):
"""Generates a graph of the covalent bond network described by the interactions. Parameters covalent_bonds: [Co... |
bond_graph=networkx.Graph()
for inter in covalent_bonds:
bond_graph.add_edge(inter.a, inter.b)
return bond_graph |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_bond_subgraphs_from_break(bond_graph, atom1, atom2):
"""Splits the bond graph between two atoms to producing subgraphs. Notes ----- This will not wo... |
bond_graph.remove_edge(atom1, atom2)
try:
subgraphs=list(networkx.connected_component_subgraphs(
bond_graph, copy=False))
finally:
# Add edge
bond_graph.add_edge(atom1, atom2)
return subgraphs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cap(v, l):
"""Shortens string is above certain length.""" |
s = str(v)
return s if len(s) <= l else s[-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 find_atoms_within_distance(atoms, cutoff_distance, point):
"""Returns atoms within the distance from the point. Parameters atoms : [ampal.atom] A list of `am... |
return [x for x in atoms if distance(x, point) <= cutoff_distance] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def centre_of_atoms(atoms, mass_weighted=True):
""" Returns centre point of any list of atoms. Parameters atoms : list List of AMPAL atom objects. mass_weighted ... |
points = [x._vector for x in atoms]
if mass_weighted:
masses = [x.mass for x in atoms]
else:
masses = []
return centre_of_mass(points=points, masses=masses) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assign_force_field(self, ff, mol2=False):
"""Assigns force field parameters to Atoms in the AMPAL object. Parameters ff: BuffForceField The force field to be... |
if hasattr(self, 'ligands'):
atoms = self.get_atoms(ligands=True, inc_alt_states=True)
else:
atoms = self.get_atoms(inc_alt_states=True)
for atom in atoms:
w_str = None
a_ff_id = None
if atom.element == 'H':
continue
... |
<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_ff(self, ff, mol2=False, force_ff_assign=False):
"""Manages assigning the force field parameters. The aim of this method is to avoid unnecessary assig... |
aff = False
if force_ff_assign:
aff = True
elif 'assigned_ff' not in self.tags:
aff = True
elif not self.tags['assigned_ff']:
aff = True
if aff:
self.assign_force_field(ff, mol2=mol2)
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 get_internal_energy(self, assign_ff=True, ff=None, mol2=False, force_ff_assign=False):
"""Calculates the internal energy of the AMPAL object. This method is ... |
if not ff:
ff = global_settings['buff']['force_field']
if assign_ff:
self.update_ff(ff, mol2=mol2, force_ff_assign=force_ff_assign)
interactions = find_intra_ampal(self, ff.distance_cutoff)
buff_score = score_interactions(interactions, ff)
return buff_sco... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotate(self, angle, axis, point=None, radians=False, inc_alt_states=True):
"""Rotates every atom in the AMPAL object. Parameters angle : float Angle that AMP... |
q = Quaternion.angle_and_axis(angle=angle, axis=axis, radians=radians)
for atom in self.get_atoms(inc_alt_states=inc_alt_states):
atom._vector = q.rotate_vector(v=atom._vector, point=point)
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 translate(self, vector, inc_alt_states=True):
"""Translates every atom in the AMPAL object. Parameters vector : 3D Vector (tuple, list, numpy.array) Vector u... |
vector = numpy.array(vector)
for atom in self.get_atoms(inc_alt_states=inc_alt_states):
atom._vector += vector
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 rmsd(self, other, backbone=False):
"""Calculates the RMSD between two AMPAL objects. Notes ----- No fitting operation is performs and both AMPAL objects must... |
assert type(self) == type(other)
if backbone and hasattr(self, 'backbone'):
points1 = self.backbone.get_atoms()
points2 = other.backbone.get_atoms()
else:
points1 = self.get_atoms()
points2 = other.get_atoms()
points1 = [x._vector for x in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, item):
"""Appends a `Monomer to the `Polymer`. Notes ----- Does not update labelling. """ |
if isinstance(item, Monomer):
self._monomers.append(item)
else:
raise TypeError(
'Only Monomer objects can be appended to an Polymer.')
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 extend(self, polymer):
"""Extends the `Polymer` with the contents of another `Polymer`. Notes ----- Does not update labelling. """ |
if isinstance(polymer, Polymer):
self._monomers.extend(polymer)
else:
raise TypeError(
'Only Polymer objects may be merged with a Polymer using unary operator "+".')
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 get_monomers(self, ligands=True):
"""Retrieves all the `Monomers` from the AMPAL object. Parameters ligands : bool, optional If true, will include ligand `Mo... |
if ligands and self.ligands:
monomers = self._monomers + self.ligands._monomers
else:
monomers = self._monomers
return iter(monomers) |
<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_atoms(self, ligands=True, inc_alt_states=False):
"""Flat list of all the Atoms in the Polymer. Parameters inc_alt_states : bool If true atoms from altern... |
if ligands and self.ligands:
monomers = self._monomers + self.ligands._monomers
else:
monomers = self._monomers
atoms = itertools.chain(
*(list(m.get_atoms(inc_alt_states=inc_alt_states)) for m in monomers))
return atoms |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relabel_monomers(self, labels=None):
"""Relabels the either in numerically or using a list of labels. Parameters labels : list, optional A list of new labels... |
if labels:
if len(self._monomers) == len(labels):
for monomer, label in zip(self._monomers, labels):
monomer.id = str(label)
else:
error_string = (
'Number of Monomers ({}) and number of labels '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relabel_atoms(self, start=1):
"""Relabels all `Atoms` in numerical order. Parameters start : int, optional Offset the labelling by `start` residues. """ |
counter = start
for atom in self.get_atoms():
atom.id = counter
counter += 1
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 make_pdb(self, alt_states=False, inc_ligands=True):
"""Generates a PDB string for the `Polymer`. Parameters alt_states : bool, optional Include alternate con... |
if any([False if x.id else True for x in self._monomers]):
self.relabel_monomers()
if self.ligands and inc_ligands:
monomers = self._monomers + self.ligands._monomers
else:
monomers = self._monomers
pdb_str = write_pdb(monomers, self.id, alt_states=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 rotate(self, angle, axis, point=None, radians=False):
"""Rotates `Atom` by `angle`. Parameters angle : float Angle that `Atom` will be rotated. axis : 3D Vec... |
q = Quaternion.angle_and_axis(angle=angle, axis=axis, radians=radians)
self._vector = q.rotate_vector(v=self._vector, point=point)
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 dict_from_mmcif(mmcif, path=True):
"""Parse mmcif file into a dictionary. Notes ----- Full list of keys/value types, and further information on them can be v... |
if path:
with open(mmcif, 'r') as foo:
lines = foo.readlines()
else:
lines = mmcif.splitlines()
lines = [' '.join(x.strip().split()) for x in lines]
# Some of the data in a .cif files are stored between 'loop_' to initiate a loop, and '#' to terminate it.
# The variable... |
<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_protein_dict(cif_data):
""" Parse cif_data dict for a subset of its data. Notes ----- cif_data dict contains all the data from the .cif file, with values... |
# Dictionary relating the keys of protein_dict (column names in Protein model) to the keys of cif_data.
mmcif_data_names = {
'keywords': '_struct_keywords.text',
'header': '_struct_keywords.pdbx_keywords',
'space_group': '_symmetry.space_group_name_H-M',
'experimental_method': ... |
<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_PISCES_output(pisces_output, path=False):
""" Takes the output list of a PISCES cull and returns in a usable dictionary. Notes ----- Designed for outpu... |
pisces_dict = {}
if path:
pisces_path = Path(pisces_output)
pisces_content = pisces_path.read_text().splitlines()[1:]
else:
pisces_content = pisces_output.splitlines()[1:]
for line in pisces_content:
pdb = line.split()[0][:4].lower()
chain = line.split()[0][-1]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_decode(URL, encoding='utf-8', verbose=True):
""" Downloads data from URL and returns decoded contents.""" |
if verbose:
print("Downloading data from " + URL)
req = Request(URL)
try:
with urlopen(req) as u:
decoded_file = u.read().decode(encoding)
except URLError as e:
if hasattr(e, 'reason'):
print('Server could not be reached.')
print('Reason: ', e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def olderado_best_model(pdb_id):
""" Checks the Olderado web server and returns the most representative conformation for PDB NMR structures. Notes ----- Uses OLD... |
pdb_code = pdb_id[:4].lower()
olderado_url = 'http://www.ebi.ac.uk/pdbe/nmr/olderado/searchEntry?pdbCode=' + pdb_code
olderado_page = download_decode(olderado_url, verbose=False)
if olderado_page:
parsed_page = BeautifulSoup(olderado_page, 'html.parser')
else:
return None
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 buff_eval(params):
"""Builds and evaluates BUFF energy of model in parallelization Parameters params: list Tuple containing the specification to be built, th... |
specification, sequence, parsed_ind = params
model = specification(*parsed_ind)
model.build()
model.pack_new_sequences(sequence)
return model.buff_interaction_energy.total_energy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buff_internal_eval(params):
"""Builds and evaluates BUFF internal energy of a model in parallelization Parameters params: list Tuple containing the specifica... |
specification, sequence, parsed_ind = params
model = specification(*parsed_ind)
model.build()
model.pack_new_sequences(sequence)
return model.buff_internal_energy.total_energy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rmsd_eval(rmsd_params):
"""Builds a model and runs profit against a reference model. Parameters rmsd_params Returns ------- rmsd: float rmsd against referenc... |
specification, sequence, parsed_ind, reference_pdb = rmsd_params
model = specification(*parsed_ind)
model.pack_new_sequences(sequence)
ca, bb, aa = run_profit(model.pdb, reference_pdb, path1=False, path2=False)
return bb |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comparator_eval(comparator_params):
"""Gets BUFF score for interaction between two AMPAL objects """ |
top1, top2, params1, params2, seq1, seq2, movements = comparator_params
xrot, yrot, zrot, xtrans, ytrans, ztrans = movements
obj1 = top1(*params1)
obj2 = top2(*params2)
obj2.rotate(xrot, [1, 0, 0])
obj2.rotate(yrot, [0, 1, 0])
obj2.rotate(zrot, [0, 0, 1])
obj2.translate([xtrans, ytrans,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parameters(self, sequence, value_means, value_ranges, arrangement):
"""Relates the individual to be evolved to the full parameter string. Parameters sequence... |
self._params['sequence'] = sequence
self._params['value_means'] = value_means
self._params['value_ranges'] = value_ranges
self._params['arrangement'] = arrangement
if any(x <= 0 for x in self._params['value_ranges']):
raise ValueError("range values must be greater th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_energy_funnel_data(self, cores=1):
"""Compares models created during the minimisation to the best model. Returns ------- energy_rmsd_gen: [(float, float... |
if not self.parameter_log:
raise AttributeError(
'No parameter log data to make funnel, have you ran the '
'optimiser?')
model_cls = self._params['specification']
gen_tagged = []
for gen, models in enumerate(self.parameter_log):
fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def funnel_rebuild(psg_trm_spec):
"""Rebuilds a model and compares it to a reference model. Parameters psg_trm: (([float], float, int), AMPAL, specification) A t... |
param_score_gen, top_result_model, specification = psg_trm_spec
params, score, gen = param_score_gen
model = specification(*params)
rmsd = top_result_model.rmsd(model)
return rmsd, score, gen |
<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_pop(self):
"""Updates the population according to crossover and fitness criteria. """ |
candidates = []
for ind in self.population:
candidates.append(self.crossover(ind))
self._params['model_count'] += len(candidates)
self.assign_fitnesses(candidates)
for i in range(len(self.population)):
if candidates[i].fitness > self.population[i].fitness... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize_pop(self):
"""Generates initial population with random positions and speeds.""" |
self.population = self.toolbox.swarm(n=self._params['popsize'])
if self._params['neighbours']:
for i in range(len(self.population)):
self.population[i].ident = i
self.population[i].neighbours = list(
set(
[(i - x) %... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize_pop(self):
"""Assigns initial fitnesses.""" |
self.toolbox.register("individual", self.generate)
self.toolbox.register("population", tools.initRepeat,
list, self.toolbox.individual)
self.population = self.toolbox.population(n=self._params['popsize'])
self.assign_fitnesses(self.population)
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 randomise_proposed_value(self):
"""Creates a randomly the proposed value. Raises ------ TypeError Raised if this method is called on a static value. TypeErro... |
if self.parameter_type is MMCParameterType.UNIFORM_DIST:
(a, b) = self.static_dist_or_list
self.proposed_value = random.uniform(a, b)
elif self.parameter_type is MMCParameterType.NORMAL_DIST:
(mu, sigma) = self.static_dist_or_list
self.proposed_value = ra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accept_proposed_value(self):
"""Changes the current value to the proposed value.""" |
if self.proposed_value is not None:
self.current_value = self.proposed_value
self.proposed_value = None
return |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.