INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Derive a new key or secret data from an existing managed object.
def derive_key(self, object_type, unique_identifiers, derivation_method, derivation_parameters, template_attribute, credential=None): """ Derive a new key or secret data from an existing man...
Check object usage according to specific constraints.
def check(self, uuid=None, usage_limits_count=None, cryptographic_usage_mask=None, lease_time=None, credential=None): """ Check object usage according to specific constraints. Args: uuid (string): The unique ident...
Send a GetAttributes request to the server.
def get_attributes(self, uuid=None, attribute_names=None): """ Send a GetAttributes request to the server. Args: uuid (string): The ID of the managed object with which the retrieved attributes should be associated. Optional, defaults to None. ...
Send a GetAttributeList request to the server.
def get_attribute_list(self, uid=None): """ Send a GetAttributeList request to the server. Args: uid (string): The ID of the managed object with which the retrieved attribute names should be associated. Returns: result (GetAttributeListResult): A...
Send a Query request to the server.
def query(self, batch=False, query_functions=None, credential=None): """ Send a Query request to the server. Args: batch (boolean): A flag indicating if the operation should be sent with a batch of additional operations. Defaults to False. query_functions...
Encrypt data using the specified encryption key and parameters.
def encrypt(self, data, unique_identifier=None, cryptographic_parameters=None, iv_counter_nonce=None, credential=None): """ Encrypt data using the specified encryption key and parameters. Args: data (byt...
Verify a message signature using the specified signing key.
def signature_verify(self, message, signature, unique_identifier=None, cryptographic_parameters=None, credential=None): """ Verify a message signature using the specified signing ...
Sign specified data using a specified signing key.
def sign(self, data, unique_identifier=None, cryptographic_parameters=None, credential=None): """ Sign specified data using a specified signing key. Args: data (bytes): Data to be signed. Required. unique_identifier (string): The unique ID of the signing ...
This internal function takes the host string from the config file and turns it into a list: return: LIST host list
def _build_host_list(self, host_list_str): ''' This internal function takes the host string from the config file and turns it into a list :return: LIST host list ''' host_list = [] if isinstance(host_list_str, str): host_list = host_list_str.replace('...
Set the KMIP version for the client.
def kmip_version(self, value): """ Set the KMIP version for the client. Args: value (KMIPVersion): A KMIPVersion enumeration Return: None Raises: ValueError: if value is not a KMIPVersion enumeration Example: >>> client....
Open the client connection.
def open(self): """ Open the client connection. Raises: ClientConnectionFailure: if the client connection is already open Exception: if an error occurs while trying to open the connection """ if self._is_open: raise exceptions.ClientConnection...
Close the client connection.
def close(self): """ Close the client connection. Raises: Exception: if an error occurs while trying to close the connection """ if not self._is_open: return else: try: self.proxy.close() self._is_open =...
Create a symmetric key on a KMIP appliance.
def create(self, algorithm, length, operation_policy_name=None, name=None, cryptographic_usage_mask=None): """ Create a symmetric key on a KMIP appliance. Args: algorithm (CryptographicAlgorithm): An enumeration defining the algorithm to use to generat...
Create an asymmetric key pair on a KMIP appliance.
def create_key_pair(self, algorithm, length, operation_policy_name=None, public_name=None, public_usage_mask=None, private_name=None, private_usage_mask...
Register a managed object with a KMIP appliance.
def register(self, managed_object): """ Register a managed object with a KMIP appliance. Args: managed_object (ManagedObject): A managed object to register. An instantiatable subclass of ManagedObject from the Pie API. Returns: string: The uid of...
Rekey an existing key.
def rekey(self, uid=None, offset=None, **kwargs): """ Rekey an existing key. Args: uid (string): The unique ID of the symmetric key to rekey. Optional, defaults to None. offset (int): The time delta, in seconds, b...
Derive a new key or secret data from existing managed objects.
def derive_key(self, object_type, unique_identifiers, derivation_method, derivation_parameters, **kwargs): """ Derive a new key or secret data from existing managed objects. Args: object_t...
Search for managed objects depending on the attributes specified in the request.
def locate(self, maximum_items=None, storage_status_mask=None, object_group_member=None, attributes=None): """ Search for managed objects, depending on the attributes specified in the request. Args: maximum_items (integer): Maximum number of object identifiers...
Check the constraints for a managed object.
def check(self, uid=None, usage_limits_count=None, cryptographic_usage_mask=None, lease_time=None): """ Check the constraints for a managed object. Args: uid (string): The unique ID of the managed object to check. ...
Get a managed object from a KMIP appliance.
def get(self, uid=None, key_wrapping_specification=None): """ Get a managed object from a KMIP appliance. Args: uid (string): The unique ID of the managed object to retrieve. key_wrapping_specification (dict): A dictionary containing various settings to b...
Get the attributes associated with a managed object.
def get_attributes(self, uid=None, attribute_names=None): """ Get the attributes associated with a managed object. If the uid is not specified, the appliance will use the ID placeholder by default. If the attribute_names list is not specified, the appliance will return ...
Activate a managed object stored by a KMIP appliance.
def activate(self, uid=None): """ Activate a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to activate. Optional, defaults to None. Returns: None Raises: ClientConnectionNo...
Revoke a managed object stored by a KMIP appliance.
def revoke(self, revocation_reason, uid=None, revocation_message=None, compromise_occurrence_date=None): """ Revoke a managed object stored by a KMIP appliance. Args: revocation_reason (RevocationReasonCode): An enumeration indicating the revocation re...
Encrypt data using the specified encryption key and parameters.
def encrypt(self, data, uid=None, cryptographic_parameters=None, iv_counter_nonce=None): """ Encrypt data using the specified encryption key and parameters. Args: data (bytes): The bytes to encrypt. Required. uid (string): The unique ID of the encryption ...
Verify a message signature using the specified signing key.
def signature_verify(self, message, signature, uid=None, cryptographic_parameters=None): """ Verify a message signature using the specified signing key. Args: message (bytes): The bytes of the signed message. Required. signature (bytes): The byte...
Get the message authentication code for data.
def mac(self, data, uid=None, algorithm=None): """ Get the message authentication code for data. Args: data (string): The data to be MACed. uid (string): The unique ID of the managed object that is the key to use for the MAC operation. algorit...
Build a CryptographicParameters struct from a dictionary.
def _build_cryptographic_parameters(self, value): """ Build a CryptographicParameters struct from a dictionary. Args: value (dict): A dictionary containing the key/value pairs for a CryptographicParameters struct. Returns: None: if value is None ...
Build an EncryptionKeyInformation struct from a dictionary.
def _build_encryption_key_information(self, value): """ Build an EncryptionKeyInformation struct from a dictionary. Args: value (dict): A dictionary containing the key/value pairs for a EncryptionKeyInformation struct. Returns: EncryptionKeyInfor...
Build an MACSignatureKeyInformation struct from a dictionary.
def _build_mac_signature_key_information(self, value): """ Build an MACSignatureKeyInformation struct from a dictionary. Args: value (dict): A dictionary containing the key/value pairs for a MACSignatureKeyInformation struct. Returns: MACSignatur...
Build a KeyWrappingSpecification struct from a dictionary.
def _build_key_wrapping_specification(self, value): """ Build a KeyWrappingSpecification struct from a dictionary. Args: value (dict): A dictionary containing the key/value pairs for a KeyWrappingSpecification struct. Returns: KeyWrappingSpecific...
Build a list of common attributes that are shared across symmetric as well as asymmetric objects
def _build_common_attributes(self, operation_policy_name=None): ''' Build a list of common attributes that are shared across symmetric as well as asymmetric objects ''' common_attributes = [] if operation_policy_name: common_attributes.append( ...
Build a name attribute returned in a list for ease of use in the caller
def _build_name_attribute(self, name=None): ''' Build a name attribute, returned in a list for ease of use in the caller ''' name_list = [] if name: name_list.append(self.attribute_factory.create_attribute( enums.AttributeType.NAME, ...
Read the data encoding the QueryRequestPayload object and decode it into its constituent parts.
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the QueryRequestPayload object and decode it into its constituent parts. Args: input_buffer (Stream): A data stream containing encoded object data, supporting a ...
Write the data encoding the QueryRequestPayload object to a stream.
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the QueryRequestPayload object to a stream. Args: output_buffer (Stream): A data stream in which to encode object data, supporting a write method; usually a Bytearray...
Read the data encoding the QueryResponsePayload object and decode it into its constituent parts.
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the QueryResponsePayload object and decode it into its constituent parts. Args: input_buffer (Stream): A data stream containing encoded object data, supporting a...
Write the data encoding the QueryResponsePayload object to a stream.
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the QueryResponsePayload object to a stream. Args: output_buffer (Stream): A data stream in which to encode object data, supporting a write method; usually a Bytearra...
Read the data encoding the GetAttributes response payload and decode it into its constituent parts.
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the GetAttributes response payload and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supportin...
Write the data encoding the GetAttributes response payload to a stream.
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the GetAttributes response payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usually...
Find a single entry point.
def get_single(group, name, path=None): """Find a single entry point. Returns an :class:`EntryPoint` object, or raises :exc:`NoSuchEntryPoint` if no match is found. """ for config, distro in iter_files_distros(path=path): if (group in config) and (name in config[group]): epstr =...
Find a group of entry points with unique names.
def get_group_named(group, path=None): """Find a group of entry points with unique names. Returns a dictionary of names to :class:`EntryPoint` objects. """ result = {} for ep in get_group_all(group, path=path): if ep.name not in result: result[ep.name] = ep return result
Find all entry points in a group.
def get_group_all(group, path=None): """Find all entry points in a group. Returns a list of :class:`EntryPoint` objects. """ result = [] for config, distro in iter_files_distros(path=path): if group in config: for name, epstr in config[group].items(): with BadEnt...
Load the object to which this entry point refers.
def load(self): """Load the object to which this entry point refers. """ mod = import_module(self.module_name) obj = mod if self.object_name: for attr in self.object_name.split('.'): obj = getattr(obj, attr) return obj
Parse an entry point from the syntax in entry_points. txt
def from_string(cls, epstr, name, distro=None): """Parse an entry point from the syntax in entry_points.txt :param str epstr: The entry point string (not including 'name =') :param str name: The name of this entry point :param Distribution distro: The distribution in which the entry poi...
Run livereload server
def live(): """Run livereload server""" from livereload import Server server = Server(app) map(server.watch, glob2.glob("application/pages/**/*.*")) # pages map(server.watch, glob2.glob("application/macros/**/*.html")) # macros map(server.watch, glob2.glob("application/static/**/*.*")) # pu...
New project.
def generate_project(args): """New project.""" # Project templates path src = os.path.join(dirname(abspath(__file__)), 'project') project_name = args.get('<project>') if not project_name: logger.warning('Project name cannot be empty.') return # Destination project path dst...
Generate controller include the controller file template & css & js directories.
def generate_controller(args): """Generate controller, include the controller file, template & css & js directories.""" controller_template = os.path.join(dirname(abspath(__file__)), 'templates/controller.py') test_template = os.path.join(dirname(abspath(__file__)), 'templates/unittest.py') controller_n...
Generate action.
def generate_action(args): """Generate action.""" controller = args.get('<controller>') action = args.get('<action>') with_template = args.get('-t') current_path = os.getcwd() logger.info('Start generating action.') controller_file_path = os.path.join(current_path, 'application/controllers...
Generate form.
def generate_form(args): """Generate form.""" form_name = args.get('<form>') logger.info('Start generating form.') _generate_form(form_name) logger.info('Finish generating form.')
Generate model.
def generate_model(args): """Generate model.""" model_name = args.get('<model>') if not model_name: logger.warning('Model name cannot be empty.') return logger.info('Start generating model.') model_template = os.path.join(dirname(abspath(__file__)), 'templates/model.py') curren...
Genarate macro.
def generate_macro(args): """Genarate macro.""" macro = args.get('<macro>').replace('-', '_') category = args.get('<category>') if not macro: logger.warning('Macro name cannot be empty.') return logger.info('Start generating macro.') current_path = os.getcwd() if category...
mkdir - p path
def _mkdir_p(path): """mkdir -p path""" try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise else: logger.info("New: %s%s", path, os.path.sep)
Replace vars and copy.
def _rewrite_and_copy(src_file, dst_file, project_name): """Replace vars and copy.""" # Create temp file fh, abs_path = mkstemp() with io.open(abs_path, 'w', encoding='utf-8') as new_file: with io.open(src_file, 'r', encoding='utf-8') as old_file: for line in old_file: ...
Friendly time gap
def timesince(value): """Friendly time gap""" if not value: return "" if not isinstance(value, datetime.date): return value now = datetime.datetime.now() delta = now - value if value > now: return "right now" elif delta.days > 365: return '%d years ago' % (...
Check url schema.
def check_url(form, field): """Check url schema.""" url = field.data.strip() if not url: return result = urlparse(url) if result.scheme == "": field.data = "http://%s" % re.sub(r'^:?/*', '', url)
Encode something with SECRET_KEY.
def encode(something): """Encode something with SECRET_KEY.""" secret_key = current_app.config.get('SECRET_KEY') s = URLSafeSerializer(secret_key) return s.dumps(something)
Decode something with SECRET_KEY.
def decode(something): """Decode something with SECRET_KEY.""" secret_key = current_app.config.get('SECRET_KEY') s = URLSafeSerializer(secret_key) try: return s.loads(something) except BadSignature: return None
JSON decorator.
def jsonify(func): """JSON decorator.""" @functools.wraps(func) def wrapper(*args, **kwargs): r = func(*args, **kwargs) if isinstance(r, tuple): code, data = r else: code, data = 200, r return Response(json.dumps(data), status=code, mimetype='applicat...
Absolute url for endpoint.
def absolute_url_for(endpoint, **values): """Absolute url for endpoint.""" config = current_app.config site_domain = config.get('SITE_DOMAIN') relative_url = url_for(endpoint, **values) return join_url(site_domain, relative_url)
Load config.
def load_config(): """Load config.""" mode = os.environ.get('MODE') try: if mode == 'PRODUCTION': from .production import ProductionConfig return ProductionConfig elif mode == 'TESTING': from .testing import TestingConfig return TestingConfig ...
Sign in user.
def signin_user(user, permenent=True): """Sign in user.""" session.permanent = permenent session['user_id'] = user.id
Get current user.
def get_current_user(): """Get current user.""" if not 'user_id' in session: return None user = User.query.filter(User.id == session['user_id']).first() if not user: signout_user() return None return user
Signin
def signin(): """Signin""" form = SigninForm() if form.validate_on_submit(): signin_user(form.user) return redirect(url_for('site.index')) return render_template('account/signin/signin.html', form=form)
Signup
def signup(): """Signup""" form = SignupForm() if form.validate_on_submit(): params = form.data.copy() params.pop('repassword') user = User(**params) db.session.add(user) db.session.commit() signin_user(user) return redirect(url_for('site.index')) ...
Create Flask app.
def create_app(): """Create Flask app.""" config = load_config() app = Flask(__name__) app.config.from_object(config) # Proxy fix app.wsgi_app = ProxyFix(app.wsgi_app) # CSRF protect CsrfProtect(app) if app.debug or app.testing: DebugToolbarExtension(app) # Serve...
Register jinja filters vars functions.
def register_jinja(app): """Register jinja filters, vars, functions.""" import jinja2 from .utils import filters, permissions, helpers if app.debug or app.testing: my_loader = jinja2.ChoiceLoader([ app.jinja_loader, jinja2.FileSystemLoader([ os.path.join(...
Register routes.
def register_routes(app): """Register routes.""" from . import controllers from flask.blueprints import Blueprint for module in _import_submodules_from_package(controllers): bp = getattr(module, 'bp') if bp and isinstance(bp, Blueprint): app.register_blueprint(bp)
Register HTTP error pages.
def register_error_handle(app): """Register HTTP error pages.""" @app.errorhandler(403) def page_403(error): return render_template('site/403/403.html'), 403 @app.errorhandler(404) def page_404(error): return render_template('site/404/404.html'), 404 @app.errorhandler(500) ...
Register hooks.
def register_hooks(app): """Register hooks.""" @app.before_request def before_request(): g.user = get_current_user() if g.user and g.user.is_admin: g._before_request_time = time.time() @app.after_request def after_request(response): if hasattr(g, '_before_reques...
serialize the dataframe with different delimiters
def _dataframe_to_csv(writer, dataframe, delimiter, with_header): """serialize the dataframe with different delimiters""" encoding_writer = codecs.getwriter('utf-8')(writer) dataframe.to_csv( path_or_buf=encoding_writer, sep=delimiter, header=with_header, index=False )
Returns csv data as a pandas Dataframe object
def _dataframe_from_csv(reader, delimiter, with_header, skipspace): """Returns csv data as a pandas Dataframe object""" sep = delimiter header = 0 if not with_header: header = None return pd.read_csv( reader, header=header, sep=sep, skipinitialspace=skipspace...
Serialize a dataframe.
def serialize_dataframe(writer, data_type_id, dataframe): """ Serialize a dataframe. Parameters ---------- writer : file File-like object to write to. Must be opened in binary mode. data_type_id : dict Serialization format to use. See the azureml.DataTypeIds class for co...
Deserialize a dataframe.
def deserialize_dataframe(reader, data_type_id): """ Deserialize a dataframe. Parameters ---------- reader : file File-like object to read from. Must be opened in binary mode. data_type_id : dict Serialization format of the raw data. See the azureml.DataTypeIds class for...
Serialize the specified DataFrame and replace the existing dataset.
def _update_from_dataframe(self, dataframe, data_type_id=None, name=None, description=None): """ Serialize the specified DataFrame and replace the existing dataset. Parameters ---------- dataframe : pandas.DataFrame Data to serialize. ...
Upload already serialized raw data and replace the existing dataset.
def _update_from_raw_data(self, raw_data, data_type_id=None, name=None, description=None): """ Upload already serialized raw data and replace the existing dataset. Parameters ---------- raw_data: bytes Dataset contents to upload. ...
Full URL to the dataset contents.
def contents_url(self): """Full URL to the dataset contents.""" loc = self.download_location return loc.base_uri + loc.location + loc.access_credential
Serialize the specified DataFrame and upload it as a new dataset.
def add_from_dataframe(self, dataframe, data_type_id, name, description): """ Serialize the specified DataFrame and upload it as a new dataset. Parameters ---------- dataframe : pandas.DataFrame Data to serialize. data_type_id : str Format to seri...
Upload already serialized raw data as a new dataset.
def add_from_raw_data(self, raw_data, data_type_id, name, description): """ Upload already serialized raw data as a new dataset. Parameters ---------- raw_data: bytes Dataset contents to upload. data_type_id : str Serialization format of the raw d...
Open and return a stream for the dataset contents.
def open(self): '''Open and return a stream for the dataset contents.''' return self.workspace._rest.open_intermediate_dataset_contents( self.workspace.workspace_id, self.experiment.experiment_id, self.node_id, self.port_name )
Read and return the dataset contents as binary.
def read_as_binary(self): '''Read and return the dataset contents as binary.''' return self.workspace._rest.read_intermediate_dataset_contents_binary( self.workspace.workspace_id, self.experiment.experiment_id, self.node_id, self.port_name )
Read and return the dataset contents as text.
def read_as_text(self): '''Read and return the dataset contents as text.''' return self.workspace._rest.read_intermediate_dataset_contents_text( self.workspace.workspace_id, self.experiment.experiment_id, self.node_id, self.port_name )
Read and return the dataset contents as a pandas DataFrame.
def _to_dataframe(self): """Read and return the dataset contents as a pandas DataFrame.""" #TODO: figure out why passing in the opened stream directly gives invalid data data = self.read_as_binary() reader = BytesIO(data) return deserialize_dataframe(reader, self.data_type_id)
Get an intermediate dataset.
def get_intermediate_dataset(self, node_id, port_name, data_type_id): """ Get an intermediate dataset. Parameters ---------- node_id : str Module node id from the experiment graph. port_name : str Output port of the module. data_type_id : ...
Runs HTTP GET request to retrieve the list of experiments.
def get_experiments(self, workspace_id): """Runs HTTP GET request to retrieve the list of experiments.""" api_path = self.EXPERIMENTS_URI_FMT.format(workspace_id) return self._send_get_req(api_path)
Runs HTTP GET request to retrieve the list of datasets.
def get_datasets(self, workspace_id): """Runs HTTP GET request to retrieve the list of datasets.""" api_path = self.DATASOURCES_URI_FMT.format(workspace_id) return self._send_get_req(api_path)
Runs HTTP GET request to retrieve a single dataset.
def get_dataset(self, workspace_id, dataset_id): """Runs HTTP GET request to retrieve a single dataset.""" api_path = self.DATASOURCE_URI_FMT.format(workspace_id, dataset_id) return self._send_get_req(api_path)
publishes a callable function or decorates a function to be published.
def publish(func_or_workspace_id, workspace_id_or_token = None, workspace_token_or_none = None, files=(), endpoint=None): '''publishes a callable function or decorates a function to be published. Returns a callable, iterable object. Calling the object will invoke the published service. Iterating the object will...
Marks a function as having been published and causes all invocations to go to the remote operationalized service.
def service(url, api_key, help_url = None): '''Marks a function as having been published and causes all invocations to go to the remote operationalized service. >>> @service(url, api_key) >>> def f(a, b): >>> pass ''' def do_publish(func): return published(url, api_key, help_url, func, None) re...
Specifies the types used for the arguments of a published service.
def types(**args): """Specifies the types used for the arguments of a published service. @types(a=int, b = str) def f(a, b): pass """ def l(func): if hasattr(func, '__annotations__'): func.__annotations__.update(args) else: func.__annotations__ = args return ...
Specifies the return type for a published service.
def returns(type): """Specifies the return type for a published service. @returns(int) def f(...): pass """ def l(func): if hasattr(func, '__annotations__'): func.__annotations__['return'] = type else: func.__annotations__ = {'return': type} return func r...
attaches a file to the payload to be uploaded.
def attach(name, contents = None): """attaches a file to the payload to be uploaded. If contents is omitted the file is read from disk. If name is a tuple it specifies the on-disk filename and the destination filename. """ def do_attach(func): if hasattr(func, '__attachments__'): func.__att...
walks the byte code to find the variables which are actually globals
def find_globals(code): """walks the byte code to find the variables which are actually globals""" cur_byte = 0 byte_code = code.co_code names = set() while cur_byte < len(byte_code): op = ord(byte_code[cur_byte]) if op >= dis.HAVE_ARGUMENT: ...
maps the function onto multiple inputs. The input should be multiple sequences. The sequences will be zipped together forming the positional arguments for the call. This is equivalent to map ( func... ) but is executed with a single network call.
def map(self, *args): """maps the function onto multiple inputs. The input should be multiple sequences. The sequences will be zipped together forming the positional arguments for the call. This is equivalent to map(func, ...) but is executed with a single network call.""" call_args = [self._map_args...
Create a copy of this pen.
def copy(self): """Create a copy of this pen.""" pen = Pen() pen.__dict__ = self.__dict__.copy() return pen
Return RGBA values of color c
def lookup_color(c): """Return RGBA values of color c c should be either an X11 color or a brewer color set and index e.g. "navajowhite", "greens3/2" """ import sys import gi gi.require_version('Gtk', '3.0') gi.require_version('PangoCairo', '1.0') from gi.repository import Gdk ...
Draw this shape with the given cairo context
def draw(self, cr, highlight=False, bounding=None): """Draw this shape with the given cairo context""" if bounding is None or self._intersects(bounding): self._draw(cr, highlight, bounding)
Find extremas of a function of real domain defined by evaluating a cubic bernstein polynomial of given bernstein coefficients.
def _cubic_bernstein_extrema(p0, p1, p2, p3): """ Find extremas of a function of real domain defined by evaluating a cubic bernstein polynomial of given bernstein coefficients. """ # compute coefficients of derivative a = 3.*(p3-p0+3.*(p1-p2)) b = 6.*(p0+p2-2.*p1)...
Evaluate polynomial of given bernstein coefficients using de Casteljau s algorithm.
def _cubic_bernstein(p0, p1, p2, p3, t): """ Evaluate polynomial of given bernstein coefficients using de Casteljau's algorithm. """ u = 1 - t return p0*(u**3) + 3*t*u*(p1*u + p2*t) + p3*(t**3)
Build choices list runtime using sitetree_tree tag
def _build_choices(self): """Build choices list runtime using 'sitetree_tree' tag""" tree_token = u'sitetree_tree from "%s" template "%s"' % (self.tree, self.template) context_kwargs = {'current_app': 'admin'} context = template.Context(context_kwargs) if VERSION >= (1, 8) else template...
Compatibility function to get rid of optparse in management commands after Django 1. 10.
def options_getter(command_options): """Compatibility function to get rid of optparse in management commands after Django 1.10. :param tuple command_options: tuple with `CommandOption` objects. """ def get_options(option_func=None): from optparse import make_option from django.core.man...
Returns SiteTree ( thread - singleton ) object implementing utility methods.
def get_sitetree(): """Returns SiteTree (thread-singleton) object, implementing utility methods. :rtype: SiteTree """ sitetree = getattr(_THREAD_LOCAL, _THREAD_SITETREE, None) if sitetree is None: sitetree = SiteTree() setattr(_THREAD_LOCAL, _THREAD_SITETREE, sitetree) return ...