text:
// +build cgo

package pkcs11

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"hash"
	"net/url"
	"os"
	"strconv"
	"strings"

	"github.com/miekg/pkcs11"
	"github.com/pkg/errors"
	pkcs11uri "github.com/stefanberger/go-pkcs11uri"
)

var (
	// OAEPLabel defines the label we use for OAEP encryption; this cannot be changed
	OAEPLabel = []byte("")
	// OAEPDefaultHash defines the default hash used for OAEP encryption; this cannot be changed
	OAEPDefaultHash = "sha1"

	// OAEPSha1Params describes the OAEP parameters with sha1 hash algorithm; needed by SoftHSM
	OAEPSha1Params = &pkcs11.OAEPParams{
		HashAlg:    pkcs11.CKM_SHA_1,
		MGF:        pkcs11.CKG_MGF1_SHA1,
		SourceType: pkcs11.CKZ_DATA_SPECIFIED,
		SourceData: OAEPLabel,
	}
	// OAEPSha256Params describes the OAEP parameters with sha256 hash algorithm
	OAEPSha256Params = &pkcs11.OAEPParams{
		HashAlg:    pkcs11.CKM_SHA256,
		MGF:        pkcs11.CKG_MGF1_SHA256,
		SourceType: pkcs11.CKZ_DATA_SPECIFIED,
		SourceData: OAEPLabel,
	}
)

// rsaPublicEncryptOAEP encrypts the given plaintext with the given *rsa.PublicKey; the
// environment variable OCICRYPT_OAEP_HASHALG can be set to 'sha1' to force usage of sha1 for OAEP (SoftHSM).
// This function is needed by clients who are using a public key file for pkcs11 encryption
func rsaPublicEncryptOAEP(pubKey *rsa.PublicKey, plaintext []byte) ([]byte, string, error) {
	var (
		hashfunc hash.Hash
		hashalg  string
	)

	oaephash := os.Getenv("OCICRYPT_OAEP_HASHALG")
	// The default is 'sha1'
	switch strings.ToLower(oaephash) {
	case "sha1", "":
		hashfunc = sha1.New()
		hashalg = "sha1"
	case "sha256":
		hashfunc = sha256.New()
		hashalg = "sha256"
	default:
		return nil, "", errors.Errorf("Unsupported OAEP hash '%s'", oaephash)
	}
	ciphertext, err := rsa.EncryptOAEP(hashfunc, rand.Reader, pubKey, plaintext, OAEPLabel)
	if err != nil {
		return nil, "", errors.Wrapf(err, "rss.EncryptOAEP failed")
	}

	return ciphertext, hashalg, nil
}

// pkcs11UriGetLoginParameters gets the parameters necessary for login from the Pkcs11URI
// PIN and module are mandatory; slot-id is optional and if not found -1 will be returned
// For a privateKeyOperation a PIN is required and if none is given, this function will return an error
func pkcs11UriGetLoginParameters(p11uri *pkcs11uri.Pkcs11URI, privateKeyOperation bool) (string, string, int64, error) {
	var (
		pin string
		err error
	)
	if privateKeyOperation {
		if !p11uri.HasPIN() {
			return "", "", 0, errors.New("Missing PIN for private key operation")
		}
	}
	// some devices require a PIN to find a *public* key object, others don't
	pin, _ = p11uri.GetPIN()

	module, err := p11uri.GetModule()
	if err != nil {
		return "", "", 0, errors.Wrap(err, "No module available in pkcs11 URI")
	}

	slotid := int64(-1)

	slot, ok := p11uri.GetPathAttribute("slot-id", false)
	if ok {
		slotid, err = strconv.ParseInt(slot, 10, 64)
		if err != nil {
			return "", "", 0, errors.Wrap(err, "slot-id is not a valid number")
		}
		if slotid < 0 {
			return "", "", 0, fmt.Errorf("slot-id is a negative number")
		}
		if uint64(slotid) > 0xffffffff {
			return "", "", 0, fmt.Errorf("slot-id is larger than 32 bit")
		}
	}

	return pin, module, slotid, nil
}

// pkcs11UriGetKeyIdAndLabel gets the key label by retrieving the value of the 'object' attribute
func pkcs11UriGetKeyIdAndLabel(p11uri *pkcs11uri.Pkcs11URI) (string, string, error) {
	keyid, ok2 := p11uri.GetPathAttribute("id", false)
	label, ok1 := p11uri.GetPathAttribute("object", false)
	if !ok1 && !ok2 {
		return "", "", errors.New("Neither 'id' nor 'object' attributes were found in pkcs11 URI")
	}
	return keyid, label, nil
}

// pkcs11OpenSession opens a session with a pkcs11 device at the given slot and logs in with the given PIN
func pkcs11OpenSession(p11ctx *pkcs11.Ctx, slotid uint, pin string) (session pkcs11.SessionHandle, err error) {
	session, err = p11ctx.OpenSession(uint(slotid), pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION)
	if err != nil {
		return 0, errors.Wrapf(err, "OpenSession to slot %d failed", slotid)
	}
	if len(pin) > 0 {
		err = p11ctx.Login(session, pkcs11.CKU_USER, pin)
		if err != nil {
			_ = p11ctx.CloseSession(session)
			return 0, errors.Wrap(err, "Could not login to device")
		}
	}
	return session, nil
}

// pkcs11UriLogin uses the given pkcs11 URI to select the pkcs11 module (share libary) and to get
// the PIN to use for login; if the URI contains a slot-id, the given slot-id will be used, otherwise
// one slot after the other will be attempted and the first one where login succeeds will be used
func pkcs11UriLogin(p11uri *pkcs11uri.Pkcs11URI, privateKeyOperation bool) (ctx *pkcs11.Ctx, session pkcs11.SessionHandle, err error) {
	pin, module, slotid, err := pkcs11UriGetLoginParameters(p11uri, privateKeyOperation)
	if err != nil {
		return nil, 0, err
	}

	p11ctx := pkcs11.New(module)
	if p11ctx == nil {
		return nil, 0, errors.New("Please check module path, input is: " + module)
	}

	err = p11ctx.Initialize()
	if err != nil {
		p11Err := err.(pkcs11.Error)
		if p11Err != pkcs11.CKR_CRYPTOKI_ALREADY_INITIALIZED {
			return nil, 0, errors.Wrap(err, "Initialize failed")
		}
	}

	if slotid >= 0 {
		session, err := pkcs11OpenSession(p11ctx, uint(slotid), pin)
		return p11ctx, session, err
	} else {
		slots, err := p11ctx.GetSlotList(true)
		if err != nil {
			return nil, 0, errors.Wrap(err, "GetSlotList failed")
		}

		tokenlabel, ok := p11uri.GetPathAttribute("token", false)
		if !ok {
			return nil, 0, errors.New("Missing 'token' attribute since 'slot-id' was not given")
		}

		for _, slot := range slots {
			ti, err := p11ctx.GetTokenInfo(slot)
			if err != nil || ti.Label != tokenlabel {
				continue
			}

			session, err = pkcs11OpenSession(p11ctx, slot, pin)
			if err == nil {
				return p11ctx, session, err
			}
		}
		if len(pin) > 0 {
			return nil, 0, errors.New("Could not create session to any slot and/or log in")
		}
		return nil, 0, errors.New("Could not create session to any slot")
	}
}

func pkcs11Logout(ctx *pkcs11.Ctx, session pkcs11.SessionHandle) {
	_ = ctx.Logout(session)
	_ = ctx.CloseSession(session)
	_ = ctx.Finalize()
	ctx.Destroy()
}

// findObject finds an object of the given class with the given keyid and/or label
func findObject(p11ctx *pkcs11.Ctx, session pkcs11.SessionHandle, class uint, keyid, label string) (pkcs11.ObjectHandle, error) {
	msg := ""

	template := []*pkcs11.Attribute{
		pkcs11.NewAttribute(pkcs11.CKA_CLASS, class),
	}
	if len(label) > 0 {
		template = append(template, pkcs11.NewAttribute(pkcs11.CKA_LABEL, label))
		msg = fmt.Sprintf("label '%s'", label)
	}
	if len(keyid) > 0 {
		template = append(template, pkcs11.NewAttribute(pkcs11.CKA_ID, keyid))
		if len(msg) > 0 {
			msg += " and "
		}
		msg += url.PathEscape(keyid)
	}

	if err := p11ctx.FindObjectsInit(session, template); err != nil {
		return 0, errors.Wrap(err, "FindObjectsInit failed")
	}

	obj, _, err := p11ctx.FindObjects(session, 100)
	if err != nil {
		return 0, errors.Wrap(err, "FindObjects failed")
	}

	if err := p11ctx.FindObjectsFinal(session); err != nil {
		return 0, errors.Wrap(err, "FindObjectsFinal failed")
	}
	if len(obj) > 1 {
		return 0, errors.Errorf("There are too many (=%d) keys with %s", len(obj), msg)
	} else if len(obj) == 1 {
		return obj[0], nil
	}

	return 0, errors.Errorf("Could not find any object with %s", msg)
}

// publicEncryptOAEP uses a public key described by a pkcs11 URI to OAEP encrypt the given plaintext
func publicEncryptOAEP(pubKey *Pkcs11KeyFileObject, plaintext []byte) ([]byte, string, error) {
	oldenv, err := setEnvVars(pubKey.Uri.GetEnvMap())
	if err != nil {
		return nil, "", err
	}
	defer restoreEnv(oldenv)

	p11ctx, session, err := pkcs11UriLogin(pubKey.Uri, false)
	if err != nil {
		return nil, "", err
	}
	defer pkcs11Logout(p11ctx, session)

	keyid, label, err := pkcs11UriGetKeyIdAndLabel(pubKey.Uri)
	if err != nil {
		return nil, "", err
	}

	p11PubKey, err := findObject(p11ctx, session, pkcs11.CKO_PUBLIC_KEY, keyid, label)
	if err != nil {
		return nil, "", err
	}

	var hashalg string

	var oaep *pkcs11.OAEPParams
	oaephash := os.Getenv("OCICRYPT_OAEP_HASHALG")
	// the default is sha1
	switch strings.ToLower(oaephash) {
	case "sha1", "":
		oaep = OAEPSha1Params
		hashalg = "sha1"
	case "sha256":
		oaep = OAEPSha256Params
		hashalg = "sha256"
	default:
		return nil, "", errors.Errorf("Unsupported OAEP hash '%s'", oaephash)
	}

	err = p11ctx.EncryptInit(session, []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_OAEP, oaep)}, p11PubKey)
	if err != nil {
		return nil, "", errors.Wrap(err, "EncryptInit error")
	}

	ciphertext, err := p11ctx.Encrypt(session, plaintext)
	if err != nil {
		return nil, "", errors.Wrap(err, "Encrypt failed")
	}
	return ciphertext, hashalg, nil
}

// privateDecryptOAEP uses a pkcs11 URI describing a private key to OAEP decrypt a ciphertext
func privateDecryptOAEP(privKeyObj *Pkcs11KeyFileObject, ciphertext []byte, hashalg string) ([]byte, error) {
	oldenv, err := setEnvVars(privKeyObj.Uri.GetEnvMap())
	if err != nil {
		return nil, err
	}
	defer restoreEnv(oldenv)

	p11ctx, session, err := pkcs11UriLogin(privKeyObj.Uri, true)
	if err != nil {
		return nil, err
	}
	defer pkcs11Logout(p11ctx, session)

	keyid, label, err := pkcs11UriGetKeyIdAndLabel(privKeyObj.Uri)
	if err != nil {
		return nil, err
	}

	p11PrivKey, err := findObject(p11ctx, session, pkcs11.CKO_PRIVATE_KEY, keyid, label)
	if err != nil {
		return nil, err
	}

	var oaep *pkcs11.OAEPParams

	// the default is sha1
	switch hashalg {
	case "sha1", "":
		oaep = OAEPSha1Params
	case "sha256":
		oaep = OAEPSha256Params
	default:
		return nil, errors.Errorf("Unsupported hash algorithm '%s' for decryption", hashalg)
	}

	err = p11ctx.DecryptInit(session, []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS_OAEP, oaep)}, p11PrivKey)
	if err != nil {
		return nil, errors.Wrapf(err, "DecryptInit failed")
	}
	plaintext, err := p11ctx.Decrypt(session, ciphertext)
	if err != nil {
		return nil, errors.Wrapf(err, "Decrypt failed")
	}
	return plaintext, err
}

//
// The following part deals with the JSON formatted message for multiple pkcs11 recipients
//

// Pkcs11Blob holds the encrypted blobs for all recipients; this is what we will put into the image's annotations
type Pkcs11Blob struct {
	Version    uint              `json:"version"`
	Recipients []Pkcs11Recipient `json:"recipients"`
}

// Pkcs11Recipient holds the b64-encoded and encrypted blob for a particular recipient
type Pkcs11Recipient struct {
	Version uint   `json:"version"`
	Blob    string `json:"blob"`
	Hash    string `json:"hash,omitempty"`
}

// EncryptMultiple encrypts for one or multiple pkcs11 devices; the public keys passed to this function
// may either be *rsa.PublicKey or *pkcs11uri.Pkcs11URI; the returned byte array is a JSON string of the
// following format:
// {
//   recipients: [  // recipient list
//     {
//        "version": 0,
//        "blob": <base64 encoded RSA OAEP encrypted blob>,
//        "hash": <hash used for OAEP other than 'sha256'>
//     } ,
//     {
//        "version": 0,
//        "blob": <base64 encoded RSA OAEP encrypted blob>,
//        "hash": <hash used for OAEP other than 'sha256'>
//     } ,
//     [...]
//   ]
// }
func EncryptMultiple(pubKeys []interface{}, data []byte) ([]byte, error) {
	var (
		ciphertext []byte
		err        error
		pkcs11blob Pkcs11Blob = Pkcs11Blob{Version: 0}
		hashalg    string
	)

	for _, pubKey := range pubKeys {
		switch pkey := pubKey.(type) {
		case *rsa.PublicKey:
			ciphertext, hashalg, err = rsaPublicEncryptOAEP(pkey, data)
		case *Pkcs11KeyFileObject:
			ciphertext, hashalg, err = publicEncryptOAEP(pkey, data)
		default:
			err = errors.Errorf("Unsupported key object type for pkcs11 public key")
		}
		if err != nil {
			return nil, err
		}

		if hashalg == OAEPDefaultHash {
			hashalg = ""
		}
		recipient := Pkcs11Recipient{
			Version: 0,
			Blob:    base64.StdEncoding.EncodeToString(ciphertext),
			Hash:    hashalg,
		}

		pkcs11blob.Recipients = append(pkcs11blob.Recipients, recipient)
	}
	return json.Marshal(&pkcs11blob)
}

// Decrypt tries to decrypt one of the recipients' blobs using a pkcs11 private key.
// The input pkcs11blobstr is a string with the following format:
// {
//   recipients: [  // recipient list
//     {
//        "version": 0,
//        "blob": <base64 encoded RSA OAEP encrypted blob>,
//        "hash": <hash used for OAEP other than 'sha256'>
//     } ,
//     {
//        "version": 0,
//        "blob": <base64 encoded RSA OAEP encrypted blob>,
//        "hash": <hash used for OAEP other than 'sha256'>
//     } ,
//     [...]
// }
func Decrypt(privKeyObjs []*Pkcs11KeyFileObject, pkcs11blobstr []byte) ([]byte, error) {
	pkcs11blob := Pkcs11Blob{}
	err := json.Unmarshal(pkcs11blobstr, &pkcs11blob)
	if err != nil {
		return nil, errors.Wrapf(err, "Could not parse Pkcs11Blob")
	}
	switch pkcs11blob.Version {
	case 0:
		// latest supported version
	default:
		return nil, errors.Errorf("Found Pkcs11Blob with version %d but maximum supported version is 0.", pkcs11blob.Version)
	}
	// since we do trial and error, collect all encountered errors
	errs := ""

	for _, recipient := range pkcs11blob.Recipients {
		switch recipient.Version {
		case 0:
			// last supported version
		default:
			return nil, errors.Errorf("Found Pkcs11Recipient with version %d but maximum supported version is 0.", recipient.Version)
		}

		ciphertext, err := base64.StdEncoding.DecodeString(recipient.Blob)
		if err != nil || len(ciphertext) == 0 {
			// This should never happen... we skip over decoding issues
			errs += fmt.Sprintf("Base64 decoding failed: %s\n", err)
			continue
		}
		// try all keys until one works
		for _, privKeyObj := range privKeyObjs {
			plaintext, err := privateDecryptOAEP(privKeyObj, ciphertext, recipient.Hash)
			if err == nil {
				return plaintext, nil
			}
			if uri, err2 := privKeyObj.Uri.Format(); err2 == nil {
				errs += fmt.Sprintf("%s : %s\n", uri, err)
			} else {
				errs += fmt.Sprintf("%s\n", err)
			}
		}
	}

	return nil, errors.Errorf("Could not find a pkcs11 key for decryption:\n%s", errs)
}


text:
require 'greenhorn/craft/base_model'

module Greenhorn
  module Craft
    class Info < BaseModel
      class << self
        def table
          'info'
        end

        def value(key)
          first.send(key)
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
---
uid: SolidEdgeFramework.CommandBarControl
summary:
remarks: It provides a way to access most of the properties that are associated with either a CommandBarButton or a CommandBarPopup without having to specify an object type.
---


text:
@protocol CrUserNotification;
class Notification;
@class NotificationCenterDelegate;
class NotificationUIManagerImpl;
class PrefService;
class Profile;

// This class is an implementation of NotificationUIManager that will send
// text-only (non-HTML) notifications to Notification Center on 10.8. This
// class is only instantiated on 10.8 and above. For HTML notifications,
// this class uses an instance of NotificationUIManagerImpl to present
// notifications in the typical way.
class NotificationUIManagerMac : public NotificationUIManager {
 public:
  explicit NotificationUIManagerMac(PrefService* local_state);
  virtual ~NotificationUIManagerMac();

  // NotificationUIManager:
  virtual void Add(const Notification& notification,
                   Profile* profile) OVERRIDE;
  virtual bool CancelById(const std::string& notification_id) OVERRIDE;
  virtual bool CancelAllBySourceOrigin(const GURL& source_origin) OVERRIDE;
  virtual void CancelAll() OVERRIDE;
  virtual BalloonCollection* balloon_collection() OVERRIDE;
  virtual NotificationPrefsManager* prefs_manager() OVERRIDE;
  virtual void GetQueuedNotificationsForTesting(
      std::vector<const Notification*>* notifications) OVERRIDE;

  // Returns the corresponding C++ object for the Cocoa notification object,
  // or NULL if it could not be found.
  const Notification* FindNotificationWithCocoaNotification(
      id<CrUserNotification> notification) const;

  NotificationUIManagerImpl* builtin_manager() const {
    return builtin_manager_.get();
  }

 private:
  // A ControllerNotification links the Cocoa (view) notification to the C++
  // (model) notification. This assumes ownership (i.e. does not retain a_view)
  // of both objects and will delete them on destruction.
  struct ControllerNotification {
    ControllerNotification(id<CrUserNotification> a_view,
                           Notification* a_model);
    ~ControllerNotification();

    id<CrUserNotification> view;
    Notification* model;

   private:
    DISALLOW_COPY_AND_ASSIGN(ControllerNotification);
  };
  typedef std::map<std::string, ControllerNotification*> NotificationMap;

  // Erases a Cocoa notification from both the application and Notification
  // Center, and deletes the corresponding C++ object.
  bool RemoveNotification(id<CrUserNotification> notification);

  // Finds a notification with a given replacement id.
  id<CrUserNotification> FindNotificationWithReplacementId(
      const string16& replacement_id) const;

  // The class used to present HTML notifications that can't be sent to
  // Notification Center.
  scoped_ptr<NotificationUIManagerImpl> builtin_manager_;

  // Cocoa class that receives callbacks from the NSUserNotificationCenter.
  scoped_nsobject<NotificationCenterDelegate> delegate_;

  // Maps notification_ids to ControllerNotifications. The map owns the value,
  // so it must be deleted when remvoed from the map. This is typically handled
  // in RemoveNotification.
  NotificationMap notification_map_;

  DISALLOW_COPY_AND_ASSIGN(NotificationUIManagerMac);
};

#endif  // CHROME_BROWSER_NOTIFICATIONS_NOTIFICATION_UI_MANAGER_MAC_H_


text:
<?php

namespace Douche\Exception;

class UserNotFoundException extends Exception
{
    public $email;

    public function __construct($email)
    {
        parent::__construct();

        $this->email = $email;
    }
}


text:
<?php

class ConsumerManagementModel extends CI_Model {
    private $affected_id=0;
    private $error=array(
        'stat'=>'error',
        'msg'=>'Sorry, error has occurred.'
    );

    function __construct(){
        // Call the Model constructor
        parent::__construct();
        $this->load->database();
    }

    function ReturnConsumerList(){
        $rows=array();
        $sql="SELECT
				CONCAT_WS('|',
				      consumer_id,
                      contact_no,
                      email,
                      second_address,
                      meter_no,
                      house_no,
                      street_no,
                      barangay,
                      municipality,
                      zip_code,
                      province

                )AS     hidden,
                        consumer_name,
                CONCAT_WS(' ',
                      house_no,
                      street_no,
                      barangay,
                      municipality,
                      zip_code,
                      province

                )AS     address
			FROM customer_info
			WHERE is_deleted=0

			";
        $query = $this->db->query($sql);
        foreach ($query->result() as $row)
        {
            $rows[]=$row; //assign each row of query in array
        }

        return $rows;
    }

    function CreateConsumer(){
        try{
            //array of data to be inserted
            $this->db->trans_start(); //start transaction
            $data = array(
                'consumer_name' => $this->input->post('consumer_name',TRUE),
                'house_no'=>$this->input->post('house_no',TRUE),
                'street_no'=>$this->input->post('street',TRUE),
                'barangay'=>$this->input->post('barangay',TRUE),
                'municipality'=>$this->input->post('municipality',TRUE),
                'zip_code'=>$this->input->post('zipcode',TRUE),
                'province'=>$this->input->post('province',TRUE),
                'house_no'=>$this->input->post('house_no',TRUE),
                'contact_no'=>$this->input->post('contact_no',TRUE),
                'email'=>$this->input->post('email',TRUE),
                'second_address'=>$this->input->post('second_address',TRUE),
                'meter_no'=>$this->input->post('meter_no',TRUE),
            );

            $this->db->set('date_created', 'NOW()', FALSE);
            $this->db->insert('customer_info',$data) or die(json_encode($this->error));
            $this->affected_id=$this->db->insert_id();	//last insert id, the sales invoice	id

            $this->db->trans_complete(); //end transaction
            return true;

        }catch(Exception $e){
            die(json_encode($this->error));
        }
    }

    function UpdateConsumer(){
        try{
            //array of data to be inserted
            $this->db->trans_start(); //start transaction
            $consumer_id=$this->input->post('id',TRUE);

            $data = array(
                'consumer_name' => $this->input->post('consumer_name',TRUE),
                'house_no'=>$this->input->post('house_no',TRUE),
                'street_no'=>$this->input->post('street',TRUE),
                'barangay'=>$this->input->post('barangay',TRUE),
                'municipality'=>$this->input->post('municipality',TRUE),
                'zip_code'=>$this->input->post('zipcode',TRUE),
                'province'=>$this->input->post('province',TRUE),
                'house_no'=>$this->input->post('house_no',TRUE),
                'contact_no'=>$this->input->post('contact_no',TRUE),
                'email'=>$this->input->post('email',TRUE),
                'second_address'=>$this->input->post('second_address',TRUE),
                'meter_no'=>$this->input->post('meter_no',TRUE),
            );

            $this->db->where('consumer_id',$consumer_id);
            $this->db->update('customer_info',$data) or die(json_encode($this->error));
            $this->affected_id=$consumer_id;

            $this->db->trans_complete(); //end transaction
            return true;

        }catch(Exception $e){
            die(json_encode($this->error));
        }
    }

    function RemoveConsumer(){
        try{
            //array of data to be inserted
            $this->db->trans_start(); //start transaction
            $consumer_id=$this->input->post('id',TRUE);

            $this->db->set('is_deleted',1);
            $this->db->where('consumer_id',$consumer_id);
            $this->db->update('customer_info') or die(json_encode($this->error));
            $this->affected_id=$consumer_id;
            $this->db->trans_complete(); //end transaction
            return true;

        }catch(Exception $e){
            die(json_encode($this->error));
        }
    }

    function ReturnLastAffectedRowDetails(){
        $rows=array();
        $sql="SELECT
				CONCAT_WS('|',
				      consumer_id,
                      contact_no,
                      email,
                      second_address,
                      meter_no,
                      house_no,
                      street_no,
                      barangay,
                      municipality,
                      zip_code,
                      province

                )AS     hidden,
                        consumer_name,
                CONCAT_WS(' ',
                      house_no,
                      street_no,
                      barangay,
                      municipality,
                      zip_code,
                      province

                )AS     address
			FROM customer_info
			WHERE
					consumer_id=".$this->affected_id;
        $query = $this->db->query($sql);

        foreach ($query->result() as $row) //this will return only 1 row
        {
            $rows[]=$row; //assign each row of query in array
        }

        return $rows;
    }

}

?>


text:
{-
Copyright (c) 2015 Nils 'bash0r' Jonsson

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-}

{-# LANGUAGE TypeSynonymInstances #-}

{- |
Module      :  $Header$
Description :  The numeric operators of the EDSL.
Author	    :  Nils 'bash0r' Jonsson
Copyright   :  (c) 2015 Nils 'bash0r' Jonsson
License	    :  MIT

Maintainer  :  aka.bash0r@gmail.com
Stability   :  unstable
Portability :  non-portable (Portability is untested.)

The numeric operators of the EDSL.
-}
module Language.JavaScript.DSL.Operators.Numeric
(
) where

import qualified Language.JavaScript.DOM as DOM

import           Language.JavaScript.DSL.TypeAliases

instance Num Expression where
  (+) (DOM.NumberLiteral l) (DOM.NumberLiteral r) = DOM.NumberLiteral (l + r)
  (+) l                     r                     = DOM.BinaryExpression DOM.Addition l r

  (-) (DOM.NumberLiteral l) (DOM.NumberLiteral r) = DOM.NumberLiteral (l - r)
  (-) l                     r                     = DOM.BinaryExpression DOM.Subtraction l r

  (*) (DOM.NumberLiteral l) (DOM.NumberLiteral r) = DOM.NumberLiteral (l * r)
  (*) l                     r                     = DOM.BinaryExpression DOM.Multiplication l r

  negate (DOM.NumberLiteral v) = DOM.NumberLiteral (negate v)
  negate v                     = DOM.BinaryExpression DOM.Multiplication v (DOM.NumberLiteral (-1))

  abs    (DOM.NumberLiteral v) = DOM.NumberLiteral (abs v)
  abs    v                     = DOM.FunctionCall function []
    where
      function   = DOM.Function Nothing [] [ DOM.ConditionTree conditions otherwise ]
      conditions = [(condition, action)]
      condition  = DOM.BinaryExpression DOM.LessThan v (DOM.NumberLiteral 0)
      action     = DOM.Return (DOM.BinaryExpression DOM.Multiplication v (DOM.NumberLiteral (-1)))
      otherwise  = DOM.Return v

  signum (DOM.NumberLiteral v) = DOM.NumberLiteral (signum v)
  signum v                     = DOM.FunctionCall function []
    where
      function   = DOM.Function Nothing [] [ DOM.ConditionTree conditions otherwise ]
      conditions = [(condGZero, actGZero), (condLZero, actLZero)]
      condLZero  = DOM.BinaryExpression DOM.LessThan v (DOM.NumberLiteral 0)
      condGZero  = DOM.BinaryExpression DOM.GreaterThan v (DOM.NumberLiteral 0)
      actLZero   = DOM.Return (DOM.NumberLiteral (-1))
      actGZero   = DOM.Return (DOM.NumberLiteral 1)
      otherwise  = DOM.Return (DOM.NumberLiteral 0)

  fromInteger i = DOM.NumberLiteral (fromInteger i)


text:
class IDemoWriter;

namespace DemoReader
{
    void ProcessDem(std::FILE* inputFp, IDemoWriter* writer);
    void ProcessJson(std::FILE* inputFp, IDemoWriter* writer);
}


text:
/**
 * @depend util/core.js
 * @depend typeOf.js
 */
/*jslint eqeqeq: false, onevar: false, plusplus: false*/
/*global module, require, sinon*/
/**
 * Match functions
 *
 * @author Maximilian Antoni (mail@maxantoni.de)
 * @license BSD
 *
 * Copyright (c) 2012 Maximilian Antoni
 */
"use strict";

(function (sinon) {
    function makeApi(sinon) {
        function assertType(value, type, name) {
            var actual = sinon.typeOf(value);
            if (actual !== type) {
                throw new TypeError("Expected type of " + name + " to be " +
                    type + ", but was " + actual);
            }
        }

        var matcher = {
            toString: function () {
                return this.message;
            }
        };

        function isMatcher(object) {
            return matcher.isPrototypeOf(object);
        }

        function matchObject(expectation, actual) {
            if (actual === null || actual === undefined) {
                return false;
            }
            for (var key in expectation) {
                if (expectation.hasOwnProperty(key)) {
                    var exp = expectation[key];
                    var act = actual[key];
                    if (match.isMatcher(exp)) {
                        if (!exp.test(act)) {
                            return false;
                        }
                    } else if (sinon.typeOf(exp) === "object") {
                        if (!matchObject(exp, act)) {
                            return false;
                        }
                    } else if (!sinon.deepEqual(exp, act)) {
                        return false;
                    }
                }
            }
            return true;
        }

        matcher.or = function (m2) {
            if (!arguments.length) {
                throw new TypeError("Matcher expected");
            } else if (!isMatcher(m2)) {
                m2 = match(m2);
            }
            var m1 = this;
            var or = sinon.create(matcher);
            or.test = function (actual) {
                return m1.test(actual) || m2.test(actual);
            };
            or.message = m1.message + ".or(" + m2.message + ")";
            return or;
        };

        matcher.and = function (m2) {
            if (!arguments.length) {
                throw new TypeError("Matcher expected");
            } else if (!isMatcher(m2)) {
                m2 = match(m2);
            }
            var m1 = this;
            var and = sinon.create(matcher);
            and.test = function


text:
<title>HTML5 History API</title>

HTML5 History API not supported

Last event fired: (none)

To test the History API, click through the urls below. Note that none of these urls point to real pages. JavaScript will intercept these clicks, load data and the browser address bar will appear to change - but this is the History API in action!

Use the back and forward buttons in your browser to navigate the history.

first

second

third

fourth

Note: since these urls aren't real, refreshing the page will land on an invalid url.


text:
namespace dslice {

dslice::SlicingReport DynamicSlicer::Slicing(const dslice::Factor& variable, ds_double lambda, ds_uint granularity) {
	dslice::Darray<ds_double> count_table;
	if (granularity == 1) {
		count_table = Clump(variable);
	} else {
		count_table = Clump(variable, granularity);
	}
	ds_uint sample_size = variable.factor.size();
	ds_double penalty = -lambda * log((ds_double)sample_size);
	dslice::SlicingReport slicing_report = SlicingImplement(count_table, penalty);
	return slicing_report;
}

dslice::SlicingReport DynamicSlicer::Slicing(const dslice::Factor& variable, ds_double lambda, const std::vector<ds_uint>& rank) {
	dslice::Darray<ds_double> count_table = Clump(variable, rank);
	ds_uint sample_size = variable.factor.size();
	ds_double penalty = -lambda * log((ds_double)sample_size);
	dslice::SlicingReport slicing_report = SlicingImplement(count_table, penalty);
	return slicing_report;
}

dslice::Darray<ds_double> DynamicSlicer::Clump(const dslice::Factor& variable) {
	ds_uint sample_size = variable.factor.size();
	dslice::Darray<ds_double> clump_array(sample_size + 1, variable.level);
	ds_uint index = 1;
	ds_uint clump_count = 1;
	ds_uint clump_num = 1;
	while (index < sample_size) {
		if (variable.factor[index] - variable.factor[index - 1] != 0) {
			clump_array.SetValue(clump_num, variable.factor[index - 1], clump_count);
			clump_count = 1;
			clump_num++;
		} else {
			clump_count++;
		}
		index++;
	}
	clump_array.SetValue(clump_num, variable.factor[sample_size - 1], clump_count);
	clump_array.Resize(clump_num + 1, variable.level);
	clump_array.SetValue(clump_array.CumSum(2));
	return clump_array;
}

dslice::Darray<ds_double> DynamicSlicer::Clump(const dslice::Factor& variable, ds_uint granularity) {
	ds_uint sample_size = variable.factor.size();
	if (granularity == 0) {
		granularity = (ds_uint)sqrt((ds_double)sample_size);
	}
	std::vector<ds_uint> candidate(sample_size / granularity + 2, 0);
	ds_uint clump_num = 0;
	ds_uint index = granularity;
	while (index < sample_size) {
		if (variable.factor[index] - variable.factor[index - 1] != 0) {
			candidate[++clump_num] = index;
			index += granularity;
		}else{
			index++;
		}
	}
	candidate[++clump_num] = sample_size;
	dslice::Darray<ds_double> clump_array(clump_num + 1, variable.level);
	for (ds_uint i = 1; i != clump_num + 1; ++i) {
		for (ds_uint j = 0; j != variable.level; ++j) {
			clump_array.SetValue(i, j, clump_array(i - 1, j));
		}
		for (ds_uint j = candidate[i - 1]; j < candidate[i]; ++j) {
			clump_array.SetValue(i, variable.factor[j], clump_array(i, variable.factor[j]) + 1);
		}
	}
	clump_array.Resize(clump_num+1, variable.level);
	return clump_array;
}

dslice::Darray<ds_double> DynamicSlicer::Clump(const dslice::Factor& variable, const std::vector<ds_uint>& rank) {
	ds_uint sample_size = variable.factor.size();
	dslice::Darray<ds_double> clump_array(sample_size + 1, variable.level);
	ds_uint index = 1;
	ds_uint clump_count = 1;
	ds_uint clump_num = 1;
	ds_double temp_value;
	while (index < sample_size) {
		if ((variable.factor[index] - variable.factor[index - 1] != 0) && (rank[index] - rank[index - 1] != 0)) {
			temp_value = clump_array(clump_num, variable.factor[index - 1]) + 1;
			clump_array.SetValue(clump_num, variable.factor[index - 1], temp_value);
			clump_count = 1;
			clump_num++;
		} else {
			temp_value = clump_array(clump_num, variable.factor[index - 1]) + 1;
			clump_array.SetValue(clump_num, variable.factor[index - 1], temp_value);
		}
		index++;
	}
	temp_value = clump_array(clump_num, variable.factor[index - 1]) + 1;
	clump_array.SetValue(clump_num, variable.factor[index - 1], temp_value);
	clump_array.Resize(clump_num+1, variable.level);
	clump_array.SetValue(clump_array.CumSum(2));
	clump_array.Print();
	return clump_array;
}

dslice::SlicingReport DynamicSlicer::SlicingImplement(const dslice::Darray<ds_double>& count_table, ds_double penalty) {
	DPTable programming_result = DynamicSlicing(count_table, penalty);
	std::vector<ds_uint> optimal_incision = Backtracking(programming_result.strategy);
	dslice::Darray<ds_uint> slices = Summary(optimal_incision, count_table);
	dslice::SlicingReport slicing_report;
	slicing_report.SetReport(programming_result.score, optimal_incision, slices);
	return slicing_report;
}

dslice::DPTable DynamicSlicer::DynamicSlicing(const dslice::Darray<ds_double>& count_table, ds_double penalty) {
	ds_uint clump_num = count_table.Nrow() - 1;
	ds_uint level = count_table.Ncol();
	DPTable dp_table;
	dp_table.strategy.resize(clump_num + 1);
	std::vector<ds_double> score(clump_num + 1, 0);
	std::vector<ds_uint> counts(level);
	ds_uint incision;
	ds_double local_sum, candidate_score, slice_score;
	// dynamic programming
	for (ds_uint i = 1; i != clump_num + 1; ++i) {
		// j = 0
		slice_score = penalty + score[0];
		local_sum = 0;
		for (ds_uint u = 0; u != level; ++u) {
			counts[u] = count_table(i, u);
			local_sum += counts[u];
			if(counts[u] > EPSILON){
				slice_score += counts[u] * log(counts[u]);
			}
		}
		slice_score -= local_sum * log(local_sum);
		incision = 0;
		// j = 0 end
		for (ds_uint j = 1; j != i; ++j) {
			candidate_score = penalty + score[j];
			local_sum = 0;
			for (ds_uint u = 0; u != level; ++u) {
				counts[u] = count_table(i, u) - count_table(j, u);
				local_sum += counts[u];
				if(counts[u] > EPSILON){
					candidate_score += counts[u] * log(counts[u]);
				}
			}
			candidate_score -= local_sum * log(local_sum);
			if (slice_score < candidate_score) {
				slice_score = candidate_score;
				incision = j;
			}
		}
		score[i] = slice_score;
		dp_table.strategy[i] = incision;
	}
	// substract null log-likelihood (assume one slice, i.e., no cut)
	ds_double max_loglikelihood = score[clump_num] - penalty;
	ds_uint sample_size = 0;
	for(ds_uint i = 0; i != level; ++i) {
		if (count_table(clump_num, i) > EPSILON){
			max_loglikelihood -= count_table(clump_num, i) * log(count_table(clump_num, i));
			sample_size += count_table(clump_num, i);
		}
	}
	max_loglikelihood += sample_size * log(sample_size);
	dp_table.score = max_loglikelihood;
	return dp_table;
}

std::vector<ds_uint> DynamicSlicer::Backtracking(const std::vector<ds_uint>& global_incision) {
	std::vector<ds_uint> optimal_incision;
	ds_uint index = global_incision.size() - 1;
	while (index > 0) {
		optimal_incision.push_back(index);
		index = global_incision[index];
	}
	optimal_incision.push_back(0);
	reverse(optimal_incision.begin(), optimal_incision.end());
	return optimal_incision;
}

dslice::Darray<ds_uint> DynamicSlicer::Summary(const std::vector<ds_uint>& optimal_incision,
	const dslice::Darray<ds_double>& count_table) {
	ds_uint level = count_table.Ncol();
	ds_uint slice_num = optimal_incision.size() - 1;
	dslice::Darray<ds_uint> slices(slice_num, level + 1);
	std::vector<std::string> rownames(slice_num);
	std::vector<std::string> colnames(level + 1);
	std::string prefix = "slice";
	for (ds_uint i = 0; i != slice_num; ++i) {
		rownames[i] = prefix + std::to_string(i + 1);
	}
	for (ds_uint j = 0; j != level; ++j) {
		colnames[j] = std::to_string(j);
	}
	colnames[level] = "total";
	slices.SetDimName(rownames, 1);
	slices.SetDimName(colnames, 2);

	ds_double category_count = 0;
	for (ds_uint i = 0; i != slice_num; ++i) {
		for (ds_uint j = 0; j != level; ++j) {
			category_count = count_table(optimal_incision[i + 1], j) - count_table(optimal_incision[i], j);
			slices.SetValue(i, j, category_count);
			slices.SetValue(i, level, category_count + slices(i, level));
		}
	}
	return slices;
}

ds_double DynamicSlicer::BayesianSlicing(const dslice::Factor& variable, ds_double lambda, ds_double alpha, ds_uint granularity) {
	dslice::Darray<ds_uint> count_table;
	if (granularity == 1) {
		count_table = GenerateCountTable(variable);
	} else {
		count_table = GenerateCountTable(variable, granularity);
	}
	ds_double dsbf = CalculateBayesFactor(count_table, lambda, alpha);
	return dsbf;
}

ds_double DynamicSlicer::BayesianSlicing(const dslice::Factor& variable, const dslice::Factor& selected, ds_double lambda, ds_double alpha, ds_uint granularity) {
	dslice::Darray<ds_uint> count_table;
	if (granularity == 1) {
		count_table = GenerateCountTable(variable, selected);
	} else {
		count_table = GenerateCountTable(variable, selected, granularity);
	}
	ds_double dsbf = CalculateBayesFactor(count_table, lambda, alpha, variable.level);
	return dsbf;
}

dslice::Darray<ds_uint> DynamicSlicer::GenerateCountTable(const dslice::Factor& variable) {
	ds_uint sample_size = variable.factor.size();
	ds_double temp_value;
	dslice::Darray<ds_uint> count_table(sample_size + 1, variable.level);
	for (ds_uint i = 1; i != sample_size + 1; ++i) {
		for (ds_uint j = 0; j != variable.level; ++j) {
			count_table.SetValue(i, j, count_table(i - 1, j));
		}
		temp_value = count_table(i, variable.factor[i - 1]) + 1;
		count_table.SetValue(i, variable.factor[i - 1], temp_value);
	}
	return count_table;
}

dslice::Darray<ds_uint> DynamicSlicer::GenerateCountTable(const dslice::Factor& variable, ds_uint granularity) {
	ds_uint sample_size = variable.factor.size();
	if (granularity == 0) {
		granularity = (ds_uint)sqrt((ds_double)sample_size);
	}
	ds_uint group_num = sample_size / granularity;
	ds_uint tail = sample_size % granularity;
	std::vector<ds_uint> candidate(group_num + 1, 0);
	for (ds_uint i = 1; i != group_num + 1; ++i) {
		candidate[i] = candidate[i - 1] + granularity;
	}
	if (tail != 0) {
		for (ds_int i = 1; i != tail + 1; ++i){
			candidate[i] += i;
		}
		for (ds_int i = tail + 1; i != group_num + 1; ++i) {
			candidate[i] += tail;
		}
	}
	ds_double temp_value;
	dslice::Darray<ds_uint> clump_array(group_num + 1, variable.level);
	for (ds_uint i = 1; i != group_num + 1; ++i) {
		for (ds_uint j = 0; j != variable.level; ++j) {
			clump_array.SetValue(i, j, clump_array(i - 1, j));
		}
		for (ds_uint j = candidate[i - 1]; j != candidate[i]; ++j) {
			temp_value = clump_array(i, variable.factor[j]) + 1;
			clump_array.SetValue(i, variable.factor[j], temp_value);
		}
	}
	return clump_array;
}

dslice::Darray<ds_uint> DynamicSlicer::GenerateCountTable(const dslice::Factor& variable, const dslice::Factor& selected) {
	ds_uint sample_size = variable.factor.size();
	ds_uint level = variable.level * selected.level;
	ds_int col_index;
	ds_double temp_value;
	dslice::Darray<ds_uint> count_table(sample_size + 1, level);
	for (ds_uint i = 1; i != sample_size + 1; ++i) {
		for (ds_uint j = 0; j != level; ++j) {
			count_table.SetValue(i, j, count_table(i - 1, j));
		}
		col_index = selected.factor[i - 1] * variable.level + variable.factor[i - 1];
		temp_value = count_table(i, col_index) + 1;
		count_table.SetValue(i, col_index, temp_value);
	}
	return count_table;
}

dslice::Darray<ds_uint> DynamicSlicer::GenerateCountTable(const dslice::Factor& variable, const dslice::Factor& selected, ds_uint granularity) {
	ds_uint sample_size = variable.factor.size();
	if (granularity == 0) {
		granularity = (ds_uint)sqrt((ds_double)sample_size);
	}
	ds_uint group_num = sample_size / granularity;
	ds_uint tail = sample_size % granularity;
	std::vector<ds_uint> candidate(group_num + 1, 0);
	for (ds_uint i = 1; i != group_num + 1; ++i) {
		candidate[i] = candidate[i - 1] + granularity;
	}
	if (tail != 0) {
		for (ds_uint i = 1; i != tail + 1; ++i){
			candidate[i] += i;
		}
		for (ds_uint i = tail + 1; i != group_num + 1; ++i) {
			candidate[i] += tail;
		}
	}
	ds_uint level = variable.level * selected.level;
	ds_uint col_index;
	ds_double temp_value;
	dslice::Darray<ds_uint> clump_array(group_num + 1, level);
	for (ds_uint i = 1; i != group_num + 1; ++i) {
		for (ds_uint j = 0; j != level; ++j) {
			clump_array.SetValue(i, j, clump_array(i - 1, j));
		}
		for (ds_uint j = candidate[i - 1]; j != candidate[i]; ++j) {
			col_index = selected.factor[j] * variable.level + variable.factor[j];
			temp_value = clump_array(i, col_index) + 1;
			clump_array.SetValue(i, col_index, temp_value);
		}
	}
	return clump_array;
}

ds_double DynamicSlicer::CalculateBayesFactor(const dslice::Darray<ds_uint>& count_table, ds_double lambda, ds_double alpha) {
	ds_uint length = count_table.Nrow() - 1;
	ds_uint level = count_table.Ncol();
	ds_double beta = alpha / level;
	ds_uint sample_size = 0;
	for (ds_uint j = 0; j < count_table.Ncol(); ++j) {
		sample_size += count_table(length, j);
	}
	std::vector<ds_double> alpha_table(sample_size + 1, 0);
	std::vector<ds_double> beta_table(sample_size + 1, 0);
	for (ds_uint i = 1; i != sample_size + 1; ++i) {
		alpha_table[i] = alpha_table[i - 1] + log(alpha + i - 1);
		beta_table[i] = beta_table[i - 1] + log(beta + i - 1);
	}
	// log Probability that null hypothesis holds
	ds_uint counts;
	std::vector<ds_double> log_pr_null(length + 1, 0);
	for (ds_uint i = 1; i != length + 1; ++i) {
		counts = 0;
		for (ds_uint v = 0; v != level; ++v){
			counts += count_table(i, v);
			log_pr_null[i] += beta_table[count_table(i, v)];
		}
		log_pr_null[i] -= alpha_table[counts];
	}
	// calculate Bayes factor
	ds_double log_delta_ji, temp_value;
	ds_uint count_diff;
	std::vector<ds_double> bayes_factor(length + 1, 0);
	ds_double prior = 1.0 / (1.0 + exp(lambda * log((ds_double)sample_size)));
	bayes_factor[0] = 1 / prior;
	for (ds_uint i = 1; i != length + 1; ++i) {
		for (ds_uint j = 0; j != i; ++j) {
			log_delta_ji = 0;
			counts = 0;
			for (ds_int v = 0; v != level; ++v) {
				count_diff = count_table(i, v) - count_table(j, v);
				counts += count_diff;
				log_delta_ji += beta_table[count_diff];
			}
			log_delta_ji += log(prior) - log(1 - prior) - alpha_table[counts];
			temp_value = (i - j) * log(1 - prior) + log_pr_null[j] - log_pr_null[i] + log_delta_ji;
			bayes_factor[i] += exp(temp_value) * bayes_factor[j];
		}
	}
	ds_double dsbf = bayes_factor[length];
	return dsbf;
}

ds_double DynamicSlicer::CalculateBayesFactor(const dslice::Darray<ds_uint>& count_table, ds_double lambda, ds_double alpha, ds_uint variable_level) {
	ds_uint length = count_table.Nrow() - 1;
	ds_uint level = count_table.Ncol();
	ds_uint selected_level = level / variable_level;
	ds_double beta = alpha / variable_level;
	ds_uint sample_size = 0;
	for (ds_uint j = 0; j < count_table.Ncol(); ++j) {
		sample_size += count_table(length, j);
	}
	std::vector<ds_double> alpha_table(sample_size + 1, 0);
	std::vector<ds_double> beta_table(sample_size + 1, 0);
	for (ds_uint i = 1; i != sample_size + 1; ++i) {
		alpha_table[i] = alpha_table[i - 1] + log(alpha + i - 1);
		beta_table[i] = beta_table[i - 1] + log(beta + i - 1);
	}
	ds_uint col_index;
	// log Probability that null hypothesis holds
	std::vector<ds_uint> selected_count(selected_level, 0);
	std::vector<ds_double> log_pr_null(length + 1, 0);
	for (ds_uint i = 1; i != length + 1; ++i) {
		for (ds_uint u = 0; u != selected_level; ++u) {
			selected_count[u] = 0;
			for (ds_uint v = 0; v != variable_level; ++v){
				col_index = u * variable_level + v;
				selected_count[u] += count_table(i, col_index);
				log_pr_null[i] += beta_table[count_table(i, col_index)];
			}
			log_pr_null[i] -= alpha_table[selected_count[u]];
		}
	}
	// calculate Bayes factor
	ds_double log_delta_ji, temp_value;
	ds_uint count_diff;
	std::vector<ds_double> bayes_factor(length + 1, 0);
	ds_double prior = 1.0 / (1.0 + exp(lambda * log((ds_double)sample_size)));
	bayes_factor[0] = 1 / prior;
	for (ds_uint i = 1; i != length + 1; ++i) {
		for (ds_uint j = 0; j != i; ++j) {
			log_delta_ji = 0;
			for (ds_int u = 0; u != selected_level; ++u) {
				selected_count[u] = 0;
				for (ds_int v = 0; v != variable_level; ++v) {
					col_index = u * variable_level + v;
					count_diff = count_table(i, col_index) - count_table(j, col_index);
					selected_count[u] += count_diff;
					log_delta_ji += beta_table[count_diff];
				}
				log_delta_ji -= alpha_table[selected_count[u]];
			}
			log_delta_ji += log(prior) - log(1 - prior);
			temp_value = (i - j) * log(1 - prior) + log_pr_null[j] - log_pr_null[i] + log_delta_ji;
			bayes_factor[i] += exp(temp_value) * bayes_factor[j];
		}
	}
	ds_double dsbf = bayes_factor[length];
	return dsbf;
}

ds_double DynamicSlicer::OneSampleSlicing(const std::vector<ds_double>& quantile, ds_double lambda, ds_double alpha) {
	ds_uint length = quantile.size();
	ds_double penalty = -lambda * log((ds_double)length);
	ds_double unit = 1.0 / length;
	std::vector<ds_double> left_score(length + 1, 0);
	std::vector<ds_double> right_score(length + 1, 0);
	std::vector<ds_uint> index(2 * length + 2, -1);

	ds_uint incision;
	ds_double candidate_score, slice_score;
	ds_double order_diff, quantile_diff;
	ds_double left_cut_value, right_cut_value;
	// i = 0, log likelihood = 0 for the left side
	left_cut_value = alpha * log(quantile[0]);
	right_cut_value = log(unit) + (alpha - 1) * log(quantile[0]); // log(unit / quantile[0]) + alpha * log(quantile[0])
	left_score[0] = left_cut_value + penalty;
	right_score[0] = right_cut_value + penalty;
	index[1] = 0;
	index[2] = 0;
	// i = 0 end
	for(ds_uint i = 1; i != length; ++i) {
		// on left side of i
		left_cut_value = i * log(i * unit / quantile[i]);
		slice_score = left_cut_value + penalty + alpha * log(quantile[i]);
		incision = 0;
		for (ds_uint j = 0; j != i - 1; ++j) {
			order_diff = i - j;
			quantile_diff = quantile[i] - quantile[j];
			left_cut_value = left_score[j] + order_diff * log(order_diff * unit / quantile_diff);
			right_cut_value = right_score[j] + (order_diff - 1) * log((order_diff - 1) * unit / quantile_diff);
			candidate_score = std::max(left_cut_value, right_cut_value) + penalty + alpha * log(quantile_diff);
			if (slice_score < candidate_score) {
				slice_score = candidate_score;
				incision = j;
			}
		}
		// j = i - 1
		order_diff = 1;
		quantile_diff = quantile[i] - quantile[i - 1];
		left_cut_value = left_score[i - 1] + log(unit / quantile_diff);
		right_cut_value = right_score[i - 1];
		candidate_score = std::max(left_cut_value, right_cut_value) + penalty + alpha * log(quantile_diff);
		if (slice_score < candidate_score) {
			slice_score = candidate_score;
			incision = i - 1;
		}
		// j = i - 1 end
		left_score[i] = slice_score;
		index[2 * i + 1] = incision;
		// on right side of i
		right_cut_value = (i + 1) * log((i + 1) * unit / quantile[i]);
		slice_score = right_cut_value + penalty + alpha * log(quantile[i]);
		incision = 0;
		for (ds_uint j = 0; j != i; ++j) {
			order_diff = i - j;
			quantile_diff = quantile[i] - quantile[j];
			left_cut_value = left_score[j] + (order_diff + 1) * log((order_diff + 1) * unit / quantile_diff);
			right_cut_value = right_score[j] + order_diff * log(order_diff * unit / quantile_diff);
			candidate_score = std::max(left_cut_value, right_cut_value) + penalty + alpha * log(quantile_diff);
			if(slice_score < candidate_score){
				slice_score = candidate_score;
				incision = j;
			}
		}
		right_score[i] = slice_score;
		index[2 * i + 2] = incision;
	}
	// i = length, i.e. for quantile_{n+1} = 1.0
	// on left side of len, no right side
	slice_score = penalty; // n*log(n/n /1) + penalty + alpha * log(1)
	incision = 0;
	for (ds_uint j = 0; j != length - 1; ++j) {
		order_diff = length - j;
		quantile_diff = 1.0 - quantile[j];
		left_cut_value = left_score[j] + order_diff * log(order_diff * unit / quantile_diff);
		right_cut_value = right_score[j] + (order_diff - 1) * log((order_diff - 1) * unit / quantile_diff);
		candidate_score = std::max(left_cut_value, right_cut_value) + penalty + alpha * log(quantile_diff);
		if (slice_score < candidate_score) {
			slice_score = candidate_score;
			incision = j;
		}
	}
	// j = length - 1
	order_diff = 1;
	quantile_diff = 1.0 - quantile[length - 1];
	left_cut_value = left_score[length - 1] + log(unit / quantile_diff);
	right_cut_value = right_score[length - 1];
	candidate_score = std::max(left_cut_value, right_cut_value) + penalty + alpha * log(quantile_diff);
	if (slice_score < candidate_score) {
		slice_score = candidate_score;
		incision = length - 1;
	}
	// j = length - 1 end
	left_score[length] = slice_score;
	index[2 * length + 1] = incision;
	// i = length end
	double max_likelihood = left_score[length] - penalty;
	return max_likelihood;
}

ds_double DynamicSlicer::OneSampleSlicing(const std::vector<ds_double>& quantile, ds_double lambda) {
	ds_uint length = quantile.size();
	ds_double penalty = -lambda * log((ds_double)length);
	ds_double unit = 1.0 / length;
	std::vector<ds_double> cum_uint(length + 1, 0); // cumulated unit counts
	ds_uint current_index = 1;
	ds_double current_cum = unit;
	for (ds_uint i = 0; i < length; ++i) {
		while (quantile[i] > current_cum) {
			cum_uint[current_index++] = i;
			current_cum += unit;
		}
	}
	for(; current_index < length + 1; ++current_index) {
		cum_uint[current_index] = length;
	}
	std::vector<ds_double> score(length + 1, 0);
	std::vector<ds_double> index(length + 1, -1);
	ds_uint incision;
	ds_double candidate_score, slice_score;
	ds_double order_diff, quantile_diff;
	for (ds_uint i = 1; i != length + 1; ++i) {
		slice_score = penalty + score[0];
		quantile_diff = i;
		order_diff = cum_uint[i] - cum_uint[0];
		if (order_diff > EPSILON) {
			slice_score += order_diff * log(order_diff / quantile_diff);
		}
		incision = 0;
		for (ds_uint j = 1; j != i; ++j) {
			candidate_score = penalty + score[j];
			quantile_diff = i - j;
			order_diff = cum_uint[i] - cum_uint[j];
			if (order_diff > EPSILON) {
				candidate_score += order_diff * log(order_diff / quantile_diff);
			}
			if(slice_score < candidate_score) {
				slice_score = candidate_score;
				incision = j;
			}
		}
		score[i] = slice_score;
		index[i] = incision;
	}
	ds_double max_likelihood = score[length] - penalty;
	quantile_diff = length;
	order_diff = cum_uint[length];
	max_likelihood -= order_diff * log(order_diff / quantile_diff);
	return max_likelihood; // maximized log-likelihood
}

} // namespace dslice


text:
layout: publication
type: "conference"
authors: "Jang, S. S., H. D. Siegler, A. Ben-zvi, R. R. Bhushan Gopaluni"
order: 19
year: 2008
title: "Parameter Estimation Using Sparse and Irregularly Sampled Data from Multiple Experiments"
journal: "In proceedings of International Symposium on Advanced Control of Industrial Processes (ADCONIP), Jasper, Canada"
pagenum: "335 – 340"
---


text:
import unittest
from biicode.common.model.brl.block_name import BlockName
from biicode.common.exception import InvalidNameException

class BlockNameTest(unittest.TestCase):

    def blockname_test(self):
        m = BlockName("user/block")
        self.assertEquals("user/block", str(m))
        m = BlockName("user/bLOck")
        self.assertEquals("user/bLOck", str(m))
        self.assertEquals('bLOck', str(m.name))
        m = BlockName("uSer/bLOck")
        self.assertEquals("uSer/bLOck", str(m))

    def blockname_underscore_test(self):
        bn = BlockName("user_1/block_1")

    def long_blockname_test(self):
        wrong_bn = "dummy/dummy/block/master"
        with self.assertRaisesRegexp(InvalidNameException,
                                     '%s is not a valid BlockName.' % wrong_bn):
            BlockName(wrong_bn)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


text:
#pragma once
#include <aws/lambda/Lambda_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Lambda
{
namespace Model
{
  class AWS_LAMBDA_API ListFunctionsByCodeSigningConfigResult
  {
  public:
    ListFunctionsByCodeSigningConfigResult();
    ListFunctionsByCodeSigningConfigResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListFunctionsByCodeSigningConfigResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The pagination token that's included if more results are available.

     */
    inline const Aws::String& GetNextMarker() const{ return m_nextMarker; }

    /**
     *
The pagination token that's included if more results are available.

     */
    inline void SetNextMarker(const Aws::String& value) { m_nextMarker = value; }

    /**
     *
The pagination token that's included if more results are available.

     */
    inline void SetNextMarker(Aws::String&& value) { m_nextMarker = std::move(value); }

    /**
     *
The pagination token that's included if more results are available.

     */
    inline void SetNextMarker(const char* value) { m_nextMarker.assign(value); }

    /**
     *
The pagination token that's included if more results are available.

     */
    inline ListFunctionsByCodeSigningConfigResult& WithNextMarker(const Aws::String& value) { SetNextMarker(value); return *this;}

    /**
     *
The pagination token that's included if more results are available.

     */
    inline ListFunctionsByCodeSigningConfigResult& WithNextMarker(Aws::String&& value) { SetNextMarker(std::move(value)); return *this;}

    /**
     *
The pagination token that's included if more results are available.

     */
    inline ListFunctionsByCodeSigningConfigResult& WithNextMarker(const char* value) { SetNextMarker(value); return *this;}

    /**
     *
The function ARNs.

     */
    inline const Aws::Vector<Aws::String>& GetFunctionArns() const{ return m_functionArns; }

    /**
     *
The function ARNs.

     */
    inline void SetFunctionArns(const Aws::Vector<Aws::String>& value) { m_functionArns = value; }

    /**
     *
The function ARNs.

     */
    inline void SetFunctionArns(Aws::Vector<Aws::String>&& value) { m_functionArns = std::move(value); }

    /**
     *
The function ARNs.

     */
    inline ListFunctionsByCodeSigningConfigResult& WithFunctionArns(const Aws::Vector<Aws::String>& value) { SetFunctionArns(value); return *this;}

    /**
     *
The function ARNs.

     */
    inline ListFunctionsByCodeSigningConfigResult& WithFunctionArns(Aws::Vector<Aws::String>&& value) { SetFunctionArns(std::move(value)); return *this;}

    /**
     *
The function ARNs.

     */
    inline ListFunctionsByCodeSigningConfigResult& AddFunctionArns(const Aws::String& value) { m_functionArns.push_back(value); return *this; }

    /**
     *
The function ARNs.

     */
    inline ListFunctionsByCodeSigningConfigResult& AddFunctionArns(Aws::String&& value) { m_functionArns.push_back(std::move(value)); return *this; }

    /**
     *
The function ARNs.

     */
    inline ListFunctionsByCodeSigningConfigResult& AddFunctionArns(const char* value) { m_functionArns.push_back(value); return *this; }

  private:

    Aws::String m_nextMarker;

    Aws::Vector<Aws::String> m_functionArns;
  };

} // namespace Model
} // namespace Lambda
} // namespace Aws


text:
<%#
 Copyright 2013-2017 the original author or authors from the StackStack project.

 This file is part of the StackStack project, see http://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%=packageName%>.config;

import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
import io.github.jhipster.config.JHipsterProperties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.*;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {

    private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);

    private final JHipsterProperties jHipsterProperties;

    public AsyncConfiguration(JHipsterProperties jHipsterProperties) {
        this.jHipsterProperties = jHipsterProperties;
    }

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        log.debug("Creating Async Task Executor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
        executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
        executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
        executor.setThreadNamePrefix("<%= dasherizedBaseName %>-Executor-");
        return new ExceptionHandlingAsyncTaskExecutor(executor);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}


text:
    <link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css"/>
    <link rel="stylesheet" href="/formstamp.css"/>

{{ item }}

    select values


text:
namespace sweep {
namespace serial {

struct device {
  int32_t fd;
};

static speed_t get_baud(int32_t bitrate) {
  SWEEP_ASSERT(bitrate > 0);
  if (bitrate != 115200) {
    throw error{"Only baud rate 115200 is supported at this time."};
    return -1;
  }

// translate human readable bitrate to termios bitrate
#ifdef B115200
  return B115200;
#endif
  return bitrate;
}

static bool wait_readable(device_s serial) {
  SWEEP_ASSERT(serial);

  // Setup a select call to block for serial data
  fd_set readfds;
  FD_ZERO(&readfds);
  FD_SET(serial->fd, &readfds);

  int32_t ret = select(serial->fd + 1, &readfds, nullptr, nullptr, nullptr);

  if (ret == -1) {
    // Select was interrupted
    if (errno == EINTR) {
      return false;
    }

    // Otherwise there was some error
    throw error{"blocking on data to read failed"};

  } else if (ret) {
    // Data Available
    return true;
  } else {
    return false;
  }

  return false;
}

device_s device_construct(const char* port, int32_t bitrate) {
  SWEEP_ASSERT(port);
  SWEEP_ASSERT(bitrate > 0);

  int32_t fd = open(port, O_RDWR | O_NOCTTY | O_NONBLOCK);

  if (fd == -1)
    throw error{"opening serial port failed"};

  if (!isatty(fd))
    throw error{"serial port is not a TTY"};

  struct termios options;

  if (tcgetattr(fd, &options) == -1)
    throw error{"querying terminal options failed"};

#ifndef __FreeBSD__
  // Input Flags
  options.c_iflag &= ~(INLCR | IGNCR | ICRNL | IGNBRK);

  // SW Flow Control OFF
  options.c_iflag &= ~(IXON | IXOFF | IXANY);

  // Output Flags
  options.c_oflag &= ~(OPOST);

  // Local Flags
  options.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ISIG);

  // IEXTEN

  // Control Flags
  options.c_cflag &= ~(PARENB | CSTOPB | CSIZE);
  options.c_cflag |= (CLOCAL | CREAD | CS8);
#else // __FreeBSD__
  cfmakeraw(&options);
#endif

  // setup baud rate
  speed_t baud = get_baud(bitrate);

  cfsetispeed(&options, baud);
  cfsetospeed(&options, baud);

  // flush the port
  if (tcflush(fd, TCIFLUSH) == -1)
    throw error{"flushing the serial port failed"};

  // set port attributes
  if (tcsetattr(fd, TCSANOW, &options) == -1) {
    if (close(fd) == -1)
      SWEEP_ASSERT(false && "closing file descriptor during error handling failed");

    throw error{"setting terminal options failed"};
  }

  auto out = new device{fd};
  return out;
}

void device_destruct(device_s serial) {
  SWEEP_ASSERT(serial);

  try {
    device_flush(serial);
  } catch (...) {
    // nothing we can do here
  }

  if (close(serial->fd) == -1)
    SWEEP_ASSERT(false && "closing file descriptor during destruct failed");

  delete serial;
}

void device_read(device_s serial, void* to, int32_t len) {
  SWEEP_ASSERT(serial);
  SWEEP_ASSERT(to);
  SWEEP_ASSERT(len >= 0);

  // the following implements reliable full read xor error
  int32_t bytes_read = 0;

  while (bytes_read < len) {
    if (wait_readable(serial)) {
      int ret = read(serial->fd, (char*)to + bytes_read, len - bytes_read);

      if (ret == -1) {
        if (errno == EAGAIN || errno == EINTR) {
          continue;
        } else {
          throw error{"reading from serial device failed"};
        }
      } else if (ret == 0) {
        throw error{"encountered EOF on serial device"};
      } else {
        bytes_read += ret;
      }
    }
  }

  SWEEP_ASSERT(bytes_read == len && "reliable read failed to read requested size of bytes");
}

void device_write(device_s serial, const void* from, int32_t len) {
  SWEEP_ASSERT(serial);
  SWEEP_ASSERT(from);
  SWEEP_ASSERT(len >= 0);

  // the following implements reliable full write xor error
  int32_t bytes_written = 0;

  while (bytes_written < len) {
    int32_t ret = write(serial->fd, (const char*)from + bytes_written, len - bytes_written);

    if (ret == -1) {
      if (errno == EAGAIN || errno == EINTR) {
        continue;
      } else {
        throw error{"writing to serial device failed"};
      }
    } else {
      bytes_written += ret;
    }
  }

  SWEEP_ASSERT(bytes_written == len && "reliable write failed to write requested size of bytes");
}

void device_flush(device_s serial) {
  SWEEP_ASSERT(serial);

  if (tcflush(serial->fd, TCIFLUSH) == -1)
    throw error{"flushing the serial port failed"};
}

} // ns serial
} // ns sweep


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using Criteo.Profiling.Tracing.Tracers.Zipkin;

namespace PerfIt.Zipkin
{
    /// <summary>
    /// Default emitter for zipkin spans
    /// </summary>
    public class SimpleEmitter : ISpanEmitter
    {
        private ConcurrentBag<IDispatcher> _dispatchers = new ConcurrentBag<IDispatcher>();

        public void Emit(Span span)
        {
            foreach (var d in _dispatchers)
            {
                d.Emit(span);
            }
        }

        /// <summary>
        /// Registers a dispatcher
        /// </summary>
        /// <param name="dispatcher">Dispatcher for the spans. THey are meant to implement batching and buffering their end</param>
        public void RegisterDispatcher(IDispatcher dispatcher)
        {
            _dispatchers.Add(dispatcher);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Zenject;
using NUnit.Framework;
using ModestTree;
using Assert=ModestTree.Assert;

namespace Zenject.Tests.Other
{
    [TestFixture]
    public class TestResolveMany : ZenjectUnitTestFixture
    {
        class Test0
        {
        }

        class Test1 : Test0
        {
        }

        class Test2 : Test0
        {
        }

        [Test]
        public void TestCase1()
        {
            Container.Bind<Test0>().To<Test1>().AsSingle();
            Container.Bind<Test0>().To<Test2>().AsSingle();

            List<Test0> many = Container.ResolveAll<Test0>();

            Assert.That(many.Count == 2);
        }

        [Test]
        public void TestOptional()
        {
            List<Test0> many = Container.ResolveAll<Test0>();
            Assert.That(many.Count == 0);
        }
    }
}


text:
pub struct ExpectedError { line: uint, kind: ~str, msg: ~str }

// Load any test directives embedded in the file
pub fn load_errors(testfile: &Path) -> ~[ExpectedError] {
    use std::rt::io::Open;
    use std::rt::io::file::FileInfo;
    use std::rt::io::buffered::BufferedReader;

    let mut error_patterns = ~[];
    let mut rdr = BufferedReader::new(testfile.open_reader(Open).unwrap());
    let mut line_num = 1u;
    loop {
        let ln = match rdr.read_line() {
            Some(ln) => ln, None => break,
        };
        error_patterns.push_all_move(parse_expected(line_num, ln));
        line_num += 1u;
    }
    return error_patterns;
}

fn parse_expected(line_num: uint, line: ~str) -> ~[ExpectedError] {
    let line = line.trim();
    let error_tag = ~"//~";
    let mut idx;
    match line.find_str(error_tag) {
      None => return ~[],
      Some(nn) => { idx = (nn as uint) + error_tag.len(); }
    }

    // "//~^^^ kind msg" denotes a message expected
    // three lines above current line:
    let mut adjust_line = 0u;
    let len = line.len();
    while idx < len && line[idx] == ('^' as u8) {
        adjust_line += 1u;
        idx += 1u;
    }

    // Extract kind:
    while idx < len && line[idx] == (' ' as u8) { idx += 1u; }
    let start_kind = idx;
    while idx < len && line[idx] != (' ' as u8) { idx += 1u; }

    // FIXME: #4318 Instead of to_ascii and to_str_ascii, could use
    // to_ascii_consume and to_str_consume to not do a unnecessary copy.
    let kind = line.slice(start_kind, idx);
    let kind = kind.to_ascii().to_lower().to_str_ascii();

    // Extract msg:
    while idx < len && line[idx] == (' ' as u8) { idx += 1u; }
    let msg = line.slice(idx, len).to_owned();

    debug2!("line={} kind={} msg={}", line_num - adjust_line, kind, msg);

    return ~[ExpectedError{line: line_num - adjust_line, kind: kind,
                           msg: msg}];
}


text:
@startDocuBlock get_admin_server_availability
@brief Return whether or not a server is available

@RESTHEADER{GET /_admin/server/availability, Return whether or not a server is available, handleAvailability}

@RESTDESCRIPTION
Return availability information about a server.

This is a public API so it does *not* require authentication. It is meant to be
used only in the context of server monitoring only.

@RESTRETURNCODES

@RESTRETURNCODE{200}
This API will return HTTP 200 in case the server is up and running and usable for
arbitrary operations, is not set to read-only mode and is currently not a follower
in case of an active failover setup.

@RESTRETURNCODE{503}
HTTP 503 will be returned in case the server is during startup or during shutdown,
is set to read-only mode or is currently a follower in an active failover setup.
@endDocuBlock


text:
class CreateSimpleImageBankImageTypes < ActiveRecord::Migration
  def change
    create_table :simple_image_bank_image_types do |t|
      t.string :image_type_name

      t.timestamps
    end
  end
end


text:
import React from "react";
import { BrowserRouter } from "react-router-dom";
// hydrate is responsible for server rendering going forward
import { hydrate as render } from "react-dom";
import App from "./app";
import { Provider } from "react-redux";
import store from "./store";
import registerServiceWorker from "./registerServiceWorker";

render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById("app")
);

registerServiceWorker();

// Hot Module Replacement API
if (module.hot) {
  module.hot.accept();
}


text:
package ninja.cero.ecommerce.order.domain;

public enum EventType {
	START, PAYMENT_COMPLETE, MAIL_SENT, ORDER_PROCESSED
}


text:
<?php $this->load->spark('assets/0.5.1'); ?>

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

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

<title>CodeIgniter Sparks | <?php echo isset($title) ? "$title" : "The Package Manager and Repository"; ?></title>

<?php display_css(array('reset.css', 'style.css', 'clear.css')); ?>

<?php display_js(array('jquery-1.4.4.min.js',
                       'jquery-ui-1.8.9.min.js',
                       'jquery.available.1.6.1.min.js',
                       'site.js')); ?>

<meta http-equiv='expires' content='-1' />
<meta http-equiv= 'pragma' content='no-cache' />
<meta name='robots' content='all' />

Sparks Beta

					<?php echo number_format(UtilityHelper::getGlobalInstallCount()); ?> Installs and Counting!
                    <a href="<?php echo config_item('sparks_download_button_url'); ?>" title="Get Sparking!"><?php echo config_item('sparks_download_button_text'); ?>

Home

Browse

Install/Setup

Get Sparks

Make Sparks

About

<form action="/search" method="post" id="headersearch"><input type="text" name="term" value="" class="text-box" /><input type="submit" name="submit" class="submit" value="Search" /></form>

			<?php $this->load->view('global/_left_column.php'); ?>

				<?php if($notices = UserHelper::getNotices()): ?>
			        <?php foreach($notices as $notice): ?>
			            <?php list($message, $is_good) = $notice; ?>
			            <?php if($is_good): ?>

<?php echo $message; ?>

			            <?php else: ?>

<?php echo $message; ?>

			            <?php endif; ?>
			        <?php endforeach; ?>
			    <?php endif; ?>


text:
Select md.elapsedSecs - nmd.elapsedSecs as diff, md.elapsedSecs - nmd.elapsedSecs < 0 as Impr
From MifData as md, NoMifData as nmd
Where md.problem = nmd.problem and md.instance = nmd.instance and md.SolverName = nmd.SolverName ;

Select AVG(diff), AVG(Impr), COUNT(*), AVG(MdOpt), AVG(NmdOpt) From
(
Select md.elapsedSecs - nmd.elapsedSecs as diff, md.elapsedSecs - nmd.elapsedSecs < 0 as Impr, md.Optimally as MdOpt, nmd.Optimally as NmdOpt
From MifData as md, NoMifData as nmd
Where md.problem = nmd.problem and md.instance = nmd.instance and md.SolverName = nmd.SolverName
);


text:
import "setimmediate";
import {Program} from "./runtime/dsl2";
import * as testUtil from "../test/util";
import "./parser/parser";

// let assert = {};
// function verify(assert:any, prog:Program, ins:any[], outs:any[]) {
//   prog.test(prog.nextTransactionId, ins);
// }

// function verifyIO(assert:any, progName:string, inputString:string, expecteds:testUtil.EAVRCTuple[][]) {
//   let inputs = testUtil.createInputs(inputString);
//   for(let input of inputs) {
//     prog.test(prog.nextTransactionId, input);
//     console.groupCollapsed("Expected");
//     console.info(testUtil.pprint(expecteds));
//     console.groupEnd();
//   }
// }

// let prog = new Program("test");

// import "./programs/flappy";
// import "./programs/compiler";
// import "./programs/hover";
// import "./programs/canvas-demo";
// import "./programs/shape-demo";
// import "./programs/ui-demo";
// import "./programs/editor-demo";


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreatePermissionsTable extends Migration {

	public function up()
	{
		Schema::create('permissions', function(Blueprint $table) {
			$table->increments('id');
			$table->string('name')->unique();
			$table->string('display_name');
            $table->integer('role_id')->unsigned();
			$table->timestamps();
		});
	}

	public function down()
	{
		Schema::drop('permissions');
	}
}


text:
package org.apache.gobblin.eventhub.writer;

import org.apache.gobblin.writer.SequentialBasedBatchAccumulator;

import java.util.Properties;

/**
 * Simply a ttl based batch accumulator for eventhub with string type
 */
public class EventhubBatchAccumulator extends SequentialBasedBatchAccumulator<String> {
  public EventhubBatchAccumulator (Properties properties) {
    super(properties);
  }

  public EventhubBatchAccumulator (long batchSizeLimit, long expireInMilliSecond, long capacity) {
    super (batchSizeLimit, expireInMilliSecond, capacity);
  }
}


text:
package org.adligo.tests4j_v1_tests.models.shared.reference_groups.jse.v1_6;

import org.adligo.tests4j.models.shared.reference_groups.jse.v1_6.JSE_1_6_UtilConcurrent;
import org.adligo.tests4j.shared.asserts.common.I_Asserts;
import org.adligo.tests4j.shared.asserts.reference.AllowedReferences;
import org.adligo.tests4j.shared.asserts.reference.I_ReferenceGroup;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j.system.shared.trials.Test;
import org.adligo.tests4j_tests.base_trials.I_CountType;
import org.adligo.tests4j_tests.base_trials.SourceFileCountingTrial;
import org.adligo.tests4j_tests.references_groups.Tests4J_JSE_v1_6_GwtReferenceGroup;

import java.util.Map;

@SourceFileScope (sourceClass=JSE_1_6_UtilConcurrent.class,minCoverage=91.0)
@AllowedReferences (groups={Tests4J_JSE_v1_6_GwtReferenceGroup.class})
public class JSE_1_6_UtilConcurrentTrial extends SourceFileCountingTrial {

  @Test
  public void testConstantLookup() {
    Map<String,String> map = JSE_1_6_UtilConcurrent.INSTANCE.getModelMap();
    assertEquals("BLOCKING_DEQUE",map.get("java.util.concurrent.BlockingDeque"));
    assertEquals("BLOCKING_QUEUE",map.get("java.util.concurrent.BlockingQueue"));
    assertEquals("CALLABLE",map.get("java.util.concurrent.Callable"));
    assertEquals("COMPLETION_SERVICE",map.get("java.util.concurrent.CompletionService"));
    assertEquals("CONCURRENT_MAP",map.get("java.util.concurrent.ConcurrentMap"));
    assertEquals("CONCURRENT_NAVIGABLE_MAP",map.get("java.util.concurrent.ConcurrentNavigableMap"));
    assertEquals("DELAYED",map.get("java.util.concurrent.Delayed"));
    assertEquals("EXECUTOR",map.get("java.util.concurrent.Executor"));
    assertEquals("EXECUTOR_SERVICE",map.get("java.util.concurrent.ExecutorService"));
    assertEquals("FUTURE",map.get("java.util.concurrent.Future"));
    assertEquals("REJECTED_EXECUTION_HANDLER",map.get("java.util.concurrent.RejectedExecutionHandler"));
    assertEquals("RUNNABLE_FUTURE",map.get("java.util.concurrent.RunnableFuture"));
    assertEquals("RUNNABLE_SCHEDULED_FUTURE",map.get("java.util.concurrent.RunnableScheduledFuture"));
    assertEquals("SCHEDULED_EXECUTOR_SERVICE",map.get("java.util.concurrent.ScheduledExecutorService"));
    assertEquals("SCHEDULED_FUTURE",map.get("java.util.concurrent.ScheduledFuture"));
    assertEquals("THREAD_FACTORY",map.get("java.util.concurrent.ThreadFactory"));
    assertEquals("ABSTRACT_EXECUTOR_SERVICE",map.get("java.util.concurrent.AbstractExecutorService"));
    assertEquals("ARRAY_BLOCKING_QUEUE",map.get("java.util.concurrent.ArrayBlockingQueue"));
    assertEquals("CONCURRENT_HASH_MAP",map.get("java.util.concurrent.ConcurrentHashMap"));
    assertEquals("CONCURRENT_LINKED_QUEUE",map.get("java.util.concurrent.ConcurrentLinkedQueue"));
    assertEquals("CONCURRENT_SKIP_LIST_MAP",map.get("java.util.concurrent.ConcurrentSkipListMap"));
    assertEquals("CONCURRENT_SKIP_LIST_SET",map.get("java.util.concurrent.ConcurrentSkipListSet"));
    assertEquals("COPY_ON_WRITE_ARRAY_LIST",map.get("java.util.concurrent.CopyOnWriteArrayList"));
    assertEquals("COPY_ON_WRITE_ARRAY_SET",map.get("java.util.concurrent.CopyOnWriteArraySet"));
    assertEquals("COUNT_DOWN_LATCH",map.get("java.util.concurrent.CountDownLatch"));
    assertEquals("CYCLIC_BARRIER",map.get("java.util.concurrent.CyclicBarrier"));
    assertEquals("DELAY_QUEUE",map.get("java.util.concurrent.DelayQueue"));
    assertEquals("EXCHANGER",map.get("java.util.concurrent.Exchanger"));
    assertEquals("EXECUTOR_COMPLETION_SERVICE",map.get("java.util.concurrent.ExecutorCompletionService"));
    assertEquals("EXECUTORS",map.get("java.util.concurrent.Executors"));
    assertEquals("FUTURE_TASK",map.get("java.util.concurrent.FutureTask"));
    assertEquals("LINKED_BLOCKING_DEQUE",map.get("java.util.concurrent.LinkedBlockingDeque"));
    assertEquals("LINKED_BLOCKING_QUEUE",map.get("java.util.concurrent.LinkedBlockingQueue"));
    assertEquals("PRIORITY_BLOCKING_QUEUE",map.get("java.util.concurrent.PriorityBlockingQueue"));
    assertEquals("SCHEDULED_THREAD_POOL_EXECUTOR",map.get("java.util.concurrent.ScheduledThreadPoolExecutor"));
    assertEquals("SEMAPHORE",map.get("java.util.concurrent.Semaphore"));
    assertEquals("SYNCHRONOUS_QUEUE",map.get("java.util.concurrent.SynchronousQueue"));
    assertEquals("THREAD_POOL_EXECUTOR",map.get("java.util.concurrent.ThreadPoolExecutor"));
    assertEquals("THREAD_POOL_EXECUTOR",map.get("java.util.concurrent.ThreadPoolExecutor"));
    assertEquals("ABORT_POLICY",map.get("java.util.concurrent.ThreadPoolExecutor$AbortPolicy"));
    assertEquals("CALLER_RUNS_POLICY",map.get("java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"));
    assertEquals("DISCARD_OLDEST_POLICY",map.get("java.util.concurrent.ThreadPoolExecutor$DiscardOldestPolicy"));
    assertEquals("DISCARD_POLICY",map.get("java.util.concurrent.ThreadPoolExecutor$DiscardPolicy"));
    assertEquals("TIME_UNIT",map.get("java.util.concurrent.TimeUnit"));
    assertEquals("BROKEN_BARRIER_EXCEPTION",map.get("java.util.concurrent.BrokenBarrierException"));
    assertEquals("CANCELLATION_EXCEPTION",map.get("java.util.concurrent.CancellationException"));
    assertEquals("EXECUTION_EXCEPTION",map.get("java.util.concurrent.ExecutionException"));
    assertEquals("REJECTED_EXECUTION_EXCEPTION",map.get("java.util.concurrent.RejectedExecutionException"));
    assertEquals("TIMEOUT_EXCEPTION",map.get("java.util.concurrent.TimeoutException"));

    assertEquals("BLOCKING_DEQUE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.BlockingDeque"));
    assertEquals("BLOCKING_QUEUE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.BlockingQueue"));
    assertEquals("CALLABLE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.Callable"));
    assertEquals("COMPLETION_SERVICE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.CompletionService"));
    assertEquals("CONCURRENT_MAP",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ConcurrentMap"));
    assertEquals("CONCURRENT_NAVIGABLE_MAP",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ConcurrentNavigableMap"));
    assertEquals("DELAYED",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.Delayed"));
    assertEquals("EXECUTOR",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.Executor"));
    assertEquals("EXECUTOR_SERVICE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ExecutorService"));
    assertEquals("FUTURE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.Future"));
    assertEquals("REJECTED_EXECUTION_HANDLER",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.RejectedExecutionHandler"));
    assertEquals("RUNNABLE_FUTURE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.RunnableFuture"));
    assertEquals("RUNNABLE_SCHEDULED_FUTURE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.RunnableScheduledFuture"));
    assertEquals("SCHEDULED_EXECUTOR_SERVICE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ScheduledExecutorService"));
    assertEquals("SCHEDULED_FUTURE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ScheduledFuture"));
    assertEquals("THREAD_FACTORY",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ThreadFactory"));
    assertEquals("ABSTRACT_EXECUTOR_SERVICE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.AbstractExecutorService"));
    assertEquals("ARRAY_BLOCKING_QUEUE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ArrayBlockingQueue"));
    assertEquals("CONCURRENT_HASH_MAP",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ConcurrentHashMap"));
    assertEquals("CONCURRENT_LINKED_QUEUE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ConcurrentLinkedQueue"));
    assertEquals("CONCURRENT_SKIP_LIST_MAP",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ConcurrentSkipListMap"));
    assertEquals("CONCURRENT_SKIP_LIST_SET",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ConcurrentSkipListSet"));
    assertEquals("COPY_ON_WRITE_ARRAY_LIST",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.CopyOnWriteArrayList"));
    assertEquals("COPY_ON_WRITE_ARRAY_SET",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.CopyOnWriteArraySet"));
    assertEquals("COUNT_DOWN_LATCH",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.CountDownLatch"));
    assertEquals("CYCLIC_BARRIER",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.CyclicBarrier"));
    assertEquals("DELAY_QUEUE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.DelayQueue"));
    assertEquals("EXCHANGER",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.Exchanger"));
    assertEquals("EXECUTOR_COMPLETION_SERVICE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ExecutorCompletionService"));
    assertEquals("EXECUTORS",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.Executors"));
    assertEquals("FUTURE_TASK",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.FutureTask"));
    assertEquals("LINKED_BLOCKING_DEQUE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.LinkedBlockingDeque"));
    assertEquals("LINKED_BLOCKING_QUEUE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.LinkedBlockingQueue"));
    assertEquals("PRIORITY_BLOCKING_QUEUE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.PriorityBlockingQueue"));
    assertEquals("SCHEDULED_THREAD_POOL_EXECUTOR",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ScheduledThreadPoolExecutor"));
    assertEquals("SEMAPHORE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.Semaphore"));
    assertEquals("SYNCHRONOUS_QUEUE",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.SynchronousQueue"));
    assertEquals("THREAD_POOL_EXECUTOR",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ThreadPoolExecutor"));
    assertEquals("THREAD_POOL_EXECUTOR",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ThreadPoolExecutor"));
    assertEquals("ABORT_POLICY",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ThreadPoolExecutor$AbortPolicy"));
    assertEquals("CALLER_RUNS_POLICY",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"));
    assertEquals("DISCARD_OLDEST_POLICY",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ThreadPoolExecutor$DiscardOldestPolicy"));
    assertEquals("DISCARD_POLICY",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ThreadPoolExecutor$DiscardPolicy"));
    assertEquals("TIME_UNIT",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.TimeUnit"));
    assertEquals("BROKEN_BARRIER_EXCEPTION",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.BrokenBarrierException"));
    assertEquals("CANCELLATION_EXCEPTION",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.CancellationException"));
    assertEquals("EXECUTION_EXCEPTION",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.ExecutionException"));
    assertEquals("REJECTED_EXECUTION_EXCEPTION",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.RejectedExecutionException"));
    assertEquals("TIMEOUT_EXCEPTION",JSE_1_6_UtilConcurrent.INSTANCE.getConstantName("java.util.concurrent.TimeoutException"));
  }

	@Test
	public void testSingletonClasses() {
		delegateSingletonClassAsserts(this, JSE_1_6_UtilConcurrent.INSTANCE);
	}

	public static void delegateSingletonClassAsserts(I_Asserts asserts, I_ReferenceGroup dg) {
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.BlockingDeque"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.BlockingQueue"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.Callable"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.CompletionService"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ConcurrentMap"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ConcurrentNavigableMap"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.Delayed"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.Executor"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ExecutorService"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.Future"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.RejectedExecutionHandler"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.RunnableFuture"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.RunnableScheduledFuture"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ScheduledExecutorService"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ScheduledFuture"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ThreadFactory"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.AbstractExecutorService"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ArrayBlockingQueue"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ConcurrentHashMap"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ConcurrentLinkedQueue"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ConcurrentSkipListMap"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ConcurrentSkipListSet"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.CopyOnWriteArrayList"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.CopyOnWriteArraySet"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.CountDownLatch"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.CyclicBarrier"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.DelayQueue"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.Exchanger"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ExecutorCompletionService"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.Executors"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.FutureTask"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.LinkedBlockingDeque"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.LinkedBlockingQueue"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.PriorityBlockingQueue"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ScheduledThreadPoolExecutor"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.Semaphore"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.SynchronousQueue"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ThreadPoolExecutor"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ThreadPoolExecutor"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ThreadPoolExecutor$AbortPolicy"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ThreadPoolExecutor$DiscardOldestPolicy"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ThreadPoolExecutor$DiscardPolicy"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.TimeUnit"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.BrokenBarrierException"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.CancellationException"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.ExecutionException"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.RejectedExecutionException"));
    asserts.assertTrue(dg.isInGroup("java.util.concurrent.TimeoutException"));
	}

	@Override
	public int getTests(I_CountType type) {
		return super.getTests(type, 2, true);
	}

	@Override
	public int getAsserts(I_CountType type) {
		int thisAsserts = 147;
		//code coverage and circular dependencies +
		//custom afterTrialTests
		//+ see above
		int thisAfterAsserts = 3;
		if (type.isFromMetaWithCoverage()) {
			return super.getAsserts(type, thisAsserts + thisAfterAsserts);
		} else {
			return super.getAsserts(type, thisAsserts);
		}
	}

	@Override
	public int getUniqueAsserts(I_CountType type) {
		int thisUniqueAsserts = 49;
		//code coverage and circular dependencies +
		//custom afterTrialTests
		//+ see above
		int thisAfterUniqueAsserts = 3;
		if (type.isFromMetaWithCoverage()) {
			//code coverage and circular dependencies +
			//custom afterTrialTests
			return super.getUniqueAsserts(type, thisUniqueAsserts + thisAfterUniqueAsserts);
		} else {
			return super.getUniqueAsserts(type, thisUniqueAsserts);
		}
	}

}


text:
package afirsraftgarrier.demoandroid.base;

/**
 * Created by AfirSraftGarrier on 2016/11/11 0011.
 */

public interface DemoDescriper {
    String getDemoName();

    Class getDemoClass();

    String getDemoDescription();
}


text:
This is a multi-module project for CQL java libraries and proof-of-concept applications.
It contains the following sub-projects:

* **cql:** generates and builds Java lexers, parsers, listeners, and visitors using the CQL ANTLR4 grammar
* **quick:** generates and builds Java classes based on the QUICK XML schema
* **elm:** generates and builds Java classes based on the ELM XML schema
* **cql-to-elm:** generates Expression Logical Model (ELM) XML from CQL source

# Building the Project

This project uses the [Gradle](http://www.gradle.org/) build system.  A gradle wrapper, which automatically downloads
and uses an instance of gradle, is provided for convenience.  To build the project, install the [Java SE Development
Kit 8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) (a.k.a. JDK 1.8), clone this
repository, then execute this command from within this directory:

    ./gradlew build

This will generate and build the ANTLR4 CQL artifacts, the JAXB QUICK artifacts, and the JAXB ELM artifacts.
It will also build and test the corresponding code libraries and applications.

To clean up the build artifacts:

    ./gradlew clean

# Generating IDE Projects

You can generate an IDE project for IntelliJ IDEa:

    ./gradlew idea

In addition to creating project modules for cql, quick, elm, and cql-to-elm, this will also import project
modules for the CQL grammar and examples.

# Executing the Sample Code

You can execute the sample code using the `gradlew` command or a script generated by gradle.

To execute the sample code using `gradlew`, you must execute the `run` command, using the project-specific
path.  The following are current possibilities:

    ./gradlew :cql:run
    ./gradlew :cql-to-elm:run
    ./gradlew :tools:cql-parsetree:run

To execute the sample code using a script generated by gradle, first generate the scripts:

    ./gradlew installApp

Then execute the generated script (optionally passing in an argument).  The following example executes
the sample cql code with the path to a CQL file as an argument:

    ./cql/build/install/cql/bin/cql ../../Examples/ChlamydiaScreening_CQM.cql

You can also execute the cql-parsetree tool in a similar way:

    ./tools/cql-parsetree/build/install/cql-parsetree/bin/cql-parsetree ../../Examples/ChlamydiaScreening_CQM.cql

## Generate an ELM Representation of CQL Logic

To generate an ELM representation of CQL logic, build and execute the cql-to-elm app:

    ./gradlew :cql-to-elm:installApp
    ./cql-to-elm/build/install/cql-to-elm/bin/cql-to-elm --input ../../Examples/ChlamydiaScreening_CQM.cql

The following options are supported:

* `--input` or `-i`: Specify the input CQL file (REQUIRED).
* `--output` or `-o`: Specify the output file.  If not specified, the output file will have the
  same base name and location as the input file.  If only a directory is specified, the output
  file will have the same base name as the input file and be written to the requested directory.
* `--format` or `-f`: Output as `XML` (default), `JSON`, or `COFFEE`.
* `--date-range-optimization` or `-d`: Refactor simple during clauses into the ClinicalRequest.
* `--annotations` or `-a`: Include annotations in the output (work in progress).
* `--stdout` or `-s`: Write output to the console instead of a file.


text:
#ifndef GRATE_DISASM_H
#define GRATE_DISASM_H 1

#include "asm.h"

struct disasm_state {
	union {
		vpe_instr128 vpe_instr[256];
		uint32_t vpe_words[1024];
	};
	unsigned int vpe_words_nb;

	union {
		link_instr lnk_instr[32];
		uint32_t linker_words[64];
	};
	unsigned int linker_inst_nb;

	pseq_instr pseq_instructions[64];
	unsigned int pseq_words_nb;

	instr_sched mfu_sched[64];
	unsigned int mfu_sched_words_nb;

	union {
		mfu_instr mfu_instructions[64];
		uint32_t mfu_words[128];

	};
	unsigned int mfu_words_nb;

	tex_instr tex_instructions[64];
	unsigned int tex_words_nb;

	union {
		union fragment_alu_instruction alu_instructions[256];
		uint32_t alu_words[512];
	};
	unsigned int alu_words_nb;

	uint32_t alu_complements[64];
	unsigned int alu_complements_nb;

	alu_instr_sched_t114 alu_sched[64];
	unsigned int alu_sched_words_nb;

	dw_instr dw_instructions[64];
	unsigned int dw_words_nb;
};

void disasm_reset(struct disasm_state *d);
void disasm_write_reg(void *opaque, uint32_t host1x_class,
		      uint32_t offset, uint32_t value);
void disasm_dump(struct disasm_state *d);

#endif


text:
layout: post
date: 2016-05-03
title: "Pronovias NICKY Short Sleeves Sweep/Brush Train Mermaid/Trumpet"
category: Pronovias
tags: [Pronovias,Mermaid/Trumpet,Queen Anne,Sweep/Brush Train,Short Sleeves]
---
### Pronovias NICKY
Just **$319.99**
###   Short Sleeves Sweep/Brush Train Mermaid/Trumpet

BRANDS	Pronovias

Silhouette	Mermaid/Trumpet

Neckline	Queen Anne

Hemline/Train	Sweep/Brush Train

Sleeve	Short Sleeves

Buy it: [https://www.readybrides.com/en/pronovias/4431-pronovias-nicky.html](https://www.readybrides.com/en/pronovias/4431-pronovias-nicky.html)


text:
typedef struct BWMsg {
  uint32_t bw;
  struct timeval recv_time;
  struct sockaddr_in addr;
  MYSLIST_ENTRY(BWMsg) entries;
} BWMsg;

MYSLIST_HEAD(BandwidthMessages, BWMsg);

void bwmsg_received(BWMsg * bw_message);

struct BandwidthMessages get_bwmsg_list(void);

void send_bwmsg (struct sockaddr_in host, uint32_t bw);

#endif


text:
<?php

namespace EnliteSeo\Options;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class GlobalOptionsFactory implements FactoryInterface
{

    /**
     * @
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config = $serviceLocator->get('Config');
        return new GlobalOptions(
            isset($config['EnliteSeo'])
                ? $config['EnliteSeo']
                : []
        );
    }

}


text:
package com.esotericsoftware.kryonet;

import java.io.IOException;
import java.net.InetAddress;

public class DiscoverHostTest extends KryoNetTestCase {
	public void testBroadcast () throws IOException {
		// This server exists solely to reply to Client#discoverHost.
		// It wouldn't be needed if the real server was using UDP.
		final Server broadcastServer = new Server();
		startEndPoint(broadcastServer);
		broadcastServer.bind(0, udpPort);

		final Server server = new Server();
		startEndPoint(server);
		server.bind(54555);
		server.addListener(new Listener() {
			public void disconnected (Connection connection) {
				broadcastServer.stop();
				server.stop();
			}
		});

		// ----

		Client client = new Client();
		InetAddress host = client.discoverHost(udpPort, 2000);
		if (host == null) {
			stopEndPoints();
			fail("No servers found.");
			return;
		}

		startEndPoint(client);
		client.connect(2000, host, tcpPort);
		client.stop();

		waitForThreads();
	}
}