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 GroupsUsersDelete(self, group_id, user_id):
"""
Delete a user from a group in CommonSense.
@return (bool) - Boolean indicating whether GroupsPost was su... |
if self.__SenseApiCall__('/groups/{group_id}/users/{user_id}.json'.format(group_id = group_id, user_id = user_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SensorShare(self, sensor_id, parameters):
"""
Share a sensor with a user
@param sensor_id (int) - Id of sensor to be shared
@param parameters (dictiona... |
if not parameters['user']['id']:
parameters['user'].pop('id')
if not parameters['user']['username']:
parameters['user'].pop('username')
if self.__SenseApiCall__("/sensors/{0}/users".format(sensor_id), "POST", parameters = parameters):
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 GroupsSensorsPost(self, group_id, sensors):
"""
Share a number of sensors within a group.
@param group_id (int) - Id of the group to share sensors with
... |
if self.__SenseApiCall__("/groups/{0}/sensors.json".format(group_id), "POST", parameters = sensors):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GroupsSensorsGet(self, group_id, parameters):
"""
Retrieve sensors shared within the group.
@param group_id (int) - Id of the group to retrieve sensors ... |
if self.__SenseApiCall("/groups/{0}/sensors.json".format(group_id), "GET", parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GroupsSensorsDelete(self, group_id, sensor_id):
"""
Stop sharing a sensor within a group
@param group_id (int) - Id of the group to stop sharing the sen... |
if self.__SenseApiCall__("/groups/{0}/sensors/{1}.json".format(group_id, sensor_id), "DELETE"):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DomainsGet(self, parameters = None, domain_id = -1):
"""
This method returns the domains of the current user.
The list also contains the domains to which... |
url = ''
if parameters is None and domain_id <> -1:
url = '/domains/{0}.json'.format(domain_id)
else:
url = '/domains.json'
if self.__SenseApiCall__(url, 'GET', parameters = parameters):
return True
else:
self.__error__ ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DomainUsersGet(self, domain_id, parameters):
"""
Retrieve users of the specified domain.
@param domain_id (int) - Id of the domain to retrieve users fro... |
if self.__SenseApiCall__('/domains/{0}/users.json'.format(domain_id), 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DomainTokensGet(self, domain_id):
"""
T his method returns the list of tokens which are available for this domain.
Only domain managers can list domain t... |
if self.__SenseApiCall__('/domains/{0}/tokens.json'.format(domain_id), 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DomainTokensCreate(self, domain_id, amount):
"""
This method creates tokens that can be used by users who want to join the domain.
Tokens are automatical... |
if self.__SenseApiCall__('/domains/{0}/tokens.json'.format(domain_id), 'POST', parameters = {"amount":amount}):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DataProcessorsGet(self, parameters):
"""
List the users data processors.
@param parameters (dictonary) - Dictionary containing the parameters of the req... |
if self.__SenseApiCall__('/dataprocessors.json', 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DataProcessorsDelete(self, dataProcessorId):
"""
Delete a data processor in CommonSense.
@param dataProcessorId - The id of the data processor that will... |
if self.__SenseApiCall__('/dataprocessors/{id}.json'.format(id = dataProcessorId), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deriv(self, mu):
""" Derivative of the negative binomial variance function. """ |
p = self._clean(mu)
return 1 + 2 * self.alpha * p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iwls(y, x, family, offset, y_fix, ini_betas=None, tol=1.0e-8, max_iter=200, wi=None):
""" Iteratively re-weighted least squares estimation routine Parameters... |
n_iter = 0
diff = 1.0e6
if ini_betas is None:
betas = np.zeros((x.shape[1], 1), np.float)
else:
betas = ini_betas
if isinstance(family, Binomial):
y = family.link._clean(y)
if isinstance(family, Poisson):
y_off = y / offset
y_off = family.starting_mu(y_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _next_regular(target):
""" Find the next regular number greater than or equal to target. Regular numbers are composites of the prime factors 2, 3, and 5. Als... |
if target <= 6:
return target
# Quickly check if it's already a power of 2
if not (target & (target - 1)):
return target
match = float('inf') # Anything found will be smaller
p5 = 1
while p5 < target:
p35 = p5
while p35 < target:
# Ceiling integer ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quantile_1D(data, weights, quantile):
""" Compute the weighted quantile of a 1D numpy array. Parameters data : ndarray Input array (one dimension). weights :... |
# Check the data
if not isinstance(data, np.matrix):
data = np.asarray(data)
if not isinstance(weights, np.matrix):
weights = np.asarray(weights)
nd = data.ndim
if nd != 1:
raise TypeError("data must be a one dimensional array")
ndw = weights.ndim
if ndw != 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 quantile(data, weights, quantile):
""" Weighted quantile of an array with respect to the last axis. Parameters data : ndarray Input array. weights : ndarray ... |
# TODO: Allow to specify the axis
nd = data.ndim
if nd == 0:
TypeError("data must have at least one dimension")
elif nd == 1:
return quantile_1D(data, weights, quantile)
elif nd > 1:
n = data.shape
imr = data.reshape((np.prod(n[:-1]), n[-1]))
result = np.appl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def einfo(self, args=None):
""" execute a NON-cached, throttled einfo query einfo.fcgi?db=<database> Input: Entrez database (&db) or None (returns info on all En... |
if args is None:
args = {}
return self._query('/einfo.fcgi', args, skip_cache=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 native_obj(self):
"""Native storage object.""" |
if self.__native is None:
self.__native = self._get_object()
return self.__native |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def smart_content_type(self):
"""Smart content type.""" |
content_type = self.content_type
if content_type in (None, '', 'application/octet-stream'):
content_type, _ = mimetypes.guess_type(self.name)
return content_type |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def smart_content_encoding(self):
"""Smart content encoding.""" |
encoding = self.content_encoding
if not encoding:
base_list = self.basename.split('.')
while (not encoding) and len(base_list) > 1:
_, encoding = mimetypes.guess_type('.'.join(base_list))
base_list.pop()
return encoding |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def native_container(self):
"""Native container object.""" |
if self.__native is None:
self.__native = self._get_container()
return self.__native |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def native_conn(self):
"""Native connection object.""" |
if self.__native is None:
self.__native = self._get_connection()
return self.__native |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self, name, value):
"""Validate and return a value.""" |
if self.valid_set and value not in self.valid_set:
raise ImproperlyConfigured(
"%s: \"%s\" is not a valid setting (choose between %s)." %
(name, value, ", ".join("\"%s\"" % x for x in self.valid_set)))
return 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 get(self, name, default=None):
"""Get value.""" |
default = default if default is not None else self.default
try:
value = getattr(_settings, name)
except AttributeError:
value = os.environ.get(name, default) if self.from_env else default
# Convert env variable.
if value != 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 _container_whitelist(self):
"""Container whitelist.""" |
if self.__container_whitelist is None:
self.__container_whitelist = \
set(self.CLOUD_BROWSER_CONTAINER_WHITELIST or [])
return self.__container_whitelist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _container_blacklist(self):
"""Container blacklist.""" |
if self.__container_blacklist is None:
self.__container_blacklist = \
set(self.CLOUD_BROWSER_CONTAINER_BLACKLIST or [])
return self.__container_blacklist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def container_permitted(self, name):
"""Return whether or not a container is permitted. :param name: Container name. :return: ``True`` if container is permitted.... |
white = self._container_whitelist
black = self._container_blacklist
return name not in black and (not white or name in white) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def app_media_url(self):
"""Get application media root from real media root URL.""" |
url = None
media_dir = self.CLOUD_BROWSER_STATIC_MEDIA_DIR
if media_dir:
url = os.path.join(self.MEDIA_URL, media_dir).rstrip('/') + '/'
return url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def module_getmtime(filename):
""" Get the mtime associated with a module. If this is a .pyc or .pyo file and a corresponding .py file exists, the time of the .p... |
if os.path.splitext(filename)[1].lower() in (".pyc", ".pyo") and os.path.exists(filename[:-1]):
return os.path.getmtime(filename[:-1])
if os.path.exists(filename):
return os.path.getmtime(filename)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def module_reload_changed(key):
""" Reload a module if it has changed since we last imported it. This is necessary if module a imports script b, script b is chan... |
imp.acquire_lock()
try:
modkey = module_sys_modules_key(key)
if not modkey:
return False
found = None
if modkey:
for second in WatchList:
secmodkey = module_sys_modules_key(second)
if secmodkey and sys.modules[modkey] == sy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def module_sys_modules_key(key):
""" Check if a module is in the sys.modules dictionary in some manner. If so, return the key used in that dictionary. :param key... |
moduleparts = key.split(".")
for partnum, part in enumerate(moduleparts):
modkey = ".".join(moduleparts[partnum:])
if modkey in sys.modules:
return modkey
return None |
<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_including_local(module):
""" Reload a module. If it isn"t found, try to include the local service directory. This must be called from a thread that ha... |
try:
reload(module)
except ImportError:
# This can happen if the module was loaded in the immediate script
# directory. Add the service path and try again.
if not hasattr(cherrypy.thread_data, "modulepath"):
raise
path = os.path.abspath(cherrypy.thread_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 reload_recent_submodules(module, mtime=0, processed=[]):
""" Recursively reload submodules which are more recent than a specified timestamp. To be called fro... |
if module.endswith(".py"):
module = module[:-3]
if module in processed:
return False
any_reloaded = False
for key in WatchList:
if WatchList[key]["parent"] == module:
reloaded = reload_recent_submodules(key, mtime, processed)
filemtime = module_getmtime(W... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def watch_import(name, globals=None, *args, **kwargs):
""" When a module is asked to be imported, check if we have previously imported it. If so, check if the ti... |
# Don"t monitor builtin modules. types seem special, so don"t monitor it
# either.
monitor = not imp.is_builtin(name) and name not in ("types", )
# Don"t monitor modules if we don"t know where they came from
monitor = monitor and isinstance(globals, dict) and globals.get("__name__")
if not mon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def watch_module_cache_get(cache, module):
""" When we ask to fetch a module with optional config file, check time stamps and dependencies to determine if it sho... |
imp.acquire_lock()
try:
if not hasattr(cache, "timestamps"):
cache.timestamps = {}
mtime = os.path.getmtime(module)
mtime = latest_submodule_time(module, mtime)
if getattr(cache, "config", False):
config_file = module[:-2] + "yaml"
if os.path.... |
<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_int(value, default, test_fn=None):
"""Convert value to integer. :param value: Integer value. :param default: Default value on failed conversion. :param t... |
try:
converted = int(value)
except ValueError:
return default
test_fn = test_fn if test_fn else lambda x: True
return converted if test_fn(converted) else 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 requires(module, name=""):
"""Enforces module presence. The general use here is to allow conditional imports that may fail (e.g., a required python package i... |
def wrapped(method):
"""Call and enforce method."""
if module is None:
raise ImproperlyConfigured("Module '%s' is not installed." % name)
return method
return wrapped |
<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_from_header(date_str):
"""Try various RFC conversions to ``datetime`` or return ``None``. :param date_str: Date string. :type date_str: ``string`` :return... |
convert_fns = (
dt_from_rfc8601,
dt_from_rfc1123,
)
for convert_fn in convert_fns:
try:
return convert_fn(date_str)
except ValueError:
pass
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def basename(path):
"""Rightmost part of path after separator.""" |
base_path = path.strip(SEP)
sep_ind = base_path.rfind(SEP)
if sep_ind < 0:
return path
return base_path[sep_ind + 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 path_parts(path):
"""Split path into container, object. :param path: Path to resource (including container). :type path: `string` :return: Container, storage... |
path = path if path is not None else ''
container_path = object_path = ''
parts = path_list(path)
if len(parts) >= 1:
container_path = parts[0]
if len(parts) > 1:
object_path = path_join(*parts[1:])
return container_path, object_path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path_yield(path):
"""Yield on all path parts.""" |
for part in (x for x in path.strip(SEP).split(SEP) if x not in (None, '')):
yield part |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path_join(*args):
"""Join path parts to single path.""" |
return SEP.join((x for x in args if x not in (None, ''))).strip(SEP) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relpath(path, start):
"""Get relative path to start. Note: Modeled after python2.6 :meth:`os.path.relpath`. """ |
path_items = path_list(path)
start_items = path_list(start)
# Find common parts of path.
common = []
for pth, stt in zip(path_items, start_items):
if pth != stt:
break
common.append(pth)
# Shared parts index in both lists.
common_ind = len(common)
parent_nu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collective_dr_squared( self ):
""" Squared sum of total displacements for these atoms. Args: None Returns: (Float):
The square of the summed total displacem... |
return sum( np.square( sum( [ atom.dr for atom in self.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 occupations( self, site_label ):
""" Number of these atoms occupying a specific site type. Args: site_label (Str):
Label for the site type being considered.... |
return sum( atom.site.label == site_label for atom in self.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 get_class(class_string):
""" Convert a string version of a function name to the callable object. """ |
try:
mod_name, class_name = get_mod_func(class_string)
if class_name != '':
cls = getattr(__import__(mod_name, {}, {}, ['']), class_name)
return cls
except (ImportError, AttributeError):
pass
raise ImportError('Failed to import %s' % class_string) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_gs_folder(cls, result):
"""Return ``True`` if GS standalone folder object. GS will create a 0 byte ``<FOLDER NAME>_$folder$`` key as a pseudo-directory p... |
return (cls.is_key(result) and
result.size == 0 and
result.name.endswith(cls._gs_folder_suffix)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_prefix(cls, result):
"""Return ``True`` if result is a prefix object. .. note:: Boto uses the S3 Prefix object for GS prefixes. """ |
from boto.s3.prefix import Prefix
return isinstance(result, Prefix) or cls._is_gs_folder(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 translate(self, exc):
"""Return whether or not to do translation.""" |
from boto.exception import StorageResponseError
if isinstance(exc, StorageResponseError):
if exc.status == 404:
return self.error_cls(str(exc))
return None |
<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_result(cls, container, result):
"""Create from ambiguous result.""" |
if result is None:
raise errors.NoObjectException
elif cls.is_prefix(result):
return cls.from_prefix(container, result)
elif cls.is_key(result):
return cls.from_key(container, result)
raise errors.CloudException("Unknown boto result type: %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 from_key(cls, container, key):
"""Create from key object.""" |
if key is None:
raise errors.NoObjectException
# Get Key (1123): Tue, 13 Apr 2010 14:02:48 GMT
# List Keys (8601): 2010-04-13T14:02:48.000Z
return cls(container,
name=key.name,
size=key.size,
content_type=key.conten... |
<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_bucket(cls, connection, bucket):
"""Create from bucket object.""" |
if bucket is None:
raise errors.NoContainerException
# It appears that Amazon does not have a single-shot REST query to
# determine the number of keys / overall byte size of a bucket.
return cls(connection, bucket.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 from_settings(cls):
"""Create configuration from Django settings or environment.""" |
from cloud_browser.app_settings import settings
from django.core.exceptions import ImproperlyConfigured
conn_cls = conn_fn = None
datastore = settings.CLOUD_BROWSER_DATASTORE
if datastore == 'AWS':
# Try AWS
from cloud_browser.cloud.aws import AwsConnect... |
<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_connection_cls(cls):
"""Return connection class. :rtype: :class:`type` """ |
if cls.__connection_cls is None:
cls.__connection_cls, _ = cls.from_settings()
return cls.__connection_cls |
<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_connection(cls):
"""Return connection object. :rtype: :class:`cloud_browser.cloud.base.CloudConnection` """ |
if cls.__connection_obj is None:
if cls.__connection_fn is None:
_, cls.__connection_fn = cls.from_settings()
cls.__connection_obj = cls.__connection_fn()
return cls.__connection_obj |
<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_path(cls, container, path):
"""Create object from path.""" |
from datetime import datetime
path = path.strip(SEP)
full_path = os.path.join(container.base_path, path)
last_modified = datetime.fromtimestamp(os.path.getmtime(full_path))
obj_type = cls.type_cls.SUBDIR if is_dir(full_path)\
else cls.type_cls.FILE
return 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 from_path(cls, conn, path):
"""Create container from path.""" |
path = path.strip(SEP)
full_path = os.path.join(conn.abs_root, path)
return cls(conn, path, 0, os.path.getsize(full_path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cubic_lattice( a, b, c, spacing ):
""" Generate a cubic lattice. Args: a (Int):
Number of lattice repeat units along x. b (Int):
Number of lattice repeat u... |
grid = np.array( list( range( 1, a * b * c + 1 ) ) ).reshape( a, b, c, order='F' )
it = np.nditer( grid, flags=[ 'multi_index' ] )
sites = []
while not it.finished:
x, y, z = it.multi_index
r = np.array( [ x, y, z ] ) * spacing
neighbours = [ np.roll( grid, +1, axis=0 )[x,y,z],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lattice_from_sites_file( site_file, cell_lengths ):
""" Generate a lattice from a sites file. Args: site_file (Str):
Filename for the file containing the si... |
sites = []
site_re = re.compile( 'site:\s+([-+]?\d+)' )
r_re = re.compile( 'cent(?:er|re):\s+([-\d\.e]+)\s+([-\d\.e]+)\s+([-\d\.e]+)' )
r_neighbours = re.compile( 'neighbou{0,1}rs:((\s+[-+]?\d+)+)' )
r_label = re.compile( 'label:\s+(\S+)' )
r_energy = re.compile( 'energy:\s([-+\d\.]+)' )
wi... |
<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_location(request):
""" Redirect to a given url while setting the chosen location in the cookie. The url and the location_id need to be specified in the r... |
next = request.GET.get('next', None) or request.POST.get('next', None)
if not next:
next = request.META.get('HTTP_REFERER', None)
if not next:
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'POST':
location_id = request.POST.get('location_id', Non... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def site_specific_nn_occupation( self ):
""" Returns the number of occupied nearest neighbour sites, classified by site type. Args: None Returns: (Dict(Str:Int))... |
to_return = { l : 0 for l in set( ( site.label for site in self.p_neighbours ) ) }
for site in self.p_neighbours:
if site.is_occupied:
to_return[ site.label ] += 1
return to_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 cn_occupation_energy( self, delta_occupation=None ):
""" The coordination-number dependent energy for this site. Args: delta_occupation (:obj:Dict(Str:Int), ... |
nn_occupations = self.site_specific_nn_occupation()
if delta_occupation:
for site in delta_occupation:
assert( site in nn_occupations )
nn_occupations[ site ] += delta_occupation[ site ]
return sum( [ self.cn_occupation_energies[ s ][ n ] for s, n 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 clear_database(self):
""" Removes all geodata stored in database. Useful for development, never use on production. """ |
self.logger.info('Removing obsolete geoip from database...')
IpRange.objects.all().delete()
City.objects.all().delete()
Region.objects.all().delete()
Country.objects.all().delete() |
<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_extract_archive(self, url):
""" Returns dict with 2 extracted filenames """ |
self.logger.info('Downloading zipfile from ipgeobase.ru...')
temp_dir = tempfile.mkdtemp()
archive = zipfile.ZipFile(self._download_url_to_string(url))
self.logger.info('Extracting files...')
file_cities = archive.extract(settings.IPGEOBASE_CITIES_FILENAME, path=temp_dir)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _line_to_dict(self, file, field_names):
""" Converts file line into dictonary """ |
for line in file:
delimiter = settings.IPGEOBASE_FILE_FIELDS_DELIMITER
yield self._extract_data_from_line(line, field_names, delimiter) |
<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_cidr_file(self, file):
""" Iterate over ip info and extract useful data """ |
data = {'cidr': list(), 'countries': set(), 'city_country_mapping': dict()}
allowed_countries = settings.IPGEOBASE_ALLOWED_COUNTRIES
for cidr_info in self._line_to_dict(file, field_names=settings.IPGEOBASE_CIDR_FIELDS):
city_id = cidr_info['city_id'] if cidr_info['city_id'] != '-' 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 _process_cities_file(self, file, city_country_mapping):
""" Iterate over cities info and extract useful data """ |
data = {'all_regions': list(), 'regions': list(), 'cities': list(), 'city_region_mapping': dict()}
allowed_countries = settings.IPGEOBASE_ALLOWED_COUNTRIES
for geo_info in self._line_to_dict(file, field_names=settings.IPGEOBASE_CITIES_FIELDS):
country_code = self._get_country_code_f... |
<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_geography(self, countries, regions, cities, city_country_mapping):
""" Update database with new countries, regions and cities """ |
existing = {
'cities': list(City.objects.values_list('id', flat=True)),
'regions': list(Region.objects.values('name', 'country__code')),
'countries': Country.objects.values_list('code', flat=True)
}
for country_code in countries:
if country_code n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relative_probability( self, l1, l2, c1, c2 ):
""" The relative probability for a jump between two sites with specific site types and coordination numbers. Ar... |
if self.site_energies:
site_delta_E = self.site_energies[ l2 ] - self.site_energies[ l1 ]
else:
site_delta_E = 0.0
if self.nn_energy:
delta_nn = c2 - c1 - 1 # -1 because the hopping ion is not counted in the final site occupation number
site_delta... |
<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_nearest_neighbour_lookup_table( self ):
""" Construct a look-up table of relative jump probabilities for a nearest-neighbour interaction Hamiltonian... |
self.jump_probability = {}
for site_label_1 in self.connected_site_pairs:
self.jump_probability[ site_label_1 ] = {}
for site_label_2 in self.connected_site_pairs[ site_label_1 ]:
self.jump_probability[ site_label_1 ][ site_label_2 ] = {}
for coor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset( self ):
""" Reinitialise the stored displacements, number of hops, and list of sites visited for this `Atom`. Args: None Returns: None """ |
self.number_of_hops = 0
self.dr = np.array( [ 0.0, 0.0, 0.0 ] )
self.summed_dr2 = 0.0
self.sites_visited = [ self._site.number ] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_ip(self, ip):
""" Find the smallest range containing the given IP. """ |
try:
number = inet_aton(ip)
except Exception:
raise IpRange.DoesNotExist
try:
return self.filter(start_ip__lte=number, end_ip__gte=number)\
.order_by('end_ip', '-start_ip')[0]
except IndexError:
raise IpRange.DoesNo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _manage(target, extra='', proj_settings=PROJ_SETTINGS):
"""Generic wrapper for ``django-admin.py``.""" |
local("export PYTHONPATH='' && "
"export DJANGO_SETTINGS_MODULE='%s' && "
"django-admin.py %s %s" %
(proj_settings, target, extra),
capture=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def types(**typefuncs):
""" Decorate a function that takes strings to one that takes typed values. The decorator's arguments are functions to perform type conver... |
def wrap(f):
@functools.wraps(f)
def typed_func(*pargs, **kwargs):
# Analyze the incoming arguments so we know how to apply the
# type-conversion functions in `typefuncs`.
argspec = inspect.getargspec(f)
# The `args` property contains the list of nam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def return_type(rettype):
""" Decorate a function to automatically convert its return type to a string using a custom function. Web-based service functions must ... |
def wrap(f):
@functools.wraps(f)
def converter(*pargs, **kwargs):
# Run the function to capture the output.
result = f(*pargs, **kwargs)
# Convert the result using the return type function.
try:
result = rettype(result)
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 excepts(cls):
"""Return tuple of underlying exception classes to trap and wrap. :rtype: ``tuple`` of ``type`` """ |
if cls._excepts is None:
cls._excepts = tuple(cls.translations.keys())
return cls._excepts |
<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, exc):
"""Return translation of exception to new class. Calling code should only raise exception if exception class is passed in, else ``None`... |
# Find actual class.
for key in self.translations.keys():
if isinstance(exc, key):
# pylint: disable=unsubscriptable-object
return self.translations[key](str(exc))
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def settings_view_decorator(function):
"""Insert decorator from settings, if any. .. note:: Decorator in ``CLOUD_BROWSER_VIEW_DECORATOR`` can be either a callabl... |
dec = settings.CLOUD_BROWSER_VIEW_DECORATOR
# Trade-up string to real decorator.
if isinstance(dec, str):
# Split into module and decorator strings.
mod_str, _, dec_str = dec.rpartition('.')
if not (mod_str and dec_str):
raise ImportError("Unable to import module: %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 _breadcrumbs(path):
"""Return breadcrumb dict from path.""" |
full = None
crumbs = []
for part in path_yield(path):
full = path_join(full, part) if full else part
crumbs.append((full, part))
return crumbs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def browser(request, path='', template="cloud_browser/browser.html"):
"""View files in a file path. :param request: The request. :param path: Path to resource, i... |
from itertools import islice
try:
# pylint: disable=redefined-builtin
from future_builtins import filter
except ImportError:
# pylint: disable=import-error
from builtins import filter
# Inputs.
container_path, object_path = path_parts(path)
incoming = request.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def document(_, path=''):
"""View single document from path. :param path: Path to resource, including container as first part of path. """ |
container_path, object_path = path_parts(path)
conn = get_connection()
try:
container = conn.get_container(container_path)
except errors.NoContainerException:
raise Http404("No container at: %s" % container_path)
except errors.NotPermittedException:
raise Http404("Access den... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""Truncate string on character boundary. .. note:: Django ticket `5025 <http://code.djangoproject.com/ticket/5025>`_ has a patch for a more extensible and robust... |
length = None
try:
length = int(num)
except ValueError:
pass
if length is not None and len(value) > length:
return value[:length - len(end_text)] + end_text
return 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 cloud_browser_media_url(_, token):
"""Get base media URL for application static media. Correctly handles whether or not the settings variable ``CLOUD_BROWSER... |
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' takes one argument" % bits[0])
rel_path = bits[1]
return MediaUrlNode(rel_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset( self ):
""" Reset all counters for this simulation. Args: None Returns: None """ |
self.lattice.reset()
for atom in self.atoms.atoms:
atom.reset() |
<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_number_of_atoms( self, n, selected_sites=None ):
""" Set the number of atoms for the simulation, and populate the simulation lattice. Args: n (Int):
Num... |
self.number_of_atoms = n
self.atoms = species.Species( self.lattice.populate_sites( self.number_of_atoms, selected_sites=selected_sites ) ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_initialised( self ):
""" Check whether the simulation has been initialised. Args: None Returns: None """ |
if not self.lattice:
raise AttributeError('Running a simulation needs the lattice to be initialised')
if not self.atoms:
raise AttributeError('Running a simulation needs the atoms to be initialised')
if not self.number_of_jumps and not self.for_time:
raise 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 old_collective_correlation( self ):
""" Returns the collective correlation factor, f_I Args: None Returns: (Float):
The collective correlation factor, f_I. ... |
if self.has_run:
return self.atoms.collective_dr_squared() / float( self.number_of_jumps )
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collective_diffusion_coefficient( self ):
""" Returns the collective or "jump" diffusion coefficient, D_J. Args: None Returns: (Float):
The collective diffu... |
if self.has_run:
return self.atoms.collective_dr_squared() / ( 6.0 * self.lattice.time )
else:
return None |
<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_lookup_table( self, hamiltonian='nearest-neighbour' ):
""" Create a jump-probability look-up table corresponding to the appropriate Hamiltonian. Args: ... |
expected_hamiltonian_values = [ 'nearest-neighbour', 'coordination_number' ]
if hamiltonian not in expected_hamiltonian_values:
raise ValueError
self.lattice.jump_lookup_table = lookup_table.LookupTable( self.lattice, hamiltonian ) |
<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, jump ):
""" Update the lattice state by accepting a specific jump Args: jump (Jump):
The jump that has been accepted. Returns: None. """ |
atom = jump.initial_site.atom
dr = jump.dr( self.cell_lengths )
#print( "atom {} jumped from site {} to site {}".format( atom.number, jump.initial_site.number, jump.final_site.number ) )
jump.final_site.occupation = atom.number
jump.final_site.atom = atom
jump.final_site... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populate_sites( self, number_of_atoms, selected_sites=None ):
""" Populate the lattice sites with a specific number of atoms. Args: number_of_atoms (Int):
T... |
if number_of_atoms > self.number_of_sites:
raise ValueError
if selected_sites:
atoms = [ atom.Atom( initial_site = site ) for site in random.sample( [ s for s in self.sites if s.label in selected_sites ], number_of_atoms ) ]
else:
atoms = [ atom.Atom( initial... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jump( self ):
""" Select a jump at random from all potential jumps, then update the lattice state. Args: None Returns: None """ |
potential_jumps = self.potential_jumps()
if not potential_jumps:
raise BlockedLatticeError('No moves are possible in this lattice')
all_transitions = transitions.Transitions( self.potential_jumps() )
random_jump = all_transitions.random()
delta_t = all_transitions.ti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def site_occupation_statistics( self ):
""" Average site occupation for each site type Args: None Returns: (Dict(Str:Float)):
Dictionary of occupation statistic... |
if self.time == 0.0:
return None
occupation_stats = { label : 0.0 for label in self.site_labels }
for site in self.sites:
occupation_stats[ site.label ] += site.time_occupied
for label in self.site_labels:
occupation_stats[ label ] /= self.time
... |
<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_site_energies( self, energies ):
""" Set the energies for every site in the lattice according to the site labels. Args: energies (Dict(Str:Float):
Dicti... |
self.site_energies = energies
for site_label in energies:
for site in self.sites:
if site.label == site_label:
site.energy = energies[ site_label ] |
<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_cn_energies( self, cn_energies ):
""" Set the coordination number dependent energies for this lattice. Args: cn_energies (Dict(Str:Dict(Int:Float))):
Di... |
for site in self.sites:
site.set_cn_occupation_energies( cn_energies[ site.label ] )
self.cn_energies = cn_energies |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def site_specific_coordination_numbers( self ):
""" Returns a dictionary of coordination numbers for each site type. Args: None Returns: (Dict(Str:List(Int))) : ... |
specific_coordination_numbers = {}
for site in self.sites:
specific_coordination_numbers[ site.label ] = site.site_specific_neighbours()
return specific_coordination_numbers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transmute_sites( self, old_site_label, new_site_label, n_sites_to_change ):
""" Selects a random subset of sites with a specific label and gives them a diffe... |
selected_sites = self.select_sites( old_site_label )
for site in random.sample( selected_sites, n_sites_to_change ):
site.label = new_site_label
self.site_labels = set( [ site.label for site in self.sites ] ) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connected_sites( self, site_labels=None ):
""" Searches the lattice to find sets of sites that are contiguously neighbouring. Mutually exclusive sets of cont... |
if site_labels:
selected_sites = self.select_sites( site_labels )
else:
selected_sites = self.sites
initial_clusters = [ cluster.Cluster( [ site ] ) for site in selected_sites ]
if site_labels:
blocking_sites = self.site_labels - set( site_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 select_sites( self, site_labels ):
""" Selects sites in the lattice with specified labels. Args: site_labels (List(Str)|Set(Str)|Str):
Labels of sites to se... |
if type( site_labels ) in ( list, set ):
selected_sites = [ s for s in self.sites if s.label in site_labels ]
elif type( site_labels ) is str:
selected_sites = [ s for s in self.sites if s.label is site_labels ]
else:
raise ValueError( str( site_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 merge( self, other_cluster ):
""" Combine two clusters into a single cluster. Args: other_cluster (Cluster):
The second cluster to combine. Returns: (Cluste... |
new_cluster = Cluster( self.sites | other_cluster.sites )
new_cluster.neighbours = ( self.neighbours | other_cluster.neighbours ).difference( new_cluster.sites )
return new_cluster |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.