text:
require 'devise_security_extension/hooks/session_traceable'

module Devise
  module Models
    # SessionTraceable takes care of session trail in every authentication.
    # When a session expires after expiring the +token+, the user
    # will be asked for credentials again, it means, he/she will be redirected
    # to the sign in page.
    #
    # == Options
    #
    # SessionTraceable adds the following options to devise_for:
    #
    #   * +session_traceable_class+: to override +session_histories+ class.
    #
    # == Examples
    #
    #   user.log_traceable_request!
    #
    module SessionTraceable
      extend ActiveSupport::Concern

      included do
        has_many :session_histories, as: :session_traceable,
                                     class_name: session_traceable_class, dependent: :destroy
      end

      def self.required_fields(_klass)
        %i(session_traceable_class paranoid_ip_verification)
      end

      # Create new traceable session
      #
      def log_traceable_request!(options = {})
        token = generate_traceable_token
        opts = options.merge unique_auth_token_id: token, last_accessed_at: Time.current.utc
        opts = session_traceable_condition(opts)
        session_traceable_adapter.create!(opts) && token
      rescue StandardError
        false
      end

      # Check if +token+ is valid
      #
      def accept_traceable_token?(token, options = {})
        opts = options.merge unique_auth_token_valid: true
        if paranoid_ip_verification
          opts[:ip_address] ||= nil
        else
          opts.delete(:ip_address)
        end
        find_traceable_by_token(token, opts).present?
      end

      # Update the `:last_accessed_at` to current time.
      #
      def update_traceable_token(token)
        record = find_traceable_by_token(token)
        record.last_accessed_at = Time.current.utc
        record.save(validate: false)
      end

      # Expire session matching the +token+
      # by setting `:unique_auth_token_valid` to false.
      #
      def expire_session_token(token)
        record = find_traceable_by_token(token)
        return unless record
        record.unique_auth_token_valid = false
        record.save(validate: false)
      end

      # Find the first instance, matching +token+, and optional +options+.
      #
      def find_traceable_by_token(token, options = {})
        opts = options.merge unique_auth_token_id: token
        opts = session_traceable_condition(opts)
        session_traceable_adapter.find_first opts
      end

      def paranoid_ip_verification
        self.class.paranoid_ip_verification
      end

      private

      def generate_traceable_token
        loop do
          token = Devise.friendly_token
          break token if find_traceable_by_token(token).blank?
        end
      end

      def session_traceable_adapter
        self.class.session_traceable_class.constantize.to_adapter
      end

      def session_traceable_condition(options = {})
        options.deep_merge session_traceable: self
      end

      module ClassMethods
        ::Devise::Models.config(self, :session_traceable_class, :paranoid_ip_verification)
      end
    end
  end
end


text:
package gov.hhs.fha.nhinc.notify.adapter.proxy;

import gov.hhs.fha.nhinc.adapternotificationconsumersecured.AdapterNotificationConsumerPortSecureType;
import gov.hhs.fha.nhinc.common.nhinccommon.AcknowledgementType;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.hiem.consumerreference.ReferenceParametersHelper;
import gov.hhs.fha.nhinc.hiem.consumerreference.SoapMessageElements;
import gov.hhs.fha.nhinc.hiem.dte.marshallers.NhincCommonAcknowledgementMarshaller;
import gov.hhs.fha.nhinc.hiem.dte.marshallers.WsntSubscribeMarshaller;
import gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory;
import gov.hhs.fha.nhinc.messaging.client.CONNECTClient;
import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.nhinclib.NullChecker;
import gov.hhs.fha.nhinc.notify.adapter.proxy.service.HiemNotifyAdapterSecuredServicePortDescriptor;
import gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper;

import org.apache.log4j.Logger;
import org.oasis_open.docs.wsn.b_2.Notify;
import org.w3c.dom.Element;

/**
 *
 * @author Jon Hoppesch
 */
public class HiemNotifyAdapterWebServiceProxySecured implements HiemNotifyAdapterProxy {

    private static final Logger LOG = Logger.getLogger(HiemNotifyAdapterWebServiceProxySecured.class);
    private static WebServiceProxyHelper oProxyHelper = null;

    public Element notify(Element notifyElement, SoapMessageElements referenceParametersElements,
            AssertionType assertion, NhinTargetSystemType target) throws Exception {
        Element responseElement = null;

        String url = getWebServiceProxyHelper().getAdapterEndPointFromConnectionManager(
                NhincConstants.HIEM_NOTIFY_ADAPTER_SERVICE_SECURED_NAME);
        if (NullChecker.isNotNullish(url)) {
            WsntSubscribeMarshaller subscribeMarshaller = new WsntSubscribeMarshaller();
            Notify notify = subscribeMarshaller.unmarshalNotifyRequest(notifyElement);

            String wsAddressingTo = ReferenceParametersHelper.getWsAddressingTo(referenceParametersElements);
            if (wsAddressingTo == null) {
                wsAddressingTo = url;
            }

            HiemNotifyAdapterSecuredServicePortDescriptor portDescriptor = new HiemNotifyAdapterSecuredServicePortDescriptor();

            CONNECTClient<AdapterNotificationConsumerPortSecureType> client = getCONNECTClientSecured(portDescriptor,
                    url, assertion, wsAddressingTo);

            AcknowledgementType response = (AcknowledgementType) client.invokePort(
                    AdapterNotificationConsumerPortSecureType.class, "notify", notify);

            NhincCommonAcknowledgementMarshaller acknowledgementMarshaller = new NhincCommonAcknowledgementMarshaller();
            responseElement = acknowledgementMarshaller.marshal(response);
        } else {
            LOG.error("Failed to call the web service (" + NhincConstants.HIEM_NOTIFY_ADAPTER_SERVICE_SECURED_NAME
                    + ").  The URL is null.");
        }

        return responseElement;
    }

    public Element notifySubscribersOfDocument(Element docNotify, AssertionType assertion, NhinTargetSystemType target)
            throws Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Element notifySubscribersOfCdcBioPackage(Element cdcNotify, AssertionType assertion,
            NhinTargetSystemType target) throws Exception {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    protected CONNECTClient<AdapterNotificationConsumerPortSecureType> getCONNECTClientSecured(
            ServicePortDescriptor<AdapterNotificationConsumerPortSecureType> portDescriptor, String url,
            AssertionType assertion, String wsAddressingTo) {

        return CONNECTCXFClientFactory.getInstance().getCONNECTClientSecured(portDescriptor, url, assertion,
                wsAddressingTo, null);
    }

    protected WebServiceProxyHelper getWebServiceProxyHelper() {
        if (oProxyHelper == null) {
            oProxyHelper = new WebServiceProxyHelper();
        }
        return oProxyHelper;
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Microsoft.CodeAnalysis
{
    /// <summary>
    /// Internal representation of an incremental output
    /// </summary>
    internal interface IIncrementalGeneratorOutputNode
    {
        IncrementalGeneratorOutputKind Kind { get; }

        void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken);
    }

    /// <summary>
    /// Represents the various output kinds of an <see cref="IIncrementalGenerator"/>.
    /// </summary>
    /// <remarks>
    /// Can be passed as a bit field when creating a <see cref="GeneratorDriver"/> to selectively disable outputs.
    /// </remarks>
    [Flags]
    public enum IncrementalGeneratorOutputKind
    {
        /// <summary>
        /// Represents no output kinds. Can be used when creating a driver to indicate that no outputs should be disabled.
        /// </summary>
        None = 0,

        /// <summary>
        /// A regular source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/>
        /// or <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/>
        /// </summary>
        Source = 0b1,

        /// <summary>
        /// A post-initialization output, which will be visible to later phases, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/>
        /// </summary>
        PostInit = 0b10,

        /// <summary>
        /// An Implementation only source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/>
        /// or <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/>
        /// </summary>
        Implementation = 0b100
    }
}


text:
package org.qi4j.runtime.appliesto;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import org.junit.Test;
import org.qi4j.api.common.AppliesTo;
import org.qi4j.api.common.Optional;
import org.qi4j.api.concern.ConcernOf;
import org.qi4j.api.concern.Concerns;
import org.qi4j.api.injection.InjectionScope;
import org.qi4j.api.injection.scope.Invocation;
import org.qi4j.api.injection.scope.This;
import org.qi4j.api.mixin.Mixins;
import org.qi4j.api.service.ServiceComposite;
import org.qi4j.api.service.ServiceReference;
import org.qi4j.api.unitofwork.UnitOfWork;
import org.qi4j.bootstrap.AssemblyException;
import org.qi4j.bootstrap.ModuleAssembly;
import org.qi4j.test.AbstractQi4jTest;

import static org.junit.Assert.assertTrue;

public class AppliesToOrConditionQI241Test
    extends AbstractQi4jTest
{

    public void assemble( ModuleAssembly module )
        throws AssemblyException
    {
        module.services( SomeServiceCompositeWithTwoAnnotations.class );
        module.services( SomeServiceCompositeWithFirstAnnotation.class );
        module.services( SomeServiceCompositeWithSecondAnnotation.class );
    }

    @Test
    public void testMultiConcerns1()
    {
        UnitOfWork uow = module.newUnitOfWork();

        try
        {
            ServiceReference<SomeServiceCompositeWithFirstAnnotation> refWithFirst = module.findService(
                SomeServiceCompositeWithFirstAnnotation.class );
            SomeServiceCompositeWithFirstAnnotation someWithFirst = refWithFirst.get();
            someWithFirst.doStuff();
            assertTrue( "AppliesTo did not match with first annotation", someWithFirst.concernHasBeenPlayed() );
        }
        finally
        {
            uow.discard();
        }
    }

    @Test
    public void testMultiConcerns2()
    {
        UnitOfWork uow = module.newUnitOfWork();

        try
        {
            ServiceReference<SomeServiceCompositeWithSecondAnnotation> refWithSecond = module.findService(
                SomeServiceCompositeWithSecondAnnotation.class );
            SomeServiceCompositeWithSecondAnnotation someWithSecond = refWithSecond.get();
            someWithSecond.doStuff();
            assertTrue( "AppliesTo did not match with second annotation", someWithSecond.concernHasBeenPlayed() );
        }
        finally
        {
            uow.discard();
        }
    }

    @Test
    public void testMultiConcernsBoth()
    {
        UnitOfWork uow = module.newUnitOfWork();

        try
        {
            ServiceReference<SomeServiceCompositeWithTwoAnnotations> refWithTwo = module.findService(
                SomeServiceCompositeWithTwoAnnotations.class );
            SomeServiceCompositeWithTwoAnnotations someWithTwo = refWithTwo.get();
            someWithTwo.doStuff();
            assertTrue( "AppliesTo did not match with two annotations", someWithTwo.concernHasBeenPlayed() );
        }
        finally
        {
            uow.discard();
        }
    }

    @Mixins( SomeMixinWithTwoAnnotations.class )
    @Concerns( MultiConcerns.class )
    public interface SomeServiceCompositeWithTwoAnnotations
        extends SomeService, ServiceComposite
    {
    }

    @Mixins( SomeMixinWithFirstAnnotation.class )
    @Concerns( MultiConcerns.class )
    public interface SomeServiceCompositeWithFirstAnnotation
        extends SomeService, ServiceComposite
    {
    }

    @Mixins( SomeMixinWithSecondAnnotation.class )
    @Concerns( MultiConcerns.class )
    public interface SomeServiceCompositeWithSecondAnnotation
        extends SomeService, ServiceComposite
    {
    }

    public interface SomeService
    {

        String doStuff();

        /**
         * Only for assertion purpose.
         */
        void playConcern();

        /**
         * Only for assertion purpose.
         */
        boolean concernHasBeenPlayed();
    }

    public static abstract class SomeBaseMixin
        implements SomeService
    {
        private boolean played = false;

        public void playConcern()
        {
            played = true;
        }

        public boolean concernHasBeenPlayed()
        {
            return played;
        }
    }

    public static abstract class SomeMixinWithTwoAnnotations
        extends SomeBaseMixin
        implements SomeService
    {
        @FirstAnnotation( "first one" )
        @SecondAnnotation( "second one" )
        public String doStuff()
        {
            return "Blah blah";
        }
    }

    public static abstract class SomeMixinWithFirstAnnotation
        extends SomeBaseMixin
        implements SomeService
    {

        @FirstAnnotation( "first one" )
        public String doStuff()
        {
            return "Blah blah";
        }
    }

    public static abstract class SomeMixinWithSecondAnnotation
        extends SomeBaseMixin
        implements SomeService
    {
        @SecondAnnotation( "second one" )
        public String doStuff()
        {
            return "Blah blah";
        }
    }

    @Retention( RetentionPolicy.RUNTIME )
    @Target( { ElementType.METHOD } )
    @InjectionScope
    public @interface FirstAnnotation
    {
        String value();
    }

    @Retention( RetentionPolicy.RUNTIME )
    @Target( { ElementType.METHOD } )
    @InjectionScope
    public @interface SecondAnnotation
    {
        String value();
    }

    @AppliesTo( { FirstAnnotation.class, SecondAnnotation.class } )
    public static class MultiConcerns
        extends ConcernOf<InvocationHandler>
        implements InvocationHandler
    {

        @Optional
        @Invocation
        private FirstAnnotation first;

        @Optional
        @Invocation
        private SecondAnnotation second;

        @This
        private SomeService someServiceComposite;

        public Object invoke( Object proxy, Method method, Object[] args )
            throws Throwable
        {
            if( first != null )
            {
                System.err.println( "FIRST IS HERE AND HAS VALUE: " + first.value() );
            }
            if( second != null )
            {
                System.err.println( "SECOND IS HERE AND HAS VALUE: " + second.value() );
            }
            someServiceComposite.playConcern();
            return next.invoke( proxy, method, args );
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="concept" name="DC.Type" />
<meta name="DC.Title" content="Privileges on views, triggers, constraints, and generated columns" />
<meta name="abstract" content="Views, triggers, constraints, and generated columns operate with the privileges of the owner of the view, trigger, constraint, or generated column." />
<meta name="description" content="Views, triggers, constraints, and generated columns operate with the privileges of the owner of the view, trigger, constraint, or generated column." />
<meta content="privileges, on views, triggers, constraints, and generated columns, permissions, views, privileges on, triggers, constraints, generated columns, invoker rights, versus definer rights, definer rights, versus invoker rights, SQL standard authorization mode" name="DC.subject" />
<meta content="privileges, on views, triggers, constraints, and generated columns, permissions, views, privileges on, triggers, constraints, generated columns, invoker rights, versus definer rights, definer rights, versus invoker rights, SQL standard authorization mode" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="csecauthorfine.html" />
<meta scheme="URI" name="DC.Relation" content="cseccsecuregrantrevokeaccess.html" />
<meta scheme="URI" name="DC.Relation" content="cseccsecureroles.html" />
<meta scheme="URI" name="DC.Relation" content="cseccsecuresqlauthupgrade.html" />
<meta scheme="URI" name="DC.Relation" content="rseccsecuresqlauthexceptions.html" />
<meta scheme="URI" name="DC.Relation" content="rseccsecurenativeauthex.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="cseccsecureprivileges" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Privileges on views, triggers, constraints, and generated columns</title>

Privileges on views, triggers, constraints, and generated columns

Views, triggers, constraints, and generated columns operate with the
privileges of the owner of the view, trigger, constraint, or generated
column.

For example, suppose that user <samp class="codeph">anita</samp> wants to create a view
using the following statement:

CREATE VIEW s.v(vc1,vc2,vc3)
    AS SELECT t1.c1,t1.c2,f(t1.c3)
    FROM t1 JOIN t2 ON t1.c1 = t2.c1
    WHERE t2.c2 = 5

User <samp class="codeph">anita</samp> needs the following privileges to create the
view:

Ownership of the schema <samp class="codeph">s</samp>, so that she can create something
in the schema

Ownership of the table <samp class="codeph">t1</samp>, so that she can allow others
to see columns in the table

SELECT privilege on column <samp class="codeph">t2.c1</samp> and column
<samp class="codeph">t2.c2</samp>

EXECUTE privilege on function <samp class="codeph">f</samp>

When the view is created, only user <samp class="codeph">anita</samp> has the SELECT
privilege on it. User <samp class="codeph">anita</samp> can grant the SELECT privilege on
any or all of the columns of view <samp class="codeph">s.v</samp> to anyone, even to users
that do not have the SELECT privilege on <samp class="codeph">t1</samp> or
<samp class="codeph">t2</samp>, or the EXECUTE privilege on <samp class="codeph">f</samp>. User
<samp class="codeph">anita</samp> then grants the SELECT privilege on view
<samp class="codeph">s.v</samp> to user <samp class="codeph">harry</samp>. When user
<samp class="codeph">harry</samp> issues a SELECT statement on the view
<samp class="codeph">s.v</samp>, Derby
checks to determine if user <samp class="codeph">harry</samp> has the SELECT privilege on
view <samp class="codeph">s.v</samp>.
Derby does not check to
determine if user <samp class="codeph">harry</samp> has the SELECT privilege on
<samp class="codeph">t1</samp> or <samp class="codeph">t2</samp>, or the EXECUTE privilege on
<samp class="codeph">f</samp>.

Privileges on triggers, constraints, and generated columns work the same way
as privileges on views. When one of these objects is created,
Derby checks that the owner
has the required privileges. Other users do not need to have those privileges
to perform actions on a view, trigger, constraint, or generated column.

If the required privileges are revoked from the owner of a view, trigger,
constraint, or generated column, the object is dropped as part of the
REVOKE statement.

Another way of saying that privileges on objects belong to the owner is to
call them definer rights, as opposed to invoker rights. This is
the terminology used by the SQL standard.

Parent topic: Configuring fine-grained user authorization

Related concepts

Using fine-grained user authorization

Using SQL roles

Upgrading an old database to use SQL standard authorization

Related reference

SQL standard authorization exceptions

NATIVE authentication and SQL authorization example


text:
package com.github.pedrovgs;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.AttributeSet;
import android.widget.FrameLayout;

/**
 * Custom view created to handle DraggableView using fragments. With this custom view the client code can configure the
 * top and bottom fragment and other elements like: top fragment height, top fragment margin right, top fragment x
 * scale factor, top fragment y scale factor, top fragment margin bottom and enable or disable horizontal alpha effect.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class DraggablePanel extends FrameLayout {

    private static final float DEFAULT_TOP_FRAGMENT_HEIGHT = 200;
    private static final float DEFAULT_SCALE_FACTOR = 2;
    private static final float DEFAULT_TOP_FRAGMENT_MARGIN = 0;
    private static final boolean DEFAULT_ENABLE_HORIZONTAL_ALPHA_EFFECT = true;

    private DraggableView draggableView;
    private DraggableListener draggableListener;

    private FragmentManager fragmentManager;
    private Fragment topFragment;
    private Fragment bottomFragment;
    private float topFragmentHeight;
    private float topFragmentMarginRight;
    private float topFragmentMarginBottom;
    private float xScaleFactor;
    private float yScaleFactor;
    private boolean enableHorizontalAlphaEffect;

    public DraggablePanel(Context context) {
        super(context);
    }

    public DraggablePanel(Context context, AttributeSet attrs) {
        super(context, attrs);
        initializeAttrs(attrs);
    }

    public DraggablePanel(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initializeAttrs(attrs);
    }

    /**
     * Configure the FragmentManager used to attach top and bottom fragment inside the view.
     *
     * @param fragmentManager
     */
    public void setFragmentManager(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
    }

    /**
     * Configure the Fragment that will work as draggable element inside this custom view. This Fragment has to be
     * configured before initialize the view.
     *
     * @param topFragment used as draggable element.
     */
    public void setTopFragment(Fragment topFragment) {
        this.topFragment = topFragment;
    }

    /**
     * Configure the Fragment that will work as secondary element inside this custom view. This Fragment has to be
     * configured before initialize the view.
     *
     * @param bottomFragment used as secondary element.
     */
    public void setBottomFragment(Fragment bottomFragment) {
        this.bottomFragment = bottomFragment;
    }

    /**
     * Configure the height associated to the top Fragment used inside the view as draggable element.
     *
     * @param topFragmentHeight in pixels.
     */
    public void setTopViewHeight(float topFragmentHeight) {
        this.topFragmentHeight = topFragmentHeight;
    }

    /**
     * Configure the horizontal scale factor applied when the top fragment is dragged to the bottom of the custom view.
     *
     * @param xScaleFactor
     */
    public void setXScaleFactor(float xScaleFactor) {
        this.xScaleFactor = xScaleFactor;
    }

    /**
     * Configure the vertical scale factor applied when the top fragment is dragged to the bottom of the custom view.
     *
     * @param yScaleFactor
     */
    public void setYScaleFactor(float yScaleFactor) {
        this.yScaleFactor = yScaleFactor;
    }

    /**
     * Configure the top Fragment margin right applied when the view has been minimized.
     *
     * @param topFragmentMarginRight in pixels.
     */
    public void setTopFragmentMarginRight(float topFragmentMarginRight) {
        this.topFragmentMarginRight = topFragmentMarginRight;
    }

    /**
     * Configure the top Fragment margin bottom applied when the view has been minimized.
     *
     * @param topFragmentMarginBottom in pixels.
     */
    public void setTopFragmentMarginBottom(float topFragmentMarginBottom) {
        this.topFragmentMarginBottom = topFragmentMarginBottom;
    }

    /**
     * Configure the DraggableListener that is going to be invoked when the view be minimized, maximized, closed to the
     * left or right.
     *
     * @param draggableListener
     */
    public void setDraggableListener(DraggableListener draggableListener) {
        this.draggableListener = draggableListener;
    }

    /**
     * Configure the disabling of the alpha effect applied when the view is being dragged horizontally.
     *
     * @param enableHorizontalAlphaEffect to enable or disable the effect.
     */
    public void setEnableHorizontalAlphaEffect(boolean enableHorizontalAlphaEffect) {
        this.enableHorizontalAlphaEffect = enableHorizontalAlphaEffect;
    }

    /**
     * Close the custom view applying an animation to close the view to the left side of the screen.
     */
    public void closeToLeft() {
        draggableView.closeToLeft();
    }

    /**
     * Close the custom view applying an animation to close the view to the right side of the screen.
     */
    public void closeToRight() {
        draggableView.closeToRight();
    }

    /**
     * Maximize the custom view applying an animation to return the view to the initial position.
     */
    public void maximize() {
        draggableView.maximize();
    }

    /**
     * Minimize the custom view applying an animation to put the top fragment on the bottom right corner of the screen.
     */
    public void minimize() {
        draggableView.minimize();
    }

    /**
     * Apply all the custom view configuration and inflate the main widgets. The view won't be visible if this method
     * is not called.
     * <p/>
     * FragmentManager, top Fragment and bottom Fragment have to be configured before initialize this view. If not,
     * this method will throw and IllegalStateException.
     */
    public void initializeView() {
        checkFragmentConsistency();
        checkSupportFragmentManagerConsistency();

        inflate(getContext(), R.layout.draggable_panel, this);
        draggableView = (DraggableView) findViewById(R.id.draggable_view);
        draggableView.setTopViewHeight(topFragmentHeight);
        draggableView.setFragmentManager(fragmentManager);
        draggableView.attachTopFragment(topFragment);
        draggableView.setXTopViewScaleFactor(xScaleFactor);
        draggableView.setYTopViewScaleFactor(yScaleFactor);
        draggableView.setTopViewMarginRight(topFragmentMarginRight);
        draggableView.setTopViewMarginBottom(topFragmentMarginBottom);
        draggableView.attachBottomFragment(bottomFragment);
        draggableView.setDraggableListener(draggableListener);
        draggableView.setHorizontalAlphaEffectEnabled(enableHorizontalAlphaEffect);
    }

    /**
     * Checks if the top Fragment is maximized.
     *
     * @return true if the view is maximized.
     */
    public boolean isMaximized() {
        return draggableView.isMaximized();
    }

    /**
     * Checks if the top Fragment is minimized.
     *
     * @return true if the view is minimized.
     */
    public boolean isMinimized() {
        return draggableView.isMinimized();
    }

    /**
     * Checks if the top Fragment closed at the right place.
     *
     * @return true if the view is closed at right.
     */
    public boolean isClosedAtRight() {
        return draggableView.isClosedAtRight();
    }

    /**
     * Checks if the top Fragment is closed at the left place.
     *
     * @return true if the view is closed at left.
     */
    public boolean isClosedAtLeft() {
        return draggableView.isClosedAtLeft();
    }

    /**
     * Initialize the xml configuration based on styleable attributes
     *
     * @param attrs to analyze.
     */
    private final void initializeAttrs(AttributeSet attrs) {
        TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.draggable_panel);
        this.topFragmentHeight = attributes.getDimension(R.styleable.draggable_panel_top_fragment_height, DEFAULT_TOP_FRAGMENT_HEIGHT);
        this.xScaleFactor = attributes.getFloat(R.styleable.draggable_panel_x_scale_factor, DEFAULT_SCALE_FACTOR);
        this.yScaleFactor = attributes.getFloat(R.styleable.draggable_panel_y_scale_factor, DEFAULT_SCALE_FACTOR);
        this.topFragmentMarginRight = attributes.getDimension(R.styleable.draggable_panel_top_fragment_margin_right, DEFAULT_TOP_FRAGMENT_MARGIN);
        this.topFragmentMarginBottom = attributes.getDimension(R.styleable.draggable_panel_top_fragment_margin_bottom, DEFAULT_TOP_FRAGMENT_MARGIN);
        this.enableHorizontalAlphaEffect = attributes.getBoolean(R.styleable.draggable_panel_enable_horizontal_alpha_effect, DEFAULT_ENABLE_HORIZONTAL_ALPHA_EFFECT);
        attributes.recycle();
    }

    /**
     * Validate FragmentManager configuration. If is not initialized, this method will throw an
     * IllegalStateException.
     */
    private void checkSupportFragmentManagerConsistency() {
        if (fragmentManager == null) {
            throw new IllegalStateException("You have to set the support FragmentManager before initialize DraggablePanel");
        }
    }

    /**
     * Validate top and bottom Fragment configuration. If are not initialized, this method will throw an
     * IllegalStateException.
     */
    private void checkFragmentConsistency() {
        if (topFragment == null || bottomFragment == null) {
            throw new IllegalStateException("You have to set top and bottom fragment before initialize DraggablePanel");
        }
    }

}


text: var jQuery = django.jQuery;


text:
package io.opentelemetry.sdk.metrics.internal.debug;

/** Diagnostic information derived from stack traces. */
final class StackTraceSourceInfo implements SourceInfo {

  private final StackTraceElement[] stackTraceElements;

  StackTraceSourceInfo(StackTraceElement[] stackTraceElements) {
    this.stackTraceElements = stackTraceElements;
  }

  @Override
  public String shortDebugString() {
    if (stackTraceElements.length > 0) {
      for (StackTraceElement e : stackTraceElements) {
        if (isInterestingStackTrace(e)) {
          return String.format("%s:%d", e.getFileName(), e.getLineNumber());
        }
      }
    }
    return "unknown source";
  }

  @Override
  public String multiLineDebugString() {
    if (stackTraceElements.length > 0) {
      // TODO - Limit trace length
      StringBuilder result = new StringBuilder();
      for (StackTraceElement e : stackTraceElements) {
        if (isInterestingStackTrace(e)) {
          result.append("\tat ").append(e).append("\n");
        }
      }
      return result.toString();
    }
    return "\tat unknown source";
  }

  private static boolean isInterestingStackTrace(StackTraceElement e) {
    return !e.getClassName().startsWith("io.opentelemetry.sdk.metrics")
        && !e.getClassName().startsWith("java.lang");
  }
}


text:
package com.github.nmorel.gwtjackson.rebind;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.github.nmorel.gwtjackson.client.AbstractConfiguration;
import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;
import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns.JsonMixIn;
import com.google.gwt.core.ext.BadPropertyValueException;
import com.google.gwt.core.ext.ConfigurationProperty;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.TreeLogger.Type;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JAbstractMethod;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JConstructor;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.core.ext.typeinfo.JParameter;
import com.google.gwt.core.ext.typeinfo.JPrimitiveType;
import com.google.gwt.core.ext.typeinfo.JType;
import com.google.gwt.core.ext.typeinfo.TypeOracleException;
import com.google.gwt.thirdparty.guava.common.base.Optional;
import com.google.gwt.thirdparty.guava.common.collect.ImmutableList;
import com.google.gwt.thirdparty.guava.common.collect.ImmutableSet;
import com.google.gwt.thirdparty.guava.common.collect.ImmutableSet.Builder;
import com.google.gwt.util.regexfilter.RegexFilter;
import com.google.gwt.util.tools.shared.Md5Utils;

/**
 * Wrap the default configuration + user configuration. It reads the configuration from {@link DefaultConfiguration} and any {@link
 * AbstractConfiguration} the user defined with :
 * <pre>
 * <extend-configuration-property name="gwtjackson.configuration.extension" value="com.example.MyAbstractConfiguration" />
 * </pre>
 *
 * @author Nicolas Morel
 */
public final class RebindConfiguration {

    public enum MapperType {
        KEY_SERIALIZER( true, true ) {
            @Override
            protected Map<Class, Class> getMapperTypeConfiguration( AbstractConfiguration configuration ) {
                return configuration.getMapTypeToKeySerializer();
            }
        }, KEY_DESERIALIZER( false, true ) {
            @Override
            protected Map<Class, Class> getMapperTypeConfiguration( AbstractConfiguration configuration ) {
                return configuration.getMapTypeToKeyDeserializer();
            }
        }, JSON_SERIALIZER( true, false ) {
            @Override
            protected Map<Class, Class> getMapperTypeConfiguration( AbstractConfiguration configuration ) {
                return configuration.getMapTypeToSerializer();
            }
        }, JSON_DESERIALIZER( false, false ) {
            @Override
            protected Map<Class, Class> getMapperTypeConfiguration( AbstractConfiguration configuration ) {
                return configuration.getMapTypeToDeserializer();
            }
        };

        private final boolean serializer;

        private final boolean key;

        MapperType( boolean serializer, boolean key ) {
            this.serializer = serializer;
            this.key = key;
        }

        abstract Map<Class, Class> getMapperTypeConfiguration( final AbstractConfiguration configuration );

        boolean isSerializer() {
            return serializer;
        }

        boolean isKey() {
            return key;
        }
    }

    public static class MapperInstance {

        private final JClassType mapperType;

        private final JAbstractMethod instanceCreationMethod;

        private final MapperType[] parameters;

        private MapperInstance( JClassType mapperType, JAbstractMethod instanceCreationMethod, MapperType[] parameters ) {
            this.mapperType = mapperType;
            this.instanceCreationMethod = instanceCreationMethod;
            this.parameters = parameters;
        }

        public JClassType getMapperType() {
            return mapperType;
        }

        public JAbstractMethod getInstanceCreationMethod() {
            return instanceCreationMethod;
        }

        public MapperType[] getParameters() {
            return parameters;
        }
    }

    private static class TypeFilter extends RegexFilter {

        public TypeFilter( TreeLogger logger, List<String> values ) throws UnableToCompleteException {
            super( logger, values );
        }

        @Override
        protected boolean acceptByDefault() {
            return false;
        }

        @Override
        protected boolean entriesArePositiveByDefault() {
            return true;
        }
    }

    private static final String CONFIGURATION_EXTENSION_PROPERTY = "gwtjackson.configuration.extension";

    private final TreeLogger logger;

    private final GeneratorContext context;

    private final JacksonTypeOracle typeOracle;

    private final Map<String, MapperInstance> serializers = new HashMap<String, MapperInstance>();

    private final Map<String, MapperInstance> deserializers = new HashMap<String, MapperInstance>();

    private final Map<String, MapperInstance> keySerializers = new HashMap<String, MapperInstance>();

    private final Map<String, MapperInstance> keyDeserializers = new HashMap<String, MapperInstance>();

    private final Map<String, JClassType> mixInAnnotations = new HashMap<String, JClassType>();

    private final JClassType rootMapperClass;

    private final String rootMapperHash;

    // If the user adds an annotation on mapper, we have to make distinct serializer/deserializer for the impacted types.
    // For now, it means any types and associated subtypes targeted by a mix-in annotation
    private final Set<JClassType> specificTypes = new HashSet<JClassType>();

    private final ImmutableSet<JClassType> allSupportedSerializationClass;

    private final ImmutableSet<JClassType> allSupportedDeserializationClass;

    private final TypeFilter additionalSupportedTypes;

    private final JsonAutoDetect.Visibility defaultFieldVisibility;

    private final JsonAutoDetect.Visibility defaultGetterVisibility;

    private final JsonAutoDetect.Visibility defaultIsGetterVisibility;

    private final JsonAutoDetect.Visibility defaultSetterVisibility;

    private final JsonAutoDetect.Visibility defaultCreatorVisibility;

    public RebindConfiguration( TreeLogger logger, GeneratorContext context, JacksonTypeOracle typeOracle, JClassType rootMapperClass )
            throws UnableToCompleteException {
        this.logger = logger;
        this.context = context;
        this.typeOracle = typeOracle;
        this.rootMapperClass = rootMapperClass;
        this.rootMapperHash = new BigInteger( 1, Md5Utils.getMd5Digest( rootMapperClass.getQualifiedSourceName().getBytes() ) )
                .toString( 16 );

        List<AbstractConfiguration> configurations = getAllConfigurations();

        Builder<JClassType> allSupportedSerializationClassBuilder = ImmutableSet.builder();
        Builder<JClassType> allSupportedDeserializationClassBuilder = ImmutableSet.builder();
        List<String> whitelist = new ArrayList<String>();

        JsonAutoDetect.Visibility fieldVisibility = JsonAutoDetect.Visibility.DEFAULT;
        JsonAutoDetect.Visibility getterVisibility = JsonAutoDetect.Visibility.DEFAULT;
        JsonAutoDetect.Visibility isGetterVisibility = JsonAutoDetect.Visibility.DEFAULT;
        JsonAutoDetect.Visibility setterVisibility = JsonAutoDetect.Visibility.DEFAULT;
        JsonAutoDetect.Visibility creatorVisibility = JsonAutoDetect.Visibility.DEFAULT;

        for ( AbstractConfiguration configuration : configurations ) {
            for ( MapperType mapperType : MapperType.values() ) {
                addMappers( configuration, mapperType, allSupportedSerializationClassBuilder, allSupportedDeserializationClassBuilder );
            }
            addMixInAnnotations( configuration.getMapMixInAnnotations(), rootMapperClass.getAnnotation( JsonMixIns.class ) );
            whitelist.addAll( configuration.getWhitelist() );

            fieldVisibility = configuration.getFieldVisibility();
            getterVisibility = configuration.getGetterVisibility();
            isGetterVisibility = configuration.getIsGetterVisibility();
            setterVisibility = configuration.getSetterVisibility();
            creatorVisibility = configuration.getCreatorVisibility();
        }

        this.allSupportedSerializationClass = allSupportedSerializationClassBuilder.build();
        this.allSupportedDeserializationClass = allSupportedDeserializationClassBuilder.build();
        this.additionalSupportedTypes = new TypeFilter( logger, whitelist );

        this.defaultFieldVisibility = fieldVisibility;
        this.defaultGetterVisibility = getterVisibility;
        this.defaultIsGetterVisibility = isGetterVisibility;
        this.defaultSetterVisibility = setterVisibility;
        this.defaultCreatorVisibility = creatorVisibility;
    }

    /**
     * @return the list of default configuration + user configurations
     */
    private List<AbstractConfiguration> getAllConfigurations() {
        ImmutableList.Builder<AbstractConfiguration> builder = ImmutableList.builder();
        builder.add( new DefaultConfiguration() );

        ConfigurationProperty property = null;
        try {
            property = context.getPropertyOracle().getConfigurationProperty( CONFIGURATION_EXTENSION_PROPERTY );
        } catch ( BadPropertyValueException e ) {
            logger.log( Type.WARN, "Cannot find the property " + CONFIGURATION_EXTENSION_PROPERTY );
        }

        if ( null != property && !property.getValues().isEmpty() ) {
            for ( String value : property.getValues() ) {
                try {
                    builder.add( (AbstractConfiguration) Class.forName( value ).newInstance() );
                } catch ( Exception e ) {
                    logger.log( Type.WARN, "Cannot instantiate the configuration class " + value );
                }
            }
        }

        return builder.build();
    }

    /**
     * Parse the configured serializer/deserializer configuration and put them into the corresponding map
     *
     * @param configuration configuration
     * @param mapperType type of the mapper
     * @param allSupportedSerializationClassBuilder builder aggregating all the types that have a serializer
     * @param allSupportedDeserializationClassBuilder builder aggregating all the types that have a deserializer
     */
    private void addMappers( final AbstractConfiguration configuration, final MapperType mapperType, Builder<JClassType>
            allSupportedSerializationClassBuilder, Builder<JClassType> allSupportedDeserializationClassBuilder ) {
        Map<Class, Class> configuredMapper = mapperType.getMapperTypeConfiguration( configuration );

        for ( Entry<Class, Class> entry : configuredMapper.entrySet() ) {

            JType mappedType = findType( entry.getKey() );
            if ( null == mappedType ) {
                continue;
            }

            JClassType mapperClassType = findClassType( entry.getValue() );
            if ( null == mapperClassType ) {
                continue;
            }

            if ( mapperType.isKey() ) {
                MapperInstance keyMapperInstance = getKeyInstance( mappedType, mapperClassType, mapperType.isSerializer() );
                if ( mapperType.isSerializer() ) {
                    keySerializers.put( mappedType.getQualifiedSourceName(), keyMapperInstance );
                } else {
                    keyDeserializers.put( mappedType.getQualifiedSourceName(), keyMapperInstance );
                }
            } else {
                MapperInstance mapperInstance = getInstance( mappedType, mapperClassType, mapperType.isSerializer() );
                if ( null != mapperInstance ) {
                    if ( mapperType.isSerializer() ) {
                        serializers.put( mappedType.getQualifiedSourceName(), mapperInstance );
                        if ( null != mappedType.isClass() ) {
                            allSupportedSerializationClassBuilder.add( mappedType.isClass() );
                        }
                    } else {
                        deserializers.put( mappedType.getQualifiedSourceName(), mapperInstance );
                        if ( null != mappedType.isClass() ) {
                            allSupportedDeserializationClassBuilder.add( mappedType.isClass() );
                        }
                    }
                }
            }
        }
    }

    /**
     * @param clazz class to find the type
     *
     * @return the {@link JType} denoted by the class given in parameter
     */

    private JType findType( Class<?> clazz ) {
        if ( clazz.isPrimitive() ) {

            return JPrimitiveType.parse( clazz.getCanonicalName() );

        } else if ( clazz.isArray() ) {

            try {
                return context.getTypeOracle().parse( clazz.getCanonicalName() );
            } catch ( TypeOracleException e ) {
                logger.log( TreeLogger.WARN, "Cannot find the array denoted by the class " + clazz.getCanonicalName() );
                return null;
            }

        } else {
            return findClassType( clazz );
        }
    }

    /**
     * @param clazz class to find the type
     *
     * @return the {@link JClassType} denoted by the class given in parameter
     */
    private JClassType findClassType( Class<?> clazz ) {
        JClassType mapperType = context.getTypeOracle().findType( clazz.getCanonicalName() );
        if ( null == mapperType ) {
            logger.log( Type.WARN, "Cannot find the type denoted by the class " + clazz.getCanonicalName() );
            return null;
        }
        return mapperType;
    }

    /**
     * Search a static method or constructor to instantiate the mapper and return a {@link String} calling it.
     */
    private MapperInstance getInstance( JType mappedType, JClassType classType, boolean isSerializers ) {
        int nbParam = 0;
        if ( null != mappedType.isGenericType() && (!isSerializers || !typeOracle.isEnumSupertype( mappedType )) ) {
            nbParam = mappedType.isGenericType().getTypeParameters().length;
        }

        // we first look at static method
        for ( JMethod method : classType.getMethods() ) {
            // method must be public static, return the instance type and take no parameters
            if ( method.isStatic() && null != method.getReturnType().isClassOrInterface()
                    && classType.isAssignableTo( method.getReturnType().isClassOrInterface() )
                    && method.getParameters().length == nbParam && method.isPublic() ) {
                MapperType[] parameters = getParameters( mappedType, method, isSerializers );
                if ( null == parameters ) {
                    continue;
                }

                return new MapperInstance( classType, method, parameters );
            }
        }

        // then we search the default constructor
        for ( JConstructor constructor : classType.getConstructors() ) {
            if ( constructor.isPublic() && constructor.getParameters().length == nbParam ) {
                MapperType[] parameters = getParameters( mappedType, constructor, isSerializers );
                if ( null == parameters ) {
                    continue;
                }

                return new MapperInstance( classType, constructor, parameters );
            }
        }

        logger.log( Type.WARN, "Cannot instantiate the custom serializer/deserializer " + classType
                .getQualifiedSourceName() + ". It will be ignored" );
        return null;
    }

    private MapperType[] getParameters( JType mappedType, JAbstractMethod method, boolean isSerializers ) {
        if ( !isSerializers && typeOracle.isEnumSupertype( mappedType ) ) {
            // For enums, the constructor requires the enum class. We just return an empty array and will handle it later
            if ( method.getParameters().length == 1 && Class.class.getName().equals( method.getParameters()[0].getType()
                    .getQualifiedSourceName() ) ) {
                return new MapperType[0];
            } else {
                // Not a valid method to create enum deserializer
                return null;
            }
        }

        MapperType[] parameters = new MapperType[method.getParameters().length];
        for ( int i = 0; i < method.getParameters().length; i++ ) {
            JParameter parameter = method.getParameters()[i];
            if ( isSerializers ) {
                if ( typeOracle.isKeySerializer( parameter.getType() ) ) {
                    parameters[i] = MapperType.KEY_SERIALIZER;
                } else if ( typeOracle.isJsonSerializer( parameter.getType() ) ) {
                    parameters[i] = MapperType.JSON_SERIALIZER;
                } else {
                    // the parameter is unknown, we ignore this method
                    return null;
                }
            } else {
                if ( typeOracle.isKeyDeserializer( parameter.getType() ) ) {
                    parameters[i] = MapperType.KEY_DESERIALIZER;
                } else if ( typeOracle.isJsonDeserializer( parameter.getType() ) ) {
                    parameters[i] = MapperType.JSON_DESERIALIZER;
                } else {
                    // the parameter is unknown, we ignore this method
                    return null;
                }
            }
        }
        return parameters;
    }

    /**
     * Search a static method or constructor to instantiate the key mapper and return a {@link String} calling it.
     */
    private MapperInstance getKeyInstance( JType mappedType, JClassType classType, boolean isSerializers ) {
        int nbParam = 0;
        if ( !isSerializers && typeOracle.isEnumSupertype( mappedType ) ) {
            nbParam = 1;
        }

        // we first look at static method
        for ( JMethod method : classType.getMethods() ) {
            // method must be public static, return the instance type and take no parameters
            if ( method.isStatic() && null != method.getReturnType().isClassOrInterface()
                    && classType.isAssignableTo( method.getReturnType().isClassOrInterface() )
                    && method.getParameters().length == nbParam && method.isPublic() ) {
                MapperType[] parameters = getParameters( mappedType, method, isSerializers );
                if ( null == parameters ) {
                    continue;
                }

                return new MapperInstance( classType, method, parameters );
            }
        }

        // then we search the default constructor
        for ( JConstructor constructor : classType.getConstructors() ) {
            if ( constructor.isPublic() && constructor.getParameters().length == nbParam ) {
                MapperType[] parameters = getParameters( mappedType, constructor, isSerializers );
                if ( null == parameters ) {
                    continue;
                }

                return new MapperInstance( classType, constructor, parameters );
            }
        }

        logger.log( Type.WARN, "Cannot instantiate the custom key serializer/deserializer " + classType
                .getQualifiedSourceName() + ". It will be ignored" );
        return null;
    }

    /**
     * Adds to {@link #mixInAnnotations} the configured mix-in annotations passed in parameters
     *
     * @param mapMixInAnnotations mix-ins annotations to add
     * @param mapperMixIns Annotation defined on mapper
     */
    private void addMixInAnnotations( Map<Class, Class> mapMixInAnnotations, JsonMixIns mapperMixIns ) {
        if ( null != mapperMixIns ) {
            for ( JsonMixIn jsonMixIn : mapperMixIns.value() ) {
                JClassType targetType = findClassType( jsonMixIn.target() );
                if ( null == targetType ) {
                    continue;
                }
                specificTypes.add( targetType );
                specificTypes.addAll( Arrays.asList( targetType.getSubtypes() ) );

                mapMixInAnnotations.put( jsonMixIn.target(), jsonMixIn.mixIn() );
            }
        }

        if ( !mapMixInAnnotations.isEmpty() ) {
            for ( Entry<Class, Class> entry : mapMixInAnnotations.entrySet() ) {
                JClassType targetType = findClassType( entry.getKey() );
                if ( null == targetType ) {
                    continue;
                }

                JClassType mixInType = findClassType( entry.getValue() );
                if ( null == mixInType ) {
                    continue;
                }

                mixInAnnotations.put( targetType.getQualifiedSourceName(), mixInType );
            }
        }
    }

    /**
     * Return a {@link MapperInstance} instantiating the serializer for the given type
     */
    public Optional<MapperInstance> getSerializer( JType type ) {
        return Optional.fromNullable( serializers.get( type.getQualifiedSourceName() ) );
    }

    /**
     * Return a {@link MapperInstance} instantiating the deserializer for the given type
     */
    public Optional<MapperInstance> getDeserializer( JType type ) {
        return Optional.fromNullable( deserializers.get( type.getQualifiedSourceName() ) );
    }

    /**
     * Return a {@link MapperInstance} instantiating the key serializer for the given type
     */
    public Optional<MapperInstance> getKeySerializer( JType type ) {
        return Optional.fromNullable( keySerializers.get( type.getQualifiedSourceName() ) );
    }

    /**
     * Return a {@link MapperInstance} instantiating the key deserializer for the given type
     */
    public Optional<MapperInstance> getKeyDeserializer( JType type ) {
        return Optional.fromNullable( keyDeserializers.get( type.getQualifiedSourceName() ) );
    }

    /**
     * Return the mixin type for the given type
     */
    public Optional<JClassType> getMixInAnnotations( JType type ) {
        return Optional.fromNullable( mixInAnnotations.get( type.getQualifiedSourceName() ) );
    }

    /**
     * @return the root mapper class that is currently generated
     */
    public JClassType getRootMapperClass() {
        return rootMapperClass;
    }

    public String getRootMapperHash() {
        return rootMapperHash;
    }

    /**
     * @param beanType type
     *
     * @return true if beanType is specific to the mapper
     */
    public boolean isSpecificToMapper( JClassType beanType ) {
        return specificTypes.contains( beanType );
    }

    public boolean isTypeSupportedForSerialization( TreeLogger logger, JClassType classType ) {
        return allSupportedSerializationClass.contains( classType )
                || additionalSupportedTypes.isIncluded( logger, classType.getQualifiedSourceName() );
    }

    public boolean isTypeSupportedForDeserialization( TreeLogger logger, JClassType classType ) {
        return allSupportedDeserializationClass.contains( classType )
                || additionalSupportedTypes.isIncluded( logger, classType.getQualifiedSourceName() );
    }

    public Visibility getDefaultFieldVisibility() {
        return defaultFieldVisibility;
    }

    public Visibility getDefaultGetterVisibility() {
        return defaultGetterVisibility;
    }

    public Visibility getDefaultIsGetterVisibility() {
        return defaultIsGetterVisibility;
    }

    public Visibility getDefaultSetterVisibility() {
        return defaultSetterVisibility;
    }

    public Visibility getDefaultCreatorVisibility() {
        return defaultCreatorVisibility;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>Mister Spex: Class Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Mister Spex
    1.0

The project Mister Spex is a funny tool to capture images and display them with overlays such as glasses or big red lips over the normal human face. All images can be saved or recorded. Within this software you have three different mode to get the images (LiveView via webcam, Static image and a playback of a recorded video).

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

All

Functions

Variables

a

b

c

d

e

f

g

i

l

m

n

o

p

q

r

s

t

u

v

w

~

 All Classes Files Functions Variables Macros Pages

Here is a list of all documented class members with links to the class documentation for each member:

- a -

add()
: Buffer< T >
, VideoImageBuffer

addRecFrame()
: RecordVideoThread

applyChangesOnSingleImage()
: MainWindow

applyChangesToImageProc()
: ImageHandler

- b -

Buffer()
: Buffer< T >

bufferSize
: Buffer< T >

- c -

CameraConnectDialog()
: CameraConnectDialog

cap
: PlaybackThread
, VideoThread

changeDetectionState()
: MainWindow

clear()
: Buffer< T >

clearBuffer_add
: Buffer< T >

clearBuffer_get
: Buffer< T >

connectToCamera()
: MainWindow
, VideoThread

containsImageBufferForDeviceNumber()
: VideoImageBuffer

counter
: PlaybackThread

createVideoWriter()
: RecordVideoThread

currentFrame
: ProcessingThread

currentFrameGrayscale
: ProcessingThread

currentROI
: ProcessingThread

cvCreateOverlay()
: FaceDetection

cvCreateOverlayGlasses()
: FaceDetection

- d -

detection
: MainWindow

detectionState
: PlaybackThread

detectObjects()
: FaceDetection

deviceNumber
: MainWindow
, ProcessingThread
, VideoThread

disconnectCamera()
: VideoThread
, MainWindow

doStop
: PlaybackThread
, ProcessingThread
, RecordVideoThread
, VideoThread

doStopMutex
: ProcessingThread
, RecordVideoThread
, VideoThread
, PlaybackThread

dropFrameIfBufferFull
: VideoThread

- e -

enableFrameProcessing
: ProcessingThread

- f -

faceDetection
: ImageHandler
, PlaybackThread

FaceDetection()
: FaceDetection

faceDetection
: ProcessingThread

file
: MainWindow

fn
: PlaybackThread
, RecordVideoThread

fps
: PlaybackThread

frame
: PlaybackThread
, ProcessingThread

framePoint
: ProcessingThread

frames
: PlaybackThread

frameSize
: ProcessingThread

freeSlots
: Buffer< T >

- g -

get()
: Buffer< T >

getByDeviceNumber()
: VideoImageBuffer

getCurrentROI()
: ProcessingThread

getImgProcSettingsForImg()
: ImageProcessingSettingsDialog

getInputSourceHeight()
: VideoThread

getInputSourceWidth()
: VideoThread

getMode()
: CameraConnectDialog

grabbedFrame
: PlaybackThread
, VideoThread

- i -

image
: ImageHandler

imageBufferMap
: VideoImageBuffer

imageDetection
: MainWindow

imageHandler
: MainWindow

ImageHandler()
: ImageHandler

imageProcessingFlags
: MainWindow

imageProcessingSettings
: MainWindow
, ImageProcessingSettingsDialog

ImageProcessingSettingsDialog()
: ImageProcessingSettingsDialog

imageProcessingSettingsDialog
: MainWindow

imgProcFlags
: PlaybackThread
, ProcessingThread

ImgProcFlagsForImg()
: ImageProcessingSettingsDialog

imgProcSettings
: ProcessingThread
, PlaybackThread

isCameraConnected()
: VideoThread

isEmpty()
: Buffer< T >

isFull()
: Buffer< T >

- l -

liveViewActive
: MainWindow

loadImageFromFile()
: ImageHandler

loadPlayback()
: PlaybackThread

- m -

MainWindow()
: MainWindow

maxSize()
: Buffer< T >

mode
: MainWindow

mutex
: VideoImageBuffer

- n -

newFrame()
: ProcessingThread

newImageProcessingFlags()
: MainWindow

newImageProcessingSettings()
: ImageProcessingSettingsDialog

nextFrame()
: PlaybackThread

- o -

orig_image
: ImageHandler

overlayParam1
: ImageProcessingSettings

overlayParam2
: ImageProcessingSettings

overlayParam3
: ImageProcessingSettings

- p -

playbackActive
: MainWindow

playbackThread
: MainWindow

PlaybackThread()
: PlaybackThread

processingMutex
: ProcessingThread
, PlaybackThread

ProcessingThread()
: ProcessingThread

processingThread
: MainWindow

- q -

queue
: Buffer< T >

queueProtect
: Buffer< T >

- r -

rec_fps
: RecordVideoThread

rec_height
: MainWindow
, RecordVideoThread

rec_width
: MainWindow
, RecordVideoThread

recDir
: ProcessingThread

recFlag
: ProcessingThread

recFn
: ProcessingThread

recFrame()
: ProcessingThread

recording
: MainWindow

recordingMutex
: RecordVideoThread

recordThread
: MainWindow

recordVideo()
: MainWindow

RecordVideoThread()
: RecordVideoThread

removeByDeviceNumber()
: VideoImageBuffer

resetOverlays()
: ImageProcessingSettingsDialog

resetROI()
: ProcessingThread

run()
: ProcessingThread
, RecordVideoThread
, PlaybackThread
, VideoThread

- s -

saveCurrentImage()
: ProcessingThread

saveDirectory
: MainWindow

saveImage
: ProcessingThread

saveImageToFile()
: ImageHandler

selectMode()
: MainWindow

setDetection()
: MainWindow

setFrameProcessing()
: ProcessingThread

setImageProcessingSettings()
: MainWindow

setLiveViewSaveImgFlag()
: MainWindow

setRecDir()
: MainWindow

setRecFlag()
: ProcessingThread

setRecordFlag()
: MainWindow

setROI()
: MainWindow
, ProcessingThread

setSaveImgFlag()
: ProcessingThread

setSaveParams()
: MainWindow
, ProcessingThread

showAboutDialog()
: MainWindow

showDetectionOn
: ImageProcessingFlags

showImage()
: MainWindow

showOverlaysOn
: ImageProcessingFlags

size()
: Buffer< T >

startPlayback()
: MainWindow

stop()
: ProcessingThread
, RecordVideoThread
, VideoThread
, PlaybackThread

stopPlayback()
: MainWindow

stopPlaybackThread()
: MainWindow

stopProcessingThread()
: MainWindow

stopVideoThread()
: MainWindow

syncSet
: VideoImageBuffer

- t -

takeSnapshot()
: MainWindow

- u -

ui
: CameraConnectDialog
, ImageProcessingSettingsDialog
, MainWindow

updateDetState()
: PlaybackThread

updateDialogSettingsFromStored()
: ImageProcessingSettingsDialog

updateFrame()
: MainWindow

updateImageProcessingFlags()
: ProcessingThread
, PlaybackThread

updateImageProcessingSettings()
: ProcessingThread
, PlaybackThread

updateStoredSettingsFromDialog()
: ImageProcessingSettingsDialog

usedSlots
: Buffer< T >

- v -

vid_writer
: RecordVideoThread

videoImageBuffer
: MainWindow
, VideoThread

VideoImageBuffer()
: VideoImageBuffer

videoImageBuffer
: ProcessingThread

VideoThread()
: VideoThread

videoThread
: MainWindow

- w -

wakeAll()
: VideoImageBuffer

wc
: VideoImageBuffer

- ~ -

~CameraConnectDialog()
: CameraConnectDialog

~ImageHandler()
: ImageHandler

~ImageProcessingSettingsDialog()
: ImageProcessingSettingsDialog

~MainWindow()
: MainWindow

<address class="footer">
Generated on Wed Jan 22 2014 11:39:00 for Mister Spex by

 1.8.4
</address>


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="br.com.superpet"/>
    <jpa:repositories base-package="br.com.superpet.repositories"/>
    <mvc:annotation-driven />

    <!-- Datasource -->
    <bean id="dataSource"
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/superpet" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        p:packagesToScan="br.com.superpet.models"
        p:dataSource-ref="dataSource"
        >
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="false" />
                <property name="showSql" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
            </bean>
        </property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    <tx:annotation-driven />

</beans>


text:
foam.CLASS({
  package: 'foam.nanos.menu',
  name: 'DocumentFileMenu',
  extends: 'foam.nanos.menu.AbstractMenu',
  requires: [
    'foam.nanos.doc.DocumentationView'
  ],

  documentation: 'A menu item which contains a document fetched from the DocumentDAO',

  properties: [
    {
      class: 'Reference',
      of: 'foam.flow.Document',
      name: 'docKey',
      label: 'Document',
      view: function(args, X) {
        return {
          class: 'foam.u2.view.ReferenceView',
          dao$: X.data$.dot('daoKey').map(function(key) {
            return X[key] || foam.dao.NullDAO.create();
          })
        };
      }
    },
    {
      class: 'String',
      name: 'daoKey',
      value: 'documentDAO'
    },
    {
      class: 'String',
      name: 'anchor'
    }
  ],

  methods: [
    function createView(X) {
      return this.DocumentationView.create({ docKey: this.docKey, daoKey: this.daoKey, anchor: this.anchor });
    }
  ]
});


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package houseOp;

import java.io.*;
import static java.lang.System.out;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;

import userOp.User;
/**
 *
 * @author yannis bitsikokos
 */
public class AddRentServlet extends HttpServlet {

    Connection connection;
    Statement stmt;
    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @throws SQLException
     */
    @Override

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException
    {

                try {
                    HttpSession session = request.getSession(false);
                    int idhouse_rent = 0;
                    int price;
                    int area_size;
                    int shared;
                    int year;
                    double lng = 0;     //diastaseis gia google map
                    double lat = 0;
                    int flag=0;     //ok i sfalma
                    String message = "start";
                    String url = "";

                    if(!request.getParameter("price").equals(""))
                        price = Integer.parseInt(request.getParameter("price"));
                    else
                        price = 0;

                    String place = request.getParameter("place");
                    if(!request.getParameter("area_size").equals(""))
                        area_size = Integer.parseInt(request.getParameter("area_size"));
                    else
                        area_size = 0;
                    int house_or_apartment = -1;
                    //Int house_or_appartment = Integer.parseInt(request.getParameter("house_or_appartment"));
                    if (request.getParameter("house_or_appartment").equals("house")){
                        house_or_apartment = 0;
                    }
                    if (request.getParameter("house_or_appartment").equals("appartment")){
                        house_or_apartment = 1;
                    }
                    if(!request.getParameter("shared").equals(""))
                        shared = Integer.parseInt(request.getParameter("shared"));
                    else
                        shared = 0;
                    if(!request.getParameter("year").equals(""))
                        year = Integer.parseInt(request.getParameter("year"));
                    else
                        year = 0;
                    int none_central_or_self = -1;
                    if (request.getParameter("none_central_or_self").equals("none")){
                        none_central_or_self = 0;
                    }
                    if (request.getParameter("none_central_or_self").equals("central")){
                        none_central_or_self = 1;
                    }
                    if (request.getParameter("none_central_or_self").equals("autonomous")){
                        none_central_or_self = 2;
                    }
                    String description = "";

                    if(!request.getParameter("description").equals("")){
                        description = request.getParameter("description");
                    }
                    if(!request.getParameter("lng").equals("default")){
                        lng = Double.parseDouble(request.getParameter("lng"));
                    }else{
                        message = "Empty_map";
                        flag = 1;
                        url = "/add_for_rent.jsp";
                    }
                    if(!request.getParameter("lat").equals("default")){
                        lat = Double.parseDouble(request.getParameter("lat"));
                    }else{
                        message = "Empty_map";
                        flag = 1;
                        url = "/add_for_rent.jsp";
                    }

                    String username =(String) session.getAttribute("username");

                    try {
                        Context initContext = new InitialContext();
                        Context context = (Context) initContext.lookup("java:/comp/env");
                        DataSource ds = (DataSource) context.lookup("jdbc/Schemas");
                        connection = ds.getConnection();
                        stmt = connection.createStatement();
                    } catch (SQLException | NamingException e) {
                        System.out.println(e.getMessage());
                    }
                    if (connection == null)
                    {
                        throw new SQLException("ERROR establishing connection!");
                    }
                    ResultSet set = null;
                    set = stmt.executeQuery("select * from house_rent");
                    int counter = 1;
                    while(set.next()){
                        counter++;
                    }
                    idhouse_rent = counter;
                    //kenh selida
                    if (idhouse_rent == 0 || price == 0  || place.length() == 0  || house_or_apartment == -1
                            || area_size == 0  || shared == 0 || year == 0 || none_central_or_self == -1)
                    {
                        flag = 1;
                        message = "Empty";
                        url = "/add_for_rent.jsp";
                    }
                    if (flag==0){

                        String info = "Price: " + price + " euros, Area size: " +area_size +
                                " squared meters in " + place;
                        //MAIN KWDIKAS GIA QUERIES
                        String sql = null;
                        //Add the data into the database
                        sql = "insert into house_rent values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
                        try (PreparedStatement pst = connection.prepareStatement(sql)) {
                            pst.setInt(1, idhouse_rent);
                            pst.setInt(2, price);
                            pst.setString(3, place);
                            pst.setInt(4, area_size);
                            pst.setInt(5, house_or_apartment);
                            pst.setInt(6, shared);
                            pst.setInt(7, year);
                            pst.setInt(8, none_central_or_self);
                            pst.setString(9, description);
                            pst.setString(10, username);
                            pst.setDouble(11,lng);
                            pst.setDouble(12,lat);
                            pst.setString(13, info);

                            pst.executeUpdate();
                            message = "registered";
                            url = "/main_page.jsp";
                        }
                    }

                    //ta messages einai gia na eidopoihsh ton xrhsth gia
                    //alert periptwsh ,h gia epityxia
                    request.setAttribute("messages", message);
                    connection.close();
                    stmt.close();
                    RequestDispatcher dispatcher =
                            getServletContext().getRequestDispatcher(url);
                    dispatcher.forward(request, response);

                } catch (SQLException ex) {
                    Logger.getLogger(AddRentServlet.class.getName()).log(Level.SEVERE, null, ex);
                }

    }
}


text:
//package com.mjiayou.trecore.manager;
//
//import android.app.Activity;
//import android.content.Intent;
//import android.os.Looper;
//import android.os.Process;
//import android.widget.Toast;
//
//import com.mjiayou.trecore.base.TCApp;
//import com.mjiayou.trecore.common.Configs;
//import com.mjiayou.trecore.helper.UmengHelper;
//import com.mjiayou.trecore.util.ThrowableUtil;
//import com.mjiayou.trecorelib.util.AppUtil;
//import com.mjiayou.trecorelib.util.DateUtil;
//import com.mjiayou.trecorelib.util.DeviceUtil;
//import com.mjiayou.trecorelib.util.DirectoryUtil;
//import com.mjiayou.trecorelib.util.FileUtil;
//import com.mjiayou.trecorelib.util.LogUtil;
//import com.mjiayou.trecorelib.util.ToastUtil;
//
///**
// * Created by treason on 15/11/18.
// */
//public class CrashHandler {
//
//    public static final String TAG = CrashHandler.class.getSimpleName();
//
//    // CrashHandler 实例
//    private static CrashHandler mInstance;
//    // 来自 MainActivity 的 mActivity,主要用户异常时,弹出分享界面
//    private Activity mActivity;
//    // 系统默认的 UncaughtException 处理类
//    private Thread.UncaughtExceptionHandler mDefaultUncaughtExceptionHandler;
//
//    /**
//     * 保证只有一个实例
//     */
//    private CrashHandler() {
//    }
//
//    /**
//     * 单例模式获取CrashHandler实例
//     */
//    public static CrashHandler get() {
//        if (mInstance == null) {
//            mInstance = new CrashHandler();
//        }
//        return mInstance;
//    }
//
//    /**
//     * 初始化
//     */
//    public void init(Activity activity) {
//        LogUtil.printInit(TAG);
//
//        mActivity = activity;
//        mDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
//
//        // 设置该 CrashHandler 为程序的默认处理器
//        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
//            @Override
//            public void uncaughtException(Thread thread, Throwable throwable) {
//                // 手动向 Umeng 提交 Throwable
//                try {
//                    UmengHelper.reportError(TCApp.get(), throwable);
//                } catch (Exception e) {
//                    LogUtil.printStackTrace(e);
//                }
//
//                // 处理未捕获异常
//                if (handleException(throwable)) { // 用户处理异常
//                    try {
//                        Thread.sleep(Configs.DELAY_CRASH_FINISH);
//                    } catch (InterruptedException e) {
//                        LogUtil.printStackTrace(e);
//                    }
//                    // 退出程序
//                    Process.killProcess(Process.myPid());
//                    System.exit(1);
//                } else { // 如果用户没有处理则让系统默认的异常处理器来处理
//                    if (mDefaultUncaughtExceptionHandler != null) {
//                        mDefaultUncaughtExceptionHandler.uncaughtException(thread, throwable);
//                    }
//                }
//            }
//        });
//    }
//
//    /**
//     * 自定义错误处理,收集错误信息、分享错误报告等操作均在此完成。
//     *
//     * @return true-处理了该异常信息;否则返回false。
//     */
//    private boolean handleException(Throwable throwable) {
//        if (throwable == null) {
//            return false;
//        }
//
//        try {
//            // 使用Toast来显示异常信息
//            new Thread() {
//                @Override
//                public void run() {
//                    Looper.prepare();
//                    ToastUtil.show("很抱歉,程序出现异常,即将退出。", Toast.LENGTH_LONG);
//                    Looper.loop();
//                }
//            }.start();
//
//            dealWithCrash(throwable);
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return false;
//    }
//
//    /**
//     * 收集设备参数信息,保存错误信息到文件中
//     */
//    private void dealWithCrash(Throwable throwable) {
//        try {
//            // 设置保存文件路径和内容
//            String fileDir = DirectoryUtil.get().APP_LOG;
//            String fileName = buildFileName();
//            String filePath = fileDir + fileName;
//            String fileContent = buildFileContent(throwable);
//
//            // 分享文件内容
//            shareText(fileContent);
//
//            // 保存文件
//            FileUtil.writeToFile(filePath, fileContent);
//            logFileInfo(filePath, fileContent);
//
//            // 重启应用
//            // restartApp();
//        } catch (Exception e) {
//            LogUtil.printStackTrace(e);
//        }
//    }
//
//    /**
//     * 构建文件名
//     */
//    private String buildFileName() {
//        return "crash-" + DateUtil.parseString(System.currentTimeMillis(), DateUtil.FormatType.FORMAT_302) + ".log";
//    }
//
//    /**
//     * 构建文件内容
//     */
//    private String buildFileContent(Throwable throwable) {
//        StringBuilder builder = new StringBuilder();
//        // time
//        builder.append("-------- DateTime --------").append("\n");
//        builder.append(DateUtil.parseString(System.currentTimeMillis(), DateUtil.FormatType.FORMAT_101)).append("\n");
//        // VersionInfo
//        builder.append("-------- VersionInfo --------").append("\n");
//        builder.append(AppUtil.getVersionInfo(TCApp.get()));
//        // ThrowableInfo
//        builder.append("-------- ThrowableInfo --------").append("\n");
//        builder.append(ThrowableUtil.getThrowableInfo(throwable));
//        // BuildInfo
//        builder.append("-------- BuildInfo --------").append("\n");
//        builder.append(DeviceUtil.getBuildInfo());
//        return builder.toString();
//    }
//
//    /**
//     * 分享
//     */
//    private void shareText(String text) {
//        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_SEND);
//        intent.setType("text/plain"); // 纯文本
//        intent.putExtra(Intent.EXTRA_TEXT, text);
//        mActivity.startActivity(intent);
//    }
//
//    /**
//     * LOG
//     */
//    private void logFileInfo(String filePath, String fileContent) {
////        StringBuilder builder = new StringBuilder();
////        builder.append("------------------------------------------------").append("\n");
////        builder.append("---------------- filePath ----------------").append("\n");
////        builder.append(filePath).append("\n");
////        builder.append("---------------- fileContent ----------------").append("\n");
////        builder.append(fileContent).append("\n");
////        builder.append("------------------------------------------------").append("\n");
////        LogUtil.e(TAG, builder.toString());
//
//        LogUtil.e(TAG, "------------------------------------------------");
//        LogUtil.e(TAG, "---------------- filePath ----------------");
//        LogUtil.e(TAG, filePath);
//        LogUtil.e(TAG, "---------------- fileContent ----------------");
//        LogUtil.e(TAG, fileContent);
//        LogUtil.e(TAG, "------------------------------------------------");
//    }
//
//    /**
//     * 重新启动应用
//     */
//    private void restartApp() {
//        Intent intent1 = new Intent(mActivity, mActivity.getClass());
//        intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
//        mActivity.startActivity(intent1);
//        System.exit(0);
//    }
//}


text:
#include "Base58.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>

#ifdef _MSC_VER // Disable the stupid ass absurd warning messages from Visual Studio telling you that using stdlib and stdio is 'not valid ANSI C'
#pragma warning(disable:4718)
#pragma warning(disable:4996)
#endif

//
//  BigNumber.c
//  cbitcoin
//
//  Created by Matthew Mitchell on 28/04/2012.
//  Copyright (c) 2012 Matthew Mitchell
//
//  This file is part of cbitcoin.
//
//  cbitcoin 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 of the License, or
//  (at your option) any later version.
//
//  cbitcoin 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 cbitcoin.  If not, see <http://www.gnu.org/licenses/>.
//
//

#define MAX_BIG_NUMBER 256	// this code snippet only supports big nubmers up to 256 bytes in length
/**
 @brief Contains byte data with the length of this data to represent a large integer. The byte data is in little-endian which stores the smallest byte first.
 */
class BigNumber
{
public:
	BigNumber(const uint8_t *sourceData,uint32_t len)
	{
		assert(len<MAX_BIG_NUMBER);
		memset(data,0,MAX_BIG_NUMBER);
		if ( sourceData )
		{
			memcpy(data,sourceData,len);
		}
		length = len;
	}
	uint8_t		data[MAX_BIG_NUMBER]; /**< The byte data. Should be little-endian */
	uint32_t	length; /**< The length of this data in bytes */
};

//  Enums

enum BigNumberCompare
{
	CB_COMPARE_MORE_THAN = 1,
	CB_COMPARE_EQUAL = 0,
	CB_COMPARE_LESS_THAN = -1,
};

/**
 @brief Compares a BigNumber to an 8 bit integer. You can replicate "a op 58" as "BigNumberCompareToUInt8(a, 58) op 0" replacing "op" with a comparison operator.
 @param a The first BigNumber
 @returns The result of the comparison as a BigNumberCompare constant. Returns what a is in relation to b.
 */
BigNumberCompare BigNumberCompareTo58(BigNumber * a);
/**
 @brief Compares two BigNumber. You can replicate "a op b" as "BigNumberCompare(a, b) op 0" replacing "op" with a comparison operator.
 @param a The first BigNumber
 @param b The second BigNumber
 @returns The result of the comparison as a BigNumberCompare constant. Returns what a is in relation to b.
 */
BigNumberCompare BigNumberCompareToBigInt(BigNumber * a, BigNumber * b);
/**
 @brief Calculates the result of an addition of a BigNumber structure by another BigNumber structure and the first BigNumber becomes this new figure. Like "a += b".
 @param a A pointer to the BigNumber
 @param b A pointer to the second BigNumber
 @returns true on success, false on failure.
 */
bool BigNumberEqualsAdditionByBigInt(BigNumber * a, BigNumber * b);
/**
 @brief Calculates the result of a division of a BigNumber structure by 58 and the BigNumber becomes this new figure. Like "a /= 58".
 @param a A pointer to the BigNumber
 @param ans A memory block the same size as the BigNumber data memory block to store temporary data in calculations. Should be set with zeros.
 */
void BigNumberEqualsDivisionBy58(BigNumber * a, uint8_t * ans);
/**
 @brief Calculates the result of a multiplication of a BigNumber structure by an 8 bit integer and the BigNumber becomes this new figure. Like "a *= b".
 @param a A pointer to the BigNumber
 @param b An 8 bit integer
 @returns true on success, false on failure
 */
bool BigNumberEqualsMultiplicationByUInt8(BigNumber * a, uint8_t b);
/**
 @brief Calculates the result of a subtraction of a BigNumber structure with another BigNumber structure and the BigNumber becomes this new figure. Like "a -= b".
 @param a A pointer to a BigNumber
 @param b A pointer to a BigNumber
 */
void BigNumberEqualsSubtractionByBigInt(BigNumber * a, BigNumber * b);
/**
 @brief Calculates the result of a subtraction of a BigNumber structure by an 8 bit integer and the BigNumber becomes this new figure. Like "a -= b".
 @param a A pointer to the BigNumber
 @param b An 8 bit integer
 */
void BigNumberEqualsSubtractionByUInt8(BigNumber * a, uint8_t b);
/**
 @brief Assigns a BigNumber as the exponentiation of an unsigned 8 bit intger with another unsigned 8 bit integer. Like "a^b". Data must be freed.
 @param bi The BigNumber. Preallocate this with at least one byte.
 @param a The base
 @param b The exponent.
 @returns true on success, false on failure.
 */
bool BigNumberFromPowUInt8(BigNumber * bi, uint8_t a, uint8_t b);
/**
 @brief Returns the result of a modulo of a BigNumber structure and 58. Like "a % 58".
 @param a The BigNumber
 @returns The result of the modulo operation as an 8 bit integer.
 */
uint8_t BigNumberModuloWith58(BigNumber * a);
/**
 @brief Normalises a BigNumber so that there are no unnecessary trailing zeros.
 @param a A pointer to the BigNumber
 */
void BigNumberNormalise(BigNumber * a);

BigNumberCompare BigNumberCompareTo58(BigNumber * a)
{
	if(a->length > 1)
		return CB_COMPARE_MORE_THAN;
	if (a->data[0] > 58)
		return CB_COMPARE_MORE_THAN;
	else if (a->data[0] < 58)
		return CB_COMPARE_LESS_THAN;
	return CB_COMPARE_EQUAL;
}

BigNumberCompare BigNumberCompareToBigInt(BigNumber * a, BigNumber * b)
{
	if (a->length > b->length)
		return CB_COMPARE_MORE_THAN;
	else if (a->length < b->length)
		return CB_COMPARE_LESS_THAN;
	for (uint32_t x = a->length; x--;)
	{
		if (a->data[x] < b->data[x])
			return CB_COMPARE_LESS_THAN;
		else if (a->data[x] > b->data[x])
			return CB_COMPARE_MORE_THAN;
	}
	return CB_COMPARE_EQUAL;
}
bool BigNumberEqualsAdditionByBigInt(BigNumber * a, BigNumber * b)
{
	if (a->length < b->length)
	{
		// Make certain expansion of data is empty
		memset(a->data + a->length, 0, b->length - a->length);
		a->length = b->length;
	}
	// a->length >= b->length
	bool overflow = 0;
	uint8_t x = 0;
	for (; x < b->length; x++)
	{
		a->data[x] += b->data[x] + overflow;
		// a->data[x] now equals the result of the addition.
		// The overflow will never go beyond 1. Imagine a->data[x] == 0xff, b->data[x] == 0xff and the overflow is 1, the new overflow is still 1 and a->data[x] is 0xff. Therefore it does work.
		overflow = (a->data[x] < (b->data[x] + overflow))? 1 : 0;
	}
	// Propagate overflow up the whole length of a if necessary
	while (overflow && x < a->length)
		overflow = ! ++a->data[x++]; // Index at x, increment x, increment data, test new value for overflow.
	if (overflow)
	{ // Add extra byte
		a->length++;
		assert( a->length < MAX_BIG_NUMBER );
		a->data[a->length - 1] = 1;
	}
	return true;
}
void BigNumberEqualsDivisionBy58(BigNumber * a, uint8_t * ans)
{
	if (a->length == 1 && ! a->data[0]) // "a" is zero
		return;
	// base-256 long division.
	uint16_t temp = 0;
	for (uint32_t x = a->length; x--;)
	{
		temp <<= 8;
		temp |= a->data[x];
		ans[x] = (uint8_t)(temp / 58);
		temp -= ans[x] * 58;
	}
	if (! ans[a->length-1]) // If last byte is zero, adjust length.
		a->length--;
	memmove(a->data, ans, a->length); // Done calculation. Move ans to "a".
}
bool BigNumberEqualsMultiplicationByUInt8(BigNumber * a, uint8_t b)
{
	if (! b)
	{
		// Mutliplication by zero. "a" becomes zero
		a->length = 1;
		a->data[0] = 0;
		return true;
	}
	if (a->length == 1 && ! a->data[0]) // "a" is zero
		return true;
	// Multiply b by each byte and then add to answer
	uint16_t carry = 0;
	uint8_t x = 0;
	for (; x < a->length; x++)
	{
		carry = carry + a->data[x] * b; // Allow for overflow onto next byte.
		a->data[x] = (uint8_t)carry;
		carry >>= 8;
	}
	if (carry)
	{ // If last byte is not zero, adjust length.
		a->length++;
		assert( a->length < MAX_BIG_NUMBER );
		a->data[x] = (uint8_t)carry;
	}
	return true;
}
void BigNumberEqualsSubtractionByBigInt(BigNumber * a, BigNumber * b)
{
	uint8_t x;
	bool carry = 0;
	// This can be made much nicer when using signed arithmetic,
	// carry and tmp could be merged to be 0 or -1 between rounds.
	for (x = 0; x < b->length; x++) {
		uint16_t tmp = carry + b->data[x];
		carry = a->data[x] < tmp;
		a->data[x] -= (uint8_t)tmp;
	}
	if (carry)
		a->data[x]--;
	BigNumberNormalise(a);
}

void BigNumberEqualsSubtractionByUInt8(BigNumber * a, uint8_t b)
{
	uint8_t carry = b;
	uint8_t x = 0;
	for (; a->data[x] < carry; x++){
		a->data[x] = 255 - carry + a->data[x] + 1;
		carry = 1;
	}
	a->data[x] -= carry;
	BigNumberNormalise(a);
}

bool BigNumberFromPowUInt8(BigNumber * bi, uint8_t a, uint8_t b)
{
	bi->length = 1;
	bi->data[0] = 1;
	for (uint8_t x = 0; x < b; x++) {
		if (! BigNumberEqualsMultiplicationByUInt8(bi, a))
			// ERROR
			return false;
	}
	return true;
}

uint8_t BigNumberModuloWith58(BigNumber * a)
{
	// Use method presented here: http://stackoverflow.com/a/10441333/238411
	uint16_t result = 0; // Prevent overflow in calculations
	for(uint32_t x = a->length - 1;; x--){
		result *= (256 % 58);
		result %= 58;
		result += a->data[x] % 58;
		result %= 58;
		if (! x)
			break;
	}
	return (uint8_t)result;
}

void BigNumberNormalise(BigNumber * a)
{
	while (a->length > 1 && ! a->data[a->length-1])
		a->length--;
}

//                                                  1         2         3         4         5
//                                        01234567890123456789012345678901234567890123456789012345678
static const char base58Characters[59] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

/**
 @brief Decodes base 58 string into byte data as a BigNumber.
 @param bi The BigNumber which should be preallocated with at least one byte.
 @param str Base 58 string to decode.
 @returns true on success, false on failure.
 */
bool CBDecodeBase58(BigNumber * bi,const char * str)
{
	// ??? Quite likely these functions can be improved
	BigNumber bi2(NULL,1);

	uint32_t slen = (uint32_t)strlen(str);

	for (uint32_t x = slen - 1;; x--)
	{ // Working backwards
		// Get index in alphabet array
		uint8_t alphaIndex = str[x];
		if (alphaIndex != 49)
		{ // If not 1
			if (str[x] < 58)
			{ // Numbers
				alphaIndex -= 49;
			}
			else if (str[x] < 73)
			{ // A-H
				alphaIndex -= 56;
			}
			else if (str[x] < 79)
			{ // J-N
				alphaIndex -= 57;
			}
			else if (str[x] < 91)
			{ // P-Z
				alphaIndex -= 58;
			}
			else if (str[x] < 108)
			{ // a-k
				alphaIndex -= 64;
			}
			else
			{ // m-z
				alphaIndex -= 65;
			}
			if (! BigNumberFromPowUInt8(&bi2, 58, (uint8_t)(slen - 1 - x)))
			{
				// Error occured.
				return false;
			}
			if (! BigNumberEqualsMultiplicationByUInt8(&bi2, alphaIndex))
			{
				// Error occured.
				return false;
			}
			if (! BigNumberEqualsAdditionByBigInt(bi, &bi2))
			{
				// Error occured.
				return false;
			}
		}
		if (!x)
			break;
	}
	// Got BigNumber from base-58 string. Add zeros on end.
	uint8_t zeros = 0;
	for (uint8_t x = 0; x < slen; x++)
	{
		if (str[x] == '1')
		{
			zeros++;
		}
		else
		{
			break;
		}
	}
	if (zeros)
	{
		bi->length += zeros;
		assert( bi->length < MAX_BIG_NUMBER );
		memset(bi->data + bi->length - zeros, 0, zeros);
	}
	return true;
}

bool CBEncodeBase58(BigNumber * bi,char *str,uint32_t maxStrLen)
{
	if ( maxStrLen < bi->length ) // must be at least twice the size of the binary
	{
		return false;
	}
	uint32_t x = 0;
	// Zeros
	for (uint32_t y = bi->length - 1;; y--)
	{
		if (! bi->data[y])
		{
			str[x] = '1';
			x++;
			if (! y)
				break;
		}
		else
		{
			break;
		}
	}
	uint32_t zeros = x;
	// Make temporary data store
	uint8_t temp[MAX_BIG_NUMBER];
	// Encode
	uint8_t mod;
	size_t size = bi->length;
	for (;BigNumberCompareTo58(bi) >= 0;x++)
	{
		mod = BigNumberModuloWith58(bi);
		if (bi->length < x + 3)
		{
			size = x + 3;
			if (size > bi->length)
			{
				if ( size > maxStrLen )
				{
					return false;
				}
			}
		}
		str[x] = base58Characters[mod];
		BigNumberEqualsSubtractionByUInt8(bi, mod);
		memset(temp, 0, bi->length);
		BigNumberEqualsDivisionBy58(bi, temp);
	}
	str[x] = base58Characters[bi->data[bi->length-1]];
	x++;
	// Reversal
	for (uint8_t y = 0; y < (x-zeros) / 2; y++)
	{
		char temp = str[y+zeros];
		str[y+zeros] = str[x-y-1];
		str[x-y-1] = temp;
	}
	str[x] = '\0';
	return true;
}

bool encodeBase58(const uint8_t *bigNumber, // The block of memory corresponding to the 'big number'
					   uint32_t length,			 // The number of bytes in the 'big-number'; this will be 25 for a bitcoin address
					   bool isBigEndian,		 // True if the input number is in little-endian format (this will be true for a bitcoin address)
					   char *output,			 // The address to store the output string.
					   uint32_t maxStrLen)		 // the maximum length of the output string
{
	// Before passing the hash into the base58 encoder; we need to reverse the byte order.
	uint8_t hash[25];
	if ( isBigEndian )
	{
		uint32_t index = length-1;
		for (uint32_t i=0; i<25; i++)
		{
			hash[i] = bigNumber[index];
			index--;
		}
	}
	else
	{
		memcpy(hash,bigNumber,length);
	}
	// We now have the 25 byte public key address in binary; we just need to convert it to ASCII
	// This involves using large integer math to compute the base58 encoding (with check)
	BigNumber bytes(hash,length);;
	return CBEncodeBase58(&bytes,output,maxStrLen);
}

uint32_t decodeBase58(const char *string,		// The base58 encoded string
					   uint8_t *output,			// The output binary buffer
					   uint32_t maxOutputLength, // The maximum output length of the binary buffer.
					   bool isBigEndian) // If the output needs to be in little endian format
{
	uint32_t ret = 0;

	BigNumber bn(NULL,0);
	if ( CBDecodeBase58(&bn,string) && bn.length <= maxOutputLength )
	{
		ret = bn.length;
		if ( isBigEndian ) // if the caller wants the number returned in little endian format; then we byte reverse the output
		{
			uint32_t index = bn.length-1;
			for (uint32_t i=0; i<bn.length; i++)
			{
				output[i] = bn.data[index];
				index--;
			}
		}
		else
		{
			memcpy(output,bn.data,bn.length);
		}
	}

	return ret;
}