code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
def GroupsUsersPost(self, parameters, group_id): if self.__SenseApiCall__('/groups/{group_id}/users.json'.format(group_id = group_id), 'POST', parameters = parameters): return True else: self.__error__ = "api call unsuccessful" return False
Add users to a group in CommonSense. @param parameters (dictonary) - Dictionary containing the users to add. @return (bool) - Boolean indicating whether GroupsPost was successful.
null
null
null
def GroupsUsersDelete(self, group_id, user_id): 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
Delete a user from a group in CommonSense. @return (bool) - Boolean indicating whether GroupsPost was successful.
null
null
null
def SensorShare(self, sensor_id, parameters): 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), "POS...
Share a sensor with a user @param sensor_id (int) - Id of sensor to be shared @param parameters (dictionary) - Additional parameters for the call @return (bool) - Boolean indicating whether the ShareSensor call was successful
null
null
null
def GroupsSensorsPost(self, group_id, sensors): if self.__SenseApiCall__("/groups/{0}/sensors.json".format(group_id), "POST", parameters = sensors): return True else: self.__error__ = "api call unsuccessful" return False
Share a number of sensors within a group. @param group_id (int) - Id of the group to share sensors with @param sensors (dictionary) - Dictionary containing the sensors to share within the groups @return (bool) - Boolean indicating whether the GroupsSens...
null
null
null
def GroupsSensorsGet(self, group_id, parameters): if self.__SenseApiCall("/groups/{0}/sensors.json".format(group_id), "GET", parameters = parameters): return True else: self.__error__ = "api call unsuccessful" return False
Retrieve sensors shared within the group. @param group_id (int) - Id of the group to retrieve sensors from @param parameters (dictionary) - Additional parameters for the call @return (bool) - Boolean indicating whether GroupsSensorsGet was successful
null
null
null
def GroupsSensorsDelete(self, group_id, sensor_id): if self.__SenseApiCall__("/groups/{0}/sensors/{1}.json".format(group_id, sensor_id), "DELETE"): return True else: self.__error__ = "api call unsuccessful" return False
Stop sharing a sensor within a group @param group_id (int) - Id of the group to stop sharing the sensor with @param sensor_id (int) - Id of the sensor to stop sharing @return (bool) - Boolean indicating whether GroupsSensorsDelete was successful
null
null
null
def DomainsGet(self, parameters = None, domain_id = -1): 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): ...
This method returns the domains of the current user. The list also contains the domains to which the users has not yet been accepted. @param parameters (dictonary) - Dictionary containing the parameters of the request. @return (...
null
null
null
def DomainUsersGet(self, domain_id, parameters): if self.__SenseApiCall__('/domains/{0}/users.json'.format(domain_id), 'GET', parameters = parameters): return True else: self.__error__ = "api call unsuccessful" return False
Retrieve users of the specified domain. @param domain_id (int) - Id of the domain to retrieve users from @param parameters (int) - parameters of the api call. @return (bool) - Boolean idicating whether DomainUsersGet was successful.
null
null
null
def DomainTokensGet(self, domain_id): if self.__SenseApiCall__('/domains/{0}/tokens.json'.format(domain_id), 'GET'): return True else: self.__error__ = "api call unsuccessful" return False
T his method returns the list of tokens which are available for this domain. Only domain managers can list domain tokens. @param domain_id - ID of the domain for which to retrieve tokens @return (bool) - Boolean indicating whether DomainTokensGet was s...
null
null
null
def DomainTokensCreate(self, domain_id, amount): if self.__SenseApiCall__('/domains/{0}/tokens.json'.format(domain_id), 'POST', parameters = {"amount":amount}): return True else: self.__error__ = "api call unsuccessful" return False
This method creates tokens that can be used by users who want to join the domain. Tokens are automatically deleted after usage. Only domain managers can create tokens.
null
null
null
def DataProcessorsGet(self, parameters): if self.__SenseApiCall__('/dataprocessors.json', 'GET', parameters = parameters): return True else: self.__error__ = "api call unsuccessful" return False
List the users data processors. @param parameters (dictonary) - Dictionary containing the parameters of the request. @return (bool) - Boolean indicating whether this call was successful.
null
null
null
def DataProcessorsPost(self, parameters): if self.__SenseApiCall__('/dataprocessors.json', 'POST', parameters = parameters): return True else: self.__error__ = "api call unsuccessful" return False
Create a Data processor in CommonSense. If DataProcessorsPost is successful, the data processor and sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string. @param parameters (dictonary) - Dictionary containing the details...
null
null
null
def DataProcessorsDelete(self, dataProcessorId): if self.__SenseApiCall__('/dataprocessors/{id}.json'.format(id = dataProcessorId), 'DELETE'): return True else: self.__error__ = "api call unsuccessful" return False
Delete a data processor in CommonSense. @param dataProcessorId - The id of the data processor that will be deleted. @return (bool) - Boolean indicating whether GroupsPost was successful.
null
null
null
from statsmodels.tools.numdiff import approx_fprime_cs, approx_fprime # return approx_fprime_cs(mu, self) # TODO fix breaks in `fabs # TODO: diag is workaround problem with numdiff for 1d return np.diag(approx_fprime(mu, self))
def deriv(self, mu)
Derivative of the variance function v'(mu)
9.270572
8.86688
1.045528
p = self._clean(mu) return 1 + 2 * self.alpha * p
def deriv(self, mu)
Derivative of the negative binomial variance function.
13.692419
9.954936
1.37544
xT = x.T xtx = spdot(xT, x) xtx_inv = la.inv(xtx) xtx_inv = sp.csr_matrix(xtx_inv) xTy = spdot(xT, y, array_out=False) betas = spdot(xtx_inv, xTy) return betas
def _compute_betas(y, x)
compute MLE coefficients using iwls routine Methods: p189, Iteratively (Re)weighted Least Squares (IWLS), Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002). Geographically weighted regression: the analysis of spatially varying relationships.
2.905587
3.86081
0.752585
xT = (x * wi).T xtx = np.dot(xT, x) xtx_inv_xt = linalg.solve(xtx, xT) betas = np.dot(xtx_inv_xt, y) return betas, xtx_inv_xt
def _compute_betas_gwr(y, x, wi)
compute MLE coefficients using iwls routine Methods: p189, Iteratively (Re)weighted Least Squares (IWLS), Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002). Geographically weighted regression: the analysis of spatially varying relationships.
2.742524
3.709396
0.739345
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_m...
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 ---------- y : array n*1, dependent variable x : array n*k, designs matrix of k independent variables family : family object probability models: Gauss...
3.101265
2.872988
1.079456
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 inte...
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. Also known as 5-smooth numbers or Hamming numbers, these are the optimal size for inputs to FFTPACK. Target must be a positive integer.
2.970471
2.780356
1.068378
# 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: ...
def quantile_1D(data, weights, quantile)
Compute the weighted quantile of a 1D numpy array. Parameters ---------- data : ndarray Input array (one dimension). weights : ndarray Array with the weights of the same size of `data`. quantile : float Quantile to compute. It must have a value between 0 and 1. Returns ...
2.487897
2.47068
1.006969
# 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....
def quantile(data, weights, quantile)
Weighted quantile of an array with respect to the last axis. Parameters ---------- data : ndarray Input array. weights : ndarray Array with the weights. It must have the same size of the last axis of `data`. quantile : float Quantile to compute. It must have a value...
2.911296
2.991674
0.973133
config_block_str = '' for line in config_block: if isinstance(line, config.Option): line_str = self.__render_option(line) elif isinstance(line, config.Config): line_str = self.__render_config(line) elif isinstance(line, config....
def __render_config_block(self, config_block)
Summary Args: config_block [config.Item, ...]: config lines Returns: str: config block str
1.793728
1.754426
1.022402
if args is None: args = {} return self._query('/einfo.fcgi', args, skip_cache=True)
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 Entrez databases) Output: XML containing database statistics Example: Find database statistics for Entrez Protein. QueryService.einfo({'db': 'pr...
8.370492
7.066892
1.184466
if self.__native is None: self.__native = self._get_object() return self.__native
def native_obj(self)
Native storage object.
5.362864
4.259841
1.258935
content_type = self.content_type if content_type in (None, '', 'application/octet-stream'): content_type, _ = mimetypes.guess_type(self.name) return content_type
def smart_content_type(self)
Smart content type.
2.709557
2.550483
1.06237
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
def smart_content_encoding(self)
Smart content encoding.
3.806775
3.751249
1.014802
if self.__native is None: self.__native = self._get_container() return self.__native
def native_container(self)
Native container object.
5.601569
4.174652
1.341805
if self.__native is None: self.__native = self._get_connection() return self.__native
def native_conn(self)
Native connection object.
5.489873
4.188233
1.310785
permitted = lambda c: settings.container_permitted(c.name) return [c for c in self._get_containers() if permitted(c)]
def get_containers(self)
Return available containers.
7.563343
6.400065
1.18176
if not settings.container_permitted(path): raise errors.NotPermittedException( "Access to container \"%s\" is not permitted." % path) return self._get_container(path)
def get_container(self, path)
Return single container.
6.027198
5.613769
1.073646
from boto.s3.key import Key return isinstance(result, Key)
def is_key(cls, result)
Return ``True`` if result is a key object.
8.73787
6.913819
1.263827
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
def validate(self, name, value)
Validate and return a value.
4.036519
3.694829
1.092478
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: ...
def get(self, name, default=None)
Get value.
4.638896
4.351833
1.065964
if value is None: return default elif isinstance(value, bool): return value elif isinstance(value, str): if value == 'True': return True elif value == 'False': return False raise Exception("Value ...
def parse_bool(cls, value, default=None)
Convert ``string`` or ``bool`` to ``bool``.
2.537941
2.414082
1.051307
if self.__container_whitelist is None: self.__container_whitelist = \ set(self.CLOUD_BROWSER_CONTAINER_WHITELIST or []) return self.__container_whitelist
def _container_whitelist(self)
Container whitelist.
5.273767
4.79394
1.10009
if self.__container_blacklist is None: self.__container_blacklist = \ set(self.CLOUD_BROWSER_CONTAINER_BLACKLIST or []) return self.__container_blacklist
def _container_blacklist(self)
Container blacklist.
5.093564
4.65607
1.093962
white = self._container_whitelist black = self._container_blacklist return name not in black and (not white or name in white)
def container_permitted(self, name)
Return whether or not a container is permitted. :param name: Container name. :return: ``True`` if container is permitted. :rtype: ``bool``
4.749992
6.743785
0.704351
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
def app_media_url(self)
Get application media root from real media root URL.
4.762409
4.123647
1.154902
def app_media_doc_root(self): # pylint: disable=R0201 app_dir = os.path.abspath(os.path.dirname(__file__)) media_root = os.path.join(app_dir, 'media') return media_root
Get application media document (file) root.
null
null
null
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
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 .py file is returned. :param filename: filename of the module. :returns: mtime or None if the file doesn"t exist.
1.893337
2.018263
0.938102
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] =...
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 changed, and then module c asks to import script b. :param key: our key used in the WatchList. :returns: True if reloaded.
4.128631
3.998618
1.032514
moduleparts = key.split(".") for partnum, part in enumerate(moduleparts): modkey = ".".join(moduleparts[partnum:]) if modkey in sys.modules: return modkey return None
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: our key to the module. :returns: the key in sys.modules or None.
3.561209
3.733032
0.953972
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_d...
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 has acquired the import lock. :param module: the module to reload.
3.336624
3.203617
1.041518
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_getmti...
def reload_recent_submodules(module, mtime=0, processed=[])
Recursively reload submodules which are more recent than a specified timestamp. To be called from a thread that has acquired the import lock to be thread safe. :param module: the module name. The WatchList is checked for modules that list this as a parent. :param mtime: the latest ...
3.479159
3.377655
1.030052
# 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...
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 time stamp of it, a companion yaml file, or any modules it imports have changed. If so, reimport the module. :params: see __builtin__.__import__
4.658657
4.575659
1.018139
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.p...
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 should be reloaded or not. :param cache: the cache object that stores whether to check for config files and which files have been loaded. :param module: the path of the module to...
3.572416
3.54635
1.00735
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
def get_int(value, default, test_fn=None)
Convert value to integer. :param value: Integer value. :param default: Default value on failed conversion. :param test_fn: Constraint function. Use default if returns ``False``. :return: Integer value. :rtype: ``int``
2.799268
3.009029
0.930289
vers = tuple(int(v) for v in mod.__version__.split('.')[:3]) if vers < required: req = '.'.join(str(v) for v in required) raise ImproperlyConfigured( "Module \"%s\" version (%s) must be >= %s." % (mod.__name__, mod.__version__, req))
def check_version(mod, required)
Require minimum version of module using ``__version__`` member.
2.795267
2.711669
1.030829
def wrapped(method): if module is None: raise ImproperlyConfigured("Module '%s' is not installed." % name) return method return wrapped
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 is not installed) but still allow the rest of the python package to compile and run fine. If the wrapped method with this decorated is invoked, then a runtime error is generated...
8.567882
6.491967
1.319767
# Normalize string and adjust for milliseconds. Note that Python 2.6+ has # ".%f" format, but we're going for Python 2.5, so truncate the portion. date_str = date_str.rstrip('Z').split('.')[0] # Format string. (2010-04-13T14:02:48.000Z) fmt = "%Y-%m-%dT%H:%M:%S" # Python 2.6+: Could format...
def dt_from_rfc8601(date_str)
Convert 8601 (ISO) date string to datetime object. Handles "Z" and milliseconds transparently. :param date_str: Date string. :type date_str: ``string`` :return: Date time. :rtype: :class:`datetime.datetime`
5.330966
5.572176
0.956712
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
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: Date time. :rtype: :class:`datetime.datetime` or ``None``
3.033598
3.321432
0.91334
base_path = path.strip(SEP) sep_ind = base_path.rfind(SEP) if sep_ind < 0: return path return base_path[sep_ind + 1:]
def basename(path)
Rightmost part of path after separator.
3.191626
3.105122
1.027858
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
def path_parts(path)
Split path into container, object. :param path: Path to resource (including container). :type path: `string` :return: Container, storage object tuple. :rtype: `tuple` of `string`, `string`
3.120075
3.275774
0.95247
for part in (x for x in path.strip(SEP).split(SEP) if x not in (None, '')): yield part
def path_yield(path)
Yield on all path parts.
5.47985
4.577446
1.197141
return SEP.join((x for x in args if x not in (None, ''))).strip(SEP)
def path_join(*args)
Join path parts to single path.
5.35331
5.070752
1.055723
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) paren...
def relpath(path, start)
Get relative path to start. Note: Modeled after python2.6 :meth:`os.path.relpath`.
4.185738
4.292946
0.975027
return sum( np.square( sum( [ atom.dr for atom in self.atoms ] ) ) )
def collective_dr_squared( self )
Squared sum of total displacements for these atoms. Args: None Returns: (Float): The square of the summed total displacements for these atoms.
8.870155
7.323548
1.211183
return sum( atom.site.label == site_label for atom in self.atoms )
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. Returns: (Int): Number of atoms occupying sites of type `site_label`.
9.210104
10.963505
0.840069
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)
def get_class(class_string)
Convert a string version of a function name to the callable object.
3.098051
2.963418
1.045432
try: dot = class_string.rindex('.') except ValueError: return class_string, '' return class_string[:dot], class_string[dot + 1:]
def get_mod_func(class_string)
Converts 'django.views.news.stories.story_detail' to ('django.views.news.stories', 'story_detail') Taken from django.core.urlresolvers
2.834995
2.197427
1.290143
return (cls.is_key(result) and result.size == 0 and result.name.endswith(cls._gs_folder_suffix))
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 place holder if there are no files present.
6.26068
5.021488
1.246778
from boto.gs.key import Key return isinstance(result, Key)
def is_key(cls, result)
Return ``True`` if result is a key object.
12.49706
9.522243
1.312407
from boto.s3.prefix import Prefix return isinstance(result, Prefix) or cls._is_gs_folder(result)
def is_prefix(cls, result)
Return ``True`` if result is a prefix object. .. note:: Boto uses the S3 Prefix object for GS prefixes.
8.925733
6.507046
1.371703
if cls._is_gs_folder(prefix): name, suffix, extra = prefix.name.partition(cls._gs_folder_suffix) if (suffix, extra) == (cls._gs_folder_suffix, ''): # Patch GS specific folder to remove suffix. prefix.name = name return super(GsObject, cls...
def from_prefix(cls, container, prefix)
Create from prefix object.
6.082087
5.659605
1.074649
# Get basename of implied folder. folder = path.split(SEP)[-1] # Query extra objects, then strip 0-byte dummy object if present. objs = super(GsContainer, self).get_objects(path, marker, limit + 1) objs = [o for o in objs if not (o.size == 0 and o.name == folder)] ...
def get_objects(self, path, marker=None, limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT)
Get objects. Certain upload clients may add a 0-byte object (e.g., ``FOLDER`` object for path ``path/to/FOLDER`` - ``path/to/FOLDER/FOLDER``). We add an extra +1 limit query and ignore any such file objects.
7.915812
6.579322
1.203135
from boto.exception import StorageResponseError if isinstance(exc, StorageResponseError): if exc.status == 404: return self.error_cls(str(exc)) return None
def translate(self, exc)
Return whether or not to do translation.
5.171856
5.053806
1.023359
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: %...
def from_result(cls, container, result)
Create from ambiguous result.
4.353512
4.061128
1.071996
if prefix is None: raise errors.NoObjectException return cls(container, name=prefix.name, obj_type=cls.type_cls.SUBDIR)
def from_prefix(cls, container, prefix)
Create from prefix object.
13.010516
10.570756
1.230803
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=ke...
def from_key(cls, container, key)
Create from key object.
4.955214
4.757087
1.041649
from itertools import islice path = path.rstrip(SEP) + SEP if path else path result_set = self.native_container.list(path, SEP, marker) # Get +1 results because marker and first item can match as we strip # the separator from results obscuring things. No real problem h...
def get_objects(self, path, marker=None, limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT)
Get objects.
8.425954
8.35126
1.008944
key = self.native_container.get_key(path) return self.obj_cls.from_key(self, key)
def get_object(self, path)
Get single object.
7.182398
6.301273
1.139833
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)
def from_bucket(cls, connection, bucket)
Create from bucket object.
14.809204
14.629819
1.012262
buckets = self.native_conn.get_all_buckets() return [self.cont_cls.from_bucket(self, b) for b in buckets]
def _get_containers(self)
Return available containers.
7.235586
6.18959
1.168993
bucket = self.native_conn.get_bucket(path) return self.cont_cls.from_bucket(self, bucket)
def _get_container(self, path)
Return single container.
8.236163
6.648324
1.238833
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 Aw...
def from_settings(cls)
Create configuration from Django settings or environment.
2.137412
2.12216
1.007187
if cls.__connection_cls is None: cls.__connection_cls, _ = cls.from_settings() return cls.__connection_cls
def get_connection_cls(cls)
Return connection class. :rtype: :class:`type`
4.994865
5.473104
0.91262
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
def get_connection(cls)
Return connection object. :rtype: :class:`cloud_browser.cloud.base.CloudConnection`
3.696459
3.89542
0.948924
return os.path.join(self.container.base_path, self.name)
def base_path(self)
Base absolute path of container.
6.557505
3.818342
1.71737
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 ...
def from_path(cls, container, path)
Create object from path.
2.989869
2.881885
1.03747
def _filter(name): return (not_dot(name) and (marker is None or os.path.join(path, name).strip(SEP) > marker.strip(SEP))) search_path = os.path.join(self.base_path, path) objs = [self.obj_cls.from_path(self, os.path.join...
def get_objects(self, path, marker=None, limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT)
Get objects.
3.760928
3.90876
0.962179
return os.path.join(self.conn.abs_root, self.name)
def base_path(self)
Base absolute path of container.
10.229005
8.172194
1.251684
path = path.strip(SEP) full_path = os.path.join(conn.abs_root, path) return cls(conn, path, 0, os.path.getsize(full_path))
def from_path(cls, conn, path)
Create container from path.
4.194344
4.19125
1.000738
def full_fn(path): return os.path.join(self.abs_root, path) return [self.cont_cls.from_path(self, d) for d in os.listdir(self.abs_root) if is_dir(full_fn(d))]
def _get_containers(self)
Return available containers.
5.416069
4.731116
1.144776
path = path.strip(SEP) if SEP in path: raise errors.InvalidNameException( "Path contains %s - %s" % (SEP, path)) return self.cont_cls.from_path(self, path)
def _get_container(self, path)
Return single container.
5.818626
4.970093
1.170728
if alternating_sites: site_labels = [ 'A', 'B', 'A', 'B' ] else: site_labels = [ 'L', 'L', 'L', 'L' ] unit_cell_lengths = np.array( [ sqrt(3), 3.0, 0.0 ] ) * spacing cell_lengths = unit_cell_lengths * np.array( [ a, b, 1.0 ] ) grid = np.array( list( range( 1, int( a * b * 4 + 1 ...
def honeycomb_lattice( a, b, spacing, alternating_sites=False )
Generate a honeycomb lattice. Args: a (Int): Number of lattice repeat units along x. b (Int): Number of lattice repeat units along y. spacing (Float): Distance between lattice sites. alternating_sites (Bool, optional): Label alternating sites with 'A' and 'B'. Defaul...
1.694317
1.696203
0.998888
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,...
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 units along y. c (Int): Number of lattice repeat units along z. spacing (Float): Distance between lattice sites. Returns: (Lattice)...
1.974809
2.004145
0.985362
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\.]+)' ) ...
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 site information. cell_lengths (List(Float,Float,Float)): A list containing the [ x, y, z ] cell lengths. Returns: (Lattice): The new lattice Notes: | The site information fil...
2.496439
2.266225
1.101585
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',...
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 request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will re...
2.347143
2.323232
1.010292
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
def site_specific_nn_occupation( self )
Returns the number of occupied nearest neighbour sites, classified by site type. Args: None Returns: (Dict(Str:Int)): Dictionary of nearest-neighbour occupied site numbers, classified by site label, e.g. { 'A' : 2, 'B' : 1 }.
4.442038
4.417942
1.005454
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 ...
def cn_occupation_energy( self, delta_occupation=None )
The coordination-number dependent energy for this site. Args: delta_occupation (:obj:Dict(Str:Int), optional): A dictionary of a change in (site-type specific) coordination number, e.g. { 'A' : 1, 'B' : -1 }. If this is not None, the coordination-number dependent energy is calculate...
3.399416
3.060315
1.110806
self.logger.info('Removing obsolete geoip from database...') IpRange.objects.all().delete() City.objects.all().delete() Region.objects.all().delete() Country.objects.all().delete()
def clear_database(self)
Removes all geodata stored in database. Useful for development, never use on production.
5.000494
4.487448
1.114329
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...
def _download_extract_archive(self, url)
Returns dict with 2 extracted filenames
3.646944
3.466102
1.052174
for line in file: delimiter = settings.IPGEOBASE_FILE_FIELDS_DELIMITER yield self._extract_data_from_line(line, field_names, delimiter)
def _line_to_dict(self, file, field_names)
Converts file line into dictonary
8.866825
8.47493
1.046242
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'] ...
def _process_cidr_file(self, file)
Iterate over ip info and extract useful data
2.601764
2.527936
1.029205
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_countr...
def _process_cities_file(self, file, city_country_mapping)
Iterate over cities info and extract useful data
2.619005
2.530715
1.034887
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 countr...
def _update_geography(self, countries, regions, cities, city_country_mapping)
Update database with new countries, regions and cities
2.15823
2.109483
1.023109
new_ip_ranges = [] is_bulk_create_supported = hasattr(IpRange.objects, 'bulk_create') IpRange.objects.all().delete() city_region_mapping = self._build_city_region_mapping() if self.logger.getEffectiveLevel() in [logging.INFO, logging.DEBUG]: pbar = ProgressB...
def _update_cidr(self, cidr)
Rebuild IPRegion table with fresh data (old ip ranges are removed for simplicity)
3.34341
3.133981
1.066825
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 si...
def relative_probability( self, l1, l2, c1, c2 )
The relative probability for a jump between two sites with specific site types and coordination numbers. Args: l1 (Str): Site label for the initial site. l2 (Str): Site label for the final site. c1 (Int): Coordination number for the initial site. c2 (Int): Coordi...
4.908866
4.697962
1.044893
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 ] = {} ...
def generate_nearest_neighbour_lookup_table( self )
Construct a look-up table of relative jump probabilities for a nearest-neighbour interaction Hamiltonian. Args: None. Returns: None.
1.840784
1.744806
1.055008
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 ]
def reset( self )
Reinitialise the stored displacements, number of hops, and list of sites visited for this `Atom`. Args: None Returns: None
5.66663
3.818829
1.483866