text:
package org.postgresql.core;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.HashMap;

/**
 * Representation of a particular character encoding.
 */
public class Encoding
{
    private static final Encoding DEFAULT_ENCODING = new Encoding(null);

    /*
     * Preferred JVM encodings for backend encodings.
     */
    private static final HashMap encodings = new HashMap();

    static {
        //Note: this list should match the set of supported server
        // encodings found in backend/util/mb/encnames.c
        encodings.put("SQL_ASCII", new String[] { "ASCII", "us-ascii" });
        encodings.put("UNICODE", new String[] { "UTF-8", "UTF8" });
        encodings.put("UTF8", new String[] { "UTF-8", "UTF8" }); // 8.1's canonical name for UNICODE changed.
        encodings.put("LATIN1", new String[] { "ISO8859_1" });
        encodings.put("LATIN2", new String[] { "ISO8859_2" });
        encodings.put("LATIN3", new String[] { "ISO8859_3" });
        encodings.put("LATIN4", new String[] { "ISO8859_4" });
        encodings.put("ISO_8859_5", new String[] { "ISO8859_5" });
        encodings.put("ISO_8859_6", new String[] { "ISO8859_6" });
        encodings.put("ISO_8859_7", new String[] { "ISO8859_7" });
        encodings.put("ISO_8859_8", new String[] { "ISO8859_8" });
        encodings.put("LATIN5", new String[] { "ISO8859_9" });
        encodings.put("LATIN7", new String[] { "ISO8859_13" });
        encodings.put("LATIN9", new String[] { "ISO8859_15_FDIS" });
        encodings.put("EUC_JP", new String[] { "EUC_JP" });
        encodings.put("EUC_CN", new String[] { "EUC_CN" });
        encodings.put("EUC_KR", new String[] { "EUC_KR" });
        encodings.put("JOHAB", new String[] { "Johab" });
        encodings.put("EUC_TW", new String[] { "EUC_TW" });
        encodings.put("SJIS", new String[] { "MS932", "SJIS" });
        encodings.put("BIG5", new String[] { "Big5", "MS950", "Cp950" });
        encodings.put("GBK", new String[] { "GBK", "MS936" });
        encodings.put("UHC", new String[] { "MS949", "Cp949", "Cp949C" });
        encodings.put("TCVN", new String[] { "Cp1258" });
        encodings.put("WIN1256", new String[] { "Cp1256" });
        encodings.put("WIN1250", new String[] { "Cp1250" });
        encodings.put("WIN874", new String[] { "MS874", "Cp874" });
        encodings.put("WIN", new String[] { "Cp1251" });
        encodings.put("ALT", new String[] { "Cp866" });
        // We prefer KOI8-U, since it is a superset of KOI8-R.
        encodings.put("KOI8", new String[] { "KOI8_U", "KOI8_R" });
        // If the database isn't encoding-aware then we can't have
        // any preferred encodings.
        encodings.put("UNKNOWN", new String[0]);
        // The following encodings do not have a java equivalent
        encodings.put("MULE_INTERNAL", new String[0]);
        encodings.put("LATIN6", new String[0]);
        encodings.put("LATIN8", new String[0]);
        encodings.put("LATIN10", new String[0]);
    }

    private final String encoding;
    private final boolean fastASCIINumbers;

    protected Encoding(String encoding)
    {
        this.encoding = encoding;
        fastASCIINumbers = testAsciiNumbers();
    }

    /**
     * Returns true if this encoding has characters
     * '-' and '0'..'9' in exactly same posision as ascii.
     *
     * @return true if the bytes can be scanned directly for ascii numbers.
     */
    public boolean hasAsciiNumbers() {
        return fastASCIINumbers;
    }

    /**
     * Construct an Encoding for a given JVM encoding.
     *
     * @param jvmEncoding the name of the JVM encoding
     * @return an Encoding instance for the specified encoding,
     *   or an Encoding instance for the default JVM encoding if the
     *   specified encoding is unavailable.
     */
    public static Encoding getJVMEncoding(String jvmEncoding) {
        if (isAvailable(jvmEncoding))
        {
            if (jvmEncoding.equals("UTF-8") || jvmEncoding.equals("UTF8"))
                return new UTF8Encoding(jvmEncoding);
            else
                return new Encoding(jvmEncoding);
        }
        else
            return defaultEncoding();
    }

    /**
     * Construct an Encoding for a given database encoding.
     *
     * @param databaseEncoding the name of the database encoding
     * @return an Encoding instance for the specified encoding,
     *   or an Encoding instance for the default JVM encoding if the
     *   specified encoding is unavailable.
     */
    public static Encoding getDatabaseEncoding(String databaseEncoding)
    {
        // If the backend encoding is known and there is a suitable
        // encoding in the JVM we use that. Otherwise we fall back
        // to the default encoding of the JVM.

        String[] candidates = (String[]) encodings.get(databaseEncoding);
        if (candidates != null)
        {
            for (int i = 0; i < candidates.length; i++)
            {
                if (isAvailable(candidates[i]))
                {
                    return new Encoding(candidates[i]);
                }
            }
        }

        // Try the encoding name directly -- maybe the charset has been
        // provided by the user.
        if (isAvailable(databaseEncoding))
            return new Encoding(databaseEncoding);

        // Fall back to default JVM encoding.
        return defaultEncoding();
    }

    /**
     * Get the name of the (JVM) encoding used.
     *
     * @return the JVM encoding name used by this instance.
     */
    public String name()
    {
        return encoding;
    }

    /**
     * Encode a string to an array of bytes.
     *
     * @param s the string to encode
     * @return a bytearray containing the encoded string
     * @throws IOException if something goes wrong
     */
    public byte[] encode(String s) throws IOException
    {
        if (s == null)
            return null;

        if (encoding == null)
            return s.getBytes();

        return s.getBytes(encoding);
    }

    /**
     * Decode an array of bytes into a string.
     *
     * @param encodedString a bytearray containing the encoded string  the string to encod
     * @param offset the offset in encodedString of the first byte of the encoded representation
     * @param length the length, in bytes, of the encoded representation
     * @return the decoded string
     * @throws IOException if something goes wrong
     */
    public String decode(byte[] encodedString, int offset, int length) throws IOException
    {
        if (encoding == null)
            return new String(encodedString, offset, length);

        return new String(encodedString, offset, length, encoding);
    }

    /**
     * Decode an array of bytes into a string.
     *
     * @param encodedString a bytearray containing the encoded string  the string to encod
     * @return the decoded string
     * @throws IOException if something goes wrong
     */
    public String decode(byte[] encodedString) throws IOException
    {
        return decode(encodedString, 0, encodedString.length);
    }

    /**
     * Get a Reader that decodes the given InputStream using this encoding.
     *
     * @param in the underlying stream to decode from
     * @return a non-null Reader implementation.
     * @throws IOException if something goes wrong
     */
    public Reader getDecodingReader(InputStream in) throws IOException
    {
        if (encoding == null)
            return new InputStreamReader(in);

        return new InputStreamReader(in, encoding);
    }

    /**
     * Get a Writer that encodes to the given OutputStream using this encoding.
     *
     * @param out the underlying stream to encode to
     * @return a non-null Writer implementation.
     * @throws IOException if something goes wrong
     */
    public Writer getEncodingWriter(OutputStream out) throws IOException
    {
        if (encoding == null)
            return new OutputStreamWriter(out);

        return new OutputStreamWriter(out, encoding);
    }

    /**
     * Get an Encoding using the default encoding for the JVM.
     * @return an Encoding instance
     */
    public static Encoding defaultEncoding()
    {
        return DEFAULT_ENCODING;
    }

    /**
     * Test if an encoding is available in the JVM.
     *
     * @param encodingName the JVM encoding name to test
     * @return true iff the encoding is supported
     */
    private static boolean isAvailable(String encodingName)
    {
        try
        {
            "DUMMY".getBytes(encodingName);
            return true;
        }
        catch (java.io.UnsupportedEncodingException e)
        {
            return false;
        }
    }

    public String toString() {
        return (encoding == null ? "<default JVM encoding>" : encoding);
    }

    /**
     * Checks weather this encoding is compatible with ASCII for the number
     * characters '-' and '0'..'9'. Where compatible means that they are encoded
     * with exactly same values.
     *
     * @return If faster ASCII number parsing can be used with this encoding.
     */
    private boolean testAsciiNumbers() {
        // TODO: test all postgres supported encoding to see if there are
        // any which do _not_ have ascii numbers in same location
        // at least all the encoding listed in the encodings hashmap have
        // working ascii numbers
	try {
	    String test = "-0123456789";
	    byte[] bytes = encode(test);
	    String res = new String(bytes, "US-ASCII");
	    return test.equals(res);
	} catch (java.io.UnsupportedEncodingException e) {
	    return false;
	} catch (IOException e) {
	    return false;
	}
    }
}


text:
package com.palantir.atlasdb.timelock.paxos;

import com.google.common.collect.Maps;
import com.palantir.paxos.Client;
import com.palantir.timelock.paxos.HealthCheckPinger;
import com.palantir.timelock.paxos.HealthCheckResponse;
import java.util.Map;
import java.util.Set;

public final class MultiLeaderHealthCheckPinger implements HealthCheckPinger {

    private final BatchPingableLeader batchPingableLeader;

    public MultiLeaderHealthCheckPinger(BatchPingableLeader batchPingableLeader) {
        this.batchPingableLeader = batchPingableLeader;
    }

    @Override
    public Map<Client, HealthCheckResponse> apply(Set<Client> request) {
        Set<Client> results = batchPingableLeader.ping(request);
        return Maps.toMap(request, client -> new HealthCheckResponse(results.contains(client)));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.jboss.hal.client.configuration.subsystem.mail;

import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.annotation.Nullable;
import javax.inject.Inject;

import org.jboss.hal.ballroom.autocomplete.ReadChildrenAutoComplete;
import org.jboss.hal.ballroom.form.Form;
import org.jboss.hal.ballroom.form.Form.FinishReset;
import org.jboss.hal.ballroom.form.FormItem;
import org.jboss.hal.ballroom.form.SingleSelectBoxItem;
import org.jboss.hal.ballroom.form.TextBoxItem;
import org.jboss.hal.core.CrudOperations;
import org.jboss.hal.core.finder.Finder;
import org.jboss.hal.core.finder.FinderPath;
import org.jboss.hal.core.finder.FinderPathFactory;
import org.jboss.hal.core.mbui.dialog.AddResourceDialog;
import org.jboss.hal.core.mbui.form.ModelNodeForm;
import org.jboss.hal.core.mvp.ApplicationFinderPresenter;
import org.jboss.hal.core.mvp.HalView;
import org.jboss.hal.core.mvp.HasPresenter;
import org.jboss.hal.core.mvp.SupportsExpertMode;
import org.jboss.hal.dmr.ModelDescriptionConstants;
import org.jboss.hal.dmr.ModelNode;
import org.jboss.hal.dmr.NamedNode;
import org.jboss.hal.dmr.Operation;
import org.jboss.hal.dmr.ResourceAddress;
import org.jboss.hal.dmr.dispatch.Dispatcher;
import org.jboss.hal.meta.Metadata;
import org.jboss.hal.meta.MetadataRegistry;
import org.jboss.hal.meta.SelectionAwareStatementContext;
import org.jboss.hal.meta.StatementContext;
import org.jboss.hal.meta.token.NameTokens;
import org.jboss.hal.resources.Ids;
import org.jboss.hal.resources.Names;
import org.jboss.hal.resources.Resources;
import org.jboss.hal.spi.Message;
import org.jboss.hal.spi.MessageEvent;
import org.jboss.hal.spi.Requires;

import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest;

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toSet;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.MAIL_ADDRESS;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.MAIL_SESSION_ADDRESS;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.MAIL_SESSION_TEMPLATE;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.SELECTED_MAIL_SESSION_TEMPLATE;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.SERVER_ADDRESS;
import static org.jboss.hal.client.configuration.subsystem.mail.AddressTemplates.SERVER_TEMPLATE;
import static org.jboss.hal.dmr.ModelDescriptionConstants.CHILD_TYPE;
import static org.jboss.hal.dmr.ModelDescriptionConstants.IMAP;
import static org.jboss.hal.dmr.ModelDescriptionConstants.MAIL;
import static org.jboss.hal.dmr.ModelDescriptionConstants.NAME;
import static org.jboss.hal.dmr.ModelDescriptionConstants.OUTBOUND_SOCKET_BINDING_REF;
import static org.jboss.hal.dmr.ModelDescriptionConstants.PASSWORD;
import static org.jboss.hal.dmr.ModelDescriptionConstants.POP3;
import static org.jboss.hal.dmr.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION;
import static org.jboss.hal.dmr.ModelDescriptionConstants.SERVER;
import static org.jboss.hal.dmr.ModelDescriptionConstants.SMTP;
import static org.jboss.hal.dmr.ModelDescriptionConstants.USERNAME;

public class MailSessionPresenter
        extends ApplicationFinderPresenter<MailSessionPresenter.MyView, MailSessionPresenter.MyProxy>
        implements SupportsExpertMode {

    private static final String EQUALS = "=";

    private final Resources resources;
    private final Dispatcher dispatcher;
    private final StatementContext statementContext;
    private final CrudOperations crud;
    private final FinderPathFactory finderPathFactory;
    private final MetadataRegistry metadataRegistry;
    private String mailSessionName;

    @Inject
    public MailSessionPresenter(EventBus eventBus,
            MyView view,
            MyProxy proxy,
            Finder finder,
            CrudOperations crud,
            FinderPathFactory finderPathFactory,
            Resources resources,
            Dispatcher dispatcher,
            StatementContext statementContext,
            MetadataRegistry metadataRegistry) {
        super(eventBus, view, proxy, finder);
        this.crud = crud;
        this.finderPathFactory = finderPathFactory;
        this.metadataRegistry = metadataRegistry;
        this.resources = resources;
        this.dispatcher = dispatcher;
        this.statementContext = new SelectionAwareStatementContext(statementContext, () -> mailSessionName);
    }

    @Override
    protected void onBind() {
        super.onBind();
        getView().setPresenter(this);
    }

    @Override
    public void prepareFromRequest(PlaceRequest request) {
        super.prepareFromRequest(request);
        mailSessionName = request.getParameter(NAME, null);
    }

    @Override
    public ResourceAddress resourceAddress() {
        return SELECTED_MAIL_SESSION_TEMPLATE.resolve(statementContext);
    }

    @Override
    public FinderPath finderPath() {
        return finderPathFactory.configurationSubsystemPath(MAIL)
                .append(Ids.MAIL_SESSION, Ids.mailSession(mailSessionName), Names.MAIL_SESSION, mailSessionName);
    }

    @Override
    protected void reload() {
        ResourceAddress address = SELECTED_MAIL_SESSION_TEMPLATE.resolve(statementContext);
        crud.readRecursive(address, result -> getView().update(new MailSession(mailSessionName, result)));
    }

    void saveMailSession(Map<String, Object> changedValues) {
        ResourceAddress address = SELECTED_MAIL_SESSION_TEMPLATE.resolve(statementContext);
        Metadata metadata = metadataRegistry.lookup(MAIL_SESSION_TEMPLATE);
        crud.save(Names.MAIL_SESSION, mailSessionName, address, changedValues, metadata, this::reload);
    }

    void resetMailSession(Form<MailSession> form) {
        ResourceAddress address = SELECTED_MAIL_SESSION_TEMPLATE.resolve(statementContext);
        Metadata metadata = metadataRegistry.lookup(MAIL_SESSION_TEMPLATE);
        crud.reset(Names.MAIL_SESSION, mailSessionName, address, form, metadata, new FinishReset<MailSession>(form) {
            @Override
            public void afterReset(Form<MailSession> form) {
                reload();
            }
        });
    }

    void launchAddServer() {
        SortedSet<String> availableServers = new TreeSet<>(asList(SMTP.toUpperCase(),
                IMAP.toUpperCase(), POP3.toUpperCase()));
        ResourceAddress selectedSessionAddress = SELECTED_MAIL_SESSION_TEMPLATE
                .resolve(statementContext);
        Operation serverNamesOp = new Operation.Builder(selectedSessionAddress, READ_CHILDREN_NAMES_OPERATION)
                .param(CHILD_TYPE, SERVER)
                .build();
        dispatcher.execute(serverNamesOp, serversResult -> {
            Set<String> existingServers = serversResult.asList().stream()
                    .map(node -> node.asString().toUpperCase())
                    .collect(toSet());
            availableServers.removeAll(existingServers);

            if (availableServers.isEmpty()) {
                MessageEvent.fire(getEventBus(), Message.error(resources.messages().allMailServersExist()));

            } else {
                FormItem<String> serverTypeItem;
                if (availableServers.size() == 1) {
                    serverTypeItem = new TextBoxItem(ModelDescriptionConstants.SERVER_TYPE,
                            resources.constants().type());
                    serverTypeItem.setValue(availableServers.first());
                    serverTypeItem.setEnabled(false);

                } else {
                    serverTypeItem = new SingleSelectBoxItem(ModelDescriptionConstants.SERVER_TYPE,
                            resources.constants().type(), new ArrayList<>(availableServers), false);
                    serverTypeItem.setRequired(true);
                }
                Metadata metadata = metadataRegistry.lookup(AddressTemplates.SERVER_TEMPLATE);
                Form<ModelNode> form = new ModelNodeForm.Builder<>(Ids.MAIL_SERVER_DIALOG, metadata)
                        .unboundFormItem(serverTypeItem, 0)
                        .include(OUTBOUND_SOCKET_BINDING_REF, USERNAME, PASSWORD, "ssl", "tls")
                        .fromRequestProperties()
                        .requiredOnly()
                        .unsorted()
                        .build();
                form.getFormItem(OUTBOUND_SOCKET_BINDING_REF).registerSuggestHandler(
                        new ReadChildrenAutoComplete(dispatcher, statementContext,
                                AddressTemplates.SOCKET_BINDING_TEMPLATE));

                AddResourceDialog dialog = new AddResourceDialog(
                        resources.messages().addResourceTitle(Names.SERVER), form,
                        (name, modelNode) -> {
                            String serverType = serverTypeItem.getValue().toLowerCase();
                            ResourceAddress address = SELECTED_MAIL_SESSION_TEMPLATE
                                    .append(SERVER + EQUALS + serverType)
                                    .resolve(statementContext);
                            Operation operation = new Operation.Builder(address, ModelDescriptionConstants.ADD)
                                    .payload(modelNode)
                                    .build();
                            dispatcher.execute(operation, result -> {
                                MessageEvent.fire(getEventBus(),
                                        Message.success(resources.messages()
                                                .addResourceSuccess(Names.SERVER, serverType)));
                                reload();
                            });
                        });
                dialog.show();
            }
        });
    }

    void saveServer(String mailServer, Map<String, Object> changedValues) {
        ResourceAddress address = SELECTED_MAIL_SESSION_TEMPLATE
                .append(SERVER + EQUALS + mailServer)
                .resolve(statementContext);
        Metadata metadata = metadataRegistry.lookup(SERVER_TEMPLATE);
        crud.save(Names.SERVER, mailServer, address, changedValues, metadata, this::reload);
    }

    ResourceAddress credentialReferenceTemplate(@Nullable String mailServer) {
        return mailServer != null
                ? SELECTED_MAIL_SESSION_TEMPLATE.append(SERVER + EQUALS + mailServer).resolve(statementContext)
                : null;
    }

    void resetServer(String mailServer, Form<NamedNode> form) {
        ResourceAddress address = SELECTED_MAIL_SESSION_TEMPLATE
                .append(SERVER + EQUALS + mailServer)
                .resolve(statementContext);
        Metadata metadata = metadataRegistry.lookup(SERVER_TEMPLATE);
        crud.reset(Names.SERVER, mailSessionName, address, form, metadata, new FinishReset<NamedNode>(form) {
            @Override
            public void afterReset(Form<NamedNode> form) {
                reload();
            }
        });
    }

    void removeServer(NamedNode mailServer) {
        String name = mailServer.getName();
        ResourceAddress address = SELECTED_MAIL_SESSION_TEMPLATE
                .append(SERVER + EQUALS + name)
                .resolve(statementContext);
        crud.remove(Names.SERVER, name, address, this::reload);
    }

    // @formatter:off
    @ProxyCodeSplit
    @NameToken(NameTokens.MAIL_SESSION)
    @Requires({ MAIL_ADDRESS, MAIL_SESSION_ADDRESS, SERVER_ADDRESS })
    public interface MyProxy extends ProxyPlace<MailSessionPresenter> {
    }

    public interface MyView extends HalView, HasPresenter<MailSessionPresenter> {
        void update(MailSession mailSession);

        void select(NamedNode mailServer);
    }
    // @formatter:on
}


text:
package main

import "github.com/pnsafonov/luck/tests_http"

func main() {
	tests_http.ExampleListenAndServe()
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**redirect_uri** | **string** | The URL that the customer should be redirected to after they have approved a single sign on session. | [optional]
**state** | **string** | An optional state variable that you provide.  It will be returned to you on the redirect.  You can inspect the state to validate the request is legitimate.  We recommend using this field. | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
@interface LSKRoundedProgressView : UIView

@property (nonatomic, assign) CGFloat progress;

@property (nonatomic, assign) BOOL clockWise;

@property (nonatomic, assign) CGFloat progressWidth;

@property (nonatomic, copy) UIColor *trackColor;
@property (nonatomic, copy) UIColor *progressColor;

@end


text:
<?php

/**
 * This is the model class for table "country".
 *
 * The followings are the available columns in table 'country':
 * @property string $country_code
 * @property string $country_name
 *
 * The followings are the available model relations:
 * @property Employee[] $employees
 */
class Country extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Country the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'country';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('country_code, country_name', 'required'),
			array('country_code', 'length', 'max'=>3),
			array('country_name', 'length', 'max'=>45),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('country_code, country_name', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'employees' => array(self::HAS_MANY, 'Employee', 'country_code'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'country_code' => 'Country Code',
			'country_name' => 'Country Name',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('country_code',$this->country_code,true);
		$criteria->compare('country_name',$this->country_name,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}


text:
{-# LANGUAGE CPP                        #-}
#if __GLASGOW_HASKELL__ >= 800
{-# LANGUAGE TemplateHaskellQuotes      #-}
#else
{-# LANGUAGE TemplateHaskell            #-}
#endif
{-# LANGUAGE DeriveDataTypeable         #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns             #-}
{-# LANGUAGE DeriveGeneric              #-}
{-# LANGUAGE DeriveLift                 #-}
{-# LANGUAGE NoImplicitPrelude          #-}
{-# LANGUAGE OverloadedStrings          #-}
module System.Etc.Internal.Spec.Types where

import           RIO
import qualified RIO.HashMap        as HashMap
import qualified RIO.Text           as Text
import qualified RIO.Vector         as Vector

import Language.Haskell.TH.Syntax (Lift(..))

import qualified Data.Aeson       as JSON

--------------------------------------------------------------------------------
-- Cli

data CliOptValueType
  = StringOpt
  | NumberOpt
  | SwitchOpt
  deriving (Generic, Show, Eq, Lift)

data CliArgValueType
  = StringArg
  | NumberArg
  deriving (Generic, Show, Eq, Lift)

data CliOptMetadata
  = CliOptMetadata {
    optLong     :: !(Maybe Text)
  , optShort    :: !(Maybe Text)
  , optMetavar  :: !(Maybe Text)
  , optHelp     :: !(Maybe Text)
  , optRequired :: !Bool
  }
  deriving (Generic, Show, Eq)

instance Lift CliOptMetadata where
  lift CliOptMetadata {optLong, optShort, optMetavar, optHelp, optRequired} =
    [| CliOptMetadata
           { optLong = fmap Text.pack optLongStr
           , optShort = fmap Text.pack optShortStr
           , optMetavar = fmap Text.pack optMetavarStr
           , optHelp = fmap Text.pack optHelpStr
           , optRequired = optRequired
           } |]
    where
      optLongStr = fmap Text.unpack optLong
      optShortStr = fmap Text.unpack optShort
      optMetavarStr = fmap Text.unpack optMetavar
      optHelpStr = fmap Text.unpack optHelp

data CliArgMetadata
  = CliArgMetadata {
    argMetavar  :: !(Maybe Text)
  , argHelp     :: !(Maybe Text)
  , argRequired :: !Bool
  }
  deriving (Generic, Show, Eq)

instance Lift CliArgMetadata where
  lift CliArgMetadata {argMetavar, argHelp, argRequired} =
    [| CliArgMetadata {
          argMetavar = fmap Text.pack argMetavarStr
        , argHelp    = fmap Text.pack argHelpStr
        , argRequired = argRequired
        }
     |]
    where
      argMetavarStr = fmap Text.unpack argMetavar
      argHelpStr = fmap Text.unpack argHelp

data CliSwitchMetadata
  = CliSwitchMetadata {
    switchLong     :: !Text
  , switchHelp     :: !(Maybe Text)
  }
  deriving (Generic, Show, Eq)

instance Lift CliSwitchMetadata where
  lift CliSwitchMetadata {switchLong, switchHelp} =
    [| CliSwitchMetadata
           { switchLong = Text.pack switchLongStr
           , switchHelp = fmap Text.pack switchHelpStr
           } |]
    where
      switchLongStr = Text.unpack switchLong
      switchHelpStr = fmap Text.unpack switchHelp

data CliEntryMetadata
  = Opt CliOptMetadata
  | Arg CliArgMetadata
  | Switch CliSwitchMetadata
  deriving (Generic, Show, Eq)

instance Lift CliEntryMetadata where
  lift (Opt metadata)    = [| Opt metadata |]
  lift (Arg metadata)    = [| Arg metadata |]
  lift (Switch metadata) = [| Switch metadata |]

data CliEntrySpec cmd
  = CmdEntry {
    cliEntryCmdValue :: !(Vector cmd)
  , cliEntryMetadata :: !CliEntryMetadata
  }
  | PlainEntry {
    cliEntryMetadata :: !CliEntryMetadata
  }
  deriving (Generic, Show, Eq)

instance Lift cmd => Lift (CliEntrySpec cmd) where
  lift CmdEntry {cliEntryCmdValue, cliEntryMetadata} =
    [| CmdEntry { cliEntryCmdValue = Vector.fromList cliEntryCmdValueList
                , cliEntryMetadata = cliEntryMetadata } |]
    where
      cliEntryCmdValueList = Vector.toList cliEntryCmdValue
  lift PlainEntry {cliEntryMetadata} =
    [| PlainEntry { cliEntryMetadata = cliEntryMetadata } |]

data CliCmdSpec
  = CliCmdSpec {
    cliCmdDesc   :: !Text
  , cliCmdHeader :: !Text
  }
  deriving (Generic, Show, Eq)

instance Lift CliCmdSpec where
  lift CliCmdSpec {cliCmdDesc, cliCmdHeader} =
    [| CliCmdSpec { cliCmdDesc = Text.pack cliCmdDescStr, cliCmdHeader = Text.pack cliCmdHeaderStr } |]
    where
      cliCmdDescStr = Text.unpack cliCmdDesc
      cliCmdHeaderStr = Text.unpack cliCmdHeader

--------------------------------------------------------------------------------

data ConfigSources cmd
  = ConfigSources {
    envVar   :: !(Maybe Text)
  , cliEntry :: !(Maybe (CliEntrySpec cmd))
  }
  deriving (Generic, Show, Eq)

instance Lift cmd => Lift (ConfigSources cmd) where
  lift ConfigSources {envVar, cliEntry} =
    [| ConfigSources (fmap Text.pack envVarStr) cliEntry |]
    where
      envVarStr = fmap Text.unpack envVar

data SingleConfigValueType
  = CVTString
  | CVTNumber
  | CVTBool
  | CVTObject
  deriving (Generic, Show, Read, Eq, Lift)

instance Display SingleConfigValueType where
  display value =
    case value of
      CVTString -> "string"
      CVTNumber -> "number"
      CVTBool   -> "bool"
      CVTObject -> "object"

data ConfigValueType
  = CVTSingle !SingleConfigValueType
  | CVTArray  !SingleConfigValueType
  deriving (Generic, Show, Read, Eq, Lift)

instance Display ConfigValueType where
  display value =
    case value of
      CVTSingle singleVal -> display singleVal
      CVTArray  singleVal -> display $ "[" <> display singleVal <> "]"

data ConfigValue cmd
  = ConfigValue {
    defaultValue    :: !(Maybe JSON.Value)
  , configValueType :: !ConfigValueType
  , isSensitive     :: !Bool
  , configSources   :: !(ConfigSources cmd)
  }
  | SubConfig {
    subConfig :: !(HashMap Text (ConfigValue cmd))
  }
  deriving (Generic, Show, Eq)

instance Lift cmd => Lift (ConfigValue cmd) where
  lift ConfigValue {defaultValue, configValueType, isSensitive, configSources} =
    [| ConfigValue defaultValue configValueType isSensitive configSources |]
  lift SubConfig {subConfig} =
    [| SubConfig (HashMap.fromList $ map (first Text.pack) subConfigList) |]
    where
      subConfigList = map (first Text.unpack) $ HashMap.toList subConfig

data CliProgramSpec
  = CliProgramSpec {
    cliProgramDesc   :: !Text
  , cliProgramHeader :: !Text
  , cliCommands      :: !(Maybe (HashMap Text CliCmdSpec))
  }
  deriving (Generic, Show, Eq)

instance Lift CliProgramSpec where
  lift CliProgramSpec {cliProgramDesc, cliProgramHeader, cliCommands} =
    [| CliProgramSpec (Text.pack cliProgramDescStr)
                      (Text.pack cliProgramHeaderStr)
                      (fmap (HashMap.fromList . map (first Text.pack)) cliCommandList) |]
    where
      cliProgramDescStr   = Text.unpack cliProgramDesc
      cliProgramHeaderStr = Text.unpack cliProgramHeader
      cliCommandList      = fmap (map (first Text.unpack) . HashMap.toList) cliCommands

data FilesSpec
  = FilePathsSpec ![Text]
  | FilesSpec { fileLocationEnvVar :: !(Maybe Text), fileLocationPaths :: ![Text] }
  deriving (Generic, Show, Eq)

instance Lift FilesSpec where
  lift (FilePathsSpec pathsList) =
    [| FilePathsSpec $ map Text.pack pathsListStr |]
    where
      pathsListStr = map Text.unpack pathsList
  lift FilesSpec { fileLocationEnvVar, fileLocationPaths } =
    [| FilesSpec (fmap Text.pack fileLocationEnvVarStr)
                 (fmap Text.pack fileLocationsPathsStr)  |]
    where
      fileLocationEnvVarStr = fmap Text.unpack fileLocationEnvVar
      fileLocationsPathsStr = fmap Text.unpack fileLocationPaths

data ConfigSpec cmd
  = ConfigSpec {
    specConfigFilepaths :: !(Maybe FilesSpec)
  , specCliProgramSpec  :: !(Maybe CliProgramSpec)
  , specConfigValues    :: !(HashMap Text (ConfigValue cmd))
  }
  deriving (Generic, Show, Eq)

instance Lift cmd => Lift (ConfigSpec cmd) where
  lift ConfigSpec {specConfigFilepaths, specCliProgramSpec, specConfigValues} =
    [| ConfigSpec specConfigFilepaths
                  specCliProgramSpec
                  (HashMap.fromList $ map (first Text.pack) configValuesList) |]
    where
      configValuesList = map (first Text.unpack) $ HashMap.toList specConfigValues


text:
namespace phi {
class DenseTensor;
}  // namespace phi

namespace paddle {
namespace platform {

template <typename T>
inline cudnnDataType_t ToCudnnDataType(const T& t) {
  auto type = framework::ToDataType(t);
  return ToCudnnDataType(phi::TransToPhiDataType(type));
}

template <typename T>
inline std::vector<T> TransformDimOrder(const std::vector<T>& dims) {
  std::vector<T> transformed_dims(dims.begin(), dims.end());
  if (dims.size() < 4) {
    return transformed_dims;
  }
  T H, W, D, C;
  if (dims.size() == 4) {
    H = dims[1];
    W = dims[2];
    C = dims[3];
    transformed_dims[1] = C;
    transformed_dims[2] = H;
    transformed_dims[3] = W;
  } else {
    D = dims[1];
    H = dims[2];
    W = dims[3];
    C = dims[4];
    transformed_dims[1] = C;
    transformed_dims[2] = D;
    transformed_dims[3] = H;
    transformed_dims[4] = W;
  }
  return transformed_dims;
}

template <>
inline cudnnDataType_t ToCudnnDataType(const phi::DataType& t) {
  cudnnDataType_t type = CUDNN_DATA_FLOAT;
  switch (t) {
    case phi::DataType::FLOAT16:
      type = CUDNN_DATA_HALF;
      break;
    case phi::DataType::FLOAT32:
      type = CUDNN_DATA_FLOAT;
      break;
    case phi::DataType::FLOAT64:
      type = CUDNN_DATA_DOUBLE;
      break;
#if CUDNN_VERSION_MIN(8, 1, 0)
    case phi::DataType::BFLOAT16:
      type = CUDNN_DATA_BFLOAT16;
      break;
#endif
    default:
      break;
  }
  return type;
}

class ActivationDescriptor {
 public:
  using T = cudnnActivationStruct;
  struct Deleter {
    void operator()(T* t) {
      if (t != nullptr) {
        PADDLE_ENFORCE_GPU_SUCCESS(
            dynload::cudnnDestroyActivationDescriptor(t));
        t = nullptr;
      }
    }
  };
  ActivationDescriptor() {
    T* raw_ptr;
    PADDLE_ENFORCE_GPU_SUCCESS(
        dynload::cudnnCreateActivationDescriptor(&raw_ptr));
    desc_.reset(raw_ptr);
  }
  template <typename T>
  void set(cudnnActivationMode_t mode, const T& coef) {
    PADDLE_ENFORCE_GPU_SUCCESS(dynload::cudnnSetActivationDescriptor(
        desc_.get(), mode, CUDNN_NOT_PROPAGATE_NAN, static_cast<double>(coef)));
  }

  T* desc() { return desc_.get(); }
  T* desc() const { return desc_.get(); }

 private:
  std::unique_ptr<T, Deleter> desc_;
};

class TensorDescriptor {
 public:
  using T = cudnnTensorStruct;
  struct Deleter {
    void operator()(T* t) {
      if (t != nullptr) {
        PADDLE_ENFORCE_GPU_SUCCESS(dynload::cudnnDestroyTensorDescriptor(t));
        t = nullptr;
      }
    }
  };
  TensorDescriptor() {
    T* raw_ptr;
    PADDLE_ENFORCE_GPU_SUCCESS(dynload::cudnnCreateTensorDescriptor(&raw_ptr));
    desc_.reset(raw_ptr);
  }
  T* desc() { return desc_.get(); }
  T* desc() const { return desc_.get(); }
  void set(const phi::DenseTensor& tensor, const int groups = 1) {
    auto dims = phi::vectorize<int>(tensor.dims());
    std::vector<int> strides(dims.size());
    strides[dims.size() - 1] = 1;
    for (int i = dims.size() - 2; i >= 0; i--) {
      strides[i] = dims[i + 1] * strides[i + 1];
    }
    std::vector<int> dims_with_group(dims.begin(), dims.end());
    if (groups > 1) {
      dims_with_group[1] = dims_with_group[1] / groups;
    }
    PADDLE_ENFORCE_GPU_SUCCESS(
        dynload::cudnnSetTensorNdDescriptor(desc_.get(),
                                            ToCudnnDataType(tensor.dtype()),
                                            dims_with_group.size(),
                                            dims_with_group.data(),
                                            strides.data()));
  }

  void set(const std::vector<int>& dims,
           const cudnnTensorFormat_t format,
           const cudnnDataType_t dtype) {
    std::vector<int> transformed_dims;
    if (format == CUDNN_TENSOR_NHWC) {
      transformed_dims = TransformDimOrder(dims);
    } else {
      transformed_dims = dims;
    }
    PADDLE_ENFORCE_GPU_SUCCESS(
        dynload::cudnnSetTensorNdDescriptorEx(desc_.get(),
                                              format,
                                              dtype,
                                              transformed_dims.size(),
                                              transformed_dims.data()));
  }

  void set(const phi::DenseTensor& tensor, const cudnnTensorFormat_t format) {
    auto dims = phi::vectorize<int>(tensor.dims());
    auto dtype = ToCudnnDataType(tensor.dtype());
    set(dims, format, dtype);
  }

 private:
  std::unique_ptr<T, Deleter> desc_;
};

class FilterDescriptor {
 public:
  using T = cudnnFilterStruct;
  struct Deleter {
    void operator()(T* t) {
      if (t != nullptr) {
        PADDLE_ENFORCE_GPU_SUCCESS(dynload::cudnnDestroyFilterDescriptor(t));
        t = nullptr;
      }
    }
  };
  FilterDescriptor() {
    T* raw_ptr;
    PADDLE_ENFORCE_GPU_SUCCESS(dynload::cudnnCreateFilterDescriptor(&raw_ptr));
    desc_.reset(raw_ptr);
  }
  T* desc() { return desc_.get(); }
  T* desc() const { return desc_.get(); }

  void set(const std::vector<int>& dims,
           const cudnnTensorFormat_t format,
           const cudnnDataType_t dtype,
           const int groups = 1) {
    std::vector<int> transformed_dims;
    if (format == CUDNN_TENSOR_NHWC) {
      transformed_dims = TransformDimOrder(dims);
    } else {
      transformed_dims = dims;
    }
    if (groups > 1) {
      transformed_dims[1] = transformed_dims[1] / groups;
    }
    PADDLE_ENFORCE_GPU_SUCCESS(
        dynload::cudnnSetFilterNdDescriptor(desc_.get(),
                                            dtype,
                                            format,
                                            transformed_dims.size(),
                                            transformed_dims.data()));
  }

  void set(const phi::DenseTensor& tensor,
           const cudnnTensorFormat_t format,
           const int groups = 1) {
    auto dims = phi::vectorize<int>(tensor.dims());
    auto dtype = ToCudnnDataType(tensor.dtype());
    set(dims, format, dtype, groups);
  }

 private:
  std::unique_ptr<T, Deleter> desc_;
};

class ConvolutionDescriptor {
 public:
  using T = cudnnConvolutionStruct;
  struct Deleter {
    void operator()(T* t) {
      if (t != nullptr) {
        PADDLE_ENFORCE_GPU_SUCCESS(
            dynload::cudnnDestroyConvolutionDescriptor(t));
        t = nullptr;
      }
    }
  };
  ConvolutionDescriptor() {
    T* raw_ptr;
    PADDLE_ENFORCE_GPU_SUCCESS(
        dynload::cudnnCreateConvolutionDescriptor(&raw_ptr));
    desc_.reset(raw_ptr);
  }
  T* desc() { return desc_.get(); }
  T* desc() const { return desc_.get(); }

  void set(cudnnDataType_t dtype,
           const std::vector<int>& pads,
           const std::vector<int>& strides,
           const std::vector<int>& dilations,
           bool allow_tf32,
           const int groups = 1) {
    allow_tf32_ = allow_tf32;
    cudnnDataType_t compute_type =
        (dtype == CUDNN_DATA_DOUBLE) ? CUDNN_DATA_DOUBLE : CUDNN_DATA_FLOAT;
    T* desc = desc_.get();
    PADDLE_ENFORCE_GPU_SUCCESS(
        dynload::cudnnSetConvolutionNdDescriptor(desc,
                                                 pads.size(),
                                                 pads.data(),
                                                 strides.data(),
                                                 dilations.data(),
                                                 CUDNN_CROSS_CORRELATION,
                                                 compute_type));
#if CUDNN_VERSION_MIN(7, 0, 1)
    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cudnnSetConvolutionGroupCount(desc, groups));
#if CUDA_VERSION >= 9000 && CUDNN_VERSION_MIN(7, 0, 1)
    PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::cudnnSetConvolutionMathType(
        desc, CUDNN_DEFAULT_MATH));
    if (dtype == CUDNN_DATA_HALF) {
      PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::cudnnSetConvolutionMathType(
          desc, CUDNN_TENSOR_OP_MATH));
#if CUDA_VERSION >= 11000
#if CUDNN_VERSION_MIN(8, 1, 0)
    } else if (dtype == CUDNN_DATA_BFLOAT16) {
      PADDLE_ENFORCE_GPU_SUCCESS(platform::dynload::cudnnSetConvolutionMathType(
          desc, CUDNN_TENSOR_OP_MATH));
#endif  // CUDNN_VERSION_MIN(8,1,0)
    } else if (dtype == CUDNN_DATA_FLOAT && !allow_tf32) {
      PADDLE_ENFORCE_GPU_SUCCESS(
          platform::dynload::cudnnSetConvolutionMathType(desc, CUDNN_FMA_MATH));
#endif  // CUDA_VERSION >= 11000
    }
#endif
#endif
  }

  bool allow_tf32_;

 private:
  std::unique_ptr<T, Deleter> desc_;
};

}  // namespace platform
}  // namespace paddle


text:
package org.apache.causeway.commons.internal.debug.xray;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Collections;
import java.util.function.Consumer;

import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import lombok.val;
import lombok.experimental.UtilityClass;

@UtilityClass
final class _SwingUtil {

    JTable newTable(final Object[][] tableData, final String[] columnNames) {
        val table = new JTable(tableData, columnNames) {
            private static final long serialVersionUID = 1L;
            @Override
            public Component prepareRenderer(final TableCellRenderer renderer, final int row, final int column) {
                Component component = super.prepareRenderer(renderer, row, column);
                int rendererWidth = component.getPreferredSize().width;
                TableColumn tableColumn = getColumnModel().getColumn(column);
                tableColumn.setPreferredWidth(Math.max(rendererWidth + getIntercellSpacing().width, tableColumn.getPreferredWidth()));
                return component;
            }
        };
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        return table;
    }

    void setTreeExpandedState(final JTree tree, final boolean expanded) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getModel().getRoot();
        setNodeExpandedState(tree, node, expanded);
    }

    void setNodeExpandedState(final JTree tree, final DefaultMutableTreeNode node, final boolean expanded) {
        for (Object treeNode : Collections.list(node.children())) {
            setNodeExpandedState(tree, (DefaultMutableTreeNode) treeNode, expanded);
        }
        if (!expanded && node.isRoot()) {
            return;
        }
        val path = new TreePath(node.getPath());
        if (expanded) {
            tree.expandPath(path);
        } else {
            tree.collapsePath(path);
        }
    }

    JPanel canvas(final Consumer<Graphics2D> onRender) {

        val canvas = new JPanel() {
            private static final long serialVersionUID = 1L;
            @Override
            public void paintComponent(final Graphics g) {
                onRender.accept((Graphics2D)g);
            }
        };

        return canvas;
    }

    public static Component verticalBox(final Component ...components) {

        val panel = new JPanel(new GridBagLayout());
        val gbc = new GridBagConstraints();
        gbc.weightx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.insets = new Insets(3, 6, 3, 6);

        for(val component : components) {
            panel.add(component, gbc);
        }

        return panel;
    }

}


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

  <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />

  <title>File: capistrano.rb [bundler-1.3.5 Documentation]</title>

  <link type="text/css" media="screen" href="../../rdoc.css" rel="stylesheet" />

Last Modified

2014-03-04 08:11:13 +0000

Requires

bundler/deployment

Description

Capistrano task for Bundler.

Just add "require 'bundler/capistrano'" in your Capistrano deploy.rb, and
Bundler will be activated after each new
deployment.


text:
namespace agency
{
namespace cuda
{
namespace this_thread
{

class parallel_executor
{
  public:
    using execution_category = parallel_execution_tag;

    template<class T>
    using allocator = cuda::allocator<T, pinned_allocator<T>>;

    template<class T>
    using container = cuda::detail::array<T, size_t, allocator<T>>;

    template<class T>
    using future = cuda::future<T>;

    template<class Function, class ResultFactory, class SharedFactory>
    __AGENCY_ANNOTATION
    agency::detail::result_of_t<ResultFactory()>
      bulk_sync_execute(Function f, size_t n, ResultFactory result_factory, SharedFactory shared_factory)
    {
      auto result = result_factory();
      auto shared_arg = shared_factory();

      for(size_t i = 0; i < n; ++i)
      {
        f(i, result, shared_arg);
      }

      return std::move(result);
    }
};

} // end this_thread

using parallel_executor = flattened_executor<grid_executor>;

} // end cuda
} // end agency


text:
package com.intellij.openapi.vcs.changes.ui;

import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeList;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.function.Supplier;

public final class ChangeListChangesSupplier implements Supplier<Iterable<Change>> {
  private final @NotNull List<ChangeList> myChangeLists;

  public ChangeListChangesSupplier(@NotNull List<ChangeList> changeLists) {
    myChangeLists = List.copyOf(changeLists);
  }

  public ChangeListChangesSupplier(@NotNull ChangeList changeList) {
    myChangeLists = List.of(changeList);
  }

  @Override
  public Iterable<Change> get() {
    return JBIterable.from(myChangeLists).flatMap(ChangeList::getChanges);
  }
}


text:
using std::cout;
using std::endl;
using std::string;

// Default Constructor
Novice::Novice()
:Character(), creationDate()
{
	this->skillPoints = 0;
	this->noviceSkillList;
}

// Constructor
Novice::Novice(const string &name, const string &sex, const Date &created, const Skill &skill, int points)
:Character(name, sex), creationDate(created)
{
	if (points <= 9)
		this->skillPoints = points;
	else
	{
		cout << "Skill points setted for 9" << endl;
		this->skillPoints = 9;
	}
	this->noviceSkillList.push_back (skill);
}

// Copy Constructor
Novice::Novice(const Novice &novice)
:Character(static_cast<Character> (novice)), creationDate(novice.creationDate)
{
	this->skillPoints = novice.skillPoints;
	this->noviceSkillList = novice.noviceSkillList;
}

// Destructor
Novice::~Novice()
{
	//cout << "~Novice() called" << endl;
}

// Overload << opperator
ostream &operator<< (ostream &output, const Novice &novice)
{
	output << static_cast< Character> (novice) << endl;
	output << "Skill list" << endl;
	for (int i = 0; i < novice.noviceSkillList.size(); i++)
		output << novice.noviceSkillList[i] << " ";
	cout << endl;
	output << "Skill points " << novice.skillPoints << endl;

	return output;
}

// Overload == operator
bool Novice::operator== (const Novice &novice) const
{
	if (static_cast< Character >(*this) != static_cast<Character> (novice))
		return false;
	if (this->skillPoints == novice.skillPoints)
		return false;
	for (int i = 0; i < novice.noviceSkillList.size(); i++)
		if (this->noviceSkillList[i] == novice.noviceSkillList[i])
			return false;
	return true;
}

// Overload = operator
const Novice &Novice::operator= (const Novice &novice)
{
	static_cast< Character> (*this) = static_cast< Character > (novice);
	this->skillPoints = novice.skillPoints;
	this->noviceSkillList = novice.noviceSkillList;

	return *this;
}

// Print novice info
void Novice::printInfo() const
{
	cout << *this << endl;
	cout << "Job Type:\tNovice" << endl;
	cout << "Race:\tHuman" << endl;
	cout << "Changer At:\tTraning Grounds" << endl;
	cout << "Total Skill Points:\t9" << endl;
	cout << "Total Quest Skills: 2" << endl;
	cout << "\tJob Bonues" << endl;
	cout << "STR\tAGI\tVIT\tINT\tDEX\tLUK" << endl;
	cout << "+0\t+0\t+0\t+0\t+0\t+0" << endl;
	cout << "\tWeapons" << endl;
	cout << "Dagger • One Handed Sword" << endl;
}

// Skill first Aid
void Novice::firstAid() const
{
	cout << "First Aid !!" << endl;
}

// Skill play dead
void Novice::playDead() const
{
	cout << "Play Dead !!" << endl;
}

// Add skill of skill list
void Novice::addSkill(const Skill &skill)
{
	this->noviceSkillList.push_back(skill);
}

// Return skill points
int Novice::getSkillPoints() const
{
	return this->skillPoints;
}

// Set skill points
void Novice::setSkillPoints(int points)
{
	this->skillPoints = points;
}

// User novice mout
void Novice::useMount() const
{
	cout << "Poring equiped" << endl;
}

// List Available Skills
void Novice::listAvailableSkill() const
{
	cout << "\tAvailable Skills" << endl;
	cout << "Empyt" << endl;
}


text:
package com.dremio.common.utils.protos;

import com.dremio.exec.proto.UserBitShared.ExternalId;
import com.dremio.exec.proto.UserBitShared.QueryId;

/**
 * represents a single attempt ID. It's a combination of an external QueryId + an attempt number
 */
public class AttemptId {

  private static final int MASK = 0xFF;
  // internal internalId
  private final ExternalId externalId;
  private final int attempt;

  public AttemptId() {
    this(ExternalIdHelper.generateExternalId(), 0);
  }

  /**
   * AttemptId = externalId + attempt #
   */
  public AttemptId(final ExternalId externalId, int attempt) {
    assert ExternalIdHelper.isValid(externalId) : "not a valid externalId";
    assert attempt >= 0 && attempt < 256 : "invalid attempt# " + attempt;
    this.externalId = externalId;
    this.attempt = attempt;
  }

  /**
   * @return internal QueryId corresponding to this attempt id
   */
  public QueryId toQueryId() {
    final long part1 = externalId.getPart1();
    final long part2 = externalId.getPart2();

    return QueryId.newBuilder()
            .setPart1(part1)
            .setPart2(part2 + ((byte) attempt & MASK))
            .build();
  }

  public ExternalId getExternalId() {
    return externalId;
  }

  @Override
  public String toString() {
    return ExternalIdHelper.toString(externalId) + "/" + attempt;
  }

  public int getAttemptNum() {
    return attempt;
  }

  /**
   * Convert an external id to an attempt id, assuming this is its first attempt
   * @param externalId
   * @return
   */
  public static AttemptId of(final ExternalId externalId) {
    return new AttemptId(externalId, 0);
  }

  /**
   * Convert a query id to an attempt id
   * @param queryId
   * @return
   */
  public static AttemptId of(final QueryId queryId) {
    ExternalId externalId = ExternalIdHelper.toExternal(queryId);
    int attempt = (int) (queryId.getPart2() & MASK);

    return new AttemptId(externalId, attempt);
  }

  public AttemptId nextAttempt() {
    return new AttemptId(externalId, attempt + 1);
  }
}


text:
import re
from sanic.views import HTTPMethodView
from sanic.response import json
from sanic import Blueprint
from peewee import fn
from python_paginate.web.sanic_paginate import Pagination
from utils import tools
from utils.decorators import admin_required
from ssr_panel.exceptions import BadRequest
from ssr_panel import render
from ssr_panel.models import User, SS_Node, SP_Config

admin_panel = Blueprint('admin_panel', url_prefix='/admin')

@admin_panel.route('/')
@admin_required
async def index_view(request):
    user = request['user']
    analytics = {
        'total_user': await User.objects.count(User.select()),
        'checkin_user': await User.objects.count(User.select().where(User.last_check_in_time > 0)),
        'traffic_usage': tools.flow_auto_show(await User.objects.scalar(User.select(fn.Sum(User.u + User.d)))),
        'online_user': await User.objects.count(User.select().where(User.t > 3600)),
        'total_node': await SS_Node.objects.count(SS_Node.select()),
    }
    return render('admin_panel/index.html', request, user=user, **analytics)

class ConfigView(HTTPMethodView):
    decorators = [admin_required]

    async def get(self, request):
        user = request['user']
        configs = {}
        for config in await SP_Config.objects.execute(SP_Config.select()):
            configs[config.key] = config.value
        return render('admin_panel/config.html', request, user=user, configs=configs)

    async def put(self, request):
        keys = {
            'analytics-code': 'analyticsCode',
            'home-code': 'homeCode',
            'app-name': 'appName',
            'user-index': 'userIndex',
            'user-node': 'userNode',
        }
        for config in await SP_Config.objects.execute(SP_Config.select()):
            key = keys.get(config.key, '')
            config.value = request.form.get(key, '')
            await SP_Config.objects.update(config)

        return json({'msg': '更新成功'})

admin_panel.add_route(ConfigView.as_view(), '/config')

@admin_panel.route('/nodes/create')
@admin_required
async def nodes_create_view(request):
    user = request['user']
    # nodes = await SS_Node.objects.execute(SS_Node.select())
    return render('admin_panel/node/create.html', request, user=user)

class NodeView(HTTPMethodView):
    decorators = [admin_required]

    async def get(self, request):
        user = request['user']
        nodes = await SS_Node.objects.execute(SS_Node.select())
        return render('admin_panel/node/index.html', request, user=user, nodes=nodes)

    async def post(self, request):
        if not request.form.get('name'):
            raise BadRequest('请输入节点名称')
        if not request.form.get('server'):
            raise BadRequest('节点地址错误')
        if not request.form.get('traffic_rate'):
            raise BadRequest('流量比例错误')

        await SS_Node.objects.create(
            SS_Node,
            name=request.form.get('name'),
            type=request.form.get('type'),
            server=request.form.get('server'),
            node_class=request.form.get('node_class', 0),
            node_group=request.form.get('node_group', 0),
            traffic_rate=request.form.get('traffic_rate'),
            info=request.form.get('info', ''),
            note=request.form.get('note', ''),
            status=request.form.get('status'),
            offset=request.form.get('offset', 0),
            sort=request.form.get('sort', 0),
        )
        return json({'msg': '节点添加成功'})

admin_panel.add_route(NodeView.as_view(), '/nodes')

@admin_panel.route('/nodes/<node_id:int>')
@admin_required
async def nodes_edit_view(request, node_id):
    user = request['user']
    node = await SS_Node.objects.get(SS_Node.id == node_id)
    return render('admin_panel/node/edit.html', request, user=user, node=node)

@admin_panel.route('/users')
@admin_required
async def users_view(request):
    user = request['user']

    total = await User.objects.count(User.select())

    page, per_page, offset = Pagination.get_page_args(request)

    users = await User.objects.execute(
        User.select()
            .order_by(User.id.asc())
            .paginate(page, per_page)
    )

    Pagination._per_page = 20
    pagination = Pagination(request, total=total, record_name='users')
    return render('admin_panel/user/index.html', request, user=user, users=users,
                  pagination=pagination)

class UserView(HTTPMethodView):
    decorators = [admin_required]

    async def get(self, request, user_id):
        user = request['user']

        user_detail = await User.objects.get(User.id == user_id)
        return render('admin_panel/user/edit.html', request, user=user, user_detail=user_detail)

    async def put(self, request, user_id):
        password = request.form.get('pass')
        sspwd = request.form.get('passwd')
        pattern = r'^[\w\-\.@#$]{6,16}$'

        if sspwd and not re.match(pattern, sspwd):
            raise BadRequest('SS连接密码不符合规则,只能为6-16位长度,包含数字大小写字母-._@#$')

        try:
            transfer_enable = tools.gb_to_byte(float(request.form.get('transfer_enable', 0)))
        except:
            raise BadRequest('总流量输入错误')

        user_detail = await User.objects.get(User.id == user_id)
        user_detail.email = request.form.get('email', user_detail.email)
        user_detail.port = request.form.get('port', user_detail.port)
        user_detail.passwd = sspwd or user_detail.passwd
        user_detail.transfer_enable = transfer_enable
        user_detail.auto_reset_day = request.form.get('auto_reset_day', 0)
        user_detail.invite_num = request.form.get('invite_num')
        user_detail.protocol = request.form.get('protocol', user_detail.protocol)
        user_detail.obfs = request.form.get('obfs', user_detail.obfs)
        user_detail.method = request.form.get('method', user_detail.method)
        user_detail.custom_method = request.form.get('custom_method', 0)
        user_detail.custom_rss = request.form.get('custom_rss', 0)
        user_detail.user_class = request.form.get('user_class', 0)
        user_detail.node_group = request.form.get('node_group', 0)
        user_detail.enable = request.form.get('enable', 0)
        user_detail.expire_at = request.form.get('expire_at', user_detail.expire_at)
        user_detail.is_admin = request.form.get('is_admin', 0)
        user_detail.ref_by = request.form.get('ref_by', user_detail.ref_by)
        await User.objects.update(user_detail)

        return json({'msg': '更新成功'})

admin_panel.add_route(UserView.as_view(), '/users/<user_id:int>')


text:
static const char* TAG = "event";
static bool s_event_init_flag = false;
static QueueHandle_t s_event_queue = NULL;
static system_event_cb_t s_event_handler_cb = NULL;
static void *s_event_ctx = NULL;

static esp_err_t esp_event_post_to_user(system_event_t *event)
{
    if (s_event_handler_cb) {
        return (*s_event_handler_cb)(s_event_ctx, event);
    }
    return ESP_OK;
}

static void esp_event_loop_task(void *pvParameters)
{
    while (1) {
        system_event_t evt;
        if (xQueueReceive(s_event_queue, &evt, portMAX_DELAY) == pdPASS) {
            esp_err_t ret = esp_event_process_default(&evt);
            if (ret != ESP_OK) {
                ESP_LOGE(TAG, "default event handler failed!");
            }
            ret = esp_event_post_to_user(&evt);
            if (ret != ESP_OK) {
                ESP_LOGE(TAG, "post event to user fail!");
            }
        }
    }
}

system_event_cb_t esp_event_loop_set_cb(system_event_cb_t cb, void *ctx)
{
    system_event_cb_t old_cb = s_event_handler_cb;
    s_event_handler_cb = cb;
    s_event_ctx = ctx;
    return old_cb;
}

esp_err_t esp_event_send(system_event_t *event)
{
    portBASE_TYPE ret = xQueueSendToBack(s_event_queue, event, 0);
    if (ret != pdPASS) {
        if (event) {
            ESP_LOGE(TAG, "e=%d f", event->event_id);
        } else {
            ESP_LOGE(TAG, "e null");
        }
        return ESP_FAIL;
    }
    return ESP_OK;
}

QueueHandle_t esp_event_loop_get_queue(void)
{
    return s_event_queue;
}

esp_err_t esp_event_loop_init(system_event_cb_t cb, void *ctx)
{
    if (s_event_init_flag) {
        return ESP_FAIL;
    }
    s_event_handler_cb = cb;
    s_event_ctx = ctx;
    s_event_queue = xQueueCreate(CONFIG_SYSTEM_EVENT_QUEUE_SIZE, sizeof(system_event_t));

    xTaskCreatePinnedToCore(esp_event_loop_task, "eventTask",
            ESP_TASKD_EVENT_STACK, NULL, ESP_TASKD_EVENT_PRIO, NULL, 0);

    s_event_init_flag = true;
    return ESP_OK;
}


text:
<assembly>
	<!--

		jar, dependencies as jar, src.zip

	-->
	<id>lib</id>
	<formats>
		<format>zip</format>
	</formats>
	<includeBaseDirectory>false</includeBaseDirectory>
	<dependencySets>
		<dependencySet>
			<outputDirectory>/jar</outputDirectory>
			<unpack>false</unpack>
			<scope>runtime</scope>
			<!-- exclude the unnecessary dist.jars -->
			<excludes>
				<exclude>org.semweb4j:rdfreactor.dist</exclude>
				<exclude>org.semweb4j:rdf2go.dist</exclude>
				<exclude>org.semweb4j:dist</exclude>
			</excludes>

		</dependencySet>
	</dependencySets>

	<fileSets>
		<!--  include src.zip -->
		<fileSet>
			<directory>target</directory>
			<includes>
				<include>src.zip</include>
			</includes>
			<outputDirectory>/</outputDirectory>
		</fileSet>

		<!--  include /apidocs -->
		<fileSet>
			<directory>target/site/apidocs</directory>
			<includes>
				<include>**/*.*</include>
			</includes>
			<outputDirectory>/javadoc</outputDirectory>
		</fileSet>
	</fileSets>

	<!--  include README.txt -->

</assembly>


text:
\documentclass[12]{scrartcl}
\usepackage{amssymb,amsmath,gensymb,dsfont,calc,multicol,fullpage}
\makeatletter
\newcommand\Aboxed[1]{
   \@Aboxed#1\ENDDNE}
\def\@Aboxed#1&#2\ENDDNE{%
   &
   \settowidth\@tempdima{$\displaystyle#1{}$}
   \setlength\@tempdima{\@tempdima+\fboxsep+\fboxrule}
   \kern-\@tempdima
   \boxed{#1#2}
}
\makeatother

\begin{document}

\title{Homework 10, Section 2.1; 6, 19–23, 27, 28
 }
\author{Alex Gordon}
\date{\today}
\maketitle
\section*{Homework}
\subsection*{6.}
$\begin{bmatrix} -5&22 \\ 12&-22 \\ 3&-2   \end{bmatrix}$\\
\subsection*{19.}
$ Ab_3 = ab_1 + Ab_2 $ since $A = A.$Therefore $b_3 = b_1 + b_2$
\subsection*{20.}
$if Ab_1 = Ab_2, $ then if you divide both sides by A then $b_1 = b_2$
\subsection*{21.}
Let bp be the last column of $B$. By hypothesis, the last column of $AB$ is zero. Thus, $Ab_p = 0$. However, $b_p$ is not the zero vector, because $B$ has no column of zeros. Thus, the equation $Ab_p = 0$ is a linear dependence relation among the columns of A, and so the columns of A are linearly dependent.
\subsection*{22.}
If the columns of $B$ are linearly dependent, then there exists a nonzero vector x such that $B_x = 0$. From this, $A(Bx) = A0$ and $(AB)x = 0$ (by associativity). Since x is nonzero, the columns of $AB$ must be linearly dependent.
\subsection*{23.}
If $x$ satisfies $Ax=0$, then $CAx=C0=0$ and so $I_nx=0$ and $x=0$.This means that the equation $Ax=0$ has no free variables so every variable is a basic variable and every column of A is a pivot column meaning each pivot is in a different row, A must have at least as many rows as columns.
\subsection*{27.}
$uv^T = \begin{bmatrix} -2a&-2b&-2c \\ 3a&3b&3c \\ -4a&-4b&-4c   \end{bmatrix}$\\
$vu^T = \begin{bmatrix} -2a&3a&-4a \\ -2b&3b&-4b \\ -2c&3c&-4c   \end{bmatrix}$\\
\subsection*{28.}
By Theorem 3, $(uv^T)^T = (v^T)^Tu^T = vu^T.$

\end{document}


text:
all:
	hovercraft ./talk.rst output

clean:
	rm -rf output


text:
import { Animation } from "../Animations/animation";

/**
 * Class used to override all child animations of a given target
 */
export class AnimationPropertiesOverride {
    /**
     * Gets or sets a value indicating if animation blending must be used
     */
    public enableBlending = false;

    /**
     * Gets or sets the blending speed to use when enableBlending is true
     */
    public blendingSpeed = 0.01;

    /**
     * Gets or sets the default loop mode to use
     */
    public loopMode = Animation.ANIMATIONLOOPMODE_CYCLE;
}


text:
extern u8 flag;
void us_delay(u16 us);
void ms_delay(u16 count);
//延时子函数
void ds18b20_reset(void);
u8 ds18b20_read_byte(void);
void ds18b20_write_byte(u8 dat);
void temperature_convert(void);
u16 get_temperature(void);
void initialize_ds18b20(void);
void GPIO_Configuration1(void);
void GPIO_Configuration2(void);
#endif


text:
<?php

/* RangaCatalogBundle:Category:index.html.twig */
class __TwigTemplate_65016f54b7df784799961e760d3ec7d9 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("::base.html.twig");

        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 5
        echo "

Category list

                Id
                Name
                Slug
                Actions

        ";
        // line 21
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getContext($context, "entities"));
        foreach ($context['_seq'] as $context["_key"] => $context["entity"]) {
            // line 22
            echo "

                env, $this->env->getExtension('routing')->getPath("category_show", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
            echo "\">";
            echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "id"), "html", null, true);
            echo "
                ";
            // line 24
            echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "name"), "html", null, true);
            echo "
                ";
            // line 25
            echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "entity"), "slug"), "html", null, true);
            echo "

                        env, $this->env->getExtension('routing')->getPath("category_show", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
            echo "\">show

                        env, $this->env->getExtension('routing')->getPath("category_edit", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
            echo "\">edit

        ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['entity'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 38
        echo "

            env->getExtension('routing')->getPath("category_new");
        echo "\">
                Create a new entry

    ";
    }

    public function getTemplateName()
    {
        return "RangaCatalogBundle:Category:index.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  98 => 43,  91 => 38,  79 => 32,  73 => 29,  66 => 25,  62 => 24,  56 => 23,  53 => 22,  49 => 21,  31 => 5,  28 => 3,);
    }
}


text:
package com.lee.democollection.view.banner;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.lee.democollection.R;
import com.lee.democollection.view.banner.adapter.LoopAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Allen on 2016/11/24.
 */

public class LoopBanner extends RelativeLayout {
    private LoopViewPager viewPager;
    private LinearLayout pageIndicator;
    private LoopAdapter adapter;
    private Handler handler = new Handler(Looper.getMainLooper());
    private int autoScrollDelay = 1000;
    private boolean canScroll = true;
    private int pageIndicatorRes;
    private List<ViewPager.OnPageChangeListener> onPageChangeListeners;

    public LoopBanner(Context context) {
        super(context);
        init(context, null);
    }

    public LoopBanner(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public LoopBanner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs){
        LayoutInflater.from(context).inflate(R.layout.view_loop_banner, this);
        viewPager = (LoopViewPager) findViewById(R.id.view_pager);
        pageIndicator = (LinearLayout) findViewById(R.id.page_indicator);

        viewPager.addOnPageChangeListener(onPageChangeListener);
        if(attrs != null){
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LoopBanner);
            autoScrollDelay = a.getInteger(R.styleable.LoopBanner_autoScrollDelay, 1000);
            pageIndicatorRes = a.getResourceId(R.styleable.LoopBanner_pageIndicatorDrawable, -1);
            a.recycle();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopAutoScroll();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                stopAutoScroll();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE:
                startAutoScroll();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public void startAutoScroll(){
        if(canScroll){
            stopAutoScroll();
        }
        canScroll = true;
        handler.postDelayed(autoScrollTask, autoScrollDelay);
    }

    public void stopAutoScroll(){
        canScroll = false;
        handler.removeCallbacksAndMessages(null);
    }

    public void setAdapter(LoopAdapter adapter){
        this.adapter = adapter;
        viewPager.setAdapter(adapter);
        adapter.setViewPager(viewPager);

        setPageIndicator();
    }

    public void addOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        if(onPageChangeListeners == null){
            onPageChangeListeners = new ArrayList<>();
        }
        onPageChangeListeners.add(listener);
    }

    private void setPageIndicator(){
        pageIndicator.removeAllViews();
        int count = adapter.getRealCount();
        for (int i = 0; i < count; i++){
            ImageView imageView = new ImageView(getContext());
            imageView.setPadding(10, 10, 10, 10);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageResource(pageIndicatorRes);
            pageIndicator.addView(imageView);
        }
    }

    private void selectIndicator(int position){
        int childCount = pageIndicator.getChildCount();
        for(int i = 0; i < childCount; i++){
            View child = pageIndicator.getChildAt(i);
            if(i == position){
                child.setSelected(true);
            }else {
                child.setSelected(false);
            }
        }
    }

    public void setCurrentItem(int index){
        if(viewPager != null){
            viewPager.setCurrentItem(index);
        }
    }

    public int getCurrentItem(){
        if(viewPager != null){
            return viewPager.getRealCurrentItem();
        }
        return -1;
    }

    private Runnable autoScrollTask = new Runnable() {
        @Override
        public void run() {
            if(canScroll){
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                handler.postDelayed(this, autoScrollDelay);
            }
        }
    };

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if(onPageChangeListeners != null && !onPageChangeListeners.isEmpty()){
                for (ViewPager.OnPageChangeListener listener : onPageChangeListeners){
                    listener.onPageScrolled(position, positionOffset, positionOffsetPixels);
                }
            }
        }

        @Override
        public void onPageSelected(int position) {
            selectIndicator(adapter.getRealPosition(position));
            if(position == 0){
                viewPager.setCurrentItem(adapter.getCount() - adapter.getRealCount());
            }else if(position == adapter.getCount() - 1){
                Log.d("LEE", "finishUpdate position-->>" + position);
                viewPager.setCurrentItem(adapter.getRealCount() - 1);
            }
            if(onPageChangeListeners != null && !onPageChangeListeners.isEmpty()){
                for (ViewPager.OnPageChangeListener listener : onPageChangeListeners){
                    listener.onPageSelected(position);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if(onPageChangeListeners != null && !onPageChangeListeners.isEmpty()){
                for (ViewPager.OnPageChangeListener listener : onPageChangeListeners){
                    listener.onPageScrollStateChanged(state);
                }
            }
        }
    };
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<INTERACTIONS>
<INTERACTION>
<SOURCE>
<CLINICAL_SOURCE>ANSM</CLINICAL_SOURCE>
<SOURCE_FILE>450-RESERPINE.html
</SOURCE_FILE>
</SOURCE>
<DRUG1>
<DRUG name="RESERPINE" rxcui="9260">
<ATC code="C02AA02" />
</DRUG>
</DRUG1>
<DRUG2>
<CLASS name="IRREVERSIBLE MONOAMINE OXIDASE INHIBITORS (MAOI)" code="N06AF0" /></DRUG2>
<DESCRIPTION>Psychomotor agitation, convulsions, hypertension</DESCRIPTION>
<SEVERITY>CONTRAINDICATION</SEVERITY>
</INTERACTION>
<INTERACTION>
<SOURCE>
<CLINICAL_SOURCE>ANSM</CLINICAL_SOURCE>
<SOURCE_FILE>450-RESERPINE.html
</SOURCE_FILE>
</SOURCE>
<DRUG1>
<DRUG name="RESERPINE" rxcui="9260">
<ATC code="C02AA02" />
</DRUG>
</DRUG1>
<DRUG2>
<DRUG name="LEVODOPA" rxcui="6375">
<ATC code="N04BA01" />
<ATC code="N04BA02" />
<ATC code="N04BA03" />
</DRUG>
</DRUG2>
<DESCRIPTION>Inhibition of the effects of the levodopa</DESCRIPTION>
<SEVERITY>CONTRAINDICATION</SEVERITY>
</INTERACTION>
</INTERACTIONS>


text:
<form class="form-horizontal">
{% for column in columns -%}
{%+  set text = column[1].split('_') |map('capitalize')| join(' ') %}

            {{ text }}:

              <input type="text" id="id_{{ column[1].lower() }}" ng-model="form_data.{{ column[1].lower() }}" placeholder="{{ text }}" required>

{% endfor %}
        </form>


text:
namespace SimpleUI {

class ListBox : public Control {
public:
	int AddString(const wchar_t* v) {
		return SendMessage(this->handle(), LB_ADDSTRING, NULL, LPARAM(v));
	}

	int DeleteString(int index) {
		return SendMessage(this->handle(), LB_DELETESTRING, WPARAM(index), NULL);
	}

	int GetCount() {
		return SendMessage(this->handle(), LB_GETCOUNT, NULL, NULL);
	}

	int GetCurSel() {
		return SendMessage(this->handle(), LB_GETCURSEL, NULL, NULL);
	}

	int SetCurSel(int index) {
		return SendMessage(this->handle(), LB_SETCURSEL, WPARAM(index), NULL);
	}

	int ResetContent() {
		return SendMessage(this->handle(), LB_RESETCONTENT, NULL, NULL);
	}

	int SetItemData(int index, DWORD data) {
		return SendMessage(this->handle(), LB_SETITEMDATA, index, data);
	}

	DWORD GetItemData(int index) {
		return SendMessage(this->handle(), LB_GETITEMDATA, index, NULL);
	}

	using Window::GetText;

	int GetText(int index, wchar_t* buffer) {
		return SendMessage(this->handle(), LB_GETTEXT, index, LPARAM(buffer));
	}

	int GetTextLen(int index) {
		return SendMessage(this->handle(), LB_GETTEXTLEN, index, NULL);
	}

	ListBox(HWND handle);
	virtual ~ListBox();
};

} //namespace

#endif


text:
//
//  UIView+RO.h
//  whitewolfdemo
//
//  This App has been generated using IBM Mobile UI Builder
//

#import <UIKit/UIKit.h>

/**
 Helper to UIView
 */
@interface UIView (RO)

- (void)ro_setBackgroundView:(UIView *)backgroundView;

/**
 Set a background image keeping the ratio aspet
 */
- (void)ro_setBackgroundImage:(UIImage *)image;

/**
 Set a background image pattern
 */
- (void)ro_setBackgroundPattern:(UIImage *)image;

/**
 Set a background color
 */
- (void)ro_setBackgroundColor:(UIColor *)color;

/*
 Add/retrieve toolbar bottom in view (only simple vertical layout).
 */
- (UIToolbar *)ro_addToolbarBottom;

- (UIToolbar *)ro_toolbarBottom;

@end


text:
import React from 'react'
import injectSheet from 'react-jss'
import { Link } from 'react-router-dom'

import { Phone, BigPhone, Tablet, Desktop } from './Breakpoints'
import Spacer from './Spacer'
import LogoBetaBlack from './icons/icon-components/logo-beta-black'
import HamburgerMenu from './icons/icon-components/hamburger-menu'
import EmergencyPhoneIcon from './icons/icon-components/emergency-phone-icon'

const LogoAndNavigation = ({ classes }) => (

		<Phone>

				<Link to="/" className={classes.logoPhone}>
					<LogoBetaBlack height={25} width={160} />
				</Link>

				<Link to="/emergency" className={classes.emergencyIconPhone}>
					<EmergencyPhoneIcon height={24} width={24} />
				</Link>

				<Link to="/menu" className={classes.hamburgerMenuPhone}>
					<HamburgerMenu />
				</Link>

		</Phone>

		<BigPhone>

				<Link to="/" className={classes.logoPhone}>
					<LogoBetaBlack height={25} width={160} />
				</Link>

				<Link to="/emergency" className={classes.emergencyIconPhone}>
					<EmergencyPhoneIcon height={24} width={24} />
				</Link>

				<Link to="/menu" className={classes.hamburgerMenuPhone}>
					<HamburgerMenu />
				</Link>

		</BigPhone>

		<Tablet>

				<Link to="/">
					<LogoBetaBlack height={33} width={208} />
				</Link>

					<Link to="/about" className={classes.navigationLinkDesktop}>
						About
					</Link>
					{/* <Spacer width="32px" /> */}
					{/* <Link to="/feedback" className={classes.navigationLinkDesktop}>
						Feedback
					</Link> */}
					<Spacer width="52px" />
					<Link to="/emergency">
						<EmergencyPhoneIcon height={38} width={38} />
					</Link>

		</Tablet>

		<Desktop>

				<Link to="/">
					<LogoBetaBlack height={33} width={208} />
				</Link>

					<Link to="/about" className={classes.navigationLinkDesktop}>
						About
					</Link>
					{/* <Spacer width="32px" /> */}
					{/* <Link to="/feedback" className={classes.navigationLinkDesktop}>
						Feedback
					</Link> */}
					<Spacer width="52px" />
					<Link to="/emergency">
						<EmergencyPhoneIcon height={38} width={38} />
					</Link>

		</Desktop>

)

const styles = {
	headerPhone: {
		display: 'grid',
		'grid-template-columns': '70% 15% 15%',
		'align-items': 'center',
		'justify-items': 'end',
		position: 'fixed',
		top: '0vh',
		height: '55px',
		padding: '0 5% 0 5%',
		'background-color': '#FFFFFF',
		'min-width': '90vw',
		'border-bottom': '1px solid #3D65F9',
		'z-index': 1,
	},
	logoPhone: {
		'grid-column-start': 1,
		'grid-column-end': 2,
		'justify-self': 'start',
	},
	emergencyIconPhone: {
		'grid-column-start': 2,
		'grid-column-end': 3,
	},
	hamburgerMenuPhone: {
		cursor: 'pointer',
		'grid-column-start': 3,
		'grid-column-end': 4,
	},
	headerDesktop: {
		position: 'fixed',
		top: '0vh',
		height: '67px',
		padding: '33px 100% 0px 42px',
		display: 'flex',
		'align-items': 'baseline',
		'justify-content': 'space-between',
		'background-color': '#FFFFFF',
		'min-width': '90vw',
		'border-bottom': '4px solid #3D65F9',
		'z-index': 1,
	},
	linksDesktop: {
		display: 'flex',
		'align-items': 'center',
	},
	navigationLinkDesktop: {
		'font-family': 'hah-regular',
		'font-size': '16px',
		color: '#000000',
		'text-decoration': 'none',
		cursor: 'pointer',
	},
}

export default injectSheet(styles)(LogoAndNavigation)


text:
<template name="_aSphere">
  <a-sphere {{attributes}}>
    {{> UI.contentBlock}}
  </a-sphere>
</template>


text:
// See https://jestjs.io/docs/en/configuration
module.exports = {
  // preset: 'ts-jest',
  transform: {
    '^.+\\.[t|j|e]sx?$': 'babel-jest',
  },
  // Automatically clear mock calls and instances before every test.
  // Equivalent to calling `jest.clearAllMocks()` before each test.
  // This does not remove any mock implementation that may have been provided.
  clearMocks: true,
  coverageDirectory: 'coverage',
  moduleFileExtensions: ['js', 'es', 'json', 'jsx', 'ts', 'tsx'],
  testMatch: [
    '**/__tests__/**/*.[ejt]s?(x)',
    '**/?(*.)+(spec|test).[ejt]s?(x)',
  ],
  collectCoverageFrom: ['./src/**/*.{es,js,ts,tsx}'],
}


text:
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------

OPEN_RDO_RUNTIME_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOSetResourceParam
// --------------------------------------------------------------------------------
template <SetOperationType::Type setOperationType>
inline RDOSetResourceParam<setOperationType>::RDOSetResourceParam(const LPRDOCalc& getResource, const std::size_t paramID, const LPRDOCalc& pCalc)
	: m_getResource (getResource)
	, m_paramID     (paramID )
	, m_pCalc       (pCalc   )
{
	if (m_pCalc)
	{
		setSrcInfo(m_pCalc->srcInfo());
	}
}

template <SetOperationType::Type setOperationType>
inline RDOSetResourceParam<setOperationType>::~RDOSetResourceParam()
{}

template <>
inline RDOValue RDOSetResourceParam<SetOperationType::NOCHANGE>::doCalc(const LPRDORuntime& pRuntime)
{
	LPRDOResource pResource = m_getResource->calcValue(pRuntime).getPointerByInterface<IResourceType>();
	ASSERT(pResource);
	RDOValue value(true);
	return value;
}

template <>
inline RDOValue RDOSetResourceParam<SetOperationType::SET>::doCalc(const LPRDORuntime& pRuntime)
{
	LPRDOResource pResource = m_getResource->calcValue(pRuntime).getPointerByInterface<IResourceType>();
	ASSERT(pResource);
	RDOValue value = m_pCalc->calcValue(pRuntime);
	pResource->setParam(m_paramID, value);
	return value;
}

CLOSE_RDO_RUNTIME_NAMESPACE