text:
package org.hornetq.javaee.example;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.hornetq.javaee.example.server.SendMessageService;

import java.util.Properties;

/**
 * An example showing how to invoke a EJB which sends a JMS message and update a JDBC table in the same transaction.
 *
 * @author Andy Taylor
 * @author Jeff Mesnil
 */
public class EJBClientExample
{
   public static void main(final String[] args) throws Exception
   {
      InitialContext initialContext = null;
      Connection connection = null;
      try
      {
         // Step 1. Create an initial context to perform the JNDI lookup.
         final Properties env = new Properties();

         env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");

         env.put(Context.PROVIDER_URL, "remote://localhost:4447");

         env.put(Context.SECURITY_PRINCIPAL, "guest");

         env.put(Context.SECURITY_CREDENTIALS, "password");

         env.put("jboss.naming.client.ejb.context", true);

         initialContext = new InitialContext(env);

         // Step 2. Lookup the EJB
         SendMessageService service = (SendMessageService)initialContext.lookup("java:ejb/SendMessageBean!org.hornetq.javaee.example.server.SendMessageService");

         // Step 3. Create the DB table which will be updated
         service.createTable();

         // Step 4. Invoke the sendAndUpdate method
         service.sendAndUpdate("This is a text message");
         System.out.println("invoked the EJB service");

         // Step 5. Lookup the JMS connection factory
         ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("jms/RemoteConnectionFactory");

         // Step 6. Lookup the queue
         Queue queue = (Queue)initialContext.lookup("jms/queues/testQueue");

         // Step 7. Create a connection, a session and a message consumer for the queue
         connection = cf.createConnection("guest", "password");
         Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
         MessageConsumer consumer = session.createConsumer(queue);

         // Step 8. Start the connection
         connection.start();

         // Step 9. Receive the message sent by the EJB
         TextMessage messageReceived = (TextMessage)consumer.receive(5000);
         System.out.println("Received message: " + messageReceived.getText() +
                            " (" +
                            messageReceived.getJMSMessageID() +
                            ")");
      }
      finally
      {
         // Step 10. Be sure to close the resources!
         if (initialContext != null)
         {
            initialContext.close();
         }
         if (connection != null)
         {
            connection.close();
         }
      }
   }
}


text:
package cafs

import (
	"bytes"
	"crypto/sha1"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"sync"

	"github.com/tchaik/tchaik/store"
)

// Index is an interface which contains methods for implementing
// a content addressable file system.
type Index interface {
	// Get returns the real path for the given filename, with true if and only
	// if the path exists in the index.
	Get(path string) (string, bool)

	// AddContent adds the path to the index, and returns the path to the file
	// and whether the path/content already exists.
	Add(path string, hash string) bool

	// Exists returns true of the hash is in the index.
	Exists(hash string) bool
}

type index struct {
	sync.RWMutex

	files map[string]string // path -> sha1
	index map[string]bool   // {sha1}
	root  string
}

func NewIndex() *index {
	return &index{
		files: make(map[string]string),
		index: make(map[string]bool),
	}
}

func (i *index) MarshalJSON() ([]byte, error) {
	i.RLock()
	defer i.RUnlock()

	exp := struct {
		Files map[string]string
	}{
		Files: i.files,
	}
	return json.Marshal(exp)
}

func (i *index) UnmarshalJSON(b []byte) error {
	i.Lock()
	defer i.Unlock()

	var exp struct {
		Files map[string]string
	}
	err := json.Unmarshal(b, &exp)
	if err != nil {
		return err
	}

	i.files = make(map[string]string)
	i.index = make(map[string]bool)
	for k, v := range exp.Files {
		i.index[v] = true
		i.files[k] = v
	}
	return nil
}

// Get implements Index.
func (i *index) Get(path string) (string, bool) {
	i.RLock()
	defer i.RUnlock()

	x, ok := i.files[path]
	return x, ok
}

// Add implements Index.
func (i *index) Add(path, hash string) bool {
	i.Lock()
	defer i.Unlock()

	i.files[path] = hash
	if !i.index[hash] {
		i.index[hash] = true
		return false
	}
	return true
}

// Exists implements Index.
func (i *index) Exists(hash string) bool {
	i.RLock()
	defer i.RUnlock()

	return i.index[hash]
}

// Add the path+data to the index.
func AddContent(idx Index, path string, content []byte) (string, bool) {
	if x, ok := idx.Get(path); ok {
		return x, true
	}
	s := fmt.Sprintf("%x", sha1.Sum(content))
	return s, idx.Add(path, s)
}

// FileSystem is a type which defines a content addressable filesystem.
type FileSystem struct {
	idx Index

	fs store.RWFileSystem
}

// Open the file with the given path.  Uses the internal index to identify
// which file to open.  NB: Stat on the returned file will refer to the
// internal file.
func (s *FileSystem) Open(path string) (http.File, error) {
	realPath, ok := s.idx.Get(path)
	if !ok {
		return nil, fmt.Errorf("no such file: %v", path)
	}
	return s.open(realPath)
}

// Wait implements RWFileSystem.
func (s *FileSystem) Wait() error { return nil }

func (s *FileSystem) open(path string) (http.File, error) {
	return s.fs.Open(path)
}

func (s *FileSystem) create(path string) (io.WriteCloser, error) {
	return s.fs.Create(path)
}

type file struct {
	bytes.Buffer

	fs   *FileSystem
	path string
}

// Close acts as a signal that all the information has been written to
// the underlying buffer, and the file can be written to the RWFileSystem.
func (a *file) Close() error {
	_, ok := a.fs.idx.Get(a.path)
	if ok {
		return fmt.Errorf("file already exists: %v", a.path)
	}

	path, ok := AddContent(a.fs.idx, a.path, a.Bytes())
	if !ok {
		fmt.Println("creating", path)
		f, err := a.fs.create(path)
		if err != nil {
			return fmt.Errorf("error creating file: %v", err)
		}
		defer f.Close()
		_, err = io.Copy(f, a)
		if err != nil {
			return fmt.Errorf("error copying data into file '%v': %v", path, err)
		}
	}
	err := a.fs.writeIndex()
	if err != nil {
		return err
	}
	return nil
}

// Create a new file with path. We buffer the contents written to the io.WriteCloser
// so that the content can be hashed and then written to the underlying RWFileSystem.
func (s *FileSystem) Create(path string) (io.WriteCloser, error) {
	_, ok := s.idx.Get(path)
	if ok {
		return nil, fmt.Errorf("file already exists for '%v'", path)
	}

	return &file{
		Buffer: bytes.Buffer{},
		path:   path,
		fs:     s,
	}, nil
}

// initIndex initialises the cafs index.
func (s *FileSystem) initIndex() error {
	f, err := s.open(".idx")
	if err != nil {
		// FIXME: Improve this
		// Can't guarantee that we will get an IsNotExist(err) here
		return nil
	}
	defer f.Close()

	b, err := ioutil.ReadAll(f)
	if err != nil {
		return fmt.Errorf("error reading index: %v", err)
	}
	err = json.Unmarshal(b, s.idx)
	if err != nil {
		return fmt.Errorf("error decoding index: %v", err)
	}
	fmt.Printf("Index initialised: %d files (%d paths)", len(s.idx.(*index).index), len(s.idx.(*index).files))
	return nil
}

func (s *FileSystem) writeIndex() error {
	f, err := s.fs.Create(".idx")
	if err != nil {
		return fmt.Errorf("error creating index: %v", err)
	}
	defer f.Close()

	b, err := json.Marshal(s.idx)
	if err != nil {
		return fmt.Errorf("error encoding index: %v", err)
	}

	_, err = f.Write(b)
	if err != nil {
		return fmt.Errorf("error writing index: %v", err)
	}
	return nil
}

// New creates a new content addressable RWFileSystem.
func New(fs store.RWFileSystem) (*FileSystem, error) {
	s := &FileSystem{
		idx: NewIndex(),
		fs:  fs,
	}
	err := s.initIndex()
	if err != nil {
		return nil, err
	}
	return s, nil
}

redpajama_set_name: RedPajamaGithub


text:
package com.loonggg.alarmmanager.clock;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.loonggg.alarmmanager.clock.view.SelectRemindCyclePopup;
import com.loonggg.alarmmanager.clock.view.SelectRemindWayPopup;
import com.loonggg.lib.alarmmanager.clock.AlarmManagerUtil;
import com.loonggg.lib.alarmmanager.clock.ClockAlarmActivity;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private  TextView date_tv;
    private TimePickerView pvTime;
    private RelativeLayout repeat_rl, ring_rl;
    private TextView tv_repeat_value, tv_ring_value;
    private LinearLayout allLayout;
    private Button set_btn;
    private String time;
    private int cycle;
    private int ring;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        allLayout = (LinearLayout) findViewById(R.id.all_layout);
        set_btn = (Button) findViewById(R.id.set_btn);
        set_btn.setOnClickListener(this);
        date_tv = (TextView) findViewById(R.id.date_tv);
        repeat_rl = (RelativeLayout) findViewById(R.id.repeat_rl);
        repeat_rl.setOnClickListener(this);
        ring_rl = (RelativeLayout) findViewById(R.id.ring_rl);
        ring_rl.setOnClickListener(this);
        tv_repeat_value = (TextView) findViewById(R.id.tv_repeat_value);
        tv_ring_value = (TextView) findViewById(R.id.tv_ring_value);
        pvTime = new TimePickerView(this, TimePickerView.Type.HOURS_MINS);
        pvTime.setTime(new Date());
        pvTime.setCyclic(false);
        pvTime.setCancelable(true);
        //时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                time = getTime(date);
                date_tv.setText(time);
            }
        });

        date_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pvTime.show();
            }
        });
        ClockAlarmActivity.setTimeListener(new ClockAlarmActivity.TimeListener() {
            @Override
            public void setTime(String time) {
                date_tv.setText(time);
                String[] times = time.split(":");
                AlarmManagerUtil.setAlarm(getApplicationContext(), 1, Integer.parseInt(times[0]), Integer.parseInt
                        (times[1]), 0, 0, "闹钟响了", ring);
            }
        });

    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.repeat_rl:
                selectRemindCycle();
                break;
            case R.id.ring_rl:
                selectRingWay();
                break;
            case R.id.set_btn:
                setClock();
                break;
            default:
                break;
        }
    }

    private void setClock() {
        if (time != null && time.length() > 0) {
            String[] times = time.split(":");
            if (cycle == 0) {//是每天的闹钟
                AlarmManagerUtil.setAlarm(this, 0, Integer.parseInt(times[0]), Integer.parseInt
                        (times[1]), 0, 0, "闹钟响了", ring);
            } if(cycle == -1){//是只响一次的闹钟
                AlarmManagerUtil.setAlarm(this, 1, Integer.parseInt(times[0]), Integer.parseInt
                        (times[1]), 0, 0, "闹钟响了", ring);
            }

            Toast.makeText(this, "闹钟设置成功", Toast.LENGTH_LONG).show();
        }

    }

    public void selectRemindCycle() {
        final SelectRemindCyclePopup fp = new SelectRemindCyclePopup(this);
        fp.showPopup(allLayout);
        fp.setOnSelectRemindCyclePopupListener(new SelectRemindCyclePopup
                .SelectRemindCyclePopupOnClickListener() {

            @Override
            public void obtainMessage(int flag, String ret) {
                switch (flag) {
                    case 8:
                        tv_repeat_value.setText("每天");
                        cycle = 0;
                        fp.dismiss();
                        break;
                    case 9:
                        tv_repeat_value.setText("只响一次");
                        cycle = -1;
                        fp.dismiss();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    public void selectRingWay() {
        SelectRemindWayPopup fp = new SelectRemindWayPopup(this);
        fp.showPopup(allLayout);
        fp.setOnSelectRemindWayPopupListener(new SelectRemindWayPopup
                .SelectRemindWayPopupOnClickListener() {

            @Override
            public void obtainMessage(int flag) {
                switch (flag) {
                    // 震动
                    case 0:
                        tv_ring_value.setText("震动");
                        ring = 0;
                        break;
                    // 铃声
                    case 1:
                        tv_ring_value.setText("铃声");
                        ring = 1;
                        break;
                    default:
                        break;
                }
            }
        });
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
   <extension
         point="com.ibm.team.rtc.cli.infrastructure.subcommand">
      <subcommand
            class="to.rtc.cli.migrate.git.MigrateToGit"
            id="to.rtc.cli.migrate.git.MigrateToGit"
            initpolicy="uri/argument/ancestor"
            name="migrate-to-git"
            options="to.rtc.cli.migrate.git.MigrateToGitOptions"
            shortHelp="migrate to git">
      </subcommand>
   </extension>
</plugin>


text:
package io.quarkus.narayana.interceptor;

import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;

public class TestXAResource implements XAResource {
    final TxAssertionData txAssertionData;

    TestXAResource(TxAssertionData txAssertionData) {
        this.txAssertionData = txAssertionData;
    }

    @Override
    public void commit(Xid xid, boolean b) throws XAException {
        txAssertionData.addCommit();
    }

    @Override
    public void end(Xid xid, int i) throws XAException {
    }

    @Override
    public void forget(Xid xid) throws XAException {
    }

    @Override
    public int getTransactionTimeout() throws XAException {
        return 0;
    }

    @Override
    public boolean isSameRM(XAResource xaResource) throws XAException {
        return false;
    }

    @Override
    public int prepare(Xid xid) throws XAException {
        return XA_OK;
    }

    @Override
    public Xid[] recover(int i) throws XAException {
        return new Xid[0];
    }

    @Override
    public void rollback(Xid xid) throws XAException {
        txAssertionData.addRollback();
    }

    @Override
    public boolean setTransactionTimeout(int i) throws XAException {
        return false;
    }

    @Override
    public void start(Xid xid, int i) throws XAException {
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- EN-Revision: 22785 -->
<!-- Reviewed: no -->
<sect1 id="zend.service.windowsazure.storage.queue">
    <title>Zend_Service_WindowsAzure_Storage_Queue</title>

    <para>
        Das Queue Service speichert Nachrichten die von jedem Client gelesen werden können welche
        auf den Speicher Account Zugriff haben.
    </para>

    <para>
        Eine Queue kann eine unbegrenzte Anzahl an Nachrichten enthalten, jede von Ihnen bis zu 8KB
        groß. Nachrichten werden generell am Ende der Queue hinzugefügt und vom Anfang der Queue
        empfangen, auch wenn das First In / First Out Verhalten (<acronym>FIFO</acronym>) nicht
        garantiert ist. Wenn man Nachrichten speichern muss die größer als 8KB sind, können die
        Daten der Nachricht als Queue gespeichert werden oder in einer Tabelle und anschließend eine
        Referenz zu den Daten als Nachricht in der Queue.
    </para>

    <para>
        Der Queue Speicher wird von Windows Azure als <acronym>REST</acronym> <acronym>API</acronym>
        angeboten welche von der <classname>Zend_Service_WindowsAzure_Storage_Queue</classname>
        Klasse umhüllt wird um ein natives <acronym>PHP</acronym> Interface zum Speicher Account zu
        bieten.
    </para>

    <sect2 id="zend.service.windowsazure.storage.queue.api">
        <title>API Beispiele</title>

        <para>
            Dieses Thema listet einige Beispiele der Verwendung der
            <classname>Zend_Service_WindowsAzure_Storage_Queue</classname> Klasse auf. Andere
            Features sind im Download Paket vorhanden, sowie eine detailierte <acronym>API</acronym>
            Dokumentation dieser Features.
        </para>

        <sect3 id="zend.service.windowsazure.storage.queue.api.create-queue">
            <title>Erstellung einer Queue</title>

            <para>
                Bei Verwendung des folgenden Codes kann eine Queue auf dem Development Speicher
                erstellt werden.
            </para>

            <example id="zend.service.windowsazure.storage.queue.api.create-queue.example">
                <title>Erstellung einer Queue</title>

                <programlisting language="php"><![CDATA[
$storageClient = new Zend_Service_WindowsAzure_Storage_Queue();
$result = $storageClient->createQueue('testqueue');

echo 'Der Name der Queue ist: ' . $result->Name;
]]></programlisting>
            </example>
        </sect3>

        <sect3 id="zend.service.windowsazure.storage.queue.api.delete-queue">
            <title>Löschen einer Queue</title>

            <para>
                Bei Verwendung des folgenden Codes kann eine Queue vom Development Speicher entfernt
                werden.
            </para>

            <example id="zend.service.windowsazure.storage.queue.api.delete-queue.example">
                <title>Löschen einer Queue</title>

                <programlisting language="php"><![CDATA[
$storageClient = new Zend_Service_WindowsAzure_Storage_Queue();
$storageClient->deleteQueue('testqueue');
]]></programlisting>
            </example>
        </sect3>

        <sect3 id="zend.service.windowsazure.storage.queue.api.storing-queue">
            <title>Hinzufügen einer Nachricht zu einer Queue</title>

            <para>
                Bei Verwendung des folgenden Codes kann eine Nachricht zu einer Queue im
                Development Speicher hinzugefügt werden. Es ist zu beachten das die Queue hierfür
                bereits erstellt worden sein muss.
            </para>

            <example id="zend.service.windowsazure.storage.queue.api.storing-queue.example">
                <title>Hinzufügen einer Nachricht zu einer Queue</title>

                <programlisting language="php"><![CDATA[
$storageClient = new Zend_Service_WindowsAzure_Storage_Queue();

// 3600 = Lebenszeit der Nachricht,
// wenn nicht angegeben ist der Standardwert 7 Tage
$storageClient->putMessage('testqueue', 'Das ist eine Testnachricht', 3600);
]]></programlisting>
            </example>
        </sect3>

        <sect3 id="zend.service.windowsazure.storage.queue.api.read-queue">
            <title>Lesen einer Nachricht von einer Queue</title>

            <para>
                Bei Verwendung des folgenden Codes kann eine Nachricht von einer Queue im
                Development Speicher gelesen werden. Es ist zu beachten das die Queue und die
                Nachricht hierfür bereits erstellt worden sein muss.
            </para>

            <example id="zend.service.windowsazure.storage.queue.api.read-queue.example">
                <title>Lesen einer Nachricht von einer Queue</title>

                <programlisting language="php"><![CDATA[
$storageClient = new Zend_Service_WindowsAzure_Storage_Queue();

// 10 Nachrichten auf einmal empfangen
$messages = $storageClient->getMessages('testqueue', 10);

foreach ($messages as $message) {
    echo $message->MessageText . "\r\n";
}
]]></programlisting>
            </example>

            <para>
                Die Nachrichten welche mit <methodname>getMessages()</methodname> gelesen werden,
                werden in der Queue für 30 Sekunden unsichtbar, und danach werden die Nachrichten
                in der Queue wieder erscheinen. Um eine Nachricht als bearbeitet zu markieren und
                Sie von der Queue zu entfernen, kann die Methode
                <methodname>deleteMessage()</methodname> verwendet werden.
            </para>

            <example id="zend.service.windowsazure.storage.queue.api.read-queue.processexample">
                <title>Eine Nachricht als bearbeitet markieren</title>

                <programlisting language="php"><![CDATA[
$storageClient = new Zend_Service_WindowsAzure_Storage_Queue();

// 10 Nachrichten auf einmal empfangen
$messages = $storageClient->getMessages('testqueue', 10);

foreach ($messages as $message) {
    echo $message . "\r\n";

    // Die Nachricht als bearbeitet markieren
    $storageClient->deleteMessage('testqueue', $message);
}
]]></programlisting>
            </example>
        </sect3>

        <sect3 id="zend.service.windowsazure.storage.queue.api.peek-queue">
            <title>Prüfen ob es Nachrichten in der Queue gibt</title>

            <para>
                Bei Verwendung des folgenden Codes kann eine Queue auf neue Nachrichten geprüft
                werden. Es ist zu beachten das die Queue und die Nachricht  hierfür bereits erstellt
                worden sein müssen.
            </para>

            <example id="zend.service.windowsazure.storage.queue.api.peek-queue.example">
                <title>Prüfen ob es Nachrichten in einer Queue gibt</title>

                <programlisting language="php"><![CDATA[
$storageClient = new Zend_Service_WindowsAzure_Storage_Queue();

// 10 Nachrichten auf einmal empfangen
$messages = $storageClient->peekMessages('testqueue', 10);

foreach ($messages as $message) {
    echo $message->MessageText . "\r\n";
}
]]></programlisting>
            </example>

            <para>
                Es ist zu beachten das Nachrichten welche mit Hilfe von
                <methodname>peekMessages()</methodname> gelesen werden in der Queue nicht
                unsichtbar, und durch Verwendung der Methode
                <methodname>deleteMessage()</methodname> auch nicht als bearbeitet markiert werden
                können. Um das zu tun sollte stattdessen <methodname>getMessages()</methodname>
                verwendet werden.
            </para>
        </sect3>
    </sect2>
</sect1>


text:
package com.hazelcast.sql.impl.exec.scan.index;

import com.hazelcast.query.impl.InternalIndex;
import com.hazelcast.query.impl.QueryableEntry;
import com.hazelcast.sql.impl.expression.ExpressionEvalContext;

import java.util.Iterator;

/**
 * Index filter which is transferred over a wire.
 */
@SuppressWarnings("rawtypes")
public interface IndexFilter {
    /**
     * Get index entries iterator
     *
     * @param index index
     * @return iterator
     */
    Iterator<QueryableEntry> getEntries(InternalIndex index, ExpressionEvalContext evalContext);

    /**
     * Gets the value to be queried. Used by upper filter to construct the final lookup request.
     *
     * @return the value to be queried
     */
    Comparable getComparable(ExpressionEvalContext evalContext);
}


text:
'use strict'
var cons = require('./console'),
    colors = require('colors'),
	_ = require('lodash');

/* Logger
	API:
		logger[level](<msg>[, user, platform])

        	level is a configured level: trace, debug, etc.
            msg is required (the message)
            company, product, etc are optional

		logger[level](<msg>[, {user: '', platform: ''}])

        	level is a configured level: trace, debug, etc.
            msg is required (the message)
            object containing company, product, etc is optional (as are the individual properties)

	Configuration:
		log: {
		  server: { // server-side logging parameters
          	  levels: ['error', 'warn', 'info', 'debug'],
		      expressFormat: ':remote-addr - - [:date] ":method :url HTTP/:http-version" (:status) :res[content-length] ":referrer" ":user-agent"',
		      transports: { // logging transports
		      	console: {
                  format: ['date', 'level', 'message', 'user', 'platform', 'locale', 'stack'],
		          level: 'info', // maximum level of logged messages
		          enabled: false, // this switch can be used to easily toggle use of a given transport
		          colorize: true, // this switch can be used to easily toggle use of colors
	              json: false	 // plain text or json output
		        }
		      }
		  },
		  client: { // client-side logging parameters
	      	transports: {
		      	console: {
		          level: 'debug', // maximum level of logged messages
		          enabled: true // this switch can be used to easily toggle use of a given transport
		        },
	            server: {
		          level: 'debug', // maximum level of logged messages
		          enabled: false, // this switch can be used to easily toggle use of a given transport
	              buffer: {
	              	interval: 2000,
	                limit: 500
	              }
	            }
		    }
		  }
		}
*/

colors.setTheme({
	trace: 'green',
    debug: 'cyan',
    info: 'blue',
    warn: 'yellow',
    error: 'red',
    fatal: 'magenta'
});

var defaultExpressFormat = ':remote-addr - - [:date] ":method :url HTTP/:http-version" (:status) :res[content-length] ":referrer" ":user-agent"';
var defaultFormat = ['date', 'level', 'message', 'user', 'platform', 'locale', 'stack'];
var defaultLevels = {
	trace: 0,
    debug: 1,
    info: 2,
    warn: 3,
    error: 4,
    fatal: 5
};
var defaultTransports = {
	console: {
    	level: 'info',
        enabled: true,
        json: false
	}
};

function makeLevels(cfg) {
	if (!cfg.levels) {
    	return defaultLevels;
    }
    var idx = cfg.levels.length;
    return _.object(cfg.levels, _.map(cfg.levels, function(level) {return idx--;}));
}

function makeTransports(cfg) {
    var transports = _.cloneDeep(cfg.transports || defaultTransports);
    var wtransports = {};
    _.each(transports, function(transport, type) {
    	if (typeof transport.enabled === 'undefined' || transport.enabled) {
            wtransports[type] = _.extend(defaultTransports[type]||{}, transport);
            if (type === 'console') {
            	wtransports[type].out = cons.log;
			} else {
            	wtransports[type].out = function(){}
            }
        }
    });
    return wtransports;
}

/*
pad(
 input // (int or string) or undefined,NaN,false,empty string
       // default:0 or PadCharacter
 // optional
 ,PadLength // (int) default:2
 ,PadCharacter // (string or int) default:'0'
 ,PadDirection // (bolean) default:0 (padLeft) - (true or 1) is padRight
)
*/
function pad(a,b,c,d){
	return a=(a||c||0)+'',b=new Array((++b||3)-a.length).join(c||0),d?a+b:b+a;
}
function formatToken(token, args, json) {
	if (token == 'date') {
    	var d = new Date();
        return d.toISOString();
    }
	if (token == 'stack') {
    	var e = new Error();
        return e.stack;
    }
    if (token == 'level' && !json) {
    	return pad(args[token] || '', 5, ' ', true);
    }
    return args[token] || '';
}

function format(format, args, json, colorizefn) {
	format = format || defaultFormat;
    var props = _.extend({level: args[0],message: args[1]}, (args.length > 2 && _.isObject(args[2]))
    	? args[2]
        : _.object(_.pull(_.clone(format), 'level','message'), _.rest(args,2))
	);
    var formatted = _.map(format, function(fmt) {
    	var v = formatToken(fmt, props, json);
        if (colorizefn && fmt == 'level') {
        	v = colorizefn(v);
        }
        return v;
	});
	if (json) {
    	return JSON.stringify(_.object(format, formatted));
    }

    return _.filter(formatted, function(t) {return !!t;}).join(' - ');
}

function colorize(transport, level) {
	if (typeof transport.colorize === 'undefined' || transport.colorize) {
    	return colors[level];
    }
    return null;
}

exports = module.exports = (config) => {
    var cfg = _.get(config, 'log.server');
    var levels = makeLevels(cfg);
    var transports = makeTransports(cfg);

    function log(args) {
    	var level = _.first(args);
    	_.each(transports, function(transport, type) {
        	if ((levels[level] || 99) >= (levels[transport.level] || 0)) {
            	var msg = format(transport.format, args, transport.json, colorize(transport, level));
                transport.out(msg);
            }
        });
    }

    function getExpressFormat() {
    	return cfg.expressFormat || defaultExpressFormat;
    }

    var logger = {
    	getExpressFormat: getExpressFormat
    };
    _.each(levels, function(level, type) {
    	logger[type] = function() {
        	log(Array.prototype.concat.apply([type], arguments));
        }
    });
    return logger;
}


text:
package com.mogujie.trade.db;

/**
 * @author by jiuru on 16/7/14.
 */
public class DataSourceConfig {

    static final int DEFAULT_MIN_POOL_SIZE = 0;
    static final int DEFAULT_MAX_POOL_SIZE = 10;
    static final int DEFAULT_INI_POOL_SIZE = 0;

    private String url;

    private String username;

    private String password;

    private int minPoolSize;

    private int maxPoolSize;

    private int initialPoolSize;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getMinPoolSize() {
        return minPoolSize;
    }

    public void setMinPoolSize(int minPoolSize) {
        this.minPoolSize = minPoolSize;
    }

    public int getMaxPoolSize() {
        return maxPoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public int getInitialPoolSize() {
        return initialPoolSize;
    }

    public void setInitialPoolSize(int initialPoolSize) {
        this.initialPoolSize = initialPoolSize;
    }

}


text:
#ifndef _ENUMERATE_H_
#define _ENUMERATE_H_

#include <vcc/util.h>
#include <set>
#include <vector>

namespace vcc {
namespace enumerate {

VCC_LIBRARY std::vector<VkLayerProperties> instance_layer_properties();
VCC_LIBRARY std::vector<VkLayerProperties> device_layer_properties(
	VkPhysicalDevice device);

VCC_LIBRARY std::vector<VkExtensionProperties> instance_extension_properties(
	const std::string &layer_name);
VCC_LIBRARY std::vector<VkExtensionProperties> device_extension_properties(
	VkPhysicalDevice device, const std::string &layer_name);

// TODO(gardell): Possibly contain version, not just string
VCC_LIBRARY bool contains_all(const std::vector<VkLayerProperties> &layers,
	const std::set<std::string> &required);

VCC_LIBRARY std::vector<std::string> filter(
	const std::vector<VkLayerProperties> &layers,
	const std::set<std::string> &optional);

// TODO(gardell): Possibly contain version, not just string
VCC_LIBRARY bool contains_all(
	const std::vector<VkExtensionProperties> &extensions,
	const std::set<std::string> &required);

VCC_LIBRARY std::vector<std::string> filter(
	const std::vector<VkExtensionProperties> &extensions,
	const std::set<std::string> &optional);

}  // namespace enumerate
}  // namespace vcc

#endif /* _ENUMERATE_H_ */


text:
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';

@Component({
  selector: 'gt-golfer',
  templateUrl: './golfer.component.html',
  styleUrls: ['./golfer.component.css']
})
export class GolferComponent implements OnInit {
  pageTitle: string = 'Golfers';

  constructor(private _title: Title) {
    this._title.setTitle(this.pageTitle + ' - GolfTracker');
  }

  ngOnInit() {
  }

}


text:
@interface ViewController ()<GSTaggedProgressViewDataSource>
@property (weak, nonatomic) IBOutlet GSTaggedProgressView *firstProgressView;
@property (weak, nonatomic) IBOutlet GSTaggedProgressView *secondProgressView;
@property (strong, nonatomic) NSArray *firstDataSource, *secondDataSource;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self initDataSource];
    self.firstProgressView.dataSource = self;
    self.firstProgressView.tagWidthStyle = GSTagWidthStyleFixed;
    [self.firstProgressView reloadData];

    self.secondProgressView.dataSource = self;
    self.secondProgressView.tagWidthStyle = GSTagWidthStylePercent;
    self.secondProgressView.progress = 0;
    [self.secondProgressView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initDataSource
{
    self.firstDataSource = @[@{@"startProgress":@(0.12)},
                        @{@"startProgress":@(0.22)},
                        @{@"startProgress":@(0.43)},
                        @{@"startProgress":@(0.51)},
                        @{@"startProgress":@(0.62)},
                        @{@"startProgress":@(0.86)}
                        ];

    self.secondDataSource = @[@{@"startProgress":@(0.12), @"endProgress":@(0.16)},
                             @{@"startProgress":@(0.24), @"endProgress":@(0.26)},
                             @{@"startProgress":@(0.33), @"endProgress":@(0.48)},
                             @{@"startProgress":@(0.49), @"endProgress":@(0.5821)},
                             @{@"startProgress":@(0.61), @"endProgress":@(0.722)},
                             @{@"startProgress":@(0.733), @"endProgress":@(0.755)},
                             @{@"startProgress":@(0.82), @"endProgress":@(0.952)},
                             ];
}

#pragma mark - GSTaggedProgressViewDataSource
- (NSInteger)numberOfTagsInProgressView:(GSTaggedProgressView *)aProgressView
{
    if (aProgressView == self.firstProgressView) {
        return self.firstDataSource.count;
    } else if (aProgressView == self.secondProgressView) {
        return self.secondDataSource.count;
    } else {
        return 0;
    }
}

- (CGFloat)progressView:(GSTaggedProgressView *)aProgressView startProgressForTagAtIndex:(NSInteger)anIndex
{
    if (aProgressView == self.firstProgressView) {
        NSDictionary *dict = [self.firstDataSource objectAtIndex:anIndex];
        return [[dict objectForKey:@"startProgress"] floatValue];
    } else if (aProgressView == self.secondProgressView) {
        NSDictionary *dict = [self.secondDataSource objectAtIndex:anIndex];
        return [[dict objectForKey:@"startProgress"] floatValue];
    } else {
        return 0;
    }
}

- (CGFloat)progressView:(GSTaggedProgressView *)aProgressView endProgressForTagAtIndex:(NSInteger)anIndex
{
    if (aProgressView == self.secondProgressView) {
        NSDictionary *dict = [self.secondDataSource objectAtIndex:anIndex];
        return [[dict objectForKey:@"endProgress"] floatValue];
    } else {
        return 0;
    }
}

//- (CGFloat)progressView:(GSTaggedProgressView *)aProgressView fixedWidthForTagAtIndex:(NSInteger)anIndex
//{
//
//}

- (UIColor *)progressView:(GSTaggedProgressView *)aProgressView colorForTagAtIndex:(NSInteger)anIndex
{
    if (aProgressView == self.firstProgressView) {
        return [UIColor whiteColor];
    } else {
        return [self randomColor];
    }
}

#pragma mark - Util
- (UIColor*)randomColor
{
    int r = arc4random() % 255;
    int g = arc4random() % 255;
    int b = arc4random() % 255;
    return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1];
}
@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Epicr. syst. mycol. (Upsaliae) 106 (1838)

#### Original name
Agaricus sudorus Fr.

### Remarks
null


text:
var BlockStream = require('./block-stream')
var u = require('./util')
var crypto = require('crypto')

module.exports = function (opts, onTree) {
  if('function' === typeof opts)
    onTree = opts, opts = {}

  var blklen = opts.blklen || 1024

  var createHash = opts.createHash || function () {
    return crypto.createHash('sha256')
  }

  var hashlen = opts.hashlen

  function digest (h) {
    var d = h.digest()
    return (
        hashlen && d.length > hashlen
      ? d.slice(0, hashlen)
      : d
    )
  }

  var ary = []
  var cur = createHash(), m = 0
  var stream = BlockStream(blklen, function (data, n) {
    if(m != n) {
      ary[m] = digest(cur);
      m = n; cur = createHash().update(data)
    }
    else
      cur.update(data)
  }, function () {
    ary[m] = digest(cur)
    this.emit('tree', u.fromArray(ary))
  })

  if(onTree) stream.on('tree', onTree)

  return stream
}


text:
package dataComponents;

import stationServerIDL.Upcasted_Record;

public class MissingRecord extends Record{

	public MissingRecord(String firstName, String lastName, String address, long lastDate, String lastLocation, StatusType status) {
		super(firstName, lastName, status);
		this.setAddress(address);
		this.setLastDate(lastDate);
		this.setLastLocation(lastLocation);

		if(status == StatusType.ON_THE_RUN|| status == StatusType.CAPTURED){
			System.err.println("Error: A CriminalRecord cannot have a MISSING or FOUND status");
			System.exit(0);
		}

		synchronized(synchronizedObjectForInstantiation){
			if(idCount == 100000){
				System.out.println("Error: Maximum criminal records have been created");
				System.exit(1);
			}
			RecordID = "MR"+idCount;
			idCount++;
		}
	}

	/**
	 * This constructor copies the interested contents of theRecord
	 * @param theRecord
	 */
	@SuppressWarnings("deprecation")
	public MissingRecord(Upcasted_Record theRecord) {
		super(theRecord.firstName, theRecord.lastName, convertStatusString2StatusType(theRecord.status));
		this.address = theRecord.address;
		this.lastDate = theRecord.lastDate;
		this.lastLocation = theRecord.lastLocation;
		synchronized(synchronizedObjectForInstantiation){
			if(idCount == 100000){
				System.out.println("Error: Maximum criminal records have been created");
				System.exit(1);
			}
			RecordID = "MR"+idCount;
			idCount++;
		}
	}

	public long getLastDate() {
		return lastDate;
	}

	public void setLastDate(long lastDate) {
		this.lastDate = lastDate;
	}

	public String getLastLocation() {
		return lastLocation;
	}

	public void setLastLocation(String lastLocation) {
		this.lastLocation = lastLocation;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	private String address;
	private long lastDate;
	private String lastLocation;

}


text:
//
//  MainTabViewController.m
//  Location
//
//  Created by taq on 10/31/14.
//  Copyright (c) 2014 Location. All rights reserved.
//

#import "MainTabViewController.h"
#import "TSTabBarItem.h"
#import "NoGpsHintView.h"
#import "OpenGpsViewController.h"

@interface MainTabViewController ()

@end

@implementation MainTabViewController

- (void)loadView
{
    UIViewController* homeVC = InstFirstVC(@"CarHome");
    UIViewController* tripVC = InstFirstVC(@"CarTrip");;
    UIViewController* assistorVC = InstFirstVC(@"CarAssistor");;
    //UIViewController* healthVC = InstFirstVC(@"CarHealth");
    UIViewController* settingVC = InstFirstVC(@"CarSetting");

    NSArray * itemIcons = @[@"tab01", @"tab02", @"tab03", @"tab05"];
    NSArray * highlightIcons = @[@"tab01_active", @"tab02_active", @"tab03_active", @"tab05_active"];
    //NSArray * itemTitles = @[@"首页", @"旅程", @"问路", @"健康", @"设置"];

    NSMutableArray * itemModels = [NSMutableArray array];
    [itemIcons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        TSTabBarItemModel * model = [TSTabBarItemModel new];
        model.itemIndex = idx;
        model.itemImage = [UIImage imageNamed:obj];
        model.itemSelectedImage = [UIImage imageNamed:highlightIcons[idx]];
        //model.itemTitle = itemTitles[idx];
        [itemModels addObject:model];
    }];

    [self setViewControllers:@[homeVC, tripVC, assistorVC, settingVC] withTabBarItemModels:itemModels];

    [super loadView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self.tabBar setTabShadowImage:[UIImage imageNamed:@"shadowtab"]];
    self.tabBar.backgroundImageView.image = [UIImage imageNamed:@"tabbar"];
    [self setSelectedIndex:0 animed:NO];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterForeground) name:@"kLocationAuthrizeStatChange" object:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self applicationEnterForeground];
}

- (void)applicationEnterForeground
{
    // show hint view
    CLAuthorizationStatus authorizationStatus= [CLLocationManager authorizationStatus];
    if (kCLAuthorizationStatusAuthorizedAlways != authorizationStatus) {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"NoGpsHintView" owner:self options:nil];
        NoGpsHintView * hintView = (NoGpsHintView*)[nibs objectAtIndex:0];
        [hintView.howToBtn addTarget:self action:@selector(showHowToOpenGps) forControlEvents:UIControlEventTouchUpInside];
        [self showHintView:hintView];
    } else {
        [self showHintView:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showHowToOpenGps
{
    OpenGpsViewController * openGpsVC = InstFirstVC(@"OpenGps");
    [self presentViewController:openGpsVC animated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
from debile.utils.commands import run_command

def arch_matches(arch, alias):
    """
    Check if given arch `arch` matches the other arch `alias`. This is most
    useful for the complex any-* rules.
    """

    if arch == alias:
        return True

    if arch == 'all' or arch == 'source':
        # These pseudo-arches does not match any wildcards or aliases
        return False

    if alias == 'any':
        # The 'any' wildcard matches all *real* architectures
        return True

    if alias == 'linux-any':
        # GNU/Linux arches are named <cpuabi>
        # Other Linux arches are named <libc>-linux-<cpuabi>
        return '-' not in arch or 'linux' in arch.split('-')

    if alias.endswith('-any'):
        # Non-Linux GNU/<os> arches are named <os>-<cpuabi>
        # Other non-Linux arches are named <libc>-<os>-<cpuabi>
        osname, _ = alias.split('-', 1)
        return osname in arch.split('-')

    if "-" not in arch and "-" not in alias:
        return False

    # This is a fucking disaster for perf. Do what we can to not get here.
    out, err, ret = run_command([
        "/usr/bin/dpkg-architecture",
        "-a%s" % (arch),
        "-i%s" % (alias)
    ])
    return ret == 0

def get_preferred_affinity(
    affinity_preference, valid_affinities, valid_arches
):
    """
    Given a list of strings representing the preffered affinities in the
    config, a list of string with valid affinities of the source, and a list
    of valid architectures in the suite, return the arch object to use as
    affinity for arch "all" jobs.
    """

    for affinity in affinity_preference:
        arch = None
        for x in valid_arches:
            if x.name == affinity:
                arch = x
                break
        if arch is None:
            continue
        for alias in valid_affinities:
            if arch_matches(affinity, alias):
                return arch

    raise ValueError(
        "No valid affinity - preferences: '%s'; valid: '%s'; arches %s" % (
            ", ".join(affinity_preference),
            ", ".join(valid_affinities),
            ", ".join([x.name for x in valid_arches]),))

def get_source_arches(dsc_arches, valid_arches):
    """
    Given a list of strings with the Architectures data from the dsc,
    and a list of valid Arch objects from the suite, return the Arch
    objects to add to the Source object.
    """

    ret = []

    for arch in valid_arches:
        for alias in dsc_arches:
            if arch_matches(arch.name, alias):
                ret.append(arch)
                break  # Break inner loop, continue outer loop

    return ret


text:
        @if((sizeof($files) > 0) || (sizeof($directories) > 0))

            @foreach($directories as $key => $dir)

                            {{----}}

                            <button type="button" onclick="clickFolder('large_folder_{{ $key }}',1)"
                                    class="btn btn-default btn-xs">
                                {!! str_limit(basename($dir), $limit = 10, $end = '...') !!}
                            </button>
                            <button type="button" class="btn btn-default dropdown-toggle btn-xs" data-toggle="dropdown"
                                    aria-expanded="false">

                                Toggle Dropdown
                            </button>

{!! Lang::get('laravel-filemanager::lfm.menu-rename') !!}

{!! Lang::get('laravel-filemanager::lfm.menu-delete') !!}

            @endforeach

            @foreach($files as $key => $file)

                            <button type="button" onclick="useFile('{!! basename($file) !!}')" class="btn btn-default btn-xs">
                                {!! str_limit(basename($file), $limit = 10, $end = '...') !!}
                            </button>
                            <button type="button" class="btn btn-default dropdown-toggle btn-xs" data-toggle="dropdown"
                                    aria-expanded="false">

                                Toggle Dropdown
                            </button>

{!! Lang::get('laravel-filemanager::lfm.menu-rename') !!}

{!! Lang::get('laravel-filemanager::lfm.menu-view') !!}

{!! Lang::get('laravel-filemanager::lfm.menu-download') !!}

                                {{--
Rotate
--}}

{!! Lang::get('laravel-filemanager::lfm.menu-resize') !!}

{!! Lang::get('laravel-filemanager::lfm.menu-crop') !!}

{!! Lang::get('laravel-filemanager::lfm.menu-delete') !!}

            @endforeach

        @else

{!! Lang::get('laravel-filemanager::lfm.message-empty') !!}

        @endif


text: {{icon.text}}


text:
<!DOCTYPE HTML>

  <meta charset="utf-8">
  <title>CSS Grid Test: align-content:baseline/last baseline</title>
  <link rel="author" title="Mats Palmgren" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1611724">
  <link rel="help" href="https://drafts.csswg.org/css-align-3/#baseline-align-content">
  <link rel="match" href="grid-item-content-baseline-004-ref.html">
  <link rel="stylesheet" type="text/css" href="/fonts/ahem.css">

AM
NX

AM
NX

AM
NX

AM
NX

AM
NX

AM
NX

AM
N

AM
N

AM
N

AM
N

AM
N

AM
N

AM
NX

AM
NX

AM
NX

AM
NX

AM
NX

AM
NX

AM
N

AM
N

AM
N

AM
N

AM
N

AM
N

AM
NX

AM
NX

AM
NX

AM
NX

AM
NX

AM
NX

AM
N

AM
N

AM
N

AM
N

AM
N

AM
N


text:
package jenkins.plugins.git.traits;

import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.plugins.git.extensions.GitSCMExtension;
import jenkins.plugins.git.GitSCMBuilder;
import jenkins.scm.api.trait.SCMBuilder;
import jenkins.scm.api.trait.SCMSourceTrait;

/**
 * Base class for exposing a {@link GitSCMExtension} as a {@link SCMSourceTrait}.
 *
 * @param <E> the {@link GitSCMExtension} that is being exposed
 * @since 3.4.0
 */
public abstract class GitSCMExtensionTrait<E extends GitSCMExtension> extends SCMSourceTrait {
    /**
     * The extension.
     */
    @NonNull
    private final E extension;

    /**
     * Constructor.
     *
     * @param extension the extension.
     */
    @SuppressFBWarnings(value="EI_EXPOSE_REP2", justification="Low risk")
    public GitSCMExtensionTrait(@NonNull E extension) {
        this.extension = extension;
    }

    /**
     * Gets the extension.
     *
     * @return the extension.
     */
    @NonNull
    @SuppressFBWarnings(value="EI_EXPOSE_REP", justification="Low risk")
    public E getExtension() {
        return extension;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void decorateBuilder(SCMBuilder<?,?> builder) {
        ((GitSCMBuilder<?>) builder).withExtension(extension);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/DialogFragmentMain" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include
            layout="@layout/dialog_negative_button"/>

        <include layout="@layout/dialog_title" />

    </LinearLayout>

    <TextView
        android:id="@+id/dialog_message"
        style="@style/DialogFragmentBody" />

    <include
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        layout="@layout/dialog_positive_button"/>

</LinearLayout>


text:
'use strict';

import path from 'path';
import glob from 'glob';
import browserify from 'browserify';
import watchify from 'watchify';
import envify from 'envify';
import babelify from 'babelify';
import _ from 'lodash';
import vsource from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import gulpif from 'gulp-if';

export default function(gulp, plugins, args, config, taskTarget, browserSync) {
  let dirs = config.directories;
  let entries = config.entries;

  let browserifyTask = (files) => {
    return files.map((entry) => {
      let dest = path.resolve(taskTarget);

      // Options
      let customOpts = {
        entries: [entry],
        debug: true,
        transform: [
          babelify, // Enable ES6 features
          envify // Sets NODE_ENV for better optimization of npm packages
        ]
      };

      let bundler = browserify(customOpts);

      if (!args.production) {
        // Setup Watchify for faster builds
        let opts = _.assign({}, watchify.args, customOpts);
        bundler = watchify(browserify(opts));
      }

      let rebundle = function() {
        let startTime = new Date().getTime();
        bundler.bundle()
          .on('error', function(err) {
            plugins.util.log(
              plugins.util.colors.red('Browserify compile error:'),
              '\n',
              err.stack,
              '\n'
            );
            this.emit('end');
          })
          .on('error', plugins.notify.onError(config.defaultNotification))
          .pipe(vsource(entry))
          .pipe(buffer())
          .pipe(plugins.sourcemaps.init({loadMaps: true}))
            .pipe(gulpif(args.production, plugins.uglify()))
            .on('error', plugins.notify.onError(config.defaultNotification))
          .pipe(plugins.rename(function(filepath) {
            // Remove 'source' directory as well as prefixed folder underscores
            // Ex: 'src/_scripts' --> '/scripts'
            filepath.dirname = filepath.dirname.replace(dirs.source, '').replace('_', '');
          }))
          .pipe(plugins.sourcemaps.write('./'))
          .pipe(gulp.dest(dest))
          // Show which file was bundled and how long it took
          .on('end', function() {
            let time = (new Date().getTime() - startTime) / 1000;
            console.log(
              plugins.util.colors.cyan(entry)
              + ' was browserified: '
              + plugins.util.colors.magenta(time + 's'));
            return browserSync.reload('*.js');
          });
      };

      if (!args.production) {
        bundler.on('update', rebundle); // on any dep update, runs the bundler
        bundler.on('log', plugins.util.log); // output build logs to terminal
      }
      return rebundle();
    });
  };

  // Browserify Task
  gulp.task('browserify', (done) => {
    return glob('./' + path.join(dirs.source, dirs.scripts, entries.js), function(err, files) {
      if (err) {
        done(err);
      }

      return browserifyTask(files);
    });
  });
}


text:
namespace libshape
{
	class Layer;
	class IVisitor;

	class LayersMgrWidget : public wxPanel
	{
		class LayerWidget;

	public:
		LayersMgrWidget(wxWindow* parent, wxWindow* stage);
		virtual ~LayersMgrWidget();

		void traverseEditableLayers(IVisitor& visitor);
		void traverseVisibleLayers(IVisitor& visitor);
		void traverseSelectableLayers(IVisitor& visitor);
		void traverseAllLayers(IVisitor& visitor);

		void setEditable(LayerWidget* layer);

		Layer* getEditedLayer() { return m_editedLayer; }

		void getAllLayers(std::vector<Layer*>& layers) const;

		void addLayer(Layer* layer);
		void addLayerBottom(Layer* layer);

		void clear();

	private:
		class LayerWidget : public wxPanel
		{
		public:
			LayerWidget(wxWindow* parent, Layer* layer);

			bool isVisible() const;
			bool isSelectable() const;

			void setEditable(bool editable);

			Layer* getLayer() { return m_layer; }

		protected:
			void onSetVisible(wxCommandEvent& event);
			void onSetEditable(wxCommandEvent& event);
			void onSetSelectable(wxCommandEvent& event);
			void onSetName(wxCommandEvent& event);

		private:
			void initLayout();

		private:
			wxRadioButton* m_editable;

			wxCheckBox* m_visible;

			wxCheckBox* m_selectable;

			wxTextCtrl* m_name;

			Layer* m_layer;
		};

	private:
		void initLayout();

		wxSizer* initLayersPanel();
		wxSizer* initButtonsPanel();

		void onAddLayer(wxCommandEvent& event);
		void onDelLayer(wxCommandEvent& event);
		void onLayerUp(wxCommandEvent& event);
		void onLayerDown(wxCommandEvent& event);

		int getEditLayerIndex() const;

	private:
		wxWindow* m_stage;

		std::vector<LayerWidget*> m_layers;

		Layer* m_editedLayer;

		wxSizer* m_layersSizer;

		wxButton *m_btnAdd, *m_btnDel;
		wxButton *m_btnUp, *m_btnDown;

	}; // LayersMgrWidget
}

#endif // _LIBSHAP_LAYERS_MANAGER_WIDGET_H_


text:
"""
For detailed usage instructions, see the readme.txt file included with the
pywrds distribution.  For the reading-averse, do the following:

The first time you run pywrds, put your WRDS username and institution
in quotes in the user_info.txt file.  Then set up a key-based login
with the WRDS server by running:

pywrds.setup_wrds_key()

You will be prompted for your WRDS password at that point, but then
never again while using that computer.  Then you can easily download a file,
say the March 2004 CRSP daily stock file with:

pywrds.get_wrds('crsp.dsf', 2004, 3)

Or you can download the *entire* Compustat Fundamentals Quarterly file with:

pywrds.wrds_loop('comp.fundq')

Data files will download to the pywrds/output directory.  Have fun.
"""

thisAlgorithmBecomingSkynetCost = 99999999999

__all__ = [
    "ectools",
    "wrdslib",
    "static",
    "sas",
    "wrds_loop",
    "get_wrds",
    "find_wrds",
    "setup_wrds_key",
    "user_info"
    ]
from . import ectools, wrdslib, sas, static

try: import simplejson as json
except ImportError: import json

get_wrds = ectools.get_wrds
wrds_loop = ectools.wrds_loop
find_wrds = ectools.find_wrds
setup_wrds_key = wrdslib.setup_wrds_key
user_info = wrdslib.user_info

import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
formatter = logging.Formatter(log_format)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)

import os
_pywrds_dir = os.path.join(os.path.expanduser('~'), '.pywrds')
_user_file = os.path.join(_pywrds_dir, 'user_info.txt')

def setup_pywrds():
    if not os.path.exists(_pywrds_dir):
        try:
            os.mkdir(_pywrds_dir)
        except OSError:
            logger.error("pywrds was unable to create the directory"
                + _pywrds_dir+".  Please create this directory"
                + " and re-load pywrds."
                )
    if not os.path.exists(_user_file):
        fd = open(_user_file, 'wb') ## permissions ?? ## lock??##
        fd.write('{}')
        fd.close()
        fd.user_info = {}
    else:
        fd = open(_user_file,'rb')
        content = fd.read()
        try:
            fd.user_info = json.loads(content)
        except ValueError:
            fd.user_info = {}
            logger.error("user_info file "+_user_file+ " does not appear"
                + " to conform to JSON format and could not be read.  Please"
                + " edit this file for future use.  In the interim, user_info"
                + " is being set to default values."
                )
    return fd

def _set_user_attr(fd, attr, value):
    fd = open(_user_file,'rb')
    content = fd.read()
    try:
        new_info = json.loads(content)
    except ValueError:
        new_info = {}
    fd = open(_user_file,'wb')
    return


text:
/* eslint-disable func-names, space-before-function-paren, no-var, space-before-blocks, prefer-rest-params, wrap-iife, no-unused-vars, one-var, indent, no-underscore-dangle, prefer-template, no-else-return, prefer-arrow-callback, radix, padded-blocks, max-len */
(function() {
  var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  this.ProjectNew = (function() {
    function ProjectNew() {
      this.toggleSettings = bind(this.toggleSettings, this);
      this.$selects = $('.features select');
      this.$repoSelects = this.$selects.filter('.js-repo-select');

      $('.project-edit-container').on('ajax:before', (function(_this) {
        return function() {
          $('.project-edit-container').hide();
          return $('.save-project-loader').show();
        };
      })(this));
      this.toggleSettings();
      this.toggleSettingsOnclick();
      this.toggleRepoVisibility();
    }

    ProjectNew.prototype.toggleSettings = function() {
      var self = this;

      this.$selects.each(function () {
        var $select = $(this),
            className = $select.data('field').replace(/_/g, '-')
              .replace('access-level', 'feature');
        self._showOrHide($select, '.' + className);
      });
    };

    ProjectNew.prototype.toggleSettingsOnclick = function() {
      this.$selects.on('change', this.toggleSettings);
    };

    ProjectNew.prototype._showOrHide = function(checkElement, container) {
      var $container = $(container);

      if ($(checkElement).val() !== '0') {
        return $container.show();
      } else {
        return $container.hide();
      }
    };

    ProjectNew.prototype.toggleRepoVisibility = function () {
      var $repoAccessLevel = $('.js-repo-access-level select'),
          containerRegistry = document.querySelectorAll('.js-container-registry')[0],
          containerRegistryCheckbox = document.getElementById('project_container_registry_enabled');

      this.$repoSelects.find("option[value='" + $repoAccessLevel.val() + "']")
        .nextAll()
        .hide();

      $repoAccessLevel.off('change')
        .on('change', function () {
          var selectedVal = parseInt($repoAccessLevel.val());

          this.$repoSelects.each(function () {
            var $this = $(this),
                repoSelectVal = parseInt($this.val());

            $this.find('option').show();

            if (selectedVal < repoSelectVal) {
              $this.val(selectedVal);
            }

            $this.find("option[value='" + selectedVal + "']").nextAll().hide();
          });

          if (selectedVal) {
            this.$repoSelects.removeClass('disabled');

            if (containerRegistry) {
              containerRegistry.style.display = '';
            }
          } else {
            this.$repoSelects.addClass('disabled');

            if (containerRegistry) {
              containerRegistry.style.display = 'none';
              containerRegistryCheckbox.checked = false;
            }
          }
        }.bind(this));
    };

    return ProjectNew;

  })();

}).call(this);


text:
package com.lachesis.mnis.web.task.notify.json;

import com.lachesis.mnis.core.inspection.entity.InspectionRecord;
import com.lachesis.mnis.core.patient.entity.Patient;

public class InspectionJson extends BaseJson{

	private String subject;

	public InspectionJson(){}

	public InspectionJson(String bedCode, String patientName, String patientId, String subject) {
		super(bedCode, patientName, patientId);
		this.subject = subject;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public static String createJson(InspectionRecord record, Patient patient) {
		return new InspectionJson(
				patient.getBedCode(),
				patient.getName(),
				patient.getPatId(),
				record.getSubject()).toJson();
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

    <link rel="icon" type="image/png" href="../favicon.png" sizes="32x32" />

    <meta name="theme-color" content="#4CAF50">
    <title>BuildRadiator.org</title>

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />

            BuildRadiator.org

            Build Radiators as a Service - a private and free build radiator for your team. This is for teams with no
            radiator up on a wall, and plenty of real reasons why Infosec will not let them put one up. There are many much more
                sophisticated "Information Radiators" available, but teams can use this one to get to green first, AND STAY THERE.

            Build Radiator Demo (non updatable)

            Getting Started

Key Features

🛂 Designed for guest Wifi

Put the radiator in your office's "guest" WiFi network so that the screen doesn't have to be logged in, and
                it will not have to adhere to the screen saver policy.
                Read more.

⛔ TCP/IP address restrictions

if you want you can restrict to only certain TCP/IP addresses to be allowed to view and
                update your radiator. See Restricting view & update TCP/IP addresses.

📺 Works on consumer TVs

Some low-end ($180) "Smart" TVs have a functional browser and
                WiFi capability, and buildradiator.org works just fine on them. See Consumer Displays.

🎲 Your radiator will be mounted on a random URL

The JSON for your radiator is mounted ion a random 20-digit URL. The demo radiator has a random directory
                of ueeusvcipmtsb755uq (90 bits turned into lower case or numeric) which is strong enough protection.

㊙ The server only keeps cryptic references for your project

On the server-side your steps can be '1', '2', '3' (etc) if you want and expand them to longer
                step names entirely on the client side. The title similarly is set on the client side.

🚧 Integrations for build technologies

So far there is an extension for Java's Maven build technology, allowing it to publish to buildradiator.org.

Other features including...

You don't need a "login" for this service to use it

The radiator only shows the last ten builds

Width of each step in the radiator is proportional to average duration for that step

Privacy Policy

The tiny amount of info held on the server is not shared with anyone. Not for money, not for free. Nobody would want it
            anyway - it is terribly boring. Here is the demo radiator's JSON .

The Paradox of Build Radiators

Teams that have a consistently 'red' (failing) build should put a build raditor up on the wall to the exclusion
            of all else, but may not do so if managers and execs walking past may realize that they are not collectively
            as capable as was previously believed. Teams that have a consistently 'green' (passing) builds mere minutes
            apart, probably could use the screen on the wall for something else as they no longer need to use it to improve.

Contribute

The 'buildradiator' project is on GitHub (open source) - github.com/BuildRadiator/BuildRadiator - and contributions are welcome via the usual pull-request mechanism. Integrations with build technologies CI tools/services are also sought.

© 2017 Paul Hammant and friends.


text:
package org.yoking.pattern.singleton;

/**
 * Singleton class with single check.
 *
 * @author YY
 */
public class S1 {
	private static S1 INSTANCE = null;

	private S1() {

	}

	public static final S1 getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new S1();
		}
		return INSTANCE;
	}

}


text:
<!DOCTYPE HTML>

<title>Uses of Class com.easypost.model.PaymentMethodObject (com.easypost:easypost-api-client 5.10.0 API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-11-03">
<meta name="description" content="use: package: com.easypost.model, class: PaymentMethodObject">
<meta name="generator" content="javadoc/ClassUseWriter">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Uses of Class
com.easypost.model.PaymentMethodObject

Packages that use PaymentMethodObject

Package

Description

com.easypost.model

Classes for the EasyPost API.

Uses of PaymentMethodObject in com.easypost.model

Methods in com.easypost.model that return PaymentMethodObject

Modifier and Type

Method

Description

static PaymentMethodObject

ReferralCustomer.addCreditCardToUser(String referralApiKey,
 String number,
 int expirationMonth,
 int expirationYear,
 String cvc)

Add credit card to a referral user.

static PaymentMethodObject

ReferralCustomer.addCreditCardToUser(String referralApiKey,
 String number,
 int expirationMonth,
 int expirationYear,
 String cvc,
 PaymentMethod.Priority priority)

Add credit card to a referral user.

PaymentMethodObject

PaymentMethod.getPrimaryPaymentMethodObject()

Get the primary payment method of this PaymentMethod object.

PaymentMethodObject

PaymentMethod.getSecondaryPaymentMethodObject()

Get the secondary payment method of this PaymentMethod object.

Copyright © 2022 EasyPost. All rights reserved.


text:
namespace v8 {
namespace internal {

enum TypeofState { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };

class StringCharLoadGenerator : public AllStatic {
 public:
  // Generates the code for handling different string types and loading the
  // indexed character into |result|.  We expect |index| as untagged input and
  // |result| as untagged output.
  static void Generate(MacroAssembler* masm,
                       Register string,
                       Register index,
                       Register result,
                       Label* call_runtime);

 private:
  DISALLOW_COPY_AND_ASSIGN(StringCharLoadGenerator);
};

class MathExpGenerator : public AllStatic {
 public:
  static void EmitMathExp(MacroAssembler* masm,
                          XMMRegister input,
                          XMMRegister result,
                          XMMRegister double_scratch,
                          Register temp1,
                          Register temp2);

 private:
  DISALLOW_COPY_AND_ASSIGN(MathExpGenerator);
};

enum StackArgumentsAccessorReceiverMode {
  ARGUMENTS_CONTAIN_RECEIVER,
  ARGUMENTS_DONT_CONTAIN_RECEIVER
};

class StackArgumentsAccessor BASE_EMBEDDED {
 public:
  StackArgumentsAccessor(
      Register base_reg,
      int argument_count_immediate,
      StackArgumentsAccessorReceiverMode receiver_mode =
          ARGUMENTS_CONTAIN_RECEIVER,
      int extra_displacement_to_last_argument = 0)
      : base_reg_(base_reg),
        argument_count_reg_(no_reg),
        argument_count_immediate_(argument_count_immediate),
        receiver_mode_(receiver_mode),
        extra_displacement_to_last_argument_(
            extra_displacement_to_last_argument) { }

  StackArgumentsAccessor(
      Register base_reg,
      Register argument_count_reg,
      StackArgumentsAccessorReceiverMode receiver_mode =
          ARGUMENTS_CONTAIN_RECEIVER,
      int extra_displacement_to_last_argument = 0)
      : base_reg_(base_reg),
        argument_count_reg_(argument_count_reg),
        argument_count_immediate_(0),
        receiver_mode_(receiver_mode),
        extra_displacement_to_last_argument_(
            extra_displacement_to_last_argument) { }

  StackArgumentsAccessor(
      Register base_reg,
      const ParameterCount& parameter_count,
      StackArgumentsAccessorReceiverMode receiver_mode =
          ARGUMENTS_CONTAIN_RECEIVER,
      int extra_displacement_to_last_argument = 0)
      : base_reg_(base_reg),
        argument_count_reg_(parameter_count.is_reg() ?
                            parameter_count.reg() : no_reg),
        argument_count_immediate_(parameter_count.is_immediate() ?
                                  parameter_count.immediate() : 0),
        receiver_mode_(receiver_mode),
        extra_displacement_to_last_argument_(
            extra_displacement_to_last_argument) { }

  Operand GetArgumentOperand(int index);
  Operand GetReceiverOperand() {
    ASSERT(receiver_mode_ == ARGUMENTS_CONTAIN_RECEIVER);
    return GetArgumentOperand(0);
  }

 private:
  const Register base_reg_;
  const Register argument_count_reg_;
  const int argument_count_immediate_;
  const StackArgumentsAccessorReceiverMode receiver_mode_;
  const int extra_displacement_to_last_argument_;

  DISALLOW_IMPLICIT_CONSTRUCTORS(StackArgumentsAccessor);
};

} }  // namespace v8::internal

#endif  // V8_X64_CODEGEN_X64_H_


text:
<?php

namespace Acme\ModelBundle\UsersRepository;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;

class UsersRepository extends EntityRepository implements UserProviderInterface
{
    /**
     * @param string $username
     *
     * @return mixed
     *
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function loadUserByUsername($username)
    {
        $q = $this
            ->createQueryBuilder('u')
            ->where('u.username = :username OR u.email = :email')
            ->setParameter('username', $username)
            ->setParameter('email', $username)
            ->getQuery()
        ;

        try {
            // The Query::getSingleResult() method throws an exception
            // if there is no record matching the criteria.
            $user = $q->getSingleResult();
        } catch (NoResultException $e) {
            throw new UsernameNotFoundException(sprintf('Unable to find an active admin AcmeUserBundle:User object identified by "%s".', $username), null, 0, $e);
        }

        return $user;
    }

    /**
     * @param UserInterface $user
     *
     * @return mixed
     */
    public function refreshUser(UserInterface $user)
    {
        $class = get_class($user);
        if (!$this->supportsClass($class)) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $class));
        }

        return $this->loadUserByUsername($user->getUsername());
    }

    /**
     * @param string $class
     *
     * @return bool
     */
    public function supportsClass($class)
    {
        return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName());
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using JobMatcher.Models;
using JobMatcher.Service.Mapping;

namespace JobMatcher.Service.ViewModels
{
    public class RecruiterProfileViewModel : IMapFrom<RecruiterProfile>, IHaveCustomMappings
    {
        public int RecruiterProfileId { get; set; }

        public string Username { get; set; }

        public string Email { get; set; }

        public ProfileType ProfileType { get; set; }

        public virtual ICollection<JobOfferViewModel> JobOffers { get; set; }

        public virtual ICollection<JobSeekerProfileViewModel> MatchedJobSeekers { get; set; }

        public virtual ICollection<Match> Matches { get; set; }

        public virtual ICollection<MessageViewModel> Messages { get; set; }

        public void CreateMappings(AutoMapper.IConfiguration configuration)
        {
            configuration.CreateMap<RecruiterProfile, RecruiterProfileViewModel>()
                .ForMember(m => m.Username, opt => opt.MapFrom(x => x.User.UserName))
                .ForMember(m => m.Email, opt => opt.MapFrom(x => x.User.Email))
                .ForMember(m => m.ProfileType, opt => opt.MapFrom(x => x.User.ProfileType))
                .ReverseMap();
        }
    }
}


text:
package lib

import com.bryzek.apidoc.api.v0.models.{Original, OriginalForm, OriginalType}
import org.scalatest.{FunSpec, ShouldMatchers}

class OriginalUtilSpec extends FunSpec with ShouldMatchers {

  it("original") {
    val data = TestHelper.readFile("../spec/apidoc-api.json")
    OriginalUtil.toOriginal(OriginalForm(data = data)) should be(
      Original(
        OriginalType.ApiJson,
        data
      )
    )
  }

  describe("guessType") {

    it("apiJson") {
      OriginalUtil.guessType(TestHelper.readFile("../spec/apidoc-api.json")) should be(Some(OriginalType.ApiJson))
      OriginalUtil.guessType(TestHelper.readFile("../spec/apidoc-spec.json")) should be(Some(OriginalType.ApiJson))
    }

    it("serviceJson") {
      OriginalUtil.guessType(TestHelper.readFile("../core/src/test/resources/apidoc-service.json")) should be(Some(OriginalType.ServiceJson))
    }

    it("swaggerJson") {
      OriginalUtil.guessType(TestHelper.readFile("../swagger/src/test/resources/petstore-with-external-docs.json")) should be(Some(OriginalType.SwaggerJson))
    }

    it("avroIdl") {
      OriginalUtil.guessType("  @namespace  ") should be(Some(OriginalType.AvroIdl))
      OriginalUtil.guessType("  protocol bar {}  ") should be(Some(OriginalType.AvroIdl))
    }

    it("unknown") {
      OriginalUtil.guessType("   ") should be(None)
    }

    it("poorly formatted json") {
      OriginalUtil.guessType("{   ") should be(None)
    }

  }

}


text:
package com.futureplatforms.kirin.state;

public interface IKirinDropbox {
    String put(String tokenPrefix, Object obj);
    Object get(String token);
    void remove(String token);

    Object consume(String token);
}


text:
import {INITIAL_STATE, setNextMemberType, enableVRMode, disableVRMode} from '../core'

export default function avatarHandler(state = INITIAL_STATE, action) {
  switch(action.type) {
    case 'NEXT_MEMBER_TYPE':
      return state.update('members', membersState => setNextMemberType(membersState, action.memberId))
    case 'ENABLE_VR_MODE':
      return enableVRMode(state)
    case 'DISABLE_VR_MODE':
      return disableVRMode(state)
  }
  return state
}


text:
@interface VZInspectorDeviceView ()

@property (nonatomic, strong) UITextView* textView;
@property (nonatomic, strong) UIButton *backBtn;

@end

@implementation VZInspectorDeviceView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        self.backgroundColor = [UIColor clearColor];

        _textView = [[UITextView alloc]initWithFrame:CGRectMake(10, 44, CGRectGetWidth(frame)-20, CGRectGetHeight(frame)-20)];
        _textView.font = [UIFont fontWithName:@"Courier-Bold" size:15];
        _textView.textColor = [UIColor orangeColor];
        _textView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6f];
        _textView.indicatorStyle = 0;
        _textView.editable = NO;
        _textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _textView.layer.borderColor = [UIColor colorWithWhite:0.5f alpha:1.0f].CGColor;
        _textView.layer.borderWidth = 2.0f;
        _textView.text = [[VZDevice infoArray] componentsJoinedByString:@"\n"];
        [self addSubview:_textView];

        _backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 0, 44, 44)];
        _backBtn.backgroundColor = [UIColor clearColor];
        [_backBtn setTitle:@"<-" forState:UIControlStateNormal];
        [_backBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        _backBtn.titleLabel.font = [UIFont systemFontOfSize:18.0f];
        [_backBtn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_backBtn];

    }
    return self;
}

- (void)pop
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    [self.parentViewController performSelector:@selector(onBack)];
#pragma clang diagnostic pop
}

@end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.apimanagement.models;

import com.azure.core.annotation.Fluent;
import com.azure.resourcemanager.apimanagement.fluent.models.SubscriptionCreateParameterProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Subscription create details. */
@Fluent
public final class SubscriptionCreateParameters {
    /*
     * Subscription contract properties.
     */
    @JsonProperty(value = "properties")
    private SubscriptionCreateParameterProperties innerProperties;

    /**
     * Get the innerProperties property: Subscription contract properties.
     *
     * @return the innerProperties value.
     */
    private SubscriptionCreateParameterProperties innerProperties() {
        return this.innerProperties;
    }

    /**
     * Get the ownerId property: User (user id path) for whom subscription is being created in form /users/{userId}.
     *
     * @return the ownerId value.
     */
    public String ownerId() {
        return this.innerProperties() == null ? null : this.innerProperties().ownerId();
    }

    /**
     * Set the ownerId property: User (user id path) for whom subscription is being created in form /users/{userId}.
     *
     * @param ownerId the ownerId value to set.
     * @return the SubscriptionCreateParameters object itself.
     */
    public SubscriptionCreateParameters withOwnerId(String ownerId) {
        if (this.innerProperties() == null) {
            this.innerProperties = new SubscriptionCreateParameterProperties();
        }
        this.innerProperties().withOwnerId(ownerId);
        return this;
    }

    /**
     * Get the scope property: Scope like /products/{productId} or /apis or /apis/{apiId}.
     *
     * @return the scope value.
     */
    public String scope() {
        return this.innerProperties() == null ? null : this.innerProperties().scope();
    }

    /**
     * Set the scope property: Scope like /products/{productId} or /apis or /apis/{apiId}.
     *
     * @param scope the scope value to set.
     * @return the SubscriptionCreateParameters object itself.
     */
    public SubscriptionCreateParameters withScope(String scope) {
        if (this.innerProperties() == null) {
            this.innerProperties = new SubscriptionCreateParameterProperties();
        }
        this.innerProperties().withScope(scope);
        return this;
    }

    /**
     * Get the displayName property: Subscription name.
     *
     * @return the displayName value.
     */
    public String displayName() {
        return this.innerProperties() == null ? null : this.innerProperties().displayName();
    }

    /**
     * Set the displayName property: Subscription name.
     *
     * @param displayName the displayName value to set.
     * @return the SubscriptionCreateParameters object itself.
     */
    public SubscriptionCreateParameters withDisplayName(String displayName) {
        if (this.innerProperties() == null) {
            this.innerProperties = new SubscriptionCreateParameterProperties();
        }
        this.innerProperties().withDisplayName(displayName);
        return this;
    }

    /**
     * Get the primaryKey property: Primary subscription key. If not specified during request key will be generated
     * automatically.
     *
     * @return the primaryKey value.
     */
    public String primaryKey() {
        return this.innerProperties() == null ? null : this.innerProperties().primaryKey();
    }

    /**
     * Set the primaryKey property: Primary subscription key. If not specified during request key will be generated
     * automatically.
     *
     * @param primaryKey the primaryKey value to set.
     * @return the SubscriptionCreateParameters object itself.
     */
    public SubscriptionCreateParameters withPrimaryKey(String primaryKey) {
        if (this.innerProperties() == null) {
            this.innerProperties = new SubscriptionCreateParameterProperties();
        }
        this.innerProperties().withPrimaryKey(primaryKey);
        return this;
    }

    /**
     * Get the secondaryKey property: Secondary subscription key. If not specified during request key will be generated
     * automatically.
     *
     * @return the secondaryKey value.
     */
    public String secondaryKey() {
        return this.innerProperties() == null ? null : this.innerProperties().secondaryKey();
    }

    /**
     * Set the secondaryKey property: Secondary subscription key. If not specified during request key will be generated
     * automatically.
     *
     * @param secondaryKey the secondaryKey value to set.
     * @return the SubscriptionCreateParameters object itself.
     */
    public SubscriptionCreateParameters withSecondaryKey(String secondaryKey) {
        if (this.innerProperties() == null) {
            this.innerProperties = new SubscriptionCreateParameterProperties();
        }
        this.innerProperties().withSecondaryKey(secondaryKey);
        return this;
    }

    /**
     * Get the state property: Initial subscription state. If no value is specified, subscription is created with
     * Submitted state. Possible states are * active – the subscription is active, * suspended – the subscription is
     * blocked, and the subscriber cannot call any APIs of the product, * submitted – the subscription request has been
     * made by the developer, but has not yet been approved or rejected, * rejected – the subscription request has been
     * denied by an administrator, * cancelled – the subscription has been cancelled by the developer or administrator,
     * * expired – the subscription reached its expiration date and was deactivated.
     *
     * @return the state value.
     */
    public SubscriptionState state() {
        return this.innerProperties() == null ? null : this.innerProperties().state();
    }

    /**
     * Set the state property: Initial subscription state. If no value is specified, subscription is created with
     * Submitted state. Possible states are * active – the subscription is active, * suspended – the subscription is
     * blocked, and the subscriber cannot call any APIs of the product, * submitted – the subscription request has been
     * made by the developer, but has not yet been approved or rejected, * rejected – the subscription request has been
     * denied by an administrator, * cancelled – the subscription has been cancelled by the developer or administrator,
     * * expired – the subscription reached its expiration date and was deactivated.
     *
     * @param state the state value to set.
     * @return the SubscriptionCreateParameters object itself.
     */
    public SubscriptionCreateParameters withState(SubscriptionState state) {
        if (this.innerProperties() == null) {
            this.innerProperties = new SubscriptionCreateParameterProperties();
        }
        this.innerProperties().withState(state);
        return this;
    }

    /**
     * Get the allowTracing property: Determines whether tracing can be enabled.
     *
     * @return the allowTracing value.
     */
    public Boolean allowTracing() {
        return this.innerProperties() == null ? null : this.innerProperties().allowTracing();
    }

    /**
     * Set the allowTracing property: Determines whether tracing can be enabled.
     *
     * @param allowTracing the allowTracing value to set.
     * @return the SubscriptionCreateParameters object itself.
     */
    public SubscriptionCreateParameters withAllowTracing(Boolean allowTracing) {
        if (this.innerProperties() == null) {
            this.innerProperties = new SubscriptionCreateParameterProperties();
        }
        this.innerProperties().withAllowTracing(allowTracing);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (innerProperties() != null) {
            innerProperties().validate();
        }
    }
}


text:
package java.lang.ref;

/**
 * This class must be implemented by the vm vendor. The documented methods must
 * be implemented to support the provided subclass implementations. As the
 * provided subclass implementations are trivial and simply call
 * initReference(Object) and initReference(Object, ReferenceQueue) from their
 * constructors, the vm vendor may elect to implement the subclasses as well.
 * Abstract class which describes behavior common to all reference objects.
 *
 * @since JDK1.2
 */
public abstract class Reference<T> extends Object {

    T referent;
    ReferenceQueue<T> queue;
    private static ReferenceQueue dummy = new ReferenceQueue();

	/**
	 * Make the referent null. This does not force the reference object to be
	 * enqueued.
	 *
	 */
	public void clear() {
        referent = null;
		return;
	}

	/**
	 * Force the reference object to be enqueued if it has been associated with
	 * a queue.
	 *
	 * @return boolean true if Reference is enqueued. false otherwise.
	 */
	public boolean enqueue() {
        ReferenceQueue<T> q;
        synchronized (this) {
            if (queue == null || queue == dummy) return false;
            q = queue;
            queue = null;
        }

        try {
            q.enqueue(this);
            return true;
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return false;
	}

	/**
	 * Return the referent of the reference object.
	 *
	 * @return Object Referent to which reference refers, or null if object has
	 *         been cleared.
	 */
	public T get() {
		return referent;
	}

	/**
	 * Return whether the reference object has been enqueued.
	 *
	 * @return boolean true if Reference has been enqueued. false otherwise.
	 */
	public boolean isEnqueued() {
		return queue == null;
	}

	/**
	 * Constructs a new instance of this class.
	 *
	 */
	Reference() {
		super();
	}

	/**
	 * Implement this method to support the provided subclass implementations.
	 * Initialize a newly created reference object. Associate the reference
	 * object with the referent.
	 *
	 * @param r
	 *            the referent
	 */
	void initReference(T r) {
        referent = r;
        queue = dummy;
		return;
	}

	/**
	 * Implement this method to support the provided subclass implementations.
	 * Initialize a newly created reference object. Associate the reference
	 * object with the referent, and the specified ReferenceQueue.
	 *
	 * @param r
	 *            the referent
	 * @param q
	 *            the ReferenceQueue
	 */
	void initReference(T r, ReferenceQueue<T> q) {
        referent = r;
        queue = q;
		return;
	}

	/**
	 * Called when a Reference has been removed from its ReferenceQueue.
	 * Set the enqueued field to false.
	 */
	void dequeue() {
		return;
	}
}


text:
'use strict';

(function() {

class MainController {

  constructor($http, $scope, socket) {
    this.$http = $http;
    this.socket = socket;
    this.awesomeThings = [];

    $scope.$on('$destroy', function() {
      socket.unsyncUpdates('thing');
    });
  }

  $onInit() {
    this.$http.get('/api/things').then(response => {
      this.awesomeThings = response.data;
      this.socket.syncUpdates('thing', this.awesomeThings);
    });
  }

  addThing() {
    if (this.newThing) {
      this.$http.post('/api/things', { name: this.newThing });
      this.newThing = '';
    }
  }

  deleteThing(thing) {
    this.$http.delete('/api/things/' + thing._id);
  }
}

angular.module('powerChessApp')
  .component('main', {
    templateUrl: 'app/main/main.html',
    controller: MainController
  });

})();


text:
from libqtile.config import Screen
from libqtile.bar import Bar
from libqtile.widget import TextBox

from .utils import Xephyr
from .test_manager import BareConfig

class ColorChanger(TextBox):
    count = 0
    def update(self, text):
        self.count += 1
        if self.count % 2 == 0:
            self.foreground = "ff0000"
        else:
            self.foreground = "0000ff"
        self.text = text

class WidgetTestConf(BareConfig):
    screens = [Screen(bottom=Bar([ColorChanger(name="colorchanger")], 20))]

@Xephyr(False, WidgetTestConf())
def test_textbox_color_change(self):
    self.c.widget["colorchanger"].update('f')
    print(self.c.widget["colorchanger"].info())
    assert self.c.widget["colorchanger"].info()["foreground"] == "0000ff"

    self.c.widget["colorchanger"].update('f')
    assert self.c.widget["colorchanger"].info()["foreground"] == "ff0000"


text:
var elem;
var name_elem;
var btn;

function handleBtnClick(e) {

  var name = name_elem.value;

  e.preventDefault();

  return greet(name).
    then(function(greeting) {
      elem.innerHTML = greeting;
    });
}

function init() {
  elem = document.querySelector("#target");
  name_elem = document.querySelector("#name");
  btn = document.querySelector("#greet-btn");

  btn.addEventListener('click', handleBtnClick);
}


text:
package state

type Crashed struct {
	*StateMachine
}

func (s Crashed) Transition(action int, rev int64) State {
	return Stopped{s.StateMachine}.Transition(action, rev)
}

func (s Crashed) String() string {
	return "CRASHED"
}


text:
package com.rim.samples.device.communicationapidemo.view;

import java.util.Vector;

import net.rim.device.api.io.messaging.Message;
import net.rim.device.api.io.messaging.MessageProcessorException;
import net.rim.device.api.io.parser.rss.RSSMessageProcessor;
import net.rim.device.api.io.parser.rss.model.RSSChannel;
import net.rim.device.api.io.parser.rss.model.RSSItem;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.TreeField;
import net.rim.device.api.ui.component.TreeFieldCallback;
import net.rim.device.api.ui.container.MainScreen;

import com.rim.samples.device.communicationapidemo.CommunicationController;
import com.rim.samples.device.communicationapidemo.ResponseCallback;
import com.rim.samples.device.communicationapidemo.ui.FullWidthButton;

public final class SendNonBlockRssScreen extends MainScreen {
    private static final int MAX_ITEMS = 5;

    private final TreeField _treeField;
    private final EditField _uriSenderField;
    private final ResponseCallback _callback;
    private boolean _pending;

    /**
     * Creates a new SendNonBlockRssScreen object
     */
    public SendNonBlockRssScreen(final CommunicationController controller) {
        setTitle("RSS");

        _callback = new SendNonBlockRssScreenCallback(this);

        _uriSenderField =
                new EditField("URI:", CommunicationController.ECHO_SERVER_URI
                        + "RSS", 140, 0);
        final FullWidthButton postButton = new FullWidthButton("Get Data");
        postButton.setChangeListener(new FieldChangeListener() {
            /**
             * @see FieldChangeListener#fieldChanged(Field, int)
             */
            public void fieldChanged(final Field field, final int context) {
                if (!_pending) {
                    _pending = true;
                    clearTree("* No RSS Message *");
                    controller.sendNonBlocking(_uriSenderField.getText(), true,
                            _callback);
                } else {
                    Dialog.alert("Previous request pending state...");
                }
            }
        });

        _treeField = new TreeField(new MyTreeFieldCallback(), Field.FOCUSABLE);
        _treeField.setDefaultExpanded(false);
        clearTree("* No RSS Message *");

        add(_uriSenderField);
        add(postButton);
        add(_treeField);

    }

    private void updateTree(final Message message) {
        if (process(message)) {
            displayRSSTree(message);
        } else {
            clearTree("* No RSS Message *");
        }
    }

    private boolean process(final Message message) {
        final RSSMessageProcessor rssMP = new RSSMessageProcessor(MAX_ITEMS);

        try {
            if (message != null) {
                rssMP.process(message);
            }
        } catch (final MessageProcessorException mpe) {
            Dialog.alert(mpe.toString());
            return false;
        }

        return true;
    }

    private void displayRSSTree(final Message message) {
        final int parentNode = 0;
        int childNode;
        RSSChannel channel;
        RSSItem item;
        Vector items;

        _treeField.deleteAll();

        final Object obj = message.getObjectPayload();

        if (obj instanceof RSSChannel) {
            channel = (RSSChannel) obj;

            items = channel.getRSSItems();

            for (int i = 0; i < items.size(); ++i) {
                item = (RSSItem) items.elementAt(i);
                final String key = item.getTitle();
                final String val = item.getDescription();
                childNode = _treeField.addChildNode(parentNode, key);
                _treeField.addChildNode(childNode, val);
            }
        }
    }

    private void clearTree(final String statusString) {
        _treeField.deleteAll();
        _treeField.setEmptyString(statusString, 0);
    }

    /**
     * @see MainScreen#onSavePrompt()
     */
    public boolean onSavePrompt() {
        // Suppress the save dialog
        return true;
    }

    private final class MyTreeFieldCallback implements TreeFieldCallback {
        /**
         * @see TreeFieldCallback#drawTreeItem(TreeField, Graphics, int, int,
         *      int, int)
         */
        public void drawTreeItem(final TreeField treeField,
                final Graphics graphics, final int node, final int y,
                final int width, final int indent) {
            if (treeField == _treeField) {
                final Object cookie = _treeField.getCookie(node);
                if (cookie instanceof String) {
                    final String text = (String) cookie;
                    graphics.drawText(text, indent, y, DrawStyle.ELLIPSIS,
                            width);
                }
            }
        }
    }

    private static final class SendNonBlockRssScreenCallback extends
            ResponseCallback {

        private final SendNonBlockRssScreen _screen;

        private SendNonBlockRssScreenCallback(final SendNonBlockRssScreen screen) {
            _screen = screen;
        }

        public void onResponse(final Message message) {
            if (message != null) {
                _screen.updateTree(message);
            }
            _screen._pending = false;
        }

        public void onTimeout(final int timeout) {
            _screen._pending = false;
            final String timeoutMessage =
                    "Wait for response: timed out after " + timeout + " sec";
            Dialog.alert(timeoutMessage);
        }
    }
}


text:
package com.porterhead.rest.user.api;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @version 1.0
 * @author: Iain Porter iain.porter@porterhead.com
 * @since 28/09/2012
 */
@XmlRootElement
public class PasswordRequest {

    @Length(min=8, max=30)
    @NotNull
    private String password;

    public PasswordRequest() {}

    public PasswordRequest(final String password) {
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}


text:
export GOPATH=$HOME/go
go get github.com/mesosphere/mesos-dns
cd $GOPATH/src/github.com/mesosphere/mesos-dns
go build .


text:
const logger = require('../lib/logger')

logger.info('Starting server...')
require('../../server/main').listen(3003, () => {
  logger.success('Server is running at http://localhost:3003')
})


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

/**
 * Interface combining {@link ObjectReader} and {@link ObjectWriter}
 *
 * @param <T> Type of the mapped object
 * @author Nicolas Morel
 * @version $Id: $
 */
public interface ObjectMapper<T> extends ObjectReader<T>, ObjectWriter<T> {}


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/pages.xsd">
    <page name="Install" mca="install/" module="Mage_Install">
        <block name="licenseBlock" class="Mage\Install\Test\Block\License" locator="body" strategy="css selector" />
        <block name="continueBlock" class="Mage\Install\Test\Block\ContinueBlock" locator=".button-set" strategy="css selector" />
    </page>
</config>