text
stringlengths
81
112k
Put some boundary to input image. :param data: input data :param crinfo: array with minimum and maximum index along each axis [[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input image is placed into [0, 0, 0]. If crinfo is just series of three numbers, it is used as an...
Function recognize order of crinfo and convert it to proper format. def fix_crinfo(crinfo, to="axis"): """ Function recognize order of crinfo and convert it to proper format. """ crinfo = np.asarray(crinfo) if crinfo.shape[0] == 2: crinfo = crinfo.T return crinfo
Get list of grid edges :param shape: :param inds: :param return_directions: :return: def grid_edges(shape, inds=None, return_directions=True): """ Get list of grid edges :param shape: :param inds: :param return_directions: :return: """ if inds is None: inds = np....
Generate list of edges for a base grid. def gen_grid_2d(shape, voxelsize): """ Generate list of edges for a base grid. """ nr, nc = shape nrm1, ncm1 = nr - 1, nc - 1 # sh = nm.asarray(shape) # calculate number of edges, in 2D: (nrows * (ncols - 1)) + ((nrows - 1) * ncols) nedges = 0 ...
Write nodes and edges to VTK file :param fname: VTK filename :param nodes: :param edges: :param node_flag: set if this node is really used in output :param edge_flag: set if this flag is used in output :return: def write_grid_to_vtk(fname, nodes, edges, node_flag=None, edge_flag=None): """ ...
Add new nodes at the end of the list. def add_nodes(self, coors, node_low_or_high=None): """ Add new nodes at the end of the list. """ last = self.lastnode if type(coors) is nm.ndarray: if len(coors.shape) == 1: coors = coors.reshape((1, coors.size)) ...
Add new edges at the end of the list. :param edge_direction: direction flag :param edge_group: describes group of edges from same low super node and same direction :param edge_low_or_high: zero for low to low resolution, one for high to high or high to low resolution. It is used to set w...
Reconnect edges. :param ndid: id of low resolution edges :param nsplit: number of split :param idxs: indexes of low resolution :param sr_tab: :param ndoffset: :param ed_remove: :param into_or_from: if zero, connection of input edges is done. If one, connection of ...
Run first step of algorithm. Next step is split_voxels :param vtk_filename: :return: def generate_base_grid(self, vtk_filename=None): """ Run first step of algorithm. Next step is split_voxels :param vtk_filename: :return: """ nd, ed, ed_dir = self.gen_gr...
Second step of algorithm :return:() def split_voxels(self, vtk_filename=None): """ Second step of algorithm :return:() """ self.cache = {} self.stats["t graph 10"] = time.time() - self.start_time self.msi = MultiscaleArray(self.data.shape, block_size=self...
Multiply values in block def mul_block(self, index, val): """Multiply values in block""" self._prepare_cache_slice(index) self.msinds[self.cache_slice] *= val
Tool to make simple feature functions take features from feature array by seeds. :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number of features :param seeds: ndarray with seeds. Does not to be linear. :param unique_cls: number of used seeds ...
Return features selected by seeds and unique_cls or selection from features and corresponding seed classes. :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number of features :param seeds: ndarray with seeds. Does not to be linear. :param uniqu...
Expands logical constructions. def expand(self, expression): """Expands logical constructions.""" self.logger.debug("expand : expression %s", str(expression)) if not is_string(expression): return expression result = self._pattern.sub(lambda var: str(self._variables[var.grou...
Creates gutter clients and memoizes them in a registry for future quick access. Args: alias (str or None): Name of the client. Used for caching. If name is falsy then do not use the cache. cache (dict): cache to store gutter managers in. **kwargs: kwargs to be passed the Manger ...
The mod operator is prone to floating point errors, so use decimal. 101.1 % 100 >>> 1.0999999999999943 decimal_context.divmod(Decimal('100.1'), 100) >>> (Decimal('1'), Decimal('0.1')) def _modulo(self, decimal_argument): """ The mod operator is prone to floating point ...
Checks to see if this switch is enabled for the provided input. If ``compounded``, all switch conditions must be ``True`` for the switch to be enabled. Otherwise, *any* condition needs to be ``True`` for the switch to be enabled. The switch state is then checked to see if it is ``GLOB...
Returns if the condition applies to the ``inpt``. If the class ``inpt`` is an instance of is not the same class as the condition's own ``argument``, then ``False`` is returned. This also applies to the ``NONE`` input. Otherwise, ``argument`` is called, with ``inpt`` as the instance an...
List of all switches currently registered. def switches(self): """ List of all switches currently registered. """ results = [ switch for name, switch in self.storage.iteritems() if name.startswith(self.__joined_namespace) ] return results
Returns the switch with the provided ``name``. If ``autocreate`` is set to ``True`` and no switch with that name exists, a ``DISABLED`` switch will be with that name. Keyword Arguments: name -- A name of a switch. def switch(self, name): """ Returns the switch with the...
Register a switch and persist it to the storage. def register(self, switch, signal=signals.switch_registered): ''' Register a switch and persist it to the storage. ''' if not switch.name: raise ValueError('Switch name cannot be blank') switch.manager = self ...
Central interface to verify interactions. `verify` uses a fluent interface:: verify(<obj>, times=2).<method_name>(<args>) `args` can be as concrete as necessary. Often a catch-all is enough, especially if you're working with strict mocks, bc they throw at call time on unwanted, unconfigured a...
Central interface to stub functions on a given `obj` `obj` should be a module, a class or an instance of a class; it can be a Dummy you created with :func:`mock`. ``when`` exposes a fluent interface where you configure a stub in three steps:: when(<obj>).<method_name>(<args>).thenReturn(<value>) ...
Stub a function call with the given arguments Exposes a more pythonic interface than :func:`when`. See :func:`when` for more documentation. Returns `AnswerSelector` interface which exposes `thenReturn`, `thenRaise`, and `thenAnswer` as usual. Always `strict`. Usage:: # Given `dog` is an ...
Patch/Replace a function. This is really like monkeypatching, but *note* that all interactions will be recorded and can be verified. That is, using `patch` you stay in the domain of mockito. Two ways to call this. Either:: patch(os.path.exists, lambda str: True) # two arguments # OR ...
Stub a function call, and set up an expected call count. Usage:: # Given `dog` is an instance of a `Dog` expect(dog, times=1).bark('Wuff').thenReturn('Miau') dog.bark('Wuff') dog.bark('Wuff') # will throw at call time: too many invocations # maybe if you need to ensure th...
Unstubs all stubbed methods and functions If you don't pass in any argument, *all* registered mocks and patched modules, classes etc. will be unstubbed. Note that additionally, the underlying registry will be cleaned. After an `unstub` you can't :func:`verify` anymore because all interactions will...
Verify that no methods have been called on given objs. Note that strict mocks usually throw early on unexpected, unstubbed invocations. Partial mocks ('monkeypatched' objects or modules) do not support this functionality at all, bc only for the stubbed invocations the actual usage gets recorded. So thi...
Verifies that expectations set via `expect` are met E.g.:: expect(os.path, times=1).exists(...).thenReturn(True) os.path('/foo') verifyNoUnwantedInteractions(os.path) # ok, called once If you leave out the argument *all* registered objects will be checked. .. note:: **DANGER...
Ensure stubs are actually used. This functions just ensures that stubbed methods are actually used. Its purpose is to detect interface changes after refactorings. It is meant to be invoked usually without arguments just before :func:`unstub`. def verifyStubbedInvocationsAreUsed(*objs): """Ensure stubs...
Destructure a given function into its host and its name. The 'host' of a function is a module, for methods it is usually its instance or its class. This is safe only for methods, for module wide, globally declared names it must be considered experimental. For all reasonable fn: ``getattr(*get_function...
Return obj for given dotted path. Typical inputs for `path` are 'os' or 'os.path' in which case you get a module; or 'os.path.exists' in which case you get a function from that module. Just returns the given input in case it is not a str. Note: Relative imports not supported. Raises ImportErr...
Split path into (obj, attribute) tuple. Given `path` is 'os.path.exists' will thus return `(os.path, 'exists')` If path is not a str, delegates to `get_function_host(path)` def get_obj_attr_tuple(path): """Split path into (obj, attribute) tuple. Given `path` is 'os.path.exists' will thus return `(os...
Spy an object. Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards. Returns Dummy-like, almost empty object as proxy to `object`. The *returned* object must be injected and used by the code under test; after that all...
Spy usage of given `fn`. Patches the module, class or object `fn` lives in, so that all interactions can be recorded; otherwise executes `fn` as before, so that all side effects happen as before. E.g.:: import time spy(time.time) do_work(...) # nothing injected, uses global p...
Create 'empty' objects ('Mocks'). Will create an empty unconfigured object, that you can pass around. All interactions (method calls) will be recorded and can be verified using :func:`verify` et.al. A plain `mock()` will be not `strict`, and thus all methods regardless of the arguments will return...
Function importPuppetClasses Force the reload of puppet classes @param smartProxyId: smartProxy Id @return RETURN: the API result def importPuppetClasses(self, smartProxyId): """ Function importPuppetClasses Force the reload of puppet classes @param smartProxyId: smart...
Return a list of templates usable by a model. def get_templates(model): """ Return a list of templates usable by a model. """ for template_name, template in templates.items(): if issubclass(template.model, model): yield (template_name, template.layout._meta.verbose_name)
Registers the given layout(s) classes admin site: @pages.register(Page) class Default(PageLayout): pass def attach(*layouts, **kwargs): """ Registers the given layout(s) classes admin site: @pages.register(Page) class Default(PageLayout): pass """ def _model_a...
Function enhance Enhance the object with new item or enhanced items def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'os_default_templates': SubDict(self.api, self.objName, ...
Get required API keys from environment variables. def get_api_envs(): """Get required API keys from environment variables.""" client_id = os.environ.get('CLIENT_ID') user_id = os.environ.get('USER_ID') if not client_id or not user_id: raise ValueError('API keys are not found in the environment'...
Call given API end_point with API keys. :param method: HTTP method (e.g. 'get', 'delete'). :param end_point: API endpoint (e.g. 'users/john/sets'). :param params: Dictionary to be sent in the query string (e.g. {'myparam': 'myval'}) :param client_id: Quizlet client ID as string. :param access_token:...
:return: json with "keyId" as secret and "url" for posting key def request_upload_secret(self, secret_id): """ :return: json with "keyId" as secret and "url" for posting key """ return self._router.post_request_upload_secret(org_id=self.organizationId, ...
Function checkAndCreate Check if a subnet exists and create it if not @param key: The targeted subnet @param payload: The targeted subnet description @param domainId: The domainId to be attached wiuth the subnet @return RETURN: The id of the subnet def checkAndCreate(self, key,...
Function removeDomain Delete a domain from a subnet @param subnetId: The subnet Id @param domainId: The domainId to be attached wiuth the subnet @return RETURN: boolean def removeDomain(self, subnetId, domainId): """ Function removeDomain Delete a domain from a subnet ...
Mark a callable as exclusive :param via: factory for a Lock to guard the callable Guards the callable against being entered again before completion. Explicitly raises a :py:exc:`RuntimeError` on violation. :note: If applied to a method, it is exclusive across all instances. def exclusive(via=threadi...
r""" Mark a class as implementing a Service Each Service class must have a ``run`` method, which does not take any arguments. This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless * the Service has been garbage collected, or * the ServiceUnit has been :py:meth:`~.Serv...
Synchronously run ``payload`` and provide its output If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution. def execute(self, payload, *args, flavour: ModuleType, **kwargs): """ Synchronously run ``payload`` and provide its output If ``*args*`` and/or...
Concurrently run ``payload`` in the background If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution. def adopt(self, payload, *args, flavour: ModuleType, **kwargs): """ Concurrently run ``payload`` in the background If ``*args*`` and/or ``**kwargs`` ...
Start accepting synchronous, asynchronous and service payloads Since services are globally defined, only one :py:class:`ServiceRunner` may :py:meth:`accept` payloads at any time. def accept(self): """ Start accepting synchronous, asynchronous and service payloads Since service...
Shutdown the accept loop and stop running payloads def shutdown(self): """Shutdown the accept loop and stop running payloads""" self._must_shutdown = True self._is_shutdown.wait() self._meta_runner.stop()
View/edit/close milestones on github def milestones(ctx, list, close): """View/edit/close milestones on github """ repos = get_repos(ctx.parent.agile.get('labels')) if list: _list_milestones(repos) elif close: click.echo('Closing milestones "%s"' % close) _close_milestone(re...
Starts a console; modified from code.interact def start_console(local_vars={}): '''Starts a console; modified from code.interact''' transforms.CONSOLE_ACTIVE = True transforms.remove_not_allowed_in_console() sys.ps1 = prompt console = ExperimentalInteractiveConsole(locals=local_vars) console.in...
Transform and push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicat...
Write dict object into file :param obj: the object to be dumped into toml :param f: the file object :param preserve: optional flag to preserve the inline table in result def dump(obj, f, preserve=False): """Write dict object into file :param obj: the object to be dumped into toml :param f: th...
Stringifies a dict as toml :param obj: the object to be dumped into toml :param preserve: optional flag to preserve the inline table in result def dumps(obj, preserve=False): """Stringifies a dict as toml :param obj: the object to be dumped into toml :param preserve: optional flag to preserve the...
Loads licenses from the given directory. def license_loader(lic_dir=LIC_DIR): """Loads licenses from the given directory.""" lics = [] for ln in os.listdir(lic_dir): lp = os.path.join(lic_dir, ln) with open(lp) as lf: txt = lf.read() lic = License(txt) li...
Return pseudo-choice vectors. def get_vector(self, max_choice=3): """Return pseudo-choice vectors.""" vec = {} for dim in ['forbidden', 'required', 'permitted']: if self.meta[dim] is None: continue dim_vec = map(lambda x: (x, max_choice), self.meta[dim]) ...
CLI for tonomi.com using contrib-python-qubell-client To enable completion: eval "$(_NOMI_COMPLETE=source nomi)" def entity(ctx, debug, uncolorize, **kwargs): """ CLI for tonomi.com using contrib-python-qubell-client To enable completion: eval "$(_NOMI_COMPLETE=source nomi)" """ ...
Upload application from file. By default, file name will be used as application name, with "-vXX.YYY" suffix stripped. Application is looked up by one of these classifiers, in order of priority: app-id, app-name, filename. If app-id is provided, looks up existing application and updates its manifest. ...
Exports current account configuration in shell-friendly form. Takes into account explicit top-level flags like --organization. def show_account(): """ Exports current account configuration in shell-friendly form. Takes into account explicit top-level flags like --organization. """ click...
Generates new session token from the given refresh token. :param refresh_token: refresh token to generate from :param verbose: whether expiration time should be added to output def generate_session_token(refresh_token, verbose): """ Generates new session token from the given refresh token. :param r...
Example interface commands def runcommand(cosmology='WMAP5'): """ Example interface commands """ # Return the WMAP5 cosmology concentration predicted for # z=0 range of masses Mi = [1e8, 1e9, 1e10] zi = 0 print("Concentrations for haloes of mass %s at z=%s" % (Mi, zi)) output = commah.run(...
Example ways to interrogate the dataset and plot the commah output def plotcommand(cosmology='WMAP5', plotname=None): """ Example ways to interrogate the dataset and plot the commah output """ # Plot the c-M relation as a functon of redshift xarray = 10**(np.arange(1, 15, 0.2)) yval = 'c' # Speci...
Function enhance Enhance the object with new item or enhanced items def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'puppetclasses': SubDict(self.api, self.objName, self...
Extract the transformers names from a line of code of the form from __experimental__ import transformer1 [,...] and adds them to the globally known dict def add_transformers(line): '''Extract the transformers names from a line of code of the form from __experimental__ import transformer1 [,......
If needed, import a transformer, and adds it to the globally known dict The code inside a module where a transformer is defined should be standard Python code, which does not need any transformation. So, we disable the import hook, and let the normal module import do its job - which is faste...
Scan a source for lines of the form from __experimental__ import transformer1 [,...] identifying transformers to be used. Such line is passed to the add_transformer function, after which it is removed from the code to be executed. def extract_transformers_from_source(source): '''Scan a ...
This function should be called from the console, when it starts. Some transformers are not allowed in the console and they could have been loaded prior to the console being activated. We effectively remove them and print an information message specific to that transformer as written in the transformer ...
Used to convert the source code, making use of known transformers. "transformers" are modules which must contain a function transform_source(source) which returns a tranformed source. Some transformers (for example, those found in the standard library module lib2to3) cannot cop...
Match all requests/responses that satisfy the following conditions: * An Admin App; i.e. the path is something like /admin/some_app/ * The ``include_flag`` is not in the response's content def _match(self, request, response): """Match all requests/responses that satisfy the following condition...
Read the minified CSS file including STATIC_URL in the references to the sprite images. def _chosen_css(self): """Read the minified CSS file including STATIC_URL in the references to the sprite images.""" css = render_to_string(self.css_template, {}) for sprite in self.chosen_sp...
Embed Chosen.js directly in html of the response. def _embed(self, request, response): """Embed Chosen.js directly in html of the response.""" if self._match(request, response): # Render the <link> and the <script> tags to include Chosen. head = render_to_string( ...
Close the I2C bus def clean_up(self): """ Close the I2C bus """ self.log.debug("Closing I2C bus for address: 0x%02X" % self.address) self.bus.close()
Send only the read / write bit def write_quick(self): """ Send only the read / write bit """ self.bus.write_quick(self.address) self.log.debug("write_quick: Sent the read / write bit")
Writes an 8-bit byte to the specified command register def write_byte(self, cmd, value): """ Writes an 8-bit byte to the specified command register """ self.bus.write_byte_data(self.address, cmd, value) self.log.debug( "write_byte: Wrote 0x%02X to command register 0x...
Writes a 16-bit word to the specified command register def write_word(self, cmd, value): """ Writes a 16-bit word to the specified command register """ self.bus.write_word_data(self.address, cmd, value) self.log.debug( "write_word: Wrote 0x%04X to command register 0x...
Writes an 8-bit byte directly to the bus def write_raw_byte(self, value): """ Writes an 8-bit byte directly to the bus """ self.bus.write_byte(self.address, value) self.log.debug("write_raw_byte: Wrote 0x%02X" % value)
Writes a block of bytes to the bus using I2C format to the specified command register def write_block_data(self, cmd, block): """ Writes a block of bytes to the bus using I2C format to the specified command register """ self.bus.write_i2c_block_data(self.address, cmd, bl...
Read an 8-bit byte directly from the bus def read_raw_byte(self): """ Read an 8-bit byte directly from the bus """ result = self.bus.read_byte(self.address) self.log.debug("read_raw_byte: Read 0x%02X from the bus" % result) return result
Read a block of bytes from the bus from the specified command register Amount of bytes read in is defined by length def read_block_data(self, cmd, length): """ Read a block of bytes from the bus from the specified command register Amount of bytes read in is defined by length """...
Read an unsigned byte from the specified command register def read_unsigned_byte(self, cmd): """ Read an unsigned byte from the specified command register """ result = self.bus.read_byte_data(self.address, cmd) self.log.debug( "read_unsigned_byte: Read 0x%02X from co...
Read an unsigned word from the specified command register We assume the data is in little endian mode, if it is in big endian mode then set little_endian to False def read_unsigned_word(self, cmd, little_endian=True): """ Read an unsigned word from the specified command register ...
Attempt to connect to an I2C bus def __connect_to_bus(self, bus): """ Attempt to connect to an I2C bus """ def connect(bus_num): try: self.log.debug("Attempting to connect to bus %s..." % bus_num) self.bus = smbus.SMBus(bus_num) ...
Default user to the current version owner. def get_formset(self, request, obj=None, **kwargs): """ Default user to the current version owner. """ data = super().get_formset(request, obj, **kwargs) if obj: data.form.base_fields['user'].initial = request.user.id return data
Function reload Reload the full object to ensure sync def reload(self): """ Function reload Reload the full object to ensure sync """ realData = self.load() self.clear() self.update(realData)
Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman def updateAfterDecorator(function): """ Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman """ def _updateAfterDecorator(self, *args, **kwargs): ...
Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman def updateBeforeDecorator(function): """ Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman """ def _updateBeforeDecorator(self, *args, **kwargs): ...
Function load Get the list of all objects @return RETURN: A ForemanItem list def load(self): """ Function load Get the list of all objects @return RETURN: A ForemanItem list """ return {x[self.index]: self.itemType(self.api, x['id'], ...
Function checkAndCreate Check if an object exists and create it if not @param key: The targeted object @param payload: The targeted object description @return RETURN: The id of the object def checkAndCreate(self, key, payload): """ Function checkAndCreate Check if an ob...
Class decorator stores all calls into list. Can be used until .invalidate() is called. :return: decorated class def operations(): """ Class decorator stores all calls into list. Can be used until .invalidate() is called. :return: decorated class """ def decorator(func): @wraps(f...
Process actions in the publishing schedule. Returns the number of actions processed. def process_actions(action_ids=None): """ Process actions in the publishing schedule. Returns the number of actions processed. """ actions_taken = 0 action_list = PublishAction.objects.prefetch_related( ...
Return a boolean if Celery tasks are enabled for this app. If the ``GLITTER_PUBLISHER_CELERY`` setting is ``True`` or ``False`` - then that value will be used. However if the setting isn't defined, then this will be enabled automatically if Celery is installed. def celery_enabled(): """ Return a b...
Function checkAndCreate Check if an object exists and create it if not @param key: The targeted object @param payload: The targeted object description @return RETURN: The id of the object def checkAndCreate(self, key, payload): """ Function checkAndCreate Check if an ob...
Collect new style (44.1+) return values to old-style kv-list def __collect_interfaces_return(interfaces): """Collect new style (44.1+) return values to old-style kv-list""" acc = [] for (interfaceName, interfaceData) in interfaces.items(): signalValues = interfaceData.get("signals",...
Guess what api we are using and return as public api does. Private has {'id':'key', 'value':'keyvalue'} format, public has {'key':'keyvalue'} def return_values(self): """ Guess what api we are using and return as public api does. Private has {'id':'key', 'value':'keyvalue'} format, public has {...
Returns activitylog object severity - filter severity ('INFO', DEBUG') start/end - time or log text def get_activitylog(self, after=None, severity=None, start=None, end=None): """ Returns activitylog object severity - filter severity ('INFO', DEBUG') start/end - time or ...
return __cached_json, if accessed withing 300 ms. This allows to optimize calls when many parameters of entity requires withing short time. def json(self): """ return __cached_json, if accessed withing 300 ms. This allows to optimize calls when many parameters of entity requires withing...
Indicated most recent update of the instance, assumption based on: - if currentWorkflow exists, its startedAt time is most recent update. - else max of workflowHistory startedAt is most recent update. def get_most_recent_update_time(self): """ Indicated most recent update of the instanc...
This method tries to guess if instance was update since last time. If return True, definitely Yes, if False, this means more unknown :return: bool def _is_projection_updated_instance(self): """ This method tries to guess if instance was update since last time. If return True, de...