Search is not available for this dataset
text
stringlengths
75
104k
def _x10_command(self, house_code, unit_number, state): """Real implementation""" # log = log or default_logger log = default_logger if state.startswith('xdim') or state.startswith('dim') or state.startswith('bright'): raise NotImplementedError('xdim/dim/bright %r' % ((house...
def _x10_command(self, house_code, unit_number, state): """Real implementation""" # log = log or default_logger log = default_logger # FIXME move these functions? def scale_255_to_8(x): """Scale x from 0..255 to 0..7 0 is considered OFF 8 is ...
def get_parser(): """ Generate an appropriate parser. :returns: an argument parser :rtype: `ArgumentParser` """ parser = argparse.ArgumentParser() parser.add_argument( "package", choices=arg_map.keys(), help="designates the package to test") parser.add_argument("...
def get_command(namespace): """ Get the pylint command for these arguments. :param `Namespace` namespace: the namespace """ cmd = ["pylint", namespace.package] + arg_map[namespace.package] if namespace.ignore: cmd.append("--ignore=%s" % namespace.ignore) return cmd
def _wrapper(func): """ Wraps a generated function so that it catches all Type- and ValueErrors and raises IntoDPValueErrors. :param func: the transforming function """ @functools.wraps(func) def the_func(expr): """ The actual function. :param object expr: the expr...
def xformers(sig): """ Get the list of xformer functions for the given signature. :param str sig: a signature :returns: a list of xformer functions for the given signature. :rtype: list of tuple of a function * str Each function catches all TypeErrors it encounters and raises corresponding...
def xformer(signature): """ Returns a transformer function for the given signature. :param str signature: a dbus signature :returns: a function to transform a list of objects to inhabit the signature :rtype: (list of object) -> (list of object) """ funcs = [f for (f, _) in xformers(signatu...
def _variant_levels(level, variant): """ Gets the level for the variant. :param int level: the current variant level :param int variant: the value for this level if variant :returns: a level for the object and one for the function :rtype: int * int """ r...
def _handle_variant(self): """ Generate the correct function for a variant signature. :returns: function that returns an appropriate value :rtype: ((str * object) or list)-> object """ def the_func(a_tuple, variant=0): """ Function for generating...
def _handle_array(toks): """ Generate the correct function for an array signature. :param toks: the list of parsed tokens :returns: function that returns an Array or Dictionary value :rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str """ if len(toks...
def _handle_struct(toks): """ Generate the correct function for a struct signature. :param toks: the list of parsed tokens :returns: function that returns an Array or Dictionary value :rtype: ((list or tuple) -> (Struct * int)) * str """ subtrees = toks[1:-1] ...
def _handle_base_case(klass, symbol): """ Handle a base case. :param type klass: the class constructor :param str symbol: the type code """ def the_func(value, variant=0): """ Base case. :param int variant: variant level for this obj...
def signature(dbus_object, unpack=False): """ Get the signature of a dbus object. :param dbus_object: the object :type dbus_object: a dbus object :param bool unpack: if True, unpack from enclosing variant type :returns: the corresponding signature :rtype: str """ # pylint: disable=t...
def plot_indices(mis, dims=None, weights=None, groups=1,legend = True,index_labels=None, colors = None,axis_labels = None,size_exponent=0.1,ax=None): ''' Plot multi-index set :param mis: Multi-index set :type mis: Iterable of SparseIndices :param dims: Which dimensions to use for plotting :...
def ezplot(f,xlim,ylim=None,ax = None,vectorized=True,N=None,contour = False,args=None,kwargs=None,dry_run=False,show=None,include_endpoints=False): ''' Plot polynomial approximation. :param vectorized: `f` can handle an array of inputs ''' kwargs = kwargs or {} args = args or [] d = 1 ...
def plot3D(X, Y, Z): ''' Surface plot. Generate X and Y using, for example X,Y = np.mgrid[0:1:50j, 0:1:50j] or X,Y= np.meshgrid([0,1,2],[1,2,3]). :param X: 2D-Array of x-coordinates :param Y: 2D-Array of y-coordinates :param Z: 2D-Array of z-coordinates ...
def plot_convergence(times, values, name=None, title=None, reference='self', convergence_type='algebraic', expect_residuals=None, expect_times=None, plot_rate='fit', base = np.exp(0),xlabel = 'x', p=2, preasymptotics=True, stagnation=False, marker='.', legend='lower left',relat...
def lower(option,value): ''' Enforces lower case options and option values where appropriate ''' if type(option) is str: option=option.lower() if type(value) is str: value=value.lower() return (option,value)
def to_float(option,value): ''' Converts string values to floats when appropriate ''' if type(value) is str: try: value=float(value) except ValueError: pass return (option,value)
def to_bool(option,value): ''' Converts string values to booleans when appropriate ''' if type(value) is str: if value.lower() == 'true': value=True elif value.lower() == 'false': value=False return (option,value)
def fork(self,name): ''' Create fork and store it in current instance ''' fork=deepcopy(self) self[name]=fork return fork
def smart_range(*args): ''' smart_range(1,3,9)==[1,3,5,7,9] ''' if len(args)==1:#String string_input = True string = args[0].replace(' ','') original_args=string.split(',') args = [] for arg in original_args: try: args.append(ast.litera...
def ld_to_dl(ld): ''' Convert list of dictionaries to dictionary of lists ''' if ld: keys = list(ld[0]) dl = {key:[d[key] for d in ld] for key in keys} return dl else: return {}
def chain(*fs): ''' Concatenate functions ''' def chained(x): for f in reversed(fs): if f: x=f(x) return x return chained
def split_list(l,N): ''' Subdivide list into N lists ''' npmode = isinstance(l,np.ndarray) if npmode: l=list(l) g=np.concatenate((np.array([0]),np.cumsum(split_integer(len(l),length=N)))) s=[l[g[i]:g[i+1]] for i in range(N)] if npmode: s=[np.array(sl) for sl in s] ret...
def random_word(length,dictionary = False):#may return offensive words if dictionary = True ''' Creates random lowercase words from dictionary or by alternating vowels and consonants The second method chooses from 85**length words. The dictionary method chooses from 3000--12000 words for 3<=length<...
def string_from_seconds(seconds): ''' Converts seconds into elapsed time string of form (X days(s)?,)? HH:MM:SS.YY ''' td = str(timedelta(seconds = seconds)) parts = td.split('.') if len(parts) == 1: td = td+'.00' elif len(parts) == 2: td = '.'.join([parts[0],p...
def input_with_prefill(prompt, text): ''' https://stackoverflow.com/questions/8505163/is-it-possible-to-prefill-a-input-in-python-3s-command-line-interface ''' def hook(): readline.insert_text(text) readline.redisplay() try: readline.set_pre_input_hook(hook) except Except...
def EasyHPC(backend:In('MP', 'MPI')|Function='MP', n_tasks:In('implicitly many', 'many', 'one', 'count')='one',#Count is special case of implicitly many where it is already known how to split jobs n_results:In('many', 'one')='one', aux_output:Bool=True, # Parellelize only first ent...
def path_from_keywords(keywords,into='path'): ''' turns keyword pairs into path or filename if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy ''' subdirs = [] def prepare_string(s): s = str(s) s = re.sub('[]...
def find_files(pattern, path=None,match_name=False): ''' https://stackoverflow.com/questions/1724693/find-a-file-in-python WARNING: pattern is by default matched to entire path not to file names ''' if not path: path = os.getcwd() result = [] for root, __, files in os.walk(path): ...
def find_directories(pattern, path=None,match_name=False): ''' WARNING: pattern is matched to entire path, not directory names, unless match_name = True ''' if not path: path = os.getcwd() result = [] for root, __, __ in os.walk(path): match_against = os.path.basename(root) i...
def zip_dir(zip_name, source_dir,rename_source_dir=False): ''' https://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory ''' src_path = Path(source_dir).expanduser().resolve() with ZipFile(zip_name, 'w', ZIP_DEFLATED) as zf: for file in src_path.rglob('*'): ...
def integral(A=None,dF=None,F=None,axis = 0,trapez = False,cumulative = False): ''' Turns an array A of length N (the function values in N points) and an array dF of length N-1 (the masses of the N-1 intervals) into an array of length N (the integral \int A dF at N points, with first entry 0) :...
def toeplitz_multiplication(a,b,v): ''' Multiply Toeplitz matrix with first row a and first column b with vector v Normal matrix multiplication would require storage and runtime O(n^2); embedding into a circulant matrix and using FFT yields O(log(n)n) ''' a = np.reshape(a,(-1)) b = np.r...
def grid_evaluation(X, Y, f,vectorized=True): ''' Evaluate function on given grid and return values in grid format Assume X and Y are 2-dimensional arrays containing x and y coordinates, respectively, of a two-dimensional grid, and f is a function that takes 1-d arrays with two entries. This f...
def orthonormal_complement_basis(v:NDim(1)): ''' Return orthonormal basis of complement of vector. :param v: 1-dimensional numpy array :return: Matrix whose .dot() computes coefficients w.r.t. an orthonormal basis of the complement of v (i.e. whose row vectors form an orthonormal basis of...
def weighted_median(values, weights): ''' Returns element such that sum of weights below and above are (roughly) equal :param values: Values whose median is sought :type values: List of reals :param weights: Weights of each value :type weights: List of positive reals :return: value of w...
def log_calls(function): ''' Decorator that logs function calls in their self.log ''' def wrapper(self,*args,**kwargs): self.log.log(group=function.__name__,message='Enter') function(self,*args,**kwargs) self.log.log(group=function.__name__,message='Exit') return wrapper
def add_runtime(function): ''' Decorator that adds a runtime profile object to the output ''' def wrapper(*args,**kwargs): pr=cProfile.Profile() pr.enable() output = function(*args,**kwargs) pr.disable() return pr,output return wrapper
def print_memory(function): ''' Decorator that prints memory information at each call of the function ''' import memory_profiler def wrapper(*args,**kwargs): m = StringIO() temp_func = memory_profiler.profile(func = function,stream=m,precision=4) output = temp_func(*args,**kw...
def print_profile(function): ''' Decorator that prints memory and runtime information at each call of the function ''' import memory_profiler def wrapper(*args,**kwargs): m=StringIO() pr=cProfile.Profile() pr.enable() temp_func = memory_profiler.profile(func=function,...
def declaration(function): ''' Declare abstract function. Requires function to be empty except for docstring describing semantics. To apply function, first argument must come with implementation of semantics. ''' function,name=_strip_function(function) if not function.__code__.co_code ...
def print_runtime(function): ''' Decorator that prints running time information at each call of the function ''' def wrapper(*args,**kwargs): pr=cProfile.Profile() pr.enable() output = function(*args,**kwargs) pr.disable() ps = pstats.Stats(pr) ps.sort_sta...
def print_peak_memory(func,stream = None): """ Print peak memory usage (in MB) of a function call :param func: Function to be called :param stream: Stream to write peak memory usage (defaults to stdout) https://stackoverflow.com/questions/9850995/tracking-maximum-memory-usage-by-a-python...
def validate(arg, spec): ''' Make sure `arg` adheres to specification :param arg: Anything :param spec: Specification :type spec: Specification :return: Validated object ''' rejection_subreason = None if spec is None: return arg try: return spec._validat...
def _validate_many(args, specs, defaults,passed_conditions,value_conditions, allow_unknowns,unknowns_spec): ''' Similar to validate but validates multiple objects at once, each with their own specification. Fill objects that were specified but not provided with NotPassed or default ...
def black_scholes(times,r,sigma,S0,d,M,dW=None): ''' Return M Euler-Maruyama sample paths with N time steps of S_t, where dS_t = S_t*r*dt+S_t*sigma*dW_t S(0)=S0 :rtype: M x N x d array ''' N=len(times) times = times.flatten() p0 = np.log(S0) if dW is None: d...
def heston(times,mu,rho,kappa,theta,xi,S0,nu0,d,M,nu_1d=True): ''' Return M Euler-Maruyama sample paths with N time steps of (S_t,v_t), where (S_t,v_t) follows the Heston model of mathematical finance :rtype: M x N x d array ''' d_nu = 1 if nu_1d else d nu = np.zeros((M,len(times),d_nu)...
def fBrown(H,T,N,M,dW = None,cholesky = False): ''' Sample fractional Brownian motion with differentiability index H on interval [0,T] (H=1/2 yields standard Brownian motion) :param H: Differentiability, larger than 0 :param T: Final time :param N: Number of time steps :param M: Number...
def r_bergomi(H,T,eta,xi,rho,S0,r,N,M,dW=None,dW_orth=None,cholesky = False,return_v=False): ''' Return M Euler-Maruyama sample paths with N time steps of (S_t,v_t), where (S_t,v_t) follows the rBergomi model of mathematical finance :rtype: M x N x d array ''' times = np.linspace(0, T, N) ...
def unique(seq): ''' https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order ''' has = [] return [x for x in seq if not (x in has or has.append(x))]
def get_default_fields(self): """ get all fields of model, execpt id """ field_names = self._meta.get_all_field_names() if 'id' in field_names: field_names.remove('id') return field_names
def get_field_value(self, field, value_verbose=True): """ 返回显示的值,而不是单纯的数据库中的值 field 是model中的field type value_verbose 为True,返回数据的显示数据,会转换为choice的内容, 如果value_verbose 为False, 返回数据的实际值 """ if not value_verbose: """ value_verbose == false, retu...
def get_fields(self, field_verbose=True, value_verbose=True, fields=[], extra_fields=[], remove_fields = []): ''' 返回字段名及其对应值的列表 field_verbose 为True,返回定义中的字段的verbose_name, False返回其name value_verbose 为True,返回数据的显示数据,会转换为choice的内容,为False, 返回数据的实际值 fields 指定了要显示的字段 extra_fiel...
def get_url(request): """ 通过menu_id,获取对应的URL eg. /easyui/MenuListView/ """ menu_id = request.GET.get('menu_id') m_object = Menu.objects.get(pk=menu_id) namespace = m_object.namespace viewname = m_object.viewname url_string = '%s:%s' %(namespace, viewname) url = reverse(url_strin...
def post(self, request, *args, **kwargs): """ Handles POST requests only argument: row_index HTML中第几行的标记,原值返回 app_label model_name pk app_label + model_name + pk 可以获取一个object method object + method 得到要调用的方法 其它参数,html和met...
def get_menu_checked(self, request): """ 获取用户或者用户组checked的菜单列表 usermenu_form.html 中定义 usermenu 这两个model的定义类似,比如menus_checked和menus_show groupmenu @return eg. ['1', '8', '9', '10' ] 获取用户或者用户组的check_ids,会给出app_label, model_name, pk eg. /easyui/menulistview/?app_la...
def fetch(self, url, path, filename): """Verify if the file is already downloaded and complete. If they don't exists or if are not complete, use homura download function to fetch files. Return a list with the path of the downloaded file and the size of the remote file. """ ...
def validate_bands(self, bands): """Validate bands parameter.""" if not isinstance(bands, list): logger.error('Parameter bands must be a "list"') raise TypeError('Parameter bands must be a "list"') valid_bands = list(range(1, 12)) + ['BQA'] for band in bands: ...
def validate_sceneInfo(self): """Check scene name and whether remote file exists. Raises WrongSceneNameError if the scene name is wrong. """ if self.sceneInfo.prefix not in self.__satellitesMap: logger.error('Google Downloader: Prefix of %s (%s) is invalid' % ...
def download(self, bands, download_dir=None, metadata=False): """Download remote .tar.bz file.""" super(GoogleDownloader, self).validate_bands(bands) pattern = re.compile('^[^\s]+_(.+)\.tiff?', re.I) image_list = [] band_list = ['B%i' % (i,) if isinstance(i, int) else i for i in ...
def validate_sceneInfo(self): """Check whether sceneInfo is valid to download from AWS Storage.""" if self.sceneInfo.prefix not in self.__prefixesValid: raise WrongSceneNameError('AWS: Prefix of %s (%s) is invalid' % (self.sceneInfo.name, self.sceneInfo.prefix))
def remote_file_exists(self): """Verify whether the file (scene) exists on AWS Storage.""" url = join(self.base_url, 'index.html') return super(AWSDownloader, self).remote_file_exists(url)
def download(self, bands, download_dir=None, metadata=False): """Download each specified band and metadata.""" super(AWSDownloader, self).validate_bands(bands) if download_dir is None: download_dir = DOWNLOAD_DIR dest_dir = check_create_folder(join(download_dir, self.sceneIn...
def open_archive(fs_url, archive): """Open an archive on a filesystem. This function tries to mimick the behaviour of `fs.open_fs` as closely as possible: it accepts either a FS URL or a filesystem instance, and will close all resources it had to open. Arguments: fs_url (FS or text_type): ...
def iso_name_slugify(name): """Slugify a name in the ISO-9660 way. Example: >>> slugify('épatant') "_patant" """ name = name.encode('ascii', 'replace').replace(b'?', b'_') return name.decode('ascii')
def iso_name_increment(name, is_dir=False, max_length=8): """Increment an ISO name to avoid name collision. Example: >>> iso_name_increment('foo.txt') 'foo1.txt' >>> iso_name_increment('bar10') 'bar11' >>> iso_name_increment('bar99', max_length=5) 'ba100' """...
def iso_path_slugify(path, path_table, is_dir=False, strict=True): """Slugify a path, maintaining a map with the previously slugified paths. The path table is used to prevent slugified names from collisioning, using the `iso_name_increment` function to deduplicate slugs. Example: >>> path_tabl...
def get_querydict(self): """ 这个函数跟 self.method有关 self.method 暂时没用, querydict都是POST的 """ if self.method: querydict = getattr(self.request, self.method.upper()) else: querydict = getattr(self.request, 'POST'.upper()) # copy make querydict ...
def get_filter_dict(self): ''' 处理过滤字段 rows 一页显示多少行 page 第几页, 1开始 order desc, asc sort 指定排序的字段 order_by(sort) querydict 中的字段名和格式需要可以直接查询 ''' querydict = self.get_querydict() # post ,在cookie中设置了csrfmiddlewaretoken if qu...
def get_slice_start(self): """ 返回queryset切片的头 """ value = None if self.easyui_page: value = (self.easyui_page -1) * self.easyui_rows return value
def get_slice_end(self): """ 返回queryset切片的尾巴 """ value = None if self.easyui_page: value = self.easyui_page * self.easyui_rows return value
def get_queryset(self): """ queryset """ filter_dict = self.get_filter_dict() queryset = super(EasyUIListMixin, self).get_queryset() queryset = queryset.filter(**filter_dict) if self.easyui_order: # 如果指定了排序字段,返回排序的queryset queryset = quer...
def get_limit_queryset(self): """ 返回分页之后的queryset """ queryset = self.get_queryset() limit_queryset = queryset.all()[self.get_slice_start() :self.get_slice_end()] #等增加排序 return limit_queryset
def get_easyui_context(self, **kwargs): """ 初始化一个空的context """ context = {} queryset = self.get_queryset() limit_queryset = self.get_limit_queryset() data = model_serialize(limit_queryset, self.extra_fields, self.remove_fields) count = queryset.count() ...
def register_views(app_name, view_filename, urlpatterns=None): """ app_name APP名 view_filename views 所在的文件 urlpatterns url中已经存在的urlpatterns return urlpatterns 只导入View结尾的,是类的视图 """ app_module = __import__(app_name) view_module = getattr(app_module, view_filename) v...
def get_template_names(self): """ datagrid的默认模板 """ names = super(EasyUIDatagridView, self).get_template_names() names.append('easyui/datagrid.html') return names
def get_template_names(self): """ datagrid的默认模板 """ names = super(EasyUICreateView, self).get_template_names() names.append('easyui/form.html') return names
def get_template_names(self): """ datagrid的默认模板 """ names = super(EasyUIUpdateView, self).get_template_names() names.append('easyui/form.html') return names
def get_template_names(self): """ datagrid的默认模板 """ names = super(EasyUIDeleteView, self).get_template_names() names.append('easyui/confirm_delete.html') return names
def get_template_names(self): """ datagrid的默认模板 """ names = super(CommandDatagridView, self).get_template_names() names.append('easyui/command_datagrid.html') return names
def dispatch(self, request, *args, **kwargs): """ 增加了权限控制,当self存在model和permission_required时,才会检查权限 """ if getattr(self, 'model', None) and self.permission_required: app_label = self.model._meta.app_label model_name = self.model.__name__.lower() permiss...
def writable_path(path): """Test whether a path can be written to. """ if os.path.exists(path): return os.access(path, os.W_OK) try: with open(path, 'w'): pass except (OSError, IOError): return False else: os.remove(path) return True
def writable_stream(handle): """Test whether a stream can be written to. """ if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5): return handle.writable() try: handle.write(b'') except (io.UnsupportedOperation, IOError): return False else: return True
def from_curvilinear(cls, x, y, z, formatter=numpy_formatter): """Construct a contour generator from a curvilinear grid. Note ---- This is an alias for the default constructor. Parameters ---------- x : array_like x coordinates of each point in `z`. ...
def from_rectilinear(cls, x, y, z, formatter=numpy_formatter): """Construct a contour generator from a rectilinear grid. Parameters ---------- x : array_like x coordinates of each column of `z`. Must be the same length as the number of columns in `z`. (len(x) =...
def from_uniform( cls, z, origin=(0, 0), step=(1, 1), formatter=numpy_formatter): """Construct a contour generator from a uniform grid. NOTE ---- The default `origin` and `step` values is equivalent to calling :meth:`matplotlib.axes.Axes.contour` with only the `z` ar...
def options(self, parser, env=None): """ Sphinx config file that can optionally take the following python template string arguments: ``database_name`` ``database_password`` ``database_username`` ``database_host`` ``database_port`` ``sphinx_search_...
def _wait_for_connection(self, port): """ Wait until we can make a socket connection to sphinx. """ connected = False max_tries = 10 num_tries = 0 wait_time = 0.5 while not connected or num_tries >= max_tries: time.sleep(wait_time) ...
def get_unique_token(self): """ Get a unique token for usage in differentiating test runs that need to run in parallel. """ if self._unique_token is None: self._unique_token = self._random_token() return self._unique_token
def _random_token(self, bits=128): """ Generates a random token, using the url-safe base64 alphabet. The "bits" argument specifies the bits of randomness to use. """ alphabet = string.ascii_letters + string.digits + '-_' # alphabet length is 64, so each letter provides lg...
def url(self): """Returns the url of the poll. If the poll has not been submitted yet, an empty string is returned instead. """ if self.id is None: return '' return '{}/{}'.format(strawpoll.API._BASE_URL, self.id)
def get_poll(self, arg, *, request_policy=None): """Retrieves a poll from strawpoll. :param arg: Either the ID of the poll or its strawpoll url. :param request_policy: Overrides :attr:`API.requests_policy` for that \ request. :type request_policy: Optional[:class:`RequestsPolicy...
def submit_poll(self, poll, *, request_policy=None): """Submits a poll on strawpoll. :param poll: The poll to submit. :type poll: :class:`Poll` :param request_policy: Overrides :attr:`API.requests_policy` for that \ request. :type request_policy: Optional[:class:`Request...
def numpy_formatter(_, vertices, codes=None): """`NumPy`_ style contour formatter. Contours are returned as a list of Nx2 arrays containing the x and y vertices of the contour line. For filled contours the direction of vertices matters: * CCW (ACW): The vertices give the exterior of a contour pol...
def matlab_formatter(level, vertices, codes=None): """`MATLAB`_ style contour formatter. Contours are returned as a single Nx2, `MATLAB`_ style, contour array. There are two types of rows in this format: * Header: The first element of a header row is the level of the contour (the lower level for...
def shapely_formatter(_, vertices, codes=None): """`Shapely`_ style contour formatter. Contours are returned as a list of :class:`shapely.geometry.LineString`, :class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point` geometry elements. Filled contours return a list of :class:`shap...
def contour(self, level): """Get contour lines at the given level. Parameters ---------- level : numbers.Number The data level to calculate the contour lines for. Returns ------- : The result of the :attr:`formatter` called on the contour...
def filled_contour(self, min=None, max=None): """Get contour polygons between the given levels. Parameters ---------- min : numbers.Number or None The minimum data level of the contour polygon. If :obj:`None`, ``numpy.finfo(numpy.float64).min`` will be used. ...