code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.modules.appbase.client; import java.util.Iterator; import java.util.LinkedList; import org.jdesktop.wonderland.common.ExperimentalAPI; import org.jdesktop.wonderland.modules.appbase.client.view.View2D; import org.jdesktop.wonderland.modules.appbase.client.view.View2DDisplayer; /** * Provides storage for all of the views of all of the windows of an app. An app can have multiple * windows, and each of these can, in turn, have multiple views. You can add both windows and * displayers (that is, <code>View2DDisplayers</code>) to the view set. When you add a window to a * a view set, a view is created for that window in every displayer in the set. When you add * a displayer to a view set, a view is created in that displayer for every window in the set. * Note: A window must belong to only one view set at a time. A displayer must belong to only one view * set at a time. (Not enforced). * * @author deronj */ @ExperimentalAPI public class View2DSet { /** The app to which this view set belongs. */ private App2D app; /** The displayers in the set. */ private LinkedList<View2DDisplayer> displayers = new LinkedList<View2DDisplayer>(); /** The windows in the set. */ private LinkedList<Window2D> windows = new LinkedList<Window2D>(); /** * Create a new instance of View2DSet. * @param app The app to which this view set belongs. */ public View2DSet (App2D app) { this.app = app; } /** * Clean up resources. */ public void cleanup () { if (app == null) return; synchronized (app.getAppCleanupLock()) { synchronized (this) { for (View2DDisplayer displayer : displayers) { displayer.destroyAllViews(); } displayers.clear(); LinkedList<Window2D> toRemoveList = (LinkedList<Window2D>) windows.clone(); for (Window2D window : toRemoveList) { remove(window); } windows.clear(); toRemoveList.clear(); app = null; } } } /** * Add a displayer to this view set. A view in that displayer is created for each window in the set. * Nothing happens if the displayer is already in the set. */ public synchronized void add (View2DDisplayer displayer) { if (displayers.contains(displayer)) return; displayers.add(displayer); displayerCreateViewsForAllWindows(displayer); } /** * Removes a displayer from the set. All views associated with the displayer are destroyed. * Nothing happens if the displayer is not in the set. */ public void remove (View2DDisplayer displayer) { if (app == null) return; synchronized (app.getAppCleanupLock()) { synchronized (this) { if (displayers.remove(displayer)) { displayer.destroyAllViews(); } } } } /** * Add a window to the view set. A view for that window is created for each displayer in the set. * Nothing happens if the window is already in the set. */ public synchronized void add (Window2D window) { if (windows.contains(window)) return; windows.add(window); windowCreateViewsForAllDisplayers(window); } /** * Removes a window from the set. All views associated with the window are destroyed. * Nothing happens if the window is not in the set. */ public void remove (Window2D window) { if (app == null) return; synchronized (app.getAppCleanupLock()) { synchronized (this) { window.removeViewsAll(); windows.remove(window); } } } /** * Returns the number of windows in this view set. */ public synchronized int getNumWindows () { return windows.size(); } /** * Returns an iterator over all displayers in this view set. */ public synchronized Iterator<View2DDisplayer> getDisplayers () { return displayers.iterator(); } /** * Returns an iterator over all windows in this view set. */ public synchronized Iterator<Window2D> getWindows () { return windows.iterator(); } /** * Creates a view associated with this displayer for all windows in the set. */ private void displayerCreateViewsForAllWindows (View2DDisplayer displayer) { for (Window2D window : windows) { if (!window.isZombie()) { View2D view = displayer.createView(window); } } } /** * Creates a view associated with this displayer for all displayers in the set. */ private void windowCreateViewsForAllDisplayers (Window2D window) { for (View2DDisplayer displayer : displayers) { View2D view = displayer.createView(window); } } }
AsherBond/MondocosmOS
wonderland/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/View2DSet.java
Java
agpl-3.0
5,674
# frozen_string_literal: true class REST::InstanceSerializer < ActiveModel::Serializer include RoutingHelper attributes :uri, :title, :short_description, :description, :email, :version, :urls, :stats, :thumbnail, :languages, :registrations, :approval_required, :invites_enabled has_one :contact_account, serializer: REST::AccountSerializer delegate :contact_account, to: :instance_presenter def uri Rails.configuration.x.local_domain end def title Setting.site_title end def short_description Setting.site_short_description end def description Setting.site_description end def email Setting.site_contact_email end def version Mastodon::Version.to_s end def thumbnail instance_presenter.thumbnail ? full_asset_url(instance_presenter.thumbnail.file.url) : full_pack_url('media/images/preview.jpg') end def stats { user_count: instance_presenter.user_count, status_count: instance_presenter.status_count, domain_count: instance_presenter.domain_count, } end def urls { streaming_api: Rails.configuration.x.streaming_api_base_url } end def languages [I18n.default_locale] end def registrations Setting.registrations_mode != 'none' && !Rails.configuration.x.single_user_mode end def approval_required Setting.registrations_mode == 'approved' end def invites_enabled Setting.min_invite_role == 'user' end private def instance_presenter @instance_presenter ||= InstancePresenter.new end end
cobodo/mastodon
app/serializers/rest/instance_serializer.rb
Ruby
agpl-3.0
1,573
""" Serializers and ModelSerializers are similar to Forms and ModelForms. Unlike forms, they are not constrained to dealing with HTML output, and form encoded input. Serialization in REST framework is a two-phase process: 1. Serializers marshal between complex types like model instances, and python primitives. 2. The process of marshalling between python primitives and request and response content is handled by parsers and renderers. """ from __future__ import unicode_literals import copy import datetime import inspect import types from decimal import Decimal from django.contrib.contenttypes.generic import GenericForeignKey from django.core.paginator import Page from django.db import models from django.forms import widgets from django.utils.datastructures import SortedDict from django.core.exceptions import ObjectDoesNotExist from rest_framework.compat import get_concrete_model, six from rest_framework.settings import api_settings # Note: We do the following so that users of the framework can use this style: # # example_field = serializers.CharField(...) # # This helps keep the separation between model fields, form fields, and # serializer fields more explicit. from rest_framework.relations import * # NOQA from rest_framework.fields import * # NOQA def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful in situtations like GH #1225 where Django may not have resolved a string-based reference to a model in another model's foreign key definition. String representations should have the format: 'appname.ModelName' """ if isinstance(obj, six.string_types) and len(obj.split('.')) == 2: app_name, model_name = obj.split('.') return models.get_model(app_name, model_name) elif inspect.isclass(obj) and issubclass(obj, models.Model): return obj else: raise ValueError("{0} is not a Django model".format(obj)) def pretty_name(name): """Converts 'first_name' to 'First name'""" if not name: return '' return name.replace('_', ' ').capitalize() class RelationsList(list): _deleted = [] class NestedValidationError(ValidationError): """ The default ValidationError behavior is to stringify each item in the list if the messages are a list of error messages. In the case of nested serializers, where the parent has many children, then the child's `serializer.errors` will be a list of dicts. In the case of a single child, the `serializer.errors` will be a dict. We need to override the default behavior to get properly nested error dicts. """ def __init__(self, message): if isinstance(message, dict): self._messages = [message] else: self._messages = message @property def messages(self): return self._messages class DictWithMetadata(dict): """ A dict-like object, that can have additional properties attached. """ def __getstate__(self): """ Used by pickle (e.g., caching). Overridden to remove the metadata from the dict, since it shouldn't be pickled and may in some instances be unpickleable. """ return dict(self) class SortedDictWithMetadata(SortedDict): """ A sorted dict-like object, that can have additional properties attached. """ def __getstate__(self): """ Used by pickle (e.g., caching). Overriden to remove the metadata from the dict, since it shouldn't be pickle and may in some instances be unpickleable. """ return SortedDict(self).__dict__ def _is_protected_type(obj): """ True if the object is a native datatype that does not need to be serialized further. """ return isinstance(obj, ( types.NoneType, int, long, datetime.datetime, datetime.date, datetime.time, float, Decimal, basestring) ) def _get_declared_fields(bases, attrs): """ Create a list of serializer field instances from the passed in 'attrs', plus any fields on the base classes (in 'bases'). Note that all fields from the base classes are used. """ fields = [(field_name, attrs.pop(field_name)) for field_name, obj in list(six.iteritems(attrs)) if isinstance(obj, Field)] fields.sort(key=lambda x: x[1].creation_counter) # If this class is subclassing another Serializer, add that Serializer's # fields. Note that we loop over the bases in *reverse*. This is necessary # in order to maintain the correct order of fields. for base in bases[::-1]: if hasattr(base, 'base_fields'): fields = list(base.base_fields.items()) + fields return SortedDict(fields) class SerializerMetaclass(type): def __new__(cls, name, bases, attrs): attrs['base_fields'] = _get_declared_fields(bases, attrs) return super(SerializerMetaclass, cls).__new__(cls, name, bases, attrs) class SerializerOptions(object): """ Meta class options for Serializer """ def __init__(self, meta): self.depth = getattr(meta, 'depth', 0) self.fields = getattr(meta, 'fields', ()) self.exclude = getattr(meta, 'exclude', ()) class BaseSerializer(WritableField): """ This is the Serializer implementation. We need to implement it as `BaseSerializer` due to metaclass magicks. """ class Meta(object): pass _options_class = SerializerOptions _dict_class = SortedDictWithMetadata def __init__(self, instance=None, data=None, files=None, context=None, partial=False, many=None, allow_add_remove=False, **kwargs): super(BaseSerializer, self).__init__(**kwargs) self.opts = self._options_class(self.Meta) self.parent = None self.root = None self.partial = partial self.many = many self.allow_add_remove = allow_add_remove self.context = context or {} self.init_data = data self.init_files = files self.object = instance self.fields = self.get_fields() self._data = None self._files = None self._errors = None if many and instance is not None and not hasattr(instance, '__iter__'): raise ValueError('instance should be a queryset or other iterable with many=True') if allow_add_remove and not many: raise ValueError('allow_add_remove should only be used for bulk updates, but you have not set many=True') ##### # Methods to determine which fields to use when (de)serializing objects. def get_default_fields(self): """ Return the complete set of default fields for the object, as a dict. """ return {} def get_fields(self): """ Returns the complete set of fields for the object as a dict. This will be the set of any explicitly declared fields, plus the set of fields returned by get_default_fields(). """ ret = SortedDict() # Get the explicitly declared fields base_fields = copy.deepcopy(self.base_fields) for key, field in base_fields.items(): ret[key] = field # Add in the default fields default_fields = self.get_default_fields() for key, val in default_fields.items(): if key not in ret: ret[key] = val # If 'fields' is specified, use those fields, in that order. if self.opts.fields: assert isinstance(self.opts.fields, (list, tuple)), '`fields` must be a list or tuple' new = SortedDict() for key in self.opts.fields: new[key] = ret[key] ret = new # Remove anything in 'exclude' if self.opts.exclude: assert isinstance(self.opts.exclude, (list, tuple)), '`exclude` must be a list or tuple' for key in self.opts.exclude: ret.pop(key, None) for key, field in ret.items(): field.initialize(parent=self, field_name=key) return ret ##### # Methods to convert or revert from objects <--> primitive representations. def get_field_key(self, field_name): """ Return the key that should be used for a given field. """ return field_name def restore_fields(self, data, files): """ Core of deserialization, together with `restore_object`. Converts a dictionary of data into a dictionary of deserialized fields. """ reverted_data = {} if data is not None and not isinstance(data, dict): self._errors['non_field_errors'] = ['Invalid data'] return None for field_name, field in self.fields.items(): field.initialize(parent=self, field_name=field_name) try: field.field_from_native(data, files, field_name, reverted_data) except ValidationError as err: self._errors[field_name] = list(err.messages) return reverted_data def perform_validation(self, attrs): """ Run `validate_<fieldname>()` and `validate()` methods on the serializer """ for field_name, field in self.fields.items(): if field_name in self._errors: continue source = field.source or field_name if self.partial and source not in attrs: continue try: validate_method = getattr(self, 'validate_%s' % field_name, None) if validate_method: attrs = validate_method(attrs, source) except ValidationError as err: self._errors[field_name] = self._errors.get(field_name, []) + list(err.messages) # If there are already errors, we don't run .validate() because # field-validation failed and thus `attrs` may not be complete. # which in turn can cause inconsistent validation errors. if not self._errors: try: attrs = self.validate(attrs) except ValidationError as err: if hasattr(err, 'message_dict'): for field_name, error_messages in err.message_dict.items(): self._errors[field_name] = self._errors.get(field_name, []) + list(error_messages) elif hasattr(err, 'messages'): self._errors['non_field_errors'] = err.messages return attrs def validate(self, attrs): """ Stub method, to be overridden in Serializer subclasses """ return attrs def restore_object(self, attrs, instance=None): """ Deserialize a dictionary of attributes into an object instance. You should override this method to control how deserialized objects are instantiated. """ if instance is not None: instance.update(attrs) return instance return attrs def to_native(self, obj): """ Serialize objects -> primitives. """ ret = self._dict_class() ret.fields = self._dict_class() for field_name, field in self.fields.items(): if field.read_only and obj is None: continue field.initialize(parent=self, field_name=field_name) key = self.get_field_key(field_name) value = field.field_to_native(obj, field_name) method = getattr(self, 'transform_%s' % field_name, None) if callable(method): value = method(obj, value) if not getattr(field, 'write_only', False): ret[key] = value ret.fields[key] = self.augment_field(field, field_name, key, value) return ret def from_native(self, data, files=None): """ Deserialize primitives -> objects. """ self._errors = {} if data is not None or files is not None: attrs = self.restore_fields(data, files) if attrs is not None: attrs = self.perform_validation(attrs) else: self._errors['non_field_errors'] = ['No input provided'] if not self._errors: return self.restore_object(attrs, instance=getattr(self, 'object', None)) def augment_field(self, field, field_name, key, value): # This horrible stuff is to manage serializers rendering to HTML field._errors = self._errors.get(key) if self._errors else None field._name = field_name field._value = self.init_data.get(key) if self._errors and self.init_data else value if not field.label: field.label = pretty_name(key) return field def field_to_native(self, obj, field_name): """ Override default so that the serializer can be used as a nested field across relationships. """ if self.write_only: return None if self.source == '*': return self.to_native(obj) # Get the raw field value try: source = self.source or field_name value = obj for component in source.split('.'): if value is None: break value = get_component(value, component) except ObjectDoesNotExist: return None if is_simple_callable(getattr(value, 'all', None)): return [self.to_native(item) for item in value.all()] if value is None: return None if self.many is not None: many = self.many else: many = hasattr(value, '__iter__') and not isinstance(value, (Page, dict, six.text_type)) if many: return [self.to_native(item) for item in value] return self.to_native(value) def field_from_native(self, data, files, field_name, into): """ Override default so that the serializer can be used as a writable nested field across relationships. """ if self.read_only: return try: value = data[field_name] except KeyError: if self.default is not None and not self.partial: # Note: partial updates shouldn't set defaults value = copy.deepcopy(self.default) else: if self.required: raise ValidationError(self.error_messages['required']) return if self.source == '*': if value: reverted_data = self.restore_fields(value, {}) if not self._errors: into.update(reverted_data) else: if value in (None, ''): into[(self.source or field_name)] = None else: # Set the serializer object if it exists obj = get_component(self.parent.object, self.source or field_name) if self.parent.object else None # If we have a model manager or similar object then we need # to iterate through each instance. if (self.many and not hasattr(obj, '__iter__') and is_simple_callable(getattr(obj, 'all', None))): obj = obj.all() kwargs = { 'instance': obj, 'data': value, 'context': self.context, 'partial': self.partial, 'many': self.many, 'allow_add_remove': self.allow_add_remove } serializer = self.__class__(**kwargs) if serializer.is_valid(): into[self.source or field_name] = serializer.object else: # Propagate errors up to our parent raise NestedValidationError(serializer.errors) def get_identity(self, data): """ This hook is required for bulk update. It is used to determine the canonical identity of a given object. Note that the data has not been validated at this point, so we need to make sure that we catch any cases of incorrect datatypes being passed to this method. """ try: return data.get('id', None) except AttributeError: return None @property def errors(self): """ Run deserialization and return error data, setting self.object if no errors occurred. """ if self._errors is None: data, files = self.init_data, self.init_files if self.many is not None: many = self.many else: many = hasattr(data, '__iter__') and not isinstance(data, (Page, dict, six.text_type)) if many: warnings.warn('Implicit list/queryset serialization is deprecated. ' 'Use the `many=True` flag when instantiating the serializer.', DeprecationWarning, stacklevel=3) if many: ret = RelationsList() errors = [] update = self.object is not None if update: # If this is a bulk update we need to map all the objects # to a canonical identity so we can determine which # individual object is being updated for each item in the # incoming data objects = self.object identities = [self.get_identity(self.to_native(obj)) for obj in objects] identity_to_objects = dict(zip(identities, objects)) if hasattr(data, '__iter__') and not isinstance(data, (dict, six.text_type)): for item in data: if update: # Determine which object we're updating identity = self.get_identity(item) self.object = identity_to_objects.pop(identity, None) if self.object is None and not self.allow_add_remove: ret.append(None) errors.append({'non_field_errors': ['Cannot create a new item, only existing items may be updated.']}) continue ret.append(self.from_native(item, None)) errors.append(self._errors) if update and self.allow_add_remove: ret._deleted = identity_to_objects.values() self._errors = any(errors) and errors or [] else: self._errors = {'non_field_errors': ['Expected a list of items.']} else: ret = self.from_native(data, files) if not self._errors: self.object = ret return self._errors def is_valid(self): return not self.errors @property def data(self): """ Returns the serialized data on the serializer. """ if self._data is None: obj = self.object if self.many is not None: many = self.many else: many = hasattr(obj, '__iter__') and not isinstance(obj, (Page, dict)) if many: warnings.warn('Implicit list/queryset serialization is deprecated. ' 'Use the `many=True` flag when instantiating the serializer.', DeprecationWarning, stacklevel=2) if many: self._data = [self.to_native(item) for item in obj] else: self._data = self.to_native(obj) return self._data def save_object(self, obj, **kwargs): obj.save(**kwargs) def delete_object(self, obj): obj.delete() def save(self, **kwargs): """ Save the deserialized object and return it. """ # Clear cached _data, which may be invalidated by `save()` self._data = None if isinstance(self.object, list): [self.save_object(item, **kwargs) for item in self.object] if self.object._deleted: [self.delete_object(item) for item in self.object._deleted] else: self.save_object(self.object, **kwargs) return self.object def metadata(self): """ Return a dictionary of metadata about the fields on the serializer. Useful for things like responding to OPTIONS requests, or generating API schemas for auto-documentation. """ return SortedDict( [(field_name, field.metadata()) for field_name, field in six.iteritems(self.fields)] ) class Serializer(six.with_metaclass(SerializerMetaclass, BaseSerializer)): pass class ModelSerializerOptions(SerializerOptions): """ Meta class options for ModelSerializer """ def __init__(self, meta): super(ModelSerializerOptions, self).__init__(meta) self.model = getattr(meta, 'model', None) self.read_only_fields = getattr(meta, 'read_only_fields', ()) self.write_only_fields = getattr(meta, 'write_only_fields', ()) class ModelSerializer(Serializer): """ A serializer that deals with model instances and querysets. """ _options_class = ModelSerializerOptions field_mapping = { models.AutoField: IntegerField, models.FloatField: FloatField, models.IntegerField: IntegerField, models.PositiveIntegerField: IntegerField, models.SmallIntegerField: IntegerField, models.PositiveSmallIntegerField: IntegerField, models.DateTimeField: DateTimeField, models.DateField: DateField, models.TimeField: TimeField, models.DecimalField: DecimalField, models.EmailField: EmailField, models.CharField: CharField, models.URLField: URLField, models.SlugField: SlugField, models.TextField: CharField, models.CommaSeparatedIntegerField: CharField, models.BooleanField: BooleanField, models.NullBooleanField: BooleanField, models.FileField: FileField, models.ImageField: ImageField, } def get_default_fields(self): """ Return all the fields that should be serialized for the model. """ cls = self.opts.model assert cls is not None, \ "Serializer class '%s' is missing 'model' Meta option" % self.__class__.__name__ opts = get_concrete_model(cls)._meta ret = SortedDict() nested = bool(self.opts.depth) # Deal with adding the primary key field pk_field = opts.pk while pk_field.rel and pk_field.rel.parent_link: # If model is a child via multitable inheritance, use parent's pk pk_field = pk_field.rel.to._meta.pk field = self.get_pk_field(pk_field) if field: ret[pk_field.name] = field # Deal with forward relationships forward_rels = [field for field in opts.fields if field.serialize] forward_rels += [field for field in opts.many_to_many if field.serialize] for model_field in forward_rels: has_through_model = False if model_field.rel: to_many = isinstance(model_field, models.fields.related.ManyToManyField) related_model = _resolve_model(model_field.rel.to) if to_many and not model_field.rel.through._meta.auto_created: has_through_model = True if model_field.rel and nested: if len(inspect.getargspec(self.get_nested_field).args) == 2: warnings.warn( 'The `get_nested_field(model_field)` call signature ' 'is due to be deprecated. ' 'Use `get_nested_field(model_field, related_model, ' 'to_many) instead', PendingDeprecationWarning ) field = self.get_nested_field(model_field) else: field = self.get_nested_field(model_field, related_model, to_many) elif model_field.rel: if len(inspect.getargspec(self.get_nested_field).args) == 3: warnings.warn( 'The `get_related_field(model_field, to_many)` call ' 'signature is due to be deprecated. ' 'Use `get_related_field(model_field, related_model, ' 'to_many) instead', PendingDeprecationWarning ) field = self.get_related_field(model_field, to_many=to_many) else: field = self.get_related_field(model_field, related_model, to_many) else: field = self.get_field(model_field) if field: if has_through_model: field.read_only = True ret[model_field.name] = field # Deal with reverse relationships if not self.opts.fields: reverse_rels = [] else: # Reverse relationships are only included if they are explicitly # present in the `fields` option on the serializer reverse_rels = opts.get_all_related_objects() reverse_rels += opts.get_all_related_many_to_many_objects() for relation in reverse_rels: accessor_name = relation.get_accessor_name() if not self.opts.fields or accessor_name not in self.opts.fields: continue related_model = relation.model to_many = relation.field.rel.multiple has_through_model = False is_m2m = isinstance(relation.field, models.fields.related.ManyToManyField) if (is_m2m and hasattr(relation.field.rel, 'through') and not relation.field.rel.through._meta.auto_created): has_through_model = True if nested: field = self.get_nested_field(None, related_model, to_many) else: field = self.get_related_field(None, related_model, to_many) if field: if has_through_model: field.read_only = True ret[accessor_name] = field # Ensure that 'read_only_fields' is an iterable assert isinstance(self.opts.read_only_fields, (list, tuple)), '`read_only_fields` must be a list or tuple' # Add the `read_only` flag to any fields that have been specified # in the `read_only_fields` option for field_name in self.opts.read_only_fields: assert field_name not in self.base_fields.keys(), ( "field '%s' on serializer '%s' specified in " "`read_only_fields`, but also added " "as an explicit field. Remove it from `read_only_fields`." % (field_name, self.__class__.__name__)) assert field_name in ret, ( "Non-existant field '%s' specified in `read_only_fields` " "on serializer '%s'." % (field_name, self.__class__.__name__)) ret[field_name].read_only = True # Ensure that 'write_only_fields' is an iterable assert isinstance(self.opts.write_only_fields, (list, tuple)), '`write_only_fields` must be a list or tuple' for field_name in self.opts.write_only_fields: assert field_name not in self.base_fields.keys(), ( "field '%s' on serializer '%s' specified in " "`write_only_fields`, but also added " "as an explicit field. Remove it from `write_only_fields`." % (field_name, self.__class__.__name__)) assert field_name in ret, ( "Non-existant field '%s' specified in `write_only_fields` " "on serializer '%s'." % (field_name, self.__class__.__name__)) ret[field_name].write_only = True return ret def get_pk_field(self, model_field): """ Returns a default instance of the pk field. """ return self.get_field(model_field) def get_nested_field(self, model_field, related_model, to_many): """ Creates a default instance of a nested relational field. Note that model_field will be `None` for reverse relationships. """ class NestedModelSerializer(ModelSerializer): class Meta: model = related_model depth = self.opts.depth - 1 return NestedModelSerializer(many=to_many) def get_related_field(self, model_field, related_model, to_many): """ Creates a default instance of a flat relational field. Note that model_field will be `None` for reverse relationships. """ # TODO: filter queryset using: # .using(db).complex_filter(self.rel.limit_choices_to) kwargs = { 'queryset': related_model._default_manager, 'many': to_many } if model_field: kwargs['required'] = not(model_field.null or model_field.blank) if model_field.help_text is not None: kwargs['help_text'] = model_field.help_text if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name if not model_field.editable: kwargs['read_only'] = True if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name if model_field.help_text is not None: kwargs['help_text'] = model_field.help_text return PrimaryKeyRelatedField(**kwargs) def get_field(self, model_field): """ Creates a default instance of a basic non-relational field. """ kwargs = {} if model_field.null or model_field.blank: kwargs['required'] = False if isinstance(model_field, models.AutoField) or not model_field.editable: kwargs['read_only'] = True if model_field.has_default(): kwargs['default'] = model_field.get_default() if issubclass(model_field.__class__, models.TextField): kwargs['widget'] = widgets.Textarea if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name if model_field.help_text is not None: kwargs['help_text'] = model_field.help_text # TODO: TypedChoiceField? if model_field.flatchoices: # This ModelField contains choices kwargs['choices'] = model_field.flatchoices if model_field.null: kwargs['empty'] = None return ChoiceField(**kwargs) # put this below the ChoiceField because min_value isn't a valid initializer if issubclass(model_field.__class__, models.PositiveIntegerField) or\ issubclass(model_field.__class__, models.PositiveSmallIntegerField): kwargs['min_value'] = 0 attribute_dict = { models.CharField: ['max_length'], models.CommaSeparatedIntegerField: ['max_length'], models.DecimalField: ['max_digits', 'decimal_places'], models.EmailField: ['max_length'], models.FileField: ['max_length'], models.ImageField: ['max_length'], models.SlugField: ['max_length'], models.URLField: ['max_length'], } if model_field.__class__ in attribute_dict: attributes = attribute_dict[model_field.__class__] for attribute in attributes: kwargs.update({attribute: getattr(model_field, attribute)}) try: return self.field_mapping[model_field.__class__](**kwargs) except KeyError: return ModelField(model_field=model_field, **kwargs) def get_validation_exclusions(self, instance=None): """ Return a list of field names to exclude from model validation. """ cls = self.opts.model opts = get_concrete_model(cls)._meta exclusions = [field.name for field in opts.fields + opts.many_to_many] for field_name, field in self.fields.items(): field_name = field.source or field_name if field_name in exclusions \ and not field.read_only \ and (field.required or hasattr(instance, field_name)) \ and not isinstance(field, Serializer): exclusions.remove(field_name) return exclusions def full_clean(self, instance): """ Perform Django's full_clean, and populate the `errors` dictionary if any validation errors occur. Note that we don't perform this inside the `.restore_object()` method, so that subclasses can override `.restore_object()`, and still get the full_clean validation checking. """ try: instance.full_clean(exclude=self.get_validation_exclusions(instance)) except ValidationError as err: self._errors = err.message_dict return None return instance def restore_object(self, attrs, instance=None): """ Restore the model instance. """ m2m_data = {} related_data = {} nested_forward_relations = {} meta = self.opts.model._meta # Reverse fk or one-to-one relations for (obj, model) in meta.get_all_related_objects_with_model(): field_name = obj.get_accessor_name() if field_name in attrs: related_data[field_name] = attrs.pop(field_name) # Reverse m2m relations for (obj, model) in meta.get_all_related_m2m_objects_with_model(): field_name = obj.get_accessor_name() if field_name in attrs: m2m_data[field_name] = attrs.pop(field_name) # Forward m2m relations for field in meta.many_to_many + meta.virtual_fields: if isinstance(field, GenericForeignKey): continue if field.name in attrs: m2m_data[field.name] = attrs.pop(field.name) # Nested forward relations - These need to be marked so we can save # them before saving the parent model instance. for field_name in attrs.keys(): if isinstance(self.fields.get(field_name, None), Serializer): nested_forward_relations[field_name] = attrs[field_name] # Create an empty instance of the model if instance is None: instance = self.opts.model() for key, val in attrs.items(): try: setattr(instance, key, val) except ValueError: self._errors[key] = self.error_messages['required'] # Any relations that cannot be set until we've # saved the model get hidden away on these # private attributes, so we can deal with them # at the point of save. instance._related_data = related_data instance._m2m_data = m2m_data instance._nested_forward_relations = nested_forward_relations return instance def from_native(self, data, files): """ Override the default method to also include model field validation. """ instance = super(ModelSerializer, self).from_native(data, files) if not self._errors: return self.full_clean(instance) def save_object(self, obj, **kwargs): """ Save the deserialized object. """ if getattr(obj, '_nested_forward_relations', None): # Nested relationships need to be saved before we can save the # parent instance. for field_name, sub_object in obj._nested_forward_relations.items(): if sub_object: self.save_object(sub_object) setattr(obj, field_name, sub_object) obj.save(**kwargs) if getattr(obj, '_m2m_data', None): for accessor_name, object_list in obj._m2m_data.items(): setattr(obj, accessor_name, object_list) del(obj._m2m_data) if getattr(obj, '_related_data', None): related_fields = dict([ (field.get_accessor_name(), field) for field, model in obj._meta.get_all_related_objects_with_model() ]) for accessor_name, related in obj._related_data.items(): if isinstance(related, RelationsList): # Nested reverse fk relationship for related_item in related: fk_field = related_fields[accessor_name].field.name setattr(related_item, fk_field, obj) self.save_object(related_item) # Delete any removed objects if related._deleted: [self.delete_object(item) for item in related._deleted] elif isinstance(related, models.Model): # Nested reverse one-one relationship fk_field = obj._meta.get_field_by_name(accessor_name)[0].field.name setattr(related, fk_field, obj) self.save_object(related) else: # Reverse FK or reverse one-one setattr(obj, accessor_name, related) del(obj._related_data) class HyperlinkedModelSerializerOptions(ModelSerializerOptions): """ Options for HyperlinkedModelSerializer """ def __init__(self, meta): super(HyperlinkedModelSerializerOptions, self).__init__(meta) self.view_name = getattr(meta, 'view_name', None) self.lookup_field = getattr(meta, 'lookup_field', None) self.url_field_name = getattr(meta, 'url_field_name', api_settings.URL_FIELD_NAME) class HyperlinkedModelSerializer(ModelSerializer): """ A subclass of ModelSerializer that uses hyperlinked relationships, instead of primary key relationships. """ _options_class = HyperlinkedModelSerializerOptions _default_view_name = '%(model_name)s-detail' _hyperlink_field_class = HyperlinkedRelatedField _hyperlink_identify_field_class = HyperlinkedIdentityField def get_default_fields(self): fields = super(HyperlinkedModelSerializer, self).get_default_fields() if self.opts.view_name is None: self.opts.view_name = self._get_default_view_name(self.opts.model) if self.opts.url_field_name not in fields: url_field = self._hyperlink_identify_field_class( view_name=self.opts.view_name, lookup_field=self.opts.lookup_field ) ret = self._dict_class() ret[self.opts.url_field_name] = url_field ret.update(fields) fields = ret return fields def get_pk_field(self, model_field): if self.opts.fields and model_field.name in self.opts.fields: return self.get_field(model_field) def get_related_field(self, model_field, related_model, to_many): """ Creates a default instance of a flat relational field. """ # TODO: filter queryset using: # .using(db).complex_filter(self.rel.limit_choices_to) kwargs = { 'queryset': related_model._default_manager, 'view_name': self._get_default_view_name(related_model), 'many': to_many } if model_field: kwargs['required'] = not(model_field.null or model_field.blank) if model_field.help_text is not None: kwargs['help_text'] = model_field.help_text if model_field.verbose_name is not None: kwargs['label'] = model_field.verbose_name if self.opts.lookup_field: kwargs['lookup_field'] = self.opts.lookup_field return self._hyperlink_field_class(**kwargs) def get_identity(self, data): """ This hook is required for bulk update. We need to override the default, to use the url as the identity. """ try: return data.get(self.opts.url_field_name, None) except AttributeError: return None def _get_default_view_name(self, model): """ Return the view name to use if 'view_name' is not specified in 'Meta' """ model_meta = model._meta format_kwargs = { 'app_label': model_meta.app_label, 'model_name': model_meta.object_name.lower() } return self._default_view_name % format_kwargs
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/rest_framework/serializers.py
Python
agpl-3.0
41,575
# These permissions are a replacement for the following authorized? method: # def authorized? # current_user.member_of?(@group) # end module VisualizePermission def may_show_visualize?(group=@group) logged_in? and current_user.member_of?(group) end end
nilclass/echosocial
app/permissions/visualize_permission.rb
Ruby
agpl-3.0
266
class CategoriesController < AdminController protect 'manage_environment_categories', :environment helper :categories def index @categories = environment.categories.find(:all, :conditions => "parent_id is null AND type is null") @regions = environment.regions.find(:all, :conditions => {:parent_id => nil}) @product_categories = environment.product_categories.find(:all, :conditions => {:parent_id => nil}) end def get_children children = Category.find(params[:id]).children render :partial => 'category_children', :locals => {:children => children} end ALLOWED_TYPES = CategoriesHelper::TYPES.map {|item| item[1] } # posts back def new type = (params[:type] || params[:parent_type] || 'Category') raise 'Type not allowed' unless ALLOWED_TYPES.include?(type) @category = type.constantize.new(params[:category]) @category.environment = environment if params[:parent_id] @category.parent = environment.categories.find(params[:parent_id]) end if request.post? begin @category.save! @saved = true redirect_to :action => 'index' rescue Exception => e render :action => 'new' end end end # posts back def edit begin @category = environment.categories.find(params[:id]) if request.post? @category.update_attributes!(params[:category]) @saved = true session[:notice] = _("Category %s saved." % @category.name) redirect_to :action => 'index' end rescue Exception => e session[:notice] = _('Could not save category.') render :action => 'edit' end end after_filter :manage_categories_menu_cache, :only => [:edit, :new] post_only :remove def remove environment.categories.find(params[:id]).destroy redirect_to :action => 'index' end protected def manage_categories_menu_cache if @saved && request.post? && @category.display_in_menu? expire_fragment(:controller => 'public', :action => 'categories_menu') end end end
evandrojr/noosferogov
app/controllers/admin/categories_controller.rb
Ruby
agpl-3.0
2,063
from sympy import (symbols, product, factorial, rf, sqrt, cos, Function, Product, Rational) a, k, n = symbols('a,k,n', integer=True) def test_simple_products(): assert product(2, (k, a, n)) == 2**(n-a+1) assert product(k, (k, 1, n)) == factorial(n) assert product(k**3, (k, 1, n)) == factorial(n)**3 assert product(k+1, (k, 0, n-1)) == factorial(n) assert product(k+1, (k, a, n-1)) == rf(1+a, n-a) assert product(cos(k), (k, 0, 5)) == cos(1)*cos(2)*cos(3)*cos(4)*cos(5) assert product(cos(k), (k, 3, 5)) == cos(3)*cos(4)*cos(5) assert product(cos(k), (k, 1, Rational(5, 2))) == cos(1)*cos(2) assert isinstance(product(k**k, (k, 1, n)), Product) def test_rational_products(): assert product(1+1/k, (k, 1, n)) == rf(2, n)/factorial(n) def test_special_products(): # Wallis product assert product((4*k)**2 / (4*k**2-1), (k, 1, n)) == \ 4**n*factorial(n)**2/rf(Rational(1, 2), n)/rf(Rational(3, 2), n) # Euler's product formula for sin assert product(1 + a/k**2, (k, 1, n)) == \ rf(1 - sqrt(-a), n)*rf(1 + sqrt(-a), n)/factorial(n)**2 def test__eval_product(): from sympy.abc import i, n # 1710 a = Function('a') assert product(2*a(i), (i, 1, n)) == 2**n * Product(a(i), (i, 1, n)) # 1711 assert product(2**i, (i, 1, n)) == 2**(n/2 + n**2/2)
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/sympy/concrete/tests/test_products.py
Python
agpl-3.0
1,362
# frozen_string_literal: true class HomeController < ApplicationController before_action :authenticate_user! before_action :set_referrer_policy_header before_action :set_initial_state_json def index @body_classes = 'app-body' end private def authenticate_user! return if user_signed_in? matches = request.path.match(/\A\/web\/(statuses|accounts)\/([\d]+)\z/) if matches case matches[1] when 'statuses' status = Status.find_by(id: matches[2]) if status && (status.public_visibility? || status.unlisted_visibility?) redirect_to(ActivityPub::TagManager.instance.url_for(status)) return end when 'accounts' account = Account.find_by(id: matches[2]) if account redirect_to(ActivityPub::TagManager.instance.url_for(account)) return end end end matches = request.path.match(%r{\A/web/timelines/tag/(?<tag>.+)\z}) redirect_to(matches ? tag_path(CGI.unescape(matches[:tag])) : default_redirect_path) end def set_initial_state_json serializable_resource = ActiveModelSerializers::SerializableResource.new(InitialStatePresenter.new(initial_state_params), serializer: InitialStateSerializer) @initial_state_json = serializable_resource.to_json end def initial_state_params { settings: Web::Setting.find_by(user: current_user)&.data || {}, push_subscription: current_account.user.web_push_subscription(current_session), current_account: current_account, token: current_session.token, admin: Account.find_local(Setting.site_contact_username.strip.gsub(/\A@/, '')), } end def default_redirect_path if request.path.start_with?('/web') new_user_session_path elsif single_user_mode? short_account_path(Account.local.without_suspended.first) else about_path end end def set_referrer_policy_header response.headers['Referrer-Policy'] = 'origin' end end
clworld/mastodon
app/controllers/home_controller.rb
Ruby
agpl-3.0
2,004
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.mod_cluster; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; import org.jboss.as.controller.ModelVersion; import org.jboss.as.model.test.FailedOperationTransformationConfig; import org.jboss.as.model.test.ModelTestControllerVersion; import org.jboss.as.model.test.ModelTestUtils; import org.jboss.as.subsystem.test.AbstractSubsystemTest; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.as.subsystem.test.KernelServicesBuilder; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * @author Radoslav Husar */ @RunWith(Parameterized.class) public class ModClusterTransformersTestCase extends AbstractSubsystemTest { @Parameters public static Iterable<ModelTestControllerVersion> parameters() { return EnumSet.of(ModelTestControllerVersion.EAP_7_4_0); } ModelTestControllerVersion version; public ModClusterTransformersTestCase(ModelTestControllerVersion version) { super(ModClusterExtension.SUBSYSTEM_NAME, new ModClusterExtension()); this.version = version; } private static String formatArtifact(String pattern, ModelTestControllerVersion version) { return String.format(pattern, version.getMavenGavVersion()); } private static ModClusterModel getModelVersion(ModelTestControllerVersion controllerVersion) { switch (controllerVersion) { case EAP_7_4_0: return ModClusterModel.VERSION_7_0_0; } throw new IllegalArgumentException(); } private static String[] getDependencies(ModelTestControllerVersion version) { switch (version) { case EAP_7_4_0: return new String[] { formatArtifact("org.jboss.eap:wildfly-mod_cluster-extension:%s", version), "org.jboss.mod_cluster:mod_cluster-core:1.4.3.Final-redhat-00002", formatArtifact("org.jboss.eap:wildfly-clustering-common:%s", version), }; } throw new IllegalArgumentException(); } @Test public void testTransformations() throws Exception { this.testTransformations(version); } private void testTransformations(ModelTestControllerVersion controllerVersion) throws Exception { ModClusterModel model = getModelVersion(controllerVersion); ModelVersion modelVersion = model.getVersion(); String[] dependencies = getDependencies(controllerVersion); Set<String> resources = new HashSet<>(); resources.add(String.format("subsystem-transform-%d_%d_%d.xml", modelVersion.getMajor(), modelVersion.getMinor(), modelVersion.getMicro())); for (String resource : resources) { String subsystemXml = readResource(resource); KernelServicesBuilder builder = createKernelServicesBuilder(new ModClusterAdditionalInitialization()) .setSubsystemXml(subsystemXml); builder.createLegacyKernelServicesBuilder(null, controllerVersion, modelVersion) .addMavenResourceURL(dependencies) .skipReverseControllerCheck() .dontPersistXml(); KernelServices mainServices = builder.build(); KernelServices legacyServices = mainServices.getLegacyServices(modelVersion); Assert.assertNotNull(legacyServices); Assert.assertTrue(mainServices.isSuccessfulBoot()); Assert.assertTrue(legacyServices.isSuccessfulBoot()); checkSubsystemModelTransformation(mainServices, modelVersion, null, false); } } @Test public void testRejections() throws Exception { this.testRejections(version); } private void testRejections(ModelTestControllerVersion controllerVersion) throws Exception { String[] dependencies = getDependencies(controllerVersion); String subsystemXml = readResource("subsystem-reject.xml"); ModClusterModel model = getModelVersion(controllerVersion); ModelVersion modelVersion = model.getVersion(); KernelServicesBuilder builder = createKernelServicesBuilder(new ModClusterAdditionalInitialization()); builder.createLegacyKernelServicesBuilder(model.getVersion().getMajor() >= 4 ? new ModClusterAdditionalInitialization() : null, controllerVersion, modelVersion) .addSingleChildFirstClass(ModClusterAdditionalInitialization.class) .addMavenResourceURL(dependencies) .skipReverseControllerCheck(); KernelServices mainServices = builder.build(); KernelServices legacyServices = mainServices.getLegacyServices(modelVersion); Assert.assertNotNull(legacyServices); Assert.assertTrue(mainServices.isSuccessfulBoot()); Assert.assertTrue(legacyServices.isSuccessfulBoot()); ModelTestUtils.checkFailedTransformedBootOperations(mainServices, modelVersion, parse(subsystemXml), createFailedOperationConfig(modelVersion)); } private static FailedOperationTransformationConfig createFailedOperationConfig(ModelVersion version) { return new FailedOperationTransformationConfig(); } }
jstourac/wildfly
mod_cluster/extension/src/test/java/org/wildfly/extension/mod_cluster/ModClusterTransformersTestCase.java
Java
lgpl-2.1
6,362
/** * @file CC3000.h * @version 1.0 * * @section License * Copyright (C) 2015, Mikael Patel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * This file is part of the Arduino Che Cosa project. */ #ifndef COSA_CC3000_H #define COSA_CC3000_H #include "CC3000.hh" #endif
rrobinet/Cosa
libraries/CC3000/CC3000.h
C
lgpl-2.1
753
/**************************************************************************/ /* */ /* OCaml */ /* */ /* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ /* */ /* Copyright 2000 Institut National de Recherche en Informatique et */ /* en Automatique. */ /* */ /* All rights reserved. This file is distributed under the terms of */ /* the GNU Lesser General Public License version 2.1, with the */ /* special exception on linking described in the file LICENSE. */ /* */ /**************************************************************************/ #define CAML_NAME_SPACE #include <stdio.h> #include <caml/mlvalues.h> #include <caml/bigarray.h> extern void filltab_(void); extern void printtab_(float * data, int * dimx, int * dimy); extern float ftab_[]; value fortran_filltab(value unit) { filltab_(); return caml_ba_alloc_dims(CAML_BA_FLOAT32 | CAML_BA_FORTRAN_LAYOUT, 2, ftab_, (intnat)8, (intnat)6); } value fortran_printtab(value ba) { int dimx = Caml_ba_array_val(ba)->dim[0]; int dimy = Caml_ba_array_val(ba)->dim[1]; printtab_(Caml_ba_data_val(ba), &dimx, &dimy); return Val_unit; }
gerdstolpmann/ocaml
testsuite/tests/lib-bigarray-2/bigarrfstub.c
C
lgpl-2.1
1,666
/* Common base code for the decNumber C Library. Copyright (C) 2007-2019 Free Software Foundation, Inc. Contributed by IBM Corporation. Author Mike Cowlishaw. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ /* ------------------------------------------------------------------ */ /* decBasic.c -- common base code for Basic decimal types */ /* ------------------------------------------------------------------ */ /* This module comprises code that is shared between decDouble and */ /* decQuad (but not decSingle). The main arithmetic operations are */ /* here (Add, Subtract, Multiply, FMA, and Division operators). */ /* */ /* Unlike decNumber, parameterization takes place at compile time */ /* rather than at runtime. The parameters are set in the decDouble.c */ /* (etc.) files, which then include this one to produce the compiled */ /* code. The functions here, therefore, are code shared between */ /* multiple formats. */ /* */ /* This must be included after decCommon.c. */ /* ------------------------------------------------------------------ */ /* Names here refer to decFloat rather than to decDouble, etc., and */ /* the functions are in strict alphabetical order. */ /* The compile-time flags SINGLE, DOUBLE, and QUAD are set up in */ /* decCommon.c */ #if !defined(QUAD) #error decBasic.c must be included after decCommon.c #endif #if SINGLE #error Routines in decBasic.c are for decDouble and decQuad only #endif /* Private constants */ #define DIVIDE 0x80000000 /* Divide operations [as flags] */ #define REMAINDER 0x40000000 /* .. */ #define DIVIDEINT 0x20000000 /* .. */ #define REMNEAR 0x10000000 /* .. */ /* Private functions (local, used only by routines in this module) */ static decFloat *decDivide(decFloat *, const decFloat *, const decFloat *, decContext *, uInt); static decFloat *decCanonical(decFloat *, const decFloat *); static void decFiniteMultiply(bcdnum *, uByte *, const decFloat *, const decFloat *); static decFloat *decInfinity(decFloat *, const decFloat *); static decFloat *decInvalid(decFloat *, decContext *); static decFloat *decNaNs(decFloat *, const decFloat *, const decFloat *, decContext *); static Int decNumCompare(const decFloat *, const decFloat *, Flag); static decFloat *decToIntegral(decFloat *, const decFloat *, decContext *, enum rounding, Flag); static uInt decToInt32(const decFloat *, decContext *, enum rounding, Flag, Flag); /* ------------------------------------------------------------------ */ /* decCanonical -- copy a decFloat, making canonical */ /* */ /* result gets the canonicalized df */ /* df is the decFloat to copy and make canonical */ /* returns result */ /* */ /* This is exposed via decFloatCanonical for Double and Quad only. */ /* This works on specials, too; no error or exception is possible. */ /* ------------------------------------------------------------------ */ static decFloat * decCanonical(decFloat *result, const decFloat *df) { uInt encode, precode, dpd; /* work */ uInt inword, uoff, canon; /* .. */ Int n; /* counter (down) */ if (df!=result) *result=*df; /* effect copy if needed */ if (DFISSPECIAL(result)) { if (DFISINF(result)) return decInfinity(result, df); /* clean Infinity */ /* is a NaN */ DFWORD(result, 0)&=~ECONNANMASK; /* clear ECON except selector */ if (DFISCCZERO(df)) return result; /* coefficient continuation is 0 */ /* drop through to check payload */ } /* return quickly if the coefficient continuation is canonical */ { /* declare block */ #if DOUBLE uInt sourhi=DFWORD(df, 0); uInt sourlo=DFWORD(df, 1); if (CANONDPDOFF(sourhi, 8) && CANONDPDTWO(sourhi, sourlo, 30) && CANONDPDOFF(sourlo, 20) && CANONDPDOFF(sourlo, 10) && CANONDPDOFF(sourlo, 0)) return result; #elif QUAD uInt sourhi=DFWORD(df, 0); uInt sourmh=DFWORD(df, 1); uInt sourml=DFWORD(df, 2); uInt sourlo=DFWORD(df, 3); if (CANONDPDOFF(sourhi, 4) && CANONDPDTWO(sourhi, sourmh, 26) && CANONDPDOFF(sourmh, 16) && CANONDPDOFF(sourmh, 6) && CANONDPDTWO(sourmh, sourml, 28) && CANONDPDOFF(sourml, 18) && CANONDPDOFF(sourml, 8) && CANONDPDTWO(sourml, sourlo, 30) && CANONDPDOFF(sourlo, 20) && CANONDPDOFF(sourlo, 10) && CANONDPDOFF(sourlo, 0)) return result; #endif } /* block */ /* Loop to repair a non-canonical coefficent, as needed */ inword=DECWORDS-1; /* current input word */ uoff=0; /* bit offset of declet */ encode=DFWORD(result, inword); for (n=DECLETS-1; n>=0; n--) { /* count down declets of 10 bits */ dpd=encode>>uoff; uoff+=10; if (uoff>32) { /* crossed uInt boundary */ inword--; encode=DFWORD(result, inword); uoff-=32; dpd|=encode<<(10-uoff); /* get pending bits */ } dpd&=0x3ff; /* clear uninteresting bits */ if (dpd<0x16e) continue; /* must be canonical */ canon=BIN2DPD[DPD2BIN[dpd]]; /* determine canonical declet */ if (canon==dpd) continue; /* have canonical declet */ /* need to replace declet */ if (uoff>=10) { /* all within current word */ encode&=~(0x3ff<<(uoff-10)); /* clear the 10 bits ready for replace */ encode|=canon<<(uoff-10); /* insert the canonical form */ DFWORD(result, inword)=encode; /* .. and save */ continue; } /* straddled words */ precode=DFWORD(result, inword+1); /* get previous */ precode&=0xffffffff>>(10-uoff); /* clear top bits */ DFWORD(result, inword+1)=precode|(canon<<(32-(10-uoff))); encode&=0xffffffff<<uoff; /* clear bottom bits */ encode|=canon>>(10-uoff); /* insert canonical */ DFWORD(result, inword)=encode; /* .. and save */ } /* n */ return result; } /* decCanonical */ /* ------------------------------------------------------------------ */ /* decDivide -- divide operations */ /* */ /* result gets the result of dividing dfl by dfr: */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* op is the operation selector */ /* returns result */ /* */ /* op is one of DIVIDE, REMAINDER, DIVIDEINT, or REMNEAR. */ /* ------------------------------------------------------------------ */ #define DIVCOUNT 0 /* 1 to instrument subtractions counter */ #define DIVBASE ((uInt)BILLION) /* the base used for divide */ #define DIVOPLEN DECPMAX9 /* operand length ('digits' base 10**9) */ #define DIVACCLEN (DIVOPLEN*3) /* accumulator length (ditto) */ static decFloat * decDivide(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set, uInt op) { decFloat quotient; /* for remainders */ bcdnum num; /* for final conversion */ uInt acc[DIVACCLEN]; /* coefficent in base-billion .. */ uInt div[DIVOPLEN]; /* divisor in base-billion .. */ uInt quo[DIVOPLEN+1]; /* quotient in base-billion .. */ uByte bcdacc[(DIVOPLEN+1)*9+2]; /* for quotient in BCD, +1, +1 */ uInt *msua, *msud, *msuq; /* -> msu of acc, div, and quo */ Int divunits, accunits; /* lengths */ Int quodigits; /* digits in quotient */ uInt *lsua, *lsuq; /* -> current acc and quo lsus */ Int length, multiplier; /* work */ uInt carry, sign; /* .. */ uInt *ua, *ud, *uq; /* .. */ uByte *ub; /* .. */ uInt uiwork; /* for macros */ uInt divtop; /* top unit of div adjusted for estimating */ #if DIVCOUNT static uInt maxcount=0; /* worst-seen subtractions count */ uInt divcount=0; /* subtractions count [this divide] */ #endif /* calculate sign */ num.sign=(DFWORD(dfl, 0)^DFWORD(dfr, 0)) & DECFLOAT_Sign; if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) { /* either is special? */ /* NaNs are handled as usual */ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set); /* one or two infinities */ if (DFISINF(dfl)) { if (DFISINF(dfr)) return decInvalid(result, set); /* Two infinities bad */ if (op&(REMAINDER|REMNEAR)) return decInvalid(result, set); /* as is rem */ /* Infinity/x is infinite and quiet, even if x=0 */ DFWORD(result, 0)=num.sign; return decInfinity(result, result); } /* must be x/Infinity -- remainders are lhs */ if (op&(REMAINDER|REMNEAR)) return decCanonical(result, dfl); /* divides: return zero with correct sign and exponent depending */ /* on op (Etiny for divide, 0 for divideInt) */ decFloatZero(result); if (op==DIVIDEINT) DFWORD(result, 0)|=num.sign; /* add sign */ else DFWORD(result, 0)=num.sign; /* zeros the exponent, too */ return result; } /* next, handle zero operands (x/0 and 0/x) */ if (DFISZERO(dfr)) { /* x/0 */ if (DFISZERO(dfl)) { /* 0/0 is undefined */ decFloatZero(result); DFWORD(result, 0)=DECFLOAT_qNaN; set->status|=DEC_Division_undefined; return result; } if (op&(REMAINDER|REMNEAR)) return decInvalid(result, set); /* bad rem */ set->status|=DEC_Division_by_zero; DFWORD(result, 0)=num.sign; return decInfinity(result, result); /* x/0 -> signed Infinity */ } num.exponent=GETEXPUN(dfl)-GETEXPUN(dfr); /* ideal exponent */ if (DFISZERO(dfl)) { /* 0/x (x!=0) */ /* if divide, result is 0 with ideal exponent; divideInt has */ /* exponent=0, remainders give zero with lower exponent */ if (op&DIVIDEINT) { decFloatZero(result); DFWORD(result, 0)|=num.sign; /* add sign */ return result; } if (!(op&DIVIDE)) { /* a remainder */ /* exponent is the minimum of the operands */ num.exponent=MINI(GETEXPUN(dfl), GETEXPUN(dfr)); /* if the result is zero the sign shall be sign of dfl */ num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign; } bcdacc[0]=0; num.msd=bcdacc; /* -> 0 */ num.lsd=bcdacc; /* .. */ return decFinalize(result, &num, set); /* [divide may clamp exponent] */ } /* 0/x */ /* [here, both operands are known to be finite and non-zero] */ /* extract the operand coefficents into 'units' which are */ /* base-billion; the lhs is high-aligned in acc and the msu of both */ /* acc and div is at the right-hand end of array (offset length-1); */ /* the quotient can need one more unit than the operands as digits */ /* in it are not necessarily aligned neatly; further, the quotient */ /* may not start accumulating until after the end of the initial */ /* operand in acc if that is small (e.g., 1) so the accumulator */ /* must have at least that number of units extra (at the ls end) */ GETCOEFFBILL(dfl, acc+DIVACCLEN-DIVOPLEN); GETCOEFFBILL(dfr, div); /* zero the low uInts of acc */ acc[0]=0; acc[1]=0; acc[2]=0; acc[3]=0; #if DOUBLE #if DIVOPLEN!=2 #error Unexpected Double DIVOPLEN #endif #elif QUAD acc[4]=0; acc[5]=0; acc[6]=0; acc[7]=0; #if DIVOPLEN!=4 #error Unexpected Quad DIVOPLEN #endif #endif /* set msu and lsu pointers */ msua=acc+DIVACCLEN-1; /* [leading zeros removed below] */ msuq=quo+DIVOPLEN; /*[loop for div will terminate because operands are non-zero] */ for (msud=div+DIVOPLEN-1; *msud==0;) msud--; /* the initial least-significant unit of acc is set so acc appears */ /* to have the same length as div. */ /* This moves one position towards the least possible for each */ /* iteration */ divunits=(Int)(msud-div+1); /* precalculate */ lsua=msua-divunits+1; /* initial working lsu of acc */ lsuq=msuq; /* and of quo */ /* set up the estimator for the multiplier; this is the msu of div, */ /* plus two bits from the unit below (if any) rounded up by one if */ /* there are any non-zero bits or units below that [the extra two */ /* bits makes for a much better estimate when the top unit is small] */ divtop=*msud<<2; if (divunits>1) { uInt *um=msud-1; uInt d=*um; if (d>=750000000) {divtop+=3; d-=750000000;} else if (d>=500000000) {divtop+=2; d-=500000000;} else if (d>=250000000) {divtop++; d-=250000000;} if (d) divtop++; else for (um--; um>=div; um--) if (*um) { divtop++; break; } } /* >1 unit */ #if DECTRACE {Int i; printf("----- div="); for (i=divunits-1; i>=0; i--) printf("%09ld ", (LI)div[i]); printf("\n");} #endif /* now collect up to DECPMAX+1 digits in the quotient (this may */ /* need OPLEN+1 uInts if unaligned) */ quodigits=0; /* no digits yet */ for (;; lsua--) { /* outer loop -- each input position */ #if DECCHECK if (lsua<acc) { printf("Acc underrun...\n"); break; } #endif #if DECTRACE printf("Outer: quodigits=%ld acc=", (LI)quodigits); for (ua=msua; ua>=lsua; ua--) printf("%09ld ", (LI)*ua); printf("\n"); #endif *lsuq=0; /* default unit result is 0 */ for (;;) { /* inner loop -- calculate quotient unit */ /* strip leading zero units from acc (either there initially or */ /* from subtraction below); this may strip all if exactly 0 */ for (; *msua==0 && msua>=lsua;) msua--; accunits=(Int)(msua-lsua+1); /* [maybe 0] */ /* subtraction is only necessary and possible if there are as */ /* least as many units remaining in acc for this iteration as */ /* there are in div */ if (accunits<divunits) { if (accunits==0) msua++; /* restore */ break; } /* If acc is longer than div then subtraction is definitely */ /* possible (as msu of both is non-zero), but if they are the */ /* same length a comparison is needed. */ /* If a subtraction is needed then a good estimate of the */ /* multiplier for the subtraction is also needed in order to */ /* minimise the iterations of this inner loop because the */ /* subtractions needed dominate division performance. */ if (accunits==divunits) { /* compare the high divunits of acc and div: */ /* acc<div: this quotient unit is unchanged; subtraction */ /* will be possible on the next iteration */ /* acc==div: quotient gains 1, set acc=0 */ /* acc>div: subtraction necessary at this position */ for (ud=msud, ua=msua; ud>div; ud--, ua--) if (*ud!=*ua) break; /* [now at first mismatch or lsu] */ if (*ud>*ua) break; /* next time... */ if (*ud==*ua) { /* all compared equal */ *lsuq+=1; /* increment result */ msua=lsua; /* collapse acc units */ *msua=0; /* .. to a zero */ break; } /* subtraction necessary; estimate multiplier [see above] */ /* if both *msud and *msua are small it is cost-effective to */ /* bring in part of the following units (if any) to get a */ /* better estimate (assume some other non-zero in div) */ #define DIVLO 1000000U #define DIVHI (DIVBASE/DIVLO) #if DECUSE64 if (divunits>1) { /* there cannot be a *(msud-2) for DECDOUBLE so next is */ /* an exact calculation unless DECQUAD (which needs to */ /* assume bits out there if divunits>2) */ uLong mul=(uLong)*msua * DIVBASE + *(msua-1); uLong div=(uLong)*msud * DIVBASE + *(msud-1); #if QUAD if (divunits>2) div++; #endif mul/=div; multiplier=(Int)mul; } else multiplier=*msua/(*msud); #else if (divunits>1 && *msua<DIVLO && *msud<DIVLO) { multiplier=(*msua*DIVHI + *(msua-1)/DIVLO) /(*msud*DIVHI + *(msud-1)/DIVLO +1); } else multiplier=(*msua<<2)/divtop; #endif } else { /* accunits>divunits */ /* msud is one unit 'lower' than msua, so estimate differently */ #if DECUSE64 uLong mul; /* as before, bring in extra digits if possible */ if (divunits>1 && *msua<DIVLO && *msud<DIVLO) { mul=((uLong)*msua * DIVHI * DIVBASE) + *(msua-1) * DIVHI + *(msua-2)/DIVLO; mul/=(*msud*DIVHI + *(msud-1)/DIVLO +1); } else if (divunits==1) { mul=(uLong)*msua * DIVBASE + *(msua-1); mul/=*msud; /* no more to the right */ } else { mul=(uLong)(*msua) * (uInt)(DIVBASE<<2) + (*(msua-1)<<2); mul/=divtop; /* [divtop already allows for sticky bits] */ } multiplier=(Int)mul; #else multiplier=*msua * ((DIVBASE<<2)/divtop); #endif } if (multiplier==0) multiplier=1; /* marginal case */ *lsuq+=multiplier; #if DIVCOUNT /* printf("Multiplier: %ld\n", (LI)multiplier); */ divcount++; #endif /* Carry out the subtraction acc-(div*multiplier); for each */ /* unit in div, do the multiply, split to units (see */ /* decFloatMultiply for the algorithm), and subtract from acc */ #define DIVMAGIC 2305843009U /* 2**61/10**9 */ #define DIVSHIFTA 29 #define DIVSHIFTB 32 carry=0; for (ud=div, ua=lsua; ud<=msud; ud++, ua++) { uInt lo, hop; #if DECUSE64 uLong sub=(uLong)multiplier*(*ud)+carry; if (sub<DIVBASE) { carry=0; lo=(uInt)sub; } else { hop=(uInt)(sub>>DIVSHIFTA); carry=(uInt)(((uLong)hop*DIVMAGIC)>>DIVSHIFTB); /* the estimate is now in hi; now calculate sub-hi*10**9 */ /* to get the remainder (which will be <DIVBASE)) */ lo=(uInt)sub; lo-=carry*DIVBASE; /* low word of result */ if (lo>=DIVBASE) { lo-=DIVBASE; /* correct by +1 */ carry++; } } #else /* 32-bit */ uInt hi; /* calculate multiplier*(*ud) into hi and lo */ LONGMUL32HI(hi, *ud, multiplier); /* get the high word */ lo=multiplier*(*ud); /* .. and the low */ lo+=carry; /* add the old hi */ carry=hi+(lo<carry); /* .. with any carry */ if (carry || lo>=DIVBASE) { /* split is needed */ hop=(carry<<3)+(lo>>DIVSHIFTA); /* hi:lo/2**29 */ LONGMUL32HI(carry, hop, DIVMAGIC); /* only need the high word */ /* [DIVSHIFTB is 32, so carry can be used directly] */ /* the estimate is now in carry; now calculate hi:lo-est*10**9; */ /* happily the top word of the result is irrelevant because it */ /* will always be zero so this needs only one multiplication */ lo-=(carry*DIVBASE); /* the correction here will be at most +1; do it */ if (lo>=DIVBASE) { lo-=DIVBASE; carry++; } } #endif if (lo>*ua) { /* borrow needed */ *ua+=DIVBASE; carry++; } *ua-=lo; } /* ud loop */ if (carry) *ua-=carry; /* accdigits>divdigits [cannot borrow] */ } /* inner loop */ /* the outer loop terminates when there is either an exact result */ /* or enough digits; first update the quotient digit count and */ /* pointer (if any significant digits) */ #if DECTRACE if (*lsuq || quodigits) printf("*lsuq=%09ld\n", (LI)*lsuq); #endif if (quodigits) { quodigits+=9; /* had leading unit earlier */ lsuq--; if (quodigits>DECPMAX+1) break; /* have enough */ } else if (*lsuq) { /* first quotient digits */ const uInt *pow; for (pow=DECPOWERS; *lsuq>=*pow; pow++) quodigits++; lsuq--; /* [cannot have >DECPMAX+1 on first unit] */ } if (*msua!=0) continue; /* not an exact result */ /* acc is zero iff used all of original units and zero down to lsua */ /* (must also continue to original lsu for correct quotient length) */ if (lsua>acc+DIVACCLEN-DIVOPLEN) continue; for (; msua>lsua && *msua==0;) msua--; if (*msua==0 && msua==lsua) break; } /* outer loop */ /* all of the original operand in acc has been covered at this point */ /* quotient now has at least DECPMAX+2 digits */ /* *msua is now non-0 if inexact and sticky bits */ /* lsuq is one below the last uint of the quotient */ lsuq++; /* set -> true lsu of quo */ if (*msua) *lsuq|=1; /* apply sticky bit */ /* quo now holds the (unrounded) quotient in base-billion; one */ /* base-billion 'digit' per uInt. */ #if DECTRACE printf("DivQuo:"); for (uq=msuq; uq>=lsuq; uq--) printf(" %09ld", (LI)*uq); printf("\n"); #endif /* Now convert to BCD for rounding and cleanup, starting from the */ /* most significant end [offset by one into bcdacc to leave room */ /* for a possible carry digit if rounding for REMNEAR is needed] */ for (uq=msuq, ub=bcdacc+1; uq>=lsuq; uq--, ub+=9) { uInt top, mid, rem; /* work */ if (*uq==0) { /* no split needed */ UBFROMUI(ub, 0); /* clear 9 BCD8s */ UBFROMUI(ub+4, 0); /* .. */ *(ub+8)=0; /* .. */ continue; } /* *uq is non-zero -- split the base-billion digit into */ /* hi, mid, and low three-digits */ #define divsplit9 1000000 /* divisor */ #define divsplit6 1000 /* divisor */ /* The splitting is done by simple divides and remainders, */ /* assuming the compiler will optimize these [GCC does] */ top=*uq/divsplit9; rem=*uq%divsplit9; mid=rem/divsplit6; rem=rem%divsplit6; /* lay out the nine BCD digits (plus one unwanted byte) */ UBFROMUI(ub, UBTOUI(&BIN2BCD8[top*4])); UBFROMUI(ub+3, UBTOUI(&BIN2BCD8[mid*4])); UBFROMUI(ub+6, UBTOUI(&BIN2BCD8[rem*4])); } /* BCD conversion loop */ ub--; /* -> lsu */ /* complete the bcdnum; quodigits is correct, so the position of */ /* the first non-zero is known */ num.msd=bcdacc+1+(msuq-lsuq+1)*9-quodigits; num.lsd=ub; /* make exponent adjustments, etc */ if (lsua<acc+DIVACCLEN-DIVOPLEN) { /* used extra digits */ num.exponent-=(Int)((acc+DIVACCLEN-DIVOPLEN-lsua)*9); /* if the result was exact then there may be up to 8 extra */ /* trailing zeros in the overflowed quotient final unit */ if (*msua==0) { for (; *ub==0;) ub--; /* drop zeros */ num.exponent+=(Int)(num.lsd-ub); /* and adjust exponent */ num.lsd=ub; } } /* adjustment needed */ #if DIVCOUNT if (divcount>maxcount) { /* new high-water nark */ maxcount=divcount; printf("DivNewMaxCount: %ld\n", (LI)maxcount); } #endif if (op&DIVIDE) return decFinalize(result, &num, set); /* all done */ /* Is DIVIDEINT or a remainder; there is more to do -- first form */ /* the integer (this is done 'after the fact', unlike as in */ /* decNumber, so as not to tax DIVIDE) */ /* The first non-zero digit will be in the first 9 digits, known */ /* from quodigits and num.msd, so there is always space for DECPMAX */ /* digits */ length=(Int)(num.lsd-num.msd+1); /*printf("Length exp: %ld %ld\n", (LI)length, (LI)num.exponent); */ if (length+num.exponent>DECPMAX) { /* cannot fit */ decFloatZero(result); DFWORD(result, 0)=DECFLOAT_qNaN; set->status|=DEC_Division_impossible; return result; } if (num.exponent>=0) { /* already an int, or need pad zeros */ for (ub=num.lsd+1; ub<=num.lsd+num.exponent; ub++) *ub=0; num.lsd+=num.exponent; } else { /* too long: round or truncate needed */ Int drop=-num.exponent; if (!(op&REMNEAR)) { /* simple truncate */ num.lsd-=drop; if (num.lsd<num.msd) { /* truncated all */ num.lsd=num.msd; /* make 0 */ *num.lsd=0; /* .. [sign still relevant] */ } } else { /* round to nearest even [sigh] */ /* round-to-nearest, in-place; msd is at or to right of bcdacc+1 */ /* (this is a special case of Quantize -- q.v. for commentary) */ uByte *roundat; /* -> re-round digit */ uByte reround; /* reround value */ *(num.msd-1)=0; /* in case of left carry, or make 0 */ if (drop<length) roundat=num.lsd-drop+1; else if (drop==length) roundat=num.msd; else roundat=num.msd-1; /* [-> 0] */ reround=*roundat; for (ub=roundat+1; ub<=num.lsd; ub++) { if (*ub!=0) { reround=DECSTICKYTAB[reround]; break; } } /* check stickies */ if (roundat>num.msd) num.lsd=roundat-1; else { num.msd--; /* use the 0 .. */ num.lsd=num.msd; /* .. at the new MSD place */ } if (reround!=0) { /* discarding non-zero */ uInt bump=0; /* rounding is DEC_ROUND_HALF_EVEN always */ if (reround>5) bump=1; /* >0.5 goes up */ else if (reround==5) /* exactly 0.5000 .. */ bump=*(num.lsd) & 0x01; /* .. up iff [new] lsd is odd */ if (bump!=0) { /* need increment */ /* increment the coefficient; this might end up with 1000... */ ub=num.lsd; for (; UBTOUI(ub-3)==0x09090909; ub-=4) UBFROMUI(ub-3, 0); for (; *ub==9; ub--) *ub=0; /* at most 3 more */ *ub+=1; if (ub<num.msd) num.msd--; /* carried */ } /* bump needed */ } /* reround!=0 */ } /* remnear */ } /* round or truncate needed */ num.exponent=0; /* all paths */ /*decShowNum(&num, "int"); */ if (op&DIVIDEINT) return decFinalize(result, &num, set); /* all done */ /* Have a remainder to calculate */ decFinalize(&quotient, &num, set); /* lay out the integer so far */ DFWORD(&quotient, 0)^=DECFLOAT_Sign; /* negate it */ sign=DFWORD(dfl, 0); /* save sign of dfl */ decFloatFMA(result, &quotient, dfr, dfl, set); if (!DFISZERO(result)) return result; /* if the result is zero the sign shall be sign of dfl */ DFWORD(&quotient, 0)=sign; /* construct decFloat of sign */ return decFloatCopySign(result, result, &quotient); } /* decDivide */ /* ------------------------------------------------------------------ */ /* decFiniteMultiply -- multiply two finite decFloats */ /* */ /* num gets the result of multiplying dfl and dfr */ /* bcdacc .. with the coefficient in this array */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* */ /* This effects the multiplication of two decFloats, both known to be */ /* finite, leaving the result in a bcdnum ready for decFinalize (for */ /* use in Multiply) or in a following addition (FMA). */ /* */ /* bcdacc must have space for at least DECPMAX9*18+1 bytes. */ /* No error is possible and no status is set. */ /* ------------------------------------------------------------------ */ /* This routine has two separate implementations of the core */ /* multiplication; both using base-billion. One uses only 32-bit */ /* variables (Ints and uInts) or smaller; the other uses uLongs (for */ /* multiplication and addition only). Both implementations cover */ /* both arithmetic sizes (DOUBLE and QUAD) in order to allow timing */ /* comparisons. In any one compilation only one implementation for */ /* each size can be used, and if DECUSE64 is 0 then use of the 32-bit */ /* version is forced. */ /* */ /* Historical note: an earlier version of this code also supported the */ /* 256-bit format and has been preserved. That is somewhat trickier */ /* during lazy carry splitting because the initial quotient estimate */ /* (est) can exceed 32 bits. */ #define MULTBASE ((uInt)BILLION) /* the base used for multiply */ #define MULOPLEN DECPMAX9 /* operand length ('digits' base 10**9) */ #define MULACCLEN (MULOPLEN*2) /* accumulator length (ditto) */ #define LEADZEROS (MULACCLEN*9 - DECPMAX*2) /* leading zeros always */ /* Assertions: exponent not too large and MULACCLEN is a multiple of 4 */ #if DECEMAXD>9 #error Exponent may overflow when doubled for Multiply #endif #if MULACCLEN!=(MULACCLEN/4)*4 /* This assumption is used below only for initialization */ #error MULACCLEN is not a multiple of 4 #endif static void decFiniteMultiply(bcdnum *num, uByte *bcdacc, const decFloat *dfl, const decFloat *dfr) { uInt bufl[MULOPLEN]; /* left coefficient (base-billion) */ uInt bufr[MULOPLEN]; /* right coefficient (base-billion) */ uInt *ui, *uj; /* work */ uByte *ub; /* .. */ uInt uiwork; /* for macros */ #if DECUSE64 uLong accl[MULACCLEN]; /* lazy accumulator (base-billion+) */ uLong *pl; /* work -> lazy accumulator */ uInt acc[MULACCLEN]; /* coefficent in base-billion .. */ #else uInt acc[MULACCLEN*2]; /* accumulator in base-billion .. */ #endif uInt *pa; /* work -> accumulator */ /*printf("Base10**9: OpLen=%d MulAcclen=%d\n", OPLEN, MULACCLEN); */ /* Calculate sign and exponent */ num->sign=(DFWORD(dfl, 0)^DFWORD(dfr, 0)) & DECFLOAT_Sign; num->exponent=GETEXPUN(dfl)+GETEXPUN(dfr); /* [see assertion above] */ /* Extract the coefficients and prepare the accumulator */ /* the coefficients of the operands are decoded into base-billion */ /* numbers in uInt arrays (bufl and bufr, LSD at offset 0) of the */ /* appropriate size. */ GETCOEFFBILL(dfl, bufl); GETCOEFFBILL(dfr, bufr); #if DECTRACE && 0 printf("CoeffbL:"); for (ui=bufl+MULOPLEN-1; ui>=bufl; ui--) printf(" %08lx", (LI)*ui); printf("\n"); printf("CoeffbR:"); for (uj=bufr+MULOPLEN-1; uj>=bufr; uj--) printf(" %08lx", (LI)*uj); printf("\n"); #endif /* start the 64-bit/32-bit differing paths... */ #if DECUSE64 /* zero the accumulator */ #if MULACCLEN==4 accl[0]=0; accl[1]=0; accl[2]=0; accl[3]=0; #else /* use a loop */ /* MULACCLEN is a multiple of four, asserted above */ for (pl=accl; pl<accl+MULACCLEN; pl+=4) { *pl=0; *(pl+1)=0; *(pl+2)=0; *(pl+3)=0;/* [reduce overhead] */ } /* pl */ #endif /* Effect the multiplication */ /* The multiplcation proceeds using MFC's lazy-carry resolution */ /* algorithm from decNumber. First, the multiplication is */ /* effected, allowing accumulation of the partial products (which */ /* are in base-billion at each column position) into 64 bits */ /* without resolving back to base=billion after each addition. */ /* These 64-bit numbers (which may contain up to 19 decimal digits) */ /* are then split using the Clark & Cowlishaw algorithm (see below). */ /* [Testing for 0 in the inner loop is not really a 'win'] */ for (ui=bufr; ui<bufr+MULOPLEN; ui++) { /* over each item in rhs */ if (*ui==0) continue; /* product cannot affect result */ pl=accl+(ui-bufr); /* where to add the lhs */ for (uj=bufl; uj<bufl+MULOPLEN; uj++, pl++) { /* over each item in lhs */ /* if (*uj==0) continue; // product cannot affect result */ *pl+=((uLong)*ui)*(*uj); } /* uj */ } /* ui */ /* The 64-bit carries must now be resolved; this means that a */ /* quotient/remainder has to be calculated for base-billion (1E+9). */ /* For this, Clark & Cowlishaw's quotient estimation approach (also */ /* used in decNumber) is needed, because 64-bit divide is generally */ /* extremely slow on 32-bit machines, and may be slower than this */ /* approach even on 64-bit machines. This algorithm splits X */ /* using: */ /* */ /* magic=2**(A+B)/1E+9; // 'magic number' */ /* hop=X/2**A; // high order part of X (by shift) */ /* est=magic*hop/2**B // quotient estimate (may be low by 1) */ /* */ /* A and B are quite constrained; hop and magic must fit in 32 bits, */ /* and 2**(A+B) must be as large as possible (which is 2**61 if */ /* magic is to fit). Further, maxX increases with the length of */ /* the operands (and hence the number of partial products */ /* accumulated); maxX is OPLEN*(10**18), which is up to 19 digits. */ /* */ /* It can be shown that when OPLEN is 2 then the maximum error in */ /* the estimated quotient is <1, but for larger maximum x the */ /* maximum error is above 1 so a correction that is >1 may be */ /* needed. Values of A and B are chosen to satisfy the constraints */ /* just mentioned while minimizing the maximum error (and hence the */ /* maximum correction), as shown in the following table: */ /* */ /* Type OPLEN A B maxX maxError maxCorrection */ /* --------------------------------------------------------- */ /* DOUBLE 2 29 32 <2*10**18 0.63 1 */ /* QUAD 4 30 31 <4*10**18 1.17 2 */ /* */ /* In the OPLEN==2 case there is most choice, but the value for B */ /* of 32 has a big advantage as then the calculation of the */ /* estimate requires no shifting; the compiler can extract the high */ /* word directly after multiplying magic*hop. */ #define MULMAGIC 2305843009U /* 2**61/10**9 [both cases] */ #if DOUBLE #define MULSHIFTA 29 #define MULSHIFTB 32 #elif QUAD #define MULSHIFTA 30 #define MULSHIFTB 31 #else #error Unexpected type #endif #if DECTRACE printf("MulAccl:"); for (pl=accl+MULACCLEN-1; pl>=accl; pl--) printf(" %08lx:%08lx", (LI)(*pl>>32), (LI)(*pl&0xffffffff)); printf("\n"); #endif for (pl=accl, pa=acc; pl<accl+MULACCLEN; pl++, pa++) { /* each column position */ uInt lo, hop; /* work */ uInt est; /* cannot exceed 4E+9 */ if (*pl>=MULTBASE) { /* *pl holds a binary number which needs to be split */ hop=(uInt)(*pl>>MULSHIFTA); est=(uInt)(((uLong)hop*MULMAGIC)>>MULSHIFTB); /* the estimate is now in est; now calculate hi:lo-est*10**9; */ /* happily the top word of the result is irrelevant because it */ /* will always be zero so this needs only one multiplication */ lo=(uInt)(*pl-((uLong)est*MULTBASE)); /* low word of result */ /* If QUAD, the correction here could be +2 */ if (lo>=MULTBASE) { lo-=MULTBASE; /* correct by +1 */ est++; #if QUAD /* may need to correct by +2 */ if (lo>=MULTBASE) { lo-=MULTBASE; est++; } #endif } /* finally place lo as the new coefficient 'digit' and add est to */ /* the next place up [this is safe because this path is never */ /* taken on the final iteration as *pl will fit] */ *pa=lo; *(pl+1)+=est; } /* *pl needed split */ else { /* *pl<MULTBASE */ *pa=(uInt)*pl; /* just copy across */ } } /* pl loop */ #else /* 32-bit */ for (pa=acc;; pa+=4) { /* zero the accumulator */ *pa=0; *(pa+1)=0; *(pa+2)=0; *(pa+3)=0; /* [reduce overhead] */ if (pa==acc+MULACCLEN*2-4) break; /* multiple of 4 asserted */ } /* pa */ /* Effect the multiplication */ /* uLongs are not available (and in particular, there is no uLong */ /* divide) but it is still possible to use MFC's lazy-carry */ /* resolution algorithm from decNumber. First, the multiplication */ /* is effected, allowing accumulation of the partial products */ /* (which are in base-billion at each column position) into 64 bits */ /* [with the high-order 32 bits in each position being held at */ /* offset +ACCLEN from the low-order 32 bits in the accumulator]. */ /* These 64-bit numbers (which may contain up to 19 decimal digits) */ /* are then split using the Clark & Cowlishaw algorithm (see */ /* below). */ for (ui=bufr;; ui++) { /* over each item in rhs */ uInt hi, lo; /* words of exact multiply result */ pa=acc+(ui-bufr); /* where to add the lhs */ for (uj=bufl;; uj++, pa++) { /* over each item in lhs */ LONGMUL32HI(hi, *ui, *uj); /* calculate product of digits */ lo=(*ui)*(*uj); /* .. */ *pa+=lo; /* accumulate low bits and .. */ *(pa+MULACCLEN)+=hi+(*pa<lo); /* .. high bits with any carry */ if (uj==bufl+MULOPLEN-1) break; } if (ui==bufr+MULOPLEN-1) break; } /* The 64-bit carries must now be resolved; this means that a */ /* quotient/remainder has to be calculated for base-billion (1E+9). */ /* For this, Clark & Cowlishaw's quotient estimation approach (also */ /* used in decNumber) is needed, because 64-bit divide is generally */ /* extremely slow on 32-bit machines. This algorithm splits X */ /* using: */ /* */ /* magic=2**(A+B)/1E+9; // 'magic number' */ /* hop=X/2**A; // high order part of X (by shift) */ /* est=magic*hop/2**B // quotient estimate (may be low by 1) */ /* */ /* A and B are quite constrained; hop and magic must fit in 32 bits, */ /* and 2**(A+B) must be as large as possible (which is 2**61 if */ /* magic is to fit). Further, maxX increases with the length of */ /* the operands (and hence the number of partial products */ /* accumulated); maxX is OPLEN*(10**18), which is up to 19 digits. */ /* */ /* It can be shown that when OPLEN is 2 then the maximum error in */ /* the estimated quotient is <1, but for larger maximum x the */ /* maximum error is above 1 so a correction that is >1 may be */ /* needed. Values of A and B are chosen to satisfy the constraints */ /* just mentioned while minimizing the maximum error (and hence the */ /* maximum correction), as shown in the following table: */ /* */ /* Type OPLEN A B maxX maxError maxCorrection */ /* --------------------------------------------------------- */ /* DOUBLE 2 29 32 <2*10**18 0.63 1 */ /* QUAD 4 30 31 <4*10**18 1.17 2 */ /* */ /* In the OPLEN==2 case there is most choice, but the value for B */ /* of 32 has a big advantage as then the calculation of the */ /* estimate requires no shifting; the high word is simply */ /* calculated from multiplying magic*hop. */ #define MULMAGIC 2305843009U /* 2**61/10**9 [both cases] */ #if DOUBLE #define MULSHIFTA 29 #define MULSHIFTB 32 #elif QUAD #define MULSHIFTA 30 #define MULSHIFTB 31 #else #error Unexpected type #endif #if DECTRACE printf("MulHiLo:"); for (pa=acc+MULACCLEN-1; pa>=acc; pa--) printf(" %08lx:%08lx", (LI)*(pa+MULACCLEN), (LI)*pa); printf("\n"); #endif for (pa=acc;; pa++) { /* each low uInt */ uInt hi, lo; /* words of exact multiply result */ uInt hop, estlo; /* work */ #if QUAD uInt esthi; /* .. */ #endif lo=*pa; hi=*(pa+MULACCLEN); /* top 32 bits */ /* hi and lo now hold a binary number which needs to be split */ #if DOUBLE hop=(hi<<3)+(lo>>MULSHIFTA); /* hi:lo/2**29 */ LONGMUL32HI(estlo, hop, MULMAGIC);/* only need the high word */ /* [MULSHIFTB is 32, so estlo can be used directly] */ /* the estimate is now in estlo; now calculate hi:lo-est*10**9; */ /* happily the top word of the result is irrelevant because it */ /* will always be zero so this needs only one multiplication */ lo-=(estlo*MULTBASE); /* esthi=0; // high word is ignored below */ /* the correction here will be at most +1; do it */ if (lo>=MULTBASE) { lo-=MULTBASE; estlo++; } #elif QUAD hop=(hi<<2)+(lo>>MULSHIFTA); /* hi:lo/2**30 */ LONGMUL32HI(esthi, hop, MULMAGIC);/* shift will be 31 .. */ estlo=hop*MULMAGIC; /* .. so low word needed */ estlo=(esthi<<1)+(estlo>>MULSHIFTB); /* [just the top bit] */ /* esthi=0; // high word is ignored below */ lo-=(estlo*MULTBASE); /* as above */ /* the correction here could be +1 or +2 */ if (lo>=MULTBASE) { lo-=MULTBASE; estlo++; } if (lo>=MULTBASE) { lo-=MULTBASE; estlo++; } #else #error Unexpected type #endif /* finally place lo as the new accumulator digit and add est to */ /* the next place up; this latter add could cause a carry of 1 */ /* to the high word of the next place */ *pa=lo; *(pa+1)+=estlo; /* esthi is always 0 for DOUBLE and QUAD so this is skipped */ /* *(pa+1+MULACCLEN)+=esthi; */ if (*(pa+1)<estlo) *(pa+1+MULACCLEN)+=1; /* carry */ if (pa==acc+MULACCLEN-2) break; /* [MULACCLEN-1 will never need split] */ } /* pa loop */ #endif /* At this point, whether using the 64-bit or the 32-bit paths, the */ /* accumulator now holds the (unrounded) result in base-billion; */ /* one base-billion 'digit' per uInt. */ #if DECTRACE printf("MultAcc:"); for (pa=acc+MULACCLEN-1; pa>=acc; pa--) printf(" %09ld", (LI)*pa); printf("\n"); #endif /* Now convert to BCD for rounding and cleanup, starting from the */ /* most significant end */ pa=acc+MULACCLEN-1; if (*pa!=0) num->msd=bcdacc+LEADZEROS;/* drop known lead zeros */ else { /* >=1 word of leading zeros */ num->msd=bcdacc; /* known leading zeros are gone */ pa--; /* skip first word .. */ for (; *pa==0; pa--) if (pa==acc) break; /* .. and any more leading 0s */ } for (ub=bcdacc;; pa--, ub+=9) { if (*pa!=0) { /* split(s) needed */ uInt top, mid, rem; /* work */ /* *pa is non-zero -- split the base-billion acc digit into */ /* hi, mid, and low three-digits */ #define mulsplit9 1000000 /* divisor */ #define mulsplit6 1000 /* divisor */ /* The splitting is done by simple divides and remainders, */ /* assuming the compiler will optimize these where useful */ /* [GCC does] */ top=*pa/mulsplit9; rem=*pa%mulsplit9; mid=rem/mulsplit6; rem=rem%mulsplit6; /* lay out the nine BCD digits (plus one unwanted byte) */ UBFROMUI(ub, UBTOUI(&BIN2BCD8[top*4])); UBFROMUI(ub+3, UBTOUI(&BIN2BCD8[mid*4])); UBFROMUI(ub+6, UBTOUI(&BIN2BCD8[rem*4])); } else { /* *pa==0 */ UBFROMUI(ub, 0); /* clear 9 BCD8s */ UBFROMUI(ub+4, 0); /* .. */ *(ub+8)=0; /* .. */ } if (pa==acc) break; } /* BCD conversion loop */ num->lsd=ub+8; /* complete the bcdnum .. */ #if DECTRACE decShowNum(num, "postmult"); decFloatShow(dfl, "dfl"); decFloatShow(dfr, "dfr"); #endif return; } /* decFiniteMultiply */ /* ------------------------------------------------------------------ */ /* decFloatAbs -- absolute value, heeding NaNs, etc. */ /* */ /* result gets the canonicalized df with sign 0 */ /* df is the decFloat to abs */ /* set is the context */ /* returns result */ /* */ /* This has the same effect as decFloatPlus unless df is negative, */ /* in which case it has the same effect as decFloatMinus. The */ /* effect is also the same as decFloatCopyAbs except that NaNs are */ /* handled normally (the sign of a NaN is not affected, and an sNaN */ /* will signal) and the result will be canonical. */ /* ------------------------------------------------------------------ */ decFloat * decFloatAbs(decFloat *result, const decFloat *df, decContext *set) { if (DFISNAN(df)) return decNaNs(result, df, NULL, set); decCanonical(result, df); /* copy and check */ DFBYTE(result, 0)&=~0x80; /* zero sign bit */ return result; } /* decFloatAbs */ /* ------------------------------------------------------------------ */ /* decFloatAdd -- add two decFloats */ /* */ /* result gets the result of adding dfl and dfr: */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* ------------------------------------------------------------------ */ #if QUAD /* Table for testing MSDs for fastpath elimination; returns the MSD of */ /* a decDouble or decQuad (top 6 bits tested) ignoring the sign. */ /* Infinities return -32 and NaNs return -128 so that summing the two */ /* MSDs also allows rapid tests for the Specials (see code below). */ const Int DECTESTMSD[64]={ 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, -32, -128, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, -32, -128}; #else /* The table for testing MSDs is shared between the modules */ extern const Int DECTESTMSD[64]; #endif decFloat * decFloatAdd(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { bcdnum num; /* for final conversion */ Int bexpl, bexpr; /* left and right biased exponents */ uByte *ub, *us, *ut; /* work */ uInt uiwork; /* for macros */ #if QUAD uShort uswork; /* .. */ #endif uInt sourhil, sourhir; /* top words from source decFloats */ /* [valid only through end of */ /* fastpath code -- before swap] */ uInt diffsign; /* non-zero if signs differ */ uInt carry; /* carry: 0 or 1 before add loop */ Int overlap; /* coefficient overlap (if full) */ Int summ; /* sum of the MSDs */ /* the following buffers hold coefficients with various alignments */ /* (see commentary and diagrams below) */ uByte acc[4+2+DECPMAX*3+8]; uByte buf[4+2+DECPMAX*2]; uByte *umsd, *ulsd; /* local MSD and LSD pointers */ #if DECLITEND #define CARRYPAT 0x01000000 /* carry=1 pattern */ #else #define CARRYPAT 0x00000001 /* carry=1 pattern */ #endif /* Start decoding the arguments */ /* The initial exponents are placed into the opposite Ints to */ /* that which might be expected; there are two sets of data to */ /* keep track of (each decFloat and the corresponding exponent), */ /* and this scheme means that at the swap point (after comparing */ /* exponents) only one pair of words needs to be swapped */ /* whichever path is taken (thereby minimising worst-case path). */ /* The calculated exponents will be nonsense when the arguments are */ /* Special, but are not used in that path */ sourhil=DFWORD(dfl, 0); /* LHS top word */ summ=DECTESTMSD[sourhil>>26]; /* get first MSD for testing */ bexpr=DECCOMBEXP[sourhil>>26]; /* get exponent high bits (in place) */ bexpr+=GETECON(dfl); /* .. + continuation */ sourhir=DFWORD(dfr, 0); /* RHS top word */ summ+=DECTESTMSD[sourhir>>26]; /* sum MSDs for testing */ bexpl=DECCOMBEXP[sourhir>>26]; bexpl+=GETECON(dfr); /* here bexpr has biased exponent from lhs, and vice versa */ diffsign=(sourhil^sourhir)&DECFLOAT_Sign; /* now determine whether to take a fast path or the full-function */ /* slow path. The slow path must be taken when: */ /* -- both numbers are finite, and: */ /* the exponents are different, or */ /* the signs are different, or */ /* the sum of the MSDs is >8 (hence might overflow) */ /* specialness and the sum of the MSDs can be tested at once using */ /* the summ value just calculated, so the test for specials is no */ /* longer on the worst-case path (as of 3.60) */ if (summ<=8) { /* MSD+MSD is good, or there is a special */ if (summ<0) { /* there is a special */ /* Inf+Inf would give -64; Inf+finite is -32 or higher */ if (summ<-64) return decNaNs(result, dfl, dfr, set); /* one or two NaNs */ /* two infinities with different signs is invalid */ if (summ==-64 && diffsign) return decInvalid(result, set); if (DFISINF(dfl)) return decInfinity(result, dfl); /* LHS is infinite */ return decInfinity(result, dfr); /* RHS must be Inf */ } /* Here when both arguments are finite; fast path is possible */ /* (currently only for aligned and same-sign) */ if (bexpr==bexpl && !diffsign) { uInt tac[DECLETS+1]; /* base-1000 coefficient */ uInt encode; /* work */ /* Get one coefficient as base-1000 and add the other */ GETCOEFFTHOU(dfl, tac); /* least-significant goes to [0] */ ADDCOEFFTHOU(dfr, tac); /* here the sum of the MSDs (plus any carry) will be <10 due to */ /* the fastpath test earlier */ /* construct the result; low word is the same for both formats */ encode =BIN2DPD[tac[0]]; encode|=BIN2DPD[tac[1]]<<10; encode|=BIN2DPD[tac[2]]<<20; encode|=BIN2DPD[tac[3]]<<30; DFWORD(result, (DECBYTES/4)-1)=encode; /* collect next two declets (all that remains, for Double) */ encode =BIN2DPD[tac[3]]>>2; encode|=BIN2DPD[tac[4]]<<8; #if QUAD /* complete and lay out middling words */ encode|=BIN2DPD[tac[5]]<<18; encode|=BIN2DPD[tac[6]]<<28; DFWORD(result, 2)=encode; encode =BIN2DPD[tac[6]]>>4; encode|=BIN2DPD[tac[7]]<<6; encode|=BIN2DPD[tac[8]]<<16; encode|=BIN2DPD[tac[9]]<<26; DFWORD(result, 1)=encode; /* and final two declets */ encode =BIN2DPD[tac[9]]>>6; encode|=BIN2DPD[tac[10]]<<4; #endif /* add exponent continuation and sign (from either argument) */ encode|=sourhil & (ECONMASK | DECFLOAT_Sign); /* create lookup index = MSD + top two bits of biased exponent <<4 */ tac[DECLETS]|=(bexpl>>DECECONL)<<4; encode|=DECCOMBFROM[tac[DECLETS]]; /* add constructed combination field */ DFWORD(result, 0)=encode; /* complete */ /* decFloatShow(result, ">"); */ return result; } /* fast path OK */ /* drop through to slow path */ } /* low sum or Special(s) */ /* Slow path required -- arguments are finite and might overflow, */ /* or require alignment, or might have different signs */ /* now swap either exponents or argument pointers */ if (bexpl<=bexpr) { /* original left is bigger */ Int bexpswap=bexpl; bexpl=bexpr; bexpr=bexpswap; /* printf("left bigger\n"); */ } else { const decFloat *dfswap=dfl; dfl=dfr; dfr=dfswap; /* printf("right bigger\n"); */ } /* [here dfl and bexpl refer to the datum with the larger exponent, */ /* of if the exponents are equal then the original LHS argument] */ /* if lhs is zero then result will be the rhs (now known to have */ /* the smaller exponent), which also may need to be tested for zero */ /* for the weird IEEE 754 sign rules */ if (DFISZERO(dfl)) { decCanonical(result, dfr); /* clean copy */ /* "When the sum of two operands with opposite signs is */ /* exactly zero, the sign of that sum shall be '+' in all */ /* rounding modes except round toward -Infinity, in which */ /* mode that sign shall be '-'." */ if (diffsign && DFISZERO(result)) { DFWORD(result, 0)&=~DECFLOAT_Sign; /* assume sign 0 */ if (set->round==DEC_ROUND_FLOOR) DFWORD(result, 0)|=DECFLOAT_Sign; } return result; } /* numfl is zero */ /* [here, LHS is non-zero; code below assumes that] */ /* Coefficients layout during the calculations to follow: */ /* */ /* Overlap case: */ /* +------------------------------------------------+ */ /* acc: |0000| coeffa | tail B | | */ /* +------------------------------------------------+ */ /* buf: |0000| pad0s | coeffb | | */ /* +------------------------------------------------+ */ /* */ /* Touching coefficients or gap: */ /* +------------------------------------------------+ */ /* acc: |0000| coeffa | gap | coeffb | */ /* +------------------------------------------------+ */ /* [buf not used or needed; gap clamped to Pmax] */ /* lay out lhs coefficient into accumulator; this starts at acc+4 */ /* for decDouble or acc+6 for decQuad so the LSD is word- */ /* aligned; the top word gap is there only in case a carry digit */ /* is prefixed after the add -- it does not need to be zeroed */ #if DOUBLE #define COFF 4 /* offset into acc */ #elif QUAD UBFROMUS(acc+4, 0); /* prefix 00 */ #define COFF 6 /* offset into acc */ #endif GETCOEFF(dfl, acc+COFF); /* decode from decFloat */ ulsd=acc+COFF+DECPMAX-1; umsd=acc+4; /* [having this here avoids */ #if DECTRACE {bcdnum tum; tum.msd=umsd; tum.lsd=ulsd; tum.exponent=bexpl-DECBIAS; tum.sign=DFWORD(dfl, 0) & DECFLOAT_Sign; decShowNum(&tum, "dflx");} #endif /* if signs differ, take ten's complement of lhs (here the */ /* coefficient is subtracted from all-nines; the 1 is added during */ /* the later add cycle -- zeros to the right do not matter because */ /* the complement of zero is zero); these are fixed-length inverts */ /* where the lsd is known to be at a 4-byte boundary (so no borrow */ /* possible) */ carry=0; /* assume no carry */ if (diffsign) { carry=CARRYPAT; /* for +1 during add */ UBFROMUI(acc+ 4, 0x09090909-UBTOUI(acc+ 4)); UBFROMUI(acc+ 8, 0x09090909-UBTOUI(acc+ 8)); UBFROMUI(acc+12, 0x09090909-UBTOUI(acc+12)); UBFROMUI(acc+16, 0x09090909-UBTOUI(acc+16)); #if QUAD UBFROMUI(acc+20, 0x09090909-UBTOUI(acc+20)); UBFROMUI(acc+24, 0x09090909-UBTOUI(acc+24)); UBFROMUI(acc+28, 0x09090909-UBTOUI(acc+28)); UBFROMUI(acc+32, 0x09090909-UBTOUI(acc+32)); UBFROMUI(acc+36, 0x09090909-UBTOUI(acc+36)); #endif } /* diffsign */ /* now process the rhs coefficient; if it cannot overlap lhs then */ /* it can be put straight into acc (with an appropriate gap, if */ /* needed) because no actual addition will be needed (except */ /* possibly to complete ten's complement) */ overlap=DECPMAX-(bexpl-bexpr); #if DECTRACE printf("exps: %ld %ld\n", (LI)(bexpl-DECBIAS), (LI)(bexpr-DECBIAS)); printf("Overlap=%ld carry=%08lx\n", (LI)overlap, (LI)carry); #endif if (overlap<=0) { /* no overlap possible */ uInt gap; /* local work */ /* since a full addition is not needed, a ten's complement */ /* calculation started above may need to be completed */ if (carry) { for (ub=ulsd; *ub==9; ub--) *ub=0; *ub+=1; carry=0; /* taken care of */ } /* up to DECPMAX-1 digits of the final result can extend down */ /* below the LSD of the lhs, so if the gap is >DECPMAX then the */ /* rhs will be simply sticky bits. In this case the gap is */ /* clamped to DECPMAX and the exponent adjusted to suit [this is */ /* safe because the lhs is non-zero]. */ gap=-overlap; if (gap>DECPMAX) { bexpr+=gap-1; gap=DECPMAX; } ub=ulsd+gap+1; /* where MSD will go */ /* Fill the gap with 0s; note that there is no addition to do */ ut=acc+COFF+DECPMAX; /* start of gap */ for (; ut<ub; ut+=4) UBFROMUI(ut, 0); /* mind the gap */ if (overlap<-DECPMAX) { /* gap was > DECPMAX */ *ub=(uByte)(!DFISZERO(dfr)); /* make sticky digit */ } else { /* need full coefficient */ GETCOEFF(dfr, ub); /* decode from decFloat */ ub+=DECPMAX-1; /* new LSD... */ } ulsd=ub; /* save new LSD */ } /* no overlap possible */ else { /* overlap>0 */ /* coefficients overlap (perhaps completely, although also */ /* perhaps only where zeros) */ if (overlap==DECPMAX) { /* aligned */ ub=buf+COFF; /* where msd will go */ #if QUAD UBFROMUS(buf+4, 0); /* clear quad's 00 */ #endif GETCOEFF(dfr, ub); /* decode from decFloat */ } else { /* unaligned */ ub=buf+COFF+DECPMAX-overlap; /* where MSD will go */ /* Fill the prefix gap with 0s; 8 will cover most common */ /* unalignments, so start with direct assignments (a loop is */ /* then used for any remaining -- the loop (and the one in a */ /* moment) is not then on the critical path because the number */ /* of additions is reduced by (at least) two in this case) */ UBFROMUI(buf+4, 0); /* [clears decQuad 00 too] */ UBFROMUI(buf+8, 0); if (ub>buf+12) { ut=buf+12; /* start any remaining */ for (; ut<ub; ut+=4) UBFROMUI(ut, 0); /* fill them */ } GETCOEFF(dfr, ub); /* decode from decFloat */ /* now move tail of rhs across to main acc; again use direct */ /* copies for 8 digits-worth */ UBFROMUI(acc+COFF+DECPMAX, UBTOUI(buf+COFF+DECPMAX)); UBFROMUI(acc+COFF+DECPMAX+4, UBTOUI(buf+COFF+DECPMAX+4)); if (buf+COFF+DECPMAX+8<ub+DECPMAX) { us=buf+COFF+DECPMAX+8; /* source */ ut=acc+COFF+DECPMAX+8; /* target */ for (; us<ub+DECPMAX; us+=4, ut+=4) UBFROMUI(ut, UBTOUI(us)); } } /* unaligned */ ulsd=acc+(ub-buf+DECPMAX-1); /* update LSD pointer */ /* Now do the add of the non-tail; this is all nicely aligned, */ /* and is over a multiple of four digits (because for Quad two */ /* zero digits were added on the left); words in both acc and */ /* buf (buf especially) will often be zero */ /* [byte-by-byte add, here, is about 15% slower total effect than */ /* the by-fours] */ /* Now effect the add; this is harder on a little-endian */ /* machine as the inter-digit carry cannot use the usual BCD */ /* addition trick because the bytes are loaded in the wrong order */ /* [this loop could be unrolled, but probably scarcely worth it] */ ut=acc+COFF+DECPMAX-4; /* target LSW (acc) */ us=buf+COFF+DECPMAX-4; /* source LSW (buf, to add to acc) */ #if !DECLITEND for (; ut>=acc+4; ut-=4, us-=4) { /* big-endian add loop */ /* bcd8 add */ carry+=UBTOUI(us); /* rhs + carry */ if (carry==0) continue; /* no-op */ carry+=UBTOUI(ut); /* lhs */ /* Big-endian BCD adjust (uses internal carry) */ carry+=0x76f6f6f6; /* note top nibble not all bits */ /* apply BCD adjust and save */ UBFROMUI(ut, (carry & 0x0f0f0f0f) - ((carry & 0x60606060)>>4)); carry>>=31; /* true carry was at far left */ } /* add loop */ #else for (; ut>=acc+4; ut-=4, us-=4) { /* little-endian add loop */ /* bcd8 add */ carry+=UBTOUI(us); /* rhs + carry */ if (carry==0) continue; /* no-op [common if unaligned] */ carry+=UBTOUI(ut); /* lhs */ /* Little-endian BCD adjust; inter-digit carry must be manual */ /* because the lsb from the array will be in the most-significant */ /* byte of carry */ carry+=0x76767676; /* note no inter-byte carries */ carry+=(carry & 0x80000000)>>15; carry+=(carry & 0x00800000)>>15; carry+=(carry & 0x00008000)>>15; carry-=(carry & 0x60606060)>>4; /* BCD adjust back */ UBFROMUI(ut, carry & 0x0f0f0f0f); /* clear debris and save */ /* here, final carry-out bit is at 0x00000080; move it ready */ /* for next word-add (i.e., to 0x01000000) */ carry=(carry & 0x00000080)<<17; } /* add loop */ #endif #if DECTRACE {bcdnum tum; printf("Add done, carry=%08lx, diffsign=%ld\n", (LI)carry, (LI)diffsign); tum.msd=umsd; /* acc+4; */ tum.lsd=ulsd; tum.exponent=0; tum.sign=0; decShowNum(&tum, "dfadd");} #endif } /* overlap possible */ /* ordering here is a little strange in order to have slowest path */ /* first in GCC asm listing */ if (diffsign) { /* subtraction */ if (!carry) { /* no carry out means RHS<LHS */ /* borrowed -- take ten's complement */ /* sign is lhs sign */ num.sign=DFWORD(dfl, 0) & DECFLOAT_Sign; /* invert the coefficient first by fours, then add one; space */ /* at the end of the buffer ensures the by-fours is always */ /* safe, but lsd+1 must be cleared to prevent a borrow */ /* if big-endian */ #if !DECLITEND *(ulsd+1)=0; #endif /* there are always at least four coefficient words */ UBFROMUI(umsd, 0x09090909-UBTOUI(umsd)); UBFROMUI(umsd+4, 0x09090909-UBTOUI(umsd+4)); UBFROMUI(umsd+8, 0x09090909-UBTOUI(umsd+8)); UBFROMUI(umsd+12, 0x09090909-UBTOUI(umsd+12)); #if DOUBLE #define BNEXT 16 #elif QUAD UBFROMUI(umsd+16, 0x09090909-UBTOUI(umsd+16)); UBFROMUI(umsd+20, 0x09090909-UBTOUI(umsd+20)); UBFROMUI(umsd+24, 0x09090909-UBTOUI(umsd+24)); UBFROMUI(umsd+28, 0x09090909-UBTOUI(umsd+28)); UBFROMUI(umsd+32, 0x09090909-UBTOUI(umsd+32)); #define BNEXT 36 #endif if (ulsd>=umsd+BNEXT) { /* unaligned */ /* eight will handle most unaligments for Double; 16 for Quad */ UBFROMUI(umsd+BNEXT, 0x09090909-UBTOUI(umsd+BNEXT)); UBFROMUI(umsd+BNEXT+4, 0x09090909-UBTOUI(umsd+BNEXT+4)); #if DOUBLE #define BNEXTY (BNEXT+8) #elif QUAD UBFROMUI(umsd+BNEXT+8, 0x09090909-UBTOUI(umsd+BNEXT+8)); UBFROMUI(umsd+BNEXT+12, 0x09090909-UBTOUI(umsd+BNEXT+12)); #define BNEXTY (BNEXT+16) #endif if (ulsd>=umsd+BNEXTY) { /* very unaligned */ ut=umsd+BNEXTY; /* -> continue */ for (;;ut+=4) { UBFROMUI(ut, 0x09090909-UBTOUI(ut)); /* invert four digits */ if (ut>=ulsd-3) break; /* all done */ } } } /* complete the ten's complement by adding 1 */ for (ub=ulsd; *ub==9; ub--) *ub=0; *ub+=1; } /* borrowed */ else { /* carry out means RHS>=LHS */ num.sign=DFWORD(dfr, 0) & DECFLOAT_Sign; /* all done except for the special IEEE 754 exact-zero-result */ /* rule (see above); while testing for zero, strip leading */ /* zeros (which will save decFinalize doing it) (this is in */ /* diffsign path, so carry impossible and true umsd is */ /* acc+COFF) */ /* Check the initial coefficient area using the fast macro; */ /* this will often be all that needs to be done (as on the */ /* worst-case path when the subtraction was aligned and */ /* full-length) */ if (ISCOEFFZERO(acc+COFF)) { umsd=acc+COFF+DECPMAX-1; /* so far, so zero */ if (ulsd>umsd) { /* more to check */ umsd++; /* to align after checked area */ for (; UBTOUI(umsd)==0 && umsd+3<ulsd;) umsd+=4; for (; *umsd==0 && umsd<ulsd;) umsd++; } if (*umsd==0) { /* must be true zero (and diffsign) */ num.sign=0; /* assume + */ if (set->round==DEC_ROUND_FLOOR) num.sign=DECFLOAT_Sign; } } /* [else was not zero, might still have leading zeros] */ } /* subtraction gave positive result */ } /* diffsign */ else { /* same-sign addition */ num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign; #if DOUBLE if (carry) { /* only possible with decDouble */ *(acc+3)=1; /* [Quad has leading 00] */ umsd=acc+3; } #endif } /* same sign */ num.msd=umsd; /* set MSD .. */ num.lsd=ulsd; /* .. and LSD */ num.exponent=bexpr-DECBIAS; /* set exponent to smaller, unbiassed */ #if DECTRACE decFloatShow(dfl, "dfl"); decFloatShow(dfr, "dfr"); decShowNum(&num, "postadd"); #endif return decFinalize(result, &num, set); /* round, check, and lay out */ } /* decFloatAdd */ /* ------------------------------------------------------------------ */ /* decFloatAnd -- logical digitwise AND of two decFloats */ /* */ /* result gets the result of ANDing dfl and dfr */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result, which will be canonical with sign=0 */ /* */ /* The operands must be positive, finite with exponent q=0, and */ /* comprise just zeros and ones; if not, Invalid operation results. */ /* ------------------------------------------------------------------ */ decFloat * decFloatAnd(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { if (!DFISUINT01(dfl) || !DFISUINT01(dfr) || !DFISCC01(dfl) || !DFISCC01(dfr)) return decInvalid(result, set); /* the operands are positive finite integers (q=0) with just 0s and 1s */ #if DOUBLE DFWORD(result, 0)=ZEROWORD |((DFWORD(dfl, 0) & DFWORD(dfr, 0))&0x04009124); DFWORD(result, 1)=(DFWORD(dfl, 1) & DFWORD(dfr, 1))&0x49124491; #elif QUAD DFWORD(result, 0)=ZEROWORD |((DFWORD(dfl, 0) & DFWORD(dfr, 0))&0x04000912); DFWORD(result, 1)=(DFWORD(dfl, 1) & DFWORD(dfr, 1))&0x44912449; DFWORD(result, 2)=(DFWORD(dfl, 2) & DFWORD(dfr, 2))&0x12449124; DFWORD(result, 3)=(DFWORD(dfl, 3) & DFWORD(dfr, 3))&0x49124491; #endif return result; } /* decFloatAnd */ /* ------------------------------------------------------------------ */ /* decFloatCanonical -- copy a decFloat, making canonical */ /* */ /* result gets the canonicalized df */ /* df is the decFloat to copy and make canonical */ /* returns result */ /* */ /* This works on specials, too; no error or exception is possible. */ /* ------------------------------------------------------------------ */ decFloat * decFloatCanonical(decFloat *result, const decFloat *df) { return decCanonical(result, df); } /* decFloatCanonical */ /* ------------------------------------------------------------------ */ /* decFloatClass -- return the class of a decFloat */ /* */ /* df is the decFloat to test */ /* returns the decClass that df falls into */ /* ------------------------------------------------------------------ */ enum decClass decFloatClass(const decFloat *df) { Int exp; /* exponent */ if (DFISSPECIAL(df)) { if (DFISQNAN(df)) return DEC_CLASS_QNAN; if (DFISSNAN(df)) return DEC_CLASS_SNAN; /* must be an infinity */ if (DFISSIGNED(df)) return DEC_CLASS_NEG_INF; return DEC_CLASS_POS_INF; } if (DFISZERO(df)) { /* quite common */ if (DFISSIGNED(df)) return DEC_CLASS_NEG_ZERO; return DEC_CLASS_POS_ZERO; } /* is finite and non-zero; similar code to decFloatIsNormal, here */ /* [this could be speeded up slightly by in-lining decFloatDigits] */ exp=GETEXPUN(df) /* get unbiased exponent .. */ +decFloatDigits(df)-1; /* .. and make adjusted exponent */ if (exp>=DECEMIN) { /* is normal */ if (DFISSIGNED(df)) return DEC_CLASS_NEG_NORMAL; return DEC_CLASS_POS_NORMAL; } /* is subnormal */ if (DFISSIGNED(df)) return DEC_CLASS_NEG_SUBNORMAL; return DEC_CLASS_POS_SUBNORMAL; } /* decFloatClass */ /* ------------------------------------------------------------------ */ /* decFloatClassString -- return the class of a decFloat as a string */ /* */ /* df is the decFloat to test */ /* returns a constant string describing the class df falls into */ /* ------------------------------------------------------------------ */ const char *decFloatClassString(const decFloat *df) { enum decClass eclass=decFloatClass(df); if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN; if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN; if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ; if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ; if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS; if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS; if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI; if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI; if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN; if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN; return DEC_ClassString_UN; /* Unknown */ } /* decFloatClassString */ /* ------------------------------------------------------------------ */ /* decFloatCompare -- compare two decFloats; quiet NaNs allowed */ /* */ /* result gets the result of comparing dfl and dfr */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result, which may be -1, 0, 1, or NaN (Unordered) */ /* ------------------------------------------------------------------ */ decFloat * decFloatCompare(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { Int comp; /* work */ /* NaNs are handled as usual */ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set); /* numeric comparison needed */ comp=decNumCompare(dfl, dfr, 0); decFloatZero(result); if (comp==0) return result; DFBYTE(result, DECBYTES-1)=0x01; /* LSD=1 */ if (comp<0) DFBYTE(result, 0)|=0x80; /* set sign bit */ return result; } /* decFloatCompare */ /* ------------------------------------------------------------------ */ /* decFloatCompareSignal -- compare two decFloats; all NaNs signal */ /* */ /* result gets the result of comparing dfl and dfr */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result, which may be -1, 0, 1, or NaN (Unordered) */ /* ------------------------------------------------------------------ */ decFloat * decFloatCompareSignal(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { Int comp; /* work */ /* NaNs are handled as usual, except that all NaNs signal */ if (DFISNAN(dfl) || DFISNAN(dfr)) { set->status|=DEC_Invalid_operation; return decNaNs(result, dfl, dfr, set); } /* numeric comparison needed */ comp=decNumCompare(dfl, dfr, 0); decFloatZero(result); if (comp==0) return result; DFBYTE(result, DECBYTES-1)=0x01; /* LSD=1 */ if (comp<0) DFBYTE(result, 0)|=0x80; /* set sign bit */ return result; } /* decFloatCompareSignal */ /* ------------------------------------------------------------------ */ /* decFloatCompareTotal -- compare two decFloats with total ordering */ /* */ /* result gets the result of comparing dfl and dfr */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* returns result, which may be -1, 0, or 1 */ /* ------------------------------------------------------------------ */ decFloat * decFloatCompareTotal(decFloat *result, const decFloat *dfl, const decFloat *dfr) { Int comp; /* work */ uInt uiwork; /* for macros */ #if QUAD uShort uswork; /* .. */ #endif if (DFISNAN(dfl) || DFISNAN(dfr)) { Int nanl, nanr; /* work */ /* morph NaNs to +/- 1 or 2, leave numbers as 0 */ nanl=DFISSNAN(dfl)+DFISQNAN(dfl)*2; /* quiet > signalling */ if (DFISSIGNED(dfl)) nanl=-nanl; nanr=DFISSNAN(dfr)+DFISQNAN(dfr)*2; if (DFISSIGNED(dfr)) nanr=-nanr; if (nanl>nanr) comp=+1; else if (nanl<nanr) comp=-1; else { /* NaNs are the same type and sign .. must compare payload */ /* buffers need +2 for QUAD */ uByte bufl[DECPMAX+4]; /* for LHS coefficient + foot */ uByte bufr[DECPMAX+4]; /* for RHS coefficient + foot */ uByte *ub, *uc; /* work */ Int sigl; /* signum of LHS */ sigl=(DFISSIGNED(dfl) ? -1 : +1); /* decode the coefficients */ /* (shift both right two if Quad to make a multiple of four) */ #if QUAD UBFROMUS(bufl, 0); UBFROMUS(bufr, 0); #endif GETCOEFF(dfl, bufl+QUAD*2); /* decode from decFloat */ GETCOEFF(dfr, bufr+QUAD*2); /* .. */ /* all multiples of four, here */ comp=0; /* assume equal */ for (ub=bufl, uc=bufr; ub<bufl+DECPMAX+QUAD*2; ub+=4, uc+=4) { uInt ui=UBTOUI(ub); if (ui==UBTOUI(uc)) continue; /* so far so same */ /* about to find a winner; go by bytes in case little-endian */ for (;; ub++, uc++) { if (*ub==*uc) continue; if (*ub>*uc) comp=sigl; /* difference found */ else comp=-sigl; /* .. */ break; } } } /* same NaN type and sign */ } else { /* numeric comparison needed */ comp=decNumCompare(dfl, dfr, 1); /* total ordering */ } decFloatZero(result); if (comp==0) return result; DFBYTE(result, DECBYTES-1)=0x01; /* LSD=1 */ if (comp<0) DFBYTE(result, 0)|=0x80; /* set sign bit */ return result; } /* decFloatCompareTotal */ /* ------------------------------------------------------------------ */ /* decFloatCompareTotalMag -- compare magnitudes with total ordering */ /* */ /* result gets the result of comparing abs(dfl) and abs(dfr) */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* returns result, which may be -1, 0, or 1 */ /* ------------------------------------------------------------------ */ decFloat * decFloatCompareTotalMag(decFloat *result, const decFloat *dfl, const decFloat *dfr) { decFloat a, b; /* for copy if needed */ /* copy and redirect signed operand(s) */ if (DFISSIGNED(dfl)) { decFloatCopyAbs(&a, dfl); dfl=&a; } if (DFISSIGNED(dfr)) { decFloatCopyAbs(&b, dfr); dfr=&b; } return decFloatCompareTotal(result, dfl, dfr); } /* decFloatCompareTotalMag */ /* ------------------------------------------------------------------ */ /* decFloatCopy -- copy a decFloat as-is */ /* */ /* result gets the copy of dfl */ /* dfl is the decFloat to copy */ /* returns result */ /* */ /* This is a bitwise operation; no errors or exceptions are possible. */ /* ------------------------------------------------------------------ */ decFloat * decFloatCopy(decFloat *result, const decFloat *dfl) { if (dfl!=result) *result=*dfl; /* copy needed */ return result; } /* decFloatCopy */ /* ------------------------------------------------------------------ */ /* decFloatCopyAbs -- copy a decFloat as-is and set sign bit to 0 */ /* */ /* result gets the copy of dfl with sign bit 0 */ /* dfl is the decFloat to copy */ /* returns result */ /* */ /* This is a bitwise operation; no errors or exceptions are possible. */ /* ------------------------------------------------------------------ */ decFloat * decFloatCopyAbs(decFloat *result, const decFloat *dfl) { if (dfl!=result) *result=*dfl; /* copy needed */ DFBYTE(result, 0)&=~0x80; /* zero sign bit */ return result; } /* decFloatCopyAbs */ /* ------------------------------------------------------------------ */ /* decFloatCopyNegate -- copy a decFloat as-is with inverted sign bit */ /* */ /* result gets the copy of dfl with sign bit inverted */ /* dfl is the decFloat to copy */ /* returns result */ /* */ /* This is a bitwise operation; no errors or exceptions are possible. */ /* ------------------------------------------------------------------ */ decFloat * decFloatCopyNegate(decFloat *result, const decFloat *dfl) { if (dfl!=result) *result=*dfl; /* copy needed */ DFBYTE(result, 0)^=0x80; /* invert sign bit */ return result; } /* decFloatCopyNegate */ /* ------------------------------------------------------------------ */ /* decFloatCopySign -- copy a decFloat with the sign of another */ /* */ /* result gets the result of copying dfl with the sign of dfr */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* returns result */ /* */ /* This is a bitwise operation; no errors or exceptions are possible. */ /* ------------------------------------------------------------------ */ decFloat * decFloatCopySign(decFloat *result, const decFloat *dfl, const decFloat *dfr) { uByte sign=(uByte)(DFBYTE(dfr, 0)&0x80); /* save sign bit */ if (dfl!=result) *result=*dfl; /* copy needed */ DFBYTE(result, 0)&=~0x80; /* clear sign .. */ DFBYTE(result, 0)=(uByte)(DFBYTE(result, 0)|sign); /* .. and set saved */ return result; } /* decFloatCopySign */ /* ------------------------------------------------------------------ */ /* decFloatDigits -- return the number of digits in a decFloat */ /* */ /* df is the decFloat to investigate */ /* returns the number of significant digits in the decFloat; a */ /* zero coefficient returns 1 as does an infinity (a NaN returns */ /* the number of digits in the payload) */ /* ------------------------------------------------------------------ */ /* private macro to extract a declet according to provided formula */ /* (form), and if it is non-zero then return the calculated digits */ /* depending on the declet number (n), where n=0 for the most */ /* significant declet; uses uInt dpd for work */ #define dpdlenchk(n, form) {dpd=(form)&0x3ff; \ if (dpd) return (DECPMAX-1-3*(n))-(3-DPD2BCD8[dpd*4+3]);} /* next one is used when it is known that the declet must be */ /* non-zero, or is the final zero declet */ #define dpdlendun(n, form) {dpd=(form)&0x3ff; \ if (dpd==0) return 1; \ return (DECPMAX-1-3*(n))-(3-DPD2BCD8[dpd*4+3]);} uInt decFloatDigits(const decFloat *df) { uInt dpd; /* work */ uInt sourhi=DFWORD(df, 0); /* top word from source decFloat */ #if QUAD uInt sourmh, sourml; #endif uInt sourlo; if (DFISINF(df)) return 1; /* A NaN effectively has an MSD of 0; otherwise if non-zero MSD */ /* then the coefficient is full-length */ if (!DFISNAN(df) && DECCOMBMSD[sourhi>>26]) return DECPMAX; #if DOUBLE if (sourhi&0x0003ffff) { /* ends in first */ dpdlenchk(0, sourhi>>8); sourlo=DFWORD(df, 1); dpdlendun(1, (sourhi<<2) | (sourlo>>30)); } /* [cannot drop through] */ sourlo=DFWORD(df, 1); /* sourhi not involved now */ if (sourlo&0xfff00000) { /* in one of first two */ dpdlenchk(1, sourlo>>30); /* very rare */ dpdlendun(2, sourlo>>20); } /* [cannot drop through] */ dpdlenchk(3, sourlo>>10); dpdlendun(4, sourlo); /* [cannot drop through] */ #elif QUAD if (sourhi&0x00003fff) { /* ends in first */ dpdlenchk(0, sourhi>>4); sourmh=DFWORD(df, 1); dpdlendun(1, ((sourhi)<<6) | (sourmh>>26)); } /* [cannot drop through] */ sourmh=DFWORD(df, 1); if (sourmh) { dpdlenchk(1, sourmh>>26); dpdlenchk(2, sourmh>>16); dpdlenchk(3, sourmh>>6); sourml=DFWORD(df, 2); dpdlendun(4, ((sourmh)<<4) | (sourml>>28)); } /* [cannot drop through] */ sourml=DFWORD(df, 2); if (sourml) { dpdlenchk(4, sourml>>28); dpdlenchk(5, sourml>>18); dpdlenchk(6, sourml>>8); sourlo=DFWORD(df, 3); dpdlendun(7, ((sourml)<<2) | (sourlo>>30)); } /* [cannot drop through] */ sourlo=DFWORD(df, 3); if (sourlo&0xfff00000) { /* in one of first two */ dpdlenchk(7, sourlo>>30); /* very rare */ dpdlendun(8, sourlo>>20); } /* [cannot drop through] */ dpdlenchk(9, sourlo>>10); dpdlendun(10, sourlo); /* [cannot drop through] */ #endif } /* decFloatDigits */ /* ------------------------------------------------------------------ */ /* decFloatDivide -- divide a decFloat by another */ /* */ /* result gets the result of dividing dfl by dfr: */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* ------------------------------------------------------------------ */ /* This is just a wrapper. */ decFloat * decFloatDivide(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { return decDivide(result, dfl, dfr, set, DIVIDE); } /* decFloatDivide */ /* ------------------------------------------------------------------ */ /* decFloatDivideInteger -- integer divide a decFloat by another */ /* */ /* result gets the result of dividing dfl by dfr: */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* ------------------------------------------------------------------ */ decFloat * decFloatDivideInteger(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { return decDivide(result, dfl, dfr, set, DIVIDEINT); } /* decFloatDivideInteger */ /* ------------------------------------------------------------------ */ /* decFloatFMA -- multiply and add three decFloats, fused */ /* */ /* result gets the result of (dfl*dfr)+dff with a single rounding */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* dff is the final decFloat (fhs) */ /* set is the context */ /* returns result */ /* */ /* ------------------------------------------------------------------ */ decFloat * decFloatFMA(decFloat *result, const decFloat *dfl, const decFloat *dfr, const decFloat *dff, decContext *set) { /* The accumulator has the bytes needed for FiniteMultiply, plus */ /* one byte to the left in case of carry, plus DECPMAX+2 to the */ /* right for the final addition (up to full fhs + round & sticky) */ #define FMALEN (ROUNDUP4(1+ (DECPMAX9*18+1) +DECPMAX+2)) uByte acc[FMALEN]; /* for multiplied coefficient in BCD */ /* .. and for final result */ bcdnum mul; /* for multiplication result */ bcdnum fin; /* for final operand, expanded */ uByte coe[ROUNDUP4(DECPMAX)]; /* dff coefficient in BCD */ bcdnum *hi, *lo; /* bcdnum with higher/lower exponent */ uInt diffsign; /* non-zero if signs differ */ uInt hipad; /* pad digit for hi if needed */ Int padding; /* excess exponent */ uInt carry; /* +1 for ten's complement and during add */ uByte *ub, *uh, *ul; /* work */ uInt uiwork; /* for macros */ /* handle all the special values [any special operand leads to a */ /* special result] */ if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr) || DFISSPECIAL(dff)) { decFloat proxy; /* multiplication result proxy */ /* NaNs are handled as usual, giving priority to sNaNs */ if (DFISSNAN(dfl) || DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set); if (DFISSNAN(dff)) return decNaNs(result, dff, NULL, set); if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set); if (DFISNAN(dff)) return decNaNs(result, dff, NULL, set); /* One or more of the three is infinite */ /* infinity times zero is bad */ decFloatZero(&proxy); if (DFISINF(dfl)) { if (DFISZERO(dfr)) return decInvalid(result, set); decInfinity(&proxy, &proxy); } else if (DFISINF(dfr)) { if (DFISZERO(dfl)) return decInvalid(result, set); decInfinity(&proxy, &proxy); } /* compute sign of multiplication and place in proxy */ DFWORD(&proxy, 0)|=(DFWORD(dfl, 0)^DFWORD(dfr, 0))&DECFLOAT_Sign; if (!DFISINF(dff)) return decFloatCopy(result, &proxy); /* dff is Infinite */ if (!DFISINF(&proxy)) return decInfinity(result, dff); /* both sides of addition are infinite; different sign is bad */ if ((DFWORD(dff, 0)&DECFLOAT_Sign)!=(DFWORD(&proxy, 0)&DECFLOAT_Sign)) return decInvalid(result, set); return decFloatCopy(result, &proxy); } /* Here when all operands are finite */ /* First multiply dfl*dfr */ decFiniteMultiply(&mul, acc+1, dfl, dfr); /* The multiply is complete, exact and unbounded, and described in */ /* mul with the coefficient held in acc[1...] */ /* now add in dff; the algorithm is essentially the same as */ /* decFloatAdd, but the code is different because the code there */ /* is highly optimized for adding two numbers of the same size */ fin.exponent=GETEXPUN(dff); /* get dff exponent and sign */ fin.sign=DFWORD(dff, 0)&DECFLOAT_Sign; diffsign=mul.sign^fin.sign; /* note if signs differ */ fin.msd=coe; fin.lsd=coe+DECPMAX-1; GETCOEFF(dff, coe); /* extract the coefficient */ /* now set hi and lo so that hi points to whichever of mul and fin */ /* has the higher exponent and lo points to the other [don't care, */ /* if the same]. One coefficient will be in acc, the other in coe. */ if (mul.exponent>=fin.exponent) { hi=&mul; lo=&fin; } else { hi=&fin; lo=&mul; } /* remove leading zeros on both operands; this will save time later */ /* and make testing for zero trivial (tests are safe because acc */ /* and coe are rounded up to uInts) */ for (; UBTOUI(hi->msd)==0 && hi->msd+3<hi->lsd;) hi->msd+=4; for (; *hi->msd==0 && hi->msd<hi->lsd;) hi->msd++; for (; UBTOUI(lo->msd)==0 && lo->msd+3<lo->lsd;) lo->msd+=4; for (; *lo->msd==0 && lo->msd<lo->lsd;) lo->msd++; /* if hi is zero then result will be lo (which has the smaller */ /* exponent), which also may need to be tested for zero for the */ /* weird IEEE 754 sign rules */ if (*hi->msd==0) { /* hi is zero */ /* "When the sum of two operands with opposite signs is */ /* exactly zero, the sign of that sum shall be '+' in all */ /* rounding modes except round toward -Infinity, in which */ /* mode that sign shall be '-'." */ if (diffsign) { if (*lo->msd==0) { /* lo is zero */ lo->sign=0; if (set->round==DEC_ROUND_FLOOR) lo->sign=DECFLOAT_Sign; } /* diffsign && lo=0 */ } /* diffsign */ return decFinalize(result, lo, set); /* may need clamping */ } /* numfl is zero */ /* [here, both are minimal length and hi is non-zero] */ /* (if lo is zero then padding with zeros may be needed, below) */ /* if signs differ, take the ten's complement of hi (zeros to the */ /* right do not matter because the complement of zero is zero); the */ /* +1 is done later, as part of the addition, inserted at the */ /* correct digit */ hipad=0; carry=0; if (diffsign) { hipad=9; carry=1; /* exactly the correct number of digits must be inverted */ for (uh=hi->msd; uh<hi->lsd-3; uh+=4) UBFROMUI(uh, 0x09090909-UBTOUI(uh)); for (; uh<=hi->lsd; uh++) *uh=(uByte)(0x09-*uh); } /* ready to add; note that hi has no leading zeros so gap */ /* calculation does not have to be as pessimistic as in decFloatAdd */ /* (this is much more like the arbitrary-precision algorithm in */ /* Rexx and decNumber) */ /* padding is the number of zeros that would need to be added to hi */ /* for its lsd to be aligned with the lsd of lo */ padding=hi->exponent-lo->exponent; /* printf("FMA pad %ld\n", (LI)padding); */ /* the result of the addition will be built into the accumulator, */ /* starting from the far right; this could be either hi or lo, and */ /* will be aligned */ ub=acc+FMALEN-1; /* where lsd of result will go */ ul=lo->lsd; /* lsd of rhs */ if (padding!=0) { /* unaligned */ /* if the msd of lo is more than DECPMAX+2 digits to the right of */ /* the original msd of hi then it can be reduced to a single */ /* digit at the right place, as it stays clear of hi digits */ /* [it must be DECPMAX+2 because during a subtraction the msd */ /* could become 0 after a borrow from 1.000 to 0.9999...] */ Int hilen=(Int)(hi->lsd-hi->msd+1); /* length of hi */ Int lolen=(Int)(lo->lsd-lo->msd+1); /* and of lo */ if (hilen+padding-lolen > DECPMAX+2) { /* can reduce lo to single */ /* make sure it is virtually at least DECPMAX from hi->msd, at */ /* least to right of hi->lsd (in case of destructive subtract), */ /* and separated by at least two digits from either of those */ /* (the tricky DOUBLE case is when hi is a 1 that will become a */ /* 0.9999... by subtraction: */ /* hi: 1 E+16 */ /* lo: .................1000000000000000 E-16 */ /* which for the addition pads to: */ /* hi: 1000000000000000000 E-16 */ /* lo: .................1000000000000000 E-16 */ Int newexp=MINI(hi->exponent, hi->exponent+hilen-DECPMAX)-3; /* printf("FMA reduce: %ld\n", (LI)reduce); */ lo->lsd=lo->msd; /* to single digit [maybe 0] */ lo->exponent=newexp; /* new lowest exponent */ padding=hi->exponent-lo->exponent; /* recalculate */ ul=lo->lsd; /* .. and repoint */ } /* padding is still > 0, but will fit in acc (less leading carry slot) */ #if DECCHECK if (padding<=0) printf("FMA low padding: %ld\n", (LI)padding); if (hilen+padding+1>FMALEN) printf("FMA excess hilen+padding: %ld+%ld \n", (LI)hilen, (LI)padding); /* printf("FMA padding: %ld\n", (LI)padding); */ #endif /* padding digits can now be set in the result; one or more of */ /* these will come from lo; others will be zeros in the gap */ for (; ul-3>=lo->msd && padding>3; padding-=4, ul-=4, ub-=4) { UBFROMUI(ub-3, UBTOUI(ul-3)); /* [cannot overlap] */ } for (; ul>=lo->msd && padding>0; padding--, ul--, ub--) *ub=*ul; for (;padding>0; padding--, ub--) *ub=0; /* mind the gap */ } /* addition now complete to the right of the rightmost digit of hi */ uh=hi->lsd; /* dow do the add from hi->lsd to the left */ /* [bytewise, because either operand can run out at any time] */ /* carry was set up depending on ten's complement above */ /* first assume both operands have some digits */ for (;; ub--) { if (uh<hi->msd || ul<lo->msd) break; *ub=(uByte)(carry+(*uh--)+(*ul--)); carry=0; if (*ub<10) continue; *ub-=10; carry=1; } /* both loop */ if (ul<lo->msd) { /* to left of lo */ for (;; ub--) { if (uh<hi->msd) break; *ub=(uByte)(carry+(*uh--)); /* [+0] */ carry=0; if (*ub<10) continue; *ub-=10; carry=1; } /* hi loop */ } else { /* to left of hi */ for (;; ub--) { if (ul<lo->msd) break; *ub=(uByte)(carry+hipad+(*ul--)); carry=0; if (*ub<10) continue; *ub-=10; carry=1; } /* lo loop */ } /* addition complete -- now handle carry, borrow, etc. */ /* use lo to set up the num (its exponent is already correct, and */ /* sign usually is) */ lo->msd=ub+1; lo->lsd=acc+FMALEN-1; /* decShowNum(lo, "lo"); */ if (!diffsign) { /* same-sign addition */ if (carry) { /* carry out */ *ub=1; /* place the 1 .. */ lo->msd--; /* .. and update */ } } /* same sign */ else { /* signs differed (subtraction) */ if (!carry) { /* no carry out means hi<lo */ /* borrowed -- take ten's complement of the right digits */ lo->sign=hi->sign; /* sign is lhs sign */ for (ul=lo->msd; ul<lo->lsd-3; ul+=4) UBFROMUI(ul, 0x09090909-UBTOUI(ul)); for (; ul<=lo->lsd; ul++) *ul=(uByte)(0x09-*ul); /* [leaves ul at lsd+1] */ /* complete the ten's complement by adding 1 [cannot overrun] */ for (ul--; *ul==9; ul--) *ul=0; *ul+=1; } /* borrowed */ else { /* carry out means hi>=lo */ /* sign to use is lo->sign */ /* all done except for the special IEEE 754 exact-zero-result */ /* rule (see above); while testing for zero, strip leading */ /* zeros (which will save decFinalize doing it) */ for (; UBTOUI(lo->msd)==0 && lo->msd+3<lo->lsd;) lo->msd+=4; for (; *lo->msd==0 && lo->msd<lo->lsd;) lo->msd++; if (*lo->msd==0) { /* must be true zero (and diffsign) */ lo->sign=0; /* assume + */ if (set->round==DEC_ROUND_FLOOR) lo->sign=DECFLOAT_Sign; } /* [else was not zero, might still have leading zeros] */ } /* subtraction gave positive result */ } /* diffsign */ #if DECCHECK /* assert no left underrun */ if (lo->msd<acc) { printf("FMA underrun by %ld \n", (LI)(acc-lo->msd)); } #endif return decFinalize(result, lo, set); /* round, check, and lay out */ } /* decFloatFMA */ /* ------------------------------------------------------------------ */ /* decFloatFromInt -- initialise a decFloat from an Int */ /* */ /* result gets the converted Int */ /* n is the Int to convert */ /* returns result */ /* */ /* The result is Exact; no errors or exceptions are possible. */ /* ------------------------------------------------------------------ */ decFloat * decFloatFromInt32(decFloat *result, Int n) { uInt u=(uInt)n; /* copy as bits */ uInt encode; /* work */ DFWORD(result, 0)=ZEROWORD; /* always */ #if QUAD DFWORD(result, 1)=0; DFWORD(result, 2)=0; #endif if (n<0) { /* handle -n with care */ /* [This can be done without the test, but is then slightly slower] */ u=(~u)+1; DFWORD(result, 0)|=DECFLOAT_Sign; } /* Since the maximum value of u now is 2**31, only the low word of */ /* result is affected */ encode=BIN2DPD[u%1000]; u/=1000; encode|=BIN2DPD[u%1000]<<10; u/=1000; encode|=BIN2DPD[u%1000]<<20; u/=1000; /* now 0, 1, or 2 */ encode|=u<<30; DFWORD(result, DECWORDS-1)=encode; return result; } /* decFloatFromInt32 */ /* ------------------------------------------------------------------ */ /* decFloatFromUInt -- initialise a decFloat from a uInt */ /* */ /* result gets the converted uInt */ /* n is the uInt to convert */ /* returns result */ /* */ /* The result is Exact; no errors or exceptions are possible. */ /* ------------------------------------------------------------------ */ decFloat * decFloatFromUInt32(decFloat *result, uInt u) { uInt encode; /* work */ DFWORD(result, 0)=ZEROWORD; /* always */ #if QUAD DFWORD(result, 1)=0; DFWORD(result, 2)=0; #endif encode=BIN2DPD[u%1000]; u/=1000; encode|=BIN2DPD[u%1000]<<10; u/=1000; encode|=BIN2DPD[u%1000]<<20; u/=1000; /* now 0 -> 4 */ encode|=u<<30; DFWORD(result, DECWORDS-1)=encode; DFWORD(result, DECWORDS-2)|=u>>2; /* rarely non-zero */ return result; } /* decFloatFromUInt32 */ /* ------------------------------------------------------------------ */ /* decFloatInvert -- logical digitwise INVERT of a decFloat */ /* */ /* result gets the result of INVERTing df */ /* df is the decFloat to invert */ /* set is the context */ /* returns result, which will be canonical with sign=0 */ /* */ /* The operand must be positive, finite with exponent q=0, and */ /* comprise just zeros and ones; if not, Invalid operation results. */ /* ------------------------------------------------------------------ */ decFloat * decFloatInvert(decFloat *result, const decFloat *df, decContext *set) { uInt sourhi=DFWORD(df, 0); /* top word of dfs */ if (!DFISUINT01(df) || !DFISCC01(df)) return decInvalid(result, set); /* the operand is a finite integer (q=0) */ #if DOUBLE DFWORD(result, 0)=ZEROWORD|((~sourhi)&0x04009124); DFWORD(result, 1)=(~DFWORD(df, 1)) &0x49124491; #elif QUAD DFWORD(result, 0)=ZEROWORD|((~sourhi)&0x04000912); DFWORD(result, 1)=(~DFWORD(df, 1)) &0x44912449; DFWORD(result, 2)=(~DFWORD(df, 2)) &0x12449124; DFWORD(result, 3)=(~DFWORD(df, 3)) &0x49124491; #endif return result; } /* decFloatInvert */ /* ------------------------------------------------------------------ */ /* decFloatIs -- decFloat tests (IsSigned, etc.) */ /* */ /* df is the decFloat to test */ /* returns 0 or 1 in a uInt */ /* */ /* Many of these could be macros, but having them as real functions */ /* is a little cleaner (and they can be referred to here by the */ /* generic names) */ /* ------------------------------------------------------------------ */ uInt decFloatIsCanonical(const decFloat *df) { if (DFISSPECIAL(df)) { if (DFISINF(df)) { if (DFWORD(df, 0)&ECONMASK) return 0; /* exponent continuation */ if (!DFISCCZERO(df)) return 0; /* coefficient continuation */ return 1; } /* is a NaN */ if (DFWORD(df, 0)&ECONNANMASK) return 0; /* exponent continuation */ if (DFISCCZERO(df)) return 1; /* coefficient continuation */ /* drop through to check payload */ } { /* declare block */ #if DOUBLE uInt sourhi=DFWORD(df, 0); uInt sourlo=DFWORD(df, 1); if (CANONDPDOFF(sourhi, 8) && CANONDPDTWO(sourhi, sourlo, 30) && CANONDPDOFF(sourlo, 20) && CANONDPDOFF(sourlo, 10) && CANONDPDOFF(sourlo, 0)) return 1; #elif QUAD uInt sourhi=DFWORD(df, 0); uInt sourmh=DFWORD(df, 1); uInt sourml=DFWORD(df, 2); uInt sourlo=DFWORD(df, 3); if (CANONDPDOFF(sourhi, 4) && CANONDPDTWO(sourhi, sourmh, 26) && CANONDPDOFF(sourmh, 16) && CANONDPDOFF(sourmh, 6) && CANONDPDTWO(sourmh, sourml, 28) && CANONDPDOFF(sourml, 18) && CANONDPDOFF(sourml, 8) && CANONDPDTWO(sourml, sourlo, 30) && CANONDPDOFF(sourlo, 20) && CANONDPDOFF(sourlo, 10) && CANONDPDOFF(sourlo, 0)) return 1; #endif } /* block */ return 0; /* a declet is non-canonical */ } uInt decFloatIsFinite(const decFloat *df) { return !DFISSPECIAL(df); } uInt decFloatIsInfinite(const decFloat *df) { return DFISINF(df); } uInt decFloatIsInteger(const decFloat *df) { return DFISINT(df); } uInt decFloatIsNaN(const decFloat *df) { return DFISNAN(df); } uInt decFloatIsNormal(const decFloat *df) { Int exp; /* exponent */ if (DFISSPECIAL(df)) return 0; if (DFISZERO(df)) return 0; /* is finite and non-zero */ exp=GETEXPUN(df) /* get unbiased exponent .. */ +decFloatDigits(df)-1; /* .. and make adjusted exponent */ return (exp>=DECEMIN); /* < DECEMIN is subnormal */ } uInt decFloatIsSignaling(const decFloat *df) { return DFISSNAN(df); } uInt decFloatIsSignalling(const decFloat *df) { return DFISSNAN(df); } uInt decFloatIsSigned(const decFloat *df) { return DFISSIGNED(df); } uInt decFloatIsSubnormal(const decFloat *df) { if (DFISSPECIAL(df)) return 0; /* is finite */ if (decFloatIsNormal(df)) return 0; /* it is <Nmin, but could be zero */ if (DFISZERO(df)) return 0; return 1; /* is subnormal */ } uInt decFloatIsZero(const decFloat *df) { return DFISZERO(df); } /* decFloatIs... */ /* ------------------------------------------------------------------ */ /* decFloatLogB -- return adjusted exponent, by 754 rules */ /* */ /* result gets the adjusted exponent as an integer, or a NaN etc. */ /* df is the decFloat to be examined */ /* set is the context */ /* returns result */ /* */ /* Notable cases: */ /* A<0 -> Use |A| */ /* A=0 -> -Infinity (Division by zero) */ /* A=Infinite -> +Infinity (Exact) */ /* A=1 exactly -> 0 (Exact) */ /* NaNs are propagated as usual */ /* ------------------------------------------------------------------ */ decFloat * decFloatLogB(decFloat *result, const decFloat *df, decContext *set) { Int ae; /* adjusted exponent */ if (DFISNAN(df)) return decNaNs(result, df, NULL, set); if (DFISINF(df)) { DFWORD(result, 0)=0; /* need +ve */ return decInfinity(result, result); /* canonical +Infinity */ } if (DFISZERO(df)) { set->status|=DEC_Division_by_zero; /* as per 754 */ DFWORD(result, 0)=DECFLOAT_Sign; /* make negative */ return decInfinity(result, result); /* canonical -Infinity */ } ae=GETEXPUN(df) /* get unbiased exponent .. */ +decFloatDigits(df)-1; /* .. and make adjusted exponent */ /* ae has limited range (3 digits for DOUBLE and 4 for QUAD), so */ /* it is worth using a special case of decFloatFromInt32 */ DFWORD(result, 0)=ZEROWORD; /* always */ if (ae<0) { DFWORD(result, 0)|=DECFLOAT_Sign; /* -0 so far */ ae=-ae; } #if DOUBLE DFWORD(result, 1)=BIN2DPD[ae]; /* a single declet */ #elif QUAD DFWORD(result, 1)=0; DFWORD(result, 2)=0; DFWORD(result, 3)=(ae/1000)<<10; /* is <10, so need no DPD encode */ DFWORD(result, 3)|=BIN2DPD[ae%1000]; #endif return result; } /* decFloatLogB */ /* ------------------------------------------------------------------ */ /* decFloatMax -- return maxnum of two operands */ /* */ /* result gets the chosen decFloat */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* If just one operand is a quiet NaN it is ignored. */ /* ------------------------------------------------------------------ */ decFloat * decFloatMax(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { Int comp; if (DFISNAN(dfl)) { /* sNaN or both NaNs leads to normal NaN processing */ if (DFISNAN(dfr) || DFISSNAN(dfl)) return decNaNs(result, dfl, dfr, set); return decCanonical(result, dfr); /* RHS is numeric */ } if (DFISNAN(dfr)) { /* sNaN leads to normal NaN processing (both NaN handled above) */ if (DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set); return decCanonical(result, dfl); /* LHS is numeric */ } /* Both operands are numeric; numeric comparison needed -- use */ /* total order for a well-defined choice (and +0 > -0) */ comp=decNumCompare(dfl, dfr, 1); if (comp>=0) return decCanonical(result, dfl); return decCanonical(result, dfr); } /* decFloatMax */ /* ------------------------------------------------------------------ */ /* decFloatMaxMag -- return maxnummag of two operands */ /* */ /* result gets the chosen decFloat */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* Returns according to the magnitude comparisons if both numeric and */ /* unequal, otherwise returns maxnum */ /* ------------------------------------------------------------------ */ decFloat * decFloatMaxMag(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { Int comp; decFloat absl, absr; if (DFISNAN(dfl) || DFISNAN(dfr)) return decFloatMax(result, dfl, dfr, set); decFloatCopyAbs(&absl, dfl); decFloatCopyAbs(&absr, dfr); comp=decNumCompare(&absl, &absr, 0); if (comp>0) return decCanonical(result, dfl); if (comp<0) return decCanonical(result, dfr); return decFloatMax(result, dfl, dfr, set); } /* decFloatMaxMag */ /* ------------------------------------------------------------------ */ /* decFloatMin -- return minnum of two operands */ /* */ /* result gets the chosen decFloat */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* If just one operand is a quiet NaN it is ignored. */ /* ------------------------------------------------------------------ */ decFloat * decFloatMin(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { Int comp; if (DFISNAN(dfl)) { /* sNaN or both NaNs leads to normal NaN processing */ if (DFISNAN(dfr) || DFISSNAN(dfl)) return decNaNs(result, dfl, dfr, set); return decCanonical(result, dfr); /* RHS is numeric */ } if (DFISNAN(dfr)) { /* sNaN leads to normal NaN processing (both NaN handled above) */ if (DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set); return decCanonical(result, dfl); /* LHS is numeric */ } /* Both operands are numeric; numeric comparison needed -- use */ /* total order for a well-defined choice (and +0 > -0) */ comp=decNumCompare(dfl, dfr, 1); if (comp<=0) return decCanonical(result, dfl); return decCanonical(result, dfr); } /* decFloatMin */ /* ------------------------------------------------------------------ */ /* decFloatMinMag -- return minnummag of two operands */ /* */ /* result gets the chosen decFloat */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* Returns according to the magnitude comparisons if both numeric and */ /* unequal, otherwise returns minnum */ /* ------------------------------------------------------------------ */ decFloat * decFloatMinMag(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { Int comp; decFloat absl, absr; if (DFISNAN(dfl) || DFISNAN(dfr)) return decFloatMin(result, dfl, dfr, set); decFloatCopyAbs(&absl, dfl); decFloatCopyAbs(&absr, dfr); comp=decNumCompare(&absl, &absr, 0); if (comp<0) return decCanonical(result, dfl); if (comp>0) return decCanonical(result, dfr); return decFloatMin(result, dfl, dfr, set); } /* decFloatMinMag */ /* ------------------------------------------------------------------ */ /* decFloatMinus -- negate value, heeding NaNs, etc. */ /* */ /* result gets the canonicalized 0-df */ /* df is the decFloat to minus */ /* set is the context */ /* returns result */ /* */ /* This has the same effect as 0-df where the exponent of the zero is */ /* the same as that of df (if df is finite). */ /* The effect is also the same as decFloatCopyNegate except that NaNs */ /* are handled normally (the sign of a NaN is not affected, and an */ /* sNaN will signal), the result is canonical, and zero gets sign 0. */ /* ------------------------------------------------------------------ */ decFloat * decFloatMinus(decFloat *result, const decFloat *df, decContext *set) { if (DFISNAN(df)) return decNaNs(result, df, NULL, set); decCanonical(result, df); /* copy and check */ if (DFISZERO(df)) DFBYTE(result, 0)&=~0x80; /* turn off sign bit */ else DFBYTE(result, 0)^=0x80; /* flip sign bit */ return result; } /* decFloatMinus */ /* ------------------------------------------------------------------ */ /* decFloatMultiply -- multiply two decFloats */ /* */ /* result gets the result of multiplying dfl and dfr: */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* ------------------------------------------------------------------ */ decFloat * decFloatMultiply(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { bcdnum num; /* for final conversion */ uByte bcdacc[DECPMAX9*18+1]; /* for coefficent in BCD */ if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) { /* either is special? */ /* NaNs are handled as usual */ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set); /* infinity times zero is bad */ if (DFISINF(dfl) && DFISZERO(dfr)) return decInvalid(result, set); if (DFISINF(dfr) && DFISZERO(dfl)) return decInvalid(result, set); /* both infinite; return canonical infinity with computed sign */ DFWORD(result, 0)=DFWORD(dfl, 0)^DFWORD(dfr, 0); /* compute sign */ return decInfinity(result, result); } /* Here when both operands are finite */ decFiniteMultiply(&num, bcdacc, dfl, dfr); return decFinalize(result, &num, set); /* round, check, and lay out */ } /* decFloatMultiply */ /* ------------------------------------------------------------------ */ /* decFloatNextMinus -- next towards -Infinity */ /* */ /* result gets the next lesser decFloat */ /* dfl is the decFloat to start with */ /* set is the context */ /* returns result */ /* */ /* This is 754 nextdown; Invalid is the only status possible (from */ /* an sNaN). */ /* ------------------------------------------------------------------ */ decFloat * decFloatNextMinus(decFloat *result, const decFloat *dfl, decContext *set) { decFloat delta; /* tiny increment */ uInt savestat; /* saves status */ enum rounding saveround; /* .. and mode */ /* +Infinity is the special case */ if (DFISINF(dfl) && !DFISSIGNED(dfl)) { DFSETNMAX(result); return result; /* [no status to set] */ } /* other cases are effected by sutracting a tiny delta -- this */ /* should be done in a wider format as the delta is unrepresentable */ /* here (but can be done with normal add if the sign of zero is */ /* treated carefully, because no Inexactitude is interesting); */ /* rounding to -Infinity then pushes the result to next below */ decFloatZero(&delta); /* set up tiny delta */ DFWORD(&delta, DECWORDS-1)=1; /* coefficient=1 */ DFWORD(&delta, 0)=DECFLOAT_Sign; /* Sign=1 + biased exponent=0 */ /* set up for the directional round */ saveround=set->round; /* save mode */ set->round=DEC_ROUND_FLOOR; /* .. round towards -Infinity */ savestat=set->status; /* save status */ decFloatAdd(result, dfl, &delta, set); /* Add rules mess up the sign when going from +Ntiny to 0 */ if (DFISZERO(result)) DFWORD(result, 0)^=DECFLOAT_Sign; /* correct */ set->status&=DEC_Invalid_operation; /* preserve only sNaN status */ set->status|=savestat; /* restore pending flags */ set->round=saveround; /* .. and mode */ return result; } /* decFloatNextMinus */ /* ------------------------------------------------------------------ */ /* decFloatNextPlus -- next towards +Infinity */ /* */ /* result gets the next larger decFloat */ /* dfl is the decFloat to start with */ /* set is the context */ /* returns result */ /* */ /* This is 754 nextup; Invalid is the only status possible (from */ /* an sNaN). */ /* ------------------------------------------------------------------ */ decFloat * decFloatNextPlus(decFloat *result, const decFloat *dfl, decContext *set) { uInt savestat; /* saves status */ enum rounding saveround; /* .. and mode */ decFloat delta; /* tiny increment */ /* -Infinity is the special case */ if (DFISINF(dfl) && DFISSIGNED(dfl)) { DFSETNMAX(result); DFWORD(result, 0)|=DECFLOAT_Sign; /* make negative */ return result; /* [no status to set] */ } /* other cases are effected by sutracting a tiny delta -- this */ /* should be done in a wider format as the delta is unrepresentable */ /* here (but can be done with normal add if the sign of zero is */ /* treated carefully, because no Inexactitude is interesting); */ /* rounding to +Infinity then pushes the result to next above */ decFloatZero(&delta); /* set up tiny delta */ DFWORD(&delta, DECWORDS-1)=1; /* coefficient=1 */ DFWORD(&delta, 0)=0; /* Sign=0 + biased exponent=0 */ /* set up for the directional round */ saveround=set->round; /* save mode */ set->round=DEC_ROUND_CEILING; /* .. round towards +Infinity */ savestat=set->status; /* save status */ decFloatAdd(result, dfl, &delta, set); /* Add rules mess up the sign when going from -Ntiny to -0 */ if (DFISZERO(result)) DFWORD(result, 0)^=DECFLOAT_Sign; /* correct */ set->status&=DEC_Invalid_operation; /* preserve only sNaN status */ set->status|=savestat; /* restore pending flags */ set->round=saveround; /* .. and mode */ return result; } /* decFloatNextPlus */ /* ------------------------------------------------------------------ */ /* decFloatNextToward -- next towards a decFloat */ /* */ /* result gets the next decFloat */ /* dfl is the decFloat to start with */ /* dfr is the decFloat to move toward */ /* set is the context */ /* returns result */ /* */ /* This is 754-1985 nextafter, as modified during revision (dropped */ /* from 754-2008); status may be set unless the result is a normal */ /* number. */ /* ------------------------------------------------------------------ */ decFloat * decFloatNextToward(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { decFloat delta; /* tiny increment or decrement */ decFloat pointone; /* 1e-1 */ uInt savestat; /* saves status */ enum rounding saveround; /* .. and mode */ uInt deltatop; /* top word for delta */ Int comp; /* work */ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set); /* Both are numeric, so Invalid no longer a possibility */ comp=decNumCompare(dfl, dfr, 0); if (comp==0) return decFloatCopySign(result, dfl, dfr); /* equal */ /* unequal; do NextPlus or NextMinus but with different status rules */ if (comp<0) { /* lhs<rhs, do NextPlus, see above for commentary */ if (DFISINF(dfl) && DFISSIGNED(dfl)) { /* -Infinity special case */ DFSETNMAX(result); DFWORD(result, 0)|=DECFLOAT_Sign; return result; } saveround=set->round; /* save mode */ set->round=DEC_ROUND_CEILING; /* .. round towards +Infinity */ deltatop=0; /* positive delta */ } else { /* lhs>rhs, do NextMinus, see above for commentary */ if (DFISINF(dfl) && !DFISSIGNED(dfl)) { /* +Infinity special case */ DFSETNMAX(result); return result; } saveround=set->round; /* save mode */ set->round=DEC_ROUND_FLOOR; /* .. round towards -Infinity */ deltatop=DECFLOAT_Sign; /* negative delta */ } savestat=set->status; /* save status */ /* Here, Inexact is needed where appropriate (and hence Underflow, */ /* etc.). Therefore the tiny delta which is otherwise */ /* unrepresentable (see NextPlus and NextMinus) is constructed */ /* using the multiplication of FMA. */ decFloatZero(&delta); /* set up tiny delta */ DFWORD(&delta, DECWORDS-1)=1; /* coefficient=1 */ DFWORD(&delta, 0)=deltatop; /* Sign + biased exponent=0 */ decFloatFromString(&pointone, "1E-1", set); /* set up multiplier */ decFloatFMA(result, &delta, &pointone, dfl, set); /* [Delta is truly tiny, so no need to correct sign of zero] */ /* use new status unless the result is normal */ if (decFloatIsNormal(result)) set->status=savestat; /* else goes forward */ set->round=saveround; /* restore mode */ return result; } /* decFloatNextToward */ /* ------------------------------------------------------------------ */ /* decFloatOr -- logical digitwise OR of two decFloats */ /* */ /* result gets the result of ORing dfl and dfr */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result, which will be canonical with sign=0 */ /* */ /* The operands must be positive, finite with exponent q=0, and */ /* comprise just zeros and ones; if not, Invalid operation results. */ /* ------------------------------------------------------------------ */ decFloat * decFloatOr(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { if (!DFISUINT01(dfl) || !DFISUINT01(dfr) || !DFISCC01(dfl) || !DFISCC01(dfr)) return decInvalid(result, set); /* the operands are positive finite integers (q=0) with just 0s and 1s */ #if DOUBLE DFWORD(result, 0)=ZEROWORD |((DFWORD(dfl, 0) | DFWORD(dfr, 0))&0x04009124); DFWORD(result, 1)=(DFWORD(dfl, 1) | DFWORD(dfr, 1))&0x49124491; #elif QUAD DFWORD(result, 0)=ZEROWORD |((DFWORD(dfl, 0) | DFWORD(dfr, 0))&0x04000912); DFWORD(result, 1)=(DFWORD(dfl, 1) | DFWORD(dfr, 1))&0x44912449; DFWORD(result, 2)=(DFWORD(dfl, 2) | DFWORD(dfr, 2))&0x12449124; DFWORD(result, 3)=(DFWORD(dfl, 3) | DFWORD(dfr, 3))&0x49124491; #endif return result; } /* decFloatOr */ /* ------------------------------------------------------------------ */ /* decFloatPlus -- add value to 0, heeding NaNs, etc. */ /* */ /* result gets the canonicalized 0+df */ /* df is the decFloat to plus */ /* set is the context */ /* returns result */ /* */ /* This has the same effect as 0+df where the exponent of the zero is */ /* the same as that of df (if df is finite). */ /* The effect is also the same as decFloatCopy except that NaNs */ /* are handled normally (the sign of a NaN is not affected, and an */ /* sNaN will signal), the result is canonical, and zero gets sign 0. */ /* ------------------------------------------------------------------ */ decFloat * decFloatPlus(decFloat *result, const decFloat *df, decContext *set) { if (DFISNAN(df)) return decNaNs(result, df, NULL, set); decCanonical(result, df); /* copy and check */ if (DFISZERO(df)) DFBYTE(result, 0)&=~0x80; /* turn off sign bit */ return result; } /* decFloatPlus */ /* ------------------------------------------------------------------ */ /* decFloatQuantize -- quantize a decFloat */ /* */ /* result gets the result of quantizing dfl to match dfr */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs), which sets the exponent */ /* set is the context */ /* returns result */ /* */ /* Unless there is an error or the result is infinite, the exponent */ /* of result is guaranteed to be the same as that of dfr. */ /* ------------------------------------------------------------------ */ decFloat * decFloatQuantize(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { Int explb, exprb; /* left and right biased exponents */ uByte *ulsd; /* local LSD pointer */ uByte *ub, *uc; /* work */ Int drop; /* .. */ uInt dpd; /* .. */ uInt encode; /* encoding accumulator */ uInt sourhil, sourhir; /* top words from source decFloats */ uInt uiwork; /* for macros */ #if QUAD uShort uswork; /* .. */ #endif /* the following buffer holds the coefficient for manipulation */ uByte buf[4+DECPMAX*3+2*QUAD]; /* + space for zeros to left or right */ #if DECTRACE bcdnum num; /* for trace displays */ #endif /* Start decoding the arguments */ sourhil=DFWORD(dfl, 0); /* LHS top word */ explb=DECCOMBEXP[sourhil>>26]; /* get exponent high bits (in place) */ sourhir=DFWORD(dfr, 0); /* RHS top word */ exprb=DECCOMBEXP[sourhir>>26]; if (EXPISSPECIAL(explb | exprb)) { /* either is special? */ /* NaNs are handled as usual */ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set); /* one infinity but not both is bad */ if (DFISINF(dfl)!=DFISINF(dfr)) return decInvalid(result, set); /* both infinite; return canonical infinity with sign of LHS */ return decInfinity(result, dfl); } /* Here when both arguments are finite */ /* complete extraction of the exponents [no need to unbias] */ explb+=GETECON(dfl); /* + continuation */ exprb+=GETECON(dfr); /* .. */ /* calculate the number of digits to drop from the coefficient */ drop=exprb-explb; /* 0 if nothing to do */ if (drop==0) return decCanonical(result, dfl); /* return canonical */ /* the coefficient is needed; lay it out into buf, offset so zeros */ /* can be added before or after as needed -- an extra heading is */ /* added so can safely pad Quad DECPMAX-1 zeros to the left by */ /* fours */ #define BUFOFF (buf+4+DECPMAX) GETCOEFF(dfl, BUFOFF); /* decode from decFloat */ /* [now the msd is at BUFOFF and the lsd is at BUFOFF+DECPMAX-1] */ #if DECTRACE num.msd=BUFOFF; num.lsd=BUFOFF+DECPMAX-1; num.exponent=explb-DECBIAS; num.sign=sourhil & DECFLOAT_Sign; decShowNum(&num, "dfl"); #endif if (drop>0) { /* [most common case] */ /* (this code is very similar to that in decFloatFinalize, but */ /* has many differences so is duplicated here -- so any changes */ /* may need to be made there, too) */ uByte *roundat; /* -> re-round digit */ uByte reround; /* reround value */ /* printf("Rounding; drop=%ld\n", (LI)drop); */ /* there is at least one zero needed to the left, in all but one */ /* exceptional (all-nines) case, so place four zeros now; this is */ /* needed almost always and makes rounding all-nines by fours safe */ UBFROMUI(BUFOFF-4, 0); /* Three cases here: */ /* 1. new LSD is in coefficient (almost always) */ /* 2. new LSD is digit to left of coefficient (so MSD is */ /* round-for-reround digit) */ /* 3. new LSD is to left of case 2 (whole coefficient is sticky) */ /* Note that leading zeros can safely be treated as useful digits */ /* [duplicate check-stickies code to save a test] */ /* [by-digit check for stickies as runs of zeros are rare] */ if (drop<DECPMAX) { /* NB lengths not addresses */ roundat=BUFOFF+DECPMAX-drop; reround=*roundat; for (ub=roundat+1; ub<BUFOFF+DECPMAX; ub++) { if (*ub!=0) { /* non-zero to be discarded */ reround=DECSTICKYTAB[reround]; /* apply sticky bit */ break; /* [remainder don't-care] */ } } /* check stickies */ ulsd=roundat-1; /* set LSD */ } else { /* edge case */ if (drop==DECPMAX) { roundat=BUFOFF; reround=*roundat; } else { roundat=BUFOFF-1; reround=0; } for (ub=roundat+1; ub<BUFOFF+DECPMAX; ub++) { if (*ub!=0) { /* non-zero to be discarded */ reround=DECSTICKYTAB[reround]; /* apply sticky bit */ break; /* [remainder don't-care] */ } } /* check stickies */ *BUFOFF=0; /* make a coefficient of 0 */ ulsd=BUFOFF; /* .. at the MSD place */ } if (reround!=0) { /* discarding non-zero */ uInt bump=0; set->status|=DEC_Inexact; /* next decide whether to increment the coefficient */ if (set->round==DEC_ROUND_HALF_EVEN) { /* fastpath slowest case */ if (reround>5) bump=1; /* >0.5 goes up */ else if (reround==5) /* exactly 0.5000 .. */ bump=*ulsd & 0x01; /* .. up iff [new] lsd is odd */ } /* r-h-e */ else switch (set->round) { case DEC_ROUND_DOWN: { /* no change */ break;} /* r-d */ case DEC_ROUND_HALF_DOWN: { if (reround>5) bump=1; break;} /* r-h-d */ case DEC_ROUND_HALF_UP: { if (reround>=5) bump=1; break;} /* r-h-u */ case DEC_ROUND_UP: { if (reround>0) bump=1; break;} /* r-u */ case DEC_ROUND_CEILING: { /* same as _UP for positive numbers, and as _DOWN for negatives */ if (!(sourhil&DECFLOAT_Sign) && reround>0) bump=1; break;} /* r-c */ case DEC_ROUND_FLOOR: { /* same as _UP for negative numbers, and as _DOWN for positive */ /* [negative reround cannot occur on 0] */ if (sourhil&DECFLOAT_Sign && reround>0) bump=1; break;} /* r-f */ case DEC_ROUND_05UP: { if (reround>0) { /* anything out there is 'sticky' */ /* bump iff lsd=0 or 5; this cannot carry so it could be */ /* effected immediately with no bump -- but the code */ /* is clearer if this is done the same way as the others */ if (*ulsd==0 || *ulsd==5) bump=1; } break;} /* r-r */ default: { /* e.g., DEC_ROUND_MAX */ set->status|=DEC_Invalid_context; #if DECCHECK printf("Unknown rounding mode: %ld\n", (LI)set->round); #endif break;} } /* switch (not r-h-e) */ /* printf("ReRound: %ld bump: %ld\n", (LI)reround, (LI)bump); */ if (bump!=0) { /* need increment */ /* increment the coefficient; this could give 1000... (after */ /* the all nines case) */ ub=ulsd; for (; UBTOUI(ub-3)==0x09090909; ub-=4) UBFROMUI(ub-3, 0); /* now at most 3 digits left to non-9 (usually just the one) */ for (; *ub==9; ub--) *ub=0; *ub+=1; /* [the all-nines case will have carried one digit to the */ /* left of the original MSD -- just where it is needed] */ } /* bump needed */ } /* inexact rounding */ /* now clear zeros to the left so exactly DECPMAX digits will be */ /* available in the coefficent -- the first word to the left was */ /* cleared earlier for safe carry; now add any more needed */ if (drop>4) { UBFROMUI(BUFOFF-8, 0); /* must be at least 5 */ for (uc=BUFOFF-12; uc>ulsd-DECPMAX-3; uc-=4) UBFROMUI(uc, 0); } } /* need round (drop>0) */ else { /* drop<0; padding with -drop digits is needed */ /* This is the case where an error can occur if the padded */ /* coefficient will not fit; checking for this can be done in the */ /* same loop as padding for zeros if the no-hope and zero cases */ /* are checked first */ if (-drop>DECPMAX-1) { /* cannot fit unless 0 */ if (!ISCOEFFZERO(BUFOFF)) return decInvalid(result, set); /* a zero can have any exponent; just drop through and use it */ ulsd=BUFOFF+DECPMAX-1; } else { /* padding will fit (but may still be too long) */ /* final-word mask depends on endianess */ #if DECLITEND static const uInt dmask[]={0, 0x000000ff, 0x0000ffff, 0x00ffffff}; #else static const uInt dmask[]={0, 0xff000000, 0xffff0000, 0xffffff00}; #endif /* note that here zeros to the right are added by fours, so in */ /* the Quad case this could write 36 zeros if the coefficient has */ /* fewer than three significant digits (hence the +2*QUAD for buf) */ for (uc=BUFOFF+DECPMAX;; uc+=4) { UBFROMUI(uc, 0); if (UBTOUI(uc-DECPMAX)!=0) { /* could be bad */ /* if all four digits should be zero, definitely bad */ if (uc<=BUFOFF+DECPMAX+(-drop)-4) return decInvalid(result, set); /* must be a 1- to 3-digit sequence; check more carefully */ if ((UBTOUI(uc-DECPMAX)&dmask[(-drop)%4])!=0) return decInvalid(result, set); break; /* no need for loop end test */ } if (uc>=BUFOFF+DECPMAX+(-drop)-4) break; /* done */ } ulsd=BUFOFF+DECPMAX+(-drop)-1; } /* pad and check leading zeros */ } /* drop<0 */ #if DECTRACE num.msd=ulsd-DECPMAX+1; num.lsd=ulsd; num.exponent=explb-DECBIAS; num.sign=sourhil & DECFLOAT_Sign; decShowNum(&num, "res"); #endif /*------------------------------------------------------------------*/ /* At this point the result is DECPMAX digits, ending at ulsd, so */ /* fits the encoding exactly; there is no possibility of error */ /*------------------------------------------------------------------*/ encode=((exprb>>DECECONL)<<4) + *(ulsd-DECPMAX+1); /* make index */ encode=DECCOMBFROM[encode]; /* indexed by (0-2)*16+msd */ /* the exponent continuation can be extracted from the original RHS */ encode|=sourhir & ECONMASK; encode|=sourhil&DECFLOAT_Sign; /* add the sign from LHS */ /* finally encode the coefficient */ /* private macro to encode a declet; this version can be used */ /* because all coefficient digits exist */ #define getDPD3q(dpd, n) ub=ulsd-(3*(n))-2; \ dpd=BCD2DPD[(*ub*256)+(*(ub+1)*16)+*(ub+2)]; #if DOUBLE getDPD3q(dpd, 4); encode|=dpd<<8; getDPD3q(dpd, 3); encode|=dpd>>2; DFWORD(result, 0)=encode; encode=dpd<<30; getDPD3q(dpd, 2); encode|=dpd<<20; getDPD3q(dpd, 1); encode|=dpd<<10; getDPD3q(dpd, 0); encode|=dpd; DFWORD(result, 1)=encode; #elif QUAD getDPD3q(dpd,10); encode|=dpd<<4; getDPD3q(dpd, 9); encode|=dpd>>6; DFWORD(result, 0)=encode; encode=dpd<<26; getDPD3q(dpd, 8); encode|=dpd<<16; getDPD3q(dpd, 7); encode|=dpd<<6; getDPD3q(dpd, 6); encode|=dpd>>4; DFWORD(result, 1)=encode; encode=dpd<<28; getDPD3q(dpd, 5); encode|=dpd<<18; getDPD3q(dpd, 4); encode|=dpd<<8; getDPD3q(dpd, 3); encode|=dpd>>2; DFWORD(result, 2)=encode; encode=dpd<<30; getDPD3q(dpd, 2); encode|=dpd<<20; getDPD3q(dpd, 1); encode|=dpd<<10; getDPD3q(dpd, 0); encode|=dpd; DFWORD(result, 3)=encode; #endif return result; } /* decFloatQuantize */ /* ------------------------------------------------------------------ */ /* decFloatReduce -- reduce finite coefficient to minimum length */ /* */ /* result gets the reduced decFloat */ /* df is the source decFloat */ /* set is the context */ /* returns result, which will be canonical */ /* */ /* This removes all possible trailing zeros from the coefficient; */ /* some may remain when the number is very close to Nmax. */ /* Special values are unchanged and no status is set unless df=sNaN. */ /* Reduced zero has an exponent q=0. */ /* ------------------------------------------------------------------ */ decFloat * decFloatReduce(decFloat *result, const decFloat *df, decContext *set) { bcdnum num; /* work */ uByte buf[DECPMAX], *ub; /* coefficient and pointer */ if (df!=result) *result=*df; /* copy, if needed */ if (DFISNAN(df)) return decNaNs(result, df, NULL, set); /* sNaN */ /* zeros and infinites propagate too */ if (DFISINF(df)) return decInfinity(result, df); /* canonical */ if (DFISZERO(df)) { uInt sign=DFWORD(df, 0)&DECFLOAT_Sign; decFloatZero(result); DFWORD(result, 0)|=sign; return result; /* exponent dropped, sign OK */ } /* non-zero finite */ GETCOEFF(df, buf); ub=buf+DECPMAX-1; /* -> lsd */ if (*ub) return result; /* no trailing zeros */ for (ub--; *ub==0;) ub--; /* terminates because non-zero */ /* *ub is the first non-zero from the right */ num.sign=DFWORD(df, 0)&DECFLOAT_Sign; /* set up number... */ num.exponent=GETEXPUN(df)+(Int)(buf+DECPMAX-1-ub); /* adjusted exponent */ num.msd=buf; num.lsd=ub; return decFinalize(result, &num, set); } /* decFloatReduce */ /* ------------------------------------------------------------------ */ /* decFloatRemainder -- integer divide and return remainder */ /* */ /* result gets the remainder of dividing dfl by dfr: */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* ------------------------------------------------------------------ */ decFloat * decFloatRemainder(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { return decDivide(result, dfl, dfr, set, REMAINDER); } /* decFloatRemainder */ /* ------------------------------------------------------------------ */ /* decFloatRemainderNear -- integer divide to nearest and remainder */ /* */ /* result gets the remainder of dividing dfl by dfr: */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* This is the IEEE remainder, where the nearest integer is used. */ /* ------------------------------------------------------------------ */ decFloat * decFloatRemainderNear(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { return decDivide(result, dfl, dfr, set, REMNEAR); } /* decFloatRemainderNear */ /* ------------------------------------------------------------------ */ /* decFloatRotate -- rotate the coefficient of a decFloat left/right */ /* */ /* result gets the result of rotating dfl */ /* dfl is the source decFloat to rotate */ /* dfr is the count of digits to rotate, an integer (with q=0) */ /* set is the context */ /* returns result */ /* */ /* The digits of the coefficient of dfl are rotated to the left (if */ /* dfr is positive) or to the right (if dfr is negative) without */ /* adjusting the exponent or the sign of dfl. */ /* */ /* dfr must be in the range -DECPMAX through +DECPMAX. */ /* NaNs are propagated as usual. An infinite dfl is unaffected (but */ /* dfr must be valid). No status is set unless dfr is invalid or an */ /* operand is an sNaN. The result is canonical. */ /* ------------------------------------------------------------------ */ #define PHALF (ROUNDUP(DECPMAX/2, 4)) /* half length, rounded up */ decFloat * decFloatRotate(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { Int rotate; /* dfr as an Int */ uByte buf[DECPMAX+PHALF]; /* coefficient + half */ uInt digits, savestat; /* work */ bcdnum num; /* .. */ uByte *ub; /* .. */ if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set); if (!DFISINT(dfr)) return decInvalid(result, set); digits=decFloatDigits(dfr); /* calculate digits */ if (digits>2) return decInvalid(result, set); /* definitely out of range */ rotate=DPD2BIN[DFWORD(dfr, DECWORDS-1)&0x3ff]; /* is in bottom declet */ if (rotate>DECPMAX) return decInvalid(result, set); /* too big */ /* [from here on no error or status change is possible] */ if (DFISINF(dfl)) return decInfinity(result, dfl); /* canonical */ /* handle no-rotate cases */ if (rotate==0 || rotate==DECPMAX) return decCanonical(result, dfl); /* a real rotate is needed: 0 < rotate < DECPMAX */ /* reduce the rotation to no more than half to reduce copying later */ /* (for QUAD in fact half + 2 digits) */ if (DFISSIGNED(dfr)) rotate=-rotate; if (abs(rotate)>PHALF) { if (rotate<0) rotate=DECPMAX+rotate; else rotate=rotate-DECPMAX; } /* now lay out the coefficient, leaving room to the right or the */ /* left depending on the direction of rotation */ ub=buf; if (rotate<0) ub+=PHALF; /* rotate right, so space to left */ GETCOEFF(dfl, ub); /* copy half the digits to left or right, and set num.msd */ if (rotate<0) { memcpy(buf, buf+DECPMAX, PHALF); num.msd=buf+PHALF+rotate; } else { memcpy(buf+DECPMAX, buf, PHALF); num.msd=buf+rotate; } /* fill in rest of num */ num.lsd=num.msd+DECPMAX-1; num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign; num.exponent=GETEXPUN(dfl); savestat=set->status; /* record */ decFinalize(result, &num, set); set->status=savestat; /* restore */ return result; } /* decFloatRotate */ /* ------------------------------------------------------------------ */ /* decFloatSameQuantum -- test decFloats for same quantum */ /* */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* returns 1 if the operands have the same quantum, 0 otherwise */ /* */ /* No error is possible and no status results. */ /* ------------------------------------------------------------------ */ uInt decFloatSameQuantum(const decFloat *dfl, const decFloat *dfr) { if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) { if (DFISNAN(dfl) && DFISNAN(dfr)) return 1; if (DFISINF(dfl) && DFISINF(dfr)) return 1; return 0; /* any other special mixture gives false */ } if (GETEXP(dfl)==GETEXP(dfr)) return 1; /* biased exponents match */ return 0; } /* decFloatSameQuantum */ /* ------------------------------------------------------------------ */ /* decFloatScaleB -- multiply by a power of 10, as per 754 */ /* */ /* result gets the result of the operation */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs), am integer (with q=0) */ /* set is the context */ /* returns result */ /* */ /* This computes result=dfl x 10**dfr where dfr is an integer in the */ /* range +/-2*(emax+pmax), typically resulting from LogB. */ /* Underflow and Overflow (with Inexact) may occur. NaNs propagate */ /* as usual. */ /* ------------------------------------------------------------------ */ #define SCALEBMAX 2*(DECEMAX+DECPMAX) /* D=800, Q=12356 */ decFloat * decFloatScaleB(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { uInt digits; /* work */ Int expr; /* dfr as an Int */ if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set); if (!DFISINT(dfr)) return decInvalid(result, set); digits=decFloatDigits(dfr); /* calculate digits */ #if DOUBLE if (digits>3) return decInvalid(result, set); /* definitely out of range */ expr=DPD2BIN[DFWORD(dfr, 1)&0x3ff]; /* must be in bottom declet */ #elif QUAD if (digits>5) return decInvalid(result, set); /* definitely out of range */ expr=DPD2BIN[DFWORD(dfr, 3)&0x3ff] /* in bottom 2 declets .. */ +DPD2BIN[(DFWORD(dfr, 3)>>10)&0x3ff]*1000; /* .. */ #endif if (expr>SCALEBMAX) return decInvalid(result, set); /* oops */ /* [from now on no error possible] */ if (DFISINF(dfl)) return decInfinity(result, dfl); /* canonical */ if (DFISSIGNED(dfr)) expr=-expr; /* dfl is finite and expr is valid */ *result=*dfl; /* copy to target */ return decFloatSetExponent(result, set, GETEXPUN(result)+expr); } /* decFloatScaleB */ /* ------------------------------------------------------------------ */ /* decFloatShift -- shift the coefficient of a decFloat left or right */ /* */ /* result gets the result of shifting dfl */ /* dfl is the source decFloat to shift */ /* dfr is the count of digits to shift, an integer (with q=0) */ /* set is the context */ /* returns result */ /* */ /* The digits of the coefficient of dfl are shifted to the left (if */ /* dfr is positive) or to the right (if dfr is negative) without */ /* adjusting the exponent or the sign of dfl. */ /* */ /* dfr must be in the range -DECPMAX through +DECPMAX. */ /* NaNs are propagated as usual. An infinite dfl is unaffected (but */ /* dfr must be valid). No status is set unless dfr is invalid or an */ /* operand is an sNaN. The result is canonical. */ /* ------------------------------------------------------------------ */ decFloat * decFloatShift(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { Int shift; /* dfr as an Int */ uByte buf[DECPMAX*2]; /* coefficient + padding */ uInt digits, savestat; /* work */ bcdnum num; /* .. */ uInt uiwork; /* for macros */ if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set); if (!DFISINT(dfr)) return decInvalid(result, set); digits=decFloatDigits(dfr); /* calculate digits */ if (digits>2) return decInvalid(result, set); /* definitely out of range */ shift=DPD2BIN[DFWORD(dfr, DECWORDS-1)&0x3ff]; /* is in bottom declet */ if (shift>DECPMAX) return decInvalid(result, set); /* too big */ /* [from here on no error or status change is possible] */ if (DFISINF(dfl)) return decInfinity(result, dfl); /* canonical */ /* handle no-shift and all-shift (clear to zero) cases */ if (shift==0) return decCanonical(result, dfl); if (shift==DECPMAX) { /* zero with sign */ uByte sign=(uByte)(DFBYTE(dfl, 0)&0x80); /* save sign bit */ decFloatZero(result); /* make +0 */ DFBYTE(result, 0)=(uByte)(DFBYTE(result, 0)|sign); /* and set sign */ /* [cannot safely use CopySign] */ return result; } /* a real shift is needed: 0 < shift < DECPMAX */ num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign; num.exponent=GETEXPUN(dfl); num.msd=buf; GETCOEFF(dfl, buf); if (DFISSIGNED(dfr)) { /* shift right */ /* edge cases are taken care of, so this is easy */ num.lsd=buf+DECPMAX-shift-1; } else { /* shift left -- zero padding needed to right */ UBFROMUI(buf+DECPMAX, 0); /* 8 will handle most cases */ UBFROMUI(buf+DECPMAX+4, 0); /* .. */ if (shift>8) memset(buf+DECPMAX+8, 0, 8+QUAD*18); /* all other cases */ num.msd+=shift; num.lsd=num.msd+DECPMAX-1; } savestat=set->status; /* record */ decFinalize(result, &num, set); set->status=savestat; /* restore */ return result; } /* decFloatShift */ /* ------------------------------------------------------------------ */ /* decFloatSubtract -- subtract a decFloat from another */ /* */ /* result gets the result of subtracting dfr from dfl: */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result */ /* */ /* ------------------------------------------------------------------ */ decFloat * decFloatSubtract(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { decFloat temp; /* NaNs must propagate without sign change */ if (DFISNAN(dfr)) return decFloatAdd(result, dfl, dfr, set); temp=*dfr; /* make a copy */ DFBYTE(&temp, 0)^=0x80; /* flip sign */ return decFloatAdd(result, dfl, &temp, set); /* and add to the lhs */ } /* decFloatSubtract */ /* ------------------------------------------------------------------ */ /* decFloatToInt -- round to 32-bit binary integer (4 flavours) */ /* */ /* df is the decFloat to round */ /* set is the context */ /* round is the rounding mode to use */ /* returns a uInt or an Int, rounded according to the name */ /* */ /* Invalid will always be signaled if df is a NaN, is Infinite, or is */ /* outside the range of the target; Inexact will not be signaled for */ /* simple rounding unless 'Exact' appears in the name. */ /* ------------------------------------------------------------------ */ uInt decFloatToUInt32(const decFloat *df, decContext *set, enum rounding round) { return decToInt32(df, set, round, 0, 1);} uInt decFloatToUInt32Exact(const decFloat *df, decContext *set, enum rounding round) { return decToInt32(df, set, round, 1, 1);} Int decFloatToInt32(const decFloat *df, decContext *set, enum rounding round) { return (Int)decToInt32(df, set, round, 0, 0);} Int decFloatToInt32Exact(const decFloat *df, decContext *set, enum rounding round) { return (Int)decToInt32(df, set, round, 1, 0);} /* ------------------------------------------------------------------ */ /* decFloatToIntegral -- round to integral value (two flavours) */ /* */ /* result gets the result */ /* df is the decFloat to round */ /* set is the context */ /* round is the rounding mode to use */ /* returns result */ /* */ /* No exceptions, even Inexact, are raised except for sNaN input, or */ /* if 'Exact' appears in the name. */ /* ------------------------------------------------------------------ */ decFloat * decFloatToIntegralValue(decFloat *result, const decFloat *df, decContext *set, enum rounding round) { return decToIntegral(result, df, set, round, 0);} decFloat * decFloatToIntegralExact(decFloat *result, const decFloat *df, decContext *set) { return decToIntegral(result, df, set, set->round, 1);} /* ------------------------------------------------------------------ */ /* decFloatXor -- logical digitwise XOR of two decFloats */ /* */ /* result gets the result of XORing dfl and dfr */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) */ /* set is the context */ /* returns result, which will be canonical with sign=0 */ /* */ /* The operands must be positive, finite with exponent q=0, and */ /* comprise just zeros and ones; if not, Invalid operation results. */ /* ------------------------------------------------------------------ */ decFloat * decFloatXor(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { if (!DFISUINT01(dfl) || !DFISUINT01(dfr) || !DFISCC01(dfl) || !DFISCC01(dfr)) return decInvalid(result, set); /* the operands are positive finite integers (q=0) with just 0s and 1s */ #if DOUBLE DFWORD(result, 0)=ZEROWORD |((DFWORD(dfl, 0) ^ DFWORD(dfr, 0))&0x04009124); DFWORD(result, 1)=(DFWORD(dfl, 1) ^ DFWORD(dfr, 1))&0x49124491; #elif QUAD DFWORD(result, 0)=ZEROWORD |((DFWORD(dfl, 0) ^ DFWORD(dfr, 0))&0x04000912); DFWORD(result, 1)=(DFWORD(dfl, 1) ^ DFWORD(dfr, 1))&0x44912449; DFWORD(result, 2)=(DFWORD(dfl, 2) ^ DFWORD(dfr, 2))&0x12449124; DFWORD(result, 3)=(DFWORD(dfl, 3) ^ DFWORD(dfr, 3))&0x49124491; #endif return result; } /* decFloatXor */ /* ------------------------------------------------------------------ */ /* decInvalid -- set Invalid_operation result */ /* */ /* result gets a canonical NaN */ /* set is the context */ /* returns result */ /* */ /* status has Invalid_operation added */ /* ------------------------------------------------------------------ */ static decFloat *decInvalid(decFloat *result, decContext *set) { decFloatZero(result); DFWORD(result, 0)=DECFLOAT_qNaN; set->status|=DEC_Invalid_operation; return result; } /* decInvalid */ /* ------------------------------------------------------------------ */ /* decInfinity -- set canonical Infinity with sign from a decFloat */ /* */ /* result gets a canonical Infinity */ /* df is source decFloat (only the sign is used) */ /* returns result */ /* */ /* df may be the same as result */ /* ------------------------------------------------------------------ */ static decFloat *decInfinity(decFloat *result, const decFloat *df) { uInt sign=DFWORD(df, 0); /* save source signword */ decFloatZero(result); /* clear everything */ DFWORD(result, 0)=DECFLOAT_Inf | (sign & DECFLOAT_Sign); return result; } /* decInfinity */ /* ------------------------------------------------------------------ */ /* decNaNs -- handle NaN argument(s) */ /* */ /* result gets the result of handling dfl and dfr, one or both of */ /* which is a NaN */ /* dfl is the first decFloat (lhs) */ /* dfr is the second decFloat (rhs) -- may be NULL for a single- */ /* operand operation */ /* set is the context */ /* returns result */ /* */ /* Called when one or both operands is a NaN, and propagates the */ /* appropriate result to res. When an sNaN is found, it is changed */ /* to a qNaN and Invalid operation is set. */ /* ------------------------------------------------------------------ */ static decFloat *decNaNs(decFloat *result, const decFloat *dfl, const decFloat *dfr, decContext *set) { /* handle sNaNs first */ if (dfr!=NULL && DFISSNAN(dfr) && !DFISSNAN(dfl)) dfl=dfr; /* use RHS */ if (DFISSNAN(dfl)) { decCanonical(result, dfl); /* propagate canonical sNaN */ DFWORD(result, 0)&=~(DECFLOAT_qNaN ^ DECFLOAT_sNaN); /* quiet */ set->status|=DEC_Invalid_operation; return result; } /* one or both is a quiet NaN */ if (!DFISNAN(dfl)) dfl=dfr; /* RHS must be NaN, use it */ return decCanonical(result, dfl); /* propagate canonical qNaN */ } /* decNaNs */ /* ------------------------------------------------------------------ */ /* decNumCompare -- numeric comparison of two decFloats */ /* */ /* dfl is the left-hand decFloat, which is not a NaN */ /* dfr is the right-hand decFloat, which is not a NaN */ /* tot is 1 for total order compare, 0 for simple numeric */ /* returns -1, 0, or +1 for dfl<dfr, dfl=dfr, dfl>dfr */ /* */ /* No error is possible; status and mode are unchanged. */ /* ------------------------------------------------------------------ */ static Int decNumCompare(const decFloat *dfl, const decFloat *dfr, Flag tot) { Int sigl, sigr; /* LHS and RHS non-0 signums */ Int shift; /* shift needed to align operands */ uByte *ub, *uc; /* work */ uInt uiwork; /* for macros */ /* buffers +2 if Quad (36 digits), need double plus 4 for safe padding */ uByte bufl[DECPMAX*2+QUAD*2+4]; /* for LHS coefficient + padding */ uByte bufr[DECPMAX*2+QUAD*2+4]; /* for RHS coefficient + padding */ sigl=1; if (DFISSIGNED(dfl)) { if (!DFISSIGNED(dfr)) { /* -LHS +RHS */ if (DFISZERO(dfl) && DFISZERO(dfr) && !tot) return 0; return -1; /* RHS wins */ } sigl=-1; } if (DFISSIGNED(dfr)) { if (!DFISSIGNED(dfl)) { /* +LHS -RHS */ if (DFISZERO(dfl) && DFISZERO(dfr) && !tot) return 0; return +1; /* LHS wins */ } } /* signs are the same; operand(s) could be zero */ sigr=-sigl; /* sign to return if abs(RHS) wins */ if (DFISINF(dfl)) { if (DFISINF(dfr)) return 0; /* both infinite & same sign */ return sigl; /* inf > n */ } if (DFISINF(dfr)) return sigr; /* n < inf [dfl is finite] */ /* here, both are same sign and finite; calculate their offset */ shift=GETEXP(dfl)-GETEXP(dfr); /* [0 means aligned] */ /* [bias can be ignored -- the absolute exponent is not relevant] */ if (DFISZERO(dfl)) { if (!DFISZERO(dfr)) return sigr; /* LHS=0, RHS!=0 */ /* both are zero, return 0 if both same exponent or numeric compare */ if (shift==0 || !tot) return 0; if (shift>0) return sigl; return sigr; /* [shift<0] */ } else { /* LHS!=0 */ if (DFISZERO(dfr)) return sigl; /* LHS!=0, RHS=0 */ } /* both are known to be non-zero at this point */ /* if the exponents are so different that the coefficients do not */ /* overlap (by even one digit) then a full comparison is not needed */ if (abs(shift)>=DECPMAX) { /* no overlap */ /* coefficients are known to be non-zero */ if (shift>0) return sigl; return sigr; /* [shift<0] */ } /* decode the coefficients */ /* (shift both right two if Quad to make a multiple of four) */ #if QUAD UBFROMUI(bufl, 0); UBFROMUI(bufr, 0); #endif GETCOEFF(dfl, bufl+QUAD*2); /* decode from decFloat */ GETCOEFF(dfr, bufr+QUAD*2); /* .. */ if (shift==0) { /* aligned; common and easy */ /* all multiples of four, here */ for (ub=bufl, uc=bufr; ub<bufl+DECPMAX+QUAD*2; ub+=4, uc+=4) { uInt ui=UBTOUI(ub); if (ui==UBTOUI(uc)) continue; /* so far so same */ /* about to find a winner; go by bytes in case little-endian */ for (;; ub++, uc++) { if (*ub>*uc) return sigl; /* difference found */ if (*ub<*uc) return sigr; /* .. */ } } } /* aligned */ else if (shift>0) { /* lhs to left */ ub=bufl; /* RHS pointer */ /* pad bufl so right-aligned; most shifts will fit in 8 */ UBFROMUI(bufl+DECPMAX+QUAD*2, 0); /* add eight zeros */ UBFROMUI(bufl+DECPMAX+QUAD*2+4, 0); /* .. */ if (shift>8) { /* more than eight; fill the rest, and also worth doing the */ /* lead-in by fours */ uByte *up; /* work */ uByte *upend=bufl+DECPMAX+QUAD*2+shift; for (up=bufl+DECPMAX+QUAD*2+8; up<upend; up+=4) UBFROMUI(up, 0); /* [pads up to 36 in all for Quad] */ for (;; ub+=4) { if (UBTOUI(ub)!=0) return sigl; if (ub+4>bufl+shift-4) break; } } /* check remaining leading digits */ for (; ub<bufl+shift; ub++) if (*ub!=0) return sigl; /* now start the overlapped part; bufl has been padded, so the */ /* comparison can go for the full length of bufr, which is a */ /* multiple of 4 bytes */ for (uc=bufr; ; uc+=4, ub+=4) { uInt ui=UBTOUI(ub); if (ui!=UBTOUI(uc)) { /* mismatch found */ for (;; uc++, ub++) { /* check from left [little-endian?] */ if (*ub>*uc) return sigl; /* difference found */ if (*ub<*uc) return sigr; /* .. */ } } /* mismatch */ if (uc==bufr+QUAD*2+DECPMAX-4) break; /* all checked */ } } /* shift>0 */ else { /* shift<0) .. RHS is to left of LHS; mirror shift>0 */ uc=bufr; /* RHS pointer */ /* pad bufr so right-aligned; most shifts will fit in 8 */ UBFROMUI(bufr+DECPMAX+QUAD*2, 0); /* add eight zeros */ UBFROMUI(bufr+DECPMAX+QUAD*2+4, 0); /* .. */ if (shift<-8) { /* more than eight; fill the rest, and also worth doing the */ /* lead-in by fours */ uByte *up; /* work */ uByte *upend=bufr+DECPMAX+QUAD*2-shift; for (up=bufr+DECPMAX+QUAD*2+8; up<upend; up+=4) UBFROMUI(up, 0); /* [pads up to 36 in all for Quad] */ for (;; uc+=4) { if (UBTOUI(uc)!=0) return sigr; if (uc+4>bufr-shift-4) break; } } /* check remaining leading digits */ for (; uc<bufr-shift; uc++) if (*uc!=0) return sigr; /* now start the overlapped part; bufr has been padded, so the */ /* comparison can go for the full length of bufl, which is a */ /* multiple of 4 bytes */ for (ub=bufl; ; ub+=4, uc+=4) { uInt ui=UBTOUI(ub); if (ui!=UBTOUI(uc)) { /* mismatch found */ for (;; ub++, uc++) { /* check from left [little-endian?] */ if (*ub>*uc) return sigl; /* difference found */ if (*ub<*uc) return sigr; /* .. */ } } /* mismatch */ if (ub==bufl+QUAD*2+DECPMAX-4) break; /* all checked */ } } /* shift<0 */ /* Here when compare equal */ if (!tot) return 0; /* numerically equal */ /* total ordering .. exponent matters */ if (shift>0) return sigl; /* total order by exponent */ if (shift<0) return sigr; /* .. */ return 0; } /* decNumCompare */ /* ------------------------------------------------------------------ */ /* decToInt32 -- local routine to effect ToInteger conversions */ /* */ /* df is the decFloat to convert */ /* set is the context */ /* rmode is the rounding mode to use */ /* exact is 1 if Inexact should be signalled */ /* unsign is 1 if the result a uInt, 0 if an Int (cast to uInt) */ /* returns 32-bit result as a uInt */ /* */ /* Invalid is set is df is a NaN, is infinite, or is out-of-range; in */ /* these cases 0 is returned. */ /* ------------------------------------------------------------------ */ static uInt decToInt32(const decFloat *df, decContext *set, enum rounding rmode, Flag exact, Flag unsign) { Int exp; /* exponent */ uInt sourhi, sourpen, sourlo; /* top word from source decFloat .. */ uInt hi, lo; /* .. penultimate, least, etc. */ decFloat zero, result; /* work */ Int i; /* .. */ /* Start decoding the argument */ sourhi=DFWORD(df, 0); /* top word */ exp=DECCOMBEXP[sourhi>>26]; /* get exponent high bits (in place) */ if (EXPISSPECIAL(exp)) { /* is special? */ set->status|=DEC_Invalid_operation; /* signal */ return 0; } /* Here when the argument is finite */ if (GETEXPUN(df)==0) result=*df; /* already a true integer */ else { /* need to round to integer */ enum rounding saveround; /* saver */ uInt savestatus; /* .. */ saveround=set->round; /* save rounding mode .. */ savestatus=set->status; /* .. and status */ set->round=rmode; /* set mode */ decFloatZero(&zero); /* make 0E+0 */ set->status=0; /* clear */ decFloatQuantize(&result, df, &zero, set); /* [this may fail] */ set->round=saveround; /* restore rounding mode .. */ if (exact) set->status|=savestatus; /* include Inexact */ else set->status=savestatus; /* .. or just original status */ } /* only the last four declets of the coefficient can contain */ /* non-zero; check for others (and also NaN or Infinity from the */ /* Quantize) first (see DFISZERO for explanation): */ /* decFloatShow(&result, "sofar"); */ #if DOUBLE if ((DFWORD(&result, 0)&0x1c03ff00)!=0 || (DFWORD(&result, 0)&0x60000000)==0x60000000) { #elif QUAD if ((DFWORD(&result, 2)&0xffffff00)!=0 || DFWORD(&result, 1)!=0 || (DFWORD(&result, 0)&0x1c003fff)!=0 || (DFWORD(&result, 0)&0x60000000)==0x60000000) { #endif set->status|=DEC_Invalid_operation; /* Invalid or out of range */ return 0; } /* get last twelve digits of the coefficent into hi & ho, base */ /* 10**9 (see GETCOEFFBILL): */ sourlo=DFWORD(&result, DECWORDS-1); lo=DPD2BIN0[sourlo&0x3ff] +DPD2BINK[(sourlo>>10)&0x3ff] +DPD2BINM[(sourlo>>20)&0x3ff]; sourpen=DFWORD(&result, DECWORDS-2); hi=DPD2BIN0[((sourpen<<2) | (sourlo>>30))&0x3ff]; /* according to request, check range carefully */ if (unsign) { if (hi>4 || (hi==4 && lo>294967295) || (hi+lo!=0 && DFISSIGNED(&result))) { set->status|=DEC_Invalid_operation; /* out of range */ return 0; } return hi*BILLION+lo; } /* signed */ if (hi>2 || (hi==2 && lo>147483647)) { /* handle the usual edge case */ if (lo==147483648 && hi==2 && DFISSIGNED(&result)) return 0x80000000; set->status|=DEC_Invalid_operation; /* truly out of range */ return 0; } i=hi*BILLION+lo; if (DFISSIGNED(&result)) i=-i; return (uInt)i; } /* decToInt32 */ /* ------------------------------------------------------------------ */ /* decToIntegral -- local routine to effect ToIntegral value */ /* */ /* result gets the result */ /* df is the decFloat to round */ /* set is the context */ /* rmode is the rounding mode to use */ /* exact is 1 if Inexact should be signalled */ /* returns result */ /* ------------------------------------------------------------------ */ static decFloat * decToIntegral(decFloat *result, const decFloat *df, decContext *set, enum rounding rmode, Flag exact) { Int exp; /* exponent */ uInt sourhi; /* top word from source decFloat */ enum rounding saveround; /* saver */ uInt savestatus; /* .. */ decFloat zero; /* work */ /* Start decoding the argument */ sourhi=DFWORD(df, 0); /* top word */ exp=DECCOMBEXP[sourhi>>26]; /* get exponent high bits (in place) */ if (EXPISSPECIAL(exp)) { /* is special? */ /* NaNs are handled as usual */ if (DFISNAN(df)) return decNaNs(result, df, NULL, set); /* must be infinite; return canonical infinity with sign of df */ return decInfinity(result, df); } /* Here when the argument is finite */ /* complete extraction of the exponent */ exp+=GETECON(df)-DECBIAS; /* .. + continuation and unbias */ if (exp>=0) return decCanonical(result, df); /* already integral */ saveround=set->round; /* save rounding mode .. */ savestatus=set->status; /* .. and status */ set->round=rmode; /* set mode */ decFloatZero(&zero); /* make 0E+0 */ decFloatQuantize(result, df, &zero, set); /* 'integrate'; cannot fail */ set->round=saveround; /* restore rounding mode .. */ if (!exact) set->status=savestatus; /* .. and status, unless exact */ return result; } /* decToIntegral */
gftg85/libdfp
libdecnumber/decBasic.c
C
lgpl-2.1
160,467
/* * Copyright (C) 2015 Martine Lenders <mlenders@inf.fu-berlin.de> * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @defgroup pkg_lwip_arch_cc Compiler and processor description * @ingroup pkg_lwip * @brief Describes compiler and processor to lwIP * @{ * * @file * @brief Compiler and processor definitions * * @author Martine Lenders <mlenders@inf.fu-berlin.de> */ #ifndef ARCH_CC_H #define ARCH_CC_H #include <assert.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include "irq.h" #include "byteorder.h" #include "mutex.h" #ifdef MODULE_LOG #include "log.h" #endif #ifdef __cplusplus extern "C" { #endif #ifndef BYTE_ORDER #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ # define BYTE_ORDER (LITTLE_ENDIAN) /**< platform's endianess */ #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ # define BYTE_ORDER (BIG_ENDIAN) /**< platform's endianess */ #else # error "Byte order is neither little nor big!" #endif #endif /** * @brief (sn)printf formatters for the generic lwIP types * @{ */ #define X8_F "02" PRIx8 #define U16_F PRIu16 #define S16_F PRId16 #define X16_F PRIx16 #define U32_F PRIu32 #define S32_F PRId32 #define X32_F PRIx32 #define SZT_F "lu" /** * @} */ /** * @brief Compiler hints for packing structures * @{ */ #define PACK_STRUCT_FIELD(x) x #define PACK_STRUCT_STRUCT __attribute__((packed)) #define PACK_STRUCT_BEGIN #define PACK_STRUCT_END /** * @} */ /** * @todo check for best value */ #define LWIP_CHKSUM_ALGORITHM (3) #ifdef MODULE_LOG # define LWIP_PLATFORM_DIAG(x) LOG_INFO x # ifdef NDEBUG # define LWIP_PLATFORM_ASSERT(x) # else # define LWIP_PLATFORM_ASSERT(x) \ do { \ LOG_ERROR("Assertion \"%s\" failed at %s:%d\n", x, __FILE__, __LINE__); \ fflush(NULL); \ abort(); \ } while (0) # endif #else # define LWIP_PLATFORM_DIAG(x) printf x # ifdef NDEBUG # define LWIP_PLATFORM_ASSERT(x) # else # define LWIP_PLATFORM_ASSERT(x) \ do { \ printf("Assertion \"%s\" failed at %s:%d\n", x, __FILE__, __LINE__); \ fflush(NULL); \ abort(); \ } while (0) # endif #endif #define SYS_ARCH_PROTECT(x) mutex_lock(&x) #define SYS_ARCH_UNPROTECT(x) mutex_unlock(&x) #define SYS_ARCH_DECL_PROTECT(x) mutex_t x = MUTEX_INIT #ifdef __cplusplus } #endif #endif /* ARCH_CC_H */ /** @} */
lazytech-org/RIOT
pkg/lwip/include/arch/cc.h
C
lgpl-2.1
2,594
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class UtilMacros(AutotoolsPackage): """This is a set of autoconf macros used by the configure.ac scripts in other Xorg modular packages, and is needed to generate new versions of their configure scripts with autoconf.""" homepage = "http://cgit.freedesktop.org/xorg/util/macros/" url = "https://www.x.org/archive/individual/util/util-macros-1.19.1.tar.bz2" version('1.19.1', '6e76e546a4e580f15cebaf8019ef1625') version('1.19.0', '1cf984125e75f8204938d998a8b6c1e1')
EmreAtes/spack
var/spack/repos/builtin/packages/util-macros/package.py
Python
lgpl-2.1
1,752
/* * Copyright (c) 2002 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with FFmpeg; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /** * @file * Shape Adaptive Blur filter, ported from MPlayer libmpcodecs/vf_sab.c */ #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "libswscale/swscale.h" #include "avfilter.h" #include "formats.h" #include "internal.h" typedef struct { float radius; float pre_filter_radius; float strength; float quality; struct SwsContext *pre_filter_context; uint8_t *pre_filter_buf; int pre_filter_linesize; int dist_width; int dist_linesize; int *dist_coeff; #define COLOR_DIFF_COEFF_SIZE 512 int color_diff_coeff[COLOR_DIFF_COEFF_SIZE]; } FilterParam; typedef struct { const AVClass *class; FilterParam luma; FilterParam chroma; int hsub; int vsub; unsigned int sws_flags; } SabContext; static int query_formats(AVFilterContext *ctx) { static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_NONE }; AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts); if (!fmts_list) return AVERROR(ENOMEM); return ff_set_common_formats(ctx, fmts_list); } #define RADIUS_MIN 0.1 #define RADIUS_MAX 4.0 #define PRE_FILTER_RADIUS_MIN 0.1 #define PRE_FILTER_RADIUS_MAX 2.0 #define STRENGTH_MIN 0.1 #define STRENGTH_MAX 100.0 #define OFFSET(x) offsetof(SabContext, x) #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM static const AVOption sab_options[] = { { "luma_radius", "set luma radius", OFFSET(luma.radius), AV_OPT_TYPE_FLOAT, {.dbl=1.0}, RADIUS_MIN, RADIUS_MAX, .flags=FLAGS }, { "lr" , "set luma radius", OFFSET(luma.radius), AV_OPT_TYPE_FLOAT, {.dbl=1.0}, RADIUS_MIN, RADIUS_MAX, .flags=FLAGS }, { "luma_pre_filter_radius", "set luma pre-filter radius", OFFSET(luma.pre_filter_radius), AV_OPT_TYPE_FLOAT, {.dbl=1.0}, PRE_FILTER_RADIUS_MIN, PRE_FILTER_RADIUS_MAX, .flags=FLAGS }, { "lpfr", "set luma pre-filter radius", OFFSET(luma.pre_filter_radius), AV_OPT_TYPE_FLOAT, {.dbl=1.0}, PRE_FILTER_RADIUS_MIN, PRE_FILTER_RADIUS_MAX, .flags=FLAGS }, { "luma_strength", "set luma strength", OFFSET(luma.strength), AV_OPT_TYPE_FLOAT, {.dbl=1.0}, STRENGTH_MIN, STRENGTH_MAX, .flags=FLAGS }, { "ls", "set luma strength", OFFSET(luma.strength), AV_OPT_TYPE_FLOAT, {.dbl=1.0}, STRENGTH_MIN, STRENGTH_MAX, .flags=FLAGS }, { "chroma_radius", "set chroma radius", OFFSET(chroma.radius), AV_OPT_TYPE_FLOAT, {.dbl=RADIUS_MIN-1}, RADIUS_MIN-1, RADIUS_MAX, .flags=FLAGS }, { "cr", "set chroma radius", OFFSET(chroma.radius), AV_OPT_TYPE_FLOAT, {.dbl=RADIUS_MIN-1}, RADIUS_MIN-1, RADIUS_MAX, .flags=FLAGS }, { "chroma_pre_filter_radius", "set chroma pre-filter radius", OFFSET(chroma.pre_filter_radius), AV_OPT_TYPE_FLOAT, {.dbl=PRE_FILTER_RADIUS_MIN-1}, PRE_FILTER_RADIUS_MIN-1, PRE_FILTER_RADIUS_MAX, .flags=FLAGS }, { "cpfr", "set chroma pre-filter radius", OFFSET(chroma.pre_filter_radius), AV_OPT_TYPE_FLOAT, {.dbl=PRE_FILTER_RADIUS_MIN-1}, PRE_FILTER_RADIUS_MIN-1, PRE_FILTER_RADIUS_MAX, .flags=FLAGS }, { "chroma_strength", "set chroma strength", OFFSET(chroma.strength), AV_OPT_TYPE_FLOAT, {.dbl=STRENGTH_MIN-1}, STRENGTH_MIN-1, STRENGTH_MAX, .flags=FLAGS }, { "cs", "set chroma strength", OFFSET(chroma.strength), AV_OPT_TYPE_FLOAT, {.dbl=STRENGTH_MIN-1}, STRENGTH_MIN-1, STRENGTH_MAX, .flags=FLAGS }, { NULL } }; AVFILTER_DEFINE_CLASS(sab); static av_cold int init(AVFilterContext *ctx) { SabContext *sab = ctx->priv; /* make chroma default to luma values, if not explicitly set */ if (sab->chroma.radius < RADIUS_MIN) sab->chroma.radius = sab->luma.radius; if (sab->chroma.pre_filter_radius < PRE_FILTER_RADIUS_MIN) sab->chroma.pre_filter_radius = sab->luma.pre_filter_radius; if (sab->chroma.strength < STRENGTH_MIN) sab->chroma.strength = sab->luma.strength; sab->luma.quality = sab->chroma.quality = 3.0; sab->sws_flags = SWS_POINT; av_log(ctx, AV_LOG_VERBOSE, "luma_radius:%f luma_pre_filter_radius::%f luma_strength:%f " "chroma_radius:%f chroma_pre_filter_radius:%f chroma_strength:%f\n", sab->luma .radius, sab->luma .pre_filter_radius, sab->luma .strength, sab->chroma.radius, sab->chroma.pre_filter_radius, sab->chroma.strength); return 0; } static void close_filter_param(FilterParam *f) { if (f->pre_filter_context) { sws_freeContext(f->pre_filter_context); f->pre_filter_context = NULL; } av_freep(&f->pre_filter_buf); av_freep(&f->dist_coeff); } static av_cold void uninit(AVFilterContext *ctx) { SabContext *sab = ctx->priv; close_filter_param(&sab->luma); close_filter_param(&sab->chroma); } static int open_filter_param(FilterParam *f, int width, int height, unsigned int sws_flags) { SwsVector *vec; SwsFilter sws_f; int i, x, y; int linesize = FFALIGN(width, 8); f->pre_filter_buf = av_malloc(linesize * height); if (!f->pre_filter_buf) return AVERROR(ENOMEM); f->pre_filter_linesize = linesize; vec = sws_getGaussianVec(f->pre_filter_radius, f->quality); sws_f.lumH = sws_f.lumV = vec; sws_f.chrH = sws_f.chrV = NULL; f->pre_filter_context = sws_getContext(width, height, AV_PIX_FMT_GRAY8, width, height, AV_PIX_FMT_GRAY8, sws_flags, &sws_f, NULL, NULL); sws_freeVec(vec); vec = sws_getGaussianVec(f->strength, 5.0); for (i = 0; i < COLOR_DIFF_COEFF_SIZE; i++) { double d; int index = i-COLOR_DIFF_COEFF_SIZE/2 + vec->length/2; if (index < 0 || index >= vec->length) d = 0.0; else d = vec->coeff[index]; f->color_diff_coeff[i] = (int)(d/vec->coeff[vec->length/2]*(1<<12) + 0.5); } sws_freeVec(vec); vec = sws_getGaussianVec(f->radius, f->quality); f->dist_width = vec->length; f->dist_linesize = FFALIGN(vec->length, 8); f->dist_coeff = av_malloc_array(f->dist_width, f->dist_linesize * sizeof(*f->dist_coeff)); if (!f->dist_coeff) { sws_freeVec(vec); return AVERROR(ENOMEM); } for (y = 0; y < vec->length; y++) { for (x = 0; x < vec->length; x++) { double d = vec->coeff[x] * vec->coeff[y]; f->dist_coeff[x + y*f->dist_linesize] = (int)(d*(1<<10) + 0.5); } } sws_freeVec(vec); return 0; } static int config_props(AVFilterLink *inlink) { SabContext *sab = inlink->dst->priv; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); int ret; sab->hsub = desc->log2_chroma_w; sab->vsub = desc->log2_chroma_h; close_filter_param(&sab->luma); ret = open_filter_param(&sab->luma, inlink->w, inlink->h, sab->sws_flags); if (ret < 0) return ret; close_filter_param(&sab->chroma); ret = open_filter_param(&sab->chroma, FF_CEIL_RSHIFT(inlink->w, sab->hsub), FF_CEIL_RSHIFT(inlink->h, sab->vsub), sab->sws_flags); return ret; } #define NB_PLANES 4 static void blur(uint8_t *dst, const int dst_linesize, const uint8_t *src, const int src_linesize, const int w, const int h, FilterParam *fp) { int x, y; FilterParam f = *fp; const int radius = f.dist_width/2; const uint8_t * const src2[NB_PLANES] = { src }; int src2_linesize[NB_PLANES] = { src_linesize }; uint8_t *dst2[NB_PLANES] = { f.pre_filter_buf }; int dst2_linesize[NB_PLANES] = { f.pre_filter_linesize }; sws_scale(f.pre_filter_context, src2, src2_linesize, 0, h, dst2, dst2_linesize); #define UPDATE_FACTOR do { \ int factor; \ factor = f.color_diff_coeff[COLOR_DIFF_COEFF_SIZE/2 + pre_val - \ f.pre_filter_buf[ix + iy*f.pre_filter_linesize]] * f.dist_coeff[dx + dy*f.dist_linesize]; \ sum += src[ix + iy*src_linesize] * factor; \ div += factor; \ } while (0) for (y = 0; y < h; y++) { for (x = 0; x < w; x++) { int sum = 0; int div = 0; int dy; const int pre_val = f.pre_filter_buf[x + y*f.pre_filter_linesize]; if (x >= radius && x < w - radius) { for (dy = 0; dy < radius*2 + 1; dy++) { int dx; int iy = y+dy - radius; iy = avpriv_mirror(iy, h-1); for (dx = 0; dx < radius*2 + 1; dx++) { const int ix = x+dx - radius; UPDATE_FACTOR; } } } else { for (dy = 0; dy < radius*2+1; dy++) { int dx; int iy = y+dy - radius; iy = avpriv_mirror(iy, h-1); for (dx = 0; dx < radius*2 + 1; dx++) { int ix = x+dx - radius; ix = avpriv_mirror(ix, w-1); UPDATE_FACTOR; } } } dst[x + y*dst_linesize] = (sum + div/2) / div; } } } static int filter_frame(AVFilterLink *inlink, AVFrame *inpic) { SabContext *sab = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *outpic; outpic = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!outpic) { av_frame_free(&inpic); return AVERROR(ENOMEM); } av_frame_copy_props(outpic, inpic); blur(outpic->data[0], outpic->linesize[0], inpic->data[0], inpic->linesize[0], inlink->w, inlink->h, &sab->luma); if (inpic->data[2]) { int cw = FF_CEIL_RSHIFT(inlink->w, sab->hsub); int ch = FF_CEIL_RSHIFT(inlink->h, sab->vsub); blur(outpic->data[1], outpic->linesize[1], inpic->data[1], inpic->linesize[1], cw, ch, &sab->chroma); blur(outpic->data[2], outpic->linesize[2], inpic->data[2], inpic->linesize[2], cw, ch, &sab->chroma); } av_frame_free(&inpic); return ff_filter_frame(outlink, outpic); } static const AVFilterPad sab_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .filter_frame = filter_frame, .config_props = config_props, }, { NULL } }; static const AVFilterPad sab_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { NULL } }; AVFilter ff_vf_sab = { .name = "sab", .description = NULL_IF_CONFIG_SMALL("Apply shape adaptive blur."), .priv_size = sizeof(SabContext), .init = init, .uninit = uninit, .query_formats = query_formats, .inputs = sab_inputs, .outputs = sab_outputs, .priv_class = &sab_class, .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC, };
dxjia/ffmpeg-for-android-shared-library
source/ffmpeg/libavfilter/vf_sab.c
C
lgpl-2.1
12,241
/* * Minecraft Forge * Copyright (c) 2016. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.fml.common.functions; import com.google.common.base.Function; public class TypeCastFunction<T> implements Function<Object, T> { private Class<T> type; public TypeCastFunction(Class<T> type) { this.type = type; } @Override public T apply(Object input) { return type.cast(input); } }
SuperUnitato/UnLonely
build/tmp/recompileMc/sources/net/minecraftforge/fml/common/functions/TypeCastFunction.java
Java
lgpl-2.1
1,106
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * http://razor-qt.org, http://lxde.org/ * * Copyright: 2010-2012 LXQt team * Authors: * Petr Vanek <petr@scribus.info> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #ifndef DEFAULTAPPS_H #define DEFAULTAPPS_H #include <QWidget> namespace Ui { class DefaultAppsPage; } class DefaultApps : public QWidget { Q_OBJECT public: explicit DefaultApps(QWidget *parent = 0); ~DefaultApps(); signals: void defaultAppChanged(const QString&, const QString&); public slots: void updateEnvVar(const QString &var, const QString &val); private: Ui::DefaultAppsPage *ui; private slots: void browserButton_clicked(); void terminalButton_clicked(); void browserChanged(); void terminalChanged(); }; #endif // DEFAULTAPPS_H
rbazaud/lxqt-session
lxqt-config-session/defaultappspage.h
C
lgpl-2.1
1,605
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> <script src="resources/js-test-pre.js"></script> </head> <body> <script src="script-tests/parser-xml-close-comment.js"></script> <script src="resources/js-test-post.js"></script> </body> </html>
youfoh/webkit-efl
LayoutTests/fast/js/parser-xml-close-comment.html
HTML
lgpl-2.1
256
package com.puppycrawl.tools.checkstyle.indentation; import java.io.FileInputStream; import java.io.IOException; import java.util.jar.JarInputStream; import java.util.jar.Manifest; // Forcing a commit class InputValidTryResourcesIndent { // Taken from JDK7 java.lang.Package src code. private static Manifest loadManifest(String fn) { try (FileInputStream fis = new FileInputStream(fn); // This should be an error JarInputStream jis = new JarInputStream(fis, false)) { return jis.getManifest(); } catch (IOException e) { return null; } } }
Andrew0701/checkstyle
src/testinputs/com/puppycrawl/tools/checkstyle/indentation/InputValidTryResourcesIndent.java
Java
lgpl-2.1
626
package org.intermine.bio.webservice; /* * Copyright (C) 2002-2016 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.intermine.api.InterMineAPI; import org.intermine.bio.web.export.GFF3Exporter; import org.intermine.bio.web.logic.SequenceFeatureExportUtil; import org.intermine.bio.web.logic.SequenceFeatureExportUtil.InvalidQueryException; import org.intermine.pathquery.PathQuery; import org.intermine.web.context.InterMineContext; import org.intermine.webservice.server.exceptions.BadRequestException; /** * A service for exporting query results as gff3. * @author Alexis Kalderimis. * */ public class GFFQueryService extends BioQueryService { /** * Constructor. * @param im A reference to an InterMine API settings bundle. */ public GFFQueryService(InterMineAPI im) { super(im); } @Override protected String getSuffix() { return ".gff3"; } @Override protected String getContentType() { return "text/x-gff3"; } /** * @param pq pathquery * @return the exporter */ @Override protected GFF3Exporter getExporter(PathQuery pq) { String sourceName = webProperties.getProperty("project.title"); Set<Integer> organisms = null; List<Integer> indexes = new ArrayList<Integer>(); List<String> viewColumns = new ArrayList<String>(pq.getView()); for (int i = 0; i < viewColumns.size(); i++) { indexes.add(Integer.valueOf(i)); } removeFirstItemInPaths(viewColumns); return new GFF3Exporter( getPrintWriter(), indexes, getSoClassNames(), viewColumns, sourceName, organisms, false, getQueryPaths(pq)); } /** * * @return map of SO class names */ static Map<String, String> getSoClassNames() { return new HashMap<String, String>( (Map) InterMineContext.getAttribute(GFF3QueryServlet.SO_CLASS_NAMES)); } /** * @param paths paths */ static void removeFirstItemInPaths(List<String> paths) { for (int i = 0; i < paths.size(); i++) { String path = paths.get(i); paths.set(i, path.substring(path.indexOf(".") + 1, path.length())); } } @Override protected void checkPathQuery(PathQuery pq) throws Exception { try { SequenceFeatureExportUtil.isValidSequenceFeatureQuery(pq); } catch (InvalidQueryException e) { throw new BadRequestException(e.getMessage(), e); } } }
zebrafishmine/intermine
bio/webapp/src/org/intermine/bio/webservice/GFFQueryService.java
Java
lgpl-2.1
2,884
/* ***** BEGIN LICENSE BLOCK ***** * * Copyright (C) 1998 Netscape Communications Corporation. * Copyright (C) 2010 Apple Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * * ***** END LICENSE BLOCK ***** */ gTestfile = 'ToLong-001.js'; /** * Preferred Argument Conversion. * * Passing a JavaScript boolean to a Java method should prefer to call * a Java method of the same name that expects a Java boolean. * */ var SECTION = "Preferred argument conversion: JavaScript Object to Long"; var VERSION = "1_4"; var TITLE = "LiveConnect 3.0 JavaScript to Java Data Type Conversion " + SECTION; startTest(); var TEST_CLASS = applet.createQAObject("com.netscape.javascript.qa.lc3.jsobject.JSObject_006"); function MyObject( value ) { this.value = value; this.valueOf = new Function( "return this.value" ); } function MyFunction() { return; } MyFunction.valueOf = new Function( "return 6060842" ); shouldBeWithErrorCheck( "TEST_CLASS.ambiguous( new String() ) +''", "'LONG'"); shouldBeWithErrorCheck( "TEST_CLASS.ambiguous( new Boolean() ) +''", "'LONG'"); shouldBeWithErrorCheck( "TEST_CLASS.ambiguous( new Number() ) +''", "'LONG'"); shouldBeWithErrorCheck( "TEST_CLASS.ambiguous( new Date(0) ) +''", "'LONG'"); shouldBeWithErrorCheck( "TEST_CLASS.ambiguous( new MyObject(999) ) +''", "'LONG'"); shouldBeWithErrorCheck( "TEST_CLASS.ambiguous( MyFunction ) +''", "'LONG'");
youfoh/webkit-efl
LayoutTests/java/lc3/ConvertJSObject/ToLong-001.js
JavaScript
lgpl-2.1
2,161
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.txn.ee.concurrency; import org.jboss.as.ee.component.Attachments; import org.jboss.as.ee.component.ComponentConfiguration; import org.jboss.as.ee.component.ComponentConfigurator; import org.jboss.as.ee.component.ComponentDescription; import org.jboss.as.ee.component.EEModuleDescription; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.txn.service.TransactionManagerService; /** * Processor which adds the {@link org.jboss.as.ee.concurrent.handle.ContextHandleFactory} to the deployment component's EE Concurrency configuration. * * @author Eduardo Martins * @author <a href="mailto:ropalka@redhat.com">Richard Opalka</a> */ public class EEConcurrencyContextHandleFactoryProcessor implements DeploymentUnitProcessor { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final EEModuleDescription eeModuleDescription = deploymentUnit.getAttachment(Attachments.EE_MODULE_DESCRIPTION); if (eeModuleDescription == null) { return; } final ComponentConfigurator componentConfigurator = new ComponentConfigurator() { @Override public void configure(DeploymentPhaseContext context, ComponentDescription description, final ComponentConfiguration configuration) { final TransactionLeakContextHandleFactory transactionLeakContextHandleFactory = new TransactionLeakContextHandleFactory(); context.requires(TransactionManagerService.INTERNAL_SERVICE_NAME, transactionLeakContextHandleFactory.getTransactionManagerSupplier()); configuration.getConcurrentContext().addFactory(transactionLeakContextHandleFactory); } }; for (ComponentDescription componentDescription : eeModuleDescription.getComponentDescriptions()) { componentDescription.getConfigurators().add(componentConfigurator); } } }
jstourac/wildfly
transactions/src/main/java/org/jboss/as/txn/ee/concurrency/EEConcurrencyContextHandleFactoryProcessor.java
Java
lgpl-2.1
3,267
/** * Copyright (C) 2009 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.pipeline.api; import org.dom4j.Element; import org.dom4j.QName; import org.orbeon.oxf.xml.dom4j.Dom4jUtils; import org.orbeon.saxon.om.NodeInfo; import java.util.HashMap; import java.util.Map; /** * ProcessorDefinition encapsulate a processor name and its associated inputs. A ProcessorDefinition * object can then be used to instantiate and run the given processor. */ public class ProcessorDefinition { private final QName name; private Map<String, Object> entries = new HashMap<String, Object>(); /** * Create a definition. * * @param name the qualified name of the processor, for example "oxf:xslt". */ public ProcessorDefinition(QName name) { this.name = name; } /** * Add an input with the given name and URL. * * @param name the name of the input, for example "config" * @param url the URL that will be connected to the input, for example "oxf:/my-file.xml" */ public void addInput(String name, String url) { entries.put(name, url); } /** * Add an input with the given name and dom4j Element. * * @param name the name of the input, for example "config" * @param element the dom4j Element containing the XML document connected to the input */ public void addInput(String name, Element element) { entries.put(name, element); } /** * Add an input with the given name and TinyTree node. * * @param name the name of the input, for example "config" * @param nodeInfo the TinyTree node containing the XML document connected to the input */ public void addInput(String name, NodeInfo nodeInfo) { entries.put(name, nodeInfo); } /** * Return the configured mappings for the processor inputs. Keys are of type String and refer to * input names. Values are of type String (which must be valid URLs) or dom4j Element * (containing an XML document). * * @return Map of name -> String or Element processor inputs mappings */ public Map<String, Object> getEntries() { return entries; } /** * Return the qualified name of the processor. * * @return the qualified name of the processor */ public QName getName() { return name; } public String toString() { final StringBuilder sb = new StringBuilder("["); sb.append(Dom4jUtils.qNameToExplodedQName(getName())); for (final Map.Entry<String, Object> currentEntry: getEntries().entrySet()) { final String key = currentEntry.getKey(); final Object value = currentEntry.getValue(); sb.append(", "); sb.append(key); sb.append(" -> "); sb.append((value instanceof String) ? value.toString() : "[inline XML document]"); } sb.append(']'); return sb.toString(); } }
wesley1001/orbeon-forms
src/main/java/org/orbeon/oxf/pipeline/api/ProcessorDefinition.java
Java
lgpl-2.1
3,587
/* * Do not modify this file; it is automatically * generated and any modifications will be overwritten. * * @(#) xdc-A71 */ /* * ======== GENERATED SECTIONS ======== * * PROLOGUE * INCLUDES * * INTERNAL DEFINITIONS * MODULE-WIDE CONFIGS * VIRTUAL FUNCTIONS * FUNCTION DECLARATIONS * CONVERTORS * SYSTEM FUNCTIONS * * EPILOGUE * STATE STRUCTURES * PREFIX ALIASES */ /* * ======== PROLOGUE ======== */ #ifndef ti_sysbios_hal_Seconds__include #define ti_sysbios_hal_Seconds__include #ifndef __nested__ #define __nested__ #define ti_sysbios_hal_Seconds__top__ #endif #ifdef __cplusplus #define __extern extern "C" #else #define __extern extern #endif #define ti_sysbios_hal_Seconds___VERS 160 /* * ======== INCLUDES ======== */ #include <xdc/std.h> #include <xdc/runtime/xdc.h> #include <xdc/runtime/Types.h> #include <ti/sysbios/hal/package/package.defs.h> #include <ti/sysbios/interfaces/ISeconds.h> #include <ti/sysbios/hal/package/Seconds_SecondsProxy.h> /* * ======== AUXILIARY DEFINITIONS ======== */ /* * ======== INTERNAL DEFINITIONS ======== */ /* * ======== MODULE-WIDE CONFIGS ======== */ /* Module__diagsEnabled */ typedef xdc_Bits32 CT__ti_sysbios_hal_Seconds_Module__diagsEnabled; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__diagsEnabled ti_sysbios_hal_Seconds_Module__diagsEnabled__C; /* Module__diagsIncluded */ typedef xdc_Bits32 CT__ti_sysbios_hal_Seconds_Module__diagsIncluded; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__diagsIncluded ti_sysbios_hal_Seconds_Module__diagsIncluded__C; /* Module__diagsMask */ typedef xdc_Bits16 *CT__ti_sysbios_hal_Seconds_Module__diagsMask; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__diagsMask ti_sysbios_hal_Seconds_Module__diagsMask__C; /* Module__gateObj */ typedef xdc_Ptr CT__ti_sysbios_hal_Seconds_Module__gateObj; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__gateObj ti_sysbios_hal_Seconds_Module__gateObj__C; /* Module__gatePrms */ typedef xdc_Ptr CT__ti_sysbios_hal_Seconds_Module__gatePrms; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__gatePrms ti_sysbios_hal_Seconds_Module__gatePrms__C; /* Module__id */ typedef xdc_runtime_Types_ModuleId CT__ti_sysbios_hal_Seconds_Module__id; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__id ti_sysbios_hal_Seconds_Module__id__C; /* Module__loggerDefined */ typedef xdc_Bool CT__ti_sysbios_hal_Seconds_Module__loggerDefined; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__loggerDefined ti_sysbios_hal_Seconds_Module__loggerDefined__C; /* Module__loggerObj */ typedef xdc_Ptr CT__ti_sysbios_hal_Seconds_Module__loggerObj; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__loggerObj ti_sysbios_hal_Seconds_Module__loggerObj__C; /* Module__loggerFxn0 */ typedef xdc_runtime_Types_LoggerFxn0 CT__ti_sysbios_hal_Seconds_Module__loggerFxn0; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__loggerFxn0 ti_sysbios_hal_Seconds_Module__loggerFxn0__C; /* Module__loggerFxn1 */ typedef xdc_runtime_Types_LoggerFxn1 CT__ti_sysbios_hal_Seconds_Module__loggerFxn1; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__loggerFxn1 ti_sysbios_hal_Seconds_Module__loggerFxn1__C; /* Module__loggerFxn2 */ typedef xdc_runtime_Types_LoggerFxn2 CT__ti_sysbios_hal_Seconds_Module__loggerFxn2; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__loggerFxn2 ti_sysbios_hal_Seconds_Module__loggerFxn2__C; /* Module__loggerFxn4 */ typedef xdc_runtime_Types_LoggerFxn4 CT__ti_sysbios_hal_Seconds_Module__loggerFxn4; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__loggerFxn4 ti_sysbios_hal_Seconds_Module__loggerFxn4__C; /* Module__loggerFxn8 */ typedef xdc_runtime_Types_LoggerFxn8 CT__ti_sysbios_hal_Seconds_Module__loggerFxn8; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__loggerFxn8 ti_sysbios_hal_Seconds_Module__loggerFxn8__C; /* Module__startupDoneFxn */ typedef xdc_Bool (*CT__ti_sysbios_hal_Seconds_Module__startupDoneFxn)(void); __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Module__startupDoneFxn ti_sysbios_hal_Seconds_Module__startupDoneFxn__C; /* Object__count */ typedef xdc_Int CT__ti_sysbios_hal_Seconds_Object__count; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Object__count ti_sysbios_hal_Seconds_Object__count__C; /* Object__heap */ typedef xdc_runtime_IHeap_Handle CT__ti_sysbios_hal_Seconds_Object__heap; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Object__heap ti_sysbios_hal_Seconds_Object__heap__C; /* Object__sizeof */ typedef xdc_SizeT CT__ti_sysbios_hal_Seconds_Object__sizeof; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Object__sizeof ti_sysbios_hal_Seconds_Object__sizeof__C; /* Object__table */ typedef xdc_Ptr CT__ti_sysbios_hal_Seconds_Object__table; __extern __FAR__ const CT__ti_sysbios_hal_Seconds_Object__table ti_sysbios_hal_Seconds_Object__table__C; /* * ======== VIRTUAL FUNCTIONS ======== */ /* Fxns__ */ struct ti_sysbios_hal_Seconds_Fxns__ { xdc_runtime_Types_Base* __base; const xdc_runtime_Types_SysFxns2 *__sysp; xdc_UInt32 (*get)(void); xdc_Void (*set)(xdc_UInt32); xdc_runtime_Types_SysFxns2 __sfxns; }; /* Module__FXNS__C */ __extern const ti_sysbios_hal_Seconds_Fxns__ ti_sysbios_hal_Seconds_Module__FXNS__C; /* * ======== FUNCTION DECLARATIONS ======== */ /* Module_startup */ #define ti_sysbios_hal_Seconds_Module_startup( state ) (-1) /* Module__startupDone__S */ xdc__CODESECT(ti_sysbios_hal_Seconds_Module__startupDone__S, "ti_sysbios_hal_Seconds_Module__startupDone__S") __extern xdc_Bool ti_sysbios_hal_Seconds_Module__startupDone__S( void ); /* get__E */ #define ti_sysbios_hal_Seconds_get ti_sysbios_hal_Seconds_get__E xdc__CODESECT(ti_sysbios_hal_Seconds_get__E, "ti_sysbios_hal_Seconds_get") __extern xdc_UInt32 ti_sysbios_hal_Seconds_get__E( void ); /* set__E */ #define ti_sysbios_hal_Seconds_set ti_sysbios_hal_Seconds_set__E xdc__CODESECT(ti_sysbios_hal_Seconds_set__E, "ti_sysbios_hal_Seconds_set") __extern xdc_Void ti_sysbios_hal_Seconds_set__E( xdc_UInt32 seconds ); /* * ======== CONVERTORS ======== */ /* Module_upCast */ static inline ti_sysbios_interfaces_ISeconds_Module ti_sysbios_hal_Seconds_Module_upCast( void ) { return (ti_sysbios_interfaces_ISeconds_Module)&ti_sysbios_hal_Seconds_Module__FXNS__C; } /* Module_to_ti_sysbios_interfaces_ISeconds */ #define ti_sysbios_hal_Seconds_Module_to_ti_sysbios_interfaces_ISeconds ti_sysbios_hal_Seconds_Module_upCast /* * ======== SYSTEM FUNCTIONS ======== */ /* Module_startupDone */ #define ti_sysbios_hal_Seconds_Module_startupDone() ti_sysbios_hal_Seconds_Module__startupDone__S() /* Object_heap */ #define ti_sysbios_hal_Seconds_Object_heap() ti_sysbios_hal_Seconds_Object__heap__C /* Module_heap */ #define ti_sysbios_hal_Seconds_Module_heap() ti_sysbios_hal_Seconds_Object__heap__C /* Module_id */ static inline CT__ti_sysbios_hal_Seconds_Module__id ti_sysbios_hal_Seconds_Module_id( void ) { return ti_sysbios_hal_Seconds_Module__id__C; } /* Module_hasMask */ static inline xdc_Bool ti_sysbios_hal_Seconds_Module_hasMask( void ) { return ti_sysbios_hal_Seconds_Module__diagsMask__C != NULL; } /* Module_getMask */ static inline xdc_Bits16 ti_sysbios_hal_Seconds_Module_getMask( void ) { return ti_sysbios_hal_Seconds_Module__diagsMask__C != NULL ? *ti_sysbios_hal_Seconds_Module__diagsMask__C : 0; } /* Module_setMask */ static inline xdc_Void ti_sysbios_hal_Seconds_Module_setMask( xdc_Bits16 mask ) { if (ti_sysbios_hal_Seconds_Module__diagsMask__C != NULL) *ti_sysbios_hal_Seconds_Module__diagsMask__C = mask; } /* * ======== EPILOGUE ======== */ #ifdef ti_sysbios_hal_Seconds__top__ #undef __nested__ #endif #endif /* ti_sysbios_hal_Seconds__include */ /* * ======== STATE STRUCTURES ======== */ #if defined(__config__) || (!defined(__nested__) && defined(ti_sysbios_hal_Seconds__internalaccess)) #ifndef ti_sysbios_hal_Seconds__include_state #define ti_sysbios_hal_Seconds__include_state #endif /* ti_sysbios_hal_Seconds__include_state */ #endif /* * ======== PREFIX ALIASES ======== */ #if !defined(__nested__) && !defined(ti_sysbios_hal_Seconds__nolocalnames) #ifndef ti_sysbios_hal_Seconds__localnames__done #define ti_sysbios_hal_Seconds__localnames__done /* module prefix */ #define Seconds_get ti_sysbios_hal_Seconds_get #define Seconds_set ti_sysbios_hal_Seconds_set #define Seconds_Module_name ti_sysbios_hal_Seconds_Module_name #define Seconds_Module_id ti_sysbios_hal_Seconds_Module_id #define Seconds_Module_startup ti_sysbios_hal_Seconds_Module_startup #define Seconds_Module_startupDone ti_sysbios_hal_Seconds_Module_startupDone #define Seconds_Module_hasMask ti_sysbios_hal_Seconds_Module_hasMask #define Seconds_Module_getMask ti_sysbios_hal_Seconds_Module_getMask #define Seconds_Module_setMask ti_sysbios_hal_Seconds_Module_setMask #define Seconds_Object_heap ti_sysbios_hal_Seconds_Object_heap #define Seconds_Module_heap ti_sysbios_hal_Seconds_Module_heap #define Seconds_Module_upCast ti_sysbios_hal_Seconds_Module_upCast #define Seconds_Module_to_ti_sysbios_interfaces_ISeconds ti_sysbios_hal_Seconds_Module_to_ti_sysbios_interfaces_ISeconds /* proxies */ #include <ti/sysbios/hal/package/Seconds_SecondsProxy.h> #endif /* ti_sysbios_hal_Seconds__localnames__done */ #endif
sanyaade-iot/Energia
hardware/common/ti/sysbios/hal/Seconds.h
C
lgpl-2.1
9,389
@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^<target^>` where ^<target^> is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\python-scss.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\python-scss.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end
n6g7/django_markdown
docs/make.bat
Batchfile
lgpl-3.0
4,521
/* * casocklib - An asynchronous communication library for C++ * --------------------------------------------------------- * Copyright (C) 2010 Leandro Costa * * This file is part of casocklib. * * casocklib is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * casocklib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with casocklib. If not, see <http://www.gnu.org/licenses/>. */ /*! * \file casock/rpc/protobuf/server/RPCCallHandlerFactory.h * \brief [brief description] * \author Leandro Costa * \date 2010 * * $LastChangedDate$ * $LastChangedBy$ * $Revision$ */ #ifndef __CASOCKLIB__CASOCK_RPC_SIGIO_PROTOBUF_SERVER__RPC_CALL_HANDLER_FACTORY_H_ #define __CASOCKLIB__CASOCK_RPC_SIGIO_PROTOBUF_SERVER__RPC_CALL_HANDLER_FACTORY_H_ namespace casock { namespace rpc { namespace protobuf { namespace server { class RPCCallHandler; class RPCCallQueue; class RPCCallHandlerFactory { public: virtual RPCCallHandler* buildRPCCallHandler (RPCCallQueue& rCallQueue) const = 0; }; } } } } #endif // __CASOCKLIB__CASOCK_RPC_SIGIO_PROTOBUF_SERVER__RPC_CALL_HANDLER_FACTORY_H_
iCoolcoder/casocklib
src/casock/rpc/protobuf/server/RPCCallHandlerFactory.h
C
lgpl-3.0
1,647
#string workflowName #string creationDate #list out_out echo "Workflow name: ${workflowName}" echo "Created: ${creationDate}" echo "Result of step1.sh:" for s in "${out_out[@]}" do echo ${s} done echo "(FOR TESTING PURPOSES: your runid is ${runid})"
RoanKanninga/molgenis-compute
molgenis-compute-core/src/main/resources/workflows/benchmark.5.1/protocols/step2.runtime.automapping.sh
Shell
lgpl-3.0
257
// stdafx.cpp : source file that includes just the standard includes // testmav.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
fatadama/mavlink-vscl
pymavlink/generator/C/test/windows/stdafx.cpp
C++
lgpl-3.0
286
/* * @BEGIN LICENSE * * Psi4: an open-source quantum chemistry software package * * Copyright (c) 2007-2021 The Psi4 Developers. * * The copyrights for code used from other parties are included in * the corresponding files. * * This file is part of Psi4. * * Psi4 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * Psi4 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with Psi4; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @END LICENSE */ /*! \file \ingroup CCENERGY \brief Enter brief description of file here */ #include <cstdio> #include <cstdlib> #include <cmath> #include "psi4/libciomr/libciomr.h" #include "psi4/libdpd/dpd.h" #include "psi4/libqt/qt.h" #include "MOInfo.h" #include "Params.h" #include "psi4/cc/ccwave.h" namespace psi { namespace ccenergy { /* Computes a modified D1 diagnostic developed by T.J. Lee, but not yet * published. * */ double CCEnergyWavefunction::new_d1diag_t1_rohf() { int nclsd, nuocc, nopen; double **T1_hp, **T1_hx, **T1_xp, **T1_sq; double *E, **C; double max_hp = 0.0, max_xp = 0.0, max_hx = 0.0, max; dpdfile2 T1_a, T1_b; auto nirreps = moinfo_.nirreps; global_dpd_->file2_init(&T1_a, PSIF_CC_OEI, 0, 0, 1, "tIA"); global_dpd_->file2_mat_init(&T1_a); global_dpd_->file2_mat_rd(&T1_a); global_dpd_->file2_init(&T1_b, PSIF_CC_OEI, 0, 0, 1, "tia"); global_dpd_->file2_mat_init(&T1_b); global_dpd_->file2_mat_rd(&T1_b); for (int h = 0; h < nirreps; h++) { nclsd = moinfo_.clsdpi[h]; nuocc = moinfo_.uoccpi[h]; nopen = moinfo_.openpi[h]; if (nclsd && nuocc) { T1_hp = block_matrix(nclsd, nuocc); for (int i = 0; i < nclsd; i++) for (int j = 0; j < nuocc; j++) T1_hp[i][j] = (T1_a.matrix[h][i][j] + T1_b.matrix[h][i][j]) / 2.; T1_sq = block_matrix(nclsd, nclsd); C_DGEMM('n', 't', nclsd, nclsd, nuocc, 1.0, &(T1_hp[0][0]), nuocc, &(T1_hp[0][0]), nuocc, 0.0, &(T1_sq[0][0]), nclsd); E = init_array(nclsd); C = block_matrix(nclsd, nclsd); sq_rsp(nclsd, nclsd, T1_sq, E, 0, C, 1e-12); for (int i = 0; i < nclsd; i++) if (E[i] > max_hp) max_hp = E[i]; free(E); free_block(C); free_block(T1_sq); free_block(T1_hp); } if (nclsd && nopen) { T1_hx = block_matrix(nclsd, nopen); for (int i = 0; i < nclsd; i++) for (int j = 0; j < nopen; j++) T1_hx[i][j] = T1_b.matrix[h][i][nuocc + j] / sqrt(2.); T1_sq = block_matrix(nclsd, nclsd); C_DGEMM('n', 't', nclsd, nclsd, nopen, 1.0, &(T1_hx[0][0]), nopen, &(T1_hx[0][0]), nopen, 0.0, &(T1_sq[0][0]), nclsd); E = init_array(nclsd); C = block_matrix(nclsd, nclsd); sq_rsp(nclsd, nclsd, T1_sq, E, 0, C, 1e-12); for (int i = 0; i < nclsd; i++) if (E[i] > max_hx) max_hx = E[i]; free(E); free_block(C); free_block(T1_sq); free_block(T1_hx); } if (nopen && nuocc) { T1_xp = block_matrix(nopen, nuocc); for (int i = 0; i < nopen; i++) for (int j = 0; j < nuocc; j++) T1_xp[i][j] = T1_a.matrix[h][nclsd + i][j] / sqrt(2.); T1_sq = block_matrix(nopen, nopen); C_DGEMM('n', 't', nopen, nopen, nuocc, 1.0, &(T1_xp[0][0]), nuocc, &(T1_xp[0][0]), nuocc, 0.0, &(T1_sq[0][0]), nopen); E = init_array(nopen); C = block_matrix(nopen, nopen); sq_rsp(nopen, nopen, T1_sq, E, 0, C, 1e-12); for (int i = 0; i < nopen; i++) if (E[i] > max_xp) max_xp = E[i]; free(E); free_block(C); free_block(T1_sq); free_block(T1_xp); } } global_dpd_->file2_mat_close(&T1_a); global_dpd_->file2_close(&T1_a); global_dpd_->file2_mat_close(&T1_b); global_dpd_->file2_close(&T1_b); max_hp = sqrt(max_hp); max_hx = sqrt(max_hx); max_xp = sqrt(max_xp); /* outfile->Printf( "ND1: hp=%8.6f hx=%8.6f xp=%8.6f\n", max_hp, max_hx, max_xp); */ max = max_hp; if (max_hx > max) max = max_hx; if (max_xp > max) max = max_xp; return max; } double CCEnergyWavefunction::new_d1diag() { double norm = 0.0; if (params_.ref == 0) { /** RHF **/ norm = d1diag_t1_rhf(); } else if (params_.ref == 1) { /** ROHF **/ norm = new_d1diag_t1_rohf(); } return norm; } } // namespace ccenergy } // namespace psi
lothian/psi4
psi4/src/psi4/cc/ccenergy/new_d1diag.cc
C++
lgpl-3.0
5,165
"""Fixer that changes raw_input(...) into input(...).""" # Author: Andre Roberge # Local imports from .. import fixer_base from ..fixer_util import Name class FixRawInput(fixer_base.BaseFix): BM_compatible = True PATTERN = """ power< name='raw_input' trailer< '(' [any] ')' > any* > """ def transform(self, node, results): name = results["name"] name.replace(Name("input", prefix=name.prefix))
Orav/kbengine
kbe/src/lib/python/Lib/lib2to3/fixes/fix_raw_input.py
Python
lgpl-3.0
471
package Genome::Model::Event::Build::ReferenceAlignment::RefCov; #REVIEW fdu 11/19/2009 #1. Fix help_detail use strict; use warnings; use Genome; use Genome::Utility::List; use Genome::Utility::Email; class Genome::Model::Event::Build::ReferenceAlignment::RefCov { is => ['Genome::Model::Event'], has => [ _sorted_bams => { is => 'Array', is_optional => 1, }, ], }; sub bsub_rusage { return "-R 'select[type==LINUX64]'"; } sub sorted_instrument_data { my $self = shift; my $build = $self->build; my @sorted_data = sort { $a->id cmp $b->id } $build->instrument_data; return @sorted_data; } sub sorted_instrument_data_ids { my $self = shift; my @ids; my @sorted_instrument_data = $self->sorted_instrument_data; my $build = $self->build; for my $instrument_data (@sorted_instrument_data) { my @alignments = $build->alignment_results_for_instrument_data($instrument_data); unless (@alignments) { $self->error_message('No alignments found for instrument data '. $instrument_data->id); return; } for my $alignment (@alignments) { my @bam_files = $alignment->alignment_bam_file_paths; unless (@bam_files) { next; } if ($alignment->force_fragment) { push @ids, $alignment->instrument_data_id; } else { push @ids, $alignment->instrument_data_id; } } } return @ids; } sub sorted_bam_files { my $self = shift; my @sorted_bam_files; my $build = $self->build; unless (defined($self->_sorted_bams)) { my @sorted_instrument_data = $self->sorted_instrument_data; for my $instrument_data (@sorted_instrument_data) { my @alignments = $build->alignment_results_for_instrument_data($instrument_data); unless (@alignments) { $self->error_message('No alignments found for instrument data '. $instrument_data->id); return; } for my $alignment (@alignments) { push @sorted_bam_files, $alignment->alignment_bam_file_paths; } } $self->_sorted_bams(\@sorted_bam_files); } else { @sorted_bam_files = @{$self->_sorted_bams}; } return @sorted_bam_files;; } sub progression_array_ref { my $self = shift; my @sorted_bam_files = $self->sorted_bam_files; my @progression; my @progression_instance; for my $bam_file (@sorted_bam_files) { push @progression_instance, $bam_file; my @current_instance = @progression_instance; push @progression, \@current_instance; } return \@progression; } sub progression_count { my $self = shift; my @sorted_bam_files = $self->sorted_bam_files; my $progression_count = scalar(@sorted_bam_files); return $progression_count; } sub execute { my $self = shift; my $ref_cov_dir = $self->build->reference_coverage_directory; unless (Genome::Sys->create_directory($ref_cov_dir)) { $self->error_message('Failed to create ref_cov directory '. $ref_cov_dir .": $!"); return; } # Run ref-cov on each accumulated iteration or progression # produces a reference coverage stats file for each iteration and relative coverage unless ($self->verify_progressions) { my $progression_array_ref = $self->progression_array_ref; $self->debug_message('Progressions look like: '. Data::Dumper::Dumper($progression_array_ref)); #parallelization starts here require Workflow::Simple; my $op = Workflow::Operation->create( name => 'RefCov Progression', operation_type => Workflow::OperationType::Command->get('Genome::Model::Tools::BioSamtools::ProgressionInstance') ); $op->parallel_by('bam_files'); my $output; if ($self->model->duplication_handler_name eq 'samtools') { Genome::Sys->disconnect_default_handles; $output = Workflow::Simple::run_workflow_lsf( $op, 'output_directory' => $ref_cov_dir, 'bam_files' => $progression_array_ref, 'target_query_file' => $self->build->transcript_bed_file, 'samtools_version' => $self->model->duplication_handler_version, ); } else { Genome::Sys->disconnect_default_handles; $output = Workflow::Simple::run_workflow_lsf( $op, 'output_directory' => $ref_cov_dir, 'bam_files' => $progression_array_ref, 'target_query_file' => $self->build->transcript_bed_file, ); } #check workflow for errors if (!defined $output) { foreach my $error (@Workflow::Simple::ERROR) { $self->error_message($error->error); } return; } else { my $results = $output->{result}; my $result_instances = $output->{instance}; for (my $i = 0; $i < scalar(@$results); $i++) { my $rv = $results->[$i]; if ($rv != 1) { $self->error_message("Workflow had an error while running progression instance: ". $result_instances->[$i]); die($self->error_message); } } } } unless ($self->verify_progressions) { $self->error_message('Failed to verify progression directories after running ref-cov'); return; } my @progression_stats_files = $self->progression_stats_files; my $final_stats_file = $progression_stats_files[-1]; unless (Genome::Sys->validate_file_for_reading($final_stats_file)) { $self->error_message("Failed to validate stats file '$final_stats_file' for reading: $!"); die($self->error_message); } my $stats_file = $self->build->coverage_stats_file; unless ( -l $stats_file) { unless (symlink($final_stats_file,$stats_file)) { $self->error_message("Failed to create final stats progression symlink: $!"); die($self->error_message); } } my @final_bias_files = glob ($ref_cov_dir .'/bias_'. $self->progression_count .'_*'); for my $final_bias_file (@final_bias_files) { unless ($final_bias_file =~ /bias_\d+_(\w+)/) { $self->error_message('Failed to parse bias file name '. $final_bias_file); die($self->error_message); } my $size = $1; my $bias_file = $self->build->relative_coverage_file($size); unless ( -l $bias_file) { unless (symlink($final_bias_file,$bias_file)) { $self->error_message("Failed to create final bias progression symlink: $!"); die($self->error_message); } } } my @progression_instrument_data_ids = $self->sorted_instrument_data_ids; unless (-s $self->build->coverage_progression_file) { unless (Genome::Model::Tools::BioSamtools::Progression->execute( stats_files => \@progression_stats_files, instrument_data_ids => \@progression_instrument_data_ids, sample_name => $self->model->subject_name, output_file => $self->build->coverage_progression_file, ) ) { $self->error_message('Failed to execute the progression for progressions: '. join("\n",@progression_stats_files)); die($self->error_message); } } unless (-s $self->build->breakdown_file) { my $breakdown = Genome::Model::Tools::BioSamtools::Breakdown->execute( bam_file => $self->build->whole_rmdup_bam_file, output_file => $self->build->breakdown_file, ); } my $report_generator = Genome::Model::ReferenceAlignment::Report::ReferenceCoverage->create(build_id => $self->build->id); unless ($report_generator) { $self->error_message('Error creating ReferenceCoverage report generator: '. Genome::Model::ReferenceAlignment::Report::ReferenceCoverage->error_message()); die($self->error_message); } my $report = $report_generator->generate_report; unless ($report) { $self->error_message('Error generating report '. $report_generator->report_name .': '. Genome::Model::ReferenceAlignment::Report::ReferenceCoverage->error_message()); $report_generator->delete; die($self->error_message); } if ($self->build->add_report($report)) { $self->debug_message('Saved report: '. $report); } else { $self->error_message('Error saving '. $report.'. Error: '. $self->build->error_message); die($self->error_message); } my $xsl_file = $report_generator->get_xsl_file_for_html; unless (-e $xsl_file) { $self->error_message('Failed to find xsl file for ReferenceCoverage report'); die($self->error_message); } my $xslt = Genome::Report::XSLT->transform_report( report => $report, xslt_file => $xsl_file, ); unless ($xslt) { $self->error_message('Failed to generate XSLT for ReferenceCoverage report'); die($self->error_message); } my $report_subdirectory = $self->build->reports_directory .'/'. $report->name_to_subdirectory($report->name); my $report_file = $report_subdirectory .'/report.'. ($xslt->{output_type} || 'html'); my $fh = Genome::Sys->open_file_for_writing( $report_file ); $fh->print( $xslt->{content} ); $fh->close; my $link = Genome::Utility::List::join_with_single_slash($ENV{GENOME_SYS_SERVICES_FILES_URL}, $report_file); send_email_report( to => undef, # don't actually send the email anymore subject => 'Genome Model '. $self->model->name .' Reference Coverage Report for Build '. $self->build->id, body => $link, ); return $self->verify_successful_completion; } sub send_email_report { my $self = shift; my %params = @_; if ($params{to}) { Genome::Utility::Email::send(%params); } } sub progression_stats_files { my $self = shift; my @stats_files = map { $self->build->reference_coverage_directory .'/STATS_'. $_ .'.tsv' } (1 .. $self->progression_count); return @stats_files; } sub verify_progressions { my $self = shift; my @progression_stats_files = $self->progression_stats_files; unless (scalar(@progression_stats_files)) { return; } for my $progression_stats_file (@progression_stats_files) { unless (-e $progression_stats_file) { return; } unless (-f $progression_stats_file) { return; } unless (-s $progression_stats_file) { return; } } return 1; } sub verify_successful_completion { my $self = shift; unless ($self->verify_progressions) { $self->error_message('Failed to verify progressions!'); die($self->error_message); } my @files = ( $self->build->coverage_progression_file, $self->build->coverage_stats_file, $self->build->breakdown_file ); my @SIZES = qw/SMALL MEDIUM LARGE/; for my $size (@SIZES) { push @files, $self->build->relative_coverage_file($size); } for my $file (@files) { $self->check_output_file_existence($file); } return 1; } sub check_output_file_existence { my $self = shift; my $file = shift; unless (-e $file) { $self->error_message('Missing reference coverage output file '. $file); return; } } 1;
apregier/genome
lib/perl/Genome/Model/Event/Build/ReferenceAlignment/RefCov.pm
Perl
lgpl-3.0
11,666
/* * @BEGIN LICENSE * * Psi4: an open-source quantum chemistry software package * * Copyright (c) 2007-2021 The Psi4 Developers. * * The copyrights for code used from other parties are included in * the corresponding files. * * This file is part of Psi4. * * Psi4 is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * Psi4 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with Psi4; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @END LICENSE */ /*! \file \ingroup CCLAMBDA \brief Enter brief description of file here */ #include "psi4/libdpd/dpd.h" #include "psi4/libqt/qt.h" #include "psi4/libciomr/libciomr.h" namespace psi { namespace cclambda { /* halftrans(): Routine to transform the last two indices of a dpdbuf4 ** between the MO and SO bases. ** ** dpdbuf4 *Buf1: Pointer to the MO dpdbuf4 (already initialized) ** dpdbuf4 *Buf2: Pointer to the SO dpdbuf4 (already initialized). ** double ***C: Pointer to the transformation matrix (symmetry blocked, SO x MO) ** int nirreps: The number of irreps in the point group ** int **mo_row: A lookup array. For a dpdbuf4 with MO indices (ij,ab), ** given the irrep h of ij (= ab) and the irrep of orbital a, the ** array returns the offset of the start of the set of b molecular ** orbitals. ** int **so_row: Like mo_row, but for a dpdbuf4 with the last two ** indices in the SO basis. ** int *mospi: The number of MO's per irrep. ** int *sospi: The number of SO's per irrep. ** int type: 0 = MO --> SO; 1 = SO --> MO ** double alpha: multiplicative factor for the transformation ** double beta: multiplicative factor for the target */ void halftrans(dpdbuf4 *Buf1, int dpdnum1, dpdbuf4 *Buf2, int dpdnum2, double ***C, int nirreps, int **mo_row, int **so_row, int *mospi, int *sospi, int type, double alpha, double beta) { int h, Gc, Gd, cd, pq, ij; double **X; for (h = 0; h < nirreps; h++) { dpd_set_default(dpdnum1); global_dpd_->buf4_mat_irrep_init(Buf1, h); dpd_set_default(dpdnum2); global_dpd_->buf4_mat_irrep_init(Buf2, h); if (type == 0) { /* alpha * Buf1 --> beta * Buf2 */ if (alpha != 0.0) { dpd_set_default(dpdnum1); global_dpd_->buf4_mat_irrep_rd(Buf1, h); } if (beta != 0.0) { dpd_set_default(dpdnum2); global_dpd_->buf4_mat_irrep_rd(Buf2, h); } } if (type == 1) { /* alpha * Buf2 --> beta * Buf1 */ if (alpha != 0.0) { dpd_set_default(dpdnum2); global_dpd_->buf4_mat_irrep_rd(Buf2, h); } if (beta != 0.0) { dpd_set_default(dpdnum1); global_dpd_->buf4_mat_irrep_rd(Buf1, h); } } for (Gc = 0; Gc < nirreps; Gc++) { Gd = h ^ Gc; cd = mo_row[h][Gc]; pq = so_row[h][Gc]; if (mospi[Gc] && mospi[Gd] && sospi[Gc] && sospi[Gd]) { if (type == 0) { X = block_matrix(mospi[Gc], sospi[Gd]); for (ij = 0; ij < Buf1->params->rowtot[h]; ij++) { C_DGEMM('n', 't', mospi[Gc], sospi[Gd], mospi[Gd], 1.0, &(Buf1->matrix[h][ij][cd]), mospi[Gd], &(C[Gd][0][0]), mospi[Gd], 0.0, &(X[0][0]), sospi[Gd]); C_DGEMM('n', 'n', sospi[Gc], sospi[Gd], mospi[Gc], alpha, &(C[Gc][0][0]), mospi[Gc], &(X[0][0]), sospi[Gd], beta, &(Buf2->matrix[h][ij][pq]), sospi[Gd]); } } else { X = block_matrix(sospi[Gc], mospi[Gd]); for (ij = 0; ij < Buf1->params->rowtot[h]; ij++) { C_DGEMM('n', 'n', sospi[Gc], mospi[Gd], sospi[Gd], 1.0, &(Buf2->matrix[h][ij][pq]), sospi[Gd], &(C[Gd][0][0]), mospi[Gd], 0.0, &(X[0][0]), mospi[Gd]); C_DGEMM('t', 'n', mospi[Gc], mospi[Gd], sospi[Gc], alpha, &(C[Gc][0][0]), mospi[Gc], &(X[0][0]), mospi[Gd], beta, &(Buf1->matrix[h][ij][cd]), mospi[Gd]); } } free_block(X); } } dpd_set_default(dpdnum1); if (type == 1) global_dpd_->buf4_mat_irrep_wrt(Buf1, h); global_dpd_->buf4_mat_irrep_close(Buf1, h); dpd_set_default(dpdnum2); if (type == 0) global_dpd_->buf4_mat_irrep_wrt(Buf2, h); global_dpd_->buf4_mat_irrep_close(Buf2, h); } } } // namespace cclambda } // namespace psi
lothian/psi4
psi4/src/psi4/cc/cclambda/halftrans.cc
C++
lgpl-3.0
5,190
<?php /* * $Id$ * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\ORM\Query\AST; /** * OrderByItem ::= (ResultVariable | StateFieldPathExpression) ["ASC" | "DESC"] * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @version $Revision: 3938 $ * @author Guilherme Blanco <guilhermeblanco@hotmail.com> * @author Jonathan Wage <jonwage@gmail.com> * @author Roman Borschel <roman@code-factory.org> */ class OrderByItem extends Node { public $expression; public $type; public function __construct($expression) { $this->expression = $expression; } public function isAsc() { return strtoupper($this->type) == 'ASC'; } public function isDesc() { return strtoupper($this->type) == 'DESC'; } public function dispatch($sqlWalker) { return $sqlWalker->walkOrderByItem($this); } }
alpho07/NQCL_LIMS
application/libraries/Doctrine_/Doctrine/ORM/Query/AST/OrderByItem.php
PHP
unlicense
1,955
# WWWSearch backend, with queries updating the is-db (optionally) # Uses WWW::Search::Google and WWW::Search # originally Google.pl, drastically altered. use strict; package W3Search; my @engines; my $no_W3Search; BEGIN { $no_W3Search = 0; eval "use WWW::Search"; $no_W3Search++ if $@; eval "use WWW::Search::Google"; $no_W3Search++ if $@; @engines = qw(AltaVista Dejanews Excite Gopher HotBot Infoseek Lycos Magellan PLweb SFgate Simple Verity Google); $W3Search::regex = join '|', @engines; } sub forking_W3Search { if ($no_W3Search) { &main::status("W3Search: this requires WWW::Search::Google to operate."); return ''; } my ($where, $what, $type, $callback) = @_; $SIG{CHLD} = 'IGNORE'; my $pid = eval { fork() }; # catch non-forking OSes and other errors return 'NOREPLY' if $pid; # parent does nothing $callback->(W3Search($where, $what, $type)); exit 0 if defined $pid; # child exits, non-forking OS returns } sub W3Search { if ($no_W3Search) { &status("WWW search requires WWW::Search and WWW::Search::Google"); return 'sorry, can\'t do that'; } else { my ($where, $what, $type) = @_; my @matches = grep { lc($_) eq lc($where) ? $_ : undef } @engines; if (!@matches) { return "i don't know how to check '$where'"; } else { $where = shift @matches; } my $Search = new WWW::Search($where); my $Query = WWW::Search::escape_query($what); $Search->native_query($Query); my ($Result, $r, $count); while ($r = $Search->next_result()) { if ($Result) { $Result .= " or ".$r->url(); } else { $Result = $r->url(); } last if ++$count >= 3; } if ($Result) { if ($type =~ /update/) { $main::correction_plausible++ if $type =~ /force/i; $main::addressed++; $main::googling = 1; &main::update($what, "is", $Result); $main::googling = 0; } return "$where says $what is $Result"; } else { return "$where can't find $what"; } } } 1;
craigbro/tichy
bot5/src/W3Search.pl
Perl
unlicense
2,019
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/cloudformation/model/EstimateTemplateCostResult.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <utility> using namespace Aws::CloudFormation::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils; using namespace Aws; EstimateTemplateCostResult::EstimateTemplateCostResult() { } EstimateTemplateCostResult::EstimateTemplateCostResult(const AmazonWebServiceResult<XmlDocument>& result) { *this = result; } EstimateTemplateCostResult& EstimateTemplateCostResult::operator =(const AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode.FirstChild("EstimateTemplateCostResult"); if(!resultNode.IsNull()) { XmlNode urlNode = resultNode.FirstChild("Url"); if(urlNode.IsNull()) { urlNode = resultNode; } if(!urlNode.IsNull()) { m_url = StringUtils::Trim(urlNode.GetText().c_str()); } } XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); m_responseMetadata = responseMetadataNode; return *this; }
d9magai/aws-sdk-cpp
aws-cpp-sdk-cloudformation/source/model/EstimateTemplateCostResult.cpp
C++
apache-2.0
1,799
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/redshift/model/DescribeClusterSnapshotsResult.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <utility> using namespace Aws::Redshift::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils; using namespace Aws; DescribeClusterSnapshotsResult::DescribeClusterSnapshotsResult() { } DescribeClusterSnapshotsResult::DescribeClusterSnapshotsResult(const AmazonWebServiceResult<XmlDocument>& result) { *this = result; } DescribeClusterSnapshotsResult& DescribeClusterSnapshotsResult::operator =(const AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode.FirstChild("DescribeClusterSnapshotsResult"); if(!resultNode.IsNull()) { XmlNode markerNode = resultNode.FirstChild("Marker"); if(markerNode.IsNull()) { markerNode = resultNode; } if(!markerNode.IsNull()) { m_marker = StringUtils::Trim(markerNode.GetText().c_str()); } XmlNode snapshotsNode = resultNode.FirstChild("Snapshots"); if(!snapshotsNode.IsNull()) { XmlNode snapshotsMember = snapshotsNode.FirstChild("Snapshot"); while(!snapshotsMember.IsNull()) { m_snapshots.push_back(snapshotsMember); snapshotsMember = snapshotsMember.NextNode("Snapshot"); } } } XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); m_responseMetadata = responseMetadataNode; return *this; }
d9magai/aws-sdk-cpp
aws-cpp-sdk-redshift/source/model/DescribeClusterSnapshotsResult.cpp
C++
apache-2.0
2,186
package org.apache.cassandra.hadoop.cql3; /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ import java.io.FileInputStream; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.Arrays; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import org.apache.cassandra.hadoop.ConfigHelper; import org.apache.cassandra.io.util.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import com.datastax.driver.core.AuthProvider; import com.datastax.driver.core.PlainTextAuthProvider; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.HostDistance; import com.datastax.driver.core.PoolingOptions; import com.datastax.driver.core.ProtocolOptions; import com.datastax.driver.core.QueryOptions; import com.datastax.driver.core.SSLOptions; import com.datastax.driver.core.SocketOptions; import com.datastax.driver.core.policies.LoadBalancingPolicy; import com.google.common.base.Optional; public class CqlConfigHelper { private static final String INPUT_CQL_COLUMNS_CONFIG = "cassandra.input.columnfamily.columns"; private static final String INPUT_CQL_PAGE_ROW_SIZE_CONFIG = "cassandra.input.page.row.size"; private static final String INPUT_CQL_WHERE_CLAUSE_CONFIG = "cassandra.input.where.clause"; private static final String INPUT_CQL = "cassandra.input.cql"; private static final String USERNAME = "cassandra.username"; private static final String PASSWORD = "cassandra.password"; private static final String INPUT_NATIVE_PORT = "cassandra.input.native.port"; private static final String INPUT_NATIVE_CORE_CONNECTIONS_PER_HOST = "cassandra.input.native.core.connections.per.host"; private static final String INPUT_NATIVE_MAX_CONNECTIONS_PER_HOST = "cassandra.input.native.max.connections.per.host"; private static final String INPUT_NATIVE_MIN_SIMULT_REQ_PER_CONNECTION = "cassandra.input.native.min.simult.reqs.per.connection"; private static final String INPUT_NATIVE_MAX_SIMULT_REQ_PER_CONNECTION = "cassandra.input.native.max.simult.reqs.per.connection"; private static final String INPUT_NATIVE_CONNECTION_TIMEOUT = "cassandra.input.native.connection.timeout"; private static final String INPUT_NATIVE_READ_CONNECTION_TIMEOUT = "cassandra.input.native.read.connection.timeout"; private static final String INPUT_NATIVE_RECEIVE_BUFFER_SIZE = "cassandra.input.native.receive.buffer.size"; private static final String INPUT_NATIVE_SEND_BUFFER_SIZE = "cassandra.input.native.send.buffer.size"; private static final String INPUT_NATIVE_SOLINGER = "cassandra.input.native.solinger"; private static final String INPUT_NATIVE_TCP_NODELAY = "cassandra.input.native.tcp.nodelay"; private static final String INPUT_NATIVE_REUSE_ADDRESS = "cassandra.input.native.reuse.address"; private static final String INPUT_NATIVE_KEEP_ALIVE = "cassandra.input.native.keep.alive"; private static final String INPUT_NATIVE_AUTH_PROVIDER = "cassandra.input.native.auth.provider"; private static final String INPUT_NATIVE_SSL_TRUST_STORE_PATH = "cassandra.input.native.ssl.trust.store.path"; private static final String INPUT_NATIVE_SSL_KEY_STORE_PATH = "cassandra.input.native.ssl.key.store.path"; private static final String INPUT_NATIVE_SSL_TRUST_STORE_PASSWARD = "cassandra.input.native.ssl.trust.store.password"; private static final String INPUT_NATIVE_SSL_KEY_STORE_PASSWARD = "cassandra.input.native.ssl.key.store.password"; private static final String INPUT_NATIVE_SSL_CIPHER_SUITES = "cassandra.input.native.ssl.cipher.suites"; private static final String INPUT_NATIVE_PROTOCOL_VERSION = "cassandra.input.native.protocol.version"; private static final String OUTPUT_CQL = "cassandra.output.cql"; /** * Set the CQL columns for the input of this job. * * @param conf Job configuration you are about to run * @param columns */ public static void setInputColumns(Configuration conf, String columns) { if (columns == null || columns.isEmpty()) return; conf.set(INPUT_CQL_COLUMNS_CONFIG, columns); } /** * Set the CQL query Limit for the input of this job. * * @param conf Job configuration you are about to run * @param cqlPageRowSize */ public static void setInputCQLPageRowSize(Configuration conf, String cqlPageRowSize) { if (cqlPageRowSize == null) { throw new UnsupportedOperationException("cql page row size may not be null"); } conf.set(INPUT_CQL_PAGE_ROW_SIZE_CONFIG, cqlPageRowSize); } /** * Set the CQL user defined where clauses for the input of this job. * * @param conf Job configuration you are about to run * @param clauses */ public static void setInputWhereClauses(Configuration conf, String clauses) { if (clauses == null || clauses.isEmpty()) return; conf.set(INPUT_CQL_WHERE_CLAUSE_CONFIG, clauses); } /** * Set the CQL prepared statement for the output of this job. * * @param conf Job configuration you are about to run * @param cql */ public static void setOutputCql(Configuration conf, String cql) { if (cql == null || cql.isEmpty()) return; conf.set(OUTPUT_CQL, cql); } public static void setInputCql(Configuration conf, String cql) { if (cql == null || cql.isEmpty()) return; conf.set(INPUT_CQL, cql); } public static void setUserNameAndPassword(Configuration conf, String username, String password) { if (StringUtils.isNotBlank(username)) { conf.set(INPUT_NATIVE_AUTH_PROVIDER, PlainTextAuthProvider.class.getName()); conf.set(USERNAME, username); conf.set(PASSWORD, password); } } public static Optional<Integer> getInputCoreConnections(Configuration conf) { return getIntSetting(INPUT_NATIVE_CORE_CONNECTIONS_PER_HOST, conf); } public static Optional<Integer> getInputMaxConnections(Configuration conf) { return getIntSetting(INPUT_NATIVE_MAX_CONNECTIONS_PER_HOST, conf); } public static int getInputNativePort(Configuration conf) { return Integer.parseInt(conf.get(INPUT_NATIVE_PORT, "9042")); } public static Optional<Integer> getInputMinSimultReqPerConnections(Configuration conf) { return getIntSetting(INPUT_NATIVE_MIN_SIMULT_REQ_PER_CONNECTION, conf); } public static Optional<Integer> getInputMaxSimultReqPerConnections(Configuration conf) { return getIntSetting(INPUT_NATIVE_MAX_SIMULT_REQ_PER_CONNECTION, conf); } public static Optional<Integer> getInputNativeConnectionTimeout(Configuration conf) { return getIntSetting(INPUT_NATIVE_CONNECTION_TIMEOUT, conf); } public static Optional<Integer> getInputNativeReadConnectionTimeout(Configuration conf) { return getIntSetting(INPUT_NATIVE_READ_CONNECTION_TIMEOUT, conf); } public static Optional<Integer> getInputNativeReceiveBufferSize(Configuration conf) { return getIntSetting(INPUT_NATIVE_RECEIVE_BUFFER_SIZE, conf); } public static Optional<Integer> getInputNativeSendBufferSize(Configuration conf) { return getIntSetting(INPUT_NATIVE_SEND_BUFFER_SIZE, conf); } public static Optional<Integer> getInputNativeSolinger(Configuration conf) { return getIntSetting(INPUT_NATIVE_SOLINGER, conf); } public static Optional<Boolean> getInputNativeTcpNodelay(Configuration conf) { return getBooleanSetting(INPUT_NATIVE_TCP_NODELAY, conf); } public static Optional<Boolean> getInputNativeReuseAddress(Configuration conf) { return getBooleanSetting(INPUT_NATIVE_REUSE_ADDRESS, conf); } public static Optional<String> getInputNativeAuthProvider(Configuration conf) { return getStringSetting(INPUT_NATIVE_AUTH_PROVIDER, conf); } public static Optional<String> getInputNativeSSLTruststorePath(Configuration conf) { return getStringSetting(INPUT_NATIVE_SSL_TRUST_STORE_PATH, conf); } public static Optional<String> getInputNativeSSLKeystorePath(Configuration conf) { return getStringSetting(INPUT_NATIVE_SSL_KEY_STORE_PATH, conf); } public static Optional<String> getInputNativeSSLKeystorePassword(Configuration conf) { return getStringSetting(INPUT_NATIVE_SSL_KEY_STORE_PASSWARD, conf); } public static Optional<String> getInputNativeSSLTruststorePassword(Configuration conf) { return getStringSetting(INPUT_NATIVE_SSL_TRUST_STORE_PASSWARD, conf); } public static Optional<String> getInputNativeSSLCipherSuites(Configuration conf) { return getStringSetting(INPUT_NATIVE_SSL_CIPHER_SUITES, conf); } public static Optional<Boolean> getInputNativeKeepAlive(Configuration conf) { return getBooleanSetting(INPUT_NATIVE_KEEP_ALIVE, conf); } public static String getInputcolumns(Configuration conf) { return conf.get(INPUT_CQL_COLUMNS_CONFIG); } public static Optional<Integer> getInputPageRowSize(Configuration conf) { return getIntSetting(INPUT_CQL_PAGE_ROW_SIZE_CONFIG, conf); } public static String getInputWhereClauses(Configuration conf) { return conf.get(INPUT_CQL_WHERE_CLAUSE_CONFIG); } public static String getInputCql(Configuration conf) { return conf.get(INPUT_CQL); } public static String getOutputCql(Configuration conf) { return conf.get(OUTPUT_CQL); } private static Optional<Integer> getProtocolVersion(Configuration conf) { return getIntSetting(INPUT_NATIVE_PROTOCOL_VERSION, conf); } public static Cluster getInputCluster(String host, Configuration conf) { // this method has been left for backward compatibility return getInputCluster(new String[] {host}, conf); } public static Cluster getInputCluster(String[] hosts, Configuration conf) { int port = getInputNativePort(conf); Optional<AuthProvider> authProvider = getAuthProvider(conf); Optional<SSLOptions> sslOptions = getSSLOptions(conf); Optional<Integer> protocolVersion = getProtocolVersion(conf); LoadBalancingPolicy loadBalancingPolicy = getReadLoadBalancingPolicy(hosts); SocketOptions socketOptions = getReadSocketOptions(conf); QueryOptions queryOptions = getReadQueryOptions(conf); PoolingOptions poolingOptions = getReadPoolingOptions(conf); Cluster.Builder builder = Cluster.builder() .addContactPoints(hosts) .withPort(port) .withCompression(ProtocolOptions.Compression.NONE); if (authProvider.isPresent()) builder.withAuthProvider(authProvider.get()); if (sslOptions.isPresent()) builder.withSSL(sslOptions.get()); if (protocolVersion.isPresent()) { builder.withProtocolVersion(protocolVersion.get()); } builder.withLoadBalancingPolicy(loadBalancingPolicy) .withSocketOptions(socketOptions) .withQueryOptions(queryOptions) .withPoolingOptions(poolingOptions); return builder.build(); } public static void setInputCoreConnections(Configuration conf, String connections) { conf.set(INPUT_NATIVE_CORE_CONNECTIONS_PER_HOST, connections); } public static void setInputMaxConnections(Configuration conf, String connections) { conf.set(INPUT_NATIVE_MAX_CONNECTIONS_PER_HOST, connections); } public static void setInputMinSimultReqPerConnections(Configuration conf, String reqs) { conf.set(INPUT_NATIVE_MIN_SIMULT_REQ_PER_CONNECTION, reqs); } public static void setInputMaxSimultReqPerConnections(Configuration conf, String reqs) { conf.set(INPUT_NATIVE_MAX_SIMULT_REQ_PER_CONNECTION, reqs); } public static void setInputNativeConnectionTimeout(Configuration conf, String timeout) { conf.set(INPUT_NATIVE_CONNECTION_TIMEOUT, timeout); } public static void setInputNativeReadConnectionTimeout(Configuration conf, String timeout) { conf.set(INPUT_NATIVE_READ_CONNECTION_TIMEOUT, timeout); } public static void setInputNativeReceiveBufferSize(Configuration conf, String size) { conf.set(INPUT_NATIVE_RECEIVE_BUFFER_SIZE, size); } public static void setInputNativeSendBufferSize(Configuration conf, String size) { conf.set(INPUT_NATIVE_SEND_BUFFER_SIZE, size); } public static void setInputNativeSolinger(Configuration conf, String solinger) { conf.set(INPUT_NATIVE_SOLINGER, solinger); } public static void setInputNativeTcpNodelay(Configuration conf, String tcpNodelay) { conf.set(INPUT_NATIVE_TCP_NODELAY, tcpNodelay); } public static void setInputNativeAuthProvider(Configuration conf, String authProvider) { conf.set(INPUT_NATIVE_AUTH_PROVIDER, authProvider); } public static void setInputNativeSSLTruststorePath(Configuration conf, String path) { conf.set(INPUT_NATIVE_SSL_TRUST_STORE_PATH, path); } public static void setInputNativeSSLKeystorePath(Configuration conf, String path) { conf.set(INPUT_NATIVE_SSL_KEY_STORE_PATH, path); } public static void setInputNativeSSLKeystorePassword(Configuration conf, String pass) { conf.set(INPUT_NATIVE_SSL_KEY_STORE_PASSWARD, pass); } public static void setInputNativeSSLTruststorePassword(Configuration conf, String pass) { conf.set(INPUT_NATIVE_SSL_TRUST_STORE_PASSWARD, pass); } public static void setInputNativeSSLCipherSuites(Configuration conf, String suites) { conf.set(INPUT_NATIVE_SSL_CIPHER_SUITES, suites); } public static void setInputNativeReuseAddress(Configuration conf, String reuseAddress) { conf.set(INPUT_NATIVE_REUSE_ADDRESS, reuseAddress); } public static void setInputNativeKeepAlive(Configuration conf, String keepAlive) { conf.set(INPUT_NATIVE_KEEP_ALIVE, keepAlive); } public static void setInputNativePort(Configuration conf, String port) { conf.set(INPUT_NATIVE_PORT, port); } private static PoolingOptions getReadPoolingOptions(Configuration conf) { Optional<Integer> coreConnections = getInputCoreConnections(conf); Optional<Integer> maxConnections = getInputMaxConnections(conf); Optional<Integer> maxSimultaneousRequests = getInputMaxSimultReqPerConnections(conf); Optional<Integer> minSimultaneousRequests = getInputMinSimultReqPerConnections(conf); PoolingOptions poolingOptions = new PoolingOptions(); for (HostDistance hostDistance : Arrays.asList(HostDistance.LOCAL, HostDistance.REMOTE)) { if (coreConnections.isPresent()) poolingOptions.setCoreConnectionsPerHost(hostDistance, coreConnections.get()); if (maxConnections.isPresent()) poolingOptions.setMaxConnectionsPerHost(hostDistance, maxConnections.get()); if (minSimultaneousRequests.isPresent()) poolingOptions.setMinSimultaneousRequestsPerConnectionThreshold(hostDistance, minSimultaneousRequests.get()); if (maxSimultaneousRequests.isPresent()) poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(hostDistance, maxSimultaneousRequests.get()); } return poolingOptions; } private static QueryOptions getReadQueryOptions(Configuration conf) { String CL = ConfigHelper.getReadConsistencyLevel(conf); Optional<Integer> fetchSize = getInputPageRowSize(conf); QueryOptions queryOptions = new QueryOptions(); if (CL != null && !CL.isEmpty()) queryOptions.setConsistencyLevel(com.datastax.driver.core.ConsistencyLevel.valueOf(CL)); if (fetchSize.isPresent()) queryOptions.setFetchSize(fetchSize.get()); return queryOptions; } private static SocketOptions getReadSocketOptions(Configuration conf) { SocketOptions socketOptions = new SocketOptions(); Optional<Integer> connectTimeoutMillis = getInputNativeConnectionTimeout(conf); Optional<Integer> readTimeoutMillis = getInputNativeReadConnectionTimeout(conf); Optional<Integer> receiveBufferSize = getInputNativeReceiveBufferSize(conf); Optional<Integer> sendBufferSize = getInputNativeSendBufferSize(conf); Optional<Integer> soLinger = getInputNativeSolinger(conf); Optional<Boolean> tcpNoDelay = getInputNativeTcpNodelay(conf); Optional<Boolean> reuseAddress = getInputNativeReuseAddress(conf); Optional<Boolean> keepAlive = getInputNativeKeepAlive(conf); if (connectTimeoutMillis.isPresent()) socketOptions.setConnectTimeoutMillis(connectTimeoutMillis.get()); if (readTimeoutMillis.isPresent()) socketOptions.setReadTimeoutMillis(readTimeoutMillis.get()); if (receiveBufferSize.isPresent()) socketOptions.setReceiveBufferSize(receiveBufferSize.get()); if (sendBufferSize.isPresent()) socketOptions.setSendBufferSize(sendBufferSize.get()); if (soLinger.isPresent()) socketOptions.setSoLinger(soLinger.get()); if (tcpNoDelay.isPresent()) socketOptions.setTcpNoDelay(tcpNoDelay.get()); if (reuseAddress.isPresent()) socketOptions.setReuseAddress(reuseAddress.get()); if (keepAlive.isPresent()) socketOptions.setKeepAlive(keepAlive.get()); return socketOptions; } private static LoadBalancingPolicy getReadLoadBalancingPolicy(final String[] stickHosts) { return new LimitedLocalNodeFirstLocalBalancingPolicy(stickHosts); } private static Optional<AuthProvider> getAuthProvider(Configuration conf) { Optional<String> authProvider = getInputNativeAuthProvider(conf); if (!authProvider.isPresent()) return Optional.absent(); return Optional.of(getClientAuthProvider(authProvider.get(), conf)); } private static Optional<SSLOptions> getSSLOptions(Configuration conf) { Optional<String> truststorePath = getInputNativeSSLTruststorePath(conf); Optional<String> keystorePath = getInputNativeSSLKeystorePath(conf); Optional<String> truststorePassword = getInputNativeSSLTruststorePassword(conf); Optional<String> keystorePassword = getInputNativeSSLKeystorePassword(conf); Optional<String> cipherSuites = getInputNativeSSLCipherSuites(conf); if (truststorePath.isPresent() && keystorePath.isPresent() && truststorePassword.isPresent() && keystorePassword.isPresent()) { SSLContext context; try { context = getSSLContext(truststorePath.get(), truststorePassword.get(), keystorePath.get(), keystorePassword.get()); } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) { throw new RuntimeException(e); } String[] css = SSLOptions.DEFAULT_SSL_CIPHER_SUITES; if (cipherSuites.isPresent()) css = cipherSuites.get().split(","); return Optional.of(new SSLOptions(context,css)); } return Optional.absent(); } private static Optional<Integer> getIntSetting(String parameter, Configuration conf) { String setting = conf.get(parameter); if (setting == null) return Optional.absent(); return Optional.of(Integer.valueOf(setting)); } private static Optional<Boolean> getBooleanSetting(String parameter, Configuration conf) { String setting = conf.get(parameter); if (setting == null) return Optional.absent(); return Optional.of(Boolean.valueOf(setting)); } private static Optional<String> getStringSetting(String parameter, Configuration conf) { String setting = conf.get(parameter); if (setting == null) return Optional.absent(); return Optional.of(setting); } private static AuthProvider getClientAuthProvider(String factoryClassName, Configuration conf) { try { Class<?> c = Class.forName(factoryClassName); if (PlainTextAuthProvider.class.equals(c)) { String username = getStringSetting(USERNAME, conf).or(""); String password = getStringSetting(PASSWORD, conf).or(""); return (AuthProvider) c.getConstructor(String.class, String.class) .newInstance(username, password); } else { return (AuthProvider) c.newInstance(); } } catch (Exception e) { throw new RuntimeException("Failed to instantiate auth provider:" + factoryClassName, e); } } private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath, String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException { FileInputStream tsf = null; FileInputStream ksf = null; SSLContext ctx = null; try { tsf = new FileInputStream(truststorePath); ksf = new FileInputStream(keystorePath); ctx = SSLContext.getInstance("SSL"); KeyStore ts = KeyStore.getInstance("JKS"); ts.load(tsf, truststorePassword.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(ksf, keystorePassword.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keystorePassword.toCharArray()); ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); } finally { FileUtils.closeQuietly(tsf); FileUtils.closeQuietly(ksf); } return ctx; } }
Bj0rnen/cassandra
src/java/org/apache/cassandra/hadoop/cql3/CqlConfigHelper.java
Java
apache-2.0
24,042
--- layout: post title: swift小项目-基于CoreLoaction和MapKit的位置app date: 2016-03-23 categories: blog tags: [swift] description: 基于CoreLoaction和MapKit的位置app --- 这是一个用了CoreLoaction和MapKit的一个小项目,界面是点击按钮找到当前位置并且在地图上标记出来。下面是几点注意的: 1.使用CoreLocation时,requestAlwaysAuthorization(),因为要获取位置权限,所以在info.plist里要添加NSLocationAlwaysUsageDescription和NSLocationWhenInUseUsageDescription这两个授权提示的描述,不然在debug的时候是进不到delegate实现的方法的。 2.下面直接贴出部分代码 import UIKit import CoreLocation import MapKit class ViewController: UIViewController , CLLocationManagerDelegate{ @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var mapView: MKMapView! var locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() self.mapView.mapType = MKMapType.Standard } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func FindButtonDidPressed(sender: AnyObject) { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() //创建一个MKCoordinateSpan对象,设置地图的范围(越小越精确) let latDelta = 0.05 let longDelta = 0.05 let currentLocationSpan:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta) //使用当前位置 var center:CLLocation = locationManager.location! // //使用自定义位置 // let center:CLLocation = CLLocation(latitude: 32.029171, longitude: 118.788231) let currentRegion:MKCoordinateRegion = MKCoordinateRegion(center: center.coordinate, span: currentLocationSpan) //设置显示区域 self.mapView.setRegion(currentRegion, animated: true) //创建一个大头针对象 let objectAnnotation = MKPointAnnotation() objectAnnotation.coordinate = center.coordinate objectAnnotation.title = center.description objectAnnotation.subtitle = "" self.mapView.addAnnotation(objectAnnotation) } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { self.locationLabel.text = "更新位置发生错误:" + error.description } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in if (error != nil) { self.locationLabel.text = "Reverse geocoder failed with error" + error!.localizedDescription return } if placemarks!.count > 0 { let pm = placemarks![0] self.displayLocationInfo(pm) } else { self.locationLabel.text = "Problem with the data received from geocoder" } }) } func displayLocationInfo(placemark:CLPlacemark?){ if let containsPlacemark = placemark { locationManager.stopUpdatingLocation() let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : "" let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : "" let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : "" let country = (containsPlacemark.country != nil) ? containsPlacemark.country : "" self.locationLabel.text = locality! + "-" + postalCode! + "-" + administrativeArea! + "-" + country! } } }
HITlilingzhi/HITlilingzhi.github.io
_posts/2016-03-23-swift小项目-基于CoreLoaction和MapKit的位置app.md
Markdown
apache-2.0
4,517
define(function (require) { var tdd = require('intern!tdd'); // Not really Chai but a Chai-compatible "assert" library for old IE. var assert = require('intern/chai!assert'); // parse-srcset is an AMD module. var parseSrcset = require('../../src/parse-srcset'); var he = require('tests/he'); tdd.suite('Parse Srcset', function() { // Adapted from the W3C srcset conformance checker at: // http://w3c-test.org/html/semantics/embedded-content/the-img-element/srcset/parse-a-srcset-attribute.html var w3Ctests = [ { groupName: "Splitting Loop", testArray: [ {srcset: '', expect: '', desc: 'empty string'}, {srcset: ',' , expect: '', desc: 'single comma'}, {srcset: ',,,', expect: '', desc: 'three commas'}, {srcset: '&#x9;&#x9;data:,a&#x9;&#x9;1x&#x9;&#x9;', expect: 'data:,a', desc: 'tabs'}, {srcset: '&#xA;&#xA;data:,a&#xA;&#xA;1x&#xA;&#xA;', expect: 'data:,a', desc: 'line feeds'}, {srcset: '&#xB;&#xB;data:,a&#xB;&#xB;1x&#xB;&#xB;', expect: '&#xB;&#xB;data:,a&#xB;&#xB;1x&#xB;&#xB;', desc: 'line tab'}, {srcset: '&#xC;&#xC;data:,a&#xC;&#xC;1x&#xC;&#xC;', expect: 'data:,a', desc: 'form feed U+000C'}, {srcset: '&#xD;&#xD;data:,a&#xD;&#xD;1x&#xD;&#xD;', expect: 'data:,a', desc: 'carriage return U+000D'}, {srcset: '&#xE;&#xE;data:,a&#xE;&#xE;1x&#xE;&#xE;', expect: '&#xE;&#xE;data:,a&#xE;&#xE;1x&#xE;&#xE;', desc: 'shift out U+000E'}, {srcset: '&#xF;&#xF;data:,a&#xF;&#xF;1x&#xF;&#xF;', expect: '&#xF;&#xF;data:,a&#xF;&#xF;1x&#xF;&#xF;', desc: 'shift in U+000F' }, {srcset: '&#x10;&#x10;data:,a&#x10;&#x10;1x&#x10;&#x10;', expect: '&#x10;&#x10;data:,a&#x10;&#x10;1x&#x10;&#x10;', desc: 'data link escape U+0010' }, {srcset: 'data:,a', expect: 'data:,a', desc:'plain url'}, {srcset: 'data:,a ', expect: 'data:,a', desc:'trailing space'}, {srcset: 'data:,a ,', expect: 'data:,a', desc:'trailing space and comma'}, {srcset: 'data:,a,', expect: 'data:,a', desc:'trailing comma'}, {srcset: 'data:,a, ', expect: 'data:,a', desc:'trailing comma and space'}, {srcset: 'data:,a,,,', expect: 'data:,a', desc:'trailing three commas'}, {srcset: 'data:,a,, , ', expect: 'data:,a', desc:'trailing two commas space comma space'}, {srcset: ' data:,a', expect: 'data:,a', desc:'leading space'}, {srcset: ',,,data:,a', expect: 'data:,a', desc:'leading three commas'}, {srcset: ' , ,,data:,a', expect: 'data:,a', desc:'leading space comma space comma comma'}, {srcset: '&nbsp;data:,a', expect: '&nbsp;data:,a', desc:'leading non-breaking space'}, {srcset: 'data:,a&nbsp;', expect: 'data:,a&nbsp;', desc:'trailing non-breaking space'} ] }, { groupName: "Descriptor Tokenizer", testArray: [ {srcset: 'data:,a 1x', expect: 'data:,a', desc: 'plain url with descriptor'}, {srcset: 'data:,a 1x ', expect: 'data:,a', desc: 'trailing space'}, {srcset: 'data:,a 1x,', expect: 'data:,a', desc: 'trailing comma'}, {srcset: 'data:,a ( , data:,b 1x, ), data:,c', expect: 'data:,c', desc: 'irregular parens 1'}, {srcset: 'data:,a ((( , data:,b 1x, ), data:,c', expect: 'data:,c', desc: 'irregular parens 2'}, {srcset: 'data:,a [ , data:,b 1x, ], data:,c', expect: 'data:,b', desc: 'brackets'}, {srcset: 'data:,a { , data:,b 1x, }, data:,c', expect: 'data:,b', desc: 'braces'}, {srcset: 'data:,a " , data:,b 1x, ", data:,c', expect: 'data:,b', desc: 'double quotes'}, {srcset: 'data:,a \\,data:;\\,b, data:,c', expect: 'data:;\\,b', desc: 'backslashes'}, {srcset: 'data:,a, data:,b (', expect: 'data:,a', desc: 'trailing unclosed paren'}, {srcset: 'data:,a, data:,b ( ', expect: 'data:,a', desc: 'unclosed paren space'}, {srcset: 'data:,a, data:,b (,', expect: 'data:,a', desc: 'unclosed paren comma'}, {srcset: 'data:,a, data:,b (x', expect: 'data:,a', desc: 'unclosed paren x'}, {srcset: 'data:,a, data:,b ()', expect: 'data:,a', desc: 'parens, no descriptor'}, {srcset: 'data:,a (, data:,b', expect: '', desc: 'unclosed paren'}, {srcset: 'data:,a /*, data:,b, data:,c */', expect: 'data:,b', desc: 'block comments'}, {srcset: 'data:,a //, data:,b', expect: 'data:,b', desc: 'double slash like a comment'} ] }, { groupName: "Descriptor Parser", testArray : [ {srcset: 'data:,a foo', expect: '', desc: 'trailing foo'}, {srcset: 'data:,a foo foo', expect: '', desc: 'trailing foo foo'}, {srcset: 'data:,a foo 1x', expect: '', desc: 'trailing foo 1x'}, {srcset: 'data:,a foo 1x foo', expect: '', desc: 'trailing 1x foo'}, {srcset: 'data:,a foo 1w', expect: '', desc: 'trailing foo 1w'}, {srcset: 'data:,a foo 1w foo', expect: '', desc: 'trailing foo 1w foo'}, {srcset: 'data:,a 1x 1x', expect: '', desc: 'two density descriptors'}, {srcset: 'data:,a 1w 1w', expect: '', desc: 'two width descriptors'}, {srcset: 'data:,a 1h 1h', expect: '', desc: 'two height descriptors'}, {srcset: 'data:,a 1w 1x', expect: '', desc: 'width then density'}, {srcset: 'data:,a 1x 1w', expect: '', desc: 'density then width'}, {srcset: 'data:,a 1w 1h', expect: 'data:,a', desc: 'width then height'}, {srcset: 'data:,a 1h 1w', expect: 'data:,a', desc: 'height then width'}, {srcset: 'data:,a 1h 1x', expect: '', desc: 'height then density'}, {srcset: 'data:,a 1h 1w 1x', expect: '', desc: 'height then width then density'}, {srcset: 'data:,a 1x 1w 1h', expect: '', desc: 'density then width then height'}, {srcset: 'data:,a 1h foo', expect: '', desc: 'trailing 1h foo'}, {srcset: 'data:,a foo 1h', expect: '', desc: 'trailing foo 1h'}, {srcset: 'data:,a 0w', expect: '', desc: 'zero width'}, {srcset: 'data:,a -1w', expect: '', desc: 'negative width'}, {srcset: 'data:,a 1w -1w', expect: '', desc: 'positive width, negative width'}, {srcset: 'data:,a 1.0w', expect: '', desc: 'floating point width'}, {srcset: 'data:,a 1w 1.0w', expect: '', desc: 'integer width, floating point width'}, {srcset: 'data:,a 1e0w', expect: '', desc: 'exponent width'}, {srcset: 'data:,a 1w 1e0w', expect: '', desc: 'integer width, exponent width'}, {srcset: 'data:,a 1www', expect: '', desc: '1www'}, {srcset: 'data:,a 1w 1www', expect: '', desc: '1w 1www'}, {srcset: 'data:,a 1w +1w', expect: '', desc: '1w +1w'}, {srcset: 'data:,a 1W', expect: '', desc: 'capital W descriptor'}, {srcset: 'data:,a 1w 1W', expect: '', desc: 'lowercase w, capital W descriptors'}, {srcset: 'data:,a Infinityw', expect: '', desc: 'Infinityw'}, {srcset: 'data:,a 1w Infinityw', expect: '', desc: '1w Infinityw'}, {srcset: 'data:,a NaNw', expect: '', desc: 'Nanw'}, {srcset: 'data:,a 1w NaNw', expect: '', desc: '1w Nanw'}, {srcset: 'data:,a 0x1w', expect: '', desc: 'ox1w'}, {srcset: 'data:,a 1&#x1;w', expect: '', desc: 'trailing U+0001'}, {srcset: 'data:,a 1&nbsp;w', expect: '', desc: 'trailing U+00A0'}, {srcset: 'data:,a 1&#x1680;w', expect: '', desc: 'trailing U+1680'}, {srcset: 'data:,a 1&#x2000;w', expect: '', desc: 'trailing U+2000'}, {srcset: 'data:,a 1&#x2001;w', expect: '', desc: 'trailing U+2001'}, {srcset: 'data:,a 1&#x2002;w', expect: '', desc: 'trailing U+2002'}, {srcset: 'data:,a 1&#x2003;w', expect: '', desc: 'trailing U+2003'}, {srcset: 'data:,a 1&#x2004;w', expect: '', desc: 'trailing U+2004'}, {srcset: 'data:,a 1&#x2005;w', expect: '', desc: 'trailing U+2005'}, {srcset: 'data:,a 1&#x2006;w', expect: '', desc: 'trailing U+2006'}, {srcset: 'data:,a 1&#x2007;w', expect: '', desc: 'trailing U+2007'}, {srcset: 'data:,a 1&#x2008;w', expect: '', desc: 'trailing U+2008'}, {srcset: 'data:,a 1&#x2009;w', expect: '', desc: 'trailing U+2009'}, {srcset: 'data:,a 1&#x200A;w', expect: '', desc: 'trailing U+200A'}, {srcset: 'data:,a 1&#x200C;w', expect: '', desc: 'trailing U+200C'}, {srcset: 'data:,a 1&#x200D;w', expect: '', desc: 'trailing U+200D'}, {srcset: 'data:,a 1&#x202F;w', expect: '', desc: 'trailing U+202F'}, {srcset: 'data:,a 1&#x205F;w', expect: '', desc: 'trailing U+205F'}, {srcset: 'data:,a 1&#x3000;w', expect: '', desc: 'trailing U+3000'}, {srcset: 'data:,a 1&#xFEFF;w', expect: '', desc: 'trailing U+FEFF'}, {srcset: 'data:,a &#x1;1w' , expect: '', desc: 'leading U+0001'}, // {srcset: 'data:,a &nbsp;1w' , expect: '', desc: 'leading U+00A0 width'}, {srcset: 'data:,a &#x1680;1w', expect: '', desc: 'leading U+1680'}, {srcset: 'data:,a &#x2000;1w', expect: '', desc: 'leading U+2000'}, {srcset: 'data:,a &#x2001;1w', expect: '', desc: 'leading U+2001'}, {srcset: 'data:,a &#x2002;1w', expect: '', desc: 'leading U+2002'}, {srcset: 'data:,a &#x2003;1w', expect: '', desc: 'leading U+2003'}, {srcset: 'data:,a &#x2004;1w', expect: '', desc: 'leading U+2004'}, {srcset: 'data:,a &#x2005;1w', expect: '', desc: 'leading U+2005'}, {srcset: 'data:,a &#x2006;1w', expect: '', desc: 'leading U+2006'}, {srcset: 'data:,a &#x2007;1w', expect: '', desc: 'leading U+2007'}, {srcset: 'data:,a &#x2008;1w', expect: '', desc: 'leading U+2008'}, {srcset: 'data:,a &#x2009;1w', expect: '', desc: 'leading U+2009'}, {srcset: 'data:,a &#x200A;1w', expect: '', desc: 'leading U+200A'}, {srcset: 'data:,a &#x200C;1w', expect: '', desc: 'leading U+200C'}, {srcset: 'data:,a &#x200D;1w', expect: '', desc: 'leading U+200D'}, {srcset: 'data:,a &#x202F;1w', expect: '', desc: 'leading U+202F'}, {srcset: 'data:,a &#x205F;1w', expect: '', desc: 'leading U+205F'}, {srcset: 'data:,a &#x3000;1w', expect: '', desc: 'leading U+3000'}, {srcset: 'data:,a &#xFEFF;1w', expect: '', desc: 'leading U+FEFF'}, {srcset: 'data:,a 0x', expect: 'data:,a', desc: 'zero density'}, {srcset: 'data:,a -0x' , expect: 'data:,a', desc: 'negative zero density'}, {srcset: 'data:,a 1x -0x', expect: '', desc: '1x -0x'}, {srcset: 'data:,a -1x', expect: '', desc: '-1x'}, {srcset: 'data:,a 1x -1x', expect: '', desc: '1x -1x'}, {srcset: 'data:,a 1e0x', expect: 'data:,a', desc: '1e0x'}, {srcset: 'data:,a 1E0x', expect: 'data:,a', desc: '1E0x'}, {srcset: 'data:,a 1e-1x', expect: 'data:,a', desc: '1e-1x'}, {srcset: 'data:,a 1.5e1x', expect: 'data:,a', desc: '1.5e1x'}, {srcset: 'data:,a -x', expect: '', desc: 'negative density with no digits'}, {srcset: 'data:,a .x', expect: '', desc: 'decimal density with no digits'}, {srcset: 'data:,a -.x', expect: '', desc: '-.x'}, {srcset: 'data:,a 1.x', expect: '', desc: '1.x'}, {srcset: 'data:,a .5x', expect: 'data:,a', desc: 'floating point density descriptor'}, {srcset: 'data:,a .5e1x', expect: 'data:,a', desc: '.5e1x'}, {srcset: 'data:,a 1x 1.5e1x', expect: '', desc: '1x 1.5e1x'}, {srcset: 'data:,a 1x 1e1.5x', expect: '', desc: '1x 1e1.5x'}, {srcset: 'data:,a 1.0x', expect: 'data:,a', desc: '1.0x'}, {srcset: 'data:,a 1x 1.0x', expect: '', desc: '1x 1.0x'}, {srcset: 'data:,a +1x', expect: '', desc: 'no plus sign allowed on floating point number'}, {srcset: 'data:,a 1X', expect: '', desc: 'Capital X descriptor'}, {srcset: 'data:,a Infinityx', expect: '', desc: 'Infinityx'}, {srcset: 'data:,a NaNx', expect: '', desc: 'NaNx'}, {srcset: 'data:,a 0x1x', expect: '', desc: '0X1x'}, {srcset: 'data:,a 0X1x', expect: '', desc: '1&#x1;x'}, {srcset: 'data:,a 1&#x1;x', expect: '', desc: 'trailing U+0001'}, {srcset: 'data:,a 1&nbsp;x' , expect: '', desc: 'trailing U+00A0 density'}, {srcset: 'data:,a 1&#x1680;x', expect: '', desc: 'trailing U+1680'}, {srcset: 'data:,a 1&#x2000;x', expect: '', desc: 'trailing U+2000'}, {srcset: 'data:,a 1&#x2001;x', expect: '', desc: 'trailing U+2001'}, {srcset: 'data:,a 1&#x2002;x', expect: '', desc: 'trailing U+2002'}, {srcset: 'data:,a 1&#x2003;x', expect: '', desc: 'trailing U+2003'}, {srcset: 'data:,a 1&#x2004;x', expect: '', desc: 'trailing U+2004'}, {srcset: 'data:,a 1&#x2005;x', expect: '', desc: 'trailing U+2005'}, {srcset: 'data:,a 1&#x2006;x', expect: '', desc: 'trailing U+2006'}, {srcset: 'data:,a 1&#x2007;x', expect: '', desc: 'trailing U+2007'}, {srcset: 'data:,a 1&#x2008;x', expect: '', desc: 'trailing U+2008'}, {srcset: 'data:,a 1&#x2009;x', expect: '', desc: 'trailing U+2009'}, {srcset: 'data:,a 1&#x200A;x', expect: '', desc: 'trailing U+200A'}, {srcset: 'data:,a 1&#x200C;x', expect: '', desc: 'trailing U+200C'}, {srcset: 'data:,a 1&#x200D;x', expect: '', desc: 'trailing U+200D'}, {srcset: 'data:,a 1&#x202F;x', expect: '', desc: 'trailing U+202F'}, {srcset: 'data:,a 1&#x205F;x', expect: '', desc: 'trailing U+205F'}, {srcset: 'data:,a 1&#x3000;x', expect: '', desc: 'trailing U+3000'}, {srcset: 'data:,a 1&#xFEFF;x', expect: '', desc: 'trailing U+FEFF'}, {srcset: 'data:,a &#x1;1x' , expect: '', desc: 'leading U+0001'}, {srcset: 'data:,a &nbsp;1x' , expect: '', desc: 'leading U+00A0 density'}, {srcset: 'data:,a &#x1680;1x', expect: '', desc: 'leading U+1680'}, {srcset: 'data:,a &#x2000;1x', expect: '', desc: 'leading U+2000'}, {srcset: 'data:,a &#x2001;1x', expect: '', desc: 'leading U+2001'}, {srcset: 'data:,a &#x2002;1x', expect: '', desc: 'leading U+2002'}, {srcset: 'data:,a &#x2003;1x', expect: '', desc: 'leading U+2003'}, {srcset: 'data:,a &#x2004;1x', expect: '', desc: 'leading U+2004'}, {srcset: 'data:,a &#x2005;1x', expect: '', desc: 'leading U+2005'}, {srcset: 'data:,a &#x2006;1x', expect: '', desc: 'leading U+2006'}, {srcset: 'data:,a &#x2007;1x', expect: '', desc: 'leading U+2007'}, {srcset: 'data:,a &#x2008;1x', expect: '', desc: 'leading U+2008'}, {srcset: 'data:,a &#x2009;1x', expect: '', desc: 'leading U+2009'}, {srcset: 'data:,a &#x200A;1x', expect: '', desc: 'leading U+200A'}, {srcset: 'data:,a &#x200C;1x', expect: '', desc: 'leading U+200C'}, {srcset: 'data:,a &#x200D;1x', expect: '', desc: 'leading U+200D'}, {srcset: 'data:,a &#x202F;1x', expect: '', desc: 'leading U+202F'}, {srcset: 'data:,a &#x205F;1x', expect: '', desc: 'leading U+205F'}, {srcset: 'data:,a &#x3000;1x', expect: '', desc: 'leading U+3000'}, {srcset: 'data:,a &#xFEFF;1x', expect: '', desc: 'leading U+FEFF'}, {srcset: 'data:,a 1w 0h', expect: '', desc: '1w 0h'}, {srcset: 'data:,a 1w -1h', expect: '', desc: '1w -1h'}, {srcset: 'data:,a 1w 1.0h', expect: '', desc: '1w 1.0h'}, {srcset: 'data:,a 1w 1e0h', expect: '', desc: '1w 1e0h'}, {srcset: 'data:,a 1w 1hhh', expect: '', desc: '1w 1hhh'}, {srcset: 'data:,a 1w 1H', expect: '', desc: '1w 1H'}, {srcset: 'data:,a 1w Infinityh', expect: '', desc: '1w Infinityh'}, {srcset: 'data:,a 1w NaNh', expect: '', desc: '1w NaNh'}, {srcset: 'data:,a 0x1h', expect: '', desc: '0x1h'}, {srcset: 'data:,a 0X1h', expect: '', desc: '0X1h'}, {srcset: 'data:,a 1w 1&#x1;h', expect: '', desc: 'trailing U+0001'}, {srcset: 'data:,a 1w 1&nbsp;h', expect: '', desc: 'trailing U+00A0'}, {srcset: 'data:,a 1w 1&#x1680;h', expect: '', desc: 'trailing U+1680'}, {srcset: 'data:,a 1w 1&#x2000;h', expect: '', desc: 'trailing U+2000'}, {srcset: 'data:,a 1w 1&#x2001;h', expect: '', desc: 'trailing U+2001'}, {srcset: 'data:,a 1w 1&#x2002;h', expect: '', desc: 'trailing U+2002'}, {srcset: 'data:,a 1w 1&#x2003;h', expect: '', desc: 'trailing U+2003'}, {srcset: 'data:,a 1w 1&#x2004;h', expect: '', desc: 'trailing U+2004'}, {srcset: 'data:,a 1w 1&#x2005;h', expect: '', desc: 'trailing U+2005'}, {srcset: 'data:,a 1w 1&#x2006;h', expect: '', desc: 'trailing U+2006'}, {srcset: 'data:,a 1w 1&#x2007;h', expect: '', desc: 'trailing U+2007'}, {srcset: 'data:,a 1w 1&#x2008;h', expect: '', desc: 'trailing U+2008'}, {srcset: 'data:,a 1w 1&#x2009;h', expect: '', desc: 'trailing U+2009'}, {srcset: 'data:,a 1w 1&#x200A;h', expect: '', desc: 'trailing U+200A'}, {srcset: 'data:,a 1w 1&#x200C;h', expect: '', desc: 'trailing U+200C'}, {srcset: 'data:,a 1w 1&#x200D;h', expect: '', desc: 'trailing U+200D'}, {srcset: 'data:,a 1w 1&#x202F;h', expect: '', desc: 'trailing U+202F'}, {srcset: 'data:,a 1w 1&#x205F;h', expect: '', desc: 'trailing U+205F'}, {srcset: 'data:,a 1w 1&#x3000;h', expect: '', desc: 'trailing U+3000'}, {srcset: 'data:,a 1w 1&#xFEFF;h', expect: '', desc: 'trailing U+FEFF'}, {srcset: 'data:,a 1w &#x1;1h', expect: '', desc: 'leading U+0001'}, {srcset: 'data:,a 1w &nbsp;1h', expect: '', desc: 'leading U+00A0'}, {srcset: 'data:,a 1w &#x1680;1h', expect: '', desc: 'leading U+1680'}, {srcset: 'data:,a 1w &#x2000;1h', expect: '', desc: 'leading U+2000'}, {srcset: 'data:,a 1w &#x2001;1h', expect: '', desc: 'leading U+2001'}, {srcset: 'data:,a 1w &#x2002;1h', expect: '', desc: 'leading U+2002'}, {srcset: 'data:,a 1w &#x2003;1h', expect: '', desc: 'leading U+2003'}, {srcset: 'data:,a 1w &#x2004;1h', expect: '', desc: 'leading U+2004'}, {srcset: 'data:,a 1w &#x2005;1h', expect: '', desc: 'leading U+2005'}, {srcset: 'data:,a 1w &#x2006;1h', expect: '', desc: 'leading U+2006'}, {srcset: 'data:,a 1w &#x2007;1h', expect: '', desc: 'leading U+2007'}, {srcset: 'data:,a 1w &#x2008;1h', expect: '', desc: 'leading U+2008'}, {srcset: 'data:,a 1w &#x2009;1h', expect: '', desc: 'leading U+2009'}, {srcset: 'data:,a 1w &#x200A;1h', expect: '', desc: 'leading U+200A'}, {srcset: 'data:,a 1w &#x200C;1h', expect: '', desc: 'leading U+200C'}, {srcset: 'data:,a 1w &#x200D;1h', expect: '', desc: 'leading U+200D'}, {srcset: 'data:,a 1w &#x202F;1h', expect: '', desc: 'leading U+202F'}, {srcset: 'data:,a 1w &#x205F;1h', expect: '', desc: 'leading U+205F'}, {srcset: 'data:,a 1w &#x3000;1h', expect: '', desc: 'leading U+3000'}, {srcset: 'data:,a 1w &#xFEFF;1h', expect: '', desc: 'leading U+FEFF'} ] } ]; // HTML Entities are much easier to troubleshoot in console. he.encode.options.useNamedReferences = true; function runTest(test) { var origAttr = test.srcset; var attrDecoded = he.decode(origAttr); var parsed = parseSrcset(attrDecoded); var firstCandidate = parsed[0]; var url = ""; var encodedUrl = ""; if (firstCandidate) { url = firstCandidate.url; } // Must re-encode url prior to comparison with expected string. if (url) { encodedUrl = he.encode(url); } console.log(""); console.log(test.desc); console.log("origAttr: '" + origAttr + "'"); console.log("attrDecoded: '" + attrDecoded + "'"); console.log("parsed: ", parsed); console.log("url: '" + url + "'"); console.log("encodedUrl: '" + encodedUrl + "'"); tdd.test( test.desc , function() { assert.strictEqual(encodedUrl, test.expect, "passed" ); }); } function runTestGroup(testGroup) { var j; var testArray = testGroup.testArray; // Group Tests tdd.suite(testGroup.groupName, function() { for (j = 0; j < testArray.length; j++) { runTest(testArray[j]); } }); } var i; var w3CtestsLength = w3Ctests.length; for (i = 0; i < w3CtestsLength; i++) { runTestGroup(w3Ctests[i]); } // tdd.test('First Test', function () { // var parsed = parseSrcset('data:,a 1x'); // var url = parsed[0].url; // // console.log("parsed: ", parsed); // console.log("url: ", url); // // assert.strictEqual(parsed, parsed, 'should be'); // // // assert.strictEqual(url, 'data:,a', 'should be'); // }); // assert.strictEqual(parseSrcset('data:,a 1x')[0], 'data:,a', 'plain url with descriptor'); // tdd.test('Second Test', function () { // assert.strictEqual(5, 5, '5 is itself, right?'); // }); }); });
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/parse-srcset/tests/unit/ps.js
JavaScript
apache-2.0
21,793
/* * Copyright (C) 2014-2015 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. */ package gobblin.runtime; import java.util.Collection; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.collect.Queues; import com.google.common.util.concurrent.AbstractIdleService; import gobblin.configuration.WorkUnitState; import gobblin.source.workunit.WorkUnit; import gobblin.util.ExecutorsUtils; /** * A class for managing {@link WorkUnit}s. * * <p> * It's responsibilities include adding new {@link WorkUnit}s and running * them locally. To run a {@link WorkUnit}, a {@link Task} is first * created based on it and the {@link Task} is scheduled and executed * through the {@link TaskExecutor}. * </p> * * @author ynli */ @Deprecated public class WorkUnitManager extends AbstractIdleService { private static final Logger LOG = LoggerFactory.getLogger(WorkUnitManager.class); // This is used to store submitted work units private final BlockingQueue<WorkUnitState> workUnitQueue; // This is used to run the handler private final ExecutorService executorService; // This handler that handles running work units locally private final WorkUnitHandler workUnitHandler; public WorkUnitManager(TaskExecutor taskExecutor, TaskStateTracker taskStateTracker) { // We need a blocking queue to support the producer-consumer model // for managing the submission and execution of work units, and we // need a priority queue to support priority-based execution of // work units. this.workUnitQueue = Queues.newLinkedBlockingQueue(); this.executorService = Executors.newSingleThreadExecutor(ExecutorsUtils.newThreadFactory(Optional.of(LOG))); this.workUnitHandler = new WorkUnitHandler(this.workUnitQueue, taskExecutor, taskStateTracker); } @Override protected void startUp() throws Exception { LOG.info("Starting the work unit manager"); this.executorService.execute(this.workUnitHandler); } @Override protected void shutDown() throws Exception { LOG.info("Stopping the work unit manager"); this.workUnitHandler.stop(); ExecutorsUtils.shutdownExecutorService(this.executorService, Optional.of(LOG)); } /** * Add a collection of {@link WorkUnitState}s. * * @param workUnitStates the collection of {@link WorkUnitState}s to add */ public void addWorkUnits(Collection<WorkUnitState> workUnitStates) { this.workUnitQueue.addAll(workUnitStates); } /** * Add a single {@link WorkUnitState}. * * @param workUnitState the {@link WorkUnitState} to add */ public void addWorkUnit(WorkUnitState workUnitState) { this.workUnitQueue.add(workUnitState); } /** * A handler that does the actual work of running {@link WorkUnit}s locally. */ private static class WorkUnitHandler implements Runnable { private final BlockingQueue<WorkUnitState> workUnitQueue; private final TaskExecutor taskExecutor; private final TaskStateTracker taskStateTracker; public WorkUnitHandler(BlockingQueue<WorkUnitState> workUnitQueue, TaskExecutor taskExecutor, TaskStateTracker taskStateTracker) { this.workUnitQueue = workUnitQueue; this.taskExecutor = taskExecutor; this.taskStateTracker = taskStateTracker; } // Tells if the handler is asked to stop private volatile boolean stopped = false; @Override @SuppressWarnings("unchecked") public void run() { while (!this.stopped) { try { // Take one work unit at a time from the queue WorkUnitState workUnitState = this.workUnitQueue.poll(5, TimeUnit.SECONDS); if (workUnitState == null) { continue; } // Create a task based off the work unit Task task = new Task(new TaskContext(workUnitState), this.taskStateTracker, taskExecutor, Optional.<CountDownLatch>absent()); // And then execute the task this.taskExecutor.execute(task); } catch (InterruptedException ie) { // Ignored } } } /** * Ask the handler to stop. */ public void stop() { this.stopped = true; } } }
slietz/gobblin
gobblin-runtime/src/main/java/gobblin/runtime/WorkUnitManager.java
Java
apache-2.0
4,913
/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <utility> #include <string> #include "util/hash.h" #include "util/sstream.h" #include "library/private.h" #include "library/module.h" #include "library/fingerprint.h" namespace lean { struct private_ext : public environment_extension { unsigned m_counter; name_map<name> m_inv_map; // map: hidden-name -> user-name /* We store private prefixes to make sure register_private_name is used correctly. This information does not need to be stored in .olean files. */ name_set m_private_prefixes; private_ext():m_counter(0) {} }; struct private_ext_reg { unsigned m_ext_id; private_ext_reg() { m_ext_id = environment::register_extension(std::make_shared<private_ext>()); } }; static private_ext_reg * g_ext = nullptr; static private_ext const & get_extension(environment const & env) { return static_cast<private_ext const &>(env.get_extension(g_ext->m_ext_id)); } static environment update(environment const & env, private_ext const & ext) { return env.update(g_ext->m_ext_id, std::make_shared<private_ext>(ext)); } static name * g_private = nullptr; struct private_modification : public modification { LEAN_MODIFICATION("prv") name m_name, m_real; private_modification() {} private_modification(name const & n, name const & h) : m_name(n), m_real(h) {} void perform(environment & env) const override { private_ext ext = get_extension(env); // we restore only the mapping hidden-name -> user-name (for pretty printing purposes) ext.m_inv_map.insert(m_real, m_name); ext.m_counter++; env = update(env, ext); } void serialize(serializer & s) const override { s << m_name << m_real; } static std::shared_ptr<modification const> deserialize(deserializer & d) { name n, h; d >> n >> h; return std::make_shared<private_modification>(n, h); } }; /* Make sure the mapping "hidden-name r ==> user-name n" is preserved when we close sections and export .olean files. */ static environment preserve_private_data(environment const & env, name const & r, name const & n) { return module::add(env, std::make_shared<private_modification>(n, r)); } static name mk_private_name_core(environment const & env, name const & n, optional<unsigned> const & extra_hash) { private_ext const & ext = get_extension(env); unsigned h = hash(n.hash(), ext.m_counter); uint64 f = get_fingerprint(env); h = hash(h, static_cast<unsigned>(f >> 32)); h = hash(h, static_cast<unsigned>(f)); if (extra_hash) h = hash(h, *extra_hash); return name(*g_private, h) + n; } pair<environment, name> add_private_name(environment const & env, name const & n, optional<unsigned> const & extra_hash) { name r = mk_private_name_core(env, n, extra_hash); private_ext ext = get_extension(env); ext.m_inv_map.insert(r, n); ext.m_counter++; environment new_env = update(env, ext); new_env = preserve_private_data(new_env, r, n); return mk_pair(new_env, r); } static unsigned mk_extra_hash_using_pos() { unsigned h = 31; if (auto pinfo = get_pos_info_provider()) { h = hash(pinfo->get_some_pos().first, pinfo->get_some_pos().second); char const * fname = pinfo->get_file_name(); h = hash_str(strlen(fname), fname, h); } return h; } pair<environment, name> mk_private_name(environment const & env, name const & c) { return add_private_name(env, c, optional<unsigned>(mk_extra_hash_using_pos())); } pair<environment, name> mk_private_prefix(environment const & env, optional<unsigned> const & extra_hash) { name r = mk_private_name_core(env, name(), extra_hash); private_ext ext = get_extension(env); ext.m_private_prefixes.insert(r); ext.m_counter++; environment new_env = update(env, ext); return mk_pair(new_env, r); } pair<environment, name> mk_private_prefix(environment const & env) { return mk_private_prefix(env, optional<unsigned>(mk_extra_hash_using_pos())); } static optional<name> get_private_prefix(private_ext const & ext, name n) { while (true) { if (ext.m_private_prefixes.contains(n)) return optional<name>(n); if (n.is_atomic()) return optional<name>(); n = n.get_prefix(); } } /* Return true iff a prefix of `n` is registered as a private prefix in `ext` */ static bool has_private_prefix(private_ext const & ext, name n) { return static_cast<bool>(get_private_prefix(ext, n)); } optional<name> get_private_prefix(environment const & env, name const & n) { private_ext const & ext = get_extension(env); return get_private_prefix(ext, n); } bool has_private_prefix(environment const & env, name const & n) { private_ext const & ext = get_extension(env); return has_private_prefix(ext, n); } environment register_private_name(environment const & env, name const & n, name const & prv_n) { private_ext ext = get_extension(env); if (!has_private_prefix(ext, prv_n)) { /* TODO(Leo): consider using an assertion */ throw exception(sstream() << "failed to register private name '" << prv_n << "', prefix has not been registered"); } ext.m_inv_map.insert(prv_n, n); environment new_env = update(env, ext); return preserve_private_data(new_env, prv_n, n); } optional<name> hidden_to_user_name(environment const & env, name const & n) { auto it = get_extension(env).m_inv_map.find(n); return it ? optional<name>(*it) : optional<name>(); } bool is_private(environment const & env, name const & n) { return static_cast<bool>(hidden_to_user_name(env, n)); } void initialize_private() { g_ext = new private_ext_reg(); g_private = new name("_private"); private_modification::init(); } void finalize_private() { private_modification::finalize(); delete g_private; delete g_ext; } }
leodemoura/lean
src/library/private.cpp
C++
apache-2.0
6,180
/** * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.waveprotocol.wave.model.document.parser; import org.waveprotocol.wave.model.util.CollectionUtils; import org.waveprotocol.wave.model.util.Preconditions; import org.waveprotocol.wave.model.util.StringMap; /** * Item type compatible with XmlPullParser interface * */ class Item { final ItemType type; final String name; final StringMap<String> attrs; final String data; /** * @param tagName * @param attrList * @return element start item */ public static Item elementStart(String tagName, StringMap<String> attrList) { return new Item(ItemType.START_ELEMENT, tagName, attrList, null); } /** * @param closingName * @return element end item */ public static Item elementEnd(String closingName) { return new Item(ItemType.END_ELEMENT, closingName, null, null); } /** * @param name * @param value * @return processing instruction item */ public static Item processingInstruction(String name, String value) { return new Item(ItemType.PROCESSING_INSTRUCTION, name, null, value); } /** * @param text * @return text item */ public static Item text(String text) { return new Item(ItemType.TEXT, null, null, text); } /** * @return an end element that corresponds to this start element. */ public Item startElementToEndElement() { Preconditions.checkState(type == ItemType.START_ELEMENT, "Can only convert start elements to end elements"); return new Item(ItemType.END_ELEMENT, name, null, null); } /** * @param type * @param name * @param attrs * @param data */ public Item(ItemType type, String name, StringMap<String> attrs, String data) { this.type = type; this.name = name; this.attrs = attrs == null || attrs.isEmpty() ? null : CollectionUtils.copyStringMap(attrs); this.data = data; } String getProcessingInstructionName() { checkAtProcessingInstruction(); return name; } String getProcessingInstructionValue() { checkAtProcessingInstruction(); return data; } String getTagName() { checkAtElement(); return name; } String getText() { checkAtText(); return data; } Item copy() { Item copy = new Item(type, name, attrs, data); return copy; } StringMap<String> getAttributes() { checkAtElementStart(); if (attrs == null) { return CollectionUtils.emptyMap(); } return attrs; } private void checkAtProcessingInstruction() { Preconditions.checkState(type == ItemType.PROCESSING_INSTRUCTION, "Cursor not at processing instruction"); } private void checkAtElement() { Preconditions.checkState(type == ItemType.START_ELEMENT || type == ItemType.END_ELEMENT, "Cursor not at element"); } private void checkAtElementStart() { Preconditions.checkState(type == ItemType.START_ELEMENT, "Cursor not at element start"); } private void checkAtText() { Preconditions.checkState(type == ItemType.TEXT, "Cursor not at text"); } }
nelsonsilva/wave-protocol
src/org/waveprotocol/wave/model/document/parser/Item.java
Java
apache-2.0
3,626
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.cluster.routing.allocation.decider; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; /** * This {@link AllocationDecider} limits the number of shards per node on a per * index or node-wide basis. The allocator prevents a single node to hold more * than <tt>index.routing.allocation.total_shards_per_node</tt> per index and * <tt>cluster.routing.allocation.total_shards_per_node</tt> globally during the allocation * process. The limits of this decider can be changed in real-time via a the * index settings API. * <p> * If <tt>index.routing.allocation.total_shards_per_node</tt> is reset to a negative value shards * per index are unlimited per node. Shards currently in the * {@link ShardRoutingState#RELOCATING relocating} state are ignored by this * {@link AllocationDecider} until the shard changed its state to either * {@link ShardRoutingState#STARTED started}, * {@link ShardRoutingState#INITIALIZING inializing} or * {@link ShardRoutingState#UNASSIGNED unassigned} * <p> * Note: Reducing the number of shards per node via the index update API can * trigger relocation and significant additional load on the clusters nodes. * </p> */ public class ShardsLimitAllocationDecider extends AllocationDecider { public static final String NAME = "shards_limit"; private volatile int clusterShardLimit; /** * Controls the maximum number of shards per index on a single Elasticsearch * node. Negative values are interpreted as unlimited. */ public static final Setting<Integer> INDEX_TOTAL_SHARDS_PER_NODE_SETTING = Setting.intSetting("index.routing.allocation.total_shards_per_node", -1, -1, Property.Dynamic, Property.IndexScope); /** * Controls the maximum number of shards per node on a global level. * Negative values are interpreted as unlimited. */ public static final Setting<Integer> CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING = Setting.intSetting("cluster.routing.allocation.total_shards_per_node", -1, -1, Property.Dynamic, Property.NodeScope); @Inject public ShardsLimitAllocationDecider(Settings settings, ClusterSettings clusterSettings) { super(settings); this.clusterShardLimit = CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING.get(settings); clusterSettings.addSettingsUpdateConsumer(CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING, this::setClusterShardLimit); } private void setClusterShardLimit(int clusterShardLimit) { this.clusterShardLimit = clusterShardLimit; } @Override public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { IndexMetaData indexMd = allocation.routingNodes().metaData().getIndexSafe(shardRouting.index()); final int indexShardLimit = INDEX_TOTAL_SHARDS_PER_NODE_SETTING.get(indexMd.getSettings(), settings); // Capture the limit here in case it changes during this method's // execution final int clusterShardLimit = this.clusterShardLimit; if (indexShardLimit <= 0 && clusterShardLimit <= 0) { return allocation.decision(Decision.YES, NAME, "total shard limits are disabled: [index: %d, cluster: %d] <= 0", indexShardLimit, clusterShardLimit); } int indexShardCount = 0; int nodeShardCount = 0; for (ShardRouting nodeShard : node) { // don't count relocating shards... if (nodeShard.relocating()) { continue; } nodeShardCount++; if (nodeShard.index().equals(shardRouting.index())) { indexShardCount++; } } if (clusterShardLimit > 0 && nodeShardCount >= clusterShardLimit) { return allocation.decision(Decision.NO, NAME, "too many shards for this node [%d], cluster-level limit per node: [%d]", nodeShardCount, clusterShardLimit); } if (indexShardLimit > 0 && indexShardCount >= indexShardLimit) { return allocation.decision(Decision.NO, NAME, "too many shards for this index [%s] on node [%d], index-level limit per node: [%d]", shardRouting.index(), indexShardCount, indexShardLimit); } return allocation.decision(Decision.YES, NAME, "the shard count is under index limit [%d] and cluster level node limit [%d] of total shards per node", indexShardLimit, clusterShardLimit); } @Override public Decision canRemain(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { IndexMetaData indexMd = allocation.routingNodes().metaData().getIndexSafe(shardRouting.index()); final int indexShardLimit = INDEX_TOTAL_SHARDS_PER_NODE_SETTING.get(indexMd.getSettings(), settings); // Capture the limit here in case it changes during this method's // execution final int clusterShardLimit = this.clusterShardLimit; if (indexShardLimit <= 0 && clusterShardLimit <= 0) { return allocation.decision(Decision.YES, NAME, "total shard limits are disabled: [index: %d, cluster: %d] <= 0", indexShardLimit, clusterShardLimit); } int indexShardCount = 0; int nodeShardCount = 0; for (ShardRouting nodeShard : node) { // don't count relocating shards... if (nodeShard.relocating()) { continue; } nodeShardCount++; if (nodeShard.index().equals(shardRouting.index())) { indexShardCount++; } } // Subtle difference between the `canAllocate` and `canRemain` is that // this checks > while canAllocate checks >= if (clusterShardLimit > 0 && nodeShardCount > clusterShardLimit) { return allocation.decision(Decision.NO, NAME, "too many shards for this node [%d], cluster-level limit per node: [%d]", nodeShardCount, clusterShardLimit); } if (indexShardLimit > 0 && indexShardCount > indexShardLimit) { return allocation.decision(Decision.NO, NAME, "too many shards for this index [%s] on node [%d], index-level limit per node: [%d]", shardRouting.index(), indexShardCount, indexShardLimit); } return allocation.decision(Decision.YES, NAME, "the shard count is under index limit [%d] and cluster level node limit [%d] of total shards per node", indexShardLimit, clusterShardLimit); } @Override public Decision canAllocate(RoutingNode node, RoutingAllocation allocation) { // Only checks the node-level limit, not the index-level // Capture the limit here in case it changes during this method's // execution final int clusterShardLimit = this.clusterShardLimit; if (clusterShardLimit <= 0) { return allocation.decision(Decision.YES, NAME, "total shard limits are disabled: [cluster: %d] <= 0", clusterShardLimit); } int nodeShardCount = 0; for (ShardRouting nodeShard : node) { // don't count relocating shards... if (nodeShard.relocating()) { continue; } nodeShardCount++; } if (clusterShardLimit >= 0 && nodeShardCount >= clusterShardLimit) { return allocation.decision(Decision.NO, NAME, "too many shards for this node [%d], cluster-level limit per node: [%d]", nodeShardCount, clusterShardLimit); } return allocation.decision(Decision.YES, NAME, "the shard count is under node limit [%d] of total shards per node", clusterShardLimit); } }
mmaracic/elasticsearch
core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/ShardsLimitAllocationDecider.java
Java
apache-2.0
9,164
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """Python 2<->3 compatibility module""" import sys def print_(template, *args, **kwargs): template = str(template) if args: template = template % args elif kwargs: template = template % kwargs sys.stdout.writelines(template) if sys.version_info < (3, 0): basestring = basestring from ConfigParser import ConfigParser from urllib import unquote iteritems = lambda d: d.iteritems() dictkeys = lambda d: d.keys() def reraise(t, e, tb): exec('raise t, e, tb', dict(t=t, e=e, tb=tb)) else: basestring = str from configparser import ConfigParser from urllib.parse import unquote iteritems = lambda d: d.items() dictkeys = lambda d: list(d.keys()) def reraise(t, e, tb): raise e.with_traceback(tb)
grepme/CMPUT410Lab01
virt_env/virt1/lib/python2.7/site-packages/PasteDeploy-1.5.2-py2.7.egg/paste/deploy/compat.py
Python
apache-2.0
961
package cmd import ( "fmt" "io/ioutil" "os" "os/exec" "path/filepath" docker "github.com/fsouza/go-dockerclient" "github.com/golang/glog" kapi "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/client/restclient" "k8s.io/kubernetes/pkg/runtime" s2iapi "github.com/openshift/source-to-image/pkg/api" "github.com/openshift/origin/pkg/build/api" bld "github.com/openshift/origin/pkg/build/builder" "github.com/openshift/origin/pkg/build/builder/cmd/scmauth" "github.com/openshift/origin/pkg/client" dockerutil "github.com/openshift/origin/pkg/cmd/util/docker" "github.com/openshift/origin/pkg/generate/git" "github.com/openshift/origin/pkg/version" ) type builder interface { Build(dockerClient bld.DockerClient, sock string, buildsClient client.BuildInterface, build *api.Build, gitClient bld.GitClient, cgLimits *s2iapi.CGroupLimits) error } type builderConfig struct { build *api.Build sourceSecretDir string dockerClient *docker.Client dockerEndpoint string buildsClient client.BuildInterface } func newBuilderConfigFromEnvironment() (*builderConfig, error) { cfg := &builderConfig{} var err error // build (BUILD) buildStr := os.Getenv("BUILD") glog.V(4).Infof("$BUILD env var is %s \n", buildStr) cfg.build = &api.Build{} if err = runtime.DecodeInto(kapi.Codecs.UniversalDecoder(), []byte(buildStr), cfg.build); err != nil { return nil, fmt.Errorf("unable to parse build: %v", err) } masterVersion := os.Getenv(api.OriginVersion) thisVersion := version.Get().String() if len(masterVersion) != 0 && masterVersion != thisVersion { glog.Warningf("Master version %q does not match Builder image version %q", masterVersion, thisVersion) } else { glog.V(2).Infof("Master version %q, Builder version %q", masterVersion, thisVersion) } // sourceSecretsDir (SOURCE_SECRET_PATH) cfg.sourceSecretDir = os.Getenv("SOURCE_SECRET_PATH") // dockerClient and dockerEndpoint (DOCKER_HOST) // usually not set, defaults to docker socket cfg.dockerClient, cfg.dockerEndpoint, err = dockerutil.NewHelper().GetClient() if err != nil { return nil, fmt.Errorf("error obtaining docker client: %v", err) } // buildsClient (KUBERNETES_SERVICE_HOST, KUBERNETES_SERVICE_PORT) clientConfig, err := restclient.InClusterConfig() if err != nil { return nil, fmt.Errorf("failed to get client config: %v", err) } osClient, err := client.New(clientConfig) if err != nil { return nil, fmt.Errorf("error obtaining OpenShift client: %v", err) } cfg.buildsClient = osClient.Builds(cfg.build.Namespace) return cfg, nil } func (c *builderConfig) setupGitEnvironment() ([]string, error) { gitSource := c.build.Spec.Source.Git // For now, we only handle git. If not specified, we're done if gitSource == nil { return []string{}, nil } sourceSecret := c.build.Spec.Source.SourceSecret gitEnv := []string{"GIT_ASKPASS=true"} // If a source secret is present, set it up and add its environment variables if sourceSecret != nil { // TODO: this should be refactored to let each source type manage which secrets // it accepts sourceURL, err := git.ParseRepository(gitSource.URI) if err != nil { return nil, fmt.Errorf("cannot parse build URL: %s", gitSource.URI) } scmAuths := scmauth.GitAuths(sourceURL) // TODO: remove when not necessary to fix up the secret dir permission sourceSecretDir, err := fixSecretPermissions(c.sourceSecretDir) if err != nil { return nil, fmt.Errorf("cannot fix source secret permissions: %v", err) } secretsEnv, overrideURL, err := scmAuths.Setup(sourceSecretDir) if err != nil { return nil, fmt.Errorf("cannot setup source secret: %v", err) } if overrideURL != nil { c.build.Annotations[bld.OriginalSourceURLAnnotationKey] = gitSource.URI gitSource.URI = overrideURL.String() } gitEnv = append(gitEnv, secretsEnv...) } if gitSource.HTTPProxy != nil && len(*gitSource.HTTPProxy) > 0 { gitEnv = append(gitEnv, fmt.Sprintf("HTTP_PROXY=%s", *gitSource.HTTPProxy)) gitEnv = append(gitEnv, fmt.Sprintf("http_proxy=%s", *gitSource.HTTPProxy)) } if gitSource.HTTPSProxy != nil && len(*gitSource.HTTPSProxy) > 0 { gitEnv = append(gitEnv, fmt.Sprintf("HTTPS_PROXY=%s", *gitSource.HTTPSProxy)) gitEnv = append(gitEnv, fmt.Sprintf("https_proxy=%s", *gitSource.HTTPSProxy)) } return bld.MergeEnv(os.Environ(), gitEnv), nil } // execute is responsible for running a build func (c *builderConfig) execute(b builder) error { gitEnv, err := c.setupGitEnvironment() if err != nil { return err } gitClient := git.NewRepositoryWithEnv(gitEnv) cgLimits, err := bld.GetCGroupLimits() if err != nil { return fmt.Errorf("failed to retrieve cgroup limits: %v", err) } glog.V(2).Infof("Running build with cgroup limits: %#v", *cgLimits) if err := b.Build(c.dockerClient, c.dockerEndpoint, c.buildsClient, c.build, gitClient, cgLimits); err != nil { return fmt.Errorf("build error: %v", err) } if c.build.Spec.Output.To == nil || len(c.build.Spec.Output.To.Name) == 0 { glog.Warning("Build does not have an Output defined, no output image was pushed to a registry.") } return nil } // fixSecretPermissions loweres access permissions to very low acceptable level // TODO: this method should be removed as soon as secrets permissions are fixed upstream // Kubernetes issue: https://github.com/kubernetes/kubernetes/issues/4789 func fixSecretPermissions(secretsDir string) (string, error) { secretTmpDir, err := ioutil.TempDir("", "tmpsecret") if err != nil { return "", err } cmd := exec.Command("cp", "-R", ".", secretTmpDir) cmd.Dir = secretsDir if err := cmd.Run(); err != nil { return "", err } secretFiles, err := ioutil.ReadDir(secretTmpDir) if err != nil { return "", err } for _, file := range secretFiles { if err := os.Chmod(filepath.Join(secretTmpDir, file.Name()), 0600); err != nil { return "", err } } return secretTmpDir, nil } type dockerBuilder struct{} // Build starts a Docker build. func (dockerBuilder) Build(dockerClient bld.DockerClient, sock string, buildsClient client.BuildInterface, build *api.Build, gitClient bld.GitClient, cgLimits *s2iapi.CGroupLimits) error { return bld.NewDockerBuilder(dockerClient, buildsClient, build, gitClient, cgLimits).Build() } type s2iBuilder struct{} // Build starts an S2I build. func (s2iBuilder) Build(dockerClient bld.DockerClient, sock string, buildsClient client.BuildInterface, build *api.Build, gitClient bld.GitClient, cgLimits *s2iapi.CGroupLimits) error { return bld.NewS2IBuilder(dockerClient, sock, buildsClient, build, gitClient, cgLimits).Build() } func runBuild(builder builder) { cfg, err := newBuilderConfigFromEnvironment() if err != nil { glog.Fatalf("Cannot setup builder configuration: %v", err) } err = cfg.execute(builder) if err != nil { glog.Fatalf("Error: %v", err) } } // RunDockerBuild creates a docker builder and runs its build func RunDockerBuild() { runBuild(dockerBuilder{}) } // RunSTIBuild creates a STI builder and runs its build func RunSTIBuild() { runBuild(s2iBuilder{}) }
tmckayus/oshinko-rest
vendor/github.com/openshift/origin/pkg/build/builder/cmd/builder.go
GO
apache-2.0
7,078
package customerinsights // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "net/http" ) // InteractionsClient is the the Azure Customer Insights management API provides a RESTful set of web services that // interact with Azure Customer Insights service to manage your resources. The API has entities that capture the // relationship between an end user and the Azure Customer Insights service. type InteractionsClient struct { BaseClient } // NewInteractionsClient creates an instance of the InteractionsClient client. func NewInteractionsClient(subscriptionID string) InteractionsClient { return NewInteractionsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewInteractionsClientWithBaseURI creates an instance of the InteractionsClient client. func NewInteractionsClientWithBaseURI(baseURI string, subscriptionID string) InteractionsClient { return InteractionsClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates an interaction or updates an existing interaction within a hub. // // resourceGroupName is the name of the resource group. hubName is the name of the hub. interactionName is the name of // the interaction. parameters is parameters supplied to the CreateOrUpdate Interaction operation. func (client InteractionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, hubName string, interactionName string, parameters InteractionResourceFormat) (result InteractionsCreateOrUpdateFuture, err error) { if err := validation.Validate([]validation.Validation{ {TargetValue: interactionName, Constraints: []validation.Constraint{{Target: "interactionName", Name: validation.MaxLength, Rule: 128, Chain: nil}, {Target: "interactionName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "interactionName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9_]+$`, Chain: nil}}}}); err != nil { return result, validation.NewErrorWithValidationError(err, "customerinsights.InteractionsClient", "CreateOrUpdate") } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, hubName, interactionName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "CreateOrUpdate", nil, "Failure preparing request") return } result, err = client.CreateOrUpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "CreateOrUpdate", result.Response(), "Failure sending request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client InteractionsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, hubName string, interactionName string, parameters InteractionResourceFormat) (*http.Request, error) { pathParameters := map[string]interface{}{ "hubName": autorest.Encode("path", hubName), "interactionName": autorest.Encode("path", interactionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-04-26" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsJSON(), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/interactions/{interactionName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client InteractionsClient) CreateOrUpdateSender(req *http.Request) (future InteractionsCreateOrUpdateFuture, err error) { sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client)) future.Future = azure.NewFuture(req) future.req = req _, err = future.Done(sender) if err != nil { return } err = autorest.Respond(future.Response(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted)) return } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client InteractionsClient) CreateOrUpdateResponder(resp *http.Response) (result InteractionResourceFormat, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Get gets information about the specified interaction. // // resourceGroupName is the name of the resource group. hubName is the name of the hub. interactionName is the name of // the interaction. localeCode is locale of interaction to retrieve, default is en-us. func (client InteractionsClient) Get(ctx context.Context, resourceGroupName string, hubName string, interactionName string, localeCode string) (result InteractionResourceFormat, err error) { req, err := client.GetPreparer(ctx, resourceGroupName, hubName, interactionName, localeCode) if err != nil { err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client InteractionsClient) GetPreparer(ctx context.Context, resourceGroupName string, hubName string, interactionName string, localeCode string) (*http.Request, error) { pathParameters := map[string]interface{}{ "hubName": autorest.Encode("path", hubName), "interactionName": autorest.Encode("path", interactionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-04-26" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(localeCode) > 0 { queryParameters["locale-code"] = autorest.Encode("query", localeCode) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/interactions/{interactionName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client InteractionsClient) GetSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client InteractionsClient) GetResponder(resp *http.Response) (result InteractionResourceFormat, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListByHub gets all interactions in the hub. // // resourceGroupName is the name of the resource group. hubName is the name of the hub. localeCode is locale of // interaction to retrieve, default is en-us. func (client InteractionsClient) ListByHub(ctx context.Context, resourceGroupName string, hubName string, localeCode string) (result InteractionListResultPage, err error) { result.fn = client.listByHubNextResults req, err := client.ListByHubPreparer(ctx, resourceGroupName, hubName, localeCode) if err != nil { err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "ListByHub", nil, "Failure preparing request") return } resp, err := client.ListByHubSender(req) if err != nil { result.ilr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "ListByHub", resp, "Failure sending request") return } result.ilr, err = client.ListByHubResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "ListByHub", resp, "Failure responding to request") } return } // ListByHubPreparer prepares the ListByHub request. func (client InteractionsClient) ListByHubPreparer(ctx context.Context, resourceGroupName string, hubName string, localeCode string) (*http.Request, error) { pathParameters := map[string]interface{}{ "hubName": autorest.Encode("path", hubName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-04-26" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(localeCode) > 0 { queryParameters["locale-code"] = autorest.Encode("query", localeCode) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/interactions", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByHubSender sends the ListByHub request. The method will close the // http.Response Body if it receives an error. func (client InteractionsClient) ListByHubSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ListByHubResponder handles the response to the ListByHub request. The method always // closes the http.Response Body. func (client InteractionsClient) ListByHubResponder(resp *http.Response) (result InteractionListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listByHubNextResults retrieves the next set of results, if any. func (client InteractionsClient) listByHubNextResults(lastResults InteractionListResult) (result InteractionListResult, err error) { req, err := lastResults.interactionListResultPreparer() if err != nil { return result, autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "listByHubNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListByHubSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "listByHubNextResults", resp, "Failure sending next results request") } result, err = client.ListByHubResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "listByHubNextResults", resp, "Failure responding to next results request") } return } // ListByHubComplete enumerates all values, automatically crossing page boundaries as required. func (client InteractionsClient) ListByHubComplete(ctx context.Context, resourceGroupName string, hubName string, localeCode string) (result InteractionListResultIterator, err error) { result.page, err = client.ListByHub(ctx, resourceGroupName, hubName, localeCode) return } // SuggestRelationshipLinks suggests relationships to create relationship links. // // resourceGroupName is the name of the resource group. hubName is the name of the hub. interactionName is the name of // the interaction. func (client InteractionsClient) SuggestRelationshipLinks(ctx context.Context, resourceGroupName string, hubName string, interactionName string) (result SuggestRelationshipLinksResponse, err error) { req, err := client.SuggestRelationshipLinksPreparer(ctx, resourceGroupName, hubName, interactionName) if err != nil { err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "SuggestRelationshipLinks", nil, "Failure preparing request") return } resp, err := client.SuggestRelationshipLinksSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "SuggestRelationshipLinks", resp, "Failure sending request") return } result, err = client.SuggestRelationshipLinksResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "customerinsights.InteractionsClient", "SuggestRelationshipLinks", resp, "Failure responding to request") } return } // SuggestRelationshipLinksPreparer prepares the SuggestRelationshipLinks request. func (client InteractionsClient) SuggestRelationshipLinksPreparer(ctx context.Context, resourceGroupName string, hubName string, interactionName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "hubName": autorest.Encode("path", hubName), "interactionName": autorest.Encode("path", interactionName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2017-04-26" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/interactions/{interactionName}/suggestRelationshipLinks", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // SuggestRelationshipLinksSender sends the SuggestRelationshipLinks request. The method will close the // http.Response Body if it receives an error. func (client InteractionsClient) SuggestRelationshipLinksSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // SuggestRelationshipLinksResponder handles the response to the SuggestRelationshipLinks request. The method always // closes the http.Response Body. func (client InteractionsClient) SuggestRelationshipLinksResponder(resp *http.Response) (result SuggestRelationshipLinksResponse, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
maxamillion/origin
vendor/github.com/Azure/azure-sdk-for-go/services/customerinsights/mgmt/2017-04-26/customerinsights/interactions.go
GO
apache-2.0
16,211
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0;url=http://microsite.omniture.com/t2/help/en_US/mobile/win8/"> <script language="javascript"> window.location.href = "http://microsite.omniture.com/t2/help/en_US/mobile/win8/" </script> <title>Page Redirection</title> </head> <body> <p>The latest documentation is available online at <a href="http://microsite.omniture.com/t2/help/en_US/mobile/win8/">http://microsite.omniture.com/t2/help/en_US/mobile/win8/</a></p>> </body> </html>
iOSTestApps/phonegap-app-developer
plugins/ADBMobile/sdks/Windows8/documentation.html
HTML
apache-2.0
577
# Copyright (C) 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Generated globbing source file # This file will be automatically regenerated if deleted, do not edit by hand. # If you add a new file to the directory, just delete this file, run any cmake # build and the file will be recreated, check in the new version. set(files a.go button.go canvas.go context2d.go div.go document.go element.go events.go node.go paragraph.go select.go span.go style.go table.go text.go window.go ) set(dirs )
dsrbecky/gapid
test/robot/web/client/dom/CMakeFiles.cmake
CMake
apache-2.0
1,084
/** * Copyright 2007-2016 Jordi Hernández Sellés, Ibrahim Chaehoi * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package net.jawr.web.resource.bundle.postprocess.impl; import java.io.IOException; import net.jawr.web.resource.bundle.postprocess.AbstractChainedResourceBundlePostProcessor; import net.jawr.web.resource.bundle.postprocess.BundleProcessingStatus; import net.jawr.web.resource.bundle.postprocess.ResourceBundlePostProcessor; /** * Wrapper class for custom user made postprocessors. Adds chaining * functionality to the custom postprocessor. * * @author Jordi Hernández Sellés * @author Ibrahim Chaehoi */ public class CustomPostProcessorChainWrapper extends AbstractChainedResourceBundlePostProcessor { /** The custom post processor */ private final ResourceBundlePostProcessor customPostProcessor; /** * Constructor * * @param id * the ID of the post processor * @param customPostProcessor * Custom implementation of ResourceBundlePostProcessor to wrap * with chaining. * @param isVariantPostProcessor * the flag indicating if it's a variant post processor */ public CustomPostProcessorChainWrapper(String id, ResourceBundlePostProcessor customPostProcessor, boolean isVariantPostProcessor) { super(id); this.customPostProcessor = customPostProcessor; this.isVariantPostProcessor = isVariantPostProcessor; } /* * (non-Javadoc) * * @see net.jawr.web.resource.bundle.postprocess. * AbstractChainedResourceBundlePostProcessor#doPostProcessBundle(net.jawr. * web.resource.bundle.postprocess.BundleProcessingStatus, * java.lang.StringBuffer) */ @Override protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleData) throws IOException { return customPostProcessor.postProcessBundle(status, bundleData); } }
davidwebster48/jawr-main-repo
jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/postprocess/impl/CustomPostProcessorChainWrapper.java
Java
apache-2.0
2,385
// bslstl_treenode.h -*-C++-*- #ifndef INCLUDED_BSLSTL_TREENODE #define INCLUDED_BSLSTL_TREENODE #ifndef INCLUDED_BSLS_IDENT #include <bsls_ident.h> #endif BSLS_IDENT("$Id: $") //@PURPOSE: Provide a POD-like tree node type holding a parameterized value. // //@CLASSES: // bslstl::TreeNode: a tree node holding a parameterized value // //@SEE_ALSO: bslstl_treenodefactory, bslstl_set, bslstl_map // //@DESCRIPTION: This component provides a single POD-like class, 'TreeNode', // used to represent a node in a red-black binary search tree holding a value // of a parameterized type. A 'TreeNode' inherits from 'bslalg::RbTreeNode', // so it may be used with 'bslalg::RbTreeUtil' functions, and adds an attribute // 'value' of the parameterized 'VALUE'. The following inheritance hierarchy // diagram shows the classes involved and their methods: //.. // ,----------------. // ( bslstl::TreeNode ) // `----------------' // | value // V // ,------------------. // ( bslalg::RbTreeNode ) // `------------------' // ctor // dtor // makeBlack // makeRed // setParent // setLeftChild // setRightChild // setColor // toggleColor // parent // leftChild // rightChild // isBlack // isRed // color //.. // This class is "POD-like" to facilitate efficient allocation and use in the // context of a container implementation. In order to meet the essential // requirements of a POD type, both this 'class' and 'bslalg::RbTreeNode' do // not define a constructor or destructor. The manipulator, 'value', returns a // modifiable reference to the object that may be constructed in-place by the // appropriate 'bsl::allocator_traits' object. // ///Usage ///----- // In this section we show intended usage of this component. // ///Example 1: Allocating and Deallocating 'TreeNode' Objects. /// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // In the following example we define a factory class for allocating and // destroying 'TreeNode' objects. // // First, we define the interface for the class 'NodeFactory': //.. // template <class VALUE, class ALLOCATOR> // class NodeFactory { //.. // The parameterized 'ALLOCATOR' is intended to allocate objects of the // parameterized 'VALUE', so to use it to allocate objects of 'TreeNode<VALUE>' // we must rebind it to the tree node type. Note that in general, we use // 'allocator_traits' to perform actions using an allocator (including the // rebind below): //.. // // PRIVATE TYPES // typedef typename bsl::allocator_traits<ALLOCATOR>::template // rebind_traits<TreeNode<VALUE> > AllocatorTraits; // typedef typename AllocatorTraits::allocator_type NodeAllocator; // // // DATA // NodeAllocator d_allocator; // rebound tree-node allocator // // // NOT IMPLEMENTED // NodeFactory(const NodeFactory&); // NodeFactory& operator=(const NodeFactory&); // // public: // // CREATORS // NodeFactory(const ALLOCATOR& allocator); // // Create a tree node-factory that will use the specified // // 'allocator' to supply memory. // // // MANIPULATORS // TreeNode<VALUE> *createNode(const VALUE& value); // // Create a new 'TreeNode' object holding the specified 'value'. // // void deleteNode(bslalg::RbTreeNode *node); // // Destroy and deallocate the specified 'node'. The behavior is // // undefined unless 'node' is the address of a // // 'TreeNode<VALUE>' object. // }; //.. // Now, we implement the 'NodeFactory' type: //.. // template <class VALUE, class ALLOCATOR> // inline // NodeFactory<VALUE, ALLOCATOR>::NodeFactory(const ALLOCATOR& allocator) // : d_allocator(allocator) // { // } //.. // We implement the 'createNode' function by using the rebound // 'allocator_traits' for our allocator to in-place copy-construct the // supplied 'value' into the 'value' data member of our 'result' node // object. Note that 'TreeNode' is a POD-like type, without a constructor, so // we do not need to call its constructor here: //.. // template <class VALUE, class ALLOCATOR> // inline // TreeNode<VALUE> * // NodeFactory<VALUE, ALLOCATOR>::createNode(const VALUE& value) // { // TreeNode<VALUE> *result = AllocatorTraits::allocate(d_allocator, 1); // AllocatorTraits::construct(d_allocator, // bsls::Util::addressOf(result->value()), // value); // return result; // } //.. // Finally, we implement the function 'deleteNode'. Again, we use the // rebound 'allocator_traits' for our tree node type, this time to destroy the // 'value' date member of node, and then to deallocate its footprint. Note // that 'TreeNode' is a POD-like type, so we do not need to call its destructor // here: //.. // template <class VALUE, class ALLOCATOR> // inline // void NodeFactory<VALUE, ALLOCATOR>::deleteNode(bslalg::RbTreeNode *node) // { // TreeNode<VALUE> *treeNode = static_cast<TreeNode<VALUE> *>(node); // AllocatorTraits::destroy(d_allocator, // bsls::Util::addressOf(treeNode->value())); // AllocatorTraits::deallocate(d_allocator, treeNode, 1); // } //.. // ///Example 2: Creating a Simple Tree of 'TreeNode' Objects. /// - - - - - - - - - - - - - - - - - - - - - - - - - - - - // In the following example we create a container-type 'Set' for // holding a set of values of a parameterized 'VALUE'. // // First, we define a comparator for 'VALUE' of 'TreeNode<VALUE>' objects. // This type is designed to be supplied to functions in 'bslalg::RbTreeUtil'. // Note that, for simplicity, this type uses 'operator<' to compare values, // rather than a client defined comparator type. //.. // template <class VALUE> // class Comparator { // public: // // CREATORS // Comparator() {} // // Create a node-value comparator. // // // ACCESSORS // bool operator()(const VALUE& lhs, // const bslalg::RbTreeNode& rhs) const; // bool operator()(const bslalg::RbTreeNode& lhs, // const VALUE& rhs) const; // // Return 'true' if the specified 'lhs' is less than (ordered // // before) the specified 'rhs', and 'false' otherwise. The // // behavior is undefined unless the supplied 'bslalg::RbTreeNode' // // object is of the derived 'TreeNode<VALUE>' type. // }; //.. // Then, we implement the comparison methods of 'Comparator'. Note that the // supplied 'RbTreeNode' objects must be 'static_cast' to // 'TreeNode<VALUE>' to access their value: //.. // template <class VALUE> // inline // bool Comparator<VALUE>::operator()(const VALUE& lhs, // const bslalg::RbTreeNode& rhs) const // { // return lhs < static_cast<const TreeNode<VALUE>& >(rhs).value(); // } // // template <class VALUE> // inline // bool Comparator<VALUE>::operator()(const bslalg::RbTreeNode& lhs, // const VALUE& rhs) const // { // return static_cast<const TreeNode<VALUE>& >(lhs).value() < rhs; // } //.. // Now, having defined the requisite helper types, we define the public // interface for 'Set'. Note that for the purposes of illustrating the use of // 'TreeNode' a number of simplifications have been made. For example, this // implementation provides only 'insert', 'remove', 'isMember', and // 'numMembers' operations: //.. // template <class VALUE, // class ALLOCATOR = bsl::allocator<VALUE> > // class Set { // // PRIVATE TYPES // typedef Comparator<VALUE> ValueComparator; // typedef NodeFactory<VALUE, ALLOCATOR> Factory; // // // DATA // bslalg::RbTreeAnchor d_tree; // tree of node objects // Factory d_factory; // allocator for node objects // // // NOT IMPLEMENTED // Set(const Set&); // Set& operator=(const Set&); // // public: // // CREATORS // Set(const ALLOCATOR& allocator = ALLOCATOR()); // // Create an empty set. Optionally specify a 'allocator' used to // // supply memory. If 'allocator' is not specified, a default // // constructed 'ALLOCATOR' object is used. // // ~Set(); // // Destroy this set. // // // MANIPULATORS // void insert(const VALUE& value); // // Insert the specified value into this set. // // bool remove(const VALUE& value); // // If 'value' is a member of this set, then remove it and return // // 'true', and return 'false' otherwise. // // // ACCESSORS // bool isElement(const VALUE& value) const; // // Return 'true' if the specified 'value' is a member of this set, // // and 'false' otherwise. // // int numElements() const; // // Return the number of elements in this set. // }; //.. // Now, we define the implementation of 'Set': //.. // // CREATORS // template <class VALUE, class ALLOCATOR> // inline // Set<VALUE, ALLOCATOR>::Set(const ALLOCATOR& allocator) // : d_tree() // , d_factory(allocator) // { // } // // template <class VALUE, class ALLOCATOR> // inline // Set<VALUE, ALLOCATOR>::~Set() // { // bslalg::RbTreeUtil::deleteTree(&d_tree, &d_factory); // } // // // MANIPULATORS // template <class VALUE, class ALLOCATOR> // void Set<VALUE, ALLOCATOR>::insert(const VALUE& value) // { // int comparisonResult; // ValueComparator comparator; // bslalg::RbTreeNode *parent = // bslalg::RbTreeUtil::findUniqueInsertLocation(&comparisonResult, // &d_tree, // comparator, // value); // if (0 != comparisonResult) { // bslalg::RbTreeNode *node = d_factory.createNode(value); // bslalg::RbTreeUtil::insertAt(&d_tree, // parent, // comparisonResult < 0, // node); // } // } // // template <class VALUE, class ALLOCATOR> // bool Set<VALUE, ALLOCATOR>::remove(const VALUE& value) // { // bslalg::RbTreeNode *node = // bslalg::RbTreeUtil::find(d_tree, ValueComparator(), value); // if (node) { // bslalg::RbTreeUtil::remove(&d_tree, node); // d_factory.deleteNode(node); // } // return node; // } // // // ACCESSORS // template <class VALUE, class ALLOCATOR> // inline // bool Set<VALUE, ALLOCATOR>::isElement(const VALUE& value) const // { // ValueComparator comparator; // return bslalg::RbTreeUtil::find(d_tree, comparator, value); // } // // template <class VALUE, class ALLOCATOR> // inline // int Set<VALUE, ALLOCATOR>::numElements() const // { // return d_tree.numNodes(); // } //.. // Notice that the definition and implementation of 'Set' never directly // uses the 'TreeNode' type, but instead use it indirectly through // 'Comparator', and 'NodeFactory', and uses it via its base-class // 'bslalg::RbTreeNode'. // // Finally, we test our 'Set'. //.. // Set<int> set; // assert(0 == set.numElements()); // // set.insert(1); // assert(set.isElement(1)); // assert(1 == set.numElements()); // // set.insert(1); // assert(set.isElement(1)); // assert(1 == set.numElements()); // // set.insert(2); // assert(set.isElement(1)); // assert(set.isElement(2)); // assert(2 == set.numElements()); //.. #ifndef INCLUDED_BSLALG_RBTREENODE #include <bslalg_rbtreenode.h> #endif namespace BloombergLP { namespace bslstl { // ============== // class TreeNode // ============== template <class VALUE> class TreeNode : public bslalg::RbTreeNode { // This POD-like 'class' describes a node suitable for use in a red-black // binary search tree of values of the parameterized 'VALUE'. This class // is a "POD-like" to facilitate efficient allocation and use in the // context of a container implementation. In order to meet the essential // requirements of a POD type, this 'class' does not define a constructor // or destructor. The manipulator, 'value', returns a modifiable reference // to 'd_value' so that it may be constructed in-place by the appropriate // 'bsl::allocator_traits' object. // DATA VALUE d_value; // payload value private: // The following functions are not defined because a 'TreeNode' should // never be constructed, destructed, or assigned. The 'd_value' member // should be separately constructed and destroyed using an appropriate // 'bsl::allocator_traits' object. TreeNode(); // Declared but not defined TreeNode(const TreeNode&); // Declared but not defined TreeNode& operator=(const TreeNode&); // Declared but not defined ~TreeNode(); // Declared but not defined public: // MANIPULATORS VALUE& value(); // Return a reference providing modifiable access to the 'value' of // this object. // ACCESSORS const VALUE& value() const; // Return a reference providing non-modifiable access to the 'value' of // this object. }; // =========================================================================== // TEMPLATE AND INLINE FUNCTION DEFINITIONS // =========================================================================== template <class VALUE> inline VALUE& TreeNode<VALUE>::value() { return d_value; } template <class VALUE> inline const VALUE& TreeNode<VALUE>::value() const { return d_value; } } // close package namespace } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ----------------------------------
jmptrader/bde
groups/bsl/bslstl/bslstl_treenode.h
C
apache-2.0
15,011
package ch.usi.dag.disl.staticcontext.uid; import ch.usi.dag.disl.staticcontext.AbstractStaticContext; public abstract class AbstractUniqueId extends AbstractStaticContext { private IdHolder idHolder; // constructor for static context protected AbstractUniqueId () { idHolder = null; } // constructor for singleton protected AbstractUniqueId ( AbstractIdCalculator idCalc, String outputFileName ) { idHolder = new IdHolder(idCalc, outputFileName); } public int get() { return getSingleton().idHolder.getID(idFor()); } // String value for which the id will be computed protected abstract String idFor (); // Singleton that holds the data protected abstract AbstractUniqueId getSingleton (); }
msteindorfer/disl-svn-2013-10-01
src/ch/usi/dag/disl/staticcontext/uid/AbstractUniqueId.java
Java
apache-2.0
729
package sampleclean.clean.deduplication.join import org.apache.spark.SparkContext import org.apache.spark.SparkContext._ import org.apache.spark.broadcast.Broadcast import org.apache.spark.rdd.RDD import org.apache.spark.sql._ import sampleclean.clean.featurize.AnnotatedSimilarityFeaturizer import scala.collection.Seq /** * A PassJoin is an implementation of a Similarity Join optimized * for String comparisons. Currently, this algorithm * is only supported by the EditBlocking Similarity Featurizer. * In a distributed environment, this optimization involves * broadcasting a series of maps to each node. * * '''Note:''' because the algorithm may collect large RDDs into maps by using * driver memory, java heap problems could arise. In this case, it is * recommended to increase allocated driver memory through Spark configuration * spark.driver.memory * * @param sc Spark Context * @param featurizer Similarity Featurizer optimized for [[PassJoin]] */ class PassJoin( @transient sc: SparkContext, featurizer: AnnotatedSimilarityFeaturizer) extends SimilarityJoin(sc,featurizer,false) { @Override override def join(rddA: RDD[Row], rddB: RDD[Row], sampleA:Boolean = false): RDD[(Row,Row)] = { println("[SampleClean] Starting Broadcast Pass Join") if (!featurizer.usesStringPrefixFiltering) { super.join(rddA, rddB, sampleA) } else { val intThreshold = featurizer.threshold.toInt var largeTableSize = rddB.count() var smallTableSize = rddA.count() var smallTable = rddA var largeTable = rddB val isSelfJoin = !sampleA var smallTableWithId: RDD[(String, (Seq[String], String, Row))] = null //Add a record ID into smallTable. Id is a unique id assigned to each row. if(!sampleA) { smallTableWithId = smallTable.zipWithUniqueId() .map(x => { val block = featurizer.tokenizer.tokenize(x._1, featurizer.getCols(false)) (x._2.toString, (block, block.mkString(" "), x._1)) }).cache() } else { smallTableWithId = smallTable.map(x => { val block = featurizer.tokenizer.tokenize(x, featurizer.getCols(false)) (x(0).asInstanceOf[String], (block, block.mkString(" "), x)) }).cache() } //find max string length in sample val maxLen = smallTableWithId.map(_._2._2.length).top(1).toSeq(0) // build hashmap for possible substrings and segments according to string length val likelyRange = 0 to maxLen val subMap = likelyRange.map(length => (length, genOptimalSubs(length, intThreshold))).toMap val segMap = { if (isSelfJoin) likelyRange.map(length => (length, genEvenSeg(length, intThreshold))).toMap else (0 to maxLen + intThreshold).map(length => (length, genEvenSeg(length, intThreshold))).toMap } // Build an inverted index with segments val invertedIndex = smallTableWithId.flatMap { case (id, (list, string, row)) => val ranges = segMap(string.length) val segments = ranges.map(x => (x._1, string.substring(x._2, x._2 + x._3), x._4)) segments.map(x => (x, id)) }.groupByKey().map(x => (x._1, x._2.toSeq.distinct)).cache() //Broadcast sample data to all nodes val broadcastIndex: Broadcast[collection.Map[(Int, String, Int), Seq[String]]] = sc.broadcast(invertedIndex.collectAsMap()) val broadcastData: Broadcast[collection.Map[String, (Seq[String], String, Row)]] = sc.broadcast(smallTableWithId.collectAsMap()) val broadcastSubMap = sc.broadcast(subMap) val scanTable: RDD[(String, (Seq[String], String, Row))] = { if (isSelfJoin) smallTableWithId else { largeTable.map(row => { val key = featurizer.tokenizer.tokenize(row,featurizer.getCols(false)) (row(0).asInstanceOf[String], (key,key.mkString(" "), row)) }) } } //Generate the candidates whose segments and substrings have overlap, and then verify their edit distance similarity scanTable.flatMap({ case (id1, (key1, string1, row1)) => if (string1.length > maxLen + intThreshold && !isSelfJoin) List() else { val broadcastDataValue = broadcastData.value val broadcastIndexValue = broadcastIndex.value val broadcastSubMapValue = broadcastSubMap.value val substrings = broadcastSubMapValue(string1.length).map { case (pid, stPos, len, segLen) => (pid, string1.substring(stPos, stPos + len), segLen) } substrings.foldLeft(Seq[String]()) { case (ids, (pid: Int, string: String, segLen: Int)) => ids ++ broadcastIndexValue.getOrElse((pid, string, segLen), List()).distinct }.map { case id2 => val (key2, string2, row2) = broadcastDataValue(id2) if (string1.length < string2.length && isSelfJoin) (null, null, false) else if (string1.length == string2.length && id2.toString >= id1.toString && isSelfJoin) { (null, null, false) } else if (id2.toString == id1.toString) { (null, null, false) } else { val similar = { featurizer.optimizedSimilarity(key1, key2, intThreshold, Map[String, Double]())._1 } (string2, row2, similar) } }.withFilter(_._3).map { case (key2, row2, similar) => (row1, row2) } } }).distinct() } } /** * Generates string segments for faster pair filtering, as per PassJoin algorithm. * @param seg_str_len length of string to be segmented *@param threshold specified threshold */ private def genEvenSeg(seg_str_len: Int, threshold: Int): Seq[(Int, Int, Int, Int)] = { val partNum = threshold + 1 var segLength = seg_str_len / partNum var segStartPos = 0 (0 until partNum).map { pid => if (pid == 0) (segStartPos, segLength) else { segStartPos += segLength segLength = { if (pid == (partNum - seg_str_len % partNum)) // almost evenly partition segLength + 1 else segLength } } (pid, segStartPos, segLength, seg_str_len) } } /** * Generates optimal tuples with substring information for a given string length. * This is part of the PassJoin algorithm. * @param strLength string length * @param threshold specified threshold * @param selfJoin if true, assumes a self-join is being performed */ private def genOptimalSubs(strLength: Int, threshold: Int, selfJoin: Boolean = false): Seq[(Int, Int, Int, Int)] = { val candidateLengths = { if (!selfJoin) strLength - threshold to strLength + threshold else strLength - threshold to strLength } candidateLengths.flatMap(genSubstrings(_, strLength, threshold)).distinct } /** * Generates tuples with substring information for a given string length. * This is part of the PassJoin algorithm. * @param seg_str_len segment length * @param sub_str_len substring length * @param threshold specified threshold */ private def genSubstrings(seg_str_len: Int, sub_str_len: Int, threshold: Int): Seq[(Int, Int, Int, Int)] = { val partNum = threshold + 1 // first value is segment starting position, second value is segment length val segInfo = genEvenSeg(seg_str_len, threshold) (0 until partNum).flatMap { pid => for (stPos: Int <- Seq(0, segInfo(pid)._2 - pid, segInfo(pid)._2 + (sub_str_len - seg_str_len) - (threshold - pid)).max to Seq(sub_str_len - segInfo(pid)._3, segInfo(pid)._2 + pid, segInfo(pid)._2 + (sub_str_len - seg_str_len) + (threshold - pid)).min) yield (pid, stPos, segInfo(pid)._3, seg_str_len) } } }
agilemobiledev/sampleclean-async
src/main/scala/sampleclean/clean/deduplication/join/PassJoin.scala
Scala
apache-2.0
8,070
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.modules.session.catalina; import java.io.IOException; import org.apache.coyote.OutputBuffer; import org.apache.coyote.Response; import org.apache.tomcat.util.buf.ByteChunk; /** * Delegating {@link OutputBuffer} that commits sessions on write through. Output data is buffered * ahead of this object and flushed through this interface when full or explicitly flushed. */ class Tomcat7CommitSessionOutputBuffer implements OutputBuffer { private final SessionCommitter sessionCommitter; private final OutputBuffer delegate; public Tomcat7CommitSessionOutputBuffer(final SessionCommitter sessionCommitter, final OutputBuffer delegate) { this.sessionCommitter = sessionCommitter; this.delegate = delegate; } @Override public int doWrite(final ByteChunk chunk, final Response response) throws IOException { sessionCommitter.commit(); return delegate.doWrite(chunk, response); } @Override public long getBytesWritten() { return delegate.getBytesWritten(); } OutputBuffer getDelegate() { return delegate; } }
masaki-yamakawa/geode
extensions/geode-modules-tomcat7/src/main/java/org/apache/geode/modules/session/catalina/Tomcat7CommitSessionOutputBuffer.java
Java
apache-2.0
1,881
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.streaming.connectors.gcp.pubsub; import org.apache.flink.api.common.io.ratelimiting.FlinkConnectorRateLimiter; import org.apache.flink.api.common.serialization.DeserializationSchema; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.metrics.MetricGroup; import org.apache.flink.streaming.api.functions.source.SourceFunction; import org.apache.flink.streaming.api.operators.StreamingRuntimeContext; import org.apache.flink.streaming.connectors.gcp.pubsub.common.AcknowledgeIdsForCheckpoint; import org.apache.flink.streaming.connectors.gcp.pubsub.common.AcknowledgeOnCheckpoint; import org.apache.flink.streaming.connectors.gcp.pubsub.common.PubSubDeserializationSchema; import org.apache.flink.streaming.connectors.gcp.pubsub.common.PubSubSubscriber; import org.apache.flink.streaming.connectors.gcp.pubsub.common.PubSubSubscriberFactory; import com.google.auth.Credentials; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.refEq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; /** Test for {@link SourceFunction}. */ @RunWith(MockitoJUnitRunner.class) public class PubSubSourceTest { @Mock private PubSubDeserializationSchema<String> deserializationSchema; @Mock private PubSubSource.AcknowledgeOnCheckpointFactory acknowledgeOnCheckpointFactory; @Mock private AcknowledgeOnCheckpoint<String> acknowledgeOnCheckpoint; @Mock private StreamingRuntimeContext streamingRuntimeContext; @Mock private MetricGroup metricGroup; @Mock private PubSubSubscriberFactory pubSubSubscriberFactory; @Mock private Credentials credentials; @Mock private PubSubSubscriber pubsubSubscriber; @Mock private FlinkConnectorRateLimiter rateLimiter; private PubSubSource<String> pubSubSource; @Before public void setup() throws Exception { when(pubSubSubscriberFactory.getSubscriber(eq(credentials))).thenReturn(pubsubSubscriber); when(streamingRuntimeContext.isCheckpointingEnabled()).thenReturn(true); when(streamingRuntimeContext.getMetricGroup()).thenReturn(metricGroup); when(metricGroup.addGroup(any(String.class))).thenReturn(metricGroup); when(acknowledgeOnCheckpointFactory.create(any())).thenReturn(acknowledgeOnCheckpoint); pubSubSource = new PubSubSource<>( deserializationSchema, pubSubSubscriberFactory, credentials, acknowledgeOnCheckpointFactory, rateLimiter, 1024); pubSubSource.setRuntimeContext(streamingRuntimeContext); } @Test(expected = IllegalArgumentException.class) public void testOpenWithoutCheckpointing() throws Exception { when(streamingRuntimeContext.isCheckpointingEnabled()).thenReturn(false); pubSubSource.open(null); } @Test public void testOpenWithCheckpointing() throws Exception { when(streamingRuntimeContext.isCheckpointingEnabled()).thenReturn(true); pubSubSource.open(null); verify(pubSubSubscriberFactory, times(1)).getSubscriber(eq(credentials)); verify(acknowledgeOnCheckpointFactory, times(1)).create(pubsubSubscriber); } @Test public void testTypeInformationFromDeserializationSchema() { TypeInformation<String> schemaTypeInformation = TypeInformation.of(String.class); when(deserializationSchema.getProducedType()).thenReturn(schemaTypeInformation); TypeInformation<String> actualTypeInformation = pubSubSource.getProducedType(); assertThat(actualTypeInformation, is(schemaTypeInformation)); verify(deserializationSchema, times(1)).getProducedType(); } @Test public void testNotifyCheckpointComplete() throws Exception { pubSubSource.open(null); pubSubSource.notifyCheckpointComplete(45L); verify(acknowledgeOnCheckpoint, times(1)).notifyCheckpointComplete(45L); } @Test public void testRestoreState() throws Exception { pubSubSource.open(null); List<AcknowledgeIdsForCheckpoint<String>> input = new ArrayList<>(); pubSubSource.restoreState(input); verify(acknowledgeOnCheckpoint, times(1)).restoreState(refEq(input)); } @Test public void testSnapshotState() throws Exception { pubSubSource.open(null); pubSubSource.snapshotState(1337L, 15000L); verify(acknowledgeOnCheckpoint, times(1)).snapshotState(1337L, 15000L); } @Test public void testOpen() throws Exception { doAnswer( (args) -> { DeserializationSchema.InitializationContext context = args.getArgument(0); Assert.assertThat( context.getMetricGroup(), Matchers.equalTo(metricGroup)); return null; }) .when(deserializationSchema) .open(any(DeserializationSchema.InitializationContext.class)); pubSubSource.open(null); verify(deserializationSchema, times(1)) .open(any(DeserializationSchema.InitializationContext.class)); } }
tillrohrmann/flink
flink-connectors/flink-connector-gcp-pubsub/src/test/java/org/apache/flink/streaming/connectors/gcp/pubsub/PubSubSourceTest.java
Java
apache-2.0
6,683
package one.two; public class ReadWithInstance { public static void main(String[] args) { KotlinObject i = KotlinObject.INSTANCE.getStaticLateinit(); } }
jwren/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/staticLateinit/ReadWithInstance.java
Java
apache-2.0
170
package ecs //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // AllocatedResourcesInDescribeElasticityAssurances is a nested struct in ecs response type AllocatedResourcesInDescribeElasticityAssurances struct { AllocatedResource []AllocatedResource `json:"AllocatedResource" xml:"AllocatedResource"` }
kubernetes/cloud-provider-alibaba-cloud
vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/ecs/struct_allocated_resources_in_describe_elasticity_assurances.go
GO
apache-2.0
941
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_13) on Wed Aug 05 08:53:15 ICT 2009 --> <META http-equiv="Content-Type" content="text/html; charset=utf8"> <TITLE> Uses of Class org.jgentleframework.utils.data.Pair </TITLE> <META NAME="date" CONTENT="2009-08-05"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.jgentleframework.utils.data.Pair"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/jgentleframework/utils/data/\class-usePair.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Pair.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.jgentleframework.utils.data.Pair</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.jgentleframework.configure"><B>org.jgentleframework.configure</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.jgentleframework.configure.objectmeta"><B>org.jgentleframework.configure.objectmeta</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.jgentleframework.utils"><B>org.jgentleframework.utils</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.jgentleframework.configure"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A> in <A HREF="../../../../../org/jgentleframework/configure/package-summary.html">org.jgentleframework.configure</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/jgentleframework/configure/package-summary.html">org.jgentleframework.configure</A> with parameters of type <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/jgentleframework/configure/objectmeta/InClass.html" title="interface in org.jgentleframework.configure.objectmeta">InClass</A></CODE></FONT></TD> <TD><CODE><B>CoreBinding.</B><B><A HREF="../../../../../org/jgentleframework/configure/CoreBinding.html#bind(org.jgentleframework.utils.data.Pair...)">bind</A></B>(<A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A>&lt;java.lang.String,java.lang.Object&gt;...&nbsp;pairs)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates a binding of bean</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/jgentleframework/configure/objectmeta/InClass.html" title="interface in org.jgentleframework.configure.objectmeta">InClass</A></CODE></FONT></TD> <TD><CODE><B>AbstractBindingConfig.</B><B><A HREF="../../../../../org/jgentleframework/configure/AbstractBindingConfig.html#bind(org.jgentleframework.utils.data.Pair...)">bind</A></B>(<A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A>&lt;java.lang.String,java.lang.Object&gt;...&nbsp;pairs)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.jgentleframework.configure.objectmeta"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A> in <A HREF="../../../../../org/jgentleframework/configure/objectmeta/package-summary.html">org.jgentleframework.configure.objectmeta</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/jgentleframework/configure/objectmeta/package-summary.html">org.jgentleframework.configure.objectmeta</A> that return types with arguments of type <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.util.Map&lt;<A HREF="../../../../../org/jgentleframework/configure/enums/Types.html" title="enum in org.jgentleframework.configure.enums">Types</A>,java.util.List&lt;<A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A>&lt;<A HREF="../../../../../org/jgentleframework/core/reflection/Identification.html" title="interface in org.jgentleframework.core.reflection">Identification</A>&lt;?&gt;,java.lang.Object&gt;&gt;&gt;</CODE></FONT></TD> <TD><CODE><B>ObjectBindingConstant.</B><B><A HREF="../../../../../org/jgentleframework/configure/objectmeta/ObjectBindingConstant.html#getAnnotatedValueList()">getAnnotatedValueList</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets the annotated value list.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/jgentleframework/configure/objectmeta/package-summary.html">org.jgentleframework.configure.objectmeta</A> with parameters of type <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/jgentleframework/configure/objectmeta/InClass.html" title="interface in org.jgentleframework.configure.objectmeta">InClass</A></CODE></FONT></TD> <TD><CODE><B>ObjectAnnotating.</B><B><A HREF="../../../../../org/jgentleframework/configure/objectmeta/ObjectAnnotating.html#annotate(org.jgentleframework.utils.data.Pair...)">annotate</A></B>(<A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A>&lt;<A HREF="../../../../../org/jgentleframework/core/reflection/Identification.html" title="interface in org.jgentleframework.core.reflection">Identification</A>&lt;?&gt;,java.lang.Object&gt;...&nbsp;pairs)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Executes the <code>annotating action</code> in order to annotate one or more <b><i>dynamic annotation instances</i></b> at differrent member target in current configuring <A HREF="../../../../../org/jgentleframework/configure/objectmeta/ObjectBindingConstant.html" title="interface in org.jgentleframework.configure.objectmeta"><CODE>ObjectBindingConstant</CODE></A>.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../org/jgentleframework/configure/objectmeta/ObjectBindingConstant.html" title="interface in org.jgentleframework.configure.objectmeta">ObjectBindingConstant</A></CODE></FONT></TD> <TD><CODE><B>Binder.</B><B><A HREF="../../../../../org/jgentleframework/configure/objectmeta/Binder.html#createObjectBindingConstant(org.jgentleframework.utils.data.Pair...)">createObjectBindingConstant</A></B>(<A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A>&lt;java.lang.String,java.lang.Object&gt;...&nbsp;pairs)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates an <A HREF="../../../../../org/jgentleframework/configure/objectmeta/ObjectBindingConstant.html" title="interface in org.jgentleframework.configure.objectmeta"><CODE>ObjectBindingConstant</CODE></A> instance.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Method parameters in <A HREF="../../../../../org/jgentleframework/configure/objectmeta/package-summary.html">org.jgentleframework.configure.objectmeta</A> with type arguments of type <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>ObjectBindingConstant.</B><B><A HREF="../../../../../org/jgentleframework/configure/objectmeta/ObjectBindingConstant.html#setAnnotatedValueList(java.util.Map)">setAnnotatedValueList</A></B>(java.util.Map&lt;<A HREF="../../../../../org/jgentleframework/configure/enums/Types.html" title="enum in org.jgentleframework.configure.enums">Types</A>,java.util.List&lt;<A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A>&lt;<A HREF="../../../../../org/jgentleframework/core/reflection/Identification.html" title="interface in org.jgentleframework.core.reflection">Identification</A>&lt;?&gt;,java.lang.Object&gt;&gt;&gt;&nbsp;annotatedValueList)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the annotated value list.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.jgentleframework.utils"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A> in <A HREF="../../../../../org/jgentleframework/utils/package-summary.html">org.jgentleframework.utils</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../org/jgentleframework/utils/package-summary.html">org.jgentleframework.utils</A> that return <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data">Pair</A>&lt;java.lang.Class&lt;?&gt;[],java.lang.Object[]&gt;</CODE></FONT></TD> <TD><CODE><B>DefinitionUtils.</B><B><A HREF="../../../../../org/jgentleframework/utils/DefinitionUtils.html#findArgsOfDefaultConstructor(org.jgentleframework.core.reflection.metadata.Definition, org.jgentleframework.context.injecting.Provider)">findArgsOfDefaultConstructor</A></B>(<A HREF="../../../../../org/jgentleframework/core/reflection/metadata/Definition.html" title="interface in org.jgentleframework.core.reflection.metadata">Definition</A>&nbsp;definition, <A HREF="../../../../../org/jgentleframework/context/injecting/Provider.html" title="interface in org.jgentleframework.context.injecting">Provider</A>&nbsp;provider)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Finds args of default constructor.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/jgentleframework/utils/data/Pair.html" title="class in org.jgentleframework.utils.data"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/jgentleframework/utils/data/\class-usePair.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Pair.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
haint/jgentle
doc/org/jgentleframework/utils/data/class-use/Pair.html
HTML
apache-2.0
17,808
# Copyright (C) 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Generated globbing source file # This file will be automatically regenerated if deleted, do not edit by hand. # If you add a new file to the directory, just delete this file, run any cmake # build and the file will be recreated, check in the new version. set(files client.go doc.go process.go ) set(dirs )
ek9852/gapid
gapis/client/CMakeFiles.cmake
CMake
apache-2.0
907
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2018 The ZAP Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.ascanrules; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.zaproxy.zap.extension.ascanrules.utils.Constants.NULL_BYTE_CHARACTER; import fi.iki.elonen.NanoHTTPD.IHTTPSession; import java.util.Map; import org.junit.jupiter.api.Test; import org.parosproxy.paros.core.scanner.Plugin.AttackStrength; import org.parosproxy.paros.network.HttpMalformedHeaderException; import org.zaproxy.addon.commonlib.CommonAlertTag; import org.zaproxy.zap.model.Tech; import org.zaproxy.zap.utils.ZapXmlConfiguration; /** Unit test for {@link RemoteFileIncludeScanRule}. */ class RemoteFileIncludeScanRuleUnitTest extends ActiveScannerTest<RemoteFileIncludeScanRule> { @Override protected RemoteFileIncludeScanRule createScanner() { RemoteFileIncludeScanRule scanner = new RemoteFileIncludeScanRule(); scanner.setConfig(new ZapXmlConfiguration()); return scanner; } @Test void shouldReturnExpectedMappings() { // Given / When int cwe = rule.getCweId(); int wasc = rule.getWascId(); Map<String, String> tags = rule.getAlertTags(); // Then assertThat(cwe, is(equalTo(98))); assertThat(wasc, is(equalTo(5))); assertThat(tags.size(), is(equalTo(3))); assertThat( tags.containsKey(CommonAlertTag.OWASP_2021_A03_INJECTION.getTag()), is(equalTo(true))); assertThat( tags.containsKey(CommonAlertTag.OWASP_2017_A01_INJECTION.getTag()), is(equalTo(true))); assertThat( tags.containsKey(CommonAlertTag.WSTG_V42_INPV_11_CODE_INJ.getTag()), is(equalTo(true))); assertThat( tags.get(CommonAlertTag.OWASP_2021_A03_INJECTION.getTag()), is(equalTo(CommonAlertTag.OWASP_2021_A03_INJECTION.getValue()))); assertThat( tags.get(CommonAlertTag.OWASP_2017_A01_INJECTION.getTag()), is(equalTo(CommonAlertTag.OWASP_2017_A01_INJECTION.getValue()))); assertThat( tags.get(CommonAlertTag.WSTG_V42_INPV_11_CODE_INJ.getTag()), is(equalTo(CommonAlertTag.WSTG_V42_INPV_11_CODE_INJ.getValue()))); } @Test void shouldRaiseAlertIfResponseHasRemoteFileContentAndPayloadIsNullByteBased() throws HttpMalformedHeaderException { // Given NullByteVulnerableServerHandler vulnServerHandler = new NullByteVulnerableServerHandler("/", "p", Tech.Linux) { @Override protected String getContent(IHTTPSession session) { String value = getFirstParamValue(session, "p"); if (value.contains(NULL_BYTE_CHARACTER)) { return "<html><title>Google</title></html>"; } else { return "<html></html>"; } } }; nano.addHandler(vulnServerHandler); rule.init(getHttpMessage("/?p=a"), parent); rule.setAttackStrength(AttackStrength.INSANE); // When rule.scan(); // Then assertThat(alertsRaised, hasSize(1)); } }
kingthorin/zap-extensions
addOns/ascanrules/src/test/java/org/zaproxy/zap/extension/ascanrules/RemoteFileIncludeScanRuleUnitTest.java
Java
apache-2.0
4,151
// Copyright (C) 2015 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.schema; import com.google.inject.Inject; import com.google.inject.Provider; public class Schema_114 extends SchemaVersion { @Inject Schema_114(Provider<Schema_113> prior) { super(prior); } }
WANdisco/gerrit
java/com/google/gerrit/server/schema/Schema_114.java
Java
apache-2.0
845
/* * Copyright 2004-2006 Stefan Reuter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.asteriskjava.manager.action; /** * Redirects a given channel (and an optional additional channel) to a new * extension. * <p> * The additional channel is usually used when redirecting two bridged channel * for example to a MeetMe room. * <p> * Note that BRIstuffed versions of Asterisk behave slightly different: While * the standard version only allows redirecting the two channels to the same * context, extension, priority the BRIstuffed version uses context, extension, * priority only for the first channel and extraContext, extraExtension, * extraPriority for the second channel. The standard version ignores the * extraContext, extraExtension, extraPriority properties. * * @author srt * @version $Id$ */ public class RedirectAction extends AbstractManagerAction { /** * Serializable version identifier */ static final long serialVersionUID = 1869279324159418150L; private String channel; private String extraChannel; private String exten; private String context; private Integer priority; private String extraExten; private String extraContext; private Integer extraPriority; /** * Creates a new empty RedirectAction. */ public RedirectAction() { } /** * Creates a new RedirectAction that redirects the given channel to the * given context, extension, priority triple. * * @param channel the name of the channel to redirect * @param context the destination context * @param exten the destination extension * @param priority the destination priority * @since 0.2 */ public RedirectAction(String channel, String context, String exten, Integer priority) { this.channel = channel; this.context = context; this.exten = exten; this.priority = priority; } /** * Creates a new RedirectAction that redirects the given channels to the * given context, extension, priority triple. * <p> * This constructor only works standard versions of Asterisk, i.e. * non-BRIstuffed versions. When used with a BRIstuffed version (and not * setting extraContext, extraExten and extraPriority) the second channel is * just hung up. * * @param channel the name of the first channel to redirect * @param extraChannel the name of the second channel to redirect * @param context the destination context * @param exten the destination extension * @param priority the destination priority * @since 0.2 */ public RedirectAction(String channel, String extraChannel, String context, String exten, Integer priority) { this.channel = channel; this.extraChannel = extraChannel; this.context = context; this.exten = exten; this.priority = priority; } /** * Creates a new RedirectAction that redirects the given channels to the * given context, extension, priority triples. * <p> * This constructor works for BRIstuffed versions of Asterisk, if used with * a standard version the extraContext, extraExten and extraPriroity * attributes are ignored. * * @param channel the name of the first channel to redirect * @param extraChannel the name of the second channel to redirect * @param context the destination context for the first channel * @param exten the destination extension for the first channel * @param priority the destination priority for the first channel * @param extraContext the destination context for the second channel * @param extraExten the destination extension for the second channel * @param extraPriority the destination priority for the second channel * @since 0.3 */ public RedirectAction(String channel, String extraChannel, String context, String exten, Integer priority, String extraContext, String extraExten, Integer extraPriority) { this.channel = channel; this.extraChannel = extraChannel; this.context = context; this.exten = exten; this.priority = priority; this.extraContext = extraContext; this.extraExten = extraExten; this.extraPriority = extraPriority; if (channel.equalsIgnoreCase(extraChannel)) { throw new RuntimeException("ExtraChannel = channel ... bad things will happen to asterisk"); } } /** * Returns the name of this action, i.e. "Redirect". */ @Override public String getAction() { return "Redirect"; } /** * Returns name of the channel to redirect. * * @return the name of the channel to redirect */ public String getChannel() { return channel; } /** * Sets the name of the channel to redirect. * * @param channel the name of the channel to redirect */ public void setChannel(String channel) { this.channel = channel; } /** * Returns the name of the additional channel to redirect. * * @return the name of the additional channel to redirect */ public String getExtraChannel() { return extraChannel; } /** * Sets the name of the additional channel to redirect. * * @param extraChannel the name of the additional channel to redirect */ public void setExtraChannel(String extraChannel) { this.extraChannel = extraChannel; if (channel.equalsIgnoreCase(extraChannel)) { throw new RuntimeException("ExtraChannel = channel ... bad things will happen to asterisk"); } } /** * Returns the destination context. * * @return the destination context */ public String getContext() { return context; } /** * Sets the destination context. * * @param context the destination context */ public void setContext(String context) { this.context = context; } /** * Returns the destination extension. * * @return the destination extension */ public String getExten() { return exten; } /** * Sets the destination extension. * * @param exten the destination extension */ public void setExten(String exten) { this.exten = exten; } /** * Returns the destination priority. * * @return the destination priority */ public Integer getPriority() { return priority; } /** * Sets the destination priority. * * @param priority the destination priority */ public void setPriority(Integer priority) { this.priority = priority; } /** * Returns the destination context for the additional channel. * <p> * This property is only used by BRIstuffed Asterisk servers. * * @return the destination context for the additional channel. */ public String getExtraContext() { return extraContext; } /** * Sets the destination context for the additional channel. * <p> * This property is only used by BRIstuffed Asterisk servers. * * @param extraContext the destination context for the additional channel. */ public void setExtraContext(String extraContext) { this.extraContext = extraContext; } /** * Sets the destination extension for the additional channel. * <p> * This property is only used by BRIstuffed Asterisk servers. * * @return the destination extension for the additional channel. */ public String getExtraExten() { return extraExten; } /** * Sets the destination extension for the additional channel. * <p> * This property is only used by BRIstuffed Asterisk servers. * * @param extraExten the destination extension for the additional channel. */ public void setExtraExten(String extraExten) { this.extraExten = extraExten; } /** * Returns the destination priority for the additional channel. * <p> * This property is only used by BRIstuffed Asterisk servers. * * @return the destination priority for the additional channel. */ public Integer getExtraPriority() { return extraPriority; } /** * Sets the destination priority for the additional channel. * <p> * This property is only used by BRIstuffed Asterisk servers. * * @param extraPriority the destination priority for the additional channel. */ public void setExtraPriority(Integer extraPriority) { this.extraPriority = extraPriority; } }
yamajun/asterisk-java
src/main/java/org/asteriskjava/manager/action/RedirectAction.java
Java
apache-2.0
9,412
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.olingo.fit.proxy.demo.odatademo.types; // CHECKSTYLE:OFF (Maven checkstyle) public interface CategoryCollectionComposableInvoker extends org.apache.olingo.ext.proxy.api.StructuredCollectionComposableInvoker<CategoryCollection, CategoryCollection.Operations> { @Override CategoryCollectionComposableInvoker select(String... select); @Override CategoryCollectionComposableInvoker expand(String... expand); }
apache/olingo-odata4
fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/CategoryCollectionComposableInvoker.java
Java
apache-2.0
1,249
package org.wso2.carbon.identity.application.authentication.framework.handler.request.impl; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCache; import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry; import org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheKey; import org.wso2.carbon.identity.application.authentication.framework.config.ConfigurationFacade; import org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig; import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext; import org.wso2.carbon.identity.application.authentication.framework.context.SessionContext; import org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException; import org.wso2.carbon.identity.application.authentication.framework.handler.request.RequestCoordinator; import org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceComponent; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils; import org.wso2.carbon.registry.core.utils.UUIDGenerator; import org.wso2.carbon.user.api.Tenant; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; /** * Request Coordinator */ public class DefaultRequestCoordinator implements RequestCoordinator { private static Log log = LogFactory.getLog(DefaultRequestCoordinator.class); private static volatile DefaultRequestCoordinator instance; public static DefaultRequestCoordinator getInstance() { if (instance == null) { synchronized (DefaultRequestCoordinator.class) { if (instance == null) { instance = new DefaultRequestCoordinator(); } } } return instance; } @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { try { AuthenticationContext context = null; AuthenticationRequestCacheEntry authRequest = null; String sessionDataKey = request.getParameter("sessionDataKey"); boolean returning = false; // Check whether this is the start of the authentication flow. // 'type' parameter should be present if so. This parameter contains // the request type (e.g. samlsso) set by the calling servlet. // TODO: use a different mechanism to determine the flow start. if (request != null && request.getParameter("type") != null) { // Retrieve AuthenticationRequestCache Entry which is stored stored from servlet. AuthenticationRequestCacheKey cacheKey = new AuthenticationRequestCacheKey( sessionDataKey); authRequest = (AuthenticationRequestCacheEntry) AuthenticationRequestCache .getInstance(0).getValueFromCache(cacheKey); log.debug("retrieving authentication request from cache.."); // if there is a cache entry, wrap the original request with params in cache entry if (authRequest != null) { request = FrameworkUtils.getCommonAuthReqWithParams(request, authRequest); } context = initializeFlow(request, response); } else { returning = true; context = FrameworkUtils.getContextData(request); } if (context != null) { context.setReturning(returning); // if this is the flow start, store the original request in the context if (!context.isReturning()) { if (authRequest != null) { context.setAuthenticationRequest(authRequest.getAuthenticationRequest()); } } if (!context.isLogoutRequest()) { FrameworkUtils.getAuthenticationRequestHandler().handle(request, response, context); } else { FrameworkUtils.getLogoutRequestHandler().handle(request, response, context); } } else { if (log.isDebugEnabled()) { String key = request.getParameter("sessionDataKey"); if (key == null) { log.debug("Session data key is null in the request"); } else { log.debug("Session data key : " + key); } } log.error("Context does not exist. Probably due to invalidated cache"); FrameworkUtils.sendToRetryPage(request, response); } } catch (Throwable e) { log.error("Exception in Authentication Framework", e); FrameworkUtils.sendToRetryPage(request, response); } finally { // FrameworkUtils.removeAuthenticationRequestFromCache(request.getParameter("sessionDataKey")); } } /** * Handles the initial request (from the calling servlet) * * @param request * @param response * @throws ServletException * @throws IOException * @throws */ protected AuthenticationContext initializeFlow(HttpServletRequest request, HttpServletResponse response) throws FrameworkException { if (log.isDebugEnabled()) { log.debug("Initializing the flow"); } // "sessionDataKey" - calling servlet maintains its state information // using this String callerSessionDataKey = request.getParameter(FrameworkConstants.SESSION_DATA_KEY); // "commonAuthCallerPath" - path of the calling servlet. This is the url // response should be sent to String callerPath = request.getParameter(FrameworkConstants.RequestParams.CALLER_PATH); try { if (callerPath != null) { callerPath = URLDecoder.decode(callerPath, "UTF-8"); } } catch (UnsupportedEncodingException e) { throw new FrameworkException(e.getMessage(), e); } // "type" - type of the request. e.g. samlsso, openid, oauth, passivests String requestType = request.getParameter(FrameworkConstants.RequestParams.TYPE); // "relyingParty" String relyingParty = request.getParameter(FrameworkConstants.RequestParams.ISSUER); // tenant domain String tenantDomain = request.getParameter(FrameworkConstants.RequestParams.TENANT_DOMAIN); if (tenantDomain == null || tenantDomain.isEmpty() || tenantDomain.equals("null")) { String tenantId = request.getParameter(FrameworkConstants.RequestParams.TENANT_ID); if (tenantId != null && !tenantId.equals("-1234")) { try { Tenant tenant = FrameworkServiceComponent.getRealmService().getTenantManager() .getTenant(Integer.valueOf(tenantId).intValue()); if (tenant != null) { tenantDomain = tenant.getDomain(); } } catch (Exception e) { throw new FrameworkException(e.getMessage(), e); } } else { tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } } // Store the request data sent by the caller AuthenticationContext context = new AuthenticationContext(); context.setCallerSessionKey(callerSessionDataKey); context.setCallerPath(callerPath); context.setRequestType(requestType); context.setRelyingParty(relyingParty); context.setTenantDomain(tenantDomain); // generate a new key to hold the context data object String contextId = UUIDGenerator.generateUUID(); context.setContextIdentifier(contextId); if (log.isDebugEnabled()) { log.debug("Framework contextId: " + contextId); } // if this a logout request from the calling servlet if (request.getParameter(FrameworkConstants.RequestParams.LOGOUT) != null) { if (log.isDebugEnabled()) { log.debug("Starting a logout flow"); } context.setLogoutRequest(true); if (context.getRelyingParty() == null || context.getRelyingParty().trim().length() == 0) { if (log.isDebugEnabled()) { log.debug("relyingParty param is null. This is a possible logout scenario."); } Cookie cookie = FrameworkUtils.getAuthCookie(request); if (cookie != null) { context.setSessionIdentifier(cookie.getValue()); } return context; } } else { if (log.isDebugEnabled()) { log.debug("Starting an authentication flow"); } } findPreviousAuthenticatedSession(request, context); buildOutboundQueryString(request, context); return context; } protected void findPreviousAuthenticatedSession(HttpServletRequest request, AuthenticationContext context) throws FrameworkException { // Get service provider chain SequenceConfig sequenceConfig = ConfigurationFacade.getInstance().getSequenceConfig( context.getRequestType(), request.getParameter(FrameworkConstants.RequestParams.ISSUER), context.getTenantDomain()); Cookie cookie = FrameworkUtils.getAuthCookie(request); // if cookie exists user has previously authenticated if (cookie != null) { if (log.isDebugEnabled()) { log.debug(FrameworkConstants.COMMONAUTH_COOKIE + " cookie is available with the value: " + cookie.getValue()); } // get the authentication details from the cache SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(cookie .getValue()); if (sessionContext != null) { context.setSessionIdentifier(cookie.getValue()); String appName = sequenceConfig.getApplicationConfig().getApplicationName(); if (log.isDebugEnabled()) { log.debug("Service Provider is: " + appName); } SequenceConfig previousAuthenticatedSeq = sessionContext .getAuthenticatedSequences().get(appName); if (previousAuthenticatedSeq != null) { if (log.isDebugEnabled()) { log.debug("A previously authenticated sequence found for the SP: " + appName); } context.setPreviousSessionFound(true); sequenceConfig = previousAuthenticatedSeq; AuthenticatedUser authenticatedUser = sequenceConfig.getAuthenticatedUser(); String authenticatedUserTenantDomain = sequenceConfig.getAuthenticatedUserTenantDomain(); if (authenticatedUser != null) { // set the user for the current authentication/logout flow context.setSubject(authenticatedUser); if (log.isDebugEnabled()) { log.debug("Already authenticated by username: " + authenticatedUser.getAuthenticatedSubjectIdentifier()); } if (authenticatedUserTenantDomain != null) { // set the user tenant domain for the current authentication/logout flow context.setProperty("user-tenant-domain", authenticatedUserTenantDomain); if (log.isDebugEnabled()) { log.debug("Authenticated user tenant domain: " + authenticatedUserTenantDomain); } } } } context.setPreviousAuthenticatedIdPs(sessionContext.getAuthenticatedIdPs()); } else { if (log.isDebugEnabled()) { log.debug("Failed to find the SessionContext from the cache. Possible cache timeout."); } } } context.setServiceProviderName(sequenceConfig.getApplicationConfig().getApplicationName()); // set the sequence for the current authentication/logout flow context.setSequenceConfig(sequenceConfig); } private void buildOutboundQueryString(HttpServletRequest request, AuthenticationContext context) { // Build the outbound query string that will be sent to the authentication endpoint and // federated IdPs StringBuilder outboundQueryStringBuilder = new StringBuilder(); outboundQueryStringBuilder.append(FrameworkUtils.getQueryStringWithConfiguredParams(request)); if (StringUtils.isNotEmpty(outboundQueryStringBuilder.toString())) { outboundQueryStringBuilder.append("&"); } outboundQueryStringBuilder.append("sessionDataKey=").append(context.getContextIdentifier()) .append("&relyingParty=").append(context.getRelyingParty()).append("&type=") .append(context.getRequestType()).append("&sp=") .append(context.getServiceProviderName()).append("&isSaaSApp=") .append(context.getSequenceConfig().getApplicationConfig().isSaaSApp()); if (log.isDebugEnabled()) { log.debug("Outbound Query String: " + outboundQueryStringBuilder.toString()); } context.setContextIdIncludedQueryParams(outboundQueryStringBuilder.toString()); context.setOrignalRequestQueryParams(outboundQueryStringBuilder.toString()); } }
cdwijayarathna/carbon-identity
components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/handler/request/impl/DefaultRequestCoordinator.java
Java
apache-2.0
14,844
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Shared helper functions for RuntimeConfig API classes.""" def config_name_from_full_name(full_name): """Extract the config name from a full resource name. >>> config_name_from_full_name('projects/my-proj/configs/my-config') "my-config" :type full_name: str :param full_name: The full resource name of a config. The full resource name looks like ``projects/project-name/configs/config-name`` and is returned as the ``name`` field of a config resource. See: https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs :rtype: str :returns: The config's short name, given its full resource name. :raises: :class:`ValueError` if ``full_name`` is not the expected format """ projects, _, configs, result = full_name.split('/') if projects != 'projects' or configs != 'configs': raise ValueError( 'Unexpected format of resource', full_name, 'Expected "projects/{proj}/configs/{cfg}"') return result def variable_name_from_full_name(full_name): """Extract the variable name from a full resource name. >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/var-name') "var-name" >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/another/var/name') "another/var/name" :type full_name: str :param full_name: The full resource name of a variable. The full resource name looks like ``projects/prj-name/configs/cfg-name/variables/var-name`` and is returned as the ``name`` field of a variable resource. See: https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables :rtype: str :returns: The variable's short name, given its full resource name. :raises: :class:`ValueError` if ``full_name`` is not the expected format """ projects, _, configs, _, variables, result = full_name.split('/', 5) if (projects != 'projects' or configs != 'configs' or variables != 'variables'): raise ValueError( 'Unexpected format of resource', full_name, 'Expected "projects/{proj}/configs/{cfg}/variables/..."') return result
jgeewax/gcloud-python
runtimeconfig/google/cloud/runtimeconfig/_helpers.py
Python
apache-2.0
2,925
// Copyright 2013 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Flags: --noanalyze-environment-liveness --allow-natives-syntax var r = /r/; function f() { r[r] = function() {}; } for (var i = 0; i < 300; i++) { f(); if (i == 150) %OptimizeOsr(); }
weolar/miniblink49
v8_7_5/test/mjsunit/regress/regress-crbug-217858.js
JavaScript
apache-2.0
363
// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SRC_PIPELINE_H_ #define SRC_PIPELINE_H_ #include <memory> #include <string> #include <vector> #include <napi.h> #include <vips/vips8> #include "./common.h" Napi::Value pipeline(const Napi::CallbackInfo& info); enum class Canvas { CROP, EMBED, MAX, MIN, IGNORE_ASPECT }; struct Composite { sharp::InputDescriptor *input; VipsBlendMode mode; int gravity; int left; int top; bool tile; bool premultiplied; Composite(): input(nullptr), mode(VIPS_BLEND_MODE_OVER), gravity(0), left(-1), top(-1), tile(false), premultiplied(false) {} }; struct PipelineBaton { sharp::InputDescriptor *input; std::string formatOut; std::string fileOut; void *bufferOut; size_t bufferOutLength; std::vector<Composite *> composite; std::vector<sharp::InputDescriptor *> joinChannelIn; int topOffsetPre; int leftOffsetPre; int widthPre; int heightPre; int topOffsetPost; int leftOffsetPost; int widthPost; int heightPost; int width; int height; int channels; Canvas canvas; int position; std::vector<double> resizeBackground; bool hasCropOffset; int cropOffsetLeft; int cropOffsetTop; bool premultiplied; std::string kernel; bool fastShrinkOnLoad; double tintA; double tintB; bool flatten; std::vector<double> flattenBackground; bool negate; double blurSigma; double brightness; double saturation; int hue; int medianSize; double sharpenSigma; double sharpenFlat; double sharpenJagged; int threshold; bool thresholdGrayscale; double trimThreshold; int trimOffsetLeft; int trimOffsetTop; double linearA; double linearB; double gamma; double gammaOut; bool greyscale; bool normalise; bool useExifOrientation; int angle; double rotationAngle; std::vector<double> rotationBackground; bool rotateBeforePreExtract; bool flip; bool flop; int extendTop; int extendBottom; int extendLeft; int extendRight; std::vector<double> extendBackground; bool withoutEnlargement; int jpegQuality; bool jpegProgressive; std::string jpegChromaSubsampling; bool jpegTrellisQuantisation; int jpegQuantisationTable; bool jpegOvershootDeringing; bool jpegOptimiseScans; bool jpegOptimiseCoding; bool pngProgressive; int pngCompressionLevel; bool pngAdaptiveFiltering; bool pngPalette; int pngQuality; int pngColours; double pngDither; int webpQuality; int webpAlphaQuality; bool webpNearLossless; bool webpLossless; bool webpSmartSubsample; int webpReductionEffort; int tiffQuality; VipsForeignTiffCompression tiffCompression; VipsForeignTiffPredictor tiffPredictor; bool tiffPyramid; bool tiffSquash; bool tiffTile; int tiffTileHeight; int tiffTileWidth; double tiffXres; double tiffYres; int heifQuality; VipsForeignHeifCompression heifCompression; bool heifLossless; std::string err; bool withMetadata; int withMetadataOrientation; std::unique_ptr<double[]> convKernel; int convKernelWidth; int convKernelHeight; double convKernelScale; double convKernelOffset; sharp::InputDescriptor *boolean; VipsOperationBoolean booleanOp; VipsOperationBoolean bandBoolOp; int extractChannel; bool removeAlpha; bool ensureAlpha; VipsInterpretation colourspace; int tileSize; int tileOverlap; VipsForeignDzContainer tileContainer; VipsForeignDzLayout tileLayout; std::string tileFormat; int tileAngle; std::vector<double> tileBackground; int tileSkipBlanks; VipsForeignDzDepth tileDepth; std::unique_ptr<double[]> recombMatrix; PipelineBaton(): input(nullptr), bufferOutLength(0), topOffsetPre(-1), topOffsetPost(-1), channels(0), canvas(Canvas::CROP), position(0), resizeBackground{ 0.0, 0.0, 0.0, 255.0 }, hasCropOffset(false), cropOffsetLeft(0), cropOffsetTop(0), premultiplied(false), tintA(128.0), tintB(128.0), flatten(false), flattenBackground{ 0.0, 0.0, 0.0 }, negate(false), blurSigma(0.0), brightness(1.0), saturation(1.0), hue(0), medianSize(0), sharpenSigma(0.0), sharpenFlat(1.0), sharpenJagged(2.0), threshold(0), thresholdGrayscale(true), trimThreshold(0.0), trimOffsetLeft(0), trimOffsetTop(0), linearA(1.0), linearB(0.0), gamma(0.0), greyscale(false), normalise(false), useExifOrientation(false), angle(0), rotationAngle(0.0), rotationBackground{ 0.0, 0.0, 0.0, 255.0 }, flip(false), flop(false), extendTop(0), extendBottom(0), extendLeft(0), extendRight(0), extendBackground{ 0.0, 0.0, 0.0, 255.0 }, withoutEnlargement(false), jpegQuality(80), jpegProgressive(false), jpegChromaSubsampling("4:2:0"), jpegTrellisQuantisation(false), jpegQuantisationTable(0), jpegOvershootDeringing(false), jpegOptimiseScans(false), jpegOptimiseCoding(true), pngProgressive(false), pngCompressionLevel(9), pngAdaptiveFiltering(false), pngPalette(false), pngQuality(100), pngColours(256), pngDither(1.0), webpQuality(80), webpAlphaQuality(100), webpNearLossless(false), webpLossless(false), webpSmartSubsample(false), webpReductionEffort(4), tiffQuality(80), tiffCompression(VIPS_FOREIGN_TIFF_COMPRESSION_JPEG), tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL), tiffPyramid(false), tiffSquash(false), tiffTile(false), tiffTileHeight(256), tiffTileWidth(256), tiffXres(1.0), tiffYres(1.0), heifQuality(80), heifCompression(VIPS_FOREIGN_HEIF_COMPRESSION_HEVC), heifLossless(false), withMetadata(false), withMetadataOrientation(-1), convKernelWidth(0), convKernelHeight(0), convKernelScale(0.0), convKernelOffset(0.0), boolean(nullptr), booleanOp(VIPS_OPERATION_BOOLEAN_LAST), bandBoolOp(VIPS_OPERATION_BOOLEAN_LAST), extractChannel(-1), removeAlpha(false), ensureAlpha(false), colourspace(VIPS_INTERPRETATION_LAST), tileSize(256), tileOverlap(0), tileContainer(VIPS_FOREIGN_DZ_CONTAINER_FS), tileLayout(VIPS_FOREIGN_DZ_LAYOUT_DZ), tileAngle(0), tileBackground{ 255.0, 255.0, 255.0, 255.0 }, tileSkipBlanks(-1), tileDepth(VIPS_FOREIGN_DZ_DEPTH_LAST) {} }; #endif // SRC_PIPELINE_H_
BigBoss424/portfolio
v8/development/node_modules/gatsby-transformer-sharp/node_modules/sharp/src/pipeline.h
C
apache-2.0
6,999
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.twill.internal; import org.apache.twill.api.TwillRunResources; import org.apache.twill.api.logging.LogEntry.Level; /** * Straightforward implementation of {@link org.apache.twill.api.TwillRunResources}. */ public class DefaultTwillRunResources implements TwillRunResources { private final String containerId; private final int instanceId; private final int virtualCores; private final int memoryMB; private final String host; private final Integer debugPort; private final Level logLevel; public DefaultTwillRunResources(int instanceId, String containerId, int cores, int memoryMB, String host, Integer debugPort, Level logLevel) { this.instanceId = instanceId; this.containerId = containerId; this.virtualCores = cores; this.memoryMB = memoryMB; this.host = host; this.debugPort = debugPort; this.logLevel = logLevel; } /** * @return instance id of the runnable. */ @Override public int getInstanceId() { return instanceId; } /** * @return id of the container the runnable is running in. */ @Override public String getContainerId() { return containerId; } /** * @return number of cores the runnable is allowed to use. YARN must be at least v2.1.0 and * it must be configured to use cgroups in order for this to be a reflection of truth. */ @Override public int getVirtualCores() { return virtualCores; } /** * @return amount of memory in MB the runnable is allowed to use. */ @Override public int getMemoryMB() { return memoryMB; } /** * @return the host the runnable is running on. */ @Override public String getHost() { return host; } @Override public Integer getDebugPort() { return debugPort; } @Override public Level getLogLevel() { return logLevel; } @Override public boolean equals(Object o) { if (!(o instanceof TwillRunResources)) { return false; } TwillRunResources other = (TwillRunResources) o; return (instanceId == other.getInstanceId()) && containerId.equals(other.getContainerId()) && host.equals(other.getHost()) && (virtualCores == other.getVirtualCores()) && (memoryMB == other.getMemoryMB()); // debugPort is ignored here } @Override public int hashCode() { int hash = 17; hash = 31 * hash + containerId.hashCode(); hash = 31 * hash + host.hashCode(); hash = 31 * hash + (instanceId ^ (instanceId >>> 32)); hash = 31 * hash + (virtualCores ^ (virtualCores >>> 32)); hash = 31 * hash + (memoryMB ^ (memoryMB >>> 32)); // debugPort is ignored here return hash; } }
sanojkodikkara/incubator-twill
twill-api/src/main/java/org/apache/twill/internal/DefaultTwillRunResources.java
Java
apache-2.0
3,520
/** * $Id$ * $URL$ * EntitySite.java - entity-broker - Jun 29, 2008 9:31:10 AM - azeckoski ************************************************************************** * Copyright (c) 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sakaiproject.entitybroker.providers.model; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.Vector; import org.azeckoski.reflectutils.annotations.ReflectIgnoreClassFields; import org.azeckoski.reflectutils.annotations.ReflectTransient; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.Member; import org.sakaiproject.authz.api.Role; import org.sakaiproject.authz.api.RoleAlreadyDefinedException; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entitybroker.DeveloperHelperService; import org.sakaiproject.entitybroker.entityprovider.annotations.EntityFieldRequired; import org.sakaiproject.entitybroker.entityprovider.annotations.EntityId; import org.sakaiproject.entitybroker.entityprovider.annotations.EntityLastModified; import org.sakaiproject.entitybroker.entityprovider.annotations.EntityOwner; import org.sakaiproject.entitybroker.entityprovider.annotations.EntitySummary; import org.sakaiproject.entitybroker.entityprovider.annotations.EntityTitle; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.time.api.Time; import org.sakaiproject.tool.api.ToolManager; import org.sakaiproject.user.api.User; import org.sakaiproject.util.Web; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * This is needed to allow RESTful access to the site data * * @author Aaron Zeckoski (azeckoski @ gmail.com) */ @SuppressWarnings("unchecked") @ReflectIgnoreClassFields({"createdBy","modifiedBy","properties","propertiesEdit","members","orderedPages","pages", "roles","users","groups","url"}) public class EntitySite implements Site { private static final long serialVersionUID = 7526472295622776147L; @EntityId private String id; @EntityFieldRequired private String title; private String shortDescription; private String htmlShortDescription; private String description; private String htmlDescription; private String iconUrl; private String iconUrlFull; private String infoUrl; private String infoUrlFull; private boolean joinable; private String joinerRole; private String maintainRole; private String skin; private boolean published; private boolean pubView; @EntityFieldRequired private String type; private String providerGroupId; private boolean customPageOrdered; private String owner; private long lastModified; private String[] userRoles; private transient List<EntityGroup> siteGroupsList; public Map<String, String> props; public Map<String, String> getProps() { if (props == null) { props = new HashMap<String, String>(); } return props; } public void setProps(Map<String, String> props) { this.props = props; } public void setProperty(String key, String value) { if (props == null) { props = new HashMap<String, String>(); } props.put(key, value); } public String getProperty(String key) { if (props == null) { return null; } return props.get(key); } private transient Site site; public EntitySite() { } public EntitySite(String title, String shortDescription, String description, String iconUrl, String iconFullUrl, String infoUrl, String infoUrlFull, boolean joinable, String joinerRole, String maintainRole, String skin, boolean published, boolean pubView, String type, String providerGroupId, boolean customPageOrdered) { this(title, shortDescription, Web.escapeHtml(shortDescription), description, Web.escapeHtml(description), iconUrl, iconFullUrl, infoUrl, infoUrlFull, joinable, joinerRole, maintainRole, skin, published, pubView, type, providerGroupId, customPageOrdered); } public EntitySite(String title, String shortDescription, String htmlShortDescription, String description, String htmlDescription, String iconUrl, String iconFullUrl, String infoUrl, String infoUrlFull, boolean joinable, String joinerRole, String maintainRole, String skin, boolean published, boolean pubView, String type, String providerGroupId, boolean customPageOrdered) { this.title = title; this.shortDescription = shortDescription; this.htmlShortDescription = htmlShortDescription; this.description = description; this.htmlDescription = htmlDescription; this.iconUrl = iconUrl; this.iconUrlFull = iconFullUrl; this.infoUrl = infoUrl; this.infoUrlFull = infoUrlFull; this.joinable = joinable; this.joinerRole = joinerRole; this.maintainRole = maintainRole; this.skin = skin; this.published = published; this.pubView = pubView; this.type = type; this.providerGroupId = providerGroupId; this.customPageOrdered = customPageOrdered; this.lastModified = System.currentTimeMillis(); getUserRoles(); // populate the user roles } public EntitySite(Site site, boolean includeGroups) { this.site = site; this.id = site.getId(); this.title = site.getTitle(); this.shortDescription = site.getShortDescription(); this.htmlShortDescription = site.getHtmlShortDescription(); this.description = site.getDescription(); this.htmlDescription = site.getHtmlDescription(); this.iconUrl = site.getIconUrl(); this.infoUrl = site.getInfoUrl(); this.iconUrlFull = site.getIconUrlFull(); this.joinable = site.isJoinable(); this.joinerRole = site.getJoinerRole(); this.skin = site.getSkin(); this.published = site.isPublished(); this.pubView = site.isPubView(); this.type = site.getType(); this.customPageOrdered = site.isCustomPageOrdered(); this.maintainRole = site.getMaintainRole(); this.providerGroupId = site.getProviderGroupId(); this.owner = site.getCreatedBy() == null ? null : site.getCreatedBy().getId(); this.lastModified = site.getModifiedTime() == null ? System.currentTimeMillis() : site.getModifiedTime().getTime(); getUserRoles(); // populate the user roles // properties ResourceProperties rp = site.getProperties(); for (Iterator<String> iterator = rp.getPropertyNames(); iterator.hasNext();) { String name = iterator.next(); String value = rp.getProperty(name); this.setProperty(name, value); } // add in the groups if (includeGroups) { Collection<Group> groups = site.getGroups(); siteGroupsList = new Vector<EntityGroup>(groups.size()); for (Group group : groups) { EntityGroup eg = new EntityGroup(group); siteGroupsList.add(eg); } } } @EntityId public String getId() { return id; } public void setId(String id) { this.id = id; } /** * @return the id of the owner of this site (will match the created by user id) */ @EntityOwner public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } /** * Special method * @return the owner data for the current site owner */ public Owner getSiteOwner() { Owner owner = null; if (this.site != null) { // TODO handle the contact info? User user = site.getCreatedBy(); owner = new Owner(user.getId(), user.getDisplayName()); } else { owner = new Owner(this.owner, this.owner); } return owner; } @EntityLastModified public long getLastModified() { if (site != null) { this.lastModified = site.getModifiedTime() == null ? lastModified : site.getModifiedTime().getTime(); } return lastModified; } public void setLastModified(long lastModified) { throw new UnsupportedOperationException("Cannot set the last modified time manually"); } @EntityTitle public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getShortDescription() { return shortDescription; } public String getHtmlShortDescription() { return htmlShortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; this.htmlShortDescription = Web.escapeHtml(shortDescription); } @EntitySummary public String getDescription() { return description; } public String getHtmlDescription() { return htmlDescription; } public void setDescription(String description) { this.description = description; this.htmlDescription = Web.escapeHtml(description); } public String getIconUrl() { return iconUrl; } public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; } public String getInfoUrl() { return infoUrl; } public void setInfoUrl(String infoUrl) { this.infoUrl = infoUrl; } public String getInfoUrlFull() { if (site != null) { return site.getInfoUrlFull(); } return infoUrlFull; } public void setInfoUrlFull(String infoUrlFull) { this.infoUrlFull = infoUrlFull; } public boolean isJoinable() { return joinable; } public void setJoinable(boolean joinable) { this.joinable = joinable; } public String getJoinerRole() { return joinerRole; } public void setJoinerRole(String joinerRole) { this.joinerRole = joinerRole; } public String getSkin() { return skin; } public void setSkin(String skin) { this.skin = skin; } public boolean isPublished() { return published; } public void setPublished(boolean published) { this.published = published; } public String getType() { return type; } public void setType(String type) { this.type = type; } public void setIconUrlFull(String iconUrlFull) { this.iconUrlFull = iconUrlFull; } public String getMaintainRole() { return maintainRole; } public void setMaintainRole(String maintainRole) { this.maintainRole = maintainRole; } public String getProviderGroupId() { return providerGroupId; } public void setProviderGroupId(String providerGroupId) { this.providerGroupId = providerGroupId; } public boolean isCustomPageOrdered() { return customPageOrdered; } public void setCustomPageOrdered(boolean customPageOrdered) { this.customPageOrdered = customPageOrdered; } public boolean isPubView() { return pubView; } public void setPubView(boolean pubView) { this.pubView = pubView; } public String[] getUserRoles() { if (userRoles == null) { if (site == null) { userRoles = new String[] {maintainRole, joinerRole}; } else { Set<Role> roles = (Set<Role>) site.getRoles(); userRoles = new String[roles.size()]; int i = 0; for (Role role : roles) { userRoles[i] = role.getId(); i++; } } } return userRoles; } public void setUserRoles(String[] userRoles) { this.userRoles = userRoles; } public List<EntityGroup> getSiteGroups() { return siteGroupsList; } public List<SitePage> getSitePages() { ArrayList<SitePage> rpgs = new ArrayList<SitePage>(0); if (site != null) { List<SitePage> pages = site.getOrderedPages(); rpgs = new ArrayList<SitePage>(pages.size()); DeveloperHelperService dhs = (DeveloperHelperService) ComponentManager.get(DeveloperHelperService.class); ToolManager toolManager = (ToolManager) ComponentManager.get(ToolManager.class.getName()); boolean siteUpdate = false; if (dhs != null && dhs.getCurrentUserId() != null) { siteUpdate = site.isAllowed(dhs.getCurrentUserId(), "site.upd"); } for (SitePage sitePage : pages) { // check if current user has permission to see page List<ToolConfiguration> pTools = sitePage.getTools(); boolean allowPage = false; for (ToolConfiguration tc : pTools) { boolean thisTool = toolManager.allowTool(site, tc); boolean unHidden = siteUpdate || !toolManager.isHidden(tc); if (thisTool && unHidden) { allowPage = true; } } if (allowPage) { rpgs.add( new EntitySitePage(sitePage) ); } } } return rpgs; } // transient public void setSiteGroupsList(List<EntityGroup> siteGroups) { this.siteGroupsList = siteGroups; } // Site operations public Group addGroup() { if (site != null) { return site.addGroup(); } throw new UnsupportedOperationException(); } public SitePage addPage() { if (site != null) { return site.addPage(); } throw new UnsupportedOperationException(); } public List<SitePage> getPages() { if (site != null) { return site.getPages(); } throw new UnsupportedOperationException(); } public User getCreatedBy() { if (site != null) { return site.getCreatedBy(); } throw new UnsupportedOperationException(); } public Time getCreatedTime() { if (site != null) { return site.getCreatedTime(); } throw new UnsupportedOperationException(); } public Date getCreatedDate() { if (site != null) { return site.getCreatedDate(); } throw new UnsupportedOperationException(); } public Group getGroup(String arg0) { if (site != null) { return site.getGroup(arg0); } throw new UnsupportedOperationException(); } public Collection getGroups() { if (site != null) { return site.getGroups(); } throw new UnsupportedOperationException(); } public Collection getGroupsWithMember(String arg0) { if (site != null) { return site.getGroupsWithMember(arg0); } throw new UnsupportedOperationException(); } public Collection getGroupsWithMemberHasRole(String arg0, String arg1) { if (site != null) { return site.getGroupsWithMemberHasRole(arg0, arg1); } throw new UnsupportedOperationException(); } public String getIconUrlFull() { if (site != null) { return site.getIconUrlFull(); } return this.iconUrlFull; } public User getModifiedBy() { if (site != null) { return site.getModifiedBy(); } throw new UnsupportedOperationException(); } public Time getModifiedTime() { if (site != null) { return site.getModifiedTime(); } throw new UnsupportedOperationException(); } public Date getModifiedDate() { if (site != null) { return site.getModifiedDate(); } throw new UnsupportedOperationException(); } public List getOrderedPages() { if (site != null) { return site.getOrderedPages(); } throw new UnsupportedOperationException(); } public SitePage getPage(String arg0) { if (site != null) { return site.getPage(arg0); } throw new UnsupportedOperationException(); } public ToolConfiguration getTool(String arg0) { if (site != null) { return site.getTool(arg0); } throw new UnsupportedOperationException(); } public ToolConfiguration getToolForCommonId(String arg0) { if (site != null) { return site.getToolForCommonId(arg0); } throw new UnsupportedOperationException(); } public Collection getTools(String[] arg0) { if (site != null) { return site.getTools(arg0); } throw new UnsupportedOperationException(); } public Collection getTools(String arg0) { if (site != null) { return site.getTools(arg0); } throw new UnsupportedOperationException(); } public boolean hasGroups() { if (site != null) { return site.hasGroups(); } throw new UnsupportedOperationException(); } public boolean isType(Object arg0) { if (site != null) { return site.isType(arg0); } throw new UnsupportedOperationException(); } public void loadAll() { if (site != null) { site.loadAll(); } throw new UnsupportedOperationException(); } public void regenerateIds() { if (site != null) { site.regenerateIds(); } throw new UnsupportedOperationException(); } public void removeGroup(Group arg0) { if (site != null) { site.removeGroup(arg0); } throw new UnsupportedOperationException(); } public void removePage(SitePage arg0) { if (site != null) { site.removePage(arg0); } throw new UnsupportedOperationException(); } public ResourcePropertiesEdit getPropertiesEdit() { if (site != null) { return site.getPropertiesEdit(); } throw new UnsupportedOperationException(); } public boolean isActiveEdit() { if (site != null) { return site.isActiveEdit(); } throw new UnsupportedOperationException(); } public ResourceProperties getProperties() { if (site != null) { return site.getProperties(); } throw new UnsupportedOperationException(); } public String getReference() { return "/site/" + id; } public String getReference(String arg0) { return this.getReference(); } public String getUrl() { if (site != null) { return site.getUrl(); } throw new UnsupportedOperationException(); } public String getUrl(String arg0) { if (site != null) { return site.getUrl(arg0); } throw new UnsupportedOperationException(); } @ReflectTransient public Element toXml(Document arg0, Stack arg1) { if (site != null) { return site.toXml(arg0, arg1); } throw new UnsupportedOperationException(); } public int compareTo(Object o) { if (site != null) { return site.compareTo(o); } throw new UnsupportedOperationException(); } public void addMember(String arg0, String arg1, boolean arg2, boolean arg3) { if (site != null) { site.addMember(arg0, arg1, arg2, arg3); } throw new UnsupportedOperationException(); } public Role addRole(String arg0) throws RoleAlreadyDefinedException { if (site != null) { return site.addRole(arg0); } throw new UnsupportedOperationException(); } public Role addRole(String arg0, Role arg1) throws RoleAlreadyDefinedException { if (site != null) { return site.addRole(arg0, arg1); } throw new UnsupportedOperationException(); } public Member getMember(String arg0) { if (site != null) { return site.getMember(arg0); } throw new UnsupportedOperationException(); } public Set getMembers() { if (site != null) { return site.getMembers(); } throw new UnsupportedOperationException(); } public Role getRole(String arg0) { if (site != null) { return site.getRole(arg0); } throw new UnsupportedOperationException(); } public Set getRoles() { if (site != null) { return site.getRoles(); } throw new UnsupportedOperationException(); } public Set getRolesIsAllowed(String arg0) { if (site != null) { return site.getRolesIsAllowed(arg0); } throw new UnsupportedOperationException(); } public Role getUserRole(String arg0) { if (site != null) { return site.getUserRole(arg0); } throw new UnsupportedOperationException(); } public Set getUsers() { if (site != null) { return site.getUsers(); } throw new UnsupportedOperationException(); } public Set getUsersHasRole(String arg0) { if (site != null) { return site.getUsersHasRole(arg0); } throw new UnsupportedOperationException(); } public Set getUsersIsAllowed(String arg0) { if (site != null) { return site.getUsersIsAllowed(arg0); } throw new UnsupportedOperationException(); } public boolean hasRole(String arg0, String arg1) { if (site != null) { return site.hasRole(arg0, arg1); } throw new UnsupportedOperationException(); } public boolean isAllowed(String arg0, String arg1) { if (site != null) { return site.isAllowed(arg0, arg1); } return false; } public boolean isEmpty() { if (site != null) { return site.isEmpty(); } return false; } public boolean keepIntersection(AuthzGroup arg0) { if (site != null) { return site.keepIntersection(arg0); } throw new UnsupportedOperationException(); } public void removeMember(String arg0) { if (site != null) { site.removeMember(arg0); return; } throw new UnsupportedOperationException(); } public void removeMembers() { if (site != null) { site.removeMembers(); return; } throw new UnsupportedOperationException(); } public void removeRole(String arg0) { if (site != null) { site.removeRole(arg0); return; } throw new UnsupportedOperationException(); } public void removeRoles() { if (site != null) { site.removeRoles(); return; } throw new UnsupportedOperationException(); } public Date getSoftlyDeletedDate() { if (site != null) { return site.getSoftlyDeletedDate(); } throw new UnsupportedOperationException(); } public boolean isSoftlyDeleted() { if (site != null) { return site.isSoftlyDeleted(); } throw new UnsupportedOperationException(); } public void setSoftlyDeleted(boolean flag) { if (site != null) { site.setSoftlyDeleted(flag); } throw new UnsupportedOperationException(); } public Collection<String> getMembersInGroups(Set<String> groupIds) { if (site != null) { return site.getMembersInGroups(groupIds); } throw new UnsupportedOperationException(); } }
marktriggs/nyu-sakai-10.4
entitybroker/core-providers/src/java/org/sakaiproject/entitybroker/providers/model/EntitySite.java
Java
apache-2.0
25,279
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.management; import org.apache.camel.Component; import org.apache.camel.api.management.ManagedAttribute; import org.apache.camel.api.management.ManagedResource; import org.apache.camel.component.mock.MockEndpoint; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; /** * CustomEndpoint is used to test {@link org.apache.camel.management.JmxInstrumentationCustomMBeanTest} and must be * declared a public class otherwise the mbean server connection cannot access its methods. */ // START SNIPPET: e1 @ManagedResource(description = "Our custom managed endpoint") @DisabledOnOs(OS.AIX) public class CustomEndpoint extends MockEndpoint { public CustomEndpoint(final String endpointUri, final Component component) { super(endpointUri, component); } @Override public boolean isSingleton() { return true; } @Override protected String createEndpointUri() { return "custom"; } @ManagedAttribute public String getFoo() { return "bar"; } @Override @ManagedAttribute public String getEndpointUri() { return super.getEndpointUri(); } } // END SNIPPET: e1
pax95/camel
core/camel-management/src/test/java/org/apache/camel/management/CustomEndpoint.java
Java
apache-2.0
2,024
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_IR_DIALECT_H_ #define TENSORFLOW_CORE_IR_DIALECT_H_ #include "mlir/IR/BuiltinTypes.h" // from @llvm-project #include "mlir/IR/Diagnostics.h" // from @llvm-project #include "mlir/IR/Dialect.h" // from @llvm-project #include "mlir/IR/TypeUtilities.h" // from @llvm-project #include "tensorflow/core/ir/interfaces.h" #include "tensorflow/core/ir/types/dialect.h" namespace mlir { namespace tfg { // Include the relevant TensorFlow attrs/types directly in the TFG namespace. using mlir::tf_type::Bfloat16RefType; // NOLINT using mlir::tf_type::BoolRefType; // NOLINT using mlir::tf_type::Complex128RefType; // NOLINT using mlir::tf_type::Complex64RefType; // NOLINT using mlir::tf_type::ControlType; // NOLINT using mlir::tf_type::DoubleRefType; // NOLINT using mlir::tf_type::FloatRefType; // NOLINT using mlir::tf_type::FuncAttr; // NOLINT using mlir::tf_type::HalfRefType; // NOLINT using mlir::tf_type::Int16RefType; // NOLINT using mlir::tf_type::Int32RefType; // NOLINT using mlir::tf_type::Int64RefType; // NOLINT using mlir::tf_type::Int8RefType; // NOLINT using mlir::tf_type::OpaqueTensorType; // NOLINT using mlir::tf_type::PlaceholderAttr; // NOLINT using mlir::tf_type::Qint16RefType; // NOLINT using mlir::tf_type::Qint16Type; // NOLINT using mlir::tf_type::Qint32RefType; // NOLINT using mlir::tf_type::Qint32Type; // NOLINT using mlir::tf_type::Qint8RefType; // NOLINT using mlir::tf_type::Qint8Type; // NOLINT using mlir::tf_type::Quint16RefType; // NOLINT using mlir::tf_type::Quint16Type; // NOLINT using mlir::tf_type::Quint8RefType; // NOLINT using mlir::tf_type::Quint8Type; // NOLINT using mlir::tf_type::ResourceRefType; // NOLINT using mlir::tf_type::ResourceType; // NOLINT using mlir::tf_type::ShapeAttr; // NOLINT using mlir::tf_type::StringRefType; // NOLINT using mlir::tf_type::StringType; // NOLINT using mlir::tf_type::Uint16RefType; // NOLINT using mlir::tf_type::Uint32RefType; // NOLINT using mlir::tf_type::Uint64RefType; // NOLINT using mlir::tf_type::Uint8RefType; // NOLINT using mlir::tf_type::VariantRefType; // NOLINT using mlir::tf_type::VariantType; // NOLINT using mlir::tf_type::VersionAttr; // NOLINT class TFGraphOpAsmInterface; } // namespace tfg } // namespace mlir // Dialect main class is defined in ODS, we include it here. #include "tensorflow/core/ir/dialect.h.inc" #endif // TENSORFLOW_CORE_IR_DIALECT_H_
tensorflow/tensorflow
tensorflow/core/ir/dialect.h
C
apache-2.0
3,276
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.bean.issues; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; import org.junit.Test; public class FilterBeanNonRegistryTest extends ContextTestSupport { @Test public void testBeanLanguageExp() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { MyBean myBean = new MyBean(); from("direct:start").filter().method(myBean, "isGoldCustomer").to("mock:result"); } }); context.start(); getMockEndpoint("mock:result").expectedBodiesReceived("Camel"); template.sendBody("direct:start", "Hello World"); template.sendBody("direct:start", "Camel"); template.sendBody("direct:start", "Bye World"); assertMockEndpointsSatisfied(); } @Test public void testMethodCallExp() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { MyBean myBean = new MyBean(); from("direct:start").filter().method(myBean).to("mock:result"); } }); context.start(); getMockEndpoint("mock:result").expectedBodiesReceived("Camel"); template.sendBody("direct:start", "Hello World"); template.sendBody("direct:start", "Camel"); template.sendBody("direct:start", "Bye World"); assertMockEndpointsSatisfied(); } @Override public boolean isUseRouteBuilder() { return false; } public class MyBean { public boolean isGoldCustomer(String name) { return "Camel".equals(name); } } }
DariusX/camel
core/camel-core/src/test/java/org/apache/camel/component/bean/issues/FilterBeanNonRegistryTest.java
Java
apache-2.0
2,588
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n) { if (n === 1) return 1; return 5; } export default [ 'ckb-IR', [ ['ب.ن', 'د.ن'], , ], , [ ['ی', 'د', 'س', 'چ', 'پ', 'ھ', 'ش'], [ 'یەکشەممە', 'دووشەممە', 'سێشەممە', 'چوارشەممە', 'پێنجشەممە', 'ھەینی', 'شەممە' ], , ['١ش', '٢ش', '٣ش', '٤ش', '٥ش', 'ھ', 'ش'] ], , [ ['ک', 'ش', 'ئ', 'ن', 'ئ', 'ح', 'ت', 'ئ', 'ئ', 'ت', 'ت', 'ک'], [ 'کانوونی دووەم', 'شوبات', 'ئازار', 'نیسان', 'ئایار', 'حوزەیران', 'تەمووز', 'ئاب', 'ئەیلوول', 'تشرینی یەکەم', 'تشرینی دووەم', 'کانونی یەکەم' ], ], , [ ['پێش زایین', 'زایینی'], , ], 6, [5, 5], ['y-MM-dd', 'y MMM d', 'dی MMMMی y', 'y MMMM d, EEEE'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], [ '{1} {0}', , , ], ['.', ',', ';', '%', '\u200e+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'IRR', 'IRR', plural ]; //# sourceMappingURL=ckb-IR.js.map
rospilot/rospilot
share/web_assets/nodejs_deps/node_modules/@angular/common/locales/ckb-IR.js
JavaScript
apache-2.0
1,598
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Util; using QuantConnect.Orders; using QuantConnect.Algorithm; using QuantConnect.Brokerages; using QuantConnect.Interfaces; using QuantConnect.Securities; using QuantConnect.Data.Market; using QuantConnect.Orders.Fees; using QuantConnect.Securities.Option; using QuantConnect.Tests.Engine.DataFeeds; using Option = QuantConnect.Securities.Option.Option; namespace QuantConnect.Tests.Common.Securities { [TestFixture] public class SecurityMarginModelTests { private static Symbol _symbol; private static FakeOrderProcessor _fakeOrderProcessor; [TestCase(1)] [TestCase(2)] [TestCase(50)] public void MarginRemainingForLeverage(decimal leverage) { var algorithm = GetAlgorithm(); algorithm.SetCash(1000); var spy = InitAndGetSecurity(algorithm, 0); spy.Holdings.SetHoldings(25, 100); spy.SetLeverage(leverage); var spyMarginAvailable = spy.Holdings.HoldingsValue - spy.Holdings.HoldingsValue * (1 / leverage); var marginRemaining = algorithm.Portfolio.MarginRemaining; Assert.AreEqual(1000 + spyMarginAvailable, marginRemaining); } [TestCase(1)] [TestCase(2)] [TestCase(50)] public void MarginUsedForPositionWhenPriceDrops(decimal leverage) { var algorithm = GetAlgorithm(); // (1000 * 20) = 20k // Initial and maintenance margin = (1000 * 20) / leverage = X var spy = InitAndGetSecurity(algorithm, 0); spy.Holdings.SetHoldings(20, 1000); spy.SetLeverage(leverage); // Drop 40% price from $20 to $12 // 1000 * 12 = 12k Update(spy, 12); var marginForPosition = spy.BuyingPowerModel.GetReservedBuyingPowerForPosition( new ReservedBuyingPowerForPositionParameters(spy)).AbsoluteUsedBuyingPower; Assert.AreEqual(1000 * 12 / leverage, marginForPosition); } [TestCase(1)] [TestCase(2)] [TestCase(50)] public void MarginUsedForPositionWhenPriceIncreases(decimal leverage) { var algorithm = GetAlgorithm(); algorithm.SetCash(1000); // (1000 * 20) = 20k // Initial and maintenance margin = (1000 * 20) / leverage = X var spy = InitAndGetSecurity(algorithm, 0); spy.Holdings.SetHoldings(25, 1000); spy.SetLeverage(leverage); // Increase from $20 to $40 // 1000 * 40 = 400000 Update(spy, 40); var marginForPosition = spy.BuyingPowerModel.GetReservedBuyingPowerForPosition( new ReservedBuyingPowerForPositionParameters(spy)).AbsoluteUsedBuyingPower; Assert.AreEqual(1000 * 40 / leverage, marginForPosition); } [Test] public void ZeroTargetWithZeroHoldingsIsNotAnError() { var algorithm = GetAlgorithm(); var security = InitAndGetSecurity(algorithm, 0); var model = new SecurityMarginModel(); var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, security, 0, 0); Assert.AreEqual(0, result.Quantity); Assert.IsTrue(result.Reason.IsNullOrEmpty()); Assert.IsFalse(result.IsError); } [TestCase(0)] [TestCase(1)] [TestCase(-1)] public void ReturnsMinimumOrderValueReason(decimal holdings) { var algorithm = GetAlgorithm(); var security = InitAndGetSecurity(algorithm, 0); var model = new SecurityMarginModel(); security.Holdings.SetHoldings(security.Price, holdings); var currentSignedUsedMargin = model.GetInitialMarginRequirement(security, security.Holdings.Quantity); var totalPortfolioValue = algorithm.Portfolio.TotalPortfolioValue; var sign = Math.Sign(security.Holdings.Quantity) == 0 ? 1 : Math.Sign(security.Holdings.Quantity); // we increase it slightly, should not trigger a new order because it's increasing final margin usage, rounds down var newTarget = currentSignedUsedMargin / (totalPortfolioValue) + 0.00001m * sign; var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, security, newTarget, 0); Assert.AreEqual(0m, result.Quantity); Assert.IsFalse(result.IsError); Assert.IsTrue(result.Reason.Contains("The order quantity is less than the lot size of", StringComparison.InvariantCultureIgnoreCase)); } [TestCase(1)] [TestCase(-1)] public void ReducesPositionWhenMarginAboveTargetWhenNegativeFreeMargin(decimal holdings) { var algorithm = GetAlgorithm(); var security = InitAndGetSecurity(algorithm, 0); var model = new SecurityMarginModel(); security.Holdings.SetHoldings(security.Price, holdings); var security2 = InitAndGetSecurity(algorithm, 0, symbol: "AAPL"); // eat up all our TPV security2.Holdings.SetHoldings(security.Price, (algorithm.Portfolio.TotalPortfolioValue / security.Price) * 2); var currentSignedUsedMargin = model.GetInitialMarginRequirement(security, security.Holdings.Quantity); var totalPortfolioValue = algorithm.Portfolio.TotalPortfolioValue; var sign = Math.Sign(security.Holdings.Quantity) == 0 ? 1 : Math.Sign(security.Holdings.Quantity); // we inverse the sign here so that new target is less than current, we expect a reduction var newTarget = currentSignedUsedMargin / (totalPortfolioValue) + 0.00001m * sign * -1; Assert.IsTrue(0 > algorithm.Portfolio.MarginRemaining); var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, security, newTarget, 0); // Reproduces GH issue #5763 a small Reduction in the target should reduce the position Assert.AreEqual(1m * sign * -1, result.Quantity); Assert.IsFalse(result.IsError); } [TestCase(1, 0)] [TestCase(-1, 0)] [TestCase(1, 0.001d)] [TestCase(-1, 0.001d)] public void ReducesPositionWhenMarginAboveTargetBasedOnSetting(decimal holdings, decimal minimumOrderMarginPortfolioPercentage) { var algorithm = GetAlgorithm(); var security = InitAndGetSecurity(algorithm, 0); var model = new SecurityMarginModel(); security.Holdings.SetHoldings(security.Price, holdings); var currentSignedUsedMargin = model.GetInitialMarginRequirement(security, security.Holdings.Quantity); var totalPortfolioValue = algorithm.Portfolio.TotalPortfolioValue; var sign = Math.Sign(security.Holdings.Quantity) == 0 ? 1 : Math.Sign(security.Holdings.Quantity); // we inverse the sign here so that new target is less than current, we expect a reduction var newTarget = currentSignedUsedMargin / (totalPortfolioValue) + 0.00001m * sign * -1; var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, security, newTarget, minimumOrderMarginPortfolioPercentage); if (minimumOrderMarginPortfolioPercentage == 0) { // Reproduces GH issue #5763 a small Reduction in the target should reduce the position Assert.AreEqual(1m * sign * -1, result.Quantity); Assert.IsFalse(result.IsError); } else { Assert.AreEqual(0, result.Quantity); Assert.IsFalse(result.IsError); } } [Test] public void ZeroTargetWithNonZeroHoldingsReturnsNegativeOfQuantity() { var algorithm = GetAlgorithm(); var security = InitAndGetSecurity(algorithm, 0); security.Holdings.SetHoldings(200, 10); var model = new SecurityMarginModel(); var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, security, 0, 0); Assert.AreEqual(-10, result.Quantity); Assert.IsTrue(result.Reason.IsNullOrEmpty()); Assert.IsFalse(result.IsError); } [Test] public void SetHoldings_ZeroToFullLong() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); var actual = algo.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security)); // (100000 * 2 * 0.9975 setHoldingsBuffer) / 25 - fee ~=7979m Assert.AreEqual(7979m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_ZeroToFullLong_NonAccountCurrency_ZeroQuoteCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); // We don't have quote currency - we will get a "loan" algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security)); // (10000 * 2 * 0.9975 setHoldingsBuffer) / 25 * 0.88 conversion rate - 5 USD fee * 0.88 conversion rate ~=906m Assert.AreEqual(906m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [TestCase("Long")] [TestCase("Short")] public void GetReservedBuyingPowerForPosition_NonAccountCurrency_ZeroQuoteCurrency(string position) { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); var security = InitAndGetSecurity(algorithm, 5); security.Holdings.SetHoldings(security.Price, (position == "Long" ? 1 : -1) * 100); var actual = security.BuyingPowerModel.GetReservedBuyingPowerForPosition(new ReservedBuyingPowerForPositionParameters(security)); // 100quantity * 25price * 0.88rate * 0.5 MaintenanceMarginRequirement = 1100 Assert.AreEqual(1100, actual.AbsoluteUsedBuyingPower); } [Test] public void SetHoldings_ZeroToFullLong_NonAccountCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); // We have 1000 USD too algorithm.Portfolio.SetCash(Currencies.USD, 1000, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security)); // ((10000 + 1000 USD * 0.88 rate) * 2 * 0.9975 setHoldingsBuffer) / 25 * 0.88 rate - 5 USD fee * 0.88 rate ~=986m Assert.AreEqual(986m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [Test] public void SetHoldings_Long_TooBigOfATarget() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); var actual = algo.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security) + 0.1m); // (100000 * 2.1* 0.9975 setHoldingsBuffer) / 25 - fee ~=8378m Assert.AreEqual(8378m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_Long_TooBigOfATarget_NonAccountCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); // We don't have quote currency - we will get a "loan" algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security) + 0.1m); // (10000 * 2.1 * 0.9975 setHoldingsBuffer) / 25 * 0.88 conversion rate - 5 USD fee * 0.88 conversion rate ~=951m Assert.AreEqual(951m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [Test] public void SetHoldings_ZeroToFullShort() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); var actual = algo.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security)); // (100000 * 2 * 0.9975 setHoldingsBuffer) / 25 - fee~=-7979m Assert.AreEqual(-7979m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_ZeroToFullShort_NonAccountCurrency_ZeroQuoteCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security)); // (10000 * - 2 * 0.9975 setHoldingsBuffer) / 25 * 0.88 conversion rate - 5 USD fee * 0.88 conversion rate ~=906m Assert.AreEqual(-906m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [Test] public void SetHoldings_ZeroToFullShort_NonAccountCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); algorithm.Portfolio.SetCash(Currencies.USD, 1000, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security)); // ((10000 + 1000 * 0.88)* - 2 * 0.9975 setHoldingsBuffer) / 25 * 0.88 conversion rate - 5 USD fee * 0.88 conversion rate ~=986m Assert.AreEqual(-986m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [Test] public void SetHoldings_Short_TooBigOfATarget() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); var actual = algo.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security) - 0.1m); // (100000 * - 2.1m * 0.9975 setHoldingsBuffer) / 25 - fee~=-8378m Assert.AreEqual(-8378m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_Short_TooBigOfATarget_NonAccountCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security) - 0.1m); // (10000 * - 2.1 * 0.9975 setHoldingsBuffer) / 25 * 0.88 conversion rate - 5 USD fee * 0.88 conversion rate ~=951m Assert.AreEqual(-951m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [Test] public void SetHoldings_ZeroToFullLong_NoFee() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); var actual = algo.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security)); // (100000 * 2 * 0.9975 setHoldingsBuffer) / 25 =7980m Assert.AreEqual(7980m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_Long_TooBigOfATarget_NoFee() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); var actual = algo.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security) + 0.1m); // (100000 * 2.1m* 0.9975 setHoldingsBuffer) / 25 = 8379m Assert.AreEqual(8379m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_ZeroToFullShort_NoFee() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); var actual = algo.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security)); var order = new MarketOrder(_symbol, actual, DateTime.UtcNow); // (100000 * 2 * 0.9975 setHoldingsBuffer) / 25 = -7980m Assert.AreEqual(-7980m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_Short_TooBigOfATarget_NoFee() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); var actual = algo.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security) - 0.1m); // (100000 * -2.1 * 0.9975 setHoldingsBuffer) / 25 = -8379m Assert.AreEqual(-8379m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void FreeBuyingPowerPercentDefault_Equity() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var model = security.BuyingPowerModel; var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 2 * 0.9975) / 25 - 1 order due to fees Assert.AreEqual(7979m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.AreEqual(algo.Portfolio.Cash, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForCashAccount_Equity() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(1, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 1 * 0.95 * 0.9975) / 25 - 1 order due to fees Assert.AreEqual(3790m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual * 1.0025m, security, algo)); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual * 1.0025m + security.SymbolProperties.LotSize + 9, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForMarginAccount_Equity() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(2, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 2 * 0.95 * 0.9975) / 25 - 1 order due to fees Assert.AreEqual(7580m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual * 1.0025m, security, algo)); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual * 1.0025m + security.SymbolProperties.LotSize + 9, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentCashAccountWithLongHoldings_Equity() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(1, requiredFreeBuyingPowerPercent); security.Holdings.SetHoldings(25, 2000); security.SettlementModel.ApplyFunds(algo.Portfolio, security, DateTime.UtcNow.AddDays(-10), Currencies.USD, -2000 * 25); // Margin remaining 50k + used 50k + initial margin 50k - 5k free buying power percent (5% of 100k) Assert.AreEqual(145000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Sell)); // Margin remaining 50k - 5k free buying power percent (5% of 100k) Assert.AreEqual(45000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); var actual = algo.CalculateOrderQuantity(_symbol, -1m * model.GetLeverage(security)); // ((100k - 5) * -1 * 0.95 * 0.9975 - (50k holdings)) / 25 - 1 order due to fees Assert.AreEqual(-5790m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual * 1.0025m, security, algo)); } [Test] public void FreeBuyingPowerPercentMarginAccountWithLongHoldings_Equity() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(2, requiredFreeBuyingPowerPercent); security.Holdings.SetHoldings(25, 2000); security.SettlementModel.ApplyFunds(algo.Portfolio, security, DateTime.UtcNow.AddDays(-10), Currencies.USD, -2000 * 25); // Margin remaining 75k + used 25k + initial margin 25k - 5k free buying power percent (5% of 100k) Assert.AreEqual(120000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Sell)); // Margin remaining 75k - 5k free buying power percent Assert.AreEqual(70000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); var actual = algo.CalculateOrderQuantity(_symbol, -1m * model.GetLeverage(security)); // ((100k - 5) * -2 * 0.95 * 0.9975 - (50k holdings)) / 25 - 1 order due to fees Assert.AreEqual(-9580m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual * 1.0025m, security, algo)); } [Test] public void FreeBuyingPowerPercentMarginAccountWithShortHoldings_Equity() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(2, requiredFreeBuyingPowerPercent); security.Holdings.SetHoldings(25, -2000); security.SettlementModel.ApplyFunds(algo.Portfolio, security, DateTime.UtcNow.AddDays(-10), Currencies.USD, 2000 * 25); // Margin remaining 75k + used 25k + initial margin 25k - 5k free buying power percent (5% of 100k) Assert.AreEqual(120000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); // Margin remaining 75k - 5k free buying power percent Assert.AreEqual(70000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Sell)); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // ((100k - 5) * 2 * 0.95 * 0.9975 - (-50k holdings)) / 25 - 1 order due to fees Assert.AreEqual(9580m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual * 1.0025m, security, algo)); } [Test] public void FreeBuyingPowerPercentDefault_Option() { const decimal price = 25m; const decimal underlyingPrice = 25m; var tz = TimeZones.NewYork; var equity = new QuantConnect.Securities.Equity.Equity( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); equity.SetMarketPrice(new Tick { Value = underlyingPrice }); var optionPutSymbol = Symbol.CreateOption(Symbols.SPY, Market.USA, OptionStyle.American, OptionRight.Put, 207m, new DateTime(2015, 02, 27)); var security = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), optionPutSymbol, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); security.SetMarketPrice(new Tick { Value = price }); security.Underlying = equity; var algo = GetAlgorithm(); security.SetLocalTimeKeeper(algo.TimeKeeper.GetLocalTimeKeeper(tz)); var actual = security.BuyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower( new GetMaximumOrderQuantityForTargetBuyingPowerParameters(algo.Portfolio, security, 1, 0)).Quantity; // (100000 * 1) / (25 * 100 contract multiplier) - 1 order due to fees Assert.AreEqual(39m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.AreEqual(algo.Portfolio.Cash, security.BuyingPowerModel.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForCashAccount_Option() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash); var security = InitAndGetSecurity(algo, 5, SecurityType.Option); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(1, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 1 * 0.95) / (25 * 100 contract multiplier) - 1 order due to fees Assert.AreEqual(37m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForMarginAccount_Option() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); var security = InitAndGetSecurity(algo, 5, SecurityType.Option); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(2, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 2 * 0.95) / (25 * 100 contract multiplier) - 1 order due to fees Assert.AreEqual(75m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentDefault_Future() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5, SecurityType.Future, "ES", time: new DateTime(2020, 1, 27)); var model = security.BuyingPowerModel; var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 1 * 0.9975 ) / 6600 - 1 order due to fees Assert.AreEqual(13m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.AreEqual(algo.Portfolio.Cash, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForCashAccount_Future() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash); var security = InitAndGetSecurity(algo, 5, SecurityType.Future); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(1, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // ((100000 - 5) * 1 * 0.95 * 0.9975 / (25 * 50) Assert.AreEqual(75m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForMarginAccount_Future() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); var security = InitAndGetSecurity(algo, 5, SecurityType.Future); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(2, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // ((100000 - 5) * 2 * 0.95 * 0.9975 / (25 * 50) Assert.AreEqual(151m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [TestCase(0)] [TestCase(10000)] public void NonAccountCurrency_GetBuyingPower(decimal nonAccountCurrencyCash) { var algo = GetAlgorithm(); algo.Portfolio.CashBook.Clear(); algo.Portfolio.SetAccountCurrency("EUR"); algo.Portfolio.SetCash(10000); algo.Portfolio.SetCash(Currencies.USD, nonAccountCurrencyCash, 0.88m); var security = InitAndGetSecurity(algo, 0); Assert.AreEqual(10000m + algo.Portfolio.CashBook[Currencies.USD].ValueInAccountCurrency, algo.Portfolio.TotalPortfolioValue); var quantity = security.BuyingPowerModel.GetBuyingPower( new BuyingPowerParameters(algo.Portfolio, security, OrderDirection.Buy)).Value; Assert.AreEqual(10000m + algo.Portfolio.CashBook[Currencies.USD].ValueInAccountCurrency, quantity); } [Test] public void NonAccountCurrencyFees() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); algo.SetCash("EUR", 0, 100); security.FeeModel = new NonAccountCurrencyCustomFeeModel(); // ((100000 - 100 * 100) * 2 * 0.9975 / (25) var actual = algo.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security)); Assert.AreEqual(7182m, actual); // ((100000 - 100 * 100) * 2 / (25) var quantity = security.BuyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower( algo.Portfolio, security, 1m, 0).Quantity; Assert.AreEqual(7200m, quantity); // the maximum order quantity can be executed Assert.IsTrue(HasSufficientBuyingPowerForOrder(quantity, security, algo)); ; } [TestCase(1)] [TestCase(-1)] public void GetMaximumOrderQuantityForTargetDeltaBuyingPower_NoHoldings(int side) { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); // we use our entire buying power var buyingPower = algo.Portfolio.MarginRemaining * side; var actual = security.BuyingPowerModel.GetMaximumOrderQuantityForDeltaBuyingPower( new GetMaximumOrderQuantityForDeltaBuyingPowerParameters(algo.Portfolio, security, buyingPower, 0)).Quantity; // (100000 * 2 ) / 25 =8k - 1 fees Assert.AreEqual(7999 * side, actual); } [TestCase(100, 510, false)] [TestCase(-100, 510, false)] [TestCase(-100, 50000, true)] [TestCase(100, -510, false)] [TestCase(-100, -510, false)] [TestCase(100, -50000, true)] public void GetMaximumOrderQuantityForTargetDeltaBuyingPower_WithHoldings(decimal quantity, decimal buyingPowerDelta, bool invertsSide) { // TPV = 100k var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); // SPY @ $25 * Quantity Shares = Holdings // Quantity = 100 -> 2500; TPV = 102500 // Quantity = -100 -> -2500; TPV = 97500 security.Holdings.SetHoldings(security.Price, quantity); // Used Buying Power = Holdings / Leverage // Target BP = Used BP + buyingPowerDelta // Target Holdings = Target BP / Unit // Max Order For Delta BP = Target Holdings - Current Holdings // EX. -100 Quantity, 510 BP Delta. // Used BP = -2500 / 2 = -1250 // Target BP = -1250 + 510 = -740 // Target Holdings = -740 / 12.5 = -59.2 -> ~-59 // Max Order = -59 - (-100) = 41 var actual = security.BuyingPowerModel.GetMaximumOrderQuantityForDeltaBuyingPower( new GetMaximumOrderQuantityForDeltaBuyingPowerParameters(algo.Portfolio, security, buyingPowerDelta, 0)).Quantity; // Calculate expected using logic above var targetBuyingPower = ((quantity * (security.Price / security.Leverage)) + buyingPowerDelta); var targetHoldings = (targetBuyingPower / (security.Price / security.Leverage)); targetHoldings -= (targetHoldings % security.SymbolProperties.LotSize); var expectedQuantity = targetHoldings - quantity; Assert.AreEqual(expectedQuantity, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); if (invertsSide) { Assert.AreNotEqual(Math.Sign(quantity), Math.Sign(actual)); } } [TestCase(true, 1, 1)] [TestCase(true, 1, -1)] [TestCase(true, -1, -1)] [TestCase(true, -1, 1)] // reducing the position to target 0 is valid [TestCase(false, 0, -1)] [TestCase(false, 0, 1)] public void NegativeMarginRemaining(bool isError, int target, int side) { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); security.Holdings.SetHoldings(security.Price, 1000 * side); algo.Portfolio.CashBook.Add(algo.AccountCurrency, -100000, 1); var fakeOrderProcessor = new FakeOrderProcessor(); algo.Transactions.SetOrderProcessor(fakeOrderProcessor); Assert.IsTrue(algo.Portfolio.MarginRemaining < 0); var quantity = security.BuyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower( new GetMaximumOrderQuantityForTargetBuyingPowerParameters(algo.Portfolio, security, target * side, 0)).Quantity; if (!isError) { Assert.AreEqual(1000 * side * -1, quantity); } else { // even if we don't have margin 'GetMaximumOrderQuantityForTargetBuyingPower' doesn't care Assert.AreNotEqual(0, quantity); } var order = new MarketOrder(security.Symbol, quantity, new DateTime(2020, 1, 1)); fakeOrderProcessor.AddTicket(order.ToOrderTicket(algo.Transactions)); var actual = security.BuyingPowerModel.HasSufficientBuyingPowerForOrder( new HasSufficientBuyingPowerForOrderParameters(algo.Portfolio, security, order)); Assert.AreEqual(!isError, actual.IsSufficient); } private static QCAlgorithm GetAlgorithm() { SymbolCache.Clear(); // Initialize algorithm var algo = new QCAlgorithm(); algo.SetFinishedWarmingUp(); _fakeOrderProcessor = new FakeOrderProcessor(); algo.Transactions.SetOrderProcessor(_fakeOrderProcessor); return algo; } private static Security InitAndGetSecurity(QCAlgorithm algo, decimal fee, SecurityType securityType = SecurityType.Equity, string symbol = "SPY", DateTime? time = null) { algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo)); Security security; if (securityType == SecurityType.Equity) { security = algo.AddEquity(symbol); _symbol = security.Symbol; } else if (securityType == SecurityType.Option) { security = algo.AddOption(symbol); _symbol = security.Symbol; } else if (securityType == SecurityType.Future) { security = algo.AddFuture(symbol == "SPY" ? "ES" : symbol); _symbol = security.Symbol; } else { throw new Exception("SecurityType not implemented"); } security.FeeModel = new ConstantFeeModel(fee); Update(security, 25, time); return security; } private static void Update(Security security, decimal close, DateTime? time = null) { security.SetMarketPrice(new TradeBar { Time = time ?? DateTime.Now, Symbol = security.Symbol, Open = close, High = close, Low = close, Close = close }); } private bool HasSufficientBuyingPowerForOrder(decimal orderQuantity, Security security, IAlgorithm algo) { var order = new MarketOrder(security.Symbol, orderQuantity, DateTime.UtcNow); _fakeOrderProcessor.AddTicket(order.ToOrderTicket(algo.Transactions)); var hashSufficientBuyingPower = security.BuyingPowerModel.HasSufficientBuyingPowerForOrder(algo.Portfolio, security, new MarketOrder(security.Symbol, orderQuantity, DateTime.UtcNow)); return hashSufficientBuyingPower.IsSufficient; } internal class NonAccountCurrencyCustomFeeModel : FeeModel { public string FeeCurrency = "EUR"; public decimal FeeAmount = 100m; public override OrderFee GetOrderFee(OrderFeeParameters parameters) { return new OrderFee(new CashAmount(FeeAmount, FeeCurrency)); } } } }
StefanoRaggi/Lean
Tests/Common/Securities/SecurityMarginModelTests.cs
C#
apache-2.0
44,236
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![feature(box_syntax)] struct J { j: isize } pub fn main() { let i: Box<_> = box J { j: 100 }; assert_eq!(i.j, 100); }
GBGamer/rust
src/test/run-pass/unique/unique-autoderef-field.rs
Rust
apache-2.0
621
fdupes——Linux中查找并删除重复文件的命令行工具 ================================================================================ 对于大多数计算机用户而言,查找并替换重复的文件是一个常见的需求。查找并移除重复文件真是一项领人不胜其烦的工作,它耗时又耗力。如果你的机器上跑着GNU/Linux,那么查找重复文件会变得十分简单,这多亏了`**fdupes**`工具。 ![Find and Delete Duplicate Files in Linux](http://www.tecmint.com/wp-content/uploads/2015/08/find-and-delete-duplicate-files-in-linux.png) Fdupes——在Linux中查找并删除重复文件 ### fdupes是啥东东? ### **Fdupes**是Linux下的一个工具,它由**Adrian Lopez**用C编程语言编写并基于MIT许可证发行,该应用程序可以在指定的目录及子目录中查找重复的文件。Fdupes通过对比文件的MD5签名,以及逐字节比较文件来识别重复内容,可以为Fdupes指定大量的选项以实现对文件的列出、删除、替换到文件副本的硬链接等操作。 对比以下列顺序开始: **大小对比 > 部分 MD5 签名对比 > 完整 MD5 签名对比 > 逐字节对比** ### 安装 fdupes 到 Linux ### 在基于**Debian**的系统上,如**Ubuntu**和**Linux Mint**,安装最新版fdupes,用下面的命令手到擒来。 $ sudo apt-get install fdupes 在基于CentOS/RHEL和Fedora的系统上,你需要开启[epel仓库][1]来安装fdupes包。 # yum install fdupes # dnf install fdupes [On Fedora 22 onwards] **注意**:自Fedora 22之后,默认的包管理器yum被dnf取代了。 ### fdupes命令咋个搞? ### 1.作为演示的目的,让我们来在某个目录(比如 tecmint)下创建一些重复文件,命令如下: $ mkdir /home/"$USER"/Desktop/tecmint && cd /home/"$USER"/Desktop/tecmint && for i in {1..15}; do echo "I Love Tecmint. Tecmint is a very nice community of Linux Users." > tecmint${i}.txt ; done 在执行以上命令后,让我们使用ls[命令][2]验证重复文件是否创建。 $ ls -l total 60 -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint10.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint11.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint12.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint13.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint14.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint15.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint1.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint2.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint3.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint4.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint5.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint6.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint7.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint8.txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint9.txt 上面的脚本创建了**15**个文件,名称分别为tecmint1.txt,tecmint2.txt……tecmint15.txt,并且每个文件的数据相同,如 "I Love Tecmint. Tecmint is a very nice community of Linux Users." 2.现在在**tecmint**文件夹内搜索重复的文件。 $ fdupes /home/$USER/Desktop/tecmint /home/tecmint/Desktop/tecmint/tecmint13.txt /home/tecmint/Desktop/tecmint/tecmint8.txt /home/tecmint/Desktop/tecmint/tecmint11.txt /home/tecmint/Desktop/tecmint/tecmint3.txt /home/tecmint/Desktop/tecmint/tecmint4.txt /home/tecmint/Desktop/tecmint/tecmint6.txt /home/tecmint/Desktop/tecmint/tecmint7.txt /home/tecmint/Desktop/tecmint/tecmint9.txt /home/tecmint/Desktop/tecmint/tecmint10.txt /home/tecmint/Desktop/tecmint/tecmint2.txt /home/tecmint/Desktop/tecmint/tecmint5.txt /home/tecmint/Desktop/tecmint/tecmint14.txt /home/tecmint/Desktop/tecmint/tecmint1.txt /home/tecmint/Desktop/tecmint/tecmint15.txt /home/tecmint/Desktop/tecmint/tecmint12.txt 3.使用**-r**选项在每个目录包括其子目录中递归搜索重复文件。 它会递归搜索所有文件和文件夹,花一点时间来扫描重复文件,时间的长短取决于文件和文件夹的数量。在此其间,终端中会显示全部过程,像下面这样。 $ fdupes -r /home Progress [37780/54747] 69% 4.使用**-S**选项来查看某个文件夹内找到的重复文件的大小。 $ fdupes -S /home/$USER/Desktop/tecmint 65 bytes each: /home/tecmint/Desktop/tecmint/tecmint13.txt /home/tecmint/Desktop/tecmint/tecmint8.txt /home/tecmint/Desktop/tecmint/tecmint11.txt /home/tecmint/Desktop/tecmint/tecmint3.txt /home/tecmint/Desktop/tecmint/tecmint4.txt /home/tecmint/Desktop/tecmint/tecmint6.txt /home/tecmint/Desktop/tecmint/tecmint7.txt /home/tecmint/Desktop/tecmint/tecmint9.txt /home/tecmint/Desktop/tecmint/tecmint10.txt /home/tecmint/Desktop/tecmint/tecmint2.txt /home/tecmint/Desktop/tecmint/tecmint5.txt /home/tecmint/Desktop/tecmint/tecmint14.txt /home/tecmint/Desktop/tecmint/tecmint1.txt /home/tecmint/Desktop/tecmint/tecmint15.txt /home/tecmint/Desktop/tecmint/tecmint12.txt 5.你可以同时使用**-S**和**-r**选项来查看所有涉及到的目录和子目录中的重复文件的大小,如下: $ fdupes -Sr /home/avi/Desktop/ 65 bytes each: /home/tecmint/Desktop/tecmint/tecmint13.txt /home/tecmint/Desktop/tecmint/tecmint8.txt /home/tecmint/Desktop/tecmint/tecmint11.txt /home/tecmint/Desktop/tecmint/tecmint3.txt /home/tecmint/Desktop/tecmint/tecmint4.txt /home/tecmint/Desktop/tecmint/tecmint6.txt /home/tecmint/Desktop/tecmint/tecmint7.txt /home/tecmint/Desktop/tecmint/tecmint9.txt /home/tecmint/Desktop/tecmint/tecmint10.txt /home/tecmint/Desktop/tecmint/tecmint2.txt /home/tecmint/Desktop/tecmint/tecmint5.txt /home/tecmint/Desktop/tecmint/tecmint14.txt /home/tecmint/Desktop/tecmint/tecmint1.txt /home/tecmint/Desktop/tecmint/tecmint15.txt /home/tecmint/Desktop/tecmint/tecmint12.txt 107 bytes each: /home/tecmint/Desktop/resume_files/r-csc.html /home/tecmint/Desktop/resume_files/fc.html 6.不同于在一个或所有文件夹内递归搜索,你可以选择按要求有选择性地在两个或三个文件夹内进行搜索。不必再提醒你了吧,如有需要,你可以使用**-S**和/或**-r**选项。 $ fdupes /home/avi/Desktop/ /home/avi/Templates/ 7.要删除重复文件,同时保留一个副本,你可以使用`**-d**`选项。使用该选项,你必须额外小心,否则最终结果可能会是文件/数据的丢失。郑重提醒,此操作不可恢复。 $ fdupes -d /home/$USER/Desktop/tecmint [1] /home/tecmint/Desktop/tecmint/tecmint13.txt [2] /home/tecmint/Desktop/tecmint/tecmint8.txt [3] /home/tecmint/Desktop/tecmint/tecmint11.txt [4] /home/tecmint/Desktop/tecmint/tecmint3.txt [5] /home/tecmint/Desktop/tecmint/tecmint4.txt [6] /home/tecmint/Desktop/tecmint/tecmint6.txt [7] /home/tecmint/Desktop/tecmint/tecmint7.txt [8] /home/tecmint/Desktop/tecmint/tecmint9.txt [9] /home/tecmint/Desktop/tecmint/tecmint10.txt [10] /home/tecmint/Desktop/tecmint/tecmint2.txt [11] /home/tecmint/Desktop/tecmint/tecmint5.txt [12] /home/tecmint/Desktop/tecmint/tecmint14.txt [13] /home/tecmint/Desktop/tecmint/tecmint1.txt [14] /home/tecmint/Desktop/tecmint/tecmint15.txt [15] /home/tecmint/Desktop/tecmint/tecmint12.txt Set 1 of 1, preserve files [1 - 15, all]: 你可能注意到了,所有重复的文件被列了出来,并给出删除提示,一个一个来,或者指定范围,或者一次性全部删除。你可以选择一个范围,就像下面这样,来删除指定范围内的文件。 Set 1 of 1, preserve files [1 - 15, all]: 2-15 [-] /home/tecmint/Desktop/tecmint/tecmint13.txt [+] /home/tecmint/Desktop/tecmint/tecmint8.txt [-] /home/tecmint/Desktop/tecmint/tecmint11.txt [-] /home/tecmint/Desktop/tecmint/tecmint3.txt [-] /home/tecmint/Desktop/tecmint/tecmint4.txt [-] /home/tecmint/Desktop/tecmint/tecmint6.txt [-] /home/tecmint/Desktop/tecmint/tecmint7.txt [-] /home/tecmint/Desktop/tecmint/tecmint9.txt [-] /home/tecmint/Desktop/tecmint/tecmint10.txt [-] /home/tecmint/Desktop/tecmint/tecmint2.txt [-] /home/tecmint/Desktop/tecmint/tecmint5.txt [-] /home/tecmint/Desktop/tecmint/tecmint14.txt [-] /home/tecmint/Desktop/tecmint/tecmint1.txt [-] /home/tecmint/Desktop/tecmint/tecmint15.txt [-] /home/tecmint/Desktop/tecmint/tecmint12.txt 8.从安全角度出发,你可能想要打印`**fdupes**`的输出结果到文件中,然后检查文本文件来决定要删除什么文件。这可以降低意外删除文件的风险。你可以这么做: $ fdupes -Sr /home > /home/fdupes.txt **注意**:你可以替换`**/home**`为你想要的文件夹。同时,如果你想要递归搜索并打印大小,可以使用`**-r**`和`**-S**`选项。 9.你可以使用`**-f**`选项来忽略每个匹配集中的首个文件。 首先列出该目录中的文件。 $ ls -l /home/$USER/Desktop/tecmint total 20 -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint9 (3rd copy).txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint9 (4th copy).txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint9 (another copy).txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint9 (copy).txt -rw-r--r-- 1 tecmint tecmint 65 Aug 8 11:22 tecmint9.txt 然后,忽略掉每个匹配集中的首个文件。 $ fdupes -f /home/$USER/Desktop/tecmint /home/tecmint/Desktop/tecmint9 (copy).txt /home/tecmint/Desktop/tecmint9 (3rd copy).txt /home/tecmint/Desktop/tecmint9 (another copy).txt /home/tecmint/Desktop/tecmint9 (4th copy).txt 10.检查已安装的fdupes版本。 $ fdupes --version fdupes 1.51 11.如果你需要关于fdupes的帮助,可以使用`**-h**`开关。 $ fdupes -h Usage: fdupes [options] DIRECTORY... -r --recurse for every directory given follow subdirectories encountered within -R --recurse: for each directory given after this option follow subdirectories encountered within (note the ':' at the end of the option, manpage for more details) -s --symlinks follow symlinks -H --hardlinks normally, when two or more files point to the same disk area they are treated as non-duplicates; this option will change this behavior -n --noempty exclude zero-length files from consideration -A --nohidden exclude hidden files from consideration -f --omitfirst omit the first file in each set of matches -1 --sameline list each set of matches on a single line -S --size show size of duplicate files -m --summarize summarize dupe information -q --quiet hide progress indicator -d --delete prompt user for files to preserve and delete all others; important: under particular circumstances, data may be lost when using this option together with -s or --symlinks, or when specifying a particular directory more than once; refer to the fdupes documentation for additional information -N --noprompt together with --delete, preserve the first file in each set of duplicates and delete the rest without prompting the user -v --version display fdupes version -h --help display this help message 到此为止了。让我知道你到现在为止你是怎么在Linux中查找并删除重复文件的?同时,也让我知道你关于这个工具的看法。在下面的评论部分中提供你有价值的反馈吧,别忘了为我们点赞并分享,帮助我们扩散哦。 我正在使用另外一个移除重复文件的工具,它叫**fslint**。很快就会把使用心得分享给大家哦,你们一定会喜欢看的。 -------------------------------------------------------------------------------- via: http://www.tecmint.com/fdupes-find-and-delete-duplicate-files-in-linux/ 作者:[GOLinux](https://github.com/GOLinux) 校对:[校对者ID](https://github.com/校对者ID) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出 [a]:http://www.tecmint.com/author/avishek/ [1]:http://www.tecmint.com/how-to-enable-epel-repository-for-rhel-centos-6-5/ [2]:http://www.tecmint.com/15-basic-ls-command-examples-in-linux/
LuoZijun/TranslateProject
translated/tech/20150811 fdupes--A Comamndline Tool to Find and Delete Duplicate Files in Linux.md
Markdown
apache-2.0
13,072
vsim CHANGELOG ============== This file is used to list changes made in each version of the vsim cookbook. 0.1.0 ----- - [your_name] - Initial release of vsim - - - Check the [Markdown Syntax Guide](http://daringfireball.net/projects/markdown/syntax) for help with Markdown. The [Github Flavored Markdown page](http://github.github.com/github-flavored-markdown/) describes the differences between markdown on github and standard markdown.
tlichten/vagrant-devstack-manila-vsim
lib/vagrant-vsim/chef/cookbooks/vagrant_vsim/CHANGELOG.md
Markdown
apache-2.0
443
/* * Copyright 2014 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.test; import java.lang.instrument.ClassFileTransformer; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.UndeclaredThrowableException; import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig; import com.navercorp.pinpoint.bootstrap.instrument.ByteCodeInstrumentor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.navercorp.pinpoint.common.util.ClassUtils; import com.navercorp.pinpoint.profiler.DefaultAgent; /** * @author hyungil.jeong */ public class TestClassLoaderFactory { private static final Logger LOGGER = LoggerFactory.getLogger(TestClassLoaderFactory.class); // Classes to check for to determine which Clover runtime has been loaded after source code instrumentation. private static final String CENQUA_CLOVER = "com_cenqua_clover.Clover"; private static final String ATLASSIAN_CLOVER = "com_atlassian_clover.Clover"; public static TestClassLoader createTestClassLoader(ProfilerConfig profilerConfig, ByteCodeInstrumentor byteCodeInstrumentor, ClassFileTransformer classFileTransformer) { final TestClassLoader testClassLoader = new TestClassLoader(profilerConfig, byteCodeInstrumentor, classFileTransformer); checkClover(testClassLoader, CENQUA_CLOVER); checkClover(testClassLoader, ATLASSIAN_CLOVER); return testClassLoader; } private static void checkClover(TestClassLoader testClassLoader, String className) { if (isCloverRuntimePresent(className)) { testClassLoader.addDelegateClass(getPackageName(className)); } } private static String getPackageName(String className) { return ClassUtils.getPackageName(className) + "."; } private static boolean isCloverRuntimePresent(String cloverFqcnToCheckFor) { return ClassUtils.isLoaded(cloverFqcnToCheckFor); } }
masonmei/pinpoint
profiler/src/main/java/com/navercorp/pinpoint/test/TestClassLoaderFactory.java
Java
apache-2.0
2,594
class CreateCodeExperiments < ActiveRecord::Migration def change create_table :code_experiment_configs do |t| t.string :name, null: false t.float :enabled_rate, null: false, default: 0 t.boolean :always_enabled_for_admins, null: false, default: true end add_index :code_experiment_configs, :name, unique: true end end
camallen/Panoptes
db/migrate/20160414151041_create_code_experiments.rb
Ruby
apache-2.0
353
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-text-input-directive-production</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script> </head> <body ng-app="textInputExample"> <script> angular.module('textInputExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.example = { text: 'guest', word: /^\s*\w*\s*$/ }; }]); </script> <form name="myForm" ng-controller="ExampleController"> Single word: <input type="text" name="input" ng-model="example.text" ng-pattern="example.word" required ng-trim="false"> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{example.text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </body> </html>
helmutkemper/GitGoServer
static/d3/angular-1.3.12/docs/examples/example-text-input-directive/index-production.html
HTML
apache-2.0
1,179
<!DOCTYPE html > <html> <head> <title>AlgebirdMonoid - io.gearpump.streaming.monoid.AlgebirdMonoid</title> <meta name="description" content="AlgebirdMonoid - io.gearpump.streaming.monoid.AlgebirdMonoid" /> <meta name="keywords" content="AlgebirdMonoid io.gearpump.streaming.monoid.AlgebirdMonoid" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../../lib/template.js"></script> <script type="text/javascript" src="../../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../../../index.html'; var hash = 'io.gearpump.streaming.monoid.AlgebirdMonoid'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="type"> <div id="definition"> <img alt="Class" src="../../../../lib/class_big.png" /> <p id="owner"><a href="../../../package.html" class="extype" name="io">io</a>.<a href="../../package.html" class="extype" name="io.gearpump">gearpump</a>.<a href="../package.html" class="extype" name="io.gearpump.streaming">streaming</a>.<a href="package.html" class="extype" name="io.gearpump.streaming.monoid">monoid</a></p> <h1>AlgebirdMonoid</h1><h3><span class="morelinks"><div>Related Doc: <a href="package.html" class="extype" name="io.gearpump.streaming.monoid">package monoid</a> </div></span></h3><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">class</span> </span> <span class="symbol"> <span class="name">AlgebirdMonoid</span><span class="tparams">[<span name="T">T</span>]</span><span class="result"> extends <a href="../state/api/Monoid.html" class="extype" name="io.gearpump.streaming.state.api.Monoid">Monoid</a>[<span class="extype" name="io.gearpump.streaming.monoid.AlgebirdMonoid.T">T</span>]</span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><a href="../state/api/Monoid.html" class="extype" name="io.gearpump.streaming.state.api.Monoid">Monoid</a>[<span class="extype" name="io.gearpump.streaming.monoid.AlgebirdMonoid.T">T</span>], <span class="extype" name="java.io.Serializable">Serializable</span>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By Inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="io.gearpump.streaming.monoid.AlgebirdMonoid"><span>AlgebirdMonoid</span></li><li class="in" name="io.gearpump.streaming.state.api.Monoid"><span>Monoid</span></li><li class="in" name="java.io.Serializable"><span>Serializable</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show All</span></li> </ol> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="constructors" class="members"> <h3>Instance Constructors</h3> <ol><li name="io.gearpump.streaming.monoid.AlgebirdMonoid#&lt;init&gt;" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="&lt;init&gt;(monoid:com.twitter.algebird.Monoid[T]):io.gearpump.streaming.monoid.AlgebirdMonoid[T]"></a> <a id="&lt;init&gt;:AlgebirdMonoid[T]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">new</span> </span> <span class="symbol"> <span class="name">AlgebirdMonoid</span><span class="params">(<span name="monoid">monoid: <span class="extype" name="com.twitter.algebird.Monoid">Monoid</span>[<span class="extype" name="io.gearpump.streaming.monoid.AlgebirdMonoid.T">T</span>]</span>)</span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@&lt;init&gt;(monoid:com.twitter.algebird.Monoid[T]):io.gearpump.streaming.monoid.AlgebirdMonoid[T]" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> </li></ol> </div> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@!=(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@##():Int" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@==(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@asInstanceOf[T0]:T0" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@clone():Object" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@eq(x$1:AnyRef):Boolean" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@equals(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@finalize():Unit" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@getClass():Class[_]" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@hashCode():Int" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@isInstanceOf[T0]:Boolean" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@ne(x$1:AnyRef):Boolean" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@notify():Unit" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@notifyAll():Unit" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="io.gearpump.streaming.monoid.AlgebirdMonoid#plus" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="plus(l:T,r:T):T"></a> <a id="plus(T,T):T"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">plus</span><span class="params">(<span name="l">l: <span class="extype" name="io.gearpump.streaming.monoid.AlgebirdMonoid.T">T</span></span>, <span name="r">r: <span class="extype" name="io.gearpump.streaming.monoid.AlgebirdMonoid.T">T</span></span>)</span><span class="result">: <span class="extype" name="io.gearpump.streaming.monoid.AlgebirdMonoid.T">T</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@plus(l:T,r:T):T" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="io.gearpump.streaming.monoid.AlgebirdMonoid">AlgebirdMonoid</a> → <a href="../state/api/Monoid.html" class="extype" name="io.gearpump.streaming.state.api.Monoid">Monoid</a></dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@synchronized[T0](x$1:=&gt;T0):T0" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@toString():String" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@wait():Unit" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@wait(x$1:Long,x$2:Int):Unit" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@wait(x$1:Long):Unit" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="io.gearpump.streaming.monoid.AlgebirdMonoid#zero" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="zero:T"></a> <a id="zero:T"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">zero</span><span class="result">: <span class="extype" name="io.gearpump.streaming.monoid.AlgebirdMonoid.T">T</span></span> </span> </h4><span class="permalink"> <a href="../../../../index.html#io.gearpump.streaming.monoid.AlgebirdMonoid@zero:T" title="Permalink" target="_top"> <img src="../../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="io.gearpump.streaming.monoid.AlgebirdMonoid">AlgebirdMonoid</a> → <a href="../state/api/Monoid.html" class="extype" name="io.gearpump.streaming.state.api.Monoid">Monoid</a></dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="io.gearpump.streaming.state.api.Monoid"> <h3>Inherited from <a href="../state/api/Monoid.html" class="extype" name="io.gearpump.streaming.state.api.Monoid">Monoid</a>[<span class="extype" name="io.gearpump.streaming.monoid.AlgebirdMonoid.T">T</span>]</h3> </div><div class="parent" name="java.io.Serializable"> <h3>Inherited from <span class="extype" name="java.io.Serializable">Serializable</span></h3> </div><div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
stanleyxu2005/gearpump.github.io
releases/latest/api/scala/io/gearpump/streaming/monoid/AlgebirdMonoid.html
HTML
apache-2.0
30,009
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.compiler.artifacts; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.DependencyScope; import com.intellij.openapi.roots.ModuleRootModificationUtil; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.elements.PackagingElement; import com.intellij.project.IntelliJProjectConfiguration; import com.intellij.testFramework.VfsTestUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author nik */ public abstract class PackagingElementsTestCase extends ArtifactsTestCase { protected Artifact addArtifact(TestPackagingElementBuilder builder) { return addArtifact("a", builder); } protected Artifact addArtifact(final String name, TestPackagingElementBuilder builder) { return addArtifact(name, builder.build()); } protected static void assertLayout(Artifact artifact, String expected) { assertLayout(artifact.getRootElement(), expected); } protected static void assertLayout(PackagingElement element, String expected) { ArtifactsTestUtil.assertLayout(element, expected); } protected String getProjectBasePath() { return getBaseDir().getPath(); } protected VirtualFile getBaseDir() { final VirtualFile baseDir = myProject.getBaseDir(); assertNotNull(baseDir); return baseDir; } protected TestPackagingElementBuilder root() { return TestPackagingElementBuilder.root(myProject); } protected TestPackagingElementBuilder archive(String name) { return TestPackagingElementBuilder.archive(myProject, name); } protected VirtualFile createFile(final String path) { return createFile(path, ""); } protected VirtualFile createFile(final String path, final String text) { return VfsTestUtil.createFile(getBaseDir(), path, text); } protected VirtualFile createDir(final String path) { return VfsTestUtil.createDir(getBaseDir(), path); } protected static VirtualFile getJDomJar() { return IntelliJProjectConfiguration.getJarFromSingleJarProjectLibrary("JDOM"); } protected static String getLocalJarPath(VirtualFile jarEntry) { return VfsUtil.getLocalFile(jarEntry).getPath(); } protected Library addProjectLibrary(final @Nullable Module module, final String name, final VirtualFile... jars) { return addProjectLibrary(module, name, DependencyScope.COMPILE, jars); } protected Library addProjectLibrary(final @Nullable Module module, final String name, final DependencyScope scope, final VirtualFile... jars) { return addProjectLibrary(myProject, module, name, scope, jars); } static Library addProjectLibrary(final Project project, final @Nullable Module module, final String name, final DependencyScope scope, final VirtualFile[] jars) { return new WriteAction<Library>() { @Override protected void run(@NotNull final Result<Library> result) { final Library library = LibraryTablesRegistrar.getInstance().getLibraryTable(project).createLibrary(name); final Library.ModifiableModel libraryModel = library.getModifiableModel(); for (VirtualFile jar : jars) { libraryModel.addRoot(jar, OrderRootType.CLASSES); } libraryModel.commit(); if (module != null) { ModuleRootModificationUtil.addDependency(module, library, scope, false); } result.setResult(library); } }.execute().getResultObject(); } protected static void addModuleLibrary(final Module module, final VirtualFile jar) { ModuleRootModificationUtil.addModuleLibrary(module, jar.getUrl()); } protected static void addModuleDependency(final Module module, final Module dependency) { ModuleRootModificationUtil.addDependency(module, dependency); } }
ThiagoGarciaAlves/intellij-community
java/compiler/tests/com/intellij/compiler/artifacts/PackagingElementsTestCase.java
Java
apache-2.0
4,860
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Provides implementations for {@link com.hazelcast.config.ConfigPatternMatcher}. */ package com.hazelcast.config.matcher;
emre-aydin/hazelcast
hazelcast/src/main/java/com/hazelcast/config/matcher/package-info.java
Java
apache-2.0
756
create table Attachment ( id numeric(19,0) identity not null, accessType int null, attachedAt datetime null, attachmentContentId numeric(19,0) not null, contentType varchar(255) null, name varchar(255) null, attachment_size int null, attachedBy_id varchar(255) null, TaskData_Attachments_Id numeric(19,0) null, primary key (id) ); create table AuditTaskImpl ( id numeric(19,0) identity not null, activationTime datetime null, actualOwner varchar(255) null, createdBy varchar(255) null, createdOn datetime null, deploymentId varchar(255) null, description varchar(255) null, dueDate datetime null, name varchar(255) null, parentId numeric(19,0) not null, priority int not null, processId varchar(255) null, processInstanceId numeric(19,0) not null, processSessionId numeric(19,0) not null, status varchar(255) null, taskId numeric(19,0) null, workItemId numeric(19,0) null, primary key (id) ); create table BAMTaskSummary ( pk numeric(19,0) identity not null, createdDate datetime null, duration numeric(19,0) null, endDate datetime null, processInstanceId numeric(19,0) not null, startDate datetime null, status varchar(255) null, taskId numeric(19,0) not null, taskName varchar(255) null, userId varchar(255) null, OPTLOCK int null, primary key (pk) ); create table BooleanExpression ( id numeric(19,0) identity not null, expression text null, type varchar(255) null, Escalation_Constraints_Id numeric(19,0) null, primary key (id) ); create table Content ( id numeric(19,0) identity not null, content image null, primary key (id) ); create table ContextMappingInfo ( mappingId numeric(19,0) identity not null, CONTEXT_ID varchar(255) not null, KSESSION_ID numeric(19,0) not null, OWNER_ID varchar(255) null, OPTLOCK int null, primary key (mappingId) ); create table CorrelationKeyInfo ( keyId numeric(19,0) identity not null, name varchar(255) null, processInstanceId numeric(19,0) not null, OPTLOCK int null, primary key (keyId) ); create table CorrelationPropertyInfo ( propertyId numeric(19,0) identity not null, name varchar(255) null, value varchar(255) null, OPTLOCK int null, correlationKey_keyId numeric(19,0) null, primary key (propertyId) ); create table Deadline ( id numeric(19,0) identity not null, deadline_date datetime null, escalated smallint null, Deadlines_StartDeadLine_Id numeric(19,0) null, Deadlines_EndDeadLine_Id numeric(19,0) null, primary key (id) ); create table Delegation_delegates ( task_id numeric(19,0) not null, entity_id varchar(255) not null ); create table DeploymentStore ( id numeric(19,0) identity not null, attributes varchar(255) null, DEPLOYMENT_ID varchar(255) null, deploymentUnit text null, state int null, updateDate datetime null, primary key (id) ); create table ErrorInfo ( id numeric(19,0) identity not null, message varchar(255) null, stacktrace varchar(5000) null, timestamp datetime null, REQUEST_ID numeric(19,0) not null, primary key (id) ); create table Escalation ( id numeric(19,0) identity not null, name varchar(255) null, Deadline_Escalation_Id numeric(19,0) null, primary key (id) ); create table EventTypes ( InstanceId numeric(19,0) not null, element varchar(255) null ); create table I18NText ( id numeric(19,0) identity not null, language varchar(255) null, shortText varchar(255) null, text text null, Task_Subjects_Id numeric(19,0) null, Task_Names_Id numeric(19,0) null, Task_Descriptions_Id numeric(19,0) null, Reassignment_Documentation_Id numeric(19,0) null, Notification_Subjects_Id numeric(19,0) null, Notification_Names_Id numeric(19,0) null, Notification_Documentation_Id numeric(19,0) null, Notification_Descriptions_Id numeric(19,0) null, Deadline_Documentation_Id numeric(19,0) null, primary key (id) ); create table NodeInstanceLog ( id numeric(19,0) identity not null, connection varchar(255) null, log_date datetime null, externalId varchar(255) null, nodeId varchar(255) null, nodeInstanceId varchar(255) null, nodeName varchar(255) null, nodeType varchar(255) null, processId varchar(255) null, processInstanceId numeric(19,0) not null, type int not null, workItemId numeric(19,0) null, primary key (id) ); create table Notification ( DTYPE varchar(31) not null, id numeric(19,0) identity not null, priority int not null, Escalation_Notifications_Id numeric(19,0) null, primary key (id) ); create table Notification_BAs ( task_id numeric(19,0) not null, entity_id varchar(255) not null ); create table Notification_Recipients ( task_id numeric(19,0) not null, entity_id varchar(255) not null ); create table Notification_email_header ( Notification_id numeric(19,0) not null, emailHeaders_id numeric(19,0) not null, mapkey varchar(255) not null, primary key (Notification_id, mapkey) ); create table OrganizationalEntity ( DTYPE varchar(31) not null, id varchar(255) not null, primary key (id) ); create table PeopleAssignments_BAs ( task_id numeric(19,0) not null, entity_id varchar(255) not null ); create table PeopleAssignments_ExclOwners ( task_id numeric(19,0) not null, entity_id varchar(255) not null ); create table PeopleAssignments_PotOwners ( task_id numeric(19,0) not null, entity_id varchar(255) not null ); create table PeopleAssignments_Recipients ( task_id numeric(19,0) not null, entity_id varchar(255) not null ); create table PeopleAssignments_Stakeholders ( task_id numeric(19,0) not null, entity_id varchar(255) not null ); create table ProcessInstanceInfo ( InstanceId numeric(19,0) identity not null, lastModificationDate datetime null, lastReadDate datetime null, processId varchar(255) null, processInstanceByteArray image null, startDate datetime null, state int not null, OPTLOCK int null, primary key (InstanceId) ); create table ProcessInstanceLog ( id numeric(19,0) identity not null, correlationKey varchar(255) null, duration numeric(19,0) null, end_date datetime null, externalId varchar(255) null, user_identity varchar(255) null, outcome varchar(255) null, parentProcessInstanceId numeric(19,0) null, processId varchar(255) null, processInstanceDescription varchar(255) null, processInstanceId numeric(19,0) not null, processName varchar(255) null, processVersion varchar(255) null, start_date datetime null, status int null, primary key (id) ); create table Reassignment ( id numeric(19,0) identity not null, Escalation_Reassignments_Id numeric(19,0) null, primary key (id) ); create table Reassignment_potentialOwners ( task_id numeric(19,0) not null, entity_id varchar(255) not null ); create table RequestInfo ( id numeric(19,0) identity not null, commandName varchar(255) null, deploymentId varchar(255) null, executions int not null, businessKey varchar(255) null, message varchar(255) null, owner varchar(255) null, requestData image null, responseData image null, retries int not null, status varchar(255) null, timestamp datetime null, primary key (id) ); create table SessionInfo ( id numeric(19,0) identity not null, lastModificationDate datetime null, rulesByteArray image null, startDate datetime null, OPTLOCK int null, primary key (id) ); create table Task ( id numeric(19,0) identity not null, archived smallint null, allowedToDelegate varchar(255) null, description varchar(255) null, formName varchar(255) null, name varchar(255) null, priority int not null, subTaskStrategy varchar(255) null, subject varchar(255) null, activationTime datetime null, createdOn datetime null, deploymentId varchar(255) null, documentAccessType int null, documentContentId numeric(19,0) not null, documentType varchar(255) null, expirationTime datetime null, faultAccessType int null, faultContentId numeric(19,0) not null, faultName varchar(255) null, faultType varchar(255) null, outputAccessType int null, outputContentId numeric(19,0) not null, outputType varchar(255) null, parentId numeric(19,0) not null, previousStatus int null, processId varchar(255) null, processInstanceId numeric(19,0) not null, processSessionId numeric(19,0) not null, skipable boolean not null, status varchar(255) null, workItemId numeric(19,0) not null, taskType varchar(255) null, OPTLOCK int null, taskInitiator_id varchar(255) null, actualOwner_id varchar(255) null, createdBy_id varchar(255) null, primary key (id) ); create table TaskDef ( id numeric(19,0) identity not null, name varchar(255) null, priority int not null, primary key (id) ); create table TaskEvent ( id numeric(19,0) identity not null, logTime datetime null, message varchar(255) null, processInstanceId numeric(19,0) null, taskId numeric(19,0) null, type varchar(255) null, userId varchar(255) null, OPTLOCK int null, workItemId numeric(19,0) null, primary key (id) ); create table VariableInstanceLog ( id numeric(19,0) identity not null, log_date datetime null, externalId varchar(255) null, oldValue varchar(255) null, processId varchar(255) null, processInstanceId numeric(19,0) not null, value varchar(255) null, variableId varchar(255) null, variableInstanceId varchar(255) null, primary key (id) ); create table WorkItemInfo ( workItemId numeric(19,0) identity not null, creationDate datetime null, name varchar(255) null, processInstanceId numeric(19,0) not null, state numeric(19,0) not null, OPTLOCK int null, workItemByteArray image null, primary key (workItemId) ); create table email_header ( id numeric(19,0) identity not null, body text null, fromAddress varchar(255) null, language varchar(255) null, replyToAddress varchar(255) null, subject varchar(255) null, primary key (id) ); create table task_comment ( id numeric(19,0) identity not null, addedAt datetime null, text text null, addedBy_id varchar(255) null, TaskData_Comments_Id numeric(19,0) null, primary key (id) ); alter table Attachment add constraint FK1C93543D937BFB5 foreign key (attachedBy_id) references OrganizationalEntity; alter table Attachment add constraint FK1C9354333CA892A foreign key (TaskData_Attachments_Id) references Task; alter table BooleanExpression add constraint FKE3D208C06C97C90E foreign key (Escalation_Constraints_Id) references Escalation; alter table CorrelationPropertyInfo add constraint FK761452A5D87156ED foreign key (correlationKey_keyId) references CorrelationKeyInfo; alter table Deadline add constraint FK21DF3E78A9FE0EF4 foreign key (Deadlines_StartDeadLine_Id) references Task; alter table Deadline add constraint FK21DF3E78695E4DDB foreign key (Deadlines_EndDeadLine_Id) references Task; alter table Delegation_delegates add constraint FK47485D5772B3A123 foreign key (entity_id) references OrganizationalEntity; alter table Delegation_delegates add constraint FK47485D57786553A5 foreign key (task_id) references Task; alter table DeploymentStore add constraint UK_DeploymentStore_1 unique (DEPLOYMENT_ID); alter table ErrorInfo add constraint FK8B1186B6724A467 foreign key (REQUEST_ID) references RequestInfo; alter table Escalation add constraint FK67B2C6B5D1E5CC1 foreign key (Deadline_Escalation_Id) references Deadline; alter table EventTypes add constraint FKB0E5621F7665489A foreign key (InstanceId) references ProcessInstanceInfo; alter table I18NText add constraint FK2349686BF4ACCD69 foreign key (Task_Subjects_Id) references Task; alter table I18NText add constraint FK2349686B424B187C foreign key (Task_Names_Id) references Task; alter table I18NText add constraint FK2349686BAB648139 foreign key (Task_Descriptions_Id) references Task; alter table I18NText add constraint FK2349686BB340A2AA foreign key (Reassignment_Documentation_Id) references Reassignment; alter table I18NText add constraint FK2349686BF0CDED35 foreign key (Notification_Subjects_Id) references Notification; alter table I18NText add constraint FK2349686BCC03ED3C foreign key (Notification_Names_Id) references Notification; alter table I18NText add constraint FK2349686B77C1C08A foreign key (Notification_Documentation_Id) references Notification; alter table I18NText add constraint FK2349686B18DDFE05 foreign key (Notification_Descriptions_Id) references Notification; alter table I18NText add constraint FK2349686B78AF072A foreign key (Deadline_Documentation_Id) references Deadline; alter table Notification add constraint FK2D45DD0BC0C0F29C foreign key (Escalation_Notifications_Id) references Escalation; alter table Notification_BAs add constraint FK2DD68EE072B3A123 foreign key (entity_id) references OrganizationalEntity; alter table Notification_BAs add constraint FK2DD68EE093F2090B foreign key (task_id) references Notification; alter table Notification_Recipients add constraint FK98FD214E72B3A123 foreign key (entity_id) references OrganizationalEntity; alter table Notification_Recipients add constraint FK98FD214E93F2090B foreign key (task_id) references Notification; alter table Notification_email_header add constraint UK_F30FE3446CEA0510 unique (emailHeaders_id); alter table Notification_email_header add constraint FKF30FE3448BED1339 foreign key (emailHeaders_id) references email_header; alter table Notification_email_header add constraint FKF30FE3443E3E97EB foreign key (Notification_id) references Notification; alter table PeopleAssignments_BAs add constraint FK9D8CF4EC72B3A123 foreign key (entity_id) references OrganizationalEntity; alter table PeopleAssignments_BAs add constraint FK9D8CF4EC786553A5 foreign key (task_id) references Task; alter table PeopleAssignments_ExclOwners add constraint FKC77B97E472B3A123 foreign key (entity_id) references OrganizationalEntity; alter table PeopleAssignments_ExclOwners add constraint FKC77B97E4786553A5 foreign key (task_id) references Task; alter table PeopleAssignments_PotOwners add constraint FK1EE418D72B3A123 foreign key (entity_id) references OrganizationalEntity; alter table PeopleAssignments_PotOwners add constraint FK1EE418D786553A5 foreign key (task_id) references Task; alter table PeopleAssignments_Recipients add constraint FKC6F615C272B3A123 foreign key (entity_id) references OrganizationalEntity; alter table PeopleAssignments_Recipients add constraint FKC6F615C2786553A5 foreign key (task_id) references Task; alter table PeopleAssignments_Stakeholders add constraint FK482F79D572B3A123 foreign key (entity_id) references OrganizationalEntity; alter table PeopleAssignments_Stakeholders add constraint FK482F79D5786553A5 foreign key (task_id) references Task; alter table Reassignment add constraint FK724D056062A1E871 foreign key (Escalation_Reassignments_Id) references Escalation; alter table Reassignment_potentialOwners add constraint FK90B59CFF72B3A123 foreign key (entity_id) references OrganizationalEntity; alter table Reassignment_potentialOwners add constraint FK90B59CFF35D2FEE0 foreign key (task_id) references Reassignment; alter table Task add constraint FK27A9A53C55C806 foreign key (taskInitiator_id) references OrganizationalEntity; alter table Task add constraint FK27A9A5B723BE8B foreign key (actualOwner_id) references OrganizationalEntity; alter table Task add constraint FK27A9A55427E8F1 foreign key (createdBy_id) references OrganizationalEntity; alter table task_comment add constraint FK61F475A57A3215D9 foreign key (addedBy_id) references OrganizationalEntity; alter table task_comment add constraint FK61F475A5F510CB46 foreign key (TaskData_Comments_Id) references Task;
Salaboy/jbpm
jbpm-installer/db/ddl-scripts/sybase/sybase-jbpm-schema.sql
SQL
apache-2.0
19,723
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.connector.thrift.api.datatypes; import com.facebook.presto.connector.thrift.api.PrestoThriftBlock; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.Type; import com.facebook.swift.codec.ThriftConstructor; import com.facebook.swift.codec.ThriftField; import com.facebook.swift.codec.ThriftStruct; import javax.annotation.Nullable; import java.util.Objects; import static com.facebook.presto.connector.thrift.api.PrestoThriftBlock.jsonData; import static com.facebook.presto.connector.thrift.api.datatypes.SliceData.fromSliceBasedBlock; import static com.facebook.swift.codec.ThriftField.Requiredness.OPTIONAL; import static com.google.common.base.MoreObjects.toStringHelper; /** * Elements of {@code nulls} array determine if a value for a corresponding row is null. * Each elements of {@code sizes} array contains the length in bytes for the corresponding element. * If row is null then the corresponding element in {@code sizes} is ignored. * {@code bytes} array contains UTF-8 encoded byte values for string representation of json. * Values for all rows are written to {@code bytes} array one after another. * The total number of bytes must be equal to the sum of all sizes. */ @ThriftStruct public final class PrestoThriftJson implements PrestoThriftColumnData { private final SliceData sliceType; @ThriftConstructor public PrestoThriftJson( @ThriftField(name = "nulls") @Nullable boolean[] nulls, @ThriftField(name = "sizes") @Nullable int[] sizes, @ThriftField(name = "bytes") @Nullable byte[] bytes) { this.sliceType = new SliceData(nulls, sizes, bytes); } @Nullable @ThriftField(value = 1, requiredness = OPTIONAL) public boolean[] getNulls() { return sliceType.getNulls(); } @Nullable @ThriftField(value = 2, requiredness = OPTIONAL) public int[] getSizes() { return sliceType.getSizes(); } @Nullable @ThriftField(value = 3, requiredness = OPTIONAL) public byte[] getBytes() { return sliceType.getBytes(); } @Override public Block toBlock(Type desiredType) { return sliceType.toBlock(desiredType); } @Override public int numberOfRecords() { return sliceType.numberOfRecords(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } PrestoThriftJson other = (PrestoThriftJson) obj; return Objects.equals(this.sliceType, other.sliceType); } @Override public int hashCode() { return sliceType.hashCode(); } @Override public String toString() { return toStringHelper(this) .add("numberOfRecords", numberOfRecords()) .toString(); } public static PrestoThriftBlock fromBlock(Block block, Type type) { return fromSliceBasedBlock(block, type, (nulls, sizes, bytes) -> jsonData(new PrestoThriftJson(nulls, sizes, bytes))); } }
Teradata/presto
presto-thrift-connector-api/src/main/java/com/facebook/presto/connector/thrift/api/datatypes/PrestoThriftJson.java
Java
apache-2.0
3,755
{% load i18n sizeformat %} {% load url from future %} <h3>{% trans "Cluster Overview" %}</h3> <div class="status row detail"> <dl> <dt>{% trans "Name" %}</dt> <dd>{{ cluster.name }}</dd> <dt>{% trans "ID" %}</dt> <dd>{{ cluster.id }}</dd> <dt>{% trans "Description" %}</dt> <dd>{{ cluster.description|default:_("None") }}</dd> <dt>{% trans "Status" %}</dt> <dd>{{ cluster.status }}</dd> </dl> {% if cluster.error_description %} <h4>{% trans "Error Details" %}</h4> <p class="well"> {{ cluster.error_description }} </p> {% endif %} <dl> <dt>{% trans "Plugin" %}</dt> <dd><a href="{% url 'horizon:project:data_processing.data_plugins:details' cluster.plugin_name %}">{{ cluster.plugin_name }}</a></dd> <dt>{% trans "Version" %}</dt> <dd>{{ cluster.hadoop_version }}</dd> </dl> <dl> <dt>{% trans "Template" %}</dt> {% if cluster_template %} <dd><a href="{% url 'horizon:project:data_processing.cluster_templates:details' cluster_template.id %}">{{ cluster_template.name }} </a></dd> {% else %} <dd>{% trans "Template not specified" %}</dd> {% endif %} <dt>{% trans "Base Image" %}</dt> <dd><a href="{% url 'horizon:project:images:images:detail' base_image.id %}">{{ base_image.name }}</a></dd> {% if network %} <dt>{% trans "Neutron Management Network" %}</dt> <dd>{{ network }}</dd> {% endif %} <dt>{% trans "Keypair" %}</dt> <dd>{{ cluster.user_keypair_id }}</dd> </dl> <dl> <dt>{% trans "Anti-affinity enabled for" %}</dt> {% if cluster.anti_affinity %} <dd> <ul class="list-bullet"> {% for process in cluster.anti_affinity %} <li>{{ process }}</li> {% endfor %} </ul> </dd> {% else %} <h6>{% trans "no processes" %}</h6> {% endif %} </dl> <dl> <dt>{% trans "Node Configurations" %}</dt> {% if cluster.cluster_configs %} <dd> {% for service, service_conf in cluster.cluster_configs.items %} <h4>{{ service }}</h4> {% if service_conf %} <ul> {% for conf_name, conf_value in service_conf.items %} <li>{% blocktrans %}{{ conf_name }}: {{ conf_value }}{% endblocktrans %}</li> {% endfor %} </ul> {% else %} <h6>{% trans "No configurations" %}</h6> {% endif %} {% endfor %} </dd> {% else %} <dd>{% trans "Cluster configurations are not specified" %}</dd> {% endif %} </dl> <dl> {% for info_key, info_val in cluster.info.items %} <dt>{{ info_key }}</dt> {% for key, val in info_val.items %} <dd> {% autoescape off %}{% blocktrans %}{{ key }}: {{ val }}{% endblocktrans %}{% endautoescape %} </dd> {% endfor %} {% endfor %} </dl> </div>
mrunge/openstack_horizon
openstack_horizon/dashboards/project/data_processing/clusters/templates/data_processing.clusters/_details.html
HTML
apache-2.0
3,275
class Partition < ApplicationRecord belongs_to :disk belongs_to :hardware has_many :volumes, lambda { |_| p = Partition.quoted_table_name v = Volume.quoted_table_name Volume.select("DISTINCT #{v}.*") .joins("JOIN #{p} ON #{v}.hardware_id = #{p}.hardware_id AND #{v}.volume_group = #{p}.volume_group") .where("#{p}.id" => id) }, :foreign_key => :volume_group virtual_column :aligned, :type => :boolean def volume_group # Override volume_group getter to prevent the special physical linkage from coming through vg = read_attribute(:volume_group) return nil if vg.respond_to?(:starts_with?) && vg.starts_with?(Volume::PHYSICAL_VOLUME_GROUP) vg end # Derived from linux fdisk "list known partition types" # More info at http://www.win.tue.nl/~aeb/partitions/partition_types-1.html PARTITION_TYPE_NAMES = { 0x00 => "Empty", 0x01 => "FAT12", 0x02 => "XENIX root", 0x03 => "XENIX usr", 0x04 => "FAT16 <32M", 0x05 => "Extended", 0x06 => "FAT16", 0x07 => "HPFS/NTFS", 0x08 => "AIX", 0x09 => "AIX bootable", 0x0a => "OS/2 Boot Manager", 0x0b => "W95 FAT32", 0x0c => "W95 FAT32 (LBA)", 0x0e => "W95 FAT16 (LBA)", 0x0f => "W95 Ext'd (LBA)", 0x10 => "OPUS", 0x11 => "Hidden FAT12", 0x12 => "Compaq diagnostic", 0x14 => "Hidden FAT16 <32M", 0x16 => "Hidden FAT16", 0x17 => "Hidden HPFS/NTFS", 0x18 => "AST SmartSleep", 0x1b => "Hidden W95 FAT32", 0x1c => "Hidden W95 FAT32 (LBA)", 0x1e => "Hidden W95 FAT16 (LBA)", 0x24 => "NEC DOS", 0x39 => "Plan 9", 0x3c => "PartitionMagic", 0x40 => "Venix 80286", 0x41 => "PPC PReP Boot", 0x42 => "SFS", 0x4d => "QNX4.x", 0x4e => "QNX4.x 2nd part", 0x4f => "QNX4.x 3rd part", 0x50 => "OnTrack DM", 0x51 => "OnTrack DM6 Aux1", 0x52 => "CP/M", 0x53 => "OnTrack DM6 Aux3", 0x54 => "OnTrackDM6", 0x55 => "EZ-Drive", 0x56 => "Golden Bow", 0x5c => "Priam Edisk", 0x61 => "SpeedStor", 0x63 => "GNU HURD or System V", 0x64 => "Novell Netware 286", 0x65 => "Novell Netware 386", 0x70 => "DiskSecure MultiBoot", 0x75 => "PC/IX", 0x80 => "Old MINIX", 0x81 => "MINIX / old Linux", 0x82 => "Linux swap / Solaris", 0x83 => "Linux", 0x84 => "OS/2 hidden C:", 0x85 => "Linux extended", 0x86 => "NTFS volume set", 0x87 => "NTFS volume set", 0x88 => "Linux plaintext", 0x8e => "Linux LVM", 0x93 => "Amoeba", 0x94 => "Amoeba BBT", 0x9f => "BSD/OS", 0xa0 => "IBM Thinkpad hibernation", 0xa5 => "FreeBSD", 0xa6 => "OpenBSD", 0xa7 => "NeXTSTEP", 0xa8 => "Darwin UFS", 0xa9 => "NetBSD", 0xab => "Darwin boot", 0xb7 => "BSDI fs", 0xb8 => "BSDI swap", 0xbb => "Boot Wizard hidden", 0xbe => "Solaris boot", 0xbf => "Solaris", 0xc1 => "DRDOS/sec (FAT-12)", 0xc4 => "DRDOS/sec (FAT-16 <32M)", 0xc6 => "DRDOS/sec (FAT-16)", 0xc7 => "Syrinx", 0xda => "Non-FS Data", 0xdb => "CP/M / CTOS", 0xde => "Dell Utility", 0xdf => "BootIt", 0xe1 => "DOS access", 0xe3 => "DOS R/O", 0xe4 => "SpeedStor", 0xeb => "BeOS fs", 0xee => "EFI GPT", 0xef => "EFI (FAT-12/16/32)", 0xf0 => "Linux/PA-RISC boot loader", 0xf1 => "SpeedStor", 0xf2 => "DOS secondary", 0xfb => "VMware File System", 0xfc => "VMware Swap", 0xfd => "Linux raid auto", 0xfe => "LANstep", 0xff => "BBT", } UNKNOWN_PARTITION_TYPE = "UNKNOWN".freeze def self.partition_type_name(partition_type) return PARTITION_TYPE_NAMES[partition_type] if PARTITION_TYPE_NAMES.key?(partition_type) UNKNOWN_PARTITION_TYPE end def partition_type_name self.class.partition_type_name(partition_type) end def self.alignment_boundary @boundary ||= (VMDB::Config.new("storage").config.fetch_path(:alignment, :boundary) || 32.kilobytes).to_i_with_method end def alignment_boundary # TODO: Base alignment on logical block size of storage self.class.alignment_boundary end def aligned? return nil if start_address.nil? # We check all of physical volumes of the VM. This Includes visible and hidden volumes, but excludes logical volumes. # The alignment of hidden volumes affects the performance of the logical volumes that are based on them. start_address % alignment_boundary == 0 end alias_method :aligned, :aligned? end
maas-ufcg/manageiq
app/models/partition.rb
Ruby
apache-2.0
4,525
/* * This file is part of dependency-check-core. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) 2014 Jeremy Long. All Rights Reserved. */ package org.owasp.dependencycheck.data.nuget; import javax.annotation.concurrent.ThreadSafe; /** * Exception during the parsing of a Nuspec file. * * @author colezlaw */ @ThreadSafe public class NuspecParseException extends Exception { /** * The serialVersionUID */ private static final long serialVersionUID = 1; /** * Constructs a new exception with <code>null</code> as its detail message. * * The cause is not initialized, and may subsequently be initialized by a * call to {@link java.lang.Throwable#initCause(java.lang.Throwable)}. */ public NuspecParseException() { super(); } /** * Constructs a new exception with the specified detail message. The cause * is not initialized, and may subsequently be initialized by a call to * {@link java.lang.Throwable#initCause(java.lang.Throwable)}. * * @param message the detail message. The detail message is saved for later * retrieval by the {@link java.lang.Throwable#getMessage()} method. */ public NuspecParseException(String message) { super(message); } /** * Constructs a new exception with the specified detail message and cause. * * Note that the detail message associated with <code>cause</code> is * <em>not</em> * automatically incorporated in this exception's detail message. * * @param message the detail message (which is saved for later retrieval by * the {@link java.lang.Throwable#getMessage()} method. * @param cause the cause (which is saved for later retrieval by the * {@link java.lang.Throwable#getCause()} method). (A <code>null</code> * value is permitted, and indicates that the cause is nonexistent or * unknown). */ public NuspecParseException(String message, Throwable cause) { super(message, cause); } }
Prakhash/security-tools
external/dependency-check-core-3.1.1/src/main/java/org/owasp/dependencycheck/data/nuget/NuspecParseException.java
Java
apache-2.0
2,565
/* * Copyright 2021 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.javascript.jscomp.AstFactory.type; import com.google.errorprone.annotations.CheckReturnValue; import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; /** Adds explicit constructors to classes that lack them. */ @CheckReturnValue final class SynthesizeExplicitConstructors { private final AbstractCompiler compiler; private final AstFactory astFactory; SynthesizeExplicitConstructors(AbstractCompiler compiler) { this.compiler = compiler; this.astFactory = compiler.createAstFactory(); } /** Add a synthetic constructor to the given class if no constructor is present */ void synthesizeClassConstructorIfMissing(NodeTraversal t, Node classNode) { checkArgument(classNode.isClass()); if (NodeUtil.getEs6ClassConstructorMemberFunctionDef(classNode) == null) { addSyntheticConstructor(t, classNode); } } private void addSyntheticConstructor(NodeTraversal t, Node classNode) { Node superClass = classNode.getSecondChild(); Node classMembers = classNode.getLastChild(); Node memberDef; if (superClass.isEmpty()) { Node function = astFactory.createEmptyFunction(type(classNode)); compiler.reportChangeToChangeScope(function); memberDef = astFactory.createMemberFunctionDef("constructor", function); } else { checkState( superClass.isQualifiedName(), "Expected Es6RewriteClassExtendsExpressions to make all extends clauses into qualified" + " names, found %s", superClass); Node body = IR.block(); // If a class is defined in an externs file or as an interface, it's only a stub, not an // implementation that should be instantiated. // A call to super() shouldn't actually exist for these cases and is problematic to // transpile, so don't generate it. if (!classNode.isFromExterns() && !isInterface(classNode)) { // Generate required call to super() // `super(...arguments);` // Note that transpilation of spread args must occur after this pass for this to work. Node exprResult = IR.exprResult( astFactory.createConstructorCall( type(classNode), // returned type is the subclass astFactory.createSuper(type(superClass)), IR.iterSpread(astFactory.createArgumentsReference()))); body.addChildToFront(exprResult); NodeUtil.addFeatureToScript(t.getCurrentScript(), Feature.SUPER, compiler); NodeUtil.addFeatureToScript(t.getCurrentScript(), Feature.SPREAD_EXPRESSIONS, compiler); } Node constructor = astFactory.createFunction("", IR.paramList(), body, type(classNode)); memberDef = astFactory.createMemberFunctionDef("constructor", constructor); } memberDef.srcrefTreeIfMissing(classNode); memberDef.makeNonIndexableRecursive(); classMembers.addChildToFront(memberDef); NodeUtil.addFeatureToScript(t.getCurrentScript(), Feature.MEMBER_DECLARATIONS, compiler); // report newly created constructor compiler.reportChangeToChangeScope(memberDef.getOnlyChild()); // report change to scope containing the class compiler.reportChangeToEnclosingScope(memberDef); } private boolean isInterface(Node classNode) { JSDocInfo classJsDocInfo = NodeUtil.getBestJSDocInfo(classNode); return classJsDocInfo != null && classJsDocInfo.isInterface(); } }
GoogleChromeLabs/chromeos_smart_card_connector
third_party/closure-compiler/src/src/com/google/javascript/jscomp/SynthesizeExplicitConstructors.java
Java
apache-2.0
4,359
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package discovery_test import ( "bytes" "encoding/json" "errors" "io" "io/ioutil" "net/http" "strings" "testing" "k8s.io/client-go/discovery" "k8s.io/client-go/pkg/api" "k8s.io/client-go/pkg/api/testapi" "k8s.io/client-go/pkg/apimachinery/registered" uapi "k8s.io/client-go/pkg/apis/meta/v1" "k8s.io/client-go/pkg/runtime" "k8s.io/client-go/pkg/runtime/schema" "k8s.io/client-go/rest" "k8s.io/client-go/rest/fake" ) func objBody(object interface{}) io.ReadCloser { output, err := json.MarshalIndent(object, "", "") if err != nil { panic(err) } return ioutil.NopCloser(bytes.NewReader([]byte(output))) } func TestNegotiateVersion(t *testing.T) { tests := []struct { name string requiredVersion *schema.GroupVersion expectedVersion *schema.GroupVersion serverVersions []string clientVersions []schema.GroupVersion expectErr func(err error) bool sendErr error statusCode int }{ { name: "server supports client default", serverVersions: []string{"version1", registered.GroupOrDie(api.GroupName).GroupVersion.String()}, clientVersions: []schema.GroupVersion{{Version: "version1"}, registered.GroupOrDie(api.GroupName).GroupVersion}, expectedVersion: &schema.GroupVersion{Version: "version1"}, statusCode: http.StatusOK, }, { name: "server falls back to client supported", serverVersions: []string{"version1"}, clientVersions: []schema.GroupVersion{{Version: "version1"}, registered.GroupOrDie(api.GroupName).GroupVersion}, expectedVersion: &schema.GroupVersion{Version: "version1"}, statusCode: http.StatusOK, }, { name: "explicit version supported", requiredVersion: &schema.GroupVersion{Version: "v1"}, serverVersions: []string{"/version1", registered.GroupOrDie(api.GroupName).GroupVersion.String()}, clientVersions: []schema.GroupVersion{{Version: "version1"}, registered.GroupOrDie(api.GroupName).GroupVersion}, expectedVersion: &schema.GroupVersion{Version: "v1"}, statusCode: http.StatusOK, }, { name: "explicit version not supported on server", requiredVersion: &schema.GroupVersion{Version: "v1"}, serverVersions: []string{"version1"}, clientVersions: []schema.GroupVersion{{Version: "version1"}, registered.GroupOrDie(api.GroupName).GroupVersion}, expectErr: func(err error) bool { return strings.Contains(err.Error(), `server does not support API version "v1"`) }, statusCode: http.StatusOK, }, { name: "explicit version not supported on client", requiredVersion: &schema.GroupVersion{Version: "v1"}, serverVersions: []string{"v1"}, clientVersions: []schema.GroupVersion{{Version: "version1"}}, expectErr: func(err error) bool { return strings.Contains(err.Error(), `client does not support API version "v1"`) }, statusCode: http.StatusOK, }, { name: "connection refused error", serverVersions: []string{"version1"}, clientVersions: []schema.GroupVersion{{Version: "version1"}, registered.GroupOrDie(api.GroupName).GroupVersion}, sendErr: errors.New("connection refused"), expectErr: func(err error) bool { return strings.Contains(err.Error(), "connection refused") }, statusCode: http.StatusOK, }, { name: "discovery fails due to 403 Forbidden errors and thus serverVersions is empty, use default GroupVersion", clientVersions: []schema.GroupVersion{{Version: "version1"}, registered.GroupOrDie(api.GroupName).GroupVersion}, expectedVersion: &schema.GroupVersion{Version: "version1"}, statusCode: http.StatusForbidden, }, { name: "discovery fails due to 404 Not Found errors and thus serverVersions is empty, use requested GroupVersion", requiredVersion: &schema.GroupVersion{Version: "version1"}, clientVersions: []schema.GroupVersion{{Version: "version1"}, registered.GroupOrDie(api.GroupName).GroupVersion}, expectedVersion: &schema.GroupVersion{Version: "version1"}, statusCode: http.StatusNotFound, }, { name: "discovery fails due to 403 Forbidden errors and thus serverVersions is empty, no fallback GroupVersion", expectErr: func(err error) bool { return strings.Contains(err.Error(), "failed to negotiate an api version;") }, statusCode: http.StatusForbidden, }, } for _, test := range tests { fakeClient := &fake.RESTClient{ NegotiatedSerializer: testapi.Default.NegotiatedSerializer(), Resp: &http.Response{ StatusCode: test.statusCode, Body: objBody(&uapi.APIVersions{Versions: test.serverVersions}), }, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { if test.sendErr != nil { return nil, test.sendErr } header := http.Header{} header.Set("Content-Type", runtime.ContentTypeJSON) return &http.Response{StatusCode: test.statusCode, Header: header, Body: objBody(&uapi.APIVersions{Versions: test.serverVersions})}, nil }), } c := discovery.NewDiscoveryClientForConfigOrDie(&rest.Config{}) c.RESTClient().(*rest.RESTClient).Client = fakeClient.Client response, err := discovery.NegotiateVersion(c, test.requiredVersion, test.clientVersions) if err == nil && test.expectErr != nil { t.Errorf("expected error, got nil for [%s].", test.name) } if err != nil { if test.expectErr == nil || !test.expectErr(err) { t.Errorf("unexpected error for [%s]: %v.", test.name, err) } continue } if *response != *test.expectedVersion { t.Errorf("%s: expected version %s, got %s.", test.name, test.expectedVersion, response) } } }
mogthesprog/kubernetes
staging/src/k8s.io/client-go/discovery/helper_blackbox_test.go
GO
apache-2.0
6,251
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.io.network.util; import org.apache.flink.runtime.event.AbstractEvent; import org.apache.flink.runtime.io.network.api.EndOfPartitionEvent; import org.apache.flink.runtime.io.network.api.serialization.EventSerializer; import org.apache.flink.runtime.io.network.partition.BufferAvailabilityListener; import org.apache.flink.runtime.io.network.partition.ResultSubpartition.BufferAndBacklog; import org.apache.flink.runtime.io.network.partition.ResultSubpartitionView; import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.flink.util.Preconditions.checkNotNull; /** * A test subpartition viewQueue consumer. * * <p> The behaviour of the consumer is customizable by specifying a callback. * * @see TestConsumerCallback */ @Deprecated public class TestSubpartitionConsumer implements Callable<Boolean>, BufferAvailabilityListener { private static final int MAX_SLEEP_TIME_MS = 20; /** The subpartition viewQueue to consume. */ private volatile ResultSubpartitionView subpartitionView; private BlockingQueue<ResultSubpartitionView> viewQueue = new ArrayBlockingQueue<>(1); /** * Flag indicating whether the consumer is slow. If true, the consumer will sleep a random * number of milliseconds between returned buffers. */ private final boolean isSlowConsumer; /** The callback to handle a notifyNonEmpty buffer. */ private final TestConsumerCallback callback; /** Random source for sleeps. */ private final Random random; private final AtomicBoolean dataAvailableNotification = new AtomicBoolean(false); public TestSubpartitionConsumer( boolean isSlowConsumer, TestConsumerCallback callback) { this.isSlowConsumer = isSlowConsumer; this.random = isSlowConsumer ? new Random() : null; this.callback = checkNotNull(callback); } public void setSubpartitionView(ResultSubpartitionView subpartitionView) { this.subpartitionView = checkNotNull(subpartitionView); } @Override public Boolean call() throws Exception { try { while (true) { if (Thread.interrupted()) { throw new InterruptedException(); } synchronized (dataAvailableNotification) { while (!dataAvailableNotification.getAndSet(false)) { dataAvailableNotification.wait(); } } final BufferAndBacklog bufferAndBacklog = subpartitionView.getNextBuffer(); if (isSlowConsumer) { Thread.sleep(random.nextInt(MAX_SLEEP_TIME_MS + 1)); } if (bufferAndBacklog != null) { if (bufferAndBacklog.isMoreAvailable()) { dataAvailableNotification.set(true); } if (bufferAndBacklog.buffer().isBuffer()) { callback.onBuffer(bufferAndBacklog.buffer()); } else { final AbstractEvent event = EventSerializer.fromBuffer(bufferAndBacklog.buffer(), getClass().getClassLoader()); callback.onEvent(event); bufferAndBacklog.buffer().recycleBuffer(); if (event.getClass() == EndOfPartitionEvent.class) { subpartitionView.notifySubpartitionConsumed(); return true; } } } else if (subpartitionView.isReleased()) { return true; } } } finally { subpartitionView.releaseAllResources(); } } @Override public void notifyDataAvailable() { synchronized (dataAvailableNotification) { dataAvailableNotification.set(true); dataAvailableNotification.notifyAll(); } } }
ueshin/apache-flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/util/TestSubpartitionConsumer.java
Java
apache-2.0
4,339
#!/bin/bash LC_ALL=C export PYTHONIOENCODING=utf8 python3 parse.py python3 redirect.py LC_ALL=C sort -u -t$'\t' -k1,1 output2.txt -o output.txt cat output.txt | ./output_statistics.awk
rasikapohankar/zeroclickinfo-fathead
lib/fathead/react_native/parse.sh
Shell
apache-2.0
189
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.example.cxf.jaxrs.resources; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @WebService @Path("/bookstore") @Consumes("application/xml") @Produces("application/xml") public interface BookStore { @WebMethod @GET @Path("/{id}") @Consumes("*/*") Book getBook(@PathParam("id") @WebParam(name = "id") Long id) throws BookNotFoundFault; @WebMethod @POST @Path("/books") Book addBook(@WebParam(name = "book") Book book); }
objectiser/camel
examples/camel-example-cxf/src/main/java/org/apache/camel/example/cxf/jaxrs/resources/BookStore.java
Java
apache-2.0
1,492
/****************************************************************************** * Copyright (c) 2006, 2010 VMware Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0 * is available at http://www.opensource.org/licenses/apache2.0.php. * You may elect to redistribute this code under either of these licenses. * * Contributors: * VMware Inc. *****************************************************************************/ package org.eclipse.gemini.blueprint.iandt.error; import org.eclipse.gemini.blueprint.iandt.simpleservice.MyService; public class TestService implements MyService { public String stringValue() { return "Bond. James Bond."; } }
glyn/Gemini-Blueprint
integration-tests/bundles/error.bundle/src/main/java/org/springframework/osgi/iandt/error/TestService.java
Java
apache-2.0
971
/** * Copyright (c) 2014-2015, Data Geekery GmbH, contact@datageekery.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jooq.lambda.fi.util.function; import java.util.function.ObjIntConsumer; /** * A {@link ObjIntConsumer} that allows for checked exceptions. * * @author Lukas Eder */ @FunctionalInterface public interface CheckedObjIntConsumer<T> { /** * Performs this operation on the given arguments. * * @param t the first input argument * @param value the second input argument */ void accept(T t, int value) throws Throwable; }
webfd/jOOL
src/main/java/org/jooq/lambda/fi/util/function/CheckedObjIntConsumer.java
Java
apache-2.0
1,105
// Copyright 2005 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: ericv@google.com (Eric Veach) #ifndef S2_S2REGION_COVERER_H_ #define S2_S2REGION_COVERER_H_ #include <queue> #include <utility> #include <vector> #include "s2/third_party/absl/base/macros.h" #include "s2/_fp_contract_off.h" #include "s2/s2cell.h" #include "s2/s2cell_id.h" #include "s2/s2cell_union.h" #ifdef _WIN32 #pragma warning(disable : 4200) #endif class S2Region; // An S2RegionCoverer is a class that allows arbitrary regions to be // approximated as unions of cells (S2CellUnion). This is useful for // implementing various sorts of search and precomputation operations. // // Typical usage: // // S2RegionCoverer::Options options; // options.set_max_cells(5); // S2RegionCoverer coverer(options); // S2Cap cap(center, radius); // S2CellUnion covering = coverer.GetCovering(cap); // // This yields a vector of at most 5 cells that is guaranteed to cover the // given cap (a disc-shaped region on the sphere). // // The approximation algorithm is not optimal but does a pretty good job in // practice. The output does not always use the maximum number of cells // allowed, both because this would not always yield a better approximation, // and because max_cells() is a limit on how much work is done exploring the // possible covering as well as a limit on the final output size. // // Because it is an approximation algorithm, one should not rely on the // stability of the output. In particular, the output of the covering algorithm // may change across different versions of the library. // // One can also generate interior coverings, which are sets of cells which // are entirely contained within a region. Interior coverings can be // empty, even for non-empty regions, if there are no cells that satisfy // the provided constraints and are contained by the region. Note that for // performance reasons, it is wise to specify a max_level when computing // interior coverings - otherwise for regions with small or zero area, the // algorithm may spend a lot of time subdividing cells all the way to leaf // level to try to find contained cells. class S2RegionCoverer { public: #ifndef SWIG class Options { public: // Sets the desired maximum number of cells in the approximation. Note // the following: // // - For any setting of max_cells(), up to 6 cells may be returned if // that is the minimum number required (e.g. if the region intersects // all six cube faces). Even for very tiny regions, up to 3 cells may // be returned if they happen to be located at the intersection of // three cube faces. // // - min_level() takes priority over max_cells(), i.e. cells below the // given level will never be used even if this causes a large number of // cells to be returned. // // - If max_cells() is less than 4, the area of the covering may be // arbitrarily large compared to the area of the original region even // if the region is convex (e.g. an S2Cap or S2LatLngRect). // // Accuracy is measured by dividing the area of the covering by the area // of the original region. The following table shows the median and worst // case values for this area ratio on a test case consisting of 100,000 // spherical caps of random size (generated using s2region_coverer_test): // // max_cells: 3 4 5 6 8 12 20 100 1000 // median ratio: 5.33 3.32 2.73 2.34 1.98 1.66 1.42 1.11 1.01 // worst case: 215518 14.41 9.72 5.26 3.91 2.75 1.92 1.20 1.02 // // The default value of 8 gives a reasonable tradeoff between the number // of cells used and the accuracy of the approximation. // // DEFAULT: kDefaultMaxCells static constexpr int kDefaultMaxCells = 8; int max_cells() const { return max_cells_; } void set_max_cells(int max_cells); // Sets the minimum and maximum cell levels to be used. The default is to // use all cell levels. // // To find the cell level corresponding to a given physical distance, use // the S2Cell metrics defined in s2metrics.h. For example, to find the // cell level that corresponds to an average edge length of 10km, use: // // int level = // S2::kAvgEdge.GetClosestLevel(S2Earth::KmToRadians(length_km)); // // Note that min_level() takes priority over max_cells(), i.e. cells below // the given level will never be used even if this causes a large number // of cells to be returned. (This doesn't apply to interior coverings, // since interior coverings make no completeness guarantees -- the result // is simply a set of cells that covers as much of the interior as // possible while satisfying the given restrictions.) // // REQUIRES: min_level() <= max_level() // DEFAULT: 0 int min_level() const { return min_level_; } void set_min_level(int min_level); // REQUIRES: min_level() <= max_level() // DEFAULT: S2CellId::kMaxLevel int max_level() const { return max_level_; } void set_max_level(int max_level); // Convenience function that sets both the maximum and minimum cell levels. void set_fixed_level(int level); // If specified, then only cells where (level - min_level) is a multiple // of "level_mod" will be used (default 1). This effectively allows the // branching factor of the S2CellId hierarchy to be increased. Currently // the only parameter values allowed are 1, 2, or 3, corresponding to // branching factors of 4, 16, and 64 respectively. // // DEFAULT: 1 int level_mod() const { return level_mod_; } void set_level_mod(int level_mod); // Convenience function that returns the maximum level such that // // (level <= max_level()) && (level - min_level()) % level_mod() == 0. // // This is the maximum level that will actually be used in coverings. int true_max_level() const; protected: int max_cells_ = kDefaultMaxCells; int min_level_ = 0; int max_level_ = S2CellId::kMaxLevel; int level_mod_ = 1; }; // Constructs an S2RegionCoverer with the given options. explicit S2RegionCoverer(const Options& options); // S2RegionCoverer is movable but not copyable. S2RegionCoverer(const S2RegionCoverer&) = delete; S2RegionCoverer& operator=(const S2RegionCoverer&) = delete; S2RegionCoverer(S2RegionCoverer&&); S2RegionCoverer& operator=(S2RegionCoverer&&); #endif // SWIG // Default constructor. Options can be set using mutable_options(). S2RegionCoverer(); ~S2RegionCoverer(); // Returns the current options. Options can be modifed between calls. const Options& options() const { return options_; } Options* mutable_options() { return &options_; } // Returns an S2CellUnion that covers (GetCovering) or is contained within // (GetInteriorCovering) the given region and satisfies the current options. // // Note that if options().min_level() > 0 or options().level_mod() > 1, the // by definition the S2CellUnion may not be normalized, i.e. there may be // groups of four child cells that can be replaced by their parent cell. S2CellUnion GetCovering(const S2Region& region); S2CellUnion GetInteriorCovering(const S2Region& region); // Like the methods above, but works directly with a vector of S2CellIds. // This version can be more efficient when this method is called many times, // since it does not require allocating a new vector on each call. void GetCovering(const S2Region& region, std::vector<S2CellId>* covering); void GetInteriorCovering(const S2Region& region, std::vector<S2CellId>* interior); // Like GetCovering(), except that this method is much faster and the // coverings are not as tight. All of the usual parameters are respected // (max_cells, min_level, max_level, and level_mod), except that the // implementation makes no attempt to take advantage of large values of // max_cells(). (A small number of cells will always be returned.) // // This function is useful as a starting point for algorithms that // recursively subdivide cells. void GetFastCovering(const S2Region& region, std::vector<S2CellId>* covering); // Given a connected region and a starting point on the boundary or inside the // region, returns a set of cells at the given level that cover the region. // The output cells are returned in arbitrary order. // // Note that this method is *not* faster than the regular GetCovering() // method for most region types, such as S2Cap or S2Polygon, and in fact it // can be much slower when the output consists of a large number of cells. // Currently it can be faster at generating coverings of long narrow regions // such as polylines, but this may change in the future, in which case this // method will most likely be removed. static void GetSimpleCovering(const S2Region& region, const S2Point& start, int level, std::vector<S2CellId>* output); // Like GetSimpleCovering(), but accepts a starting S2CellId rather than a // starting point and cell level. Returns all edge-connected cells at the // same level as "start" that intersect "region", in arbitrary order. static void FloodFill(const S2Region& region, S2CellId start, std::vector<S2CellId>* output); // Returns true if the given S2CellId vector represents a valid covering // that conforms to the current covering parameters. In particular: // // - All S2CellIds must be valid. // // - S2CellIds must be sorted and non-overlapping. // // - S2CellId levels must satisfy min_level(), max_level(), and level_mod(). // // - If covering.size() > max_cells(), there must be no two cells with // a common ancestor at min_level() or higher. // // - There must be no sequence of cells that could be replaced by an // ancestor (i.e. with level_mod() == 1, the 4 child cells of a parent). bool IsCanonical(const S2CellUnion& covering) const; bool IsCanonical(const std::vector<S2CellId>& covering) const; // Modify "covering" if necessary so that it conforms to the current // covering parameters (max_cells, min_level, max_level, and level_mod). // There are no restrictions on the input S2CellIds (they may be unsorted, // overlapping, etc). S2CellUnion CanonicalizeCovering(const S2CellUnion& covering); void CanonicalizeCovering(std::vector<S2CellId>* covering); private: struct Candidate { S2Cell cell; bool is_terminal; // Cell should not be expanded further. int num_children; // Number of children that intersect the region. Candidate* children[0]; // Actual size may be 0, 4, 16, or 64 elements. }; // If the cell intersects the given region, return a new candidate with no // children, otherwise return nullptr. Also marks the candidate as "terminal" // if it should not be expanded further. Candidate* NewCandidate(const S2Cell& cell); // Returns the log base 2 of the maximum number of children of a candidate. int max_children_shift() const { return 2 * options().level_mod(); } // Frees the memory associated with a candidate. static void DeleteCandidate(Candidate* candidate, bool delete_children); // Processes a candidate by either adding it to the result_ vector or // expanding its children and inserting it into the priority queue. // Passing an argument of nullptr does nothing. void AddCandidate(Candidate* candidate); // Populates the children of "candidate" by expanding the given number of // levels from the given cell. Returns the number of children that were // marked "terminal". int ExpandChildren(Candidate* candidate, const S2Cell& cell, int num_levels); // Computes a set of initial candidates that cover the given region. void GetInitialCandidates(); // Generates a covering and stores it in result_. void GetCoveringInternal(const S2Region& region); // If level > min_level(), then reduces "level" if necessary so that it also // satisfies level_mod(). Levels smaller than min_level() are not affected // (since cells at these levels are eventually expanded). int AdjustLevel(int level) const; // Ensures that all cells with level > min_level() also satisfy level_mod(), // by replacing them with an ancestor if necessary. Cell levels smaller // than min_level() are not modified (see AdjustLevel). The output is // then normalized to ensure that no redundant cells are present. void AdjustCellLevels(std::vector<S2CellId>* cells) const; // Returns true if "covering" contains all children of "id" at level // (id.level() + options_.level_mod()). bool ContainsAllChildren(const std::vector<S2CellId>& covering, S2CellId id) const; // Replaces all descendants of "id" in "covering" with "id". // REQUIRES: "covering" contains at least one descendant of "id". void ReplaceCellsWithAncestor(std::vector<S2CellId>* covering, S2CellId id) const; Options options_; // We save a temporary copy of the pointer passed to GetCovering() in order // to avoid passing this parameter around internally. It is only used (and // only valid) for the duration of a single GetCovering() call. const S2Region* region_ = nullptr; // The set of S2CellIds that have been added to the covering so far. std::vector<S2CellId> result_; // We keep the candidates in a priority queue. We specify a vector to hold // the queue entries since for some reason priority_queue<> uses a deque by // default. We define our own own comparison function on QueueEntries in // order to make the results deterministic. (Using the default // less<QueueEntry>, entries of equal priority would be sorted according to // the memory address of the candidate.) typedef std::pair<int, Candidate*> QueueEntry; struct CompareQueueEntries { bool operator()(const QueueEntry& x, const QueueEntry& y) const { return x.first < y.first; } }; typedef std::priority_queue<QueueEntry, std::vector<QueueEntry>, CompareQueueEntries> CandidateQueue; CandidateQueue pq_; // True if we're computing an interior covering. bool interior_covering_; // Counter of number of candidates created, for performance evaluation. int candidates_created_counter_; }; #endif // S2_S2REGION_COVERER_H_
wiltonlazary/arangodb
3rdParty/s2geometry/dfefe0c/src/s2/s2region_coverer.h
C
apache-2.0
15,112
@import url("//fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700"); /*! * Bootstrap v3.0.0 * * Copyright 2013 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world by @mdo and @fat. */ /*! normalize.css v2.1.0 | MIT License | git.io/normalize */ article, aside, details, figcaption, figure, footer, header, hgroup, main, nav, section, summary { display: block; } audio, canvas, video { display: inline-block; } audio:not([controls]) { display: none; height: 0; } [hidden] { display: none; } html { font-family: sans-serif; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } body { margin: 0; } a:focus { outline: thin dotted; } a:active, a:hover { outline: 0; } h1 { margin: 0.67em 0; font-size: 2em; } abbr[title] { border-bottom: 1px dotted; } b, strong { font-weight: bold; } dfn { font-style: italic; } hr { height: 0; -moz-box-sizing: content-box; box-sizing: content-box; } mark { color: #000; background: #ff0; } code, kbd, pre, samp { font-family: monospace, serif; font-size: 1em; } pre { white-space: pre-wrap; } q { quotes: "\201C" "\201D" "\2018" "\2019"; } small { font-size: 80%; } sub, sup { position: relative; font-size: 75%; line-height: 0; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } img { border: 0; } svg:not(:root) { overflow: hidden; } figure { margin: 0; } fieldset { padding: 0.35em 0.625em 0.75em; margin: 0 2px; border: 1px solid #c0c0c0; } legend { padding: 0; border: 0; } button, input, select, textarea { margin: 0; font-family: inherit; font-size: 100%; } button, input { line-height: normal; } button, select { text-transform: none; } button, html input[type="button"], input[type="reset"], input[type="submit"] { cursor: pointer; -webkit-appearance: button; } button[disabled], html input[disabled] { cursor: default; } input[type="checkbox"], input[type="radio"] { padding: 0; box-sizing: border-box; } input[type="search"] { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; -webkit-appearance: textfield; } input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } button::-moz-focus-inner, input::-moz-focus-inner { padding: 0; border: 0; } textarea { overflow: auto; vertical-align: top; } table { border-collapse: collapse; border-spacing: 0; } @media print { * { color: #000 !important; text-shadow: none !important; background: transparent !important; box-shadow: none !important; } a, a:visited { text-decoration: underline; } a[href]:after { content: " (" attr(href) ")"; } abbr[title]:after { content: " (" attr(title) ")"; } .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; } pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } tr, img { page-break-inside: avoid; } img { max-width: 100% !important; } @page { margin: 2cm .5cm; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } .navbar { display: none; } .table td, .table th { background-color: #fff !important; } .btn > .caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { border: 1px solid #000; } .table { border-collapse: collapse !important; } .table-bordered th, .table-bordered td { border: 1px solid #ddd !important; } } *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } html { font-size: 62.5%; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } body { font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.428571429; color: #666666; background-color: #ffffff; } input, button, select, textarea { font-family: inherit; font-size: inherit; line-height: inherit; } button, input, select[multiple], textarea { background-image: none; } a { color: #3399f3; text-decoration: none; } a:hover, a:focus { color: #3399f3; text-decoration: underline; } a:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } img { vertical-align: middle; } .img-responsive { display: block; height: auto; max-width: 100%; } .img-rounded { border-radius: 6px; } .img-thumbnail { display: inline-block; height: auto; max-width: 100%; padding: 4px; line-height: 1.428571429; background-color: #ffffff; border: 1px solid #dddddd; border-radius: 4px; -webkit-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .img-circle { border-radius: 50%; } hr { margin-top: 20px; margin-bottom: 20px; border: 0; border-top: 1px solid #eeeeee; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); border: 0; } p { margin: 0 0 10px; } .lead { margin-bottom: 20px; font-size: 16.099999999999998px; font-weight: 200; line-height: 1.4; } @media (min-width: 768px) { .lead { font-size: 21px; } } small { font-size: 85%; } cite { font-style: normal; } .text-muted { color: #999999; } .text-primary { color: #446e9b; } .text-warning { color: #c09853; } .text-danger { color: #b94a48; } .text-success { color: #468847; } .text-info { color: #3a87ad; } .text-left { text-align: left; } .text-right { text-align: right; } .text-center { text-align: center; } h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 { font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 500; line-height: 1.1; } h1 small, h2 small, h3 small, h4 small, h5 small, h6 small, .h1 small, .h2 small, .h3 small, .h4 small, .h5 small, .h6 small { font-weight: normal; line-height: 1; color: #999999; } h1, h2, h3 { margin-top: 20px; margin-bottom: 10px; } h4, h5, h6 { margin-top: 10px; margin-bottom: 10px; } h1, .h1 { font-size: 36px; } h2, .h2 { font-size: 30px; } h3, .h3 { font-size: 24px; } h4, .h4 { font-size: 18px; } h5, .h5 { font-size: 14px; } h6, .h6 { font-size: 12px; } h1 small, .h1 small { font-size: 24px; } h2 small, .h2 small { font-size: 18px; } h3 small, .h3 small, h4 small, .h4 small { font-size: 14px; } .page-header { padding-bottom: 9px; margin: 40px 0 20px; border-bottom: 1px solid #eeeeee; } ul, ol { margin-top: 0; margin-bottom: 10px; } ul ul, ol ul, ul ol, ol ol { margin-bottom: 0; } .list-unstyled { padding-left: 0; list-style: none; } .list-inline { padding-left: 0; list-style: none; } .list-inline > li { display: inline-block; padding-right: 5px; padding-left: 5px; } dl { margin-bottom: 20px; } dt, dd { line-height: 1.428571429; } dt { font-weight: bold; } dd { margin-left: 0; } @media (min-width: 768px) { .dl-horizontal dt { float: left; width: 160px; overflow: hidden; clear: left; text-align: right; text-overflow: ellipsis; white-space: nowrap; } .dl-horizontal dd { margin-left: 180px; } .dl-horizontal dd:before, .dl-horizontal dd:after { display: table; content: " "; } .dl-horizontal dd:after { clear: both; } .dl-horizontal dd:before, .dl-horizontal dd:after { display: table; content: " "; } .dl-horizontal dd:after { clear: both; } .dl-horizontal dd:before, .dl-horizontal dd:after { display: table; content: " "; } .dl-horizontal dd:after { clear: both; } .dl-horizontal dd:before, .dl-horizontal dd:after { display: table; content: " "; } .dl-horizontal dd:after { clear: both; } .dl-horizontal dd:before, .dl-horizontal dd:after { display: table; content: " "; } .dl-horizontal dd:after { clear: both; } } abbr[title], abbr[data-original-title] { cursor: help; border-bottom: 1px dotted #999999; } abbr.initialism { font-size: 90%; text-transform: uppercase; } blockquote { padding: 10px 20px; margin: 0 0 20px; border-left: 5px solid #eeeeee; } blockquote p { font-size: 17.5px; font-weight: 300; line-height: 1.25; } blockquote p:last-child { margin-bottom: 0; } blockquote small { display: block; line-height: 1.428571429; color: #999999; } blockquote small:before { content: '\2014 \00A0'; } blockquote.pull-right { padding-right: 15px; padding-left: 0; border-right: 5px solid #eeeeee; border-left: 0; } blockquote.pull-right p, blockquote.pull-right small { text-align: right; } blockquote.pull-right small:before { content: ''; } blockquote.pull-right small:after { content: '\00A0 \2014'; } q:before, q:after, blockquote:before, blockquote:after { content: ""; } address { display: block; margin-bottom: 20px; font-style: normal; line-height: 1.428571429; } code, pre { font-family: Monaco, Menlo, Consolas, "Courier New", monospace; } code { padding: 2px 4px; font-size: 90%; color: #c7254e; white-space: nowrap; background-color: #f9f2f4; border-radius: 4px; } pre { display: block; padding: 9.5px; margin: 0 0 10px; font-size: 13px; line-height: 1.428571429; color: #333333; word-break: break-all; word-wrap: break-word; background-color: #f5f5f5; border: 1px solid #cccccc; border-radius: 4px; } pre.prettyprint { margin-bottom: 20px; } pre code { padding: 0; font-size: inherit; color: inherit; white-space: pre-wrap; background-color: transparent; border: 0; } .pre-scrollable { max-height: 340px; overflow-y: scroll; } .container { padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } .container:before, .container:after { display: table; content: " "; } .container:after { clear: both; } .container:before, .container:after { display: table; content: " "; } .container:after { clear: both; } .container:before, .container:after { display: table; content: " "; } .container:after { clear: both; } .container:before, .container:after { display: table; content: " "; } .container:after { clear: both; } .container:before, .container:after { display: table; content: " "; } .container:after { clear: both; } .row { margin-right: -15px; margin-left: -15px; } .row:before, .row:after { display: table; content: " "; } .row:after { clear: both; } .row:before, .row:after { display: table; content: " "; } .row:after { clear: both; } .row:before, .row:after { display: table; content: " "; } .row:after { clear: both; } .row:before, .row:after { display: table; content: " "; } .row:after { clear: both; } .row:before, .row:after { display: table; content: " "; } .row:after { clear: both; } .col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 { position: relative; min-height: 1px; padding-right: 15px; padding-left: 15px; } .col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11 { float: left; } .col-xs-1 { width: 8.333333333333332%; } .col-xs-2 { width: 16.666666666666664%; } .col-xs-3 { width: 25%; } .col-xs-4 { width: 33.33333333333333%; } .col-xs-5 { width: 41.66666666666667%; } .col-xs-6 { width: 50%; } .col-xs-7 { width: 58.333333333333336%; } .col-xs-8 { width: 66.66666666666666%; } .col-xs-9 { width: 75%; } .col-xs-10 { width: 83.33333333333334%; } .col-xs-11 { width: 91.66666666666666%; } .col-xs-12 { width: 100%; } @media (min-width: 768px) { .container { max-width: 750px; } .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11 { float: left; } .col-sm-1 { width: 8.333333333333332%; } .col-sm-2 { width: 16.666666666666664%; } .col-sm-3 { width: 25%; } .col-sm-4 { width: 33.33333333333333%; } .col-sm-5 { width: 41.66666666666667%; } .col-sm-6 { width: 50%; } .col-sm-7 { width: 58.333333333333336%; } .col-sm-8 { width: 66.66666666666666%; } .col-sm-9 { width: 75%; } .col-sm-10 { width: 83.33333333333334%; } .col-sm-11 { width: 91.66666666666666%; } .col-sm-12 { width: 100%; } .col-sm-push-1 { left: 8.333333333333332%; } .col-sm-push-2 { left: 16.666666666666664%; } .col-sm-push-3 { left: 25%; } .col-sm-push-4 { left: 33.33333333333333%; } .col-sm-push-5 { left: 41.66666666666667%; } .col-sm-push-6 { left: 50%; } .col-sm-push-7 { left: 58.333333333333336%; } .col-sm-push-8 { left: 66.66666666666666%; } .col-sm-push-9 { left: 75%; } .col-sm-push-10 { left: 83.33333333333334%; } .col-sm-push-11 { left: 91.66666666666666%; } .col-sm-pull-1 { right: 8.333333333333332%; } .col-sm-pull-2 { right: 16.666666666666664%; } .col-sm-pull-3 { right: 25%; } .col-sm-pull-4 { right: 33.33333333333333%; } .col-sm-pull-5 { right: 41.66666666666667%; } .col-sm-pull-6 { right: 50%; } .col-sm-pull-7 { right: 58.333333333333336%; } .col-sm-pull-8 { right: 66.66666666666666%; } .col-sm-pull-9 { right: 75%; } .col-sm-pull-10 { right: 83.33333333333334%; } .col-sm-pull-11 { right: 91.66666666666666%; } .col-sm-offset-1 { margin-left: 8.333333333333332%; } .col-sm-offset-2 { margin-left: 16.666666666666664%; } .col-sm-offset-3 { margin-left: 25%; } .col-sm-offset-4 { margin-left: 33.33333333333333%; } .col-sm-offset-5 { margin-left: 41.66666666666667%; } .col-sm-offset-6 { margin-left: 50%; } .col-sm-offset-7 { margin-left: 58.333333333333336%; } .col-sm-offset-8 { margin-left: 66.66666666666666%; } .col-sm-offset-9 { margin-left: 75%; } .col-sm-offset-10 { margin-left: 83.33333333333334%; } .col-sm-offset-11 { margin-left: 91.66666666666666%; } } @media (min-width: 992px) { .container { max-width: 970px; } .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11 { float: left; } .col-md-1 { width: 8.333333333333332%; } .col-md-2 { width: 16.666666666666664%; } .col-md-3 { width: 25%; } .col-md-4 { width: 33.33333333333333%; } .col-md-5 { width: 41.66666666666667%; } .col-md-6 { width: 50%; } .col-md-7 { width: 58.333333333333336%; } .col-md-8 { width: 66.66666666666666%; } .col-md-9 { width: 75%; } .col-md-10 { width: 83.33333333333334%; } .col-md-11 { width: 91.66666666666666%; } .col-md-12 { width: 100%; } .col-md-push-0 { left: auto; } .col-md-push-1 { left: 8.333333333333332%; } .col-md-push-2 { left: 16.666666666666664%; } .col-md-push-3 { left: 25%; } .col-md-push-4 { left: 33.33333333333333%; } .col-md-push-5 { left: 41.66666666666667%; } .col-md-push-6 { left: 50%; } .col-md-push-7 { left: 58.333333333333336%; } .col-md-push-8 { left: 66.66666666666666%; } .col-md-push-9 { left: 75%; } .col-md-push-10 { left: 83.33333333333334%; } .col-md-push-11 { left: 91.66666666666666%; } .col-md-pull-0 { right: auto; } .col-md-pull-1 { right: 8.333333333333332%; } .col-md-pull-2 { right: 16.666666666666664%; } .col-md-pull-3 { right: 25%; } .col-md-pull-4 { right: 33.33333333333333%; } .col-md-pull-5 { right: 41.66666666666667%; } .col-md-pull-6 { right: 50%; } .col-md-pull-7 { right: 58.333333333333336%; } .col-md-pull-8 { right: 66.66666666666666%; } .col-md-pull-9 { right: 75%; } .col-md-pull-10 { right: 83.33333333333334%; } .col-md-pull-11 { right: 91.66666666666666%; } .col-md-offset-0 { margin-left: 0; } .col-md-offset-1 { margin-left: 8.333333333333332%; } .col-md-offset-2 { margin-left: 16.666666666666664%; } .col-md-offset-3 { margin-left: 25%; } .col-md-offset-4 { margin-left: 33.33333333333333%; } .col-md-offset-5 { margin-left: 41.66666666666667%; } .col-md-offset-6 { margin-left: 50%; } .col-md-offset-7 { margin-left: 58.333333333333336%; } .col-md-offset-8 { margin-left: 66.66666666666666%; } .col-md-offset-9 { margin-left: 75%; } .col-md-offset-10 { margin-left: 83.33333333333334%; } .col-md-offset-11 { margin-left: 91.66666666666666%; } } @media (min-width: 1200px) { .container { max-width: 1170px; } .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11 { float: left; } .col-lg-1 { width: 8.333333333333332%; } .col-lg-2 { width: 16.666666666666664%; } .col-lg-3 { width: 25%; } .col-lg-4 { width: 33.33333333333333%; } .col-lg-5 { width: 41.66666666666667%; } .col-lg-6 { width: 50%; } .col-lg-7 { width: 58.333333333333336%; } .col-lg-8 { width: 66.66666666666666%; } .col-lg-9 { width: 75%; } .col-lg-10 { width: 83.33333333333334%; } .col-lg-11 { width: 91.66666666666666%; } .col-lg-12 { width: 100%; } .col-lg-push-0 { left: auto; } .col-lg-push-1 { left: 8.333333333333332%; } .col-lg-push-2 { left: 16.666666666666664%; } .col-lg-push-3 { left: 25%; } .col-lg-push-4 { left: 33.33333333333333%; } .col-lg-push-5 { left: 41.66666666666667%; } .col-lg-push-6 { left: 50%; } .col-lg-push-7 { left: 58.333333333333336%; } .col-lg-push-8 { left: 66.66666666666666%; } .col-lg-push-9 { left: 75%; } .col-lg-push-10 { left: 83.33333333333334%; } .col-lg-push-11 { left: 91.66666666666666%; } .col-lg-pull-0 { right: auto; } .col-lg-pull-1 { right: 8.333333333333332%; } .col-lg-pull-2 { right: 16.666666666666664%; } .col-lg-pull-3 { right: 25%; } .col-lg-pull-4 { right: 33.33333333333333%; } .col-lg-pull-5 { right: 41.66666666666667%; } .col-lg-pull-6 { right: 50%; } .col-lg-pull-7 { right: 58.333333333333336%; } .col-lg-pull-8 { right: 66.66666666666666%; } .col-lg-pull-9 { right: 75%; } .col-lg-pull-10 { right: 83.33333333333334%; } .col-lg-pull-11 { right: 91.66666666666666%; } .col-lg-offset-0 { margin-left: 0; } .col-lg-offset-1 { margin-left: 8.333333333333332%; } .col-lg-offset-2 { margin-left: 16.666666666666664%; } .col-lg-offset-3 { margin-left: 25%; } .col-lg-offset-4 { margin-left: 33.33333333333333%; } .col-lg-offset-5 { margin-left: 41.66666666666667%; } .col-lg-offset-6 { margin-left: 50%; } .col-lg-offset-7 { margin-left: 58.333333333333336%; } .col-lg-offset-8 { margin-left: 66.66666666666666%; } .col-lg-offset-9 { margin-left: 75%; } .col-lg-offset-10 { margin-left: 83.33333333333334%; } .col-lg-offset-11 { margin-left: 91.66666666666666%; } } table { max-width: 100%; background-color: transparent; } th { text-align: left; } .table { width: 100%; margin-bottom: 20px; } .table thead > tr > th, .table tbody > tr > th, .table tfoot > tr > th, .table thead > tr > td, .table tbody > tr > td, .table tfoot > tr > td { padding: 8px; line-height: 1.428571429; vertical-align: top; border-top: 1px solid #dddddd; } .table thead > tr > th { vertical-align: bottom; border-bottom: 2px solid #dddddd; } .table caption + thead tr:first-child th, .table colgroup + thead tr:first-child th, .table thead:first-child tr:first-child th, .table caption + thead tr:first-child td, .table colgroup + thead tr:first-child td, .table thead:first-child tr:first-child td { border-top: 0; } .table tbody + tbody { border-top: 2px solid #dddddd; } .table .table { background-color: #ffffff; } .table-condensed thead > tr > th, .table-condensed tbody > tr > th, .table-condensed tfoot > tr > th, .table-condensed thead > tr > td, .table-condensed tbody > tr > td, .table-condensed tfoot > tr > td { padding: 5px; } .table-bordered { border: 1px solid #dddddd; } .table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td { border: 1px solid #dddddd; } .table-bordered > thead > tr > th, .table-bordered > thead > tr > td { border-bottom-width: 2px; } .table-striped > tbody > tr:nth-child(odd) > td, .table-striped > tbody > tr:nth-child(odd) > th { background-color: #f9f9f9; } .table-hover > tbody > tr:hover > td, .table-hover > tbody > tr:hover > th { background-color: #f5f5f5; } table col[class*="col-"] { display: table-column; float: none; } table td[class*="col-"], table th[class*="col-"] { display: table-cell; float: none; } .table > thead > tr > td.active, .table > tbody > tr > td.active, .table > tfoot > tr > td.active, .table > thead > tr > th.active, .table > tbody > tr > th.active, .table > tfoot > tr > th.active, .table > thead > tr.active > td, .table > tbody > tr.active > td, .table > tfoot > tr.active > td, .table > thead > tr.active > th, .table > tbody > tr.active > th, .table > tfoot > tr.active > th { background-color: #f5f5f5; } .table > thead > tr > td.success, .table > tbody > tr > td.success, .table > tfoot > tr > td.success, .table > thead > tr > th.success, .table > tbody > tr > th.success, .table > tfoot > tr > th.success, .table > thead > tr.success > td, .table > tbody > tr.success > td, .table > tfoot > tr.success > td, .table > thead > tr.success > th, .table > tbody > tr.success > th, .table > tfoot > tr.success > th { background-color: #dff0d8; border-color: #d6e9c6; } .table-hover > tbody > tr > td.success:hover, .table-hover > tbody > tr > th.success:hover, .table-hover > tbody > tr.success:hover > td { background-color: #d0e9c6; border-color: #c9e2b3; } .table > thead > tr > td.danger, .table > tbody > tr > td.danger, .table > tfoot > tr > td.danger, .table > thead > tr > th.danger, .table > tbody > tr > th.danger, .table > tfoot > tr > th.danger, .table > thead > tr.danger > td, .table > tbody > tr.danger > td, .table > tfoot > tr.danger > td, .table > thead > tr.danger > th, .table > tbody > tr.danger > th, .table > tfoot > tr.danger > th { background-color: #f2dede; border-color: #eed3d7; } .table-hover > tbody > tr > td.danger:hover, .table-hover > tbody > tr > th.danger:hover, .table-hover > tbody > tr.danger:hover > td { background-color: #ebcccc; border-color: #e6c1c7; } .table > thead > tr > td.warning, .table > tbody > tr > td.warning, .table > tfoot > tr > td.warning, .table > thead > tr > th.warning, .table > tbody > tr > th.warning, .table > tfoot > tr > th.warning, .table > thead > tr.warning > td, .table > tbody > tr.warning > td, .table > tfoot > tr.warning > td, .table > thead > tr.warning > th, .table > tbody > tr.warning > th, .table > tfoot > tr.warning > th { background-color: #fcf8e3; border-color: #fbeed5; } .table-hover > tbody > tr > td.warning:hover, .table-hover > tbody > tr > th.warning:hover, .table-hover > tbody > tr.warning:hover > td { background-color: #faf2cc; border-color: #f8e5be; } @media (max-width: 768px) { .table-responsive { width: 100%; margin-bottom: 15px; overflow-x: scroll; overflow-y: hidden; border: 1px solid #dddddd; } .table-responsive > .table { margin-bottom: 0; background-color: #fff; } .table-responsive > .table > thead > tr > th, .table-responsive > .table > tbody > tr > th, .table-responsive > .table > tfoot > tr > th, .table-responsive > .table > thead > tr > td, .table-responsive > .table > tbody > tr > td, .table-responsive > .table > tfoot > tr > td { white-space: nowrap; } .table-responsive > .table-bordered { border: 0; } .table-responsive > .table-bordered > thead > tr > th:first-child, .table-responsive > .table-bordered > tbody > tr > th:first-child, .table-responsive > .table-bordered > tfoot > tr > th:first-child, .table-responsive > .table-bordered > thead > tr > td:first-child, .table-responsive > .table-bordered > tbody > tr > td:first-child, .table-responsive > .table-bordered > tfoot > tr > td:first-child { border-left: 0; } .table-responsive > .table-bordered > thead > tr > th:last-child, .table-responsive > .table-bordered > tbody > tr > th:last-child, .table-responsive > .table-bordered > tfoot > tr > th:last-child, .table-responsive > .table-bordered > thead > tr > td:last-child, .table-responsive > .table-bordered > tbody > tr > td:last-child, .table-responsive > .table-bordered > tfoot > tr > td:last-child { border-right: 0; } .table-responsive > .table-bordered > thead > tr:last-child > th, .table-responsive > .table-bordered > tbody > tr:last-child > th, .table-responsive > .table-bordered > tfoot > tr:last-child > th, .table-responsive > .table-bordered > thead > tr:last-child > td, .table-responsive > .table-bordered > tbody > tr:last-child > td, .table-responsive > .table-bordered > tfoot > tr:last-child > td { border-bottom: 0; } } fieldset { padding: 0; margin: 0; border: 0; } legend { display: block; width: 100%; padding: 0; margin-bottom: 20px; font-size: 21px; line-height: inherit; color: #666666; border: 0; border-bottom: 1px solid #e5e5e5; } label { display: inline-block; margin-bottom: 5px; font-weight: bold; } input[type="search"] { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } input[type="radio"], input[type="checkbox"] { margin: 4px 0 0; margin-top: 1px \9; /* IE8-9 */ line-height: normal; } input[type="file"] { display: block; } select[multiple], select[size] { height: auto; } select optgroup { font-family: inherit; font-size: inherit; font-style: inherit; } input[type="file"]:focus, input[type="radio"]:focus, input[type="checkbox"]:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } input[type="number"]::-webkit-outer-spin-button, input[type="number"]::-webkit-inner-spin-button { height: auto; } .form-control:-moz-placeholder { color: #999999; } .form-control::-moz-placeholder { color: #999999; } .form-control:-ms-input-placeholder { color: #999999; } .form-control::-webkit-input-placeholder { color: #999999; } .form-control { display: block; width: 100%; height: 38px; padding: 8px 12px; font-size: 14px; line-height: 1.428571429; color: #666666; vertical-align: middle; background-color: #ffffff; border: 1px solid #cccccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; } .form-control:focus { border-color: #66afe9; outline: 0; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(102, 175, 233, 0.6); } .form-control[disabled], .form-control[readonly], fieldset[disabled] .form-control { cursor: not-allowed; background-color: #eeeeee; } textarea.form-control { height: auto; } .form-group { margin-bottom: 15px; } .radio, .checkbox { display: block; min-height: 20px; padding-left: 20px; margin-top: 10px; margin-bottom: 10px; vertical-align: middle; } .radio label, .checkbox label { display: inline; margin-bottom: 0; font-weight: normal; cursor: pointer; } .radio input[type="radio"], .radio-inline input[type="radio"], .checkbox input[type="checkbox"], .checkbox-inline input[type="checkbox"] { float: left; margin-left: -20px; } .radio + .radio, .checkbox + .checkbox { margin-top: -5px; } .radio-inline, .checkbox-inline { display: inline-block; padding-left: 20px; margin-bottom: 0; font-weight: normal; vertical-align: middle; cursor: pointer; } .radio-inline + .radio-inline, .checkbox-inline + .checkbox-inline { margin-top: 0; margin-left: 10px; } input[type="radio"][disabled], input[type="checkbox"][disabled], .radio[disabled], .radio-inline[disabled], .checkbox[disabled], .checkbox-inline[disabled], fieldset[disabled] input[type="radio"], fieldset[disabled] input[type="checkbox"], fieldset[disabled] .radio, fieldset[disabled] .radio-inline, fieldset[disabled] .checkbox, fieldset[disabled] .checkbox-inline { cursor: not-allowed; } .input-sm { height: 30px; padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } select.input-sm { height: 30px; line-height: 30px; } textarea.input-sm { height: auto; } .input-lg { height: 56px; padding: 14px 16px; font-size: 18px; line-height: 1.33; border-radius: 6px; } select.input-lg { height: 56px; line-height: 56px; } textarea.input-lg { height: auto; } .has-warning .help-block, .has-warning .control-label { color: #c09853; } .has-warning .form-control { border-color: #c09853; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .has-warning .form-control:focus { border-color: #a47e3c; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e; } .has-warning .input-group-addon { color: #c09853; background-color: #fcf8e3; border-color: #c09853; } .has-error .help-block, .has-error .control-label { color: #b94a48; } .has-error .form-control { border-color: #b94a48; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .has-error .form-control:focus { border-color: #953b39; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392; } .has-error .input-group-addon { color: #b94a48; background-color: #f2dede; border-color: #b94a48; } .has-success .help-block, .has-success .control-label { color: #468847; } .has-success .form-control { border-color: #468847; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); } .has-success .form-control:focus { border-color: #356635; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b; } .has-success .input-group-addon { color: #468847; background-color: #dff0d8; border-color: #468847; } .form-control-static { padding-top: 9px; margin-bottom: 0; } .help-block { display: block; margin-top: 5px; margin-bottom: 10px; color: #a6a6a6; } @media (min-width: 768px) { .form-inline .form-group { display: inline-block; margin-bottom: 0; vertical-align: middle; } .form-inline .form-control { display: inline-block; } .form-inline .radio, .form-inline .checkbox { display: inline-block; padding-left: 0; margin-top: 0; margin-bottom: 0; } .form-inline .radio input[type="radio"], .form-inline .checkbox input[type="checkbox"] { float: none; margin-left: 0; } } .form-horizontal .control-label, .form-horizontal .radio, .form-horizontal .checkbox, .form-horizontal .radio-inline, .form-horizontal .checkbox-inline { padding-top: 9px; margin-top: 0; margin-bottom: 0; } .form-horizontal .form-group { margin-right: -15px; margin-left: -15px; } .form-horizontal .form-group:before, .form-horizontal .form-group:after { display: table; content: " "; } .form-horizontal .form-group:after { clear: both; } .form-horizontal .form-group:before, .form-horizontal .form-group:after { display: table; content: " "; } .form-horizontal .form-group:after { clear: both; } .form-horizontal .form-group:before, .form-horizontal .form-group:after { display: table; content: " "; } .form-horizontal .form-group:after { clear: both; } .form-horizontal .form-group:before, .form-horizontal .form-group:after { display: table; content: " "; } .form-horizontal .form-group:after { clear: both; } .form-horizontal .form-group:before, .form-horizontal .form-group:after { display: table; content: " "; } .form-horizontal .form-group:after { clear: both; } @media (min-width: 768px) { .form-horizontal .control-label { text-align: right; } } .btn { display: inline-block; padding: 8px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; line-height: 1.428571429; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; border: 1px solid transparent; border-radius: 4px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } .btn:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } .btn:hover, .btn:focus { color: #ffffff; text-decoration: none; } .btn:active, .btn.active { background-image: none; outline: 0; -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn.disabled, .btn[disabled], fieldset[disabled] .btn { pointer-events: none; cursor: not-allowed; opacity: 0.65; filter: alpha(opacity=65); -webkit-box-shadow: none; box-shadow: none; } .btn-default { color: #ffffff; background-color: #474949; border-color: #474949; } .btn-default:hover, .btn-default:focus, .btn-default:active, .btn-default.active, .open .dropdown-toggle.btn-default { color: #ffffff; background-color: #333434; border-color: #292a2a; } .btn-default:active, .btn-default.active, .open .dropdown-toggle.btn-default { background-image: none; } .btn-default.disabled, .btn-default[disabled], fieldset[disabled] .btn-default, .btn-default.disabled:hover, .btn-default[disabled]:hover, fieldset[disabled] .btn-default:hover, .btn-default.disabled:focus, .btn-default[disabled]:focus, fieldset[disabled] .btn-default:focus, .btn-default.disabled:active, .btn-default[disabled]:active, fieldset[disabled] .btn-default:active, .btn-default.disabled.active, .btn-default[disabled].active, fieldset[disabled] .btn-default.active { background-color: #474949; border-color: #474949; } .btn-primary { color: #ffffff; background-color: #446e9b; border-color: #446e9b; } .btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open .dropdown-toggle.btn-primary { color: #ffffff; background-color: #385a7f; border-color: #315070; } .btn-primary:active, .btn-primary.active, .open .dropdown-toggle.btn-primary { background-image: none; } .btn-primary.disabled, .btn-primary[disabled], fieldset[disabled] .btn-primary, .btn-primary.disabled:hover, .btn-primary[disabled]:hover, fieldset[disabled] .btn-primary:hover, .btn-primary.disabled:focus, .btn-primary[disabled]:focus, fieldset[disabled] .btn-primary:focus, .btn-primary.disabled:active, .btn-primary[disabled]:active, fieldset[disabled] .btn-primary:active, .btn-primary.disabled.active, .btn-primary[disabled].active, fieldset[disabled] .btn-primary.active { background-color: #446e9b; border-color: #446e9b; } .btn-warning { color: #ffffff; background-color: #d47500; border-color: #d47500; } .btn-warning:hover, .btn-warning:focus, .btn-warning:active, .btn-warning.active, .open .dropdown-toggle.btn-warning { color: #ffffff; background-color: #ab5e00; border-color: #975300; } .btn-warning:active, .btn-warning.active, .open .dropdown-toggle.btn-warning { background-image: none; } .btn-warning.disabled, .btn-warning[disabled], fieldset[disabled] .btn-warning, .btn-warning.disabled:hover, .btn-warning[disabled]:hover, fieldset[disabled] .btn-warning:hover, .btn-warning.disabled:focus, .btn-warning[disabled]:focus, fieldset[disabled] .btn-warning:focus, .btn-warning.disabled:active, .btn-warning[disabled]:active, fieldset[disabled] .btn-warning:active, .btn-warning.disabled.active, .btn-warning[disabled].active, fieldset[disabled] .btn-warning.active { background-color: #d47500; border-color: #d47500; } .btn-danger { color: #ffffff; background-color: #cd0200; border-color: #cd0200; } .btn-danger:hover, .btn-danger:focus, .btn-danger:active, .btn-danger.active, .open .dropdown-toggle.btn-danger { color: #ffffff; background-color: #a40200; border-color: #900100; } .btn-danger:active, .btn-danger.active, .open .dropdown-toggle.btn-danger { background-image: none; } .btn-danger.disabled, .btn-danger[disabled], fieldset[disabled] .btn-danger, .btn-danger.disabled:hover, .btn-danger[disabled]:hover, fieldset[disabled] .btn-danger:hover, .btn-danger.disabled:focus, .btn-danger[disabled]:focus, fieldset[disabled] .btn-danger:focus, .btn-danger.disabled:active, .btn-danger[disabled]:active, fieldset[disabled] .btn-danger:active, .btn-danger.disabled.active, .btn-danger[disabled].active, fieldset[disabled] .btn-danger.active { background-color: #cd0200; border-color: #cd0200; } .btn-success { color: #ffffff; background-color: #3cb521; border-color: #3cb521; } .btn-success:hover, .btn-success:focus, .btn-success:active, .btn-success.active, .open .dropdown-toggle.btn-success { color: #ffffff; background-color: #31921b; border-color: #2b8118; } .btn-success:active, .btn-success.active, .open .dropdown-toggle.btn-success { background-image: none; } .btn-success.disabled, .btn-success[disabled], fieldset[disabled] .btn-success, .btn-success.disabled:hover, .btn-success[disabled]:hover, fieldset[disabled] .btn-success:hover, .btn-success.disabled:focus, .btn-success[disabled]:focus, fieldset[disabled] .btn-success:focus, .btn-success.disabled:active, .btn-success[disabled]:active, fieldset[disabled] .btn-success:active, .btn-success.disabled.active, .btn-success[disabled].active, fieldset[disabled] .btn-success.active { background-color: #3cb521; border-color: #3cb521; } .btn-info { color: #ffffff; background-color: #3399f3; border-color: #3399f3; } .btn-info:hover, .btn-info:focus, .btn-info:active, .btn-info.active, .open .dropdown-toggle.btn-info { color: #ffffff; background-color: #0e86ef; border-color: #0d7bdc; } .btn-info:active, .btn-info.active, .open .dropdown-toggle.btn-info { background-image: none; } .btn-info.disabled, .btn-info[disabled], fieldset[disabled] .btn-info, .btn-info.disabled:hover, .btn-info[disabled]:hover, fieldset[disabled] .btn-info:hover, .btn-info.disabled:focus, .btn-info[disabled]:focus, fieldset[disabled] .btn-info:focus, .btn-info.disabled:active, .btn-info[disabled]:active, fieldset[disabled] .btn-info:active, .btn-info.disabled.active, .btn-info[disabled].active, fieldset[disabled] .btn-info.active { background-color: #3399f3; border-color: #3399f3; } .btn-link { font-weight: normal; color: #3399f3; cursor: pointer; border-radius: 0; } .btn-link, .btn-link:active, .btn-link[disabled], fieldset[disabled] .btn-link { background-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .btn-link, .btn-link:hover, .btn-link:focus, .btn-link:active { border-color: transparent; } .btn-link:hover, .btn-link:focus { color: #3399f3; text-decoration: underline; background-color: transparent; } .btn-link[disabled]:hover, fieldset[disabled] .btn-link:hover, .btn-link[disabled]:focus, fieldset[disabled] .btn-link:focus { color: #999999; text-decoration: none; } .btn-lg { padding: 14px 16px; font-size: 18px; line-height: 1.33; border-radius: 6px; } .btn-sm, .btn-xs { padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } .btn-xs { padding: 1px 5px; } .btn-block { display: block; width: 100%; padding-right: 0; padding-left: 0; } .btn-block + .btn-block { margin-top: 5px; } input[type="submit"].btn-block, input[type="reset"].btn-block, input[type="button"].btn-block { width: 100%; } .fade { opacity: 0; -webkit-transition: opacity 0.15s linear; transition: opacity 0.15s linear; } .fade.in { opacity: 1; } .collapse { display: none; } .collapse.in { display: block; } .collapsing { position: relative; height: 0; overflow: hidden; -webkit-transition: height 0.35s ease; transition: height 0.35s ease; } @font-face { font-family: 'Glyphicons Halflings'; src: url('../fonts/glyphicons-halflings-regular.eot'); src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg'); } .glyphicon { position: relative; top: 1px; display: inline-block; font-family: 'Glyphicons Halflings'; -webkit-font-smoothing: antialiased; font-style: normal; font-weight: normal; line-height: 1; } .glyphicon-asterisk:before { content: "\2a"; } .glyphicon-plus:before { content: "\2b"; } .glyphicon-euro:before { content: "\20ac"; } .glyphicon-minus:before { content: "\2212"; } .glyphicon-cloud:before { content: "\2601"; } .glyphicon-envelope:before { content: "\2709"; } .glyphicon-pencil:before { content: "\270f"; } .glyphicon-glass:before { content: "\e001"; } .glyphicon-music:before { content: "\e002"; } .glyphicon-search:before { content: "\e003"; } .glyphicon-heart:before { content: "\e005"; } .glyphicon-star:before { content: "\e006"; } .glyphicon-star-empty:before { content: "\e007"; } .glyphicon-user:before { content: "\e008"; } .glyphicon-film:before { content: "\e009"; } .glyphicon-th-large:before { content: "\e010"; } .glyphicon-th:before { content: "\e011"; } .glyphicon-th-list:before { content: "\e012"; } .glyphicon-ok:before { content: "\e013"; } .glyphicon-remove:before { content: "\e014"; } .glyphicon-zoom-in:before { content: "\e015"; } .glyphicon-zoom-out:before { content: "\e016"; } .glyphicon-off:before { content: "\e017"; } .glyphicon-signal:before { content: "\e018"; } .glyphicon-cog:before { content: "\e019"; } .glyphicon-trash:before { content: "\e020"; } .glyphicon-home:before { content: "\e021"; } .glyphicon-file:before { content: "\e022"; } .glyphicon-time:before { content: "\e023"; } .glyphicon-road:before { content: "\e024"; } .glyphicon-download-alt:before { content: "\e025"; } .glyphicon-download:before { content: "\e026"; } .glyphicon-upload:before { content: "\e027"; } .glyphicon-inbox:before { content: "\e028"; } .glyphicon-play-circle:before { content: "\e029"; } .glyphicon-repeat:before { content: "\e030"; } .glyphicon-refresh:before { content: "\e031"; } .glyphicon-list-alt:before { content: "\e032"; } .glyphicon-flag:before { content: "\e034"; } .glyphicon-headphones:before { content: "\e035"; } .glyphicon-volume-off:before { content: "\e036"; } .glyphicon-volume-down:before { content: "\e037"; } .glyphicon-volume-up:before { content: "\e038"; } .glyphicon-qrcode:before { content: "\e039"; } .glyphicon-barcode:before { content: "\e040"; } .glyphicon-tag:before { content: "\e041"; } .glyphicon-tags:before { content: "\e042"; } .glyphicon-book:before { content: "\e043"; } .glyphicon-print:before { content: "\e045"; } .glyphicon-font:before { content: "\e047"; } .glyphicon-bold:before { content: "\e048"; } .glyphicon-italic:before { content: "\e049"; } .glyphicon-text-height:before { content: "\e050"; } .glyphicon-text-width:before { content: "\e051"; } .glyphicon-align-left:before { content: "\e052"; } .glyphicon-align-center:before { content: "\e053"; } .glyphicon-align-right:before { content: "\e054"; } .glyphicon-align-justify:before { content: "\e055"; } .glyphicon-list:before { content: "\e056"; } .glyphicon-indent-left:before { content: "\e057"; } .glyphicon-indent-right:before { content: "\e058"; } .glyphicon-facetime-video:before { content: "\e059"; } .glyphicon-picture:before { content: "\e060"; } .glyphicon-map-marker:before { content: "\e062"; } .glyphicon-adjust:before { content: "\e063"; } .glyphicon-tint:before { content: "\e064"; } .glyphicon-edit:before { content: "\e065"; } .glyphicon-share:before { content: "\e066"; } .glyphicon-check:before { content: "\e067"; } .glyphicon-move:before { content: "\e068"; } .glyphicon-step-backward:before { content: "\e069"; } .glyphicon-fast-backward:before { content: "\e070"; } .glyphicon-backward:before { content: "\e071"; } .glyphicon-play:before { content: "\e072"; } .glyphicon-pause:before { content: "\e073"; } .glyphicon-stop:before { content: "\e074"; } .glyphicon-forward:before { content: "\e075"; } .glyphicon-fast-forward:before { content: "\e076"; } .glyphicon-step-forward:before { content: "\e077"; } .glyphicon-eject:before { content: "\e078"; } .glyphicon-chevron-left:before { content: "\e079"; } .glyphicon-chevron-right:before { content: "\e080"; } .glyphicon-plus-sign:before { content: "\e081"; } .glyphicon-minus-sign:before { content: "\e082"; } .glyphicon-remove-sign:before { content: "\e083"; } .glyphicon-ok-sign:before { content: "\e084"; } .glyphicon-question-sign:before { content: "\e085"; } .glyphicon-info-sign:before { content: "\e086"; } .glyphicon-screenshot:before { content: "\e087"; } .glyphicon-remove-circle:before { content: "\e088"; } .glyphicon-ok-circle:before { content: "\e089"; } .glyphicon-ban-circle:before { content: "\e090"; } .glyphicon-arrow-left:before { content: "\e091"; } .glyphicon-arrow-right:before { content: "\e092"; } .glyphicon-arrow-up:before { content: "\e093"; } .glyphicon-arrow-down:before { content: "\e094"; } .glyphicon-share-alt:before { content: "\e095"; } .glyphicon-resize-full:before { content: "\e096"; } .glyphicon-resize-small:before { content: "\e097"; } .glyphicon-exclamation-sign:before { content: "\e101"; } .glyphicon-gift:before { content: "\e102"; } .glyphicon-leaf:before { content: "\e103"; } .glyphicon-eye-open:before { content: "\e105"; } .glyphicon-eye-close:before { content: "\e106"; } .glyphicon-warning-sign:before { content: "\e107"; } .glyphicon-plane:before { content: "\e108"; } .glyphicon-random:before { content: "\e110"; } .glyphicon-comment:before { content: "\e111"; } .glyphicon-magnet:before { content: "\e112"; } .glyphicon-chevron-up:before { content: "\e113"; } .glyphicon-chevron-down:before { content: "\e114"; } .glyphicon-retweet:before { content: "\e115"; } .glyphicon-shopping-cart:before { content: "\e116"; } .glyphicon-folder-close:before { content: "\e117"; } .glyphicon-folder-open:before { content: "\e118"; } .glyphicon-resize-vertical:before { content: "\e119"; } .glyphicon-resize-horizontal:before { content: "\e120"; } .glyphicon-hdd:before { content: "\e121"; } .glyphicon-bullhorn:before { content: "\e122"; } .glyphicon-certificate:before { content: "\e124"; } .glyphicon-thumbs-up:before { content: "\e125"; } .glyphicon-thumbs-down:before { content: "\e126"; } .glyphicon-hand-right:before { content: "\e127"; } .glyphicon-hand-left:before { content: "\e128"; } .glyphicon-hand-up:before { content: "\e129"; } .glyphicon-hand-down:before { content: "\e130"; } .glyphicon-circle-arrow-right:before { content: "\e131"; } .glyphicon-circle-arrow-left:before { content: "\e132"; } .glyphicon-circle-arrow-up:before { content: "\e133"; } .glyphicon-circle-arrow-down:before { content: "\e134"; } .glyphicon-globe:before { content: "\e135"; } .glyphicon-tasks:before { content: "\e137"; } .glyphicon-filter:before { content: "\e138"; } .glyphicon-fullscreen:before { content: "\e140"; } .glyphicon-dashboard:before { content: "\e141"; } .glyphicon-heart-empty:before { content: "\e143"; } .glyphicon-link:before { content: "\e144"; } .glyphicon-phone:before { content: "\e145"; } .glyphicon-usd:before { content: "\e148"; } .glyphicon-gbp:before { content: "\e149"; } .glyphicon-sort:before { content: "\e150"; } .glyphicon-sort-by-alphabet:before { content: "\e151"; } .glyphicon-sort-by-alphabet-alt:before { content: "\e152"; } .glyphicon-sort-by-order:before { content: "\e153"; } .glyphicon-sort-by-order-alt:before { content: "\e154"; } .glyphicon-sort-by-attributes:before { content: "\e155"; } .glyphicon-sort-by-attributes-alt:before { content: "\e156"; } .glyphicon-unchecked:before { content: "\e157"; } .glyphicon-expand:before { content: "\e158"; } .glyphicon-collapse-down:before { content: "\e159"; } .glyphicon-collapse-up:before { content: "\e160"; } .glyphicon-log-in:before { content: "\e161"; } .glyphicon-flash:before { content: "\e162"; } .glyphicon-log-out:before { content: "\e163"; } .glyphicon-new-window:before { content: "\e164"; } .glyphicon-record:before { content: "\e165"; } .glyphicon-save:before { content: "\e166"; } .glyphicon-open:before { content: "\e167"; } .glyphicon-saved:before { content: "\e168"; } .glyphicon-import:before { content: "\e169"; } .glyphicon-export:before { content: "\e170"; } .glyphicon-send:before { content: "\e171"; } .glyphicon-floppy-disk:before { content: "\e172"; } .glyphicon-floppy-saved:before { content: "\e173"; } .glyphicon-floppy-remove:before { content: "\e174"; } .glyphicon-floppy-save:before { content: "\e175"; } .glyphicon-floppy-open:before { content: "\e176"; } .glyphicon-credit-card:before { content: "\e177"; } .glyphicon-transfer:before { content: "\e178"; } .glyphicon-cutlery:before { content: "\e179"; } .glyphicon-header:before { content: "\e180"; } .glyphicon-compressed:before { content: "\e181"; } .glyphicon-earphone:before { content: "\e182"; } .glyphicon-phone-alt:before { content: "\e183"; } .glyphicon-tower:before { content: "\e184"; } .glyphicon-stats:before { content: "\e185"; } .glyphicon-sd-video:before { content: "\e186"; } .glyphicon-hd-video:before { content: "\e187"; } .glyphicon-subtitles:before { content: "\e188"; } .glyphicon-sound-stereo:before { content: "\e189"; } .glyphicon-sound-dolby:before { content: "\e190"; } .glyphicon-sound-5-1:before { content: "\e191"; } .glyphicon-sound-6-1:before { content: "\e192"; } .glyphicon-sound-7-1:before { content: "\e193"; } .glyphicon-copyright-mark:before { content: "\e194"; } .glyphicon-registration-mark:before { content: "\e195"; } .glyphicon-cloud-download:before { content: "\e197"; } .glyphicon-cloud-upload:before { content: "\e198"; } .glyphicon-tree-conifer:before { content: "\e199"; } .glyphicon-tree-deciduous:before { content: "\e200"; } .glyphicon-briefcase:before { content: "\1f4bc"; } .glyphicon-calendar:before { content: "\1f4c5"; } .glyphicon-pushpin:before { content: "\1f4cc"; } .glyphicon-paperclip:before { content: "\1f4ce"; } .glyphicon-camera:before { content: "\1f4f7"; } .glyphicon-lock:before { content: "\1f512"; } .glyphicon-bell:before { content: "\1f514"; } .glyphicon-bookmark:before { content: "\1f516"; } .glyphicon-fire:before { content: "\1f525"; } .glyphicon-wrench:before { content: "\1f527"; } .caret { display: inline-block; width: 0; height: 0; margin-left: 2px; vertical-align: middle; border-top: 4px solid #000000; border-right: 4px solid transparent; border-bottom: 0 dotted; border-left: 4px solid transparent; content: ""; } .dropdown { position: relative; } .dropdown-toggle:focus { outline: 0; } .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; float: left; min-width: 160px; padding: 5px 0; margin: 2px 0 0; font-size: 14px; list-style: none; background-color: #ffffff; border: 1px solid #cccccc; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 4px; -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); background-clip: padding-box; } .dropdown-menu.pull-right { right: 0; left: auto; } .dropdown-menu .divider { height: 1px; margin: 9px 0; overflow: hidden; background-color: #e5e5e5; } .dropdown-menu > li > a { display: block; padding: 3px 20px; clear: both; font-weight: normal; line-height: 1.428571429; color: #333333; white-space: nowrap; } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { color: #ffffff; text-decoration: none; background-color: #446e9b; } .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { color: #ffffff; text-decoration: none; background-color: #446e9b; outline: 0; } .dropdown-menu > .disabled > a, .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { color: #999999; } .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { text-decoration: none; cursor: not-allowed; background-color: transparent; background-image: none; filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); } .open > .dropdown-menu { display: block; } .open > a { outline: 0; } .dropdown-header { display: block; padding: 3px 20px; font-size: 12px; line-height: 1.428571429; color: #999999; } .dropdown-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 990; } .pull-right > .dropdown-menu { right: 0; left: auto; } .dropup .caret, .navbar-fixed-bottom .dropdown .caret { border-top: 0 dotted; border-bottom: 4px solid #000000; content: ""; } .dropup .dropdown-menu, .navbar-fixed-bottom .dropdown .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 1px; } @media (min-width: 768px) { .navbar-right .dropdown-menu { right: 0; left: auto; } } .btn-default .caret { border-top-color: #ffffff; } .btn-primary .caret, .btn-success .caret, .btn-warning .caret, .btn-danger .caret, .btn-info .caret { border-top-color: #fff; } .dropup .btn-default .caret { border-bottom-color: #ffffff; } .dropup .btn-primary .caret, .dropup .btn-success .caret, .dropup .btn-warning .caret, .dropup .btn-danger .caret, .dropup .btn-info .caret { border-bottom-color: #fff; } .btn-group, .btn-group-vertical { position: relative; display: inline-block; vertical-align: middle; } .btn-group > .btn, .btn-group-vertical > .btn { position: relative; float: left; } .btn-group > .btn:hover, .btn-group-vertical > .btn:hover, .btn-group > .btn:focus, .btn-group-vertical > .btn:focus, .btn-group > .btn:active, .btn-group-vertical > .btn:active, .btn-group > .btn.active, .btn-group-vertical > .btn.active { z-index: 2; } .btn-group > .btn:focus, .btn-group-vertical > .btn:focus { outline: none; } .btn-group .btn + .btn, .btn-group .btn + .btn-group, .btn-group .btn-group + .btn, .btn-group .btn-group + .btn-group { margin-left: -1px; } .btn-toolbar:before, .btn-toolbar:after { display: table; content: " "; } .btn-toolbar:after { clear: both; } .btn-toolbar:before, .btn-toolbar:after { display: table; content: " "; } .btn-toolbar:after { clear: both; } .btn-toolbar:before, .btn-toolbar:after { display: table; content: " "; } .btn-toolbar:after { clear: both; } .btn-toolbar:before, .btn-toolbar:after { display: table; content: " "; } .btn-toolbar:after { clear: both; } .btn-toolbar:before, .btn-toolbar:after { display: table; content: " "; } .btn-toolbar:after { clear: both; } .btn-toolbar .btn-group { float: left; } .btn-toolbar > .btn + .btn, .btn-toolbar > .btn-group + .btn, .btn-toolbar > .btn + .btn-group, .btn-toolbar > .btn-group + .btn-group { margin-left: 5px; } .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { border-radius: 0; } .btn-group > .btn:first-child { margin-left: 0; } .btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) { border-top-right-radius: 0; border-bottom-right-radius: 0; } .btn-group > .btn:last-child:not(:first-child), .btn-group > .dropdown-toggle:not(:first-child) { border-bottom-left-radius: 0; border-top-left-radius: 0; } .btn-group > .btn-group { float: left; } .btn-group > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group > .btn-group:first-child > .btn:last-child, .btn-group > .btn-group:first-child > .dropdown-toggle { border-top-right-radius: 0; border-bottom-right-radius: 0; } .btn-group > .btn-group:last-child > .btn:first-child { border-bottom-left-radius: 0; border-top-left-radius: 0; } .btn-group .dropdown-toggle:active, .btn-group.open .dropdown-toggle { outline: 0; } .btn-group-xs > .btn { padding: 5px 10px; padding: 1px 5px; font-size: 12px; line-height: 1.5; border-radius: 3px; } .btn-group-sm > .btn { padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } .btn-group-lg > .btn { padding: 14px 16px; font-size: 18px; line-height: 1.33; border-radius: 6px; } .btn-group > .btn + .dropdown-toggle { padding-right: 8px; padding-left: 8px; } .btn-group > .btn-lg + .dropdown-toggle { padding-right: 12px; padding-left: 12px; } .btn-group.open .dropdown-toggle { -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn .caret { margin-left: 0; } .btn-lg .caret { border-width: 5px 5px 0; border-bottom-width: 0; } .dropup .btn-lg .caret { border-width: 0 5px 5px; } .btn-group-vertical > .btn, .btn-group-vertical > .btn-group { display: block; float: none; width: 100%; max-width: 100%; } .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after { display: table; content: " "; } .btn-group-vertical > .btn-group:after { clear: both; } .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after { display: table; content: " "; } .btn-group-vertical > .btn-group:after { clear: both; } .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after { display: table; content: " "; } .btn-group-vertical > .btn-group:after { clear: both; } .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after { display: table; content: " "; } .btn-group-vertical > .btn-group:after { clear: both; } .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after { display: table; content: " "; } .btn-group-vertical > .btn-group:after { clear: both; } .btn-group-vertical > .btn-group > .btn { float: none; } .btn-group-vertical > .btn + .btn, .btn-group-vertical > .btn + .btn-group, .btn-group-vertical > .btn-group + .btn, .btn-group-vertical > .btn-group + .btn-group { margin-top: -1px; margin-left: 0; } .btn-group-vertical > .btn:not(:first-child):not(:last-child) { border-radius: 0; } .btn-group-vertical > .btn:first-child:not(:last-child) { border-top-right-radius: 4px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .btn-group-vertical > .btn:last-child:not(:first-child) { border-top-right-radius: 0; border-bottom-left-radius: 4px; border-top-left-radius: 0; } .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { border-radius: 0; } .btn-group-vertical > .btn-group:first-child > .btn:last-child, .btn-group-vertical > .btn-group:first-child > .dropdown-toggle { border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .btn-group-vertical > .btn-group:last-child > .btn:first-child { border-top-right-radius: 0; border-top-left-radius: 0; } .btn-group-justified { display: table; width: 100%; border-collapse: separate; table-layout: fixed; } .btn-group-justified .btn { display: table-cell; float: none; width: 1%; } [data-toggle="buttons"] > .btn > input[type="radio"], [data-toggle="buttons"] > .btn > input[type="checkbox"] { display: none; } .input-group { position: relative; display: table; border-collapse: separate; } .input-group.col { float: none; padding-right: 0; padding-left: 0; } .input-group .form-control { width: 100%; margin-bottom: 0; } .input-group-lg > .form-control, .input-group-lg > .input-group-addon, .input-group-lg > .input-group-btn > .btn { height: 56px; padding: 14px 16px; font-size: 18px; line-height: 1.33; border-radius: 6px; } select.input-group-lg > .form-control, select.input-group-lg > .input-group-addon, select.input-group-lg > .input-group-btn > .btn { height: 56px; line-height: 56px; } textarea.input-group-lg > .form-control, textarea.input-group-lg > .input-group-addon, textarea.input-group-lg > .input-group-btn > .btn { height: auto; } .input-group-sm > .form-control, .input-group-sm > .input-group-addon, .input-group-sm > .input-group-btn > .btn { height: 30px; padding: 5px 10px; font-size: 12px; line-height: 1.5; border-radius: 3px; } select.input-group-sm > .form-control, select.input-group-sm > .input-group-addon, select.input-group-sm > .input-group-btn > .btn { height: 30px; line-height: 30px; } textarea.input-group-sm > .form-control, textarea.input-group-sm > .input-group-addon, textarea.input-group-sm > .input-group-btn > .btn { height: auto; } .input-group-addon, .input-group-btn, .input-group .form-control { display: table-cell; } .input-group-addon:not(:first-child):not(:last-child), .input-group-btn:not(:first-child):not(:last-child), .input-group .form-control:not(:first-child):not(:last-child) { border-radius: 0; } .input-group-addon, .input-group-btn { width: 1%; white-space: nowrap; vertical-align: middle; } .input-group-addon { padding: 8px 12px; font-size: 14px; font-weight: normal; line-height: 1; text-align: center; background-color: #eeeeee; border: 1px solid #cccccc; border-radius: 4px; } .input-group-addon.input-sm { padding: 5px 10px; font-size: 12px; border-radius: 3px; } .input-group-addon.input-lg { padding: 14px 16px; font-size: 18px; border-radius: 6px; } .input-group-addon input[type="radio"], .input-group-addon input[type="checkbox"] { margin-top: 0; } .input-group .form-control:first-child, .input-group-addon:first-child, .input-group-btn:first-child > .btn, .input-group-btn:first-child > .dropdown-toggle, .input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle) { border-top-right-radius: 0; border-bottom-right-radius: 0; } .input-group-addon:first-child { border-right: 0; } .input-group .form-control:last-child, .input-group-addon:last-child, .input-group-btn:last-child > .btn, .input-group-btn:last-child > .dropdown-toggle, .input-group-btn:first-child > .btn:not(:first-child) { border-bottom-left-radius: 0; border-top-left-radius: 0; } .input-group-addon:last-child { border-left: 0; } .input-group-btn { position: relative; white-space: nowrap; } .input-group-btn > .btn { position: relative; } .input-group-btn > .btn + .btn { margin-left: -4px; } .input-group-btn > .btn:hover, .input-group-btn > .btn:active { z-index: 2; } .nav { padding-left: 0; margin-bottom: 0; list-style: none; } .nav:before, .nav:after { display: table; content: " "; } .nav:after { clear: both; } .nav:before, .nav:after { display: table; content: " "; } .nav:after { clear: both; } .nav:before, .nav:after { display: table; content: " "; } .nav:after { clear: both; } .nav:before, .nav:after { display: table; content: " "; } .nav:after { clear: both; } .nav:before, .nav:after { display: table; content: " "; } .nav:after { clear: both; } .nav > li { position: relative; display: block; } .nav > li > a { position: relative; display: block; padding: 10px 15px; } .nav > li > a:hover, .nav > li > a:focus { text-decoration: none; background-color: #eeeeee; } .nav > li.disabled > a { color: #999999; } .nav > li.disabled > a:hover, .nav > li.disabled > a:focus { color: #999999; text-decoration: none; cursor: not-allowed; background-color: transparent; } .nav .open > a, .nav .open > a:hover, .nav .open > a:focus { background-color: #eeeeee; border-color: #3399f3; } .nav .nav-divider { height: 1px; margin: 9px 0; overflow: hidden; background-color: #e5e5e5; } .nav > li > a > img { max-width: none; } .nav-tabs { border-bottom: 1px solid #dddddd; } .nav-tabs > li { float: left; margin-bottom: -1px; } .nav-tabs > li > a { margin-right: 2px; line-height: 1.428571429; border: 1px solid transparent; border-radius: 4px 4px 0 0; } .nav-tabs > li > a:hover { border-color: #eeeeee #eeeeee #dddddd; } .nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus { color: #666666; cursor: default; background-color: #ffffff; border: 1px solid #dddddd; border-bottom-color: transparent; } .nav-tabs.nav-justified { width: 100%; border-bottom: 0; } .nav-tabs.nav-justified > li { float: none; } .nav-tabs.nav-justified > li > a { text-align: center; } @media (min-width: 768px) { .nav-tabs.nav-justified > li { display: table-cell; width: 1%; } } .nav-tabs.nav-justified > li > a { margin-right: 0; border-bottom: 1px solid #dddddd; } .nav-tabs.nav-justified > .active > a { border-bottom-color: #ffffff; } .nav-pills > li { float: left; } .nav-pills > li > a { border-radius: 5px; } .nav-pills > li + li { margin-left: 2px; } .nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus { color: #ffffff; background-color: #446e9b; } .nav-stacked > li { float: none; } .nav-stacked > li + li { margin-top: 2px; margin-left: 0; } .nav-justified { width: 100%; } .nav-justified > li { float: none; } .nav-justified > li > a { text-align: center; } @media (min-width: 768px) { .nav-justified > li { display: table-cell; width: 1%; } } .nav-tabs-justified { border-bottom: 0; } .nav-tabs-justified > li > a { margin-right: 0; border-bottom: 1px solid #dddddd; } .nav-tabs-justified > .active > a { border-bottom-color: #ffffff; } .tabbable:before, .tabbable:after { display: table; content: " "; } .tabbable:after { clear: both; } .tabbable:before, .tabbable:after { display: table; content: " "; } .tabbable:after { clear: both; } .tabbable:before, .tabbable:after { display: table; content: " "; } .tabbable:after { clear: both; } .tabbable:before, .tabbable:after { display: table; content: " "; } .tabbable:after { clear: both; } .tabbable:before, .tabbable:after { display: table; content: " "; } .tabbable:after { clear: both; } .tab-content > .tab-pane, .pill-content > .pill-pane { display: none; } .tab-content > .active, .pill-content > .active { display: block; } .nav .caret { border-top-color: #3399f3; border-bottom-color: #3399f3; } .nav a:hover .caret { border-top-color: #3399f3; border-bottom-color: #3399f3; } .nav-tabs .dropdown-menu { margin-top: -1px; border-top-right-radius: 0; border-top-left-radius: 0; } .navbar { position: relative; z-index: 1000; min-height: 50px; margin-bottom: 20px; border: 1px solid transparent; } .navbar:before, .navbar:after { display: table; content: " "; } .navbar:after { clear: both; } .navbar:before, .navbar:after { display: table; content: " "; } .navbar:after { clear: both; } .navbar:before, .navbar:after { display: table; content: " "; } .navbar:after { clear: both; } .navbar:before, .navbar:after { display: table; content: " "; } .navbar:after { clear: both; } .navbar:before, .navbar:after { display: table; content: " "; } .navbar:after { clear: both; } @media (min-width: 768px) { .navbar { border-radius: 4px; } } .navbar-header:before, .navbar-header:after { display: table; content: " "; } .navbar-header:after { clear: both; } .navbar-header:before, .navbar-header:after { display: table; content: " "; } .navbar-header:after { clear: both; } .navbar-header:before, .navbar-header:after { display: table; content: " "; } .navbar-header:after { clear: both; } .navbar-header:before, .navbar-header:after { display: table; content: " "; } .navbar-header:after { clear: both; } .navbar-header:before, .navbar-header:after { display: table; content: " "; } .navbar-header:after { clear: both; } @media (min-width: 768px) { .navbar-header { float: left; } } .navbar-collapse { max-height: 340px; padding-right: 15px; padding-left: 15px; overflow-x: visible; border-top: 1px solid transparent; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1); -webkit-overflow-scrolling: touch; } .navbar-collapse:before, .navbar-collapse:after { display: table; content: " "; } .navbar-collapse:after { clear: both; } .navbar-collapse:before, .navbar-collapse:after { display: table; content: " "; } .navbar-collapse:after { clear: both; } .navbar-collapse:before, .navbar-collapse:after { display: table; content: " "; } .navbar-collapse:after { clear: both; } .navbar-collapse:before, .navbar-collapse:after { display: table; content: " "; } .navbar-collapse:after { clear: both; } .navbar-collapse:before, .navbar-collapse:after { display: table; content: " "; } .navbar-collapse:after { clear: both; } .navbar-collapse.in { overflow-y: auto; } @media (min-width: 768px) { .navbar-collapse { width: auto; border-top: 0; box-shadow: none; } .navbar-collapse.collapse { display: block !important; height: auto !important; padding-bottom: 0; overflow: visible !important; } .navbar-collapse.in { overflow-y: visible; } .navbar-collapse .navbar-nav.navbar-left:first-child { margin-left: -15px; } .navbar-collapse .navbar-nav.navbar-right:last-child { margin-right: -15px; } .navbar-collapse .navbar-text:last-child { margin-right: 0; } } .container > .navbar-header, .container > .navbar-collapse { margin-right: -15px; margin-left: -15px; } @media (min-width: 768px) { .container > .navbar-header, .container > .navbar-collapse { margin-right: 0; margin-left: 0; } } .navbar-static-top { border-width: 0 0 1px; } @media (min-width: 768px) { .navbar-static-top { border-radius: 0; } } .navbar-fixed-top, .navbar-fixed-bottom { position: fixed; right: 0; left: 0; border-width: 0 0 1px; } @media (min-width: 768px) { .navbar-fixed-top, .navbar-fixed-bottom { border-radius: 0; } } .navbar-fixed-top { top: 0; z-index: 1030; } .navbar-fixed-bottom { bottom: 0; margin-bottom: 0; } .navbar-brand { float: left; padding: 15px 15px; font-size: 18px; line-height: 20px; } .navbar-brand:hover, .navbar-brand:focus { text-decoration: none; } @media (min-width: 768px) { .navbar > .container .navbar-brand { margin-left: -15px; } } .navbar-toggle { position: relative; float: right; padding: 9px 10px; margin-top: 8px; margin-right: 15px; margin-bottom: 8px; background-color: transparent; border: 1px solid transparent; border-radius: 4px; } .navbar-toggle .icon-bar { display: block; width: 22px; height: 2px; border-radius: 1px; } .navbar-toggle .icon-bar + .icon-bar { margin-top: 4px; } @media (min-width: 768px) { .navbar-toggle { display: none; } } .navbar-nav { margin: 7.5px -15px; } .navbar-nav > li > a { padding-top: 10px; padding-bottom: 10px; line-height: 20px; } @media (max-width: 767px) { .navbar-nav .open .dropdown-menu { position: static; float: none; width: auto; margin-top: 0; background-color: transparent; border: 0; box-shadow: none; } .navbar-nav .open .dropdown-menu > li > a, .navbar-nav .open .dropdown-menu .dropdown-header { padding: 5px 15px 5px 25px; } .navbar-nav .open .dropdown-menu > li > a { line-height: 20px; } .navbar-nav .open .dropdown-menu > li > a:hover, .navbar-nav .open .dropdown-menu > li > a:focus { background-image: none; } } @media (min-width: 768px) { .navbar-nav { float: left; margin: 0; } .navbar-nav > li { float: left; } .navbar-nav > li > a { padding-top: 15px; padding-bottom: 15px; } } @media (min-width: 768px) { .navbar-left { float: left !important; } .navbar-right { float: right !important; } } .navbar-form { padding: 10px 15px; margin-top: 6px; margin-right: -15px; margin-bottom: 6px; margin-left: -15px; border-top: 1px solid transparent; border-bottom: 1px solid transparent; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); } @media (min-width: 768px) { .navbar-form .form-group { display: inline-block; margin-bottom: 0; vertical-align: middle; } .navbar-form .form-control { display: inline-block; } .navbar-form .radio, .navbar-form .checkbox { display: inline-block; padding-left: 0; margin-top: 0; margin-bottom: 0; } .navbar-form .radio input[type="radio"], .navbar-form .checkbox input[type="checkbox"] { float: none; margin-left: 0; } } @media (max-width: 767px) { .navbar-form .form-group { margin-bottom: 5px; } } @media (min-width: 768px) { .navbar-form { width: auto; padding-top: 0; padding-bottom: 0; margin-right: 0; margin-left: 0; border: 0; -webkit-box-shadow: none; box-shadow: none; } } .navbar-nav > li > .dropdown-menu { margin-top: 0; border-top-right-radius: 0; border-top-left-radius: 0; } .navbar-fixed-bottom .navbar-nav > li > .dropdown-menu { border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .navbar-nav.pull-right > li > .dropdown-menu, .navbar-nav > li > .dropdown-menu.pull-right { right: 0; left: auto; } .navbar-btn { margin-top: 6px; margin-bottom: 6px; } .navbar-text { float: left; margin-top: 15px; margin-bottom: 15px; } @media (min-width: 768px) { .navbar-text { margin-right: 15px; margin-left: 15px; } } .navbar-default { background-color: #eeeeee; border-color: #dddddd; } .navbar-default .navbar-brand { color: #777777; } .navbar-default .navbar-brand:hover, .navbar-default .navbar-brand:focus { color: #3399f3; background-color: transparent; } .navbar-default .navbar-text { color: #777777; } .navbar-default .navbar-nav > li > a { color: #777777; } .navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus { color: #3399f3; background-color: transparent; } .navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus { color: #3399f3; background-color: transparent; } .navbar-default .navbar-nav > .disabled > a, .navbar-default .navbar-nav > .disabled > a:hover, .navbar-default .navbar-nav > .disabled > a:focus { color: #444444; background-color: transparent; } .navbar-default .navbar-toggle { border-color: #dddddd; } .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus { background-color: #dddddd; } .navbar-default .navbar-toggle .icon-bar { background-color: #cccccc; } .navbar-default .navbar-collapse, .navbar-default .navbar-form { border-color: #dcdcdc; } .navbar-default .navbar-nav > .dropdown > a:hover .caret, .navbar-default .navbar-nav > .dropdown > a:focus .caret { border-top-color: #3399f3; border-bottom-color: #3399f3; } .navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:hover, .navbar-default .navbar-nav > .open > a:focus { color: #3399f3; background-color: transparent; } .navbar-default .navbar-nav > .open > a .caret, .navbar-default .navbar-nav > .open > a:hover .caret, .navbar-default .navbar-nav > .open > a:focus .caret { border-top-color: #3399f3; border-bottom-color: #3399f3; } .navbar-default .navbar-nav > .dropdown > a .caret { border-top-color: #777777; border-bottom-color: #777777; } @media (max-width: 767px) { .navbar-default .navbar-nav .open .dropdown-menu > li > a { color: #777777; } .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus { color: #3399f3; background-color: transparent; } .navbar-default .navbar-nav .open .dropdown-menu > .active > a, .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus { color: #3399f3; background-color: transparent; } .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a, .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover, .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus { color: #444444; background-color: transparent; } } .navbar-default .navbar-link { color: #777777; } .navbar-default .navbar-link:hover { color: #3399f3; } .navbar-inverse { background-color: #446e9b; border-color: #345578; } .navbar-inverse .navbar-brand { color: #dddddd; } .navbar-inverse .navbar-brand:hover, .navbar-inverse .navbar-brand:focus { color: #ffffff; background-color: transparent; } .navbar-inverse .navbar-text { color: #dddddd; } .navbar-inverse .navbar-nav > li > a { color: #dddddd; } .navbar-inverse .navbar-nav > li > a:hover, .navbar-inverse .navbar-nav > li > a:focus { color: #ffffff; background-color: transparent; } .navbar-inverse .navbar-nav > .active > a, .navbar-inverse .navbar-nav > .active > a:hover, .navbar-inverse .navbar-nav > .active > a:focus { color: #ffffff; background-color: transparent; } .navbar-inverse .navbar-nav > .disabled > a, .navbar-inverse .navbar-nav > .disabled > a:hover, .navbar-inverse .navbar-nav > .disabled > a:focus { color: #cccccc; background-color: transparent; } .navbar-inverse .navbar-toggle { border-color: #345578; } .navbar-inverse .navbar-toggle:hover, .navbar-inverse .navbar-toggle:focus { background-color: #345578; } .navbar-inverse .navbar-toggle .icon-bar { background-color: #ffffff; } .navbar-inverse .navbar-collapse, .navbar-inverse .navbar-form { border-color: #395c82; } .navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-nav > .open > a:hover, .navbar-inverse .navbar-nav > .open > a:focus { color: #ffffff; background-color: transparent; } .navbar-inverse .navbar-nav > .dropdown > a:hover .caret { border-top-color: #ffffff; border-bottom-color: #ffffff; } .navbar-inverse .navbar-nav > .dropdown > a .caret { border-top-color: #dddddd; border-bottom-color: #dddddd; } .navbar-inverse .navbar-nav > .open > a .caret, .navbar-inverse .navbar-nav > .open > a:hover .caret, .navbar-inverse .navbar-nav > .open > a:focus .caret { border-top-color: #ffffff; border-bottom-color: #ffffff; } @media (max-width: 767px) { .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header { border-color: #345578; } .navbar-inverse .navbar-nav .open .dropdown-menu > li > a { color: #dddddd; } .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover, .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus { color: #ffffff; background-color: transparent; } .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a, .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover, .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus { color: #ffffff; background-color: transparent; } .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a, .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover, .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus { color: #cccccc; background-color: transparent; } } .navbar-inverse .navbar-link { color: #dddddd; } .navbar-inverse .navbar-link:hover { color: #ffffff; } .breadcrumb { padding: 8px 15px; margin-bottom: 20px; list-style: none; background-color: #f5f5f5; border-radius: 4px; } .breadcrumb > li { display: inline-block; } .breadcrumb > li + li:before { padding: 0 5px; color: #cccccc; content: "/\00a0"; } .breadcrumb > .active { color: #999999; } .pagination { display: inline-block; padding-left: 0; margin: 20px 0; border-radius: 4px; } .pagination > li { display: inline; } .pagination > li > a, .pagination > li > span { position: relative; float: left; padding: 8px 12px; margin-left: -1px; line-height: 1.428571429; text-decoration: none; background-color: #ffffff; border: 1px solid #dddddd; } .pagination > li:first-child > a, .pagination > li:first-child > span { margin-left: 0; border-bottom-left-radius: 4px; border-top-left-radius: 4px; } .pagination > li:last-child > a, .pagination > li:last-child > span { border-top-right-radius: 4px; border-bottom-right-radius: 4px; } .pagination > li > a:hover, .pagination > li > span:hover, .pagination > li > a:focus, .pagination > li > span:focus { background-color: #eeeeee; } .pagination > .active > a, .pagination > .active > span, .pagination > .active > a:hover, .pagination > .active > span:hover, .pagination > .active > a:focus, .pagination > .active > span:focus { z-index: 2; color: #999999; cursor: default; background-color: #f5f5f5; border-color: #f5f5f5; } .pagination > .disabled > span, .pagination > .disabled > a, .pagination > .disabled > a:hover, .pagination > .disabled > a:focus { color: #999999; cursor: not-allowed; background-color: #ffffff; border-color: #dddddd; } .pagination-lg > li > a, .pagination-lg > li > span { padding: 14px 16px; font-size: 18px; } .pagination-lg > li:first-child > a, .pagination-lg > li:first-child > span { border-bottom-left-radius: 6px; border-top-left-radius: 6px; } .pagination-lg > li:last-child > a, .pagination-lg > li:last-child > span { border-top-right-radius: 6px; border-bottom-right-radius: 6px; } .pagination-sm > li > a, .pagination-sm > li > span { padding: 5px 10px; font-size: 12px; } .pagination-sm > li:first-child > a, .pagination-sm > li:first-child > span { border-bottom-left-radius: 3px; border-top-left-radius: 3px; } .pagination-sm > li:last-child > a, .pagination-sm > li:last-child > span { border-top-right-radius: 3px; border-bottom-right-radius: 3px; } .pager { padding-left: 0; margin: 20px 0; text-align: center; list-style: none; } .pager:before, .pager:after { display: table; content: " "; } .pager:after { clear: both; } .pager:before, .pager:after { display: table; content: " "; } .pager:after { clear: both; } .pager:before, .pager:after { display: table; content: " "; } .pager:after { clear: both; } .pager:before, .pager:after { display: table; content: " "; } .pager:after { clear: both; } .pager:before, .pager:after { display: table; content: " "; } .pager:after { clear: both; } .pager li { display: inline; } .pager li > a, .pager li > span { display: inline-block; padding: 5px 14px; background-color: #ffffff; border: 1px solid #dddddd; border-radius: 15px; } .pager li > a:hover, .pager li > a:focus { text-decoration: none; background-color: #eeeeee; } .pager .next > a, .pager .next > span { float: right; } .pager .previous > a, .pager .previous > span { float: left; } .pager .disabled > a, .pager .disabled > a:hover, .pager .disabled > a:focus, .pager .disabled > span { color: #999999; cursor: not-allowed; background-color: #ffffff; } .label { display: inline; padding: .2em .6em .3em; font-size: 75%; font-weight: bold; line-height: 1; color: #ffffff; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: .25em; } .label[href]:hover, .label[href]:focus { color: #ffffff; text-decoration: none; cursor: pointer; } .label:empty { display: none; } .label-default { background-color: #474949; } .label-default[href]:hover, .label-default[href]:focus { background-color: #2e2f2f; } .label-primary { background-color: #446e9b; } .label-primary[href]:hover, .label-primary[href]:focus { background-color: #345578; } .label-success { background-color: #3cb521; } .label-success[href]:hover, .label-success[href]:focus { background-color: #2e8a19; } .label-info { background-color: #3399f3; } .label-info[href]:hover, .label-info[href]:focus { background-color: #0e80e5; } .label-warning { background-color: #d47500; } .label-warning[href]:hover, .label-warning[href]:focus { background-color: #a15900; } .label-danger { background-color: #cd0200; } .label-danger[href]:hover, .label-danger[href]:focus { background-color: #9a0200; } .badge { display: inline-block; min-width: 10px; padding: 3px 7px; font-size: 12px; font-weight: bold; line-height: 1; color: #ffffff; text-align: center; white-space: nowrap; vertical-align: baseline; background-color: #999999; border-radius: 10px; } .badge:empty { display: none; } a.badge:hover, a.badge:focus { color: #ffffff; text-decoration: none; cursor: pointer; } .btn .badge { position: relative; top: -1px; } a.list-group-item.active > .badge, .nav-pills > .active > a > .badge { color: #3399f3; background-color: #ffffff; } .nav-pills > li > a > .badge { margin-left: 3px; } .jumbotron { padding: 30px; margin-bottom: 30px; font-size: 21px; font-weight: 200; line-height: 2.1428571435; color: inherit; background-color: #eeeeee; } .jumbotron h1 { line-height: 1; color: inherit; } .jumbotron p { line-height: 1.4; } .container .jumbotron { border-radius: 6px; } @media screen and (min-width: 768px) { .jumbotron { padding-top: 48px; padding-bottom: 48px; } .container .jumbotron { padding-right: 60px; padding-left: 60px; } .jumbotron h1 { font-size: 63px; } } .thumbnail { display: inline-block; display: block; height: auto; max-width: 100%; padding: 4px; line-height: 1.428571429; background-color: #ffffff; border: 1px solid #dddddd; border-radius: 4px; -webkit-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .thumbnail > img { display: block; height: auto; max-width: 100%; } a.thumbnail:hover, a.thumbnail:focus { border-color: #3399f3; } .thumbnail > img { margin-right: auto; margin-left: auto; } .thumbnail .caption { padding: 9px; color: #666666; } .alert { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; } .alert h4 { margin-top: 0; color: inherit; } .alert .alert-link { font-weight: bold; } .alert > p, .alert > ul { margin-bottom: 0; } .alert > p + p { margin-top: 5px; } .alert-dismissable { padding-right: 35px; } .alert-dismissable .close { position: relative; top: -2px; right: -21px; color: inherit; } .alert-success { color: #468847; background-color: #dff0d8; border-color: #d6e9c6; } .alert-success hr { border-top-color: #c9e2b3; } .alert-success .alert-link { color: #356635; } .alert-info { color: #3a87ad; background-color: #d9edf7; border-color: #bce8f1; } .alert-info hr { border-top-color: #a6e1ec; } .alert-info .alert-link { color: #2d6987; } .alert-warning { color: #c09853; background-color: #fcf8e3; border-color: #fbeed5; } .alert-warning hr { border-top-color: #f8e5be; } .alert-warning .alert-link { color: #a47e3c; } .alert-danger { color: #b94a48; background-color: #f2dede; border-color: #eed3d7; } .alert-danger hr { border-top-color: #e6c1c7; } .alert-danger .alert-link { color: #953b39; } @-webkit-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @-moz-keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } @-o-keyframes progress-bar-stripes { from { background-position: 0 0; } to { background-position: 40px 0; } } @keyframes progress-bar-stripes { from { background-position: 40px 0; } to { background-position: 0 0; } } .progress { height: 20px; margin-bottom: 20px; overflow: hidden; background-color: #f5f5f5; border-radius: 4px; -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); } .progress-bar { float: left; width: 0; height: 100%; font-size: 12px; color: #ffffff; text-align: center; background-color: #446e9b; -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); -webkit-transition: width 0.6s ease; transition: width 0.6s ease; } .progress-striped .progress-bar { background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-size: 40px 40px; } .progress.active .progress-bar { -webkit-animation: progress-bar-stripes 2s linear infinite; -moz-animation: progress-bar-stripes 2s linear infinite; -ms-animation: progress-bar-stripes 2s linear infinite; -o-animation: progress-bar-stripes 2s linear infinite; animation: progress-bar-stripes 2s linear infinite; } .progress-bar-success { background-color: #3cb521; } .progress-striped .progress-bar-success { background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-info { background-color: #3399f3; } .progress-striped .progress-bar-info { background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-warning { background-color: #d47500; } .progress-striped .progress-bar-warning { background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .progress-bar-danger { background-color: #cd0200; } .progress-striped .progress-bar-danger { background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .media, .media-body { overflow: hidden; zoom: 1; } .media, .media .media { margin-top: 15px; } .media:first-child { margin-top: 0; } .media-object { display: block; } .media-heading { margin: 0 0 5px; } .media > .pull-left { margin-right: 10px; } .media > .pull-right { margin-left: 10px; } .media-list { padding-left: 0; list-style: none; } .list-group { padding-left: 0; margin-bottom: 20px; } .list-group-item { position: relative; display: block; padding: 10px 15px; margin-bottom: -1px; background-color: #ffffff; border: 1px solid #dddddd; } .list-group-item:first-child { border-top-right-radius: 4px; border-top-left-radius: 4px; } .list-group-item:last-child { margin-bottom: 0; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; } .list-group-item > .badge { float: right; } .list-group-item > .badge + .badge { margin-right: 5px; } a.list-group-item { color: #555555; } a.list-group-item .list-group-item-heading { color: #333333; } a.list-group-item:hover, a.list-group-item:focus { text-decoration: none; background-color: #f5f5f5; } .list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus { z-index: 2; color: #ffffff; background-color: #446e9b; border-color: #446e9b; } .list-group-item.active .list-group-item-heading, .list-group-item.active:hover .list-group-item-heading, .list-group-item.active:focus .list-group-item-heading { color: inherit; } .list-group-item.active .list-group-item-text, .list-group-item.active:hover .list-group-item-text, .list-group-item.active:focus .list-group-item-text { color: #c5d5e6; } .list-group-item-heading { margin-top: 0; margin-bottom: 5px; } .list-group-item-text { margin-bottom: 0; line-height: 1.3; } .panel { margin-bottom: 20px; background-color: #ffffff; border: 1px solid transparent; border-radius: 4px; -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05); box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05); } .panel-body { padding: 15px; } .panel-body:before, .panel-body:after { display: table; content: " "; } .panel-body:after { clear: both; } .panel-body:before, .panel-body:after { display: table; content: " "; } .panel-body:after { clear: both; } .panel-body:before, .panel-body:after { display: table; content: " "; } .panel-body:after { clear: both; } .panel-body:before, .panel-body:after { display: table; content: " "; } .panel-body:after { clear: both; } .panel-body:before, .panel-body:after { display: table; content: " "; } .panel-body:after { clear: both; } .panel > .list-group { margin-bottom: 0; } .panel > .list-group .list-group-item { border-width: 1px 0; } .panel > .list-group .list-group-item:first-child { border-top-right-radius: 0; border-top-left-radius: 0; } .panel > .list-group .list-group-item:last-child { border-bottom: 0; } .panel-heading + .list-group .list-group-item:first-child { border-top-width: 0; } .panel > .table { margin-bottom: 0; } .panel > .panel-body + .table { border-top: 1px solid #dddddd; } .panel-heading { padding: 10px 15px; border-bottom: 1px solid transparent; border-top-right-radius: 3px; border-top-left-radius: 3px; } .panel-title { margin-top: 0; margin-bottom: 0; font-size: 16px; } .panel-title > a { color: inherit; } .panel-footer { padding: 10px 15px; background-color: #f5f5f5; border-top: 1px solid #dddddd; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; } .panel-group .panel { margin-bottom: 0; overflow: hidden; border-radius: 4px; } .panel-group .panel + .panel { margin-top: 5px; } .panel-group .panel-heading { border-bottom: 0; } .panel-group .panel-heading + .panel-collapse .panel-body { border-top: 1px solid #dddddd; } .panel-group .panel-footer { border-top: 0; } .panel-group .panel-footer + .panel-collapse .panel-body { border-bottom: 1px solid #dddddd; } .panel-default { border-color: #dddddd; } .panel-default > .panel-heading { color: #333333; background-color: #f5f5f5; border-color: #dddddd; } .panel-default > .panel-heading + .panel-collapse .panel-body { border-top-color: #dddddd; } .panel-default > .panel-footer + .panel-collapse .panel-body { border-bottom-color: #dddddd; } .panel-primary { border-color: #446e9b; } .panel-primary > .panel-heading { color: #ffffff; background-color: #446e9b; border-color: #446e9b; } .panel-primary > .panel-heading + .panel-collapse .panel-body { border-top-color: #446e9b; } .panel-primary > .panel-footer + .panel-collapse .panel-body { border-bottom-color: #446e9b; } .panel-success { border-color: #d6e9c6; } .panel-success > .panel-heading { color: #468847; background-color: #dff0d8; border-color: #d6e9c6; } .panel-success > .panel-heading + .panel-collapse .panel-body { border-top-color: #d6e9c6; } .panel-success > .panel-footer + .panel-collapse .panel-body { border-bottom-color: #d6e9c6; } .panel-warning { border-color: #fbeed5; } .panel-warning > .panel-heading { color: #c09853; background-color: #fcf8e3; border-color: #fbeed5; } .panel-warning > .panel-heading + .panel-collapse .panel-body { border-top-color: #fbeed5; } .panel-warning > .panel-footer + .panel-collapse .panel-body { border-bottom-color: #fbeed5; } .panel-danger { border-color: #eed3d7; } .panel-danger > .panel-heading { color: #b94a48; background-color: #f2dede; border-color: #eed3d7; } .panel-danger > .panel-heading + .panel-collapse .panel-body { border-top-color: #eed3d7; } .panel-danger > .panel-footer + .panel-collapse .panel-body { border-bottom-color: #eed3d7; } .panel-info { border-color: #bce8f1; } .panel-info > .panel-heading { color: #3a87ad; background-color: #d9edf7; border-color: #bce8f1; } .panel-info > .panel-heading + .panel-collapse .panel-body { border-top-color: #bce8f1; } .panel-info > .panel-footer + .panel-collapse .panel-body { border-bottom-color: #bce8f1; } .well { min-height: 20px; padding: 19px; margin-bottom: 20px; background-color: #f5f5f5; border: 1px solid #e3e3e3; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05); } .well blockquote { border-color: #ddd; border-color: rgba(0, 0, 0, 0.15); } .well-lg { padding: 24px; border-radius: 6px; } .well-sm { padding: 9px; border-radius: 3px; } .close { float: right; font-size: 21px; font-weight: bold; line-height: 1; color: #000000; text-shadow: 0 1px 0 #ffffff; opacity: 0.2; filter: alpha(opacity=20); } .close:hover, .close:focus { color: #000000; text-decoration: none; cursor: pointer; opacity: 0.5; filter: alpha(opacity=50); } button.close { padding: 0; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; } .modal-open { overflow: hidden; } body.modal-open, .modal-open .navbar-fixed-top, .modal-open .navbar-fixed-bottom { margin-right: 15px; } .modal { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; display: none; overflow: auto; overflow-y: scroll; } .modal.fade .modal-dialog { -webkit-transform: translate(0, -25%); -ms-transform: translate(0, -25%); transform: translate(0, -25%); -webkit-transition: -webkit-transform 0.3s ease-out; -moz-transition: -moz-transform 0.3s ease-out; -o-transition: -o-transform 0.3s ease-out; transition: transform 0.3s ease-out; } .modal.in .modal-dialog { -webkit-transform: translate(0, 0); -ms-transform: translate(0, 0); transform: translate(0, 0); } .modal-dialog { z-index: 1050; width: auto; padding: 10px; margin-right: auto; margin-left: auto; } .modal-content { position: relative; background-color: #ffffff; border: 1px solid #999999; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 6px; outline: none; -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5); box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5); background-clip: padding-box; } .modal-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1030; background-color: #000000; } .modal-backdrop.fade { opacity: 0; filter: alpha(opacity=0); } .modal-backdrop.in { opacity: 0.5; filter: alpha(opacity=50); } .modal-header { min-height: 16.428571429px; padding: 15px; border-bottom: 1px solid #e5e5e5; } .modal-header .close { margin-top: -2px; } .modal-title { margin: 0; line-height: 1.428571429; } .modal-body { position: relative; padding: 20px; } .modal-footer { padding: 19px 20px 20px; margin-top: 15px; text-align: right; border-top: 1px solid #e5e5e5; } .modal-footer:before, .modal-footer:after { display: table; content: " "; } .modal-footer:after { clear: both; } .modal-footer:before, .modal-footer:after { display: table; content: " "; } .modal-footer:after { clear: both; } .modal-footer:before, .modal-footer:after { display: table; content: " "; } .modal-footer:after { clear: both; } .modal-footer:before, .modal-footer:after { display: table; content: " "; } .modal-footer:after { clear: both; } .modal-footer:before, .modal-footer:after { display: table; content: " "; } .modal-footer:after { clear: both; } .modal-footer .btn + .btn { margin-bottom: 0; margin-left: 5px; } .modal-footer .btn-group .btn + .btn { margin-left: -1px; } .modal-footer .btn-block + .btn-block { margin-left: 0; } @media screen and (min-width: 768px) { .modal-dialog { right: auto; left: 50%; width: 600px; padding-top: 30px; padding-bottom: 30px; } .modal-content { -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5); } } .tooltip { position: absolute; z-index: 1030; display: block; font-size: 12px; line-height: 1.4; opacity: 0; filter: alpha(opacity=0); visibility: visible; } .tooltip.in { opacity: 0.9; filter: alpha(opacity=90); } .tooltip.top { padding: 5px 0; margin-top: -3px; } .tooltip.right { padding: 0 5px; margin-left: 3px; } .tooltip.bottom { padding: 5px 0; margin-top: 3px; } .tooltip.left { padding: 0 5px; margin-left: -3px; } .tooltip-inner { max-width: 200px; padding: 3px 8px; color: #ffffff; text-align: center; text-decoration: none; background-color: rgba(0, 0, 0, 0.9); border-radius: 4px; } .tooltip-arrow { position: absolute; width: 0; height: 0; border-color: transparent; border-style: solid; } .tooltip.top .tooltip-arrow { bottom: 0; left: 50%; margin-left: -5px; border-top-color: rgba(0, 0, 0, 0.9); border-width: 5px 5px 0; } .tooltip.top-left .tooltip-arrow { bottom: 0; left: 5px; border-top-color: rgba(0, 0, 0, 0.9); border-width: 5px 5px 0; } .tooltip.top-right .tooltip-arrow { right: 5px; bottom: 0; border-top-color: rgba(0, 0, 0, 0.9); border-width: 5px 5px 0; } .tooltip.right .tooltip-arrow { top: 50%; left: 0; margin-top: -5px; border-right-color: rgba(0, 0, 0, 0.9); border-width: 5px 5px 5px 0; } .tooltip.left .tooltip-arrow { top: 50%; right: 0; margin-top: -5px; border-left-color: rgba(0, 0, 0, 0.9); border-width: 5px 0 5px 5px; } .tooltip.bottom .tooltip-arrow { top: 0; left: 50%; margin-left: -5px; border-bottom-color: rgba(0, 0, 0, 0.9); border-width: 0 5px 5px; } .tooltip.bottom-left .tooltip-arrow { top: 0; left: 5px; border-bottom-color: rgba(0, 0, 0, 0.9); border-width: 0 5px 5px; } .tooltip.bottom-right .tooltip-arrow { top: 0; right: 5px; border-bottom-color: rgba(0, 0, 0, 0.9); border-width: 0 5px 5px; } .popover { position: absolute; top: 0; left: 0; z-index: 1010; display: none; max-width: 276px; padding: 1px; text-align: left; white-space: normal; background-color: #ffffff; border: 1px solid #cccccc; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 6px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); background-clip: padding-box; } .popover.top { margin-top: -10px; } .popover.right { margin-left: 10px; } .popover.bottom { margin-top: 10px; } .popover.left { margin-left: -10px; } .popover-title { padding: 8px 14px; margin: 0; font-size: 14px; font-weight: normal; line-height: 18px; background-color: #f7f7f7; border-bottom: 1px solid #ebebeb; border-radius: 5px 5px 0 0; } .popover-content { padding: 9px 14px; } .popover .arrow, .popover .arrow:after { position: absolute; display: block; width: 0; height: 0; border-color: transparent; border-style: solid; } .popover .arrow { border-width: 11px; } .popover .arrow:after { border-width: 10px; content: ""; } .popover.top .arrow { bottom: -11px; left: 50%; margin-left: -11px; border-top-color: #999999; border-top-color: rgba(0, 0, 0, 0.25); border-bottom-width: 0; } .popover.top .arrow:after { bottom: 1px; margin-left: -10px; border-top-color: #ffffff; border-bottom-width: 0; content: " "; } .popover.right .arrow { top: 50%; left: -11px; margin-top: -11px; border-right-color: #999999; border-right-color: rgba(0, 0, 0, 0.25); border-left-width: 0; } .popover.right .arrow:after { bottom: -10px; left: 1px; border-right-color: #ffffff; border-left-width: 0; content: " "; } .popover.bottom .arrow { top: -11px; left: 50%; margin-left: -11px; border-bottom-color: #999999; border-bottom-color: rgba(0, 0, 0, 0.25); border-top-width: 0; } .popover.bottom .arrow:after { top: 1px; margin-left: -10px; border-bottom-color: #ffffff; border-top-width: 0; content: " "; } .popover.left .arrow { top: 50%; right: -11px; margin-top: -11px; border-left-color: #999999; border-left-color: rgba(0, 0, 0, 0.25); border-right-width: 0; } .popover.left .arrow:after { right: 1px; bottom: -10px; border-left-color: #ffffff; border-right-width: 0; content: " "; } .carousel { position: relative; } .carousel-inner { position: relative; width: 100%; overflow: hidden; } .carousel-inner > .item { position: relative; display: none; -webkit-transition: 0.6s ease-in-out left; transition: 0.6s ease-in-out left; } .carousel-inner > .item > img, .carousel-inner > .item > a > img { display: block; height: auto; max-width: 100%; line-height: 1; } .carousel-inner > .active, .carousel-inner > .next, .carousel-inner > .prev { display: block; } .carousel-inner > .active { left: 0; } .carousel-inner > .next, .carousel-inner > .prev { position: absolute; top: 0; width: 100%; } .carousel-inner > .next { left: 100%; } .carousel-inner > .prev { left: -100%; } .carousel-inner > .next.left, .carousel-inner > .prev.right { left: 0; } .carousel-inner > .active.left { left: -100%; } .carousel-inner > .active.right { left: 100%; } .carousel-control { position: absolute; top: 0; bottom: 0; left: 0; width: 15%; font-size: 20px; color: #ffffff; text-align: center; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6); opacity: 0.5; filter: alpha(opacity=50); } .carousel-control.left { background-image: -webkit-gradient(linear, 0 top, 100% top, from(rgba(0, 0, 0, 0.5)), to(rgba(0, 0, 0, 0.0001))); background-image: -webkit-linear-gradient(left, color-stop(rgba(0, 0, 0, 0.5) 0), color-stop(rgba(0, 0, 0, 0.0001) 100%)); background-image: -moz-linear-gradient(left, rgba(0, 0, 0, 0.5) 0, rgba(0, 0, 0, 0.0001) 100%); background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5) 0, rgba(0, 0, 0, 0.0001) 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1); } .carousel-control.right { right: 0; left: auto; background-image: -webkit-gradient(linear, 0 top, 100% top, from(rgba(0, 0, 0, 0.0001)), to(rgba(0, 0, 0, 0.5))); background-image: -webkit-linear-gradient(left, color-stop(rgba(0, 0, 0, 0.0001) 0), color-stop(rgba(0, 0, 0, 0.5) 100%)); background-image: -moz-linear-gradient(left, rgba(0, 0, 0, 0.0001) 0, rgba(0, 0, 0, 0.5) 100%); background-image: linear-gradient(to right, rgba(0, 0, 0, 0.0001) 0, rgba(0, 0, 0, 0.5) 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1); } .carousel-control:hover, .carousel-control:focus { color: #ffffff; text-decoration: none; opacity: 0.9; filter: alpha(opacity=90); } .carousel-control .icon-prev, .carousel-control .icon-next, .carousel-control .glyphicon-chevron-left, .carousel-control .glyphicon-chevron-right { position: absolute; top: 50%; left: 50%; z-index: 5; display: inline-block; } .carousel-control .icon-prev, .carousel-control .icon-next { width: 20px; height: 20px; margin-top: -10px; margin-left: -10px; font-family: serif; } .carousel-control .icon-prev:before { content: '\2039'; } .carousel-control .icon-next:before { content: '\203a'; } .carousel-indicators { position: absolute; bottom: 10px; left: 50%; z-index: 15; width: 60%; padding-left: 0; margin-left: -30%; text-align: center; list-style: none; } .carousel-indicators li { display: inline-block; width: 10px; height: 10px; margin: 1px; text-indent: -999px; cursor: pointer; border: 1px solid #ffffff; border-radius: 10px; } .carousel-indicators .active { width: 12px; height: 12px; margin: 0; background-color: #ffffff; } .carousel-caption { position: absolute; right: 15%; bottom: 20px; left: 15%; z-index: 10; padding-top: 20px; padding-bottom: 20px; color: #ffffff; text-align: center; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6); } .carousel-caption .btn { text-shadow: none; } @media screen and (min-width: 768px) { .carousel-control .icon-prev, .carousel-control .icon-next { width: 30px; height: 30px; margin-top: -15px; margin-left: -15px; font-size: 30px; } .carousel-caption { right: 20%; left: 20%; padding-bottom: 30px; } .carousel-indicators { bottom: 20px; } } .clearfix:before, .clearfix:after { display: table; content: " "; } .clearfix:after { clear: both; } .clearfix:before, .clearfix:after { display: table; content: " "; } .clearfix:after { clear: both; } .pull-right { float: right !important; } .pull-left { float: left !important; } .hide { display: none !important; } .show { display: block !important; } .invisible { visibility: hidden; } .text-hide { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .affix { position: fixed; } @-ms-viewport { width: device-width; } @media screen and (max-width: 400px) { @-ms-viewport { width: 320px; } } .hidden { display: none !important; visibility: hidden !important; } .visible-xs { display: none !important; } tr.visible-xs { display: none !important; } th.visible-xs, td.visible-xs { display: none !important; } @media (max-width: 767px) { .visible-xs { display: block !important; } tr.visible-xs { display: table-row !important; } th.visible-xs, td.visible-xs { display: table-cell !important; } } @media (min-width: 768px) and (max-width: 991px) { .visible-xs.visible-sm { display: block !important; } tr.visible-xs.visible-sm { display: table-row !important; } th.visible-xs.visible-sm, td.visible-xs.visible-sm { display: table-cell !important; } } @media (min-width: 992px) and (max-width: 1199px) { .visible-xs.visible-md { display: block !important; } tr.visible-xs.visible-md { display: table-row !important; } th.visible-xs.visible-md, td.visible-xs.visible-md { display: table-cell !important; } } @media (min-width: 1200px) { .visible-xs.visible-lg { display: block !important; } tr.visible-xs.visible-lg { display: table-row !important; } th.visible-xs.visible-lg, td.visible-xs.visible-lg { display: table-cell !important; } } .visible-sm { display: none !important; } tr.visible-sm { display: none !important; } th.visible-sm, td.visible-sm { display: none !important; } @media (max-width: 767px) { .visible-sm.visible-xs { display: block !important; } tr.visible-sm.visible-xs { display: table-row !important; } th.visible-sm.visible-xs, td.visible-sm.visible-xs { display: table-cell !important; } } @media (min-width: 768px) and (max-width: 991px) { .visible-sm { display: block !important; } tr.visible-sm { display: table-row !important; } th.visible-sm, td.visible-sm { display: table-cell !important; } } @media (min-width: 992px) and (max-width: 1199px) { .visible-sm.visible-md { display: block !important; } tr.visible-sm.visible-md { display: table-row !important; } th.visible-sm.visible-md, td.visible-sm.visible-md { display: table-cell !important; } } @media (min-width: 1200px) { .visible-sm.visible-lg { display: block !important; } tr.visible-sm.visible-lg { display: table-row !important; } th.visible-sm.visible-lg, td.visible-sm.visible-lg { display: table-cell !important; } } .visible-md { display: none !important; } tr.visible-md { display: none !important; } th.visible-md, td.visible-md { display: none !important; } @media (max-width: 767px) { .visible-md.visible-xs { display: block !important; } tr.visible-md.visible-xs { display: table-row !important; } th.visible-md.visible-xs, td.visible-md.visible-xs { display: table-cell !important; } } @media (min-width: 768px) and (max-width: 991px) { .visible-md.visible-sm { display: block !important; } tr.visible-md.visible-sm { display: table-row !important; } th.visible-md.visible-sm, td.visible-md.visible-sm { display: table-cell !important; } } @media (min-width: 992px) and (max-width: 1199px) { .visible-md { display: block !important; } tr.visible-md { display: table-row !important; } th.visible-md, td.visible-md { display: table-cell !important; } } @media (min-width: 1200px) { .visible-md.visible-lg { display: block !important; } tr.visible-md.visible-lg { display: table-row !important; } th.visible-md.visible-lg, td.visible-md.visible-lg { display: table-cell !important; } } .visible-lg { display: none !important; } tr.visible-lg { display: none !important; } th.visible-lg, td.visible-lg { display: none !important; } @media (max-width: 767px) { .visible-lg.visible-xs { display: block !important; } tr.visible-lg.visible-xs { display: table-row !important; } th.visible-lg.visible-xs, td.visible-lg.visible-xs { display: table-cell !important; } } @media (min-width: 768px) and (max-width: 991px) { .visible-lg.visible-sm { display: block !important; } tr.visible-lg.visible-sm { display: table-row !important; } th.visible-lg.visible-sm, td.visible-lg.visible-sm { display: table-cell !important; } } @media (min-width: 992px) and (max-width: 1199px) { .visible-lg.visible-md { display: block !important; } tr.visible-lg.visible-md { display: table-row !important; } th.visible-lg.visible-md, td.visible-lg.visible-md { display: table-cell !important; } } @media (min-width: 1200px) { .visible-lg { display: block !important; } tr.visible-lg { display: table-row !important; } th.visible-lg, td.visible-lg { display: table-cell !important; } } .hidden-xs { display: block !important; } tr.hidden-xs { display: table-row !important; } th.hidden-xs, td.hidden-xs { display: table-cell !important; } @media (max-width: 767px) { .hidden-xs { display: none !important; } tr.hidden-xs { display: none !important; } th.hidden-xs, td.hidden-xs { display: none !important; } } @media (min-width: 768px) and (max-width: 991px) { .hidden-xs.hidden-sm { display: none !important; } tr.hidden-xs.hidden-sm { display: none !important; } th.hidden-xs.hidden-sm, td.hidden-xs.hidden-sm { display: none !important; } } @media (min-width: 992px) and (max-width: 1199px) { .hidden-xs.hidden-md { display: none !important; } tr.hidden-xs.hidden-md { display: none !important; } th.hidden-xs.hidden-md, td.hidden-xs.hidden-md { display: none !important; } } @media (min-width: 1200px) { .hidden-xs.hidden-lg { display: none !important; } tr.hidden-xs.hidden-lg { display: none !important; } th.hidden-xs.hidden-lg, td.hidden-xs.hidden-lg { display: none !important; } } .hidden-sm { display: block !important; } tr.hidden-sm { display: table-row !important; } th.hidden-sm, td.hidden-sm { display: table-cell !important; } @media (max-width: 767px) { .hidden-sm.hidden-xs { display: none !important; } tr.hidden-sm.hidden-xs { display: none !important; } th.hidden-sm.hidden-xs, td.hidden-sm.hidden-xs { display: none !important; } } @media (min-width: 768px) and (max-width: 991px) { .hidden-sm { display: none !important; } tr.hidden-sm { display: none !important; } th.hidden-sm, td.hidden-sm { display: none !important; } } @media (min-width: 992px) and (max-width: 1199px) { .hidden-sm.hidden-md { display: none !important; } tr.hidden-sm.hidden-md { display: none !important; } th.hidden-sm.hidden-md, td.hidden-sm.hidden-md { display: none !important; } } @media (min-width: 1200px) { .hidden-sm.hidden-lg { display: none !important; } tr.hidden-sm.hidden-lg { display: none !important; } th.hidden-sm.hidden-lg, td.hidden-sm.hidden-lg { display: none !important; } } .hidden-md { display: block !important; } tr.hidden-md { display: table-row !important; } th.hidden-md, td.hidden-md { display: table-cell !important; } @media (max-width: 767px) { .hidden-md.hidden-xs { display: none !important; } tr.hidden-md.hidden-xs { display: none !important; } th.hidden-md.hidden-xs, td.hidden-md.hidden-xs { display: none !important; } } @media (min-width: 768px) and (max-width: 991px) { .hidden-md.hidden-sm { display: none !important; } tr.hidden-md.hidden-sm { display: none !important; } th.hidden-md.hidden-sm, td.hidden-md.hidden-sm { display: none !important; } } @media (min-width: 992px) and (max-width: 1199px) { .hidden-md { display: none !important; } tr.hidden-md { display: none !important; } th.hidden-md, td.hidden-md { display: none !important; } } @media (min-width: 1200px) { .hidden-md.hidden-lg { display: none !important; } tr.hidden-md.hidden-lg { display: none !important; } th.hidden-md.hidden-lg, td.hidden-md.hidden-lg { display: none !important; } } .hidden-lg { display: block !important; } tr.hidden-lg { display: table-row !important; } th.hidden-lg, td.hidden-lg { display: table-cell !important; } @media (max-width: 767px) { .hidden-lg.hidden-xs { display: none !important; } tr.hidden-lg.hidden-xs { display: none !important; } th.hidden-lg.hidden-xs, td.hidden-lg.hidden-xs { display: none !important; } } @media (min-width: 768px) and (max-width: 991px) { .hidden-lg.hidden-sm { display: none !important; } tr.hidden-lg.hidden-sm { display: none !important; } th.hidden-lg.hidden-sm, td.hidden-lg.hidden-sm { display: none !important; } } @media (min-width: 992px) and (max-width: 1199px) { .hidden-lg.hidden-md { display: none !important; } tr.hidden-lg.hidden-md { display: none !important; } th.hidden-lg.hidden-md, td.hidden-lg.hidden-md { display: none !important; } } @media (min-width: 1200px) { .hidden-lg { display: none !important; } tr.hidden-lg { display: none !important; } th.hidden-lg, td.hidden-lg { display: none !important; } } .visible-print { display: none !important; } tr.visible-print { display: none !important; } th.visible-print, td.visible-print { display: none !important; } @media print { .visible-print { display: block !important; } tr.visible-print { display: table-row !important; } th.visible-print, td.visible-print { display: table-cell !important; } .hidden-print { display: none !important; } tr.hidden-print { display: none !important; } th.hidden-print, td.hidden-print { display: none !important; } } .navbar { text-shadow: 0 1px 0 rgba(255, 255, 255, 0.3); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), color-stop(50%, #eeeeee), to(#e4e4e4)); background-image: -webkit-linear-gradient(#ffffff, #eeeeee 50%, #e4e4e4); background-image: -moz-linear-gradient(top, #ffffff, #eeeeee 50%, #e4e4e4); background-image: linear-gradient(#ffffff, #eeeeee 50%, #e4e4e4); background-repeat: no-repeat; border: 1px solid #d5d5d5; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe4e4e4', GradientType=0); filter: none; } .navbar-inverse { text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#6d94bf), color-stop(50%, #446e9b), to(#3e648d)); background-image: -webkit-linear-gradient(#6d94bf, #446e9b 50%, #3e648d); background-image: -moz-linear-gradient(top, #6d94bf, #446e9b 50%, #3e648d); background-image: linear-gradient(#6d94bf, #446e9b 50%, #3e648d); background-repeat: no-repeat; border: 1px solid #345578; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff6d94bf', endColorstr='#ff3e648d', GradientType=0); filter: none; } .navbar-nav > li > a, .navbar-nav > li > a:hover { padding-top: 17px; padding-bottom: 13px; -webkit-transition: color ease-in-out 0.2s; transition: color ease-in-out 0.2s; } .navbar-brand, .navbar-brand:hover { -webkit-transition: color ease-in-out 0.2s; transition: color ease-in-out 0.2s; } .navbar .caret, .navbar .caret:hover { -webkit-transition: border-color ease-in-out 0.2s; transition: border-color ease-in-out 0.2s; } .navbar .dropdown-menu { text-shadow: none; } .btn { text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3); } .btn-default, .btn-default:hover { background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#6d7070), color-stop(50%, #474949), to(#3d3f3f)); background-image: -webkit-linear-gradient(#6d7070, #474949 50%, #3d3f3f); background-image: -moz-linear-gradient(top, #6d7070, #474949 50%, #3d3f3f); background-image: linear-gradient(#6d7070, #474949 50%, #3d3f3f); background-repeat: no-repeat; border: 1px solid #2e2f2f; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff6d7070', endColorstr='#ff3d3f3f', GradientType=0); } .btn-primary, .btn-primary:hover { background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#6d94bf), color-stop(50%, #446e9b), to(#3e648d)); background-image: -webkit-linear-gradient(#6d94bf, #446e9b 50%, #3e648d); background-image: -moz-linear-gradient(top, #6d94bf, #446e9b 50%, #3e648d); background-image: linear-gradient(#6d94bf, #446e9b 50%, #3e648d); background-repeat: no-repeat; border: 1px solid #345578; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff6d94bf', endColorstr='#ff3e648d', GradientType=0); } .btn-success, .btn-success:hover { background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#61dd45), color-stop(50%, #3cb521), to(#36a41e)); background-image: -webkit-linear-gradient(#61dd45, #3cb521 50%, #36a41e); background-image: -moz-linear-gradient(top, #61dd45, #3cb521 50%, #36a41e); background-image: linear-gradient(#61dd45, #3cb521 50%, #36a41e); background-repeat: no-repeat; border: 1px solid #2e8a19; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff61dd45', endColorstr='#ff36a41e', GradientType=0); } .btn-info, .btn-info:hover { background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#7bbdf7), color-stop(50%, #3399f3), to(#208ff2)); background-image: -webkit-linear-gradient(#7bbdf7, #3399f3 50%, #208ff2); background-image: -moz-linear-gradient(top, #7bbdf7, #3399f3 50%, #208ff2); background-image: linear-gradient(#7bbdf7, #3399f3 50%, #208ff2); background-repeat: no-repeat; border: 1px solid #0e80e5; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff7bbdf7', endColorstr='#ff208ff2', GradientType=0); } .btn-warning, .btn-warning:hover { background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ff9c21), color-stop(50%, #d47500), to(#c06a00)); background-image: -webkit-linear-gradient(#ff9c21, #d47500 50%, #c06a00); background-image: -moz-linear-gradient(top, #ff9c21, #d47500 50%, #c06a00); background-image: linear-gradient(#ff9c21, #d47500 50%, #c06a00); background-repeat: no-repeat; border: 1px solid #a15900; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff9c21', endColorstr='#ffc06a00', GradientType=0); } .btn-danger, .btn-danger:hover { background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ff1d1b), color-stop(50%, #cd0200), to(#b90200)); background-image: -webkit-linear-gradient(#ff1d1b, #cd0200 50%, #b90200); background-image: -moz-linear-gradient(top, #ff1d1b, #cd0200 50%, #b90200); background-image: linear-gradient(#ff1d1b, #cd0200 50%, #b90200); background-repeat: no-repeat; border: 1px solid #9a0200; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff1d1b', endColorstr='#ffb90200', GradientType=0); } h1, h2, h3, h4, h5, h6 { color: #2d2d2d; } .pagination .active > a, .pagination .active > a:hover { border-color: #ddd; } .clearfix:before, .clearfix:after { display: table; content: " "; } .clearfix:after { clear: both; } .clearfix:before, .clearfix:after { display: table; content: " "; } .clearfix:after { clear: both; } .pull-right { float: right !important; } .pull-left { float: left !important; } .hide { display: none !important; } .show { display: block !important; } .invisible { visibility: hidden; } .text-hide { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .affix { position: fixed; }
samukasmk/django_dashboard_example
smkcpanel_django/smkcpanel/static/bootstrap/extra/bootswatch/spacelab/css/bootstrap.css
CSS
apache-2.0
131,169
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ module.exports = angular.module('trafficPortal.private.tenants.deliveryServices', []) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('trafficPortal.private.tenants.deliveryServices', { url: '/{tenantId}/delivery-services?all', views: { tenantsContent: { templateUrl: 'common/modules/table/tenantDeliveryServices/table.tenantDeliveryServices.tpl.html', controller: 'TableTenantDeliveryServicesController', resolve: { tenant: function($stateParams, tenantService) { return tenantService.getTenant($stateParams.tenantId); }, deliveryServices: function($stateParams, tenant, deliveryServiceService) { if ($stateParams.all && $stateParams.all === 'true') { return deliveryServiceService.getDeliveryServices({ accessibleTo: tenant.id }); } return deliveryServiceService.getDeliveryServices({ tenant: tenant.id }); }, filter: function($stateParams, tenant) { if ($stateParams.all && $stateParams.all === 'true') { return null; } return { tenant: { filterType: "text", type: "equals", filter: tenant.name } } } } } } }) ; $urlRouterProvider.otherwise('/'); });
hbeatty/incubator-trafficcontrol
traffic_portal/app/src/modules/private/tenants/deliveryServices/index.js
JavaScript
apache-2.0
2,124
package hex.kmeans; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import water.TestUtil; import water.fvec.Frame; import water.util.Log; import java.util.Random; public class KMeansRandomTest extends TestUtil { @BeforeClass() public static void setup() { stall_till_cloudsize(1); } @Test public void run() { long seed = 0xDECAF; Random rng = new Random(seed); String[] datasets = new String[2]; datasets[0] = "smalldata/logreg/prostate.csv"; datasets[1] = "smalldata/iris/iris_wheader.csv"; int testcount = 0; int count = 0; for( String dataset : datasets ) { Frame frame = parse_test_file(dataset); try { for (int centers : new int[]{2, 10, 100}) { for (int max_iter : new int[]{1, 10, 100}) { for (boolean standardize : new boolean[]{false, true}) { for (KMeans.Initialization init : new KMeans.Initialization[]{ KMeans.Initialization.Random, KMeans.Initialization.Furthest, KMeans.Initialization.PlusPlus, }) { count++; KMeansModel.KMeansParameters parms = new KMeansModel.KMeansParameters(); parms._train = frame._key; if(dataset != null && dataset.equals("smalldata/iris/iris_wheader.csv")) parms._ignored_columns = new String[] {"class"}; parms._k = centers; parms._seed = rng.nextLong(); parms._max_iterations = max_iter; parms._standardize = standardize; parms._init = init; KMeans job = new KMeans(parms); KMeansModel m = job.trainModel().get(); Assert.assertTrue("Progress not 100%, but " + job.progress() *100, job.progress() == 1.0); Frame score = null; try { for (int j = 0; j < parms._k; j++) Assert.assertTrue(m._output._size[j] != 0); Assert.assertTrue(m._output._iterations <= max_iter); for (double d : m._output._withinss) Assert.assertFalse(Double.isNaN(d)); Assert.assertFalse(Double.isNaN(m._output._tot_withinss)); for (long o : m._output._size) Assert.assertTrue(o > 0); //have at least one point per centroid for (double[] dc : m._output._centers_raw) for (double d : dc) Assert.assertFalse(Double.isNaN(d)); // make prediction (cluster assignment) score = m.score(frame); for (long j = 0; j < score.numRows(); ++j) Assert.assertTrue(score.anyVec().at8(j) >= 0 && score.anyVec().at8(j) < centers); Log.info("Parameters combination " + count + ": PASS"); testcount++; } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } finally { m.delete(); if (score!=null) score.delete(); job.remove(); } } } } } } finally { frame.delete(); } } Log.info("\n\n============================================="); Log.info("Tested " + testcount + " out of " + count + " parameter combinations."); Log.info("============================================="); } }
weaver-viii/h2o-3
h2o-algos/src/test/java/hex/kmeans/KMeansRandomTest.java
Java
apache-2.0
3,514
/** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version * 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package org.apache.storm.trident.topology; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import org.apache.storm.Config; import org.apache.storm.spout.SpoutOutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichSpout; import org.apache.storm.trident.spout.ITridentSpout; import org.apache.storm.trident.topology.state.TransactionalState; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Values; import org.apache.storm.utils.WindowedTimeThrottler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MasterBatchCoordinator extends BaseRichSpout { public static final Logger LOG = LoggerFactory.getLogger(MasterBatchCoordinator.class); public static final long INIT_TXID = 1L; public static final String BATCH_STREAM_ID = "$batch"; public static final String COMMIT_STREAM_ID = "$commit"; public static final String SUCCESS_STREAM_ID = "$success"; private static final String CURRENT_TX = "currtx"; private static final String CURRENT_ATTEMPTS = "currattempts"; TreeMap<Long, TransactionStatus> activeTx = new TreeMap<Long, TransactionStatus>(); TreeMap<Long, Integer> attemptIds; Long currTransaction; int maxTransactionActive; List<ITridentSpout.BatchCoordinator> coordinators = new ArrayList(); List<String> managedSpoutIds; List<ITridentSpout> spouts; WindowedTimeThrottler throttler; boolean active = true; private List<TransactionalState> states = new ArrayList(); private SpoutOutputCollector collector; public MasterBatchCoordinator(List<String> spoutIds, List<ITridentSpout> spouts) { if (spoutIds.isEmpty()) { throw new IllegalArgumentException("Must manage at least one spout"); } managedSpoutIds = spoutIds; this.spouts = spouts; LOG.debug("Created {}", this); } public List<String> getManagedSpoutIds() { return managedSpoutIds; } @Override public void activate() { active = true; } @Override public void deactivate() { active = false; } @Override public void open(Map<String, Object> conf, TopologyContext context, SpoutOutputCollector collector) { throttler = new WindowedTimeThrottler((Number) conf.get(Config.TOPOLOGY_TRIDENT_BATCH_EMIT_INTERVAL_MILLIS), 1); for (String spoutId : managedSpoutIds) { states.add(TransactionalState.newCoordinatorState(conf, spoutId)); } currTransaction = getStoredCurrTransaction(); this.collector = collector; Number active = (Number) conf.get(Config.TOPOLOGY_MAX_SPOUT_PENDING); if (active == null) { maxTransactionActive = 1; } else { maxTransactionActive = active.intValue(); } attemptIds = getStoredCurrAttempts(currTransaction, maxTransactionActive); for (int i = 0; i < spouts.size(); i++) { String txId = managedSpoutIds.get(i); coordinators.add(spouts.get(i).getCoordinator(txId, conf, context)); } LOG.debug("Opened {}", this); } @Override public void close() { for (TransactionalState state : states) { state.close(); } LOG.debug("Closed {}", this); } @Override public void nextTuple() { sync(); } @Override public void ack(Object msgId) { TransactionAttempt tx = (TransactionAttempt) msgId; TransactionStatus status = activeTx.get(tx.getTransactionId()); LOG.debug("Ack. [tx_attempt = {}], [tx_status = {}], [{}]", tx, status, this); if (status != null && tx.equals(status.attempt)) { if (status.status == AttemptStatus.PROCESSING) { status.status = AttemptStatus.PROCESSED; LOG.debug("Changed status. [tx_attempt = {}] [tx_status = {}]", tx, status); } else if (status.status == AttemptStatus.COMMITTING) { activeTx.remove(tx.getTransactionId()); attemptIds.remove(tx.getTransactionId()); collector.emit(SUCCESS_STREAM_ID, new Values(tx)); currTransaction = nextTransactionId(tx.getTransactionId()); for (TransactionalState state : states) { state.setData(CURRENT_TX, currTransaction); } LOG.debug("Emitted on [stream = {}], [tx_attempt = {}], [tx_status = {}], [{}]", SUCCESS_STREAM_ID, tx, status, this); } sync(); } } @Override public void fail(Object msgId) { TransactionAttempt tx = (TransactionAttempt) msgId; TransactionStatus stored = activeTx.remove(tx.getTransactionId()); LOG.debug("Fail. [tx_attempt = {}], [tx_status = {}], [{}]", tx, stored, this); if (stored != null && tx.equals(stored.attempt)) { activeTx.tailMap(tx.getTransactionId()).clear(); sync(); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { // in partitioned example, in case an emitter task receives a later transaction than it's emitted so far, // when it sees the earlier txid it should know to emit nothing declarer.declareStream(BATCH_STREAM_ID, new Fields("tx")); declarer.declareStream(COMMIT_STREAM_ID, new Fields("tx")); declarer.declareStream(SUCCESS_STREAM_ID, new Fields("tx")); } private void sync() { // note that sometimes the tuples active may be less than max_spout_pending, e.g. // max_spout_pending = 3 // tx 1, 2, 3 active, tx 2 is acked. there won't be a commit for tx 2 (because tx 1 isn't committed yet), // and there won't be a batch for tx 4 because there's max_spout_pending tx active TransactionStatus maybeCommit = activeTx.get(currTransaction); if (maybeCommit != null && maybeCommit.status == AttemptStatus.PROCESSED) { maybeCommit.status = AttemptStatus.COMMITTING; collector.emit(COMMIT_STREAM_ID, new Values(maybeCommit.attempt), maybeCommit.attempt); LOG.debug("Emitted on [stream = {}], [tx_status = {}], [{}]", COMMIT_STREAM_ID, maybeCommit, this); } if (active) { if (activeTx.size() < maxTransactionActive) { Long curr = currTransaction; for (int i = 0; i < maxTransactionActive; i++) { if (!activeTx.containsKey(curr) && isReady(curr)) { // by using a monotonically increasing attempt id, downstream tasks // can be memory efficient by clearing out state for old attempts // as soon as they see a higher attempt id for a transaction Integer attemptId = attemptIds.get(curr); if (attemptId == null) { attemptId = 0; } else { attemptId++; } attemptIds.put(curr, attemptId); for (TransactionalState state : states) { state.setData(CURRENT_ATTEMPTS, attemptIds); } TransactionAttempt attempt = new TransactionAttempt(curr, attemptId); final TransactionStatus newTransactionStatus = new TransactionStatus(attempt); activeTx.put(curr, newTransactionStatus); collector.emit(BATCH_STREAM_ID, new Values(attempt), attempt); LOG.debug("Emitted on [stream = {}], [tx_attempt = {}], [tx_status = {}], [{}]", BATCH_STREAM_ID, attempt, newTransactionStatus, this); throttler.markEvent(); } curr = nextTransactionId(curr); } } } } private boolean isReady(long txid) { if (throttler.isThrottled()) { return false; } //TODO: make this strategy configurable?... right now it goes if anyone is ready for (ITridentSpout.BatchCoordinator coord : coordinators) { if (coord.isReady(txid)) { return true; } } return false; } @Override public Map<String, Object> getComponentConfiguration() { Config ret = new Config(); ret.setMaxTaskParallelism(1); ret.registerSerialization(TransactionAttempt.class); return ret; } private Long nextTransactionId(Long id) { return id + 1; } private Long getStoredCurrTransaction() { Long ret = INIT_TXID; for (TransactionalState state : states) { Long curr = (Long) state.getData(CURRENT_TX); if (curr != null && curr.compareTo(ret) > 0) { ret = curr; } } return ret; } private TreeMap<Long, Integer> getStoredCurrAttempts(long currTransaction, int maxBatches) { TreeMap<Long, Integer> ret = new TreeMap<Long, Integer>(); for (TransactionalState state : states) { Map<Object, Number> attempts = (Map) state.getData(CURRENT_ATTEMPTS); if (attempts == null) { attempts = new HashMap(); } for (Entry<Object, Number> e : attempts.entrySet()) { // this is because json doesn't allow numbers as keys... // TODO: replace json with a better form of encoding Number txidObj; if (e.getKey() instanceof String) { txidObj = Long.parseLong((String) e.getKey()); } else { txidObj = (Number) e.getKey(); } long txid = ((Number) txidObj).longValue(); int attemptId = ((Number) e.getValue()).intValue(); Integer curr = ret.get(txid); if (curr == null || attemptId > curr) { ret.put(txid, attemptId); } } } ret.headMap(currTransaction).clear(); ret.tailMap(currTransaction + maxBatches - 1).clear(); return ret; } @Override public String toString() { return "MasterBatchCoordinator{" + "states=" + states + ", activeTx=" + activeTx + ", attemptIds=" + attemptIds + ", collector=" + collector + ", currTransaction=" + currTransaction + ", maxTransactionActive=" + maxTransactionActive + ", coordinators=" + coordinators + ", managedSpoutIds=" + managedSpoutIds + ", spouts=" + spouts + ", throttler=" + throttler + ", active=" + active + "}"; } private enum AttemptStatus { PROCESSING, PROCESSED, COMMITTING } private static class TransactionStatus { TransactionAttempt attempt; AttemptStatus status; TransactionStatus(TransactionAttempt attempt) { this.attempt = attempt; this.status = AttemptStatus.PROCESSING; } @Override public String toString() { return attempt.toString() + " <" + status.toString() + ">"; } } }
kishorvpatil/incubator-storm
storm-client/src/jvm/org/apache/storm/trident/topology/MasterBatchCoordinator.java
Java
apache-2.0
12,435
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.rt.execution.junit; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Clone of GeneralCommandLine. */ public class ProcessBuilder { public static final boolean isWindows = isWindows(); private static boolean isWindows() { try { return System.getProperty("os.name").toLowerCase().startsWith("windows"); } catch (SecurityException e) { return false; } } private static final String WIN_SHELL_SPECIALS = "&<>()@^|"; private final List myParameters = new ArrayList(); private File myWorkingDir = null; public void add(final String parameter) { myParameters.add(parameter); } public void add(final List parameters) { for (int i = 0; i < parameters.size(); i++) { add((String)parameters.get(i)); } } public void setWorkingDir(File workingDir) { myWorkingDir = workingDir; } // please keep an implementation in sync with [util] CommandLineUtil.toCommandLine() public Process createProcess() throws IOException { if (myParameters.size() < 1) { throw new IllegalArgumentException("Executable name not specified"); } String command = myParameters.get(0).toString(); boolean winShell = isWindows && isWinShell(command); String[] commandLine = new String[myParameters.size()]; commandLine[0] = command; for (int i = 1; i < myParameters.size(); i++) { String parameter = myParameters.get(i).toString(); if (isWindows) { int pos = parameter.indexOf('\"'); if (pos >= 0) { StringBuffer buffer = new StringBuffer(parameter); do { buffer.insert(pos, '\\'); pos += 2; } while ((pos = parameter.indexOf('\"', pos)) >= 0); parameter = buffer.toString(); } else if (parameter.length() == 0) { parameter = "\"\""; } if (winShell && containsAnyChar(parameter, WIN_SHELL_SPECIALS)) { parameter = '"' + parameter + '"'; } } commandLine[i] = parameter; } return Runtime.getRuntime().exec(commandLine, null, myWorkingDir); } private static boolean isWinShell(String command) { return endsWithIgnoreCase(command, ".cmd") || endsWithIgnoreCase(command, ".bat") || "cmd".equalsIgnoreCase(command) || "cmd.exe".equalsIgnoreCase(command); } private static boolean endsWithIgnoreCase(String str, String suffix) { return str.regionMatches(true, str.length() - suffix.length(), suffix, 0, suffix.length()); } private static boolean containsAnyChar(String value, String chars) { for (int i = 0; i < value.length(); i++) { if (chars.indexOf(value.charAt(i)) >= 0) { return true; } } return false; } }
Lekanich/intellij-community
plugins/junit_rt/src/com/intellij/rt/execution/junit/ProcessBuilder.java
Java
apache-2.0
3,422
package org.xtuml.bp.core.test; import org.xtuml.bp.test.GlobalsTestEnabler; public class SystemLevelGlobalsTest extends GlobalsTestEnabler { public SystemLevelGlobalsTest(){ super(null, null); } }
jason-rhodes/bridgepoint
src/org.xtuml.bp.core.test/src/org/xtuml/bp/core/test/SystemLevelGlobalsTest.java
Java
apache-2.0
215