code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
// Copyright 2012 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package provisiontest
import (
"fmt"
"io"
"io/ioutil"
"net/url"
"sort"
"sync"
"sync/atomic"
"time"
docker "github.com/fsouza/go-dockerclient"
"github.com/pkg/errors"
"github.com/tsuru/tsuru/action"
"github.com/tsuru/tsuru/app/bind"
"github.com/tsuru/tsuru/event"
"github.com/tsuru/tsuru/net"
"github.com/tsuru/tsuru/provision"
"github.com/tsuru/tsuru/provision/dockercommon"
"github.com/tsuru/tsuru/quota"
"github.com/tsuru/tsuru/router/routertest"
appTypes "github.com/tsuru/tsuru/types/app"
)
var (
ProvisionerInstance *FakeProvisioner
errNotProvisioned = &provision.Error{Reason: "App is not provisioned."}
uniqueIpCounter int32 = 0
_ provision.NodeProvisioner = &FakeProvisioner{}
_ provision.Provisioner = &FakeProvisioner{}
_ provision.App = &FakeApp{}
_ bind.App = &FakeApp{}
)
const fakeAppImage = "app-image"
func init() {
ProvisionerInstance = NewFakeProvisioner()
provision.Register("fake", func() (provision.Provisioner, error) {
return ProvisionerInstance, nil
})
}
// Fake implementation for provision.App.
type FakeApp struct {
name string
cname []string
IP string
platform string
units []provision.Unit
logs []string
logMut sync.Mutex
Commands []string
Memory int64
Swap int64
CpuShare int
commMut sync.Mutex
Deploys uint
env map[string]bind.EnvVar
bindCalls []*provision.Unit
bindLock sync.Mutex
serviceEnvs []bind.ServiceEnvVar
serviceLock sync.Mutex
Pool string
UpdatePlatform bool
TeamOwner string
Teams []string
quota.Quota
}
func NewFakeApp(name, platform string, units int) *FakeApp {
app := FakeApp{
name: name,
platform: platform,
units: make([]provision.Unit, units),
Quota: quota.Unlimited,
Pool: "test-default",
}
routertest.FakeRouter.AddBackend(&app)
namefmt := "%s-%d"
for i := 0; i < units; i++ {
val := atomic.AddInt32(&uniqueIpCounter, 1)
app.units[i] = provision.Unit{
ID: fmt.Sprintf(namefmt, name, i),
Status: provision.StatusStarted,
IP: fmt.Sprintf("10.10.10.%d", val),
Address: &url.URL{
Scheme: "http",
Host: fmt.Sprintf("10.10.10.%d:%d", val, val),
},
}
}
return &app
}
func (a *FakeApp) GetMemory() int64 {
return a.Memory
}
func (a *FakeApp) GetSwap() int64 {
return a.Swap
}
func (a *FakeApp) GetCpuShare() int {
return a.CpuShare
}
func (a *FakeApp) GetTeamsName() []string {
return a.Teams
}
func (a *FakeApp) HasBind(unit *provision.Unit) bool {
a.bindLock.Lock()
defer a.bindLock.Unlock()
for _, u := range a.bindCalls {
if u.ID == unit.ID {
return true
}
}
return false
}
func (a *FakeApp) BindUnit(unit *provision.Unit) error {
a.bindLock.Lock()
defer a.bindLock.Unlock()
a.bindCalls = append(a.bindCalls, unit)
return nil
}
func (a *FakeApp) UnbindUnit(unit *provision.Unit) error {
a.bindLock.Lock()
defer a.bindLock.Unlock()
index := -1
for i, u := range a.bindCalls {
if u.ID == unit.ID {
index = i
break
}
}
if index < 0 {
return errors.New("not bound")
}
length := len(a.bindCalls)
a.bindCalls[index] = a.bindCalls[length-1]
a.bindCalls = a.bindCalls[:length-1]
return nil
}
func (a *FakeApp) GetQuota() quota.Quota {
return a.Quota
}
func (a *FakeApp) SetQuotaInUse(inUse int) error {
if !a.Quota.Unlimited() && inUse > a.Quota.Limit {
return "a.QuotaExceededError{
Requested: uint(inUse),
Available: uint(a.Quota.Limit),
}
}
a.Quota.InUse = inUse
return nil
}
func (a *FakeApp) GetCname() []string {
return a.cname
}
func (a *FakeApp) GetServiceEnvs() []bind.ServiceEnvVar {
a.serviceLock.Lock()
defer a.serviceLock.Unlock()
return a.serviceEnvs
}
func (a *FakeApp) AddInstance(instanceArgs bind.AddInstanceArgs) error {
a.serviceLock.Lock()
defer a.serviceLock.Unlock()
a.serviceEnvs = append(a.serviceEnvs, instanceArgs.Envs...)
if instanceArgs.Writer != nil {
instanceArgs.Writer.Write([]byte("add instance"))
}
return nil
}
func (a *FakeApp) RemoveInstance(instanceArgs bind.RemoveInstanceArgs) error {
a.serviceLock.Lock()
defer a.serviceLock.Unlock()
lenBefore := len(a.serviceEnvs)
for i := 0; i < len(a.serviceEnvs); i++ {
se := a.serviceEnvs[i]
if se.ServiceName == instanceArgs.ServiceName && se.InstanceName == instanceArgs.InstanceName {
a.serviceEnvs = append(a.serviceEnvs[:i], a.serviceEnvs[i+1:]...)
i--
}
}
if len(a.serviceEnvs) == lenBefore {
return errors.New("instance not found")
}
if instanceArgs.Writer != nil {
instanceArgs.Writer.Write([]byte("remove instance"))
}
return nil
}
func (a *FakeApp) Logs() []string {
a.logMut.Lock()
defer a.logMut.Unlock()
logs := make([]string, len(a.logs))
copy(logs, a.logs)
return logs
}
func (a *FakeApp) HasLog(source, unit, message string) bool {
log := source + unit + message
a.logMut.Lock()
defer a.logMut.Unlock()
for _, l := range a.logs {
if l == log {
return true
}
}
return false
}
func (a *FakeApp) GetCommands() []string {
a.commMut.Lock()
defer a.commMut.Unlock()
return a.Commands
}
func (a *FakeApp) Log(message, source, unit string) error {
a.logMut.Lock()
a.logs = append(a.logs, source+unit+message)
a.logMut.Unlock()
return nil
}
func (a *FakeApp) GetName() string {
return a.name
}
func (a *FakeApp) GetPool() string {
return a.Pool
}
func (a *FakeApp) GetPlatform() string {
return a.platform
}
func (a *FakeApp) GetDeploys() uint {
return a.Deploys
}
func (a *FakeApp) GetTeamOwner() string {
return a.TeamOwner
}
func (a *FakeApp) Units() ([]provision.Unit, error) {
return a.units, nil
}
func (a *FakeApp) AddUnit(u provision.Unit) {
a.units = append(a.units, u)
}
func (a *FakeApp) SetEnv(env bind.EnvVar) {
if a.env == nil {
a.env = map[string]bind.EnvVar{}
}
a.env[env.Name] = env
}
func (a *FakeApp) SetEnvs(setEnvs bind.SetEnvArgs) error {
for _, env := range setEnvs.Envs {
a.SetEnv(env)
}
return nil
}
func (a *FakeApp) UnsetEnvs(unsetEnvs bind.UnsetEnvArgs) error {
for _, env := range unsetEnvs.VariableNames {
delete(a.env, env)
}
return nil
}
func (a *FakeApp) GetLock() provision.AppLock {
return nil
}
func (a *FakeApp) GetUnits() ([]bind.Unit, error) {
units := make([]bind.Unit, len(a.units))
for i := range a.units {
units[i] = &a.units[i]
}
return units, nil
}
func (a *FakeApp) Envs() map[string]bind.EnvVar {
return a.env
}
func (a *FakeApp) Run(cmd string, w io.Writer, args provision.RunArgs) error {
a.commMut.Lock()
a.Commands = append(a.Commands, fmt.Sprintf("ran %s", cmd))
a.commMut.Unlock()
return nil
}
func (a *FakeApp) GetUpdatePlatform() bool {
return a.UpdatePlatform
}
func (app *FakeApp) GetRouters() []appTypes.AppRouter {
return []appTypes.AppRouter{{Name: "fake"}}
}
func (app *FakeApp) GetAddresses() ([]string, error) {
addr, err := routertest.FakeRouter.Addr(app.GetName())
if err != nil {
return nil, err
}
return []string{addr}, nil
}
type Cmd struct {
Cmd string
Args []string
App provision.App
}
type failure struct {
method string
err error
}
// Fake implementation for provision.Provisioner.
type FakeProvisioner struct {
Name string
cmds []Cmd
cmdMut sync.Mutex
outputs chan []byte
failures chan failure
apps map[string]provisionedApp
mut sync.RWMutex
shells map[string][]provision.ShellOptions
shellMut sync.Mutex
nodes map[string]FakeNode
nodeContainers map[string]int
}
func NewFakeProvisioner() *FakeProvisioner {
p := FakeProvisioner{Name: "fake"}
p.outputs = make(chan []byte, 8)
p.failures = make(chan failure, 8)
p.apps = make(map[string]provisionedApp)
p.shells = make(map[string][]provision.ShellOptions)
p.nodes = make(map[string]FakeNode)
p.nodeContainers = make(map[string]int)
return &p
}
func (p *FakeProvisioner) getError(method string) error {
select {
case fail := <-p.failures:
if fail.method == method {
return fail.err
}
p.failures <- fail
default:
}
return nil
}
type FakeNode struct {
ID string
Addr string
PoolName string
Meta map[string]string
status string
p *FakeProvisioner
failures int
hasSuccess bool
}
func (n *FakeNode) IaaSID() string {
return n.ID
}
func (n *FakeNode) Pool() string {
return n.PoolName
}
func (n *FakeNode) Address() string {
return n.Addr
}
func (n *FakeNode) Metadata() map[string]string {
return n.Meta
}
func (n *FakeNode) MetadataNoPrefix() map[string]string {
return n.Meta
}
func (n *FakeNode) Units() ([]provision.Unit, error) {
n.p.mut.Lock()
defer n.p.mut.Unlock()
return n.unitsLocked()
}
func (n *FakeNode) unitsLocked() ([]provision.Unit, error) {
var units []provision.Unit
for _, a := range n.p.apps {
for _, u := range a.units {
if net.URLToHost(u.Address.String()) == net.URLToHost(n.Addr) {
units = append(units, u)
}
}
}
return units, nil
}
func (n *FakeNode) Status() string {
return n.status
}
func (n *FakeNode) FailureCount() int {
return n.failures
}
func (n *FakeNode) HasSuccess() bool {
return n.hasSuccess
}
func (n *FakeNode) ResetFailures() {
n.failures = 0
}
func (n *FakeNode) Provisioner() provision.NodeProvisioner {
return n.p
}
func (n *FakeNode) SetHealth(failures int, hasSuccess bool) {
n.failures = failures
n.hasSuccess = hasSuccess
}
func (p *FakeProvisioner) AddNode(opts provision.AddNodeOptions) error {
p.mut.Lock()
defer p.mut.Unlock()
if err := p.getError("AddNode"); err != nil {
return err
}
if err := p.getError("AddNode:" + opts.Address); err != nil {
return err
}
metadata := opts.Metadata
if metadata == nil {
metadata = map[string]string{}
}
if _, ok := p.nodes[opts.Address]; ok {
return errors.New("fake node already exists")
}
p.nodes[opts.Address] = FakeNode{
ID: opts.IaaSID,
Addr: opts.Address,
PoolName: opts.Pool,
Meta: metadata,
p: p,
status: "enabled",
}
return nil
}
func (p *FakeProvisioner) GetNode(address string) (provision.Node, error) {
p.mut.RLock()
defer p.mut.RUnlock()
if err := p.getError("GetNode"); err != nil {
return nil, err
}
if n, ok := p.nodes[address]; ok {
return &n, nil
}
return nil, provision.ErrNodeNotFound
}
func (p *FakeProvisioner) RemoveNode(opts provision.RemoveNodeOptions) error {
p.mut.Lock()
defer p.mut.Unlock()
if err := p.getError("RemoveNode"); err != nil {
return err
}
_, ok := p.nodes[opts.Address]
if !ok {
return provision.ErrNodeNotFound
}
delete(p.nodes, opts.Address)
if opts.Writer != nil {
if opts.Rebalance {
opts.Writer.Write([]byte("rebalancing..."))
p.rebalanceNodesLocked(provision.RebalanceNodesOptions{
Force: true,
})
}
opts.Writer.Write([]byte("remove done!"))
}
return nil
}
func (p *FakeProvisioner) UpdateNode(opts provision.UpdateNodeOptions) error {
p.mut.Lock()
defer p.mut.Unlock()
if err := p.getError("UpdateNode"); err != nil {
return err
}
n, ok := p.nodes[opts.Address]
if !ok {
return provision.ErrNodeNotFound
}
if opts.Pool != "" {
n.PoolName = opts.Pool
}
if opts.Metadata != nil {
n.Meta = opts.Metadata
}
if opts.Enable {
n.status = "enabled"
}
if opts.Disable {
n.status = "disabled"
}
p.nodes[opts.Address] = n
return nil
}
type nodeList []provision.Node
func (l nodeList) Len() int { return len(l) }
func (l nodeList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func (l nodeList) Less(i, j int) bool { return l[i].Address() < l[j].Address() }
func (p *FakeProvisioner) ListNodes(addressFilter []string) ([]provision.Node, error) {
p.mut.RLock()
defer p.mut.RUnlock()
if err := p.getError("ListNodes"); err != nil {
return nil, err
}
var result []provision.Node
if addressFilter != nil {
result = make([]provision.Node, 0, len(addressFilter))
for _, a := range addressFilter {
n := p.nodes[a]
result = append(result, &n)
}
} else {
result = make([]provision.Node, 0, len(p.nodes))
for a := range p.nodes {
n := p.nodes[a]
result = append(result, &n)
}
}
sort.Sort(nodeList(result))
return result, nil
}
func (p *FakeProvisioner) NodeForNodeData(nodeData provision.NodeStatusData) (provision.Node, error) {
return provision.FindNodeByAddrs(p, nodeData.Addrs)
}
func (p *FakeProvisioner) RebalanceNodes(opts provision.RebalanceNodesOptions) (bool, error) {
p.mut.Lock()
defer p.mut.Unlock()
return p.rebalanceNodesLocked(opts)
}
func (p *FakeProvisioner) rebalanceNodesLocked(opts provision.RebalanceNodesOptions) (bool, error) {
if err := p.getError("RebalanceNodes"); err != nil {
return true, err
}
var w io.Writer
if opts.Event == nil {
w = ioutil.Discard
} else {
w = opts.Event
}
fmt.Fprintf(w, "rebalancing - dry: %v, force: %v\n", opts.Dry, opts.Force)
if len(opts.AppFilter) != 0 {
fmt.Fprintf(w, "filtering apps: %v\n", opts.AppFilter)
}
if len(opts.MetadataFilter) != 0 {
fmt.Fprintf(w, "filtering metadata: %v\n", opts.MetadataFilter)
}
if opts.Pool != "" {
fmt.Fprintf(w, "filtering pool: %v\n", opts.Pool)
}
if len(p.nodes) == 0 || opts.Dry {
return true, nil
}
max := 0
min := -1
var nodes []FakeNode
for _, n := range p.nodes {
nodes = append(nodes, n)
units, err := n.unitsLocked()
if err != nil {
return true, err
}
unitCount := len(units)
if unitCount > max {
max = unitCount
}
if min == -1 || unitCount < min {
min = unitCount
}
}
if max-min < 2 && !opts.Force {
return false, nil
}
gi := 0
for _, a := range p.apps {
nodeIdx := 0
for i := range a.units {
u := &a.units[i]
firstIdx := nodeIdx
var hostAddr string
for {
idx := nodeIdx
nodeIdx = (nodeIdx + 1) % len(nodes)
if nodes[idx].Pool() == a.app.GetPool() {
hostAddr = net.URLToHost(nodes[idx].Address())
break
}
if nodeIdx == firstIdx {
return true, errors.Errorf("unable to find node for pool %s", a.app.GetPool())
}
}
u.IP = hostAddr
u.Address = &url.URL{
Scheme: "http",
Host: fmt.Sprintf("%s:%d", hostAddr, gi),
}
gi++
}
}
return true, nil
}
// Restarts returns the number of restarts for a given app.
func (p *FakeProvisioner) Restarts(a provision.App, process string) int {
p.mut.RLock()
defer p.mut.RUnlock()
return p.apps[a.GetName()].restarts[process]
}
// Starts returns the number of starts for a given app.
func (p *FakeProvisioner) Starts(app provision.App, process string) int {
p.mut.RLock()
defer p.mut.RUnlock()
return p.apps[app.GetName()].starts[process]
}
// Stops returns the number of stops for a given app.
func (p *FakeProvisioner) Stops(app provision.App, process string) int {
p.mut.RLock()
defer p.mut.RUnlock()
return p.apps[app.GetName()].stops[process]
}
// Sleeps returns the number of sleeps for a given app.
func (p *FakeProvisioner) Sleeps(app provision.App, process string) int {
p.mut.RLock()
defer p.mut.RUnlock()
return p.apps[app.GetName()].sleeps[process]
}
func (p *FakeProvisioner) CustomData(app provision.App) map[string]interface{} {
p.mut.RLock()
defer p.mut.RUnlock()
return p.apps[app.GetName()].lastData
}
// Shells return all shell calls to the given unit.
func (p *FakeProvisioner) Shells(unit string) []provision.ShellOptions {
p.shellMut.Lock()
defer p.shellMut.Unlock()
return p.shells[unit]
}
// Returns the number of calls to restart.
// GetCmds returns a list of commands executed in an app. If you don't specify
// the command (an empty string), it will return all commands executed in the
// given app.
func (p *FakeProvisioner) GetCmds(cmd string, app provision.App) []Cmd {
var cmds []Cmd
p.cmdMut.Lock()
for _, c := range p.cmds {
if (cmd == "" || c.Cmd == cmd) && app.GetName() == c.App.GetName() {
cmds = append(cmds, c)
}
}
p.cmdMut.Unlock()
return cmds
}
// Provisioned checks whether the given app has been provisioned.
func (p *FakeProvisioner) Provisioned(app provision.App) bool {
p.mut.RLock()
defer p.mut.RUnlock()
_, ok := p.apps[app.GetName()]
return ok
}
func (p *FakeProvisioner) GetUnits(app provision.App) []provision.Unit {
p.mut.RLock()
pApp := p.apps[app.GetName()]
p.mut.RUnlock()
return pApp.units
}
// GetAppFromUnitID returns an app from unitID
func (p *FakeProvisioner) GetAppFromUnitID(unitID string) (provision.App, error) {
p.mut.RLock()
defer p.mut.RUnlock()
for _, a := range p.apps {
for _, u := range a.units {
if u.GetID() == unitID {
return a.app, nil
}
}
}
return nil, errors.New("app not found")
}
// PrepareOutput sends the given slice of bytes to a queue of outputs.
//
// Each prepared output will be used in the ExecuteCommand. It might be sent to
// the standard output or standard error. See ExecuteCommand docs for more
// details.
func (p *FakeProvisioner) PrepareOutput(b []byte) {
p.outputs <- b
}
// PrepareFailure prepares a failure for the given method name.
//
// For instance, PrepareFailure("GitDeploy", errors.New("GitDeploy failed")) will
// cause next Deploy call to return the given error. Multiple calls to this
// method will enqueue failures, i.e. three calls to
// PrepareFailure("GitDeploy"...) means that the three next GitDeploy call will
// fail.
func (p *FakeProvisioner) PrepareFailure(method string, err error) {
p.failures <- failure{method, err}
}
// Reset cleans up the FakeProvisioner, deleting all apps and their data. It
// also deletes prepared failures and output. It's like calling
// NewFakeProvisioner again, without all the allocations.
func (p *FakeProvisioner) Reset() {
p.cmdMut.Lock()
p.cmds = nil
p.cmdMut.Unlock()
p.mut.Lock()
p.apps = make(map[string]provisionedApp)
p.mut.Unlock()
p.shellMut.Lock()
p.shells = make(map[string][]provision.ShellOptions)
p.shellMut.Unlock()
p.mut.Lock()
p.nodes = make(map[string]FakeNode)
p.mut.Unlock()
uniqueIpCounter = 0
p.nodeContainers = make(map[string]int)
for {
select {
case <-p.outputs:
case <-p.failures:
default:
return
}
}
}
func (p *FakeProvisioner) Swap(app1, app2 provision.App, cnameOnly bool) error {
return routertest.FakeRouter.Swap(app1.GetName(), app2.GetName(), cnameOnly)
}
func (p *FakeProvisioner) Deploy(app provision.App, img string, evt *event.Event) (string, error) {
if err := p.getError("Deploy"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
pApp.image = img
evt.Write([]byte("Builder deploy called"))
p.apps[app.GetName()] = pApp
return fakeAppImage, nil
}
func (p *FakeProvisioner) GetClient(app provision.App) (provision.BuilderDockerClient, error) {
for _, node := range p.nodes {
client, err := docker.NewClient(node.Addr)
if err != nil {
return nil, err
}
return &dockercommon.PullAndCreateClient{Client: client}, nil
}
return nil, errors.New("No node found")
}
func (p *FakeProvisioner) CleanImage(appName, imgName string) error {
for _, node := range p.nodes {
c, err := docker.NewClient(node.Addr)
if err != nil {
return err
}
err = c.RemoveImage(imgName)
if err != nil && err != docker.ErrNoSuchImage {
return err
}
}
return nil
}
func (p *FakeProvisioner) ArchiveDeploy(app provision.App, archiveURL string, evt *event.Event) (string, error) {
if err := p.getError("ArchiveDeploy"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
evt.Write([]byte("Archive deploy called"))
pApp.lastArchive = archiveURL
p.apps[app.GetName()] = pApp
return fakeAppImage, nil
}
func (p *FakeProvisioner) UploadDeploy(app provision.App, file io.ReadCloser, fileSize int64, build bool, evt *event.Event) (string, error) {
if err := p.getError("UploadDeploy"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
evt.Write([]byte("Upload deploy called"))
pApp.lastFile = file
p.apps[app.GetName()] = pApp
return fakeAppImage, nil
}
func (p *FakeProvisioner) ImageDeploy(app provision.App, img string, evt *event.Event) (string, error) {
if err := p.getError("ImageDeploy"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
pApp.image = img
evt.Write([]byte("Image deploy called"))
p.apps[app.GetName()] = pApp
return img, nil
}
func (p *FakeProvisioner) Rollback(app provision.App, img string, evt *event.Event) (string, error) {
if err := p.getError("Rollback"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
evt.Write([]byte("Rollback deploy called"))
p.apps[app.GetName()] = pApp
return img, nil
}
func (p *FakeProvisioner) Rebuild(app provision.App, evt *event.Event) (string, error) {
if err := p.getError("Rebuild"); err != nil {
return "", err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return "", errNotProvisioned
}
evt.Write([]byte("Rebuild deploy called"))
p.apps[app.GetName()] = pApp
return fakeAppImage, nil
}
func (p *FakeProvisioner) Provision(app provision.App) error {
if err := p.getError("Provision"); err != nil {
return err
}
if p.Provisioned(app) {
return &provision.Error{Reason: "App already provisioned."}
}
p.mut.Lock()
defer p.mut.Unlock()
p.apps[app.GetName()] = provisionedApp{
app: app,
restarts: make(map[string]int),
starts: make(map[string]int),
stops: make(map[string]int),
sleeps: make(map[string]int),
}
return nil
}
func (p *FakeProvisioner) Restart(app provision.App, process string, w io.Writer) error {
if err := p.getError("Restart"); err != nil {
return err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.restarts[process]++
p.apps[app.GetName()] = pApp
if w != nil {
fmt.Fprintf(w, "restarting app")
}
return nil
}
func (p *FakeProvisioner) Start(app provision.App, process string) error {
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.starts[process]++
p.apps[app.GetName()] = pApp
return nil
}
func (p *FakeProvisioner) Destroy(app provision.App) error {
if err := p.getError("Destroy"); err != nil {
return err
}
if !p.Provisioned(app) {
return errNotProvisioned
}
p.mut.Lock()
defer p.mut.Unlock()
delete(p.apps, app.GetName())
return nil
}
func (p *FakeProvisioner) AddUnits(app provision.App, n uint, process string, w io.Writer) error {
_, err := p.AddUnitsToNode(app, n, process, w, "")
return err
}
func (p *FakeProvisioner) AddUnitsToNode(app provision.App, n uint, process string, w io.Writer, nodeAddr string) ([]provision.Unit, error) {
if err := p.getError("AddUnits"); err != nil {
return nil, err
}
if n == 0 {
return nil, errors.New("Cannot add 0 units.")
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return nil, errNotProvisioned
}
name := app.GetName()
platform := app.GetPlatform()
length := uint(len(pApp.units))
var addresses []*url.URL
for i := uint(0); i < n; i++ {
val := atomic.AddInt32(&uniqueIpCounter, 1)
var hostAddr string
if nodeAddr != "" {
hostAddr = net.URLToHost(nodeAddr)
} else if len(p.nodes) > 0 {
for _, n := range p.nodes {
hostAddr = net.URLToHost(n.Address())
break
}
} else {
hostAddr = fmt.Sprintf("10.10.10.%d", val)
}
unit := provision.Unit{
ID: fmt.Sprintf("%s-%d", name, pApp.unitLen),
AppName: name,
Type: platform,
Status: provision.StatusStarted,
IP: hostAddr,
ProcessName: process,
Address: &url.URL{
Scheme: "http",
Host: fmt.Sprintf("%s:%d", hostAddr, val),
},
}
addresses = append(addresses, unit.Address)
pApp.units = append(pApp.units, unit)
pApp.unitLen++
}
err := routertest.FakeRouter.AddRoutes(name, addresses)
if err != nil {
return nil, err
}
result := make([]provision.Unit, int(n))
copy(result, pApp.units[length:])
p.apps[app.GetName()] = pApp
if w != nil {
fmt.Fprintf(w, "added %d units", n)
}
return result, nil
}
func (p *FakeProvisioner) RemoveUnits(app provision.App, n uint, process string, w io.Writer) error {
if err := p.getError("RemoveUnits"); err != nil {
return err
}
if n == 0 {
return errors.New("cannot remove 0 units")
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
var newUnits []provision.Unit
removedCount := n
var addresses []*url.URL
for _, u := range pApp.units {
if removedCount > 0 && u.ProcessName == process {
removedCount--
addresses = append(addresses, u.Address)
continue
}
newUnits = append(newUnits, u)
}
err := routertest.FakeRouter.RemoveRoutes(app.GetName(), addresses)
if err != nil {
return err
}
if removedCount > 0 {
return errors.New("too many units to remove")
}
if w != nil {
fmt.Fprintf(w, "removing %d units", n)
}
pApp.units = newUnits
pApp.unitLen = len(newUnits)
p.apps[app.GetName()] = pApp
return nil
}
// ExecuteCommand will pretend to execute the given command, recording data
// about it.
//
// The output of the command must be prepared with PrepareOutput, and failures
// must be prepared with PrepareFailure. In case of failure, the prepared
// output will be sent to the standard error stream, otherwise, it will be sent
// to the standard error stream.
//
// When there is no output nor failure prepared, ExecuteCommand will return a
// timeout error.
func (p *FakeProvisioner) ExecuteCommand(stdout, stderr io.Writer, app provision.App, cmd string, args ...string) error {
var (
output []byte
err error
)
command := Cmd{
Cmd: cmd,
Args: args,
App: app,
}
p.cmdMut.Lock()
p.cmds = append(p.cmds, command)
p.cmdMut.Unlock()
units, err := p.Units(app)
if err != nil {
return err
}
for range units {
select {
case output = <-p.outputs:
select {
case fail := <-p.failures:
if fail.method == "ExecuteCommand" {
stderr.Write(output)
return fail.err
}
p.failures <- fail
default:
stdout.Write(output)
}
case fail := <-p.failures:
if fail.method == "ExecuteCommand" {
err = fail.err
select {
case output = <-p.outputs:
stderr.Write(output)
default:
}
} else {
p.failures <- fail
}
case <-time.After(2e9):
return errors.New("FakeProvisioner timed out waiting for output.")
}
}
return err
}
func (p *FakeProvisioner) ExecuteCommandOnce(stdout, stderr io.Writer, app provision.App, cmd string, args ...string) error {
var output []byte
command := Cmd{
Cmd: cmd,
Args: args,
App: app,
}
p.cmdMut.Lock()
p.cmds = append(p.cmds, command)
p.cmdMut.Unlock()
select {
case output = <-p.outputs:
stdout.Write(output)
case fail := <-p.failures:
if fail.method == "ExecuteCommandOnce" {
select {
case output = <-p.outputs:
stderr.Write(output)
default:
}
return fail.err
} else {
p.failures <- fail
}
case <-time.After(2e9):
return errors.New("FakeProvisioner timed out waiting for output.")
}
return nil
}
func (p *FakeProvisioner) ExecuteCommandIsolated(stdout, stderr io.Writer, app provision.App, cmd string, args ...string) error {
var output []byte
command := Cmd{
Cmd: cmd,
Args: args,
App: app,
}
p.cmdMut.Lock()
p.cmds = append(p.cmds, command)
p.cmdMut.Unlock()
select {
case output = <-p.outputs:
stdout.Write(output)
case fail := <-p.failures:
if fail.method == "ExecuteCommandIsolated" {
select {
case output = <-p.outputs:
stderr.Write(output)
default:
}
return fail.err
} else {
p.failures <- fail
}
case <-time.After(2e9):
return errors.New("FakeProvisioner timed out waiting for output.")
}
return nil
}
func (p *FakeProvisioner) AddUnit(app provision.App, unit provision.Unit) {
p.mut.Lock()
defer p.mut.Unlock()
a := p.apps[app.GetName()]
a.units = append(a.units, unit)
a.unitLen++
p.apps[app.GetName()] = a
}
func (p *FakeProvisioner) Units(apps ...provision.App) ([]provision.Unit, error) {
if err := p.getError("Units"); err != nil {
return nil, err
}
p.mut.Lock()
defer p.mut.Unlock()
var allUnits []provision.Unit
for _, a := range apps {
allUnits = append(allUnits, p.apps[a.GetName()].units...)
}
return allUnits, nil
}
func (p *FakeProvisioner) RoutableAddresses(app provision.App) ([]url.URL, error) {
p.mut.Lock()
defer p.mut.Unlock()
units := p.apps[app.GetName()].units
addrs := make([]url.URL, len(units))
for i := range units {
addrs[i] = *units[i].Address
}
return addrs, nil
}
func (p *FakeProvisioner) SetUnitStatus(unit provision.Unit, status provision.Status) error {
p.mut.Lock()
defer p.mut.Unlock()
var units []provision.Unit
if unit.AppName == "" {
units = p.getAllUnits()
} else {
app, ok := p.apps[unit.AppName]
if !ok {
return errNotProvisioned
}
units = app.units
}
index := -1
for i, unt := range units {
if unt.ID == unit.ID {
index = i
unit.AppName = unt.AppName
break
}
}
if index < 0 {
return &provision.UnitNotFoundError{ID: unit.ID}
}
app := p.apps[unit.AppName]
app.units[index].Status = status
p.apps[unit.AppName] = app
return nil
}
func (p *FakeProvisioner) getAllUnits() []provision.Unit {
var units []provision.Unit
for _, app := range p.apps {
units = append(units, app.units...)
}
return units
}
func (p *FakeProvisioner) Addr(app provision.App) (string, error) {
if err := p.getError("Addr"); err != nil {
return "", err
}
return routertest.FakeRouter.Addr(app.GetName())
}
func (p *FakeProvisioner) SetCName(app provision.App, cname string) error {
if err := p.getError("SetCName"); err != nil {
return err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.cnames = append(pApp.cnames, cname)
p.apps[app.GetName()] = pApp
return routertest.FakeRouter.SetCName(cname, app.GetName())
}
func (p *FakeProvisioner) UnsetCName(app provision.App, cname string) error {
if err := p.getError("UnsetCName"); err != nil {
return err
}
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.cnames = []string{}
p.apps[app.GetName()] = pApp
return routertest.FakeRouter.UnsetCName(cname, app.GetName())
}
func (p *FakeProvisioner) HasCName(app provision.App, cname string) bool {
p.mut.RLock()
pApp, ok := p.apps[app.GetName()]
p.mut.RUnlock()
for _, cnameApp := range pApp.cnames {
if cnameApp == cname {
return ok && true
}
}
return false
}
func (p *FakeProvisioner) Stop(app provision.App, process string) error {
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.stops[process]++
for i, u := range pApp.units {
u.Status = provision.StatusStopped
pApp.units[i] = u
}
p.apps[app.GetName()] = pApp
return nil
}
func (p *FakeProvisioner) Sleep(app provision.App, process string) error {
p.mut.Lock()
defer p.mut.Unlock()
pApp, ok := p.apps[app.GetName()]
if !ok {
return errNotProvisioned
}
pApp.sleeps[process]++
for i, u := range pApp.units {
u.Status = provision.StatusAsleep
pApp.units[i] = u
}
p.apps[app.GetName()] = pApp
return nil
}
func (p *FakeProvisioner) RegisterUnit(a provision.App, unitId string, customData map[string]interface{}) error {
p.mut.Lock()
defer p.mut.Unlock()
pa, ok := p.apps[a.GetName()]
if !ok {
return errors.New("app not found")
}
pa.lastData = customData
for i, u := range pa.units {
if u.ID == unitId {
u.IP = u.IP + "-updated"
pa.units[i] = u
p.apps[a.GetName()] = pa
return nil
}
}
return &provision.UnitNotFoundError{ID: unitId}
}
func (p *FakeProvisioner) Shell(opts provision.ShellOptions) error {
var unit provision.Unit
units, err := p.Units(opts.App)
if err != nil {
return err
}
if len(units) == 0 {
return errors.New("app has no units")
} else if opts.Unit != "" {
for _, u := range units {
if u.ID == opts.Unit {
unit = u
break
}
}
} else {
unit = units[0]
}
if unit.ID == "" {
return errors.New("unit not found")
}
p.shellMut.Lock()
defer p.shellMut.Unlock()
p.shells[unit.ID] = append(p.shells[unit.ID], opts)
return nil
}
func (p *FakeProvisioner) FilterAppsByUnitStatus(apps []provision.App, status []string) ([]provision.App, error) {
filteredApps := []provision.App{}
for i := range apps {
units, _ := p.Units(apps[i])
for _, u := range units {
if stringInArray(u.Status.String(), status) {
filteredApps = append(filteredApps, apps[i])
break
}
}
}
return filteredApps, nil
}
func (p *FakeProvisioner) GetName() string {
return p.Name
}
func (p *FakeProvisioner) UpgradeNodeContainer(name string, pool string, writer io.Writer) error {
p.nodeContainers[name+"-"+pool]++
return nil
}
func (p *FakeProvisioner) RemoveNodeContainer(name string, pool string, writer io.Writer) error {
p.nodeContainers[name+"-"+pool] = 0
return nil
}
func (p *FakeProvisioner) HasNodeContainer(name string, pool string) bool {
return p.nodeContainers[name+"-"+pool] > 0
}
func stringInArray(value string, array []string) bool {
for _, str := range array {
if str == value {
return true
}
}
return false
}
type PipelineFakeProvisioner struct {
*FakeProvisioner
executedPipeline bool
}
func (p *PipelineFakeProvisioner) ExecutedPipeline() bool {
return p.executedPipeline
}
func (p *PipelineFakeProvisioner) DeployPipeline() *action.Pipeline {
act := action.Action{
Name: "change-executed-pipeline",
Forward: func(ctx action.FWContext) (action.Result, error) {
p.executedPipeline = true
return nil, nil
},
Backward: func(ctx action.BWContext) {
},
}
actions := []*action.Action{&act}
pipeline := action.NewPipeline(actions...)
return pipeline
}
type PipelineErrorFakeProvisioner struct {
*FakeProvisioner
}
func (p *PipelineErrorFakeProvisioner) DeployPipeline() *action.Pipeline {
act := action.Action{
Name: "error-pipeline",
Forward: func(ctx action.FWContext) (action.Result, error) {
return nil, errors.New("deploy error")
},
Backward: func(ctx action.BWContext) {
},
}
actions := []*action.Action{&act}
pipeline := action.NewPipeline(actions...)
return pipeline
}
type provisionedApp struct {
units []provision.Unit
app provision.App
restarts map[string]int
starts map[string]int
stops map[string]int
sleeps map[string]int
lastArchive string
lastFile io.ReadCloser
cnames []string
unitLen int
lastData map[string]interface{}
image string
}
|
Java
|
/******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#ifndef __RTL_REGD_H__
#define __RTL_REGD_H__
struct country_code_to_enum_rd {
u16 countrycode;
const char *iso_name;
};
enum country_code_type_t {
COUNTRY_CODE_FCC = 0,
COUNTRY_CODE_IC = 1,
COUNTRY_CODE_ETSI = 2,
COUNTRY_CODE_SPAIN = 3,
COUNTRY_CODE_FRANCE = 4,
COUNTRY_CODE_MKK = 5,
COUNTRY_CODE_MKK1 = 6,
COUNTRY_CODE_ISRAEL = 7,
COUNTRY_CODE_TELEC = 8,
COUNTRY_CODE_MIC = 9,
COUNTRY_CODE_GLOBAL_DOMAIN = 10,
COUNTRY_CODE_WORLD_WIDE_13 = 11,
COUNTRY_CODE_TELEC_NETGEAR = 12,
/*add new channel plan above this line */
COUNTRY_CODE_MAX
};
int rtl_regd_init(struct ieee80211_hw *hw,
int (*reg_notifier) (struct wiphy *wiphy,
struct regulatory_request *request));
int rtl_reg_notifier(struct wiphy *wiphy, struct regulatory_request *request);
#endif
|
Java
|
var request = require('request'),
log = require('bole')('npme-send-data'),
config = require('../../../config')
module.exports = function (formGuid, data, callback) {
var hubspot = config.license.hubspot.forms
.replace(":portal_id", config.license.hubspot.portal_id)
.replace(":form_guid", formGuid);
request.post(hubspot, function (er, resp) {
// we can ignore 302 responses
if (resp.statusCode === 204 || resp.statusCode === 302) {
return callback(null);
}
log.error('unexpected status code from hubspot; status=' + resp.statusCode + '; data=', data);
callback(new Error('unexpected status code: ' + resp.statusCode));
}).form(data);
}
|
Java
|
module.exports = {
env: {
mocha: true
},
plugins: [
'mocha'
]
};
|
Java
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Converting 'MC' programs to 'MCMem'.
module Futhark.Pass.ExplicitAllocations.MC (explicitAllocations) where
import Futhark.IR.MC
import Futhark.IR.MCMem
import Futhark.Pass.ExplicitAllocations
import Futhark.Pass.ExplicitAllocations.SegOp
instance SizeSubst (MCOp rep op) where
opSizeSubst _ _ = mempty
handleSegOp :: SegOp () MC -> AllocM MC MCMem (SegOp () MCMem)
handleSegOp op = do
let num_threads = intConst Int64 256 -- FIXME
mapSegOpM (mapper num_threads) op
where
scope = scopeOfSegSpace $ segSpace op
mapper num_threads =
identitySegOpMapper
{ mapOnSegOpBody =
localScope scope . allocInKernelBody,
mapOnSegOpLambda =
allocInBinOpLambda num_threads (segSpace op)
}
handleMCOp :: Op MC -> AllocM MC MCMem (Op MCMem)
handleMCOp (ParOp par_op op) =
Inner <$> (ParOp <$> traverse handleSegOp par_op <*> handleSegOp op)
handleMCOp (OtherOp soac) =
error $ "Cannot allocate memory in SOAC: " ++ pretty soac
-- | The pass from 'MC' to 'MCMem'.
explicitAllocations :: Pass MC MCMem
explicitAllocations = explicitAllocationsGeneric handleMCOp defaultExpHints
|
Java
|
/*******************************************************************************
*
* Module Name: rscalc - Calculate stream and list lengths
*
******************************************************************************/
/*
* Copyright (C) 2000 - 2016, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <contrib/dev/acpica/include/acpi.h>
#include <contrib/dev/acpica/include/accommon.h>
#include <contrib/dev/acpica/include/acresrc.h>
#include <contrib/dev/acpica/include/acnamesp.h>
#define _COMPONENT ACPI_RESOURCES
ACPI_MODULE_NAME ("rscalc")
/* Local prototypes */
static UINT8
AcpiRsCountSetBits (
UINT16 BitField);
static ACPI_RS_LENGTH
AcpiRsStructOptionLength (
ACPI_RESOURCE_SOURCE *ResourceSource);
static UINT32
AcpiRsStreamOptionLength (
UINT32 ResourceLength,
UINT32 MinimumTotalLength);
/*******************************************************************************
*
* FUNCTION: AcpiRsCountSetBits
*
* PARAMETERS: BitField - Field in which to count bits
*
* RETURN: Number of bits set within the field
*
* DESCRIPTION: Count the number of bits set in a resource field. Used for
* (Short descriptor) interrupt and DMA lists.
*
******************************************************************************/
static UINT8
AcpiRsCountSetBits (
UINT16 BitField)
{
UINT8 BitsSet;
ACPI_FUNCTION_ENTRY ();
for (BitsSet = 0; BitField; BitsSet++)
{
/* Zero the least significant bit that is set */
BitField &= (UINT16) (BitField - 1);
}
return (BitsSet);
}
/*******************************************************************************
*
* FUNCTION: AcpiRsStructOptionLength
*
* PARAMETERS: ResourceSource - Pointer to optional descriptor field
*
* RETURN: Status
*
* DESCRIPTION: Common code to handle optional ResourceSourceIndex and
* ResourceSource fields in some Large descriptors. Used during
* list-to-stream conversion
*
******************************************************************************/
static ACPI_RS_LENGTH
AcpiRsStructOptionLength (
ACPI_RESOURCE_SOURCE *ResourceSource)
{
ACPI_FUNCTION_ENTRY ();
/*
* If the ResourceSource string is valid, return the size of the string
* (StringLength includes the NULL terminator) plus the size of the
* ResourceSourceIndex (1).
*/
if (ResourceSource->StringPtr)
{
return ((ACPI_RS_LENGTH) (ResourceSource->StringLength + 1));
}
return (0);
}
/*******************************************************************************
*
* FUNCTION: AcpiRsStreamOptionLength
*
* PARAMETERS: ResourceLength - Length from the resource header
* MinimumTotalLength - Minimum length of this resource, before
* any optional fields. Includes header size
*
* RETURN: Length of optional string (0 if no string present)
*
* DESCRIPTION: Common code to handle optional ResourceSourceIndex and
* ResourceSource fields in some Large descriptors. Used during
* stream-to-list conversion
*
******************************************************************************/
static UINT32
AcpiRsStreamOptionLength (
UINT32 ResourceLength,
UINT32 MinimumAmlResourceLength)
{
UINT32 StringLength = 0;
ACPI_FUNCTION_ENTRY ();
/*
* The ResourceSourceIndex and ResourceSource are optional elements of
* some Large-type resource descriptors.
*/
/*
* If the length of the actual resource descriptor is greater than the
* ACPI spec-defined minimum length, it means that a ResourceSourceIndex
* exists and is followed by a (required) null terminated string. The
* string length (including the null terminator) is the resource length
* minus the minimum length, minus one byte for the ResourceSourceIndex
* itself.
*/
if (ResourceLength > MinimumAmlResourceLength)
{
/* Compute the length of the optional string */
StringLength = ResourceLength - MinimumAmlResourceLength - 1;
}
/*
* Round the length up to a multiple of the native word in order to
* guarantee that the entire resource descriptor is native word aligned
*/
return ((UINT32) ACPI_ROUND_UP_TO_NATIVE_WORD (StringLength));
}
/*******************************************************************************
*
* FUNCTION: AcpiRsGetAmlLength
*
* PARAMETERS: Resource - Pointer to the resource linked list
* ResourceListSize - Size of the resource linked list
* SizeNeeded - Where the required size is returned
*
* RETURN: Status
*
* DESCRIPTION: Takes a linked list of internal resource descriptors and
* calculates the size buffer needed to hold the corresponding
* external resource byte stream.
*
******************************************************************************/
ACPI_STATUS
AcpiRsGetAmlLength (
ACPI_RESOURCE *Resource,
ACPI_SIZE ResourceListSize,
ACPI_SIZE *SizeNeeded)
{
ACPI_SIZE AmlSizeNeeded = 0;
ACPI_RESOURCE *ResourceEnd;
ACPI_RS_LENGTH TotalSize;
ACPI_FUNCTION_TRACE (RsGetAmlLength);
/* Traverse entire list of internal resource descriptors */
ResourceEnd = ACPI_ADD_PTR (ACPI_RESOURCE, Resource, ResourceListSize);
while (Resource < ResourceEnd)
{
/* Validate the descriptor type */
if (Resource->Type > ACPI_RESOURCE_TYPE_MAX)
{
return_ACPI_STATUS (AE_AML_INVALID_RESOURCE_TYPE);
}
/* Sanity check the length. It must not be zero, or we loop forever */
if (!Resource->Length)
{
return_ACPI_STATUS (AE_AML_BAD_RESOURCE_LENGTH);
}
/* Get the base size of the (external stream) resource descriptor */
TotalSize = AcpiGbl_AmlResourceSizes [Resource->Type];
/*
* Augment the base size for descriptors with optional and/or
* variable-length fields
*/
switch (Resource->Type)
{
case ACPI_RESOURCE_TYPE_IRQ:
/* Length can be 3 or 2 */
if (Resource->Data.Irq.DescriptorLength == 2)
{
TotalSize--;
}
break;
case ACPI_RESOURCE_TYPE_START_DEPENDENT:
/* Length can be 1 or 0 */
if (Resource->Data.Irq.DescriptorLength == 0)
{
TotalSize--;
}
break;
case ACPI_RESOURCE_TYPE_VENDOR:
/*
* Vendor Defined Resource:
* For a Vendor Specific resource, if the Length is between 1 and 7
* it will be created as a Small Resource data type, otherwise it
* is a Large Resource data type.
*/
if (Resource->Data.Vendor.ByteLength > 7)
{
/* Base size of a Large resource descriptor */
TotalSize = sizeof (AML_RESOURCE_LARGE_HEADER);
}
/* Add the size of the vendor-specific data */
TotalSize = (ACPI_RS_LENGTH)
(TotalSize + Resource->Data.Vendor.ByteLength);
break;
case ACPI_RESOURCE_TYPE_END_TAG:
/*
* End Tag:
* We are done -- return the accumulated total size.
*/
*SizeNeeded = AmlSizeNeeded + TotalSize;
/* Normal exit */
return_ACPI_STATUS (AE_OK);
case ACPI_RESOURCE_TYPE_ADDRESS16:
/*
* 16-Bit Address Resource:
* Add the size of the optional ResourceSource info
*/
TotalSize = (ACPI_RS_LENGTH) (TotalSize +
AcpiRsStructOptionLength (
&Resource->Data.Address16.ResourceSource));
break;
case ACPI_RESOURCE_TYPE_ADDRESS32:
/*
* 32-Bit Address Resource:
* Add the size of the optional ResourceSource info
*/
TotalSize = (ACPI_RS_LENGTH) (TotalSize +
AcpiRsStructOptionLength (
&Resource->Data.Address32.ResourceSource));
break;
case ACPI_RESOURCE_TYPE_ADDRESS64:
/*
* 64-Bit Address Resource:
* Add the size of the optional ResourceSource info
*/
TotalSize = (ACPI_RS_LENGTH) (TotalSize +
AcpiRsStructOptionLength (
&Resource->Data.Address64.ResourceSource));
break;
case ACPI_RESOURCE_TYPE_EXTENDED_IRQ:
/*
* Extended IRQ Resource:
* Add the size of each additional optional interrupt beyond the
* required 1 (4 bytes for each UINT32 interrupt number)
*/
TotalSize = (ACPI_RS_LENGTH) (TotalSize +
((Resource->Data.ExtendedIrq.InterruptCount - 1) * 4) +
/* Add the size of the optional ResourceSource info */
AcpiRsStructOptionLength (
&Resource->Data.ExtendedIrq.ResourceSource));
break;
case ACPI_RESOURCE_TYPE_GPIO:
TotalSize = (ACPI_RS_LENGTH) (TotalSize +
(Resource->Data.Gpio.PinTableLength * 2) +
Resource->Data.Gpio.ResourceSource.StringLength +
Resource->Data.Gpio.VendorLength);
break;
case ACPI_RESOURCE_TYPE_SERIAL_BUS:
TotalSize = AcpiGbl_AmlResourceSerialBusSizes [
Resource->Data.CommonSerialBus.Type];
TotalSize = (ACPI_RS_LENGTH) (TotalSize +
Resource->Data.I2cSerialBus.ResourceSource.StringLength +
Resource->Data.I2cSerialBus.VendorLength);
break;
default:
break;
}
/* Update the total */
AmlSizeNeeded += TotalSize;
/* Point to the next object */
Resource = ACPI_ADD_PTR (ACPI_RESOURCE, Resource, Resource->Length);
}
/* Did not find an EndTag resource descriptor */
return_ACPI_STATUS (AE_AML_NO_RESOURCE_END_TAG);
}
/*******************************************************************************
*
* FUNCTION: AcpiRsGetListLength
*
* PARAMETERS: AmlBuffer - Pointer to the resource byte stream
* AmlBufferLength - Size of AmlBuffer
* SizeNeeded - Where the size needed is returned
*
* RETURN: Status
*
* DESCRIPTION: Takes an external resource byte stream and calculates the size
* buffer needed to hold the corresponding internal resource
* descriptor linked list.
*
******************************************************************************/
ACPI_STATUS
AcpiRsGetListLength (
UINT8 *AmlBuffer,
UINT32 AmlBufferLength,
ACPI_SIZE *SizeNeeded)
{
ACPI_STATUS Status;
UINT8 *EndAml;
UINT8 *Buffer;
UINT32 BufferSize;
UINT16 Temp16;
UINT16 ResourceLength;
UINT32 ExtraStructBytes;
UINT8 ResourceIndex;
UINT8 MinimumAmlResourceLength;
AML_RESOURCE *AmlResource;
ACPI_FUNCTION_TRACE (RsGetListLength);
*SizeNeeded = ACPI_RS_SIZE_MIN; /* Minimum size is one EndTag */
EndAml = AmlBuffer + AmlBufferLength;
/* Walk the list of AML resource descriptors */
while (AmlBuffer < EndAml)
{
/* Validate the Resource Type and Resource Length */
Status = AcpiUtValidateResource (NULL, AmlBuffer, &ResourceIndex);
if (ACPI_FAILURE (Status))
{
/*
* Exit on failure. Cannot continue because the descriptor length
* may be bogus also.
*/
return_ACPI_STATUS (Status);
}
AmlResource = (void *) AmlBuffer;
/* Get the resource length and base (minimum) AML size */
ResourceLength = AcpiUtGetResourceLength (AmlBuffer);
MinimumAmlResourceLength = AcpiGbl_ResourceAmlSizes[ResourceIndex];
/*
* Augment the size for descriptors with optional
* and/or variable length fields
*/
ExtraStructBytes = 0;
Buffer = AmlBuffer + AcpiUtGetResourceHeaderLength (AmlBuffer);
switch (AcpiUtGetResourceType (AmlBuffer))
{
case ACPI_RESOURCE_NAME_IRQ:
/*
* IRQ Resource:
* Get the number of bits set in the 16-bit IRQ mask
*/
ACPI_MOVE_16_TO_16 (&Temp16, Buffer);
ExtraStructBytes = AcpiRsCountSetBits (Temp16);
break;
case ACPI_RESOURCE_NAME_DMA:
/*
* DMA Resource:
* Get the number of bits set in the 8-bit DMA mask
*/
ExtraStructBytes = AcpiRsCountSetBits (*Buffer);
break;
case ACPI_RESOURCE_NAME_VENDOR_SMALL:
case ACPI_RESOURCE_NAME_VENDOR_LARGE:
/*
* Vendor Resource:
* Get the number of vendor data bytes
*/
ExtraStructBytes = ResourceLength;
/*
* There is already one byte included in the minimum
* descriptor size. If there are extra struct bytes,
* subtract one from the count.
*/
if (ExtraStructBytes)
{
ExtraStructBytes--;
}
break;
case ACPI_RESOURCE_NAME_END_TAG:
/*
* End Tag: This is the normal exit
*/
return_ACPI_STATUS (AE_OK);
case ACPI_RESOURCE_NAME_ADDRESS32:
case ACPI_RESOURCE_NAME_ADDRESS16:
case ACPI_RESOURCE_NAME_ADDRESS64:
/*
* Address Resource:
* Add the size of the optional ResourceSource
*/
ExtraStructBytes = AcpiRsStreamOptionLength (
ResourceLength, MinimumAmlResourceLength);
break;
case ACPI_RESOURCE_NAME_EXTENDED_IRQ:
/*
* Extended IRQ Resource:
* Using the InterruptTableLength, add 4 bytes for each additional
* interrupt. Note: at least one interrupt is required and is
* included in the minimum descriptor size (reason for the -1)
*/
ExtraStructBytes = (Buffer[1] - 1) * sizeof (UINT32);
/* Add the size of the optional ResourceSource */
ExtraStructBytes += AcpiRsStreamOptionLength (
ResourceLength - ExtraStructBytes, MinimumAmlResourceLength);
break;
case ACPI_RESOURCE_NAME_GPIO:
/* Vendor data is optional */
if (AmlResource->Gpio.VendorLength)
{
ExtraStructBytes +=
AmlResource->Gpio.VendorOffset -
AmlResource->Gpio.PinTableOffset +
AmlResource->Gpio.VendorLength;
}
else
{
ExtraStructBytes +=
AmlResource->LargeHeader.ResourceLength +
sizeof (AML_RESOURCE_LARGE_HEADER) -
AmlResource->Gpio.PinTableOffset;
}
break;
case ACPI_RESOURCE_NAME_SERIAL_BUS:
MinimumAmlResourceLength = AcpiGbl_ResourceAmlSerialBusSizes[
AmlResource->CommonSerialBus.Type];
ExtraStructBytes +=
AmlResource->CommonSerialBus.ResourceLength -
MinimumAmlResourceLength;
break;
default:
break;
}
/*
* Update the required buffer size for the internal descriptor structs
*
* Important: Round the size up for the appropriate alignment. This
* is a requirement on IA64.
*/
if (AcpiUtGetResourceType (AmlBuffer) ==
ACPI_RESOURCE_NAME_SERIAL_BUS)
{
BufferSize = AcpiGbl_ResourceStructSerialBusSizes[
AmlResource->CommonSerialBus.Type] + ExtraStructBytes;
}
else
{
BufferSize = AcpiGbl_ResourceStructSizes[ResourceIndex] +
ExtraStructBytes;
}
BufferSize = (UINT32) ACPI_ROUND_UP_TO_NATIVE_WORD (BufferSize);
*SizeNeeded += BufferSize;
ACPI_DEBUG_PRINT ((ACPI_DB_RESOURCES,
"Type %.2X, AmlLength %.2X InternalLength %.2X\n",
AcpiUtGetResourceType (AmlBuffer),
AcpiUtGetDescriptorLength (AmlBuffer), BufferSize));
/*
* Point to the next resource within the AML stream using the length
* contained in the resource descriptor header
*/
AmlBuffer += AcpiUtGetDescriptorLength (AmlBuffer);
}
/* Did not find an EndTag resource descriptor */
return_ACPI_STATUS (AE_AML_NO_RESOURCE_END_TAG);
}
/*******************************************************************************
*
* FUNCTION: AcpiRsGetPciRoutingTableLength
*
* PARAMETERS: PackageObject - Pointer to the package object
* BufferSizeNeeded - UINT32 pointer of the size buffer
* needed to properly return the
* parsed data
*
* RETURN: Status
*
* DESCRIPTION: Given a package representing a PCI routing table, this
* calculates the size of the corresponding linked list of
* descriptions.
*
******************************************************************************/
ACPI_STATUS
AcpiRsGetPciRoutingTableLength (
ACPI_OPERAND_OBJECT *PackageObject,
ACPI_SIZE *BufferSizeNeeded)
{
UINT32 NumberOfElements;
ACPI_SIZE TempSizeNeeded = 0;
ACPI_OPERAND_OBJECT **TopObjectList;
UINT32 Index;
ACPI_OPERAND_OBJECT *PackageElement;
ACPI_OPERAND_OBJECT **SubObjectList;
BOOLEAN NameFound;
UINT32 TableIndex;
ACPI_FUNCTION_TRACE (RsGetPciRoutingTableLength);
NumberOfElements = PackageObject->Package.Count;
/*
* Calculate the size of the return buffer.
* The base size is the number of elements * the sizes of the
* structures. Additional space for the strings is added below.
* The minus one is to subtract the size of the UINT8 Source[1]
* member because it is added below.
*
* But each PRT_ENTRY structure has a pointer to a string and
* the size of that string must be found.
*/
TopObjectList = PackageObject->Package.Elements;
for (Index = 0; Index < NumberOfElements; Index++)
{
/* Dereference the subpackage */
PackageElement = *TopObjectList;
/* We must have a valid Package object */
if (!PackageElement ||
(PackageElement->Common.Type != ACPI_TYPE_PACKAGE))
{
return_ACPI_STATUS (AE_AML_OPERAND_TYPE);
}
/*
* The SubObjectList will now point to an array of the
* four IRQ elements: Address, Pin, Source and SourceIndex
*/
SubObjectList = PackageElement->Package.Elements;
/* Scan the IrqTableElements for the Source Name String */
NameFound = FALSE;
for (TableIndex = 0;
TableIndex < PackageElement->Package.Count && !NameFound;
TableIndex++)
{
if (*SubObjectList && /* Null object allowed */
((ACPI_TYPE_STRING ==
(*SubObjectList)->Common.Type) ||
((ACPI_TYPE_LOCAL_REFERENCE ==
(*SubObjectList)->Common.Type) &&
((*SubObjectList)->Reference.Class ==
ACPI_REFCLASS_NAME))))
{
NameFound = TRUE;
}
else
{
/* Look at the next element */
SubObjectList++;
}
}
TempSizeNeeded += (sizeof (ACPI_PCI_ROUTING_TABLE) - 4);
/* Was a String type found? */
if (NameFound)
{
if ((*SubObjectList)->Common.Type == ACPI_TYPE_STRING)
{
/*
* The length String.Length field does not include the
* terminating NULL, add 1
*/
TempSizeNeeded += ((ACPI_SIZE)
(*SubObjectList)->String.Length + 1);
}
else
{
TempSizeNeeded += AcpiNsGetPathnameLength (
(*SubObjectList)->Reference.Node);
}
}
else
{
/*
* If no name was found, then this is a NULL, which is
* translated as a UINT32 zero.
*/
TempSizeNeeded += sizeof (UINT32);
}
/* Round up the size since each element must be aligned */
TempSizeNeeded = ACPI_ROUND_UP_TO_64BIT (TempSizeNeeded);
/* Point to the next ACPI_OPERAND_OBJECT */
TopObjectList++;
}
/*
* Add an extra element to the end of the list, essentially a
* NULL terminator
*/
*BufferSizeNeeded = TempSizeNeeded + sizeof (ACPI_PCI_ROUTING_TABLE);
return_ACPI_STATUS (AE_OK);
}
|
Java
|
/* eslint-disable flowtype/require-parameter-type, flowtype/require-return-type, no-magic-numbers */
import {test} from "tap"
import {spy} from "sinon"
import aside from "./"
test(({equal, end}) => {
const unction = spy(() => "b")
equal(aside([unction])("a"), "a")
end()
})
test(({ok, end}) => {
const unction = spy(() => "b")
aside([unction])("a")
ok(unction.calledWith("a"))
end()
})
test(({equal, end}) => {
const unction = spy(() => "b")
equal(aside([unction])("a"), "a")
end()
})
test(({ok, equal, end}) => {
const unctionA = spy(() => "b")
const unctionB = spy(() => "c")
equal(aside([unctionA, unctionB])("a"), "a")
ok(unctionA.calledWith("a"))
ok(unctionB.calledWith("b"))
end()
})
|
Java
|
/*-
* Copyright (c) 1999 M. Warner Losh <imp@village.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Modifications for Megahertz X-Jack Ethernet Card (XJ-10BT)
*
* Copyright (c) 1996 by Tatsumi Hosokawa <hosokawa@jp.FreeBSD.org>
* BSD-nomads, Tokyo, Japan.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <sys/param.h>
#include <sys/bus.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/socket.h>
#include <sys/systm.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <machine/bus.h>
#include <machine/resource.h>
#include <sys/rman.h>
#include <dev/pccard/pccardvar.h>
#include <dev/pccard/pccard_cis.h>
#include <dev/sn/if_snreg.h>
#include <dev/sn/if_snvar.h>
#include "card_if.h"
#include "pccarddevs.h"
typedef int sn_get_enaddr_t(device_t dev, u_char *eaddr);
typedef int sn_activate_t(device_t dev);
struct sn_sw
{
int type;
#define SN_NORMAL 1
#define SN_MEGAHERTZ 2
#define SN_OSITECH 3
#define SN_OSI_SOD 4
#define SN_MOTO_MARINER 5
char *typestr;
sn_get_enaddr_t *get_mac;
sn_activate_t *activate;
};
static sn_get_enaddr_t sn_pccard_normal_get_mac;
static sn_activate_t sn_pccard_normal_activate;
const static struct sn_sw sn_normal_sw = {
SN_NORMAL, "plain",
sn_pccard_normal_get_mac,
sn_pccard_normal_activate
};
static sn_get_enaddr_t sn_pccard_megahertz_get_mac;
static sn_activate_t sn_pccard_megahertz_activate;
const static struct sn_sw sn_mhz_sw = {
SN_MEGAHERTZ, "Megahertz",
sn_pccard_megahertz_get_mac,
sn_pccard_megahertz_activate
};
static const struct sn_product {
struct pccard_product prod;
const struct sn_sw *sw;
} sn_pccard_products[] = {
{ PCMCIA_CARD(DSPSI, XJEM1144), &sn_mhz_sw },
{ PCMCIA_CARD(DSPSI, XJACK), &sn_normal_sw },
/* { PCMCIA_CARD(MOTOROLA, MARINER), SN_MOTO_MARINER }, */
{ PCMCIA_CARD(NEWMEDIA, BASICS), &sn_normal_sw },
{ PCMCIA_CARD(MEGAHERTZ, VARIOUS), &sn_mhz_sw},
{ PCMCIA_CARD(MEGAHERTZ, XJEM3336), &sn_mhz_sw},
/* { PCMCIA_CARD(OSITECH, TRUMP_SOD), SN_OSI_SOD }, */
/* { PCMCIA_CARD(OSITECH, TRUMP_JOH), SN_OSITECH }, */
/* { PCMCIA_CARD(PSION, GOLDCARD), SN_OSITECH }, */
/* { PCMCIA_CARD(PSION, NETGLOBAL), SNI_OSI_SOD }, */
/* { PCMCIA_CARD(PSION, NETGLOBAL2), SN_OSITECH }, */
{ PCMCIA_CARD(SMC, 8020BT), &sn_normal_sw },
{ PCMCIA_CARD(SMC, SMC91C96), &sn_normal_sw },
{ { NULL } }
};
static const struct sn_product *
sn_pccard_lookup(device_t dev)
{
return ((const struct sn_product *)
pccard_product_lookup(dev,
(const struct pccard_product *)sn_pccard_products,
sizeof(sn_pccard_products[0]), NULL));
}
static int
sn_pccard_probe(device_t dev)
{
const struct sn_product *pp;
if ((pp = sn_pccard_lookup(dev)) != NULL) {
if (pp->prod.pp_name != NULL)
device_set_desc(dev, pp->prod.pp_name);
return 0;
}
return EIO;
}
static int
sn_pccard_ascii_enaddr(const char *str, u_char *enet)
{
uint8_t digit;
int i;
memset(enet, 0, ETHER_ADDR_LEN);
for (i = 0, digit = 0; i < (ETHER_ADDR_LEN * 2); i++) {
if (str[i] >= '0' && str[i] <= '9')
digit |= str[i] - '0';
else if (str[i] >= 'a' && str[i] <= 'f')
digit |= (str[i] - 'a') + 10;
else if (str[i] >= 'A' && str[i] <= 'F')
digit |= (str[i] - 'A') + 10;
else
return (0); /* Bogus digit!! */
/* Compensate for ordering of digits. */
if (i & 1) {
enet[i >> 1] = digit;
digit = 0;
} else
digit <<= 4;
}
return (1);
}
static int
sn_pccard_normal_get_mac(device_t dev, u_char *eaddr)
{
int i, sum;
const char *cisstr;
pccard_get_ether(dev, eaddr);
for (i = 0, sum = 0; i < ETHER_ADDR_LEN; i++)
sum |= eaddr[i];
if (sum == 0) {
pccard_get_cis3_str(dev, &cisstr);
if (cisstr && strlen(cisstr) == ETHER_ADDR_LEN * 2)
sum = sn_pccard_ascii_enaddr(cisstr, eaddr);
}
if (sum == 0) {
pccard_get_cis4_str(dev, &cisstr);
if (cisstr && strlen(cisstr) == ETHER_ADDR_LEN * 2)
sum = sn_pccard_ascii_enaddr(cisstr, eaddr);
}
return sum;
}
static int
sn_pccard_normal_activate(device_t dev)
{
int err;
err = sn_activate(dev);
if (err)
sn_deactivate(dev);
return (err);
}
static int
sn_pccard_megahertz_mac(const struct pccard_tuple *tuple, void *argp)
{
uint8_t *enaddr = argp;
int i;
uint8_t buffer[ETHER_ADDR_LEN * 2];
/* Code 0x81 is Megahertz' special cis node contianing the MAC */
if (tuple->code != 0x81)
return (0);
/* Make sure this is a sane node, as ASCII digits */
if (tuple->length != ETHER_ADDR_LEN * 2 + 1)
return (0);
/* Copy the MAC ADDR and return success if decoded */
for (i = 0; i < ETHER_ADDR_LEN * 2; i++)
buffer[i] = pccard_tuple_read_1(tuple, i);
return (sn_pccard_ascii_enaddr(buffer, enaddr));
}
static int
sn_pccard_megahertz_get_mac(device_t dev, u_char *eaddr)
{
if (sn_pccard_normal_get_mac(dev, eaddr))
return 1;
/*
* If that fails, try the special CIS tuple 0x81 that the
* '3288 and '3336 cards have. That tuple specifies an ASCII
* string, ala CIS3 or CIS4 in the 'normal' cards.
*/
return (pccard_cis_scan(dev, sn_pccard_megahertz_mac, eaddr));
}
static int
sn_pccard_megahertz_activate(device_t dev)
{
int err;
struct sn_softc *sc = device_get_softc(dev);
u_long start;
err = sn_activate(dev);
if (err) {
sn_deactivate(dev);
return (err);
}
/*
* CIS resource is the modem one, so save it away.
*/
sc->modem_rid = sc->port_rid;
sc->modem_res = sc->port_res;
/*
* The MHz XJEM/CCEM series of cards just need to have any
* old resource allocated for the ethernet side of things,
* provided bit 0x80 isn't set in the address. That bit is
* evidentially reserved for modem function and is how the
* card steers the addresses internally.
*/
sc->port_res = NULL;
start = 0;
do
{
sc->port_rid = 1;
sc->port_res = bus_alloc_resource(dev, SYS_RES_IOPORT,
&sc->port_rid, start, ~0, SMC_IO_EXTENT, RF_ACTIVE);
if (sc->port_res == NULL)
break;
if (!(rman_get_start(sc->port_res) & 0x80))
break;
start = rman_get_start(sc->port_res) + SMC_IO_EXTENT;
bus_release_resource(dev, SYS_RES_IOPORT, sc->port_rid,
sc->port_res);
} while (start < 0xff80);
if (sc->port_res == NULL) {
sn_deactivate(dev);
return ENOMEM;
}
return 0;
}
static int
sn_pccard_attach(device_t dev)
{
struct sn_softc *sc = device_get_softc(dev);
u_char eaddr[ETHER_ADDR_LEN];
int i, err;
uint16_t w;
u_char sum;
const struct sn_product *pp;
pp = sn_pccard_lookup(dev);
sum = pp->sw->get_mac(dev, eaddr);
/* Allocate resources so we can program the ether addr */
sc->dev = dev;
err = pp->sw->activate(dev);
if (err != 0)
return (err);
if (sum) {
printf("Programming sn card's addr\n");
SMC_SELECT_BANK(sc, 1);
for (i = 0; i < 3; i++) {
w = (uint16_t)eaddr[i * 2] |
(((uint16_t)eaddr[i * 2 + 1]) << 8);
CSR_WRITE_2(sc, IAR_ADDR0_REG_W + i * 2, w);
}
}
err = sn_attach(dev);
if (err)
sn_deactivate(dev);
return (err);
}
static device_method_t sn_pccard_methods[] = {
/* Device interface */
DEVMETHOD(device_probe, sn_pccard_probe),
DEVMETHOD(device_attach, sn_pccard_attach),
DEVMETHOD(device_detach, sn_detach),
{ 0, 0 }
};
static driver_t sn_pccard_driver = {
"sn",
sn_pccard_methods,
sizeof(struct sn_softc),
};
extern devclass_t sn_devclass;
DRIVER_MODULE(sn, pccard, sn_pccard_driver, sn_devclass, 0, 0);
MODULE_DEPEND(sn, ether, 1, 1, 1);
PCCARD_PNP_INFO(sn_pccard_products);
|
Java
|
/*
Copyright (C) 2004 Michael J. Silbersack. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/*
* $FreeBSD$
* The goal of this program is to see if fstat reports the correct
* data count for a pipe. Prior to revision 1.172 of sys_pipe.c,
* 0 would be returned once the pipe entered direct write mode.
*
* Linux (2.6) always returns zero, so it's not a valuable platform
* for comparison.
*/
int
main(void)
{
char buffer[32768], buffer2[32768], go[] = "go", go2[] = "go2";
int desc[2], ipc_coord[2];
ssize_t error;
int successes = 0;
struct stat status;
pid_t new_pid;
error = pipe(desc);
if (error == -1)
err(1, "Couldn't allocate data pipe");
error = pipe(ipc_coord);
if (error == -1)
err(1, "Couldn't allocate IPC coordination pipe");
new_pid = fork();
assert(new_pid != -1);
close(new_pid == 0 ? desc[0] : desc[1]);
#define SYNC_R(i, _buf) do { \
int _error = errno; \
warnx("%d: waiting for synchronization", __LINE__); \
if (read(ipc_coord[i], &_buf, sizeof(_buf)) != sizeof(_buf)) \
err(1, "failed to synchronize (%s)", (i == 0 ? "parent" : "child")); \
errno = _error; \
} while(0)
#define SYNC_W(i, _buf) do { \
int _error = errno; \
warnx("%d: sending synchronization", __LINE__); \
if (write(ipc_coord[i], &_buf, sizeof(_buf)) != sizeof(_buf)) \
err(1, "failed to synchronize (%s)", (i == 0 ? "child" : "parent")); \
errno = _error; \
} while(0)
#define WRITE(s) do { \
ssize_t _size; \
if ((_size = write(desc[1], &buffer, s)) != s) \
warn("short write; wrote %zd, expected %d", _size, s); \
} while(0)
if (new_pid == 0) {
SYNC_R(0, go);
WRITE(145);
SYNC_W(0, go2);
SYNC_R(0, go);
WRITE(2048);
SYNC_W(0, go2);
SYNC_R(0, go);
WRITE(4096);
SYNC_W(0, go2);
SYNC_R(0, go);
WRITE(8191);
SYNC_W(0, go2);
SYNC_R(0, go);
SYNC_W(0, go2); /* XXX: why is this required? */
WRITE(8192);
SYNC_W(0, go2);
close(ipc_coord[0]);
close(ipc_coord[1]);
_exit(0);
}
while (successes < 5) {
SYNC_W(1, go);
SYNC_R(1, go2);
fstat(desc[0], &status);
error = read(desc[0], &buffer2, sizeof(buffer2));
if (status.st_size != error)
err(1, "FAILURE: stat size %jd read size %zd",
(intmax_t)status.st_size, error);
if (error > 0) {
printf("SUCCESS at stat size %jd read size %zd\n",
(intmax_t)status.st_size, error);
successes++;
}
}
exit(0);
}
|
Java
|
/*
* The Yices SMT Solver. Copyright 2014 SRI International.
*
* This program may only be used subject to the noncommercial end user
* license agreement which is downloadable along with this program.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include "utils/int_stack.h"
static int_stack_t stack;
static void print_stack(int_stack_t *stack) {
iblock_t *b;
printf("stack %p\n", stack);
printf(" current block = %p\n", stack->current);
printf(" free list = %p\n", stack->free);
printf(" active blocks:\n");
b = stack->current;
while (b != NULL) {
printf(" block %p: size = %"PRIu32" ptr = %"PRIu32" data = %p\n", b, b->size, b->ptr, b->data);
b = b->next;
}
printf(" free blocks:\n");
b = stack->free;
while (b != NULL) {
printf(" block %p: size = %"PRIu32" ptr = %"PRIu32" data = %p\n", b, b->size, b->ptr, b->data);
b = b->next;
}
printf("\n");
}
int main(void) {
int32_t *a1, *a2, *a3, *a4;
printf("=== Initialization ===\n");
init_istack(&stack);
print_stack(&stack);
printf("=== Allocation a1: size 100 ===\n");
a1 = alloc_istack_array(&stack, 100);
printf(" a1 = %p\n", a1);
print_stack(&stack);
printf("=== Allocation a2: size 500 ===\n");
a2 = alloc_istack_array(&stack, 500);
printf(" a2 = %p\n", a2);
print_stack(&stack);
printf("=== Allocation a3: size 800 ===\n");
a3 = alloc_istack_array(&stack, 800);
printf(" a3 = %p\n", a3);
print_stack(&stack);
printf("=== Allocation a4: size 8000 ===\n");
a4 = alloc_istack_array(&stack, 8000);
printf(" a4 = %p\n", a4);
print_stack(&stack);
printf("=== Free a4 ===\n");
free_istack_array(&stack, a4);
print_stack(&stack);
printf("=== Allocation a4: size 800 ===\n");
a4 = alloc_istack_array(&stack, 800);
printf(" a4 = %p\n", a4);
print_stack(&stack);
printf("=== Free a4 ===\n");
free_istack_array(&stack, a4);
print_stack(&stack);
printf("=== Free a3 ===\n");
free_istack_array(&stack, a3);
print_stack(&stack);
printf("=== Reset ===\n");
reset_istack(&stack);
print_stack(&stack);
delete_istack(&stack);
return 0;
}
|
Java
|
/*
* Copyright (c) 2006, 2007 ThoughtWorks, Inc.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
package com.thoughtworks.cozmos;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.util.StringTokenizer;
public class ModDavSvnProxyServlet2 extends HttpServlet {
private String targetURL;
private String newPageTemplate;
public void init(ServletConfig servletConfig) throws ServletException {
targetURL = servletConfig.getInitParameter("mod_dav_svn_url");
newPageTemplate = servletConfig.getInitParameter("new_page_template_file");
super.init(servletConfig);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = req.getServletPath();
Socket socket = startGet(new URL(targetURL + path));
InputStream is = socket.getInputStream();
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is));
boolean ok = isOk(lnr);
if (!ok) {
socket = startGet(new URL(targetURL + newPageTemplate));
lnr = new LineNumberReader(new InputStreamReader(is));
ok = isOk(lnr);
}
if (ok) {
lnr.readLine(); // Date:
lnr.readLine(); // Server:
lnr.readLine(); // ETag:
lnr.readLine(); // Accept-Ranges:
int contentLength = getContentLen(lnr.readLine());
lnr.readLine(); // Content-Type:
lnr.readLine(); // end of header
resp.setContentType(getServletContext().getMimeType(path));
OutputStream os = resp.getOutputStream();
int done = 0;
while (done < contentLength) {
int i = lnr.read();
done++;
os.write(i);
}
socket.close();
}
}
private int getContentLen(String s) {
StringTokenizer st = new StringTokenizer(s);
st.nextToken();
return Integer.parseInt(st.nextToken());
}
private boolean isOk(LineNumberReader lnr) throws IOException {
return "HTTP/1.1 200 OK".equals(lnr.readLine());
}
private Socket startGet(URL url) throws IOException {
Socket socket = new Socket(url.getHost(), 80);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println("GET " + url.getPath() + " HTTP/1.1");
pw.println("Host: " + url.getHost());
pw.println();
return socket;
}
}
|
Java
|
/*-
* Copyright (c) 2010, 2012 Konstantin Belousov <kib@FreeBSD.org>
* Copyright (c) 2015 The FreeBSD Foundation
* All rights reserved.
*
* Portions of this software were developed by Konstantin Belousov
* under sponsorship from the FreeBSD Foundation.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include "opt_compat.h"
#include "opt_vm.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/rwlock.h>
#include <sys/sysent.h>
#include <sys/sysctl.h>
#include <sys/vdso.h>
#include <vm/vm.h>
#include <vm/vm_param.h>
#include <vm/pmap.h>
#include <vm/vm_extern.h>
#include <vm/vm_kern.h>
#include <vm/vm_map.h>
#include <vm/vm_object.h>
#include <vm/vm_page.h>
#include <vm/vm_pager.h>
static struct sx shared_page_alloc_sx;
static vm_object_t shared_page_obj;
static int shared_page_free;
char *shared_page_mapping;
void
shared_page_write(int base, int size, const void *data)
{
bcopy(data, shared_page_mapping + base, size);
}
static int
shared_page_alloc_locked(int size, int align)
{
int res;
res = roundup(shared_page_free, align);
if (res + size >= IDX_TO_OFF(shared_page_obj->size))
res = -1;
else
shared_page_free = res + size;
return (res);
}
int
shared_page_alloc(int size, int align)
{
int res;
sx_xlock(&shared_page_alloc_sx);
res = shared_page_alloc_locked(size, align);
sx_xunlock(&shared_page_alloc_sx);
return (res);
}
int
shared_page_fill(int size, int align, const void *data)
{
int res;
sx_xlock(&shared_page_alloc_sx);
res = shared_page_alloc_locked(size, align);
if (res != -1)
shared_page_write(res, size, data);
sx_xunlock(&shared_page_alloc_sx);
return (res);
}
static void
shared_page_init(void *dummy __unused)
{
vm_page_t m;
vm_offset_t addr;
sx_init(&shared_page_alloc_sx, "shpsx");
shared_page_obj = vm_pager_allocate(OBJT_PHYS, 0, PAGE_SIZE,
VM_PROT_DEFAULT, 0, NULL);
VM_OBJECT_WLOCK(shared_page_obj);
m = vm_page_grab(shared_page_obj, 0, VM_ALLOC_NOBUSY | VM_ALLOC_ZERO);
m->valid = VM_PAGE_BITS_ALL;
VM_OBJECT_WUNLOCK(shared_page_obj);
addr = kva_alloc(PAGE_SIZE);
pmap_qenter(addr, &m, 1);
shared_page_mapping = (char *)addr;
}
SYSINIT(shp, SI_SUB_EXEC, SI_ORDER_FIRST, (sysinit_cfunc_t)shared_page_init,
NULL);
/*
* Push the timehands update to the shared page.
*
* The lockless update scheme is similar to the one used to update the
* in-kernel timehands, see sys/kern/kern_tc.c:tc_windup() (which
* calls us after the timehands are updated).
*/
static void
timehands_update(struct vdso_sv_tk *svtk)
{
struct vdso_timehands th;
struct vdso_timekeep *tk;
uint32_t enabled, idx;
enabled = tc_fill_vdso_timehands(&th);
th.th_gen = 0;
idx = svtk->sv_timekeep_curr;
if (++idx >= VDSO_TH_NUM)
idx = 0;
svtk->sv_timekeep_curr = idx;
if (++svtk->sv_timekeep_gen == 0)
svtk->sv_timekeep_gen = 1;
tk = (struct vdso_timekeep *)(shared_page_mapping +
svtk->sv_timekeep_off);
tk->tk_th[idx].th_gen = 0;
atomic_thread_fence_rel();
if (enabled)
tk->tk_th[idx] = th;
atomic_store_rel_32(&tk->tk_th[idx].th_gen, svtk->sv_timekeep_gen);
atomic_store_rel_32(&tk->tk_current, idx);
/*
* The ordering of the assignment to tk_enabled relative to
* the update of the vdso_timehands is not important.
*/
tk->tk_enabled = enabled;
}
#ifdef COMPAT_FREEBSD32
static void
timehands_update32(struct vdso_sv_tk *svtk)
{
struct vdso_timehands32 th;
struct vdso_timekeep32 *tk;
uint32_t enabled, idx;
enabled = tc_fill_vdso_timehands32(&th);
th.th_gen = 0;
idx = svtk->sv_timekeep_curr;
if (++idx >= VDSO_TH_NUM)
idx = 0;
svtk->sv_timekeep_curr = idx;
if (++svtk->sv_timekeep_gen == 0)
svtk->sv_timekeep_gen = 1;
tk = (struct vdso_timekeep32 *)(shared_page_mapping +
svtk->sv_timekeep_off);
tk->tk_th[idx].th_gen = 0;
atomic_thread_fence_rel();
if (enabled)
tk->tk_th[idx] = th;
atomic_store_rel_32(&tk->tk_th[idx].th_gen, svtk->sv_timekeep_gen);
atomic_store_rel_32(&tk->tk_current, idx);
tk->tk_enabled = enabled;
}
#endif
/*
* This is hackish, but easiest way to avoid creating list structures
* that needs to be iterated over from the hardclock interrupt
* context.
*/
static struct vdso_sv_tk *host_svtk;
#ifdef COMPAT_FREEBSD32
static struct vdso_sv_tk *compat32_svtk;
#endif
void
timekeep_push_vdso(void)
{
if (host_svtk != NULL)
timehands_update(host_svtk);
#ifdef COMPAT_FREEBSD32
if (compat32_svtk != NULL)
timehands_update32(compat32_svtk);
#endif
}
struct vdso_sv_tk *
alloc_sv_tk(void)
{
struct vdso_sv_tk *svtk;
int tk_base;
uint32_t tk_ver;
tk_ver = VDSO_TK_VER_CURR;
svtk = malloc(sizeof(struct vdso_sv_tk), M_TEMP, M_WAITOK | M_ZERO);
tk_base = shared_page_alloc(sizeof(struct vdso_timekeep) +
sizeof(struct vdso_timehands) * VDSO_TH_NUM, 16);
KASSERT(tk_base != -1, ("tk_base -1 for native"));
shared_page_write(tk_base + offsetof(struct vdso_timekeep, tk_ver),
sizeof(uint32_t), &tk_ver);
svtk->sv_timekeep_off = tk_base;
timekeep_push_vdso();
return (svtk);
}
#ifdef COMPAT_FREEBSD32
struct vdso_sv_tk *
alloc_sv_tk_compat32(void)
{
struct vdso_sv_tk *svtk;
int tk_base;
uint32_t tk_ver;
svtk = malloc(sizeof(struct vdso_sv_tk), M_TEMP, M_WAITOK | M_ZERO);
tk_ver = VDSO_TK_VER_CURR;
tk_base = shared_page_alloc(sizeof(struct vdso_timekeep32) +
sizeof(struct vdso_timehands32) * VDSO_TH_NUM, 16);
KASSERT(tk_base != -1, ("tk_base -1 for 32bit"));
shared_page_write(tk_base + offsetof(struct vdso_timekeep32,
tk_ver), sizeof(uint32_t), &tk_ver);
svtk->sv_timekeep_off = tk_base;
timekeep_push_vdso();
return (svtk);
}
#endif
void
exec_sysvec_init(void *param)
{
struct sysentvec *sv;
sv = (struct sysentvec *)param;
if ((sv->sv_flags & SV_SHP) == 0)
return;
sv->sv_shared_page_obj = shared_page_obj;
sv->sv_sigcode_base = sv->sv_shared_page_base +
shared_page_fill(*(sv->sv_szsigcode), 16, sv->sv_sigcode);
if ((sv->sv_flags & SV_ABI_MASK) != SV_ABI_FREEBSD)
return;
if ((sv->sv_flags & SV_TIMEKEEP) != 0) {
#ifdef COMPAT_FREEBSD32
if ((sv->sv_flags & SV_ILP32) != 0) {
KASSERT(compat32_svtk == NULL,
("Compat32 already registered"));
compat32_svtk = alloc_sv_tk_compat32();
sv->sv_timekeep_base = sv->sv_shared_page_base +
compat32_svtk->sv_timekeep_off;
} else {
#endif
KASSERT(host_svtk == NULL, ("Host already registered"));
host_svtk = alloc_sv_tk();
sv->sv_timekeep_base = sv->sv_shared_page_base +
host_svtk->sv_timekeep_off;
#ifdef COMPAT_FREEBSD32
}
#endif
}
}
|
Java
|
# $FreeBSD$
SUBDIR= libasn1 libgssapi_krb5 libgssapi_ntlm libgssapi_spnego libhdb \
libheimntlm libhx509 libkadm5clnt libkadm5srv libkrb5 \
libroken libsl libvers libkdc libwind libheimbase libheimipcc libheimipcs
SUBDIR+= libkafs5 # requires krb_err.h from libkrb5
SUBDIR_DEPEND_libkafs5= libkrb5
.include <bsd.subdir.mk>
|
Java
|
TARGETS = cpcond tagintr
EXTRA_OBJS = ../dmatags.o ../dmasend.o
EE_LIBS = -lg -ldma
COMMON_DIR=../../../common
include $(COMMON_DIR)/common-ee.mk
|
Java
|
var doNothing = function () {}
/**
* The `Base` log defines methods that transports will share.
*/
var Base = module.exports = function (config, defaults) {
var cedar = require('../../cedar')
// A log is a shorthand for `log.log`, among other things.
var log = function () {
log.log.apply(log, arguments)
}
// Don't run `setMethods` until all config properties are set.
var setMethods = doNothing
// Define properties that trigger `setMethods`.
Base.resetters.forEach(function (property) {
var value
Object.defineProperty(log, property, {
get: function () {
return value
},
set: function (newValue) {
value = newValue
setMethods.apply(log)
}
})
})
// Copy `config` properties to the `log`.
Base.decorate(log, config, true)
// Apply default properties.
Base.decorate(log, defaults || Base.defaults)
// Set up logging methods.
Base.setMethods.apply(log)
// Re-run `setMethods` if `resetters` change.
setMethods = Base.setMethods
// Return the fully-decorated log function.
return log
}
/**
* Some properties will reset methods if changed.
*/
Base.resetters = ['level', 'prefixes', 'format', 'showTrace']
/**
* Cedar supports 7 levels of logging.
*/
Base.levels = ['trace', 'debug', 'log', 'info', 'warn', 'error', 'fatal']
/**
* Share defaults between log objects.
*/
Base.defaults = {
// Show all log messages by default.
level: 'trace',
// Stream to `stdout` (using `write`).
stream: process.stdout,
// Don't add any space to JSON.
space: '',
// Stringify with `JSON.stringify`.
stringify: JSON.stringify,
// Join arguments together as an array.
join: function (args) {
var list = []
for (var index = 0, length = args.length; index < length; index++) {
var arg = args[index]
if (arg instanceof Error) {
arg = '"' + (arg.stack || arg.toString()).replace(/\n/, '\\n') + '"'
} else {
arg = JSON.stringify(arg, null, this.space)
}
list.push(arg)
}
return '[' + list.join(',') + ']'
},
// Start messages with a prefix for each log method.
prefixes: {
trace: 'TRACE ',
debug: 'DEBUG ',
log: 'LOG ',
info: 'INFO ',
warn: 'WARN ',
error: 'ERROR ',
fatal: 'FATAL '
},
// Format a log message.
format: function (message, type, prefix) {
return prefix + message + '\n'
}
}
/**
* Decorate an object with the properties of another.
*/
Base.decorate = function (object, defaults, shouldOverwrite) {
object = object || {}
for (var key in defaults) {
if (shouldOverwrite || (typeof object[key] === 'undefined')) {
object[key] = defaults[key]
}
}
return object
}
/**
* Create logging methods based on the configured `level`.
*/
Base.setMethods = function () {
var self = this
var found = false
if ((Base.levels.indexOf(self.level) < 0) && self.level !== 'nothing') {
self.error('Unknown log level: "' + self.level + '".')
} else {
Base.levels.forEach(function (methodName, index) {
if (methodName === self.level) {
found = true
}
var prefix = self.prefixes[methodName] || ''
var format = self.format
// If this log is an Emitter, we can catch and emit errors.
if (self.emit) {
self[methodName] = found ? function () {
var message = self.join(arguments)
message = format.call(self, message, methodName, prefix)
try {
self.stream.write(message)
} catch (e) {
self.emit('error', e)
}
} : doNothing
// Otherwise, they'll just throw.
} else {
self[methodName] = found ? function () {
var message = self.join(arguments)
message = format.call(self, message, methodName, prefix)
self.stream.write(message)
} : doNothing
}
})
// Wrap the trace method with a stack tracer.
if (self.trace !== doNothing) {
var traceMethod = self.trace
self.trace = function () {
var e = new Error('')
Error.captureStackTrace(e, self.trace)
var l = arguments.length
arguments[l] = e.stack.split('\n').splice(2).join('\n')
arguments.length = ++l
traceMethod.apply(self, arguments)
}
}
}
}
|
Java
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GAPPSF.OKAPI
{
public class SiteInfoNetherlands: SiteInfo
{
public const string STR_INFO = "opencaching.nl";
public SiteInfoNetherlands()
{
ID = "2";
Info = STR_INFO;
OKAPIBaseUrl = "http://www.opencaching.nl/okapi/";
GeocodePrefix = "OB";
}
public override void LoadSettings()
{
Username = Core.ApplicationData.Instance.AccountInfos.GetAccountInfo(GeocodePrefix).AccountName ?? "";
UserID = Core.Settings.Default.OKAPISiteInfoNetherlandsUserID ?? "";
Token = Core.Settings.Default.OKAPISiteInfoNetherlandsToken ?? "";
TokenSecret = Core.Settings.Default.OKAPISiteInfoNetherlandsTokenSecret ?? "";
base.LoadSettings();
}
public override void SaveSettings()
{
Core.ApplicationData.Instance.AccountInfos.GetAccountInfo(GeocodePrefix).AccountName = Username ?? "";
Core.Settings.Default.OKAPISiteInfoNetherlandsUserID = UserID ?? "";
Core.Settings.Default.OKAPISiteInfoNetherlandsToken = Token ?? "";
Core.Settings.Default.OKAPISiteInfoNetherlandsTokenSecret = TokenSecret ?? "";
}
}
}
|
Java
|
import Omni = require('../../lib/omni-sharp-server/omni');
import {Observable, CompositeDisposable} from "rx";
import {setupFeature, restoreBuffers, openEditor} from "../test-helpers";
describe('Run Tests', () => {
setupFeature(['features/run-tests']);
it('adds commands', () => {
var disposable = new CompositeDisposable();
runs(() => {
var commands: any = atom.commands;
expect(commands.registeredCommands['omnisharp-atom:run-all-tests']).toBeTruthy();
expect(commands.registeredCommands['omnisharp-atom:run-fixture-tests']).toBeTruthy();
expect(commands.registeredCommands['omnisharp-atom:run-single-test']).toBeTruthy();
expect(commands.registeredCommands['omnisharp-atom:run-last-test']).toBeTruthy();
disposable.dispose();
});
});
// TODO: Test functionality
});
|
Java
|
*{
margin: 0px;
padding: 0px;
}
#introduce{
width: 1000px;
height: 680px;
background-color: #f4f4f4;
margin: auto;
}
h1{
font-size: 2em;
text-align: center;
}
li{
list-style: none;
font-size: 1em;
}
#pic1{
margin-left: 60px;
float: left;
width: 361px;
height: 237px;
}
#pic2{
margin-left: 300px;
float: left;
width: 169px;
height: 237px;
}
#pic-describe{
text-align: center;
font-size: 13px;
}
|
Java
|
//
using System;
if (double.TryParse(aaa, out var bbb))
{
// ...
}
//
|
Java
|
{{- define "main" -}}
<h1>{{ .Title | markdownify }}</h1>
<p>
<small class="text-secondary">
{{ $customDateFormat := "January 2, 2006" }}
{{ with .Site.Params.customDateFormat }}{{ $customDateFormat = . }}{{ end }}
{{ .PublishDate.Format $customDateFormat }}{{ if gt .Lastmod .PublishDate }}, updated {{ .Lastmod.Format $customDateFormat }}{{ end }}
</small>
{{ partial "tags" . }}
</p>
{{ .Content }}
{{- end -}}
|
Java
|
using System;
using System.Collections.Generic;
using KellermanSoftware.CompareNetObjects;
using KellermanSoftware.CompareNetObjects.TypeComparers;
using ProtoBuf;
namespace Abc.Zebus.Testing.Comparison
{
internal static class ComparisonExtensions
{
public static bool DeepCompare<T>(this T firstObj, T secondObj, params string[] elementsToIgnore)
{
var comparer = CreateComparer();
comparer.Config.MembersToIgnore.AddRange(elementsToIgnore);
return comparer.Compare(firstObj, secondObj).AreEqual;
}
public static CompareLogic CreateComparer()
{
return new CompareLogic
{
Config =
{
CompareStaticProperties = false,
CompareStaticFields = false,
CustomComparers =
{
// TODO : Is this still used?
new EquatableComparer()
},
AttributesToIgnore = new List<Type> { typeof(ProtoIgnoreAttribute) },
}
};
}
private class EquatableComparer : BaseTypeComparer
{
public EquatableComparer()
: base(RootComparerFactory.GetRootComparer())
{
}
public override bool IsTypeMatch(Type type1, Type type2)
{
if (type1 != type2)
return false;
return typeof(IEquatable<>).MakeGenericType(type1).IsAssignableFrom(type1);
}
public override void CompareType(CompareParms parms)
{
if (!Equals(parms.Object1, parms.Object2))
AddDifference(parms);
}
}
}
}
|
Java
|
// Generated on 12/11/2014 19:01:22
using System;
using System.Collections.Generic;
using System.Linq;
using BlueSheep.Common.Protocol.Types;
using BlueSheep.Common.IO;
using BlueSheep.Engine.Types;
namespace BlueSheep.Common.Protocol.Messages
{
public class SequenceNumberMessage : Message
{
public new const uint ID =6317;
public override uint ProtocolID
{
get { return ID; }
}
public ushort number;
public SequenceNumberMessage()
{
}
public SequenceNumberMessage(ushort number)
{
this.number = number;
}
public override void Serialize(BigEndianWriter writer)
{
writer.WriteUShort(number);
}
public override void Deserialize(BigEndianReader reader)
{
number = reader.ReadUShort();
if (number < 0 || number > 65535)
throw new Exception("Forbidden value on number = " + number + ", it doesn't respect the following condition : number < 0 || number > 65535");
}
}
}
|
Java
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Unittest extends CI_Controller {
function __construct() {
parent::__construct ();
$this->load->model('UnitTest_model');
$this->load->library('unit_test');
}
function index(){
echo "test";
}
function debate(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$debate_test_list = $this->UnitTest_model->debate_list_test($offset, $limit);
for($i = 0 ; $i < count($debate_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($debate_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($debate_test_list[$i]->title, 'is_string', 'title_type');
$this->unit->run($debate_test_list[$i]->content, 'is_string', 'content_type');
$this->unit->run($debate_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
$this->unit->run($debate_test_list[$i]->del_st, 'is_numeric', 'del_st_type');
}
echo $this->unit->report();
}
function debate_reply(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$debate_reply_test_list = $this->UnitTest_model->debate_reply_list_test($offset, $limit);
for($i = 0 ; $i < count($debate_reply_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($debate_reply_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($debate_reply_test_list[$i]->debate_id, 'is_numeric', 'debate_id_type');
$this->unit->run($debate_reply_test_list[$i]->content, 'is_string', 'content_type');
$this->unit->run($debate_reply_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
$this->unit->run($debate_reply_test_list[$i]->del_st, 'is_numeric', 'del_st_type');
}
echo $this->unit->report();
}
function debate_back(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$debate_back_test_list = $this->UnitTest_model->debate_back_list_test($offset, $limit);
for($i = 0 ; $i < count($debate_back_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($debate_back_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($debate_back_test_list[$i]->debate_id, 'is_numeric', 'debate_id_type');
$this->unit->run($debate_back_test_list[$i]->seq, 'is_numeric', 'seq_type');
$this->unit->run($debate_back_test_list[$i]->title, 'is_string', 'title_type');
$this->unit->run($debate_back_test_list[$i]->content, 'is_string', 'content_type');
}
echo $this->unit->report();
}
function board(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$board_test_list = $this->UnitTest_model->board_list_test($offset, $limit);
for($i = 0 ; $i < count($board_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($board_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($board_test_list[$i]->title, 'is_string', 'title_type');
$this->unit->run($board_test_list[$i]->content, 'is_string', 'content_type');
$this->unit->run($board_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
$this->unit->run($board_test_list[$i]->del_st, 'is_numeric', 'del_st_type');
}
echo $this->unit->report();
}
function board_reply(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$board_reply_test_list = $this->UnitTest_model->board_reply_list_test($offset, $limit);
for($i = 0 ; $i < count($board_reply_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($board_reply_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($board_reply_test_list[$i]->board_id, 'is_numeric', 'board_id_type');
$this->unit->run($board_reply_test_list[$i]->content, 'is_string', 'content_type');
$this->unit->run($board_reply_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
$this->unit->run($board_reply_test_list[$i]->del_st, 'is_numeric', 'del_st_type');
}
echo $this->unit->report();
}
function law(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$law_test_list = $this->UnitTest_model->law_list_test($offset, $limit);
for($i = 0 ; $i < count($law_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($law_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($law_test_list[$i]->d1, 'is_null', 'd1_type');
$this->unit->run($law_test_list[$i]->d2, 'is_null', 'd2_type');
$this->unit->run($law_test_list[$i]->d3, 'is_null', 'd3_type');
$this->unit->run($law_test_list[$i]->d4, 'is_null', 'd4_type');
$this->unit->run($law_test_list[$i]->d5, 'is_null', 'd5_type');
$this->unit->run($law_test_list[$i]->d6, 'is_null', 'd6_type');
$this->unit->run($law_test_list[$i]->d7, 'is_null', 'd7_type');
$this->unit->run($law_test_list[$i]->d8, 'is_null', 'd8_type');
$this->unit->run($law_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
}
echo $this->unit->report();
}
function law_model(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$law_model_test_list = $this->UnitTest_model->law_model_list_test($offset, $limit);
for($i = 0 ; $i < count($law_model_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($law_model_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($law_model_test_list[$i]->title, 'is_string', 'title_type');
$this->unit->run($law_model_test_list[$i]->content, 'is_string', 'content_type');
$this->unit->run($law_model_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
$this->unit->run($law_model_test_list[$i]->del_st, 'is_numeric', 'del_st_type');
}
echo $this->unit->report();
}
function log(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$log_test_list = $this->UnitTest_model->log_list_test($offset, $limit);
for($i = 0 ; $i < count($log_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($log_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($log_test_list[$i]->code, 'is_numeric', 'code_type');
$this->unit->run($log_test_list[$i]->content_id, 'is_numeric', 'content_id_type');
$this->unit->run($log_test_list[$i]->reg_id, 'is_numeric', 'reg_id_type');
}
echo $this->unit->report();
}
function user(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$user_test_list = $this->UnitTest_model->user_list_test($offset, $limit);
for($i = 0 ; $i < count($user_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($user_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($user_test_list[$i]->email, 'is_string', 'email_type');
$this->unit->run($user_test_list[$i]->auth_code, 'is_string', 'auth_code_type');
}
echo $this->unit->report();
}
function user_info(){
$offset = $this->input->get("offset");
$limit = $this->input->get("limit");
$user_info_test_list = $this->UnitTest_model->user_info_list_test($offset, $limit);
for($i = 0 ; $i < count($user_info_test_list); $i ++){
$this->unit->use_strict(TRUE);
$this->unit->run($user_info_test_list[$i]->id, 'is_numeric', 'id_type');
$this->unit->run($user_info_test_list[$i]->user_id, 'is_numeric', 'user_id_type');
$this->unit->run($user_info_test_list[$i]->user_code, 'is_numeric', 'user_code_type');
$this->unit->run($user_info_test_list[$i]->acc_st, 'is_numeric', 'acc_st_type');
}
echo $this->unit->report();
}
}
|
Java
|
# modern-django
Modern Django: A Guide on How to Deploy Django-based Web Applications in 2017
|
Java
|
#include <iostream>
using namespace std;
#include <omp.h>
#define SIZE 8
int main(void){
int x[SIZE];
int sum=0;
for(int i=0;i<SIZE;i++){
x[i]=i;
}
#pragma omp parallel for reduction (+:sum)
for(int i=0;i<SIZE;i++){
sum+=x[i];
}
cout<<sum<<std::endl;
return 0;
}
|
Java
|
- 只验证值,不关心这个值从哪里来
- 验证成功返回`undefined`,验证失败返回提示信息
- 验证又分:输入时验证,提交时验证
- 验证失败处理:提示,获得焦点
- 验证失败提示:提示时机,提示方式
|
Java
|
from .image import Image
from .product_category import ProductCategory
from .supplier import Supplier, PaymentMethod
from .product import Product
from .product import ProductImage
from .enum_values import EnumValues
from .related_values import RelatedValues
from .customer import Customer
from .expense import Expense
from .incoming import Incoming
from .shipping import Shipping, ShippingLine
from .receiving import Receiving, ReceivingLine
from .inventory_transaction import InventoryTransaction, InventoryTransactionLine
from .purchase_order import PurchaseOrder, PurchaseOrderLine
from .sales_order import SalesOrder, SalesOrderLine
from .user import User
from .role import Role, roles_users
from .organization import Organization
from .inventory_in_out_link import InventoryInOutLink
from .aspects import update_menemonic
from .product_inventory import ProductInventory
|
Java
|
import type {ResponseType} from "./base.type";
function parseJSON(response: ResponseType): Object {
return response.json();
}
export {parseJSON};
|
Java
|
// This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.
#include <RendererTextureDesc.h>
using namespace SampleRenderer;
RendererTextureDesc::RendererTextureDesc(void)
{
format = RendererTexture::NUM_FORMATS;
filter = RendererTexture::FILTER_LINEAR;
addressingU = RendererTexture::ADDRESSING_WRAP;
addressingV = RendererTexture::ADDRESSING_WRAP;
addressingW = RendererTexture::ADDRESSING_WRAP;
width = 0;
height = 0;
depth = 1;
numLevels = 0;
renderTarget = false;
data = NULL;
}
bool RendererTextureDesc::isValid(void) const
{
bool ok = true;
if(format >= RendererTexture2D::NUM_FORMATS) ok = false;
if(filter >= RendererTexture2D::NUM_FILTERS) ok = false;
if(addressingU >= RendererTexture2D::NUM_ADDRESSING) ok = false;
if(addressingV >= RendererTexture2D::NUM_ADDRESSING) ok = false;
if(width <= 0 || height <= 0 || depth <= 0) ok = false; // TODO: check for power of two.
if(numLevels <= 0) ok = false;
if(renderTarget)
{
if(depth > 1) ok = false;
if(format == RendererTexture2D::FORMAT_DXT1) ok = false;
if(format == RendererTexture2D::FORMAT_DXT3) ok = false;
if(format == RendererTexture2D::FORMAT_DXT5) ok = false;
}
return ok;
}
|
Java
|
var request = require('request'),
mongoose = require('mongoose'),
util = require('util'),
url = require('url'),
helpers = require('./helpers'),
sync = require('./sync')
// turn off request pooling
request.defaults({ agent:false })
// cache elasticsearch url options for elmongo.search() to use
var elasticUrlOptions = null
/**
* Attach mongoose plugin for elasticsearch indexing
*
* @param {Object} schema mongoose schema
* @param {Object} options elasticsearch options object. Keys: host, port, index, type
*/
module.exports = elmongo = function (schema, options) {
// attach methods to schema
schema.methods.index = index
schema.methods.unindex = unindex
schema.statics.sync = function (cb) {
options = helpers.mergeModelOptions(options, this)
return sync.call(this, schema, options, cb)
}
schema.statics.search = function (searchOpts, cb) {
options = helpers.mergeModelOptions(options, this)
var searchUri = helpers.makeTypeUri(options) + '/_search?search_type=dfs_query_then_fetch&preference=_primary_first'
return helpers.doSearchAndNormalizeResults(searchUri, searchOpts, cb)
}
// attach mongoose middleware hooks
schema.post('save', function () {
options = helpers.mergeModelOptions(options, this)
this.index(options)
})
schema.post('remove', function () {
options = helpers.mergeModelOptions(options, this)
this.unindex(options)
})
}
/**
* Search across multiple collections. Same usage as model search, but with an extra key on `searchOpts` - `collections`
* @param {Object} searchOpts
* @param {Function} cb
*/
elmongo.search = function (searchOpts, cb) {
// merge elasticsearch url config options
elasticUrlOptions = helpers.mergeOptions(elasticUrlOptions)
// determine collections to search on
var collections = searchOpts.collections;
if (elasticUrlOptions.prefix) {
// prefix was specified - namespace the index names to use the prefix for each collection's index
if (searchOpts.collections && searchOpts.collections.length) {
// collections were specified - prepend the prefix on each collection name
collections = collections.map(function (collection) {
return elasticUrlOptions.prefix + '-' + collection
})
} else {
// no collections specified, but prefix specified - use wildcard index with prefix
collections = [ elasticUrlOptions.prefix + '*' ]
}
} else {
// no prefix used
// if collections specified, just use their names without the prefix
if (!collections) {
// no collections were specified so use _all (searches all collections), without prefix
searchOpts.collections = [ '_all' ]
}
}
var searchUri = helpers.makeDomainUri(elasticUrlOptions) + '/' + collections.join(',') + '/_search?search_type=dfs_query_then_fetch&preference=_primary_first'
return helpers.doSearchAndNormalizeResults(searchUri, searchOpts, cb)
}
/**
* Configure the Elasticsearch url options for `elmongo.search()`.
*
* @param {Object} options - keys: host, port, prefix (optional)
*/
elmongo.search.config = function (options) {
// only overwrite `options` values that are being specified in this call to `config`
if (elasticUrlOptions) {
Object
.keys(elasticUrlOptions)
.forEach(function (key) {
elasticUrlOptions[key] = options[key] || elasticUrlOptions[key]
})
}
// normalize the `options` object
elasticUrlOptions = helpers.mergeOptions(options)
}
/**
* Index a document in elasticsearch (create if not existing)
*
* @param {Object} options elasticsearch options object. Keys: host, port, index, type
*/
function index (options) {
var self = this
// strip mongoose-added functions, depopulate any populated fields, and serialize the doc
var esearchDoc = helpers.serializeModel(this)
var indexUri = helpers.makeDocumentUri(options, self)
var reqOpts = {
method: 'PUT',
url: indexUri,
body: JSON.stringify(esearchDoc)
}
// console.log('index:', indexUri)
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
var error = new Error('Elasticsearch document indexing error: '+util.inspect(err, true, 10, true))
error.details = err
self.emit('error', error)
return
}
self.emit('elmongo-indexed', body)
})
}
/**
* Remove a document from elasticsearch
*
* @param {Object} options elasticsearch options object. Keys: host, port, index, type
*/
function unindex (options) {
var self = this
var unindexUri = helpers.makeDocumentUri(options, self)
// console.log('unindex:', unindexUri)
var reqOpts = {
method: 'DELETE',
url: unindexUri
}
helpers.backOffRequest(reqOpts, function (err, res, body) {
if (err) {
var error = new Error('Elasticsearch document index deletion error: '+util.inspect(err, true, 10, true))
error.details = err
self.emit('error', error)
return
}
self.emit('elmongo-unindexed', body)
})
}
|
Java
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>local::basic_endpoint::operator!=</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../local__basic_endpoint.html" title="local::basic_endpoint">
<link rel="prev" href="data_type.html" title="local::basic_endpoint::data_type">
<link rel="next" href="operator_lt_.html" title="local::basic_endpoint::operator<">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="data_type.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../local__basic_endpoint.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator_lt_.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.local__basic_endpoint.operator_not__eq_"></a><a class="link" href="operator_not__eq_.html" title="local::basic_endpoint::operator!=">local::basic_endpoint::operator!=</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="idp180210864"></a>
Compare two endpoints for inequality.
</p>
<pre class="programlisting"><span class="keyword">friend</span> <span class="keyword">bool</span> <span class="keyword">operator</span><span class="special">!=(</span>
<span class="keyword">const</span> <span class="identifier">basic_endpoint</span><span class="special"><</span> <span class="identifier">Protocol</span> <span class="special">></span> <span class="special">&</span> <span class="identifier">e1</span><span class="special">,</span>
<span class="keyword">const</span> <span class="identifier">basic_endpoint</span><span class="special"><</span> <span class="identifier">Protocol</span> <span class="special">></span> <span class="special">&</span> <span class="identifier">e2</span><span class="special">);</span>
</pre>
<h6>
<a name="boost_asio.reference.local__basic_endpoint.operator_not__eq_.h0"></a>
<span class="phrase"><a name="boost_asio.reference.local__basic_endpoint.operator_not__eq_.requirements"></a></span><a class="link" href="operator_not__eq_.html#boost_asio.reference.local__basic_endpoint.operator_not__eq_.requirements">Requirements</a>
</h6>
<p>
<span class="emphasis"><em>Header: </em></span><code class="literal">boost/asio/local/basic_endpoint.hpp</code>
</p>
<p>
<span class="emphasis"><em>Convenience header: </em></span><code class="literal">boost/asio.hpp</code>
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2014 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="data_type.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../local__basic_endpoint.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator_lt_.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
Java
|
/**
* Copyright 2015 Telerik AD
*
* 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.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["qut"] = {
name: "qut",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "",
abbr: "",
pattern: ["($n)","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "Q"
}
},
calendars: {
standard: {
days: {
names: ["juq\u0027ij","kaq\u0027ij","oxq\u0027ij","kajq\u0027ij","joq\u0027ij","waqq\u0027ij","wuqq\u0027ij"],
namesAbbr: ["juq\u0027","kaq\u0027","oxq\u0027","kajq\u0027","joq\u0027","waqq\u0027","wuqq\u0027"],
namesShort: ["ju","ka","ox","kj","jo","wa","wu"]
},
months: {
names: ["nab\u0027e ik\u0027","ukab\u0027 ik\u0027","urox ik\u0027","ukaj ik\u0027","uro ik\u0027","uwaq ik\u0027","uwuq ik\u0027","uwajxaq ik\u0027","ub\u0027elej ik\u0027","ulaj ik\u0027","ujulaj ik\u0027","ukab\u0027laj ik\u0027"],
namesAbbr: ["nab\u0027e","ukab\u0027","urox","ukaj","uro","uwaq","uwuq","uwajxaq","ub\u0027elej","ulaj","ujulaj","ukab\u0027laj"]
},
AM: ["a.m.","a.m.","A.M."],
PM: ["p.m.","p.m.","P.M."],
patterns: {
d: "dd/MM/yyyy",
D: "dddd, dd' rech 'MMMM' rech 'yyyy",
F: "dddd, dd' rech 'MMMM' rech 'yyyy h:mm:ss tt",
g: "dd/MM/yyyy h:mm tt",
G: "dd/MM/yyyy h:mm:ss tt",
m: "d' rech 'MMMM",
M: "d' rech 'MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "h:mm tt",
T: "h:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM' rech 'yyyy",
Y: "MMMM' rech 'yyyy"
},
"/": "/",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
|
Java
|
#!/bin/bash
export LDFLAGS="-lstdc++fs"
mkdir -p $PREFIX/lib
./configure --prefix $PREFIX
make
make install
|
Java
|
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall;
using FlatRedBall.Gui;
using FlatRedBall.AI.Pathfinding;
#if FRB_MDX
using Color = System.Drawing.Color;
#else
using Color = Microsoft.Xna.Framework.Graphics.Color;
#endif
using CameraPropertyGrid = EditorObjects.Gui.CameraPropertyGrid;
using EditorObjects.Gui;
using EditorObjects;
namespace AIEditor.Gui
{
public static class GuiData
{
#region Fields
static int mFramesSinceLastExpensiveGuiUpdate = 0;
static Menu mMenuStrip;
static CameraPropertyGrid mCameraPropertyGrid;
static NodeNetworkPropertyGrid mNodeNetworkPropertyGrid;
static ToolsWindow mToolsWindow;
static CommandDisplay mCommandDisplay;
static ScenePropertyGrid mScenePropertyGrid;
static ShapeCollectionPropertyGrid mShapeCollectionPropertyGrid;
public static EditorPropertiesGrid mEditorPropertiesGrid;
#endregion
#region Properties
public static CameraPropertyGrid CameraPropertyGrid
{
get { return mCameraPropertyGrid; }
}
public static CommandDisplay CommandDisplay
{
get { return mCommandDisplay; }
}
public static EditorPropertiesGrid EditorPropertiesGrid
{
get { return mEditorPropertiesGrid; }
}
public static NodeNetworkPropertyGrid NodeNetworkPropertyGrid
{
get { return mNodeNetworkPropertyGrid; }
set { mNodeNetworkPropertyGrid = value; }
}
public static ScenePropertyGrid ScenePropertyGrid
{
get { return mScenePropertyGrid; }
}
public static ShapeCollectionPropertyGrid ShapeCollectionPropertyGrid
{
get { return mShapeCollectionPropertyGrid; }
}
public static ToolsWindow ToolsWindow
{
get { return mToolsWindow; }
}
#endregion
#region Events
private static void CreateColorPropertyGrid(Window callingWindow)
{
((PropertyGrid<Color>)callingWindow).ExcludeAllMembers();
((PropertyGrid<Color>)callingWindow).IncludeMember("A");
((PropertyGrid<Color>)callingWindow).IncludeMember("R");
((PropertyGrid<Color>)callingWindow).IncludeMember("G");
((PropertyGrid<Color>)callingWindow).IncludeMember("B");
callingWindow.Y = 40;
}
private static void CreatePositionedNodePropertyGrid(Window callingWindow)
{
PropertyGrid<PositionedNode> asPropertyGrid = callingWindow as PropertyGrid<PositionedNode>;
asPropertyGrid.ExcludeMember("CostToGetHere");
asPropertyGrid.ExcludeMember("Links");
asPropertyGrid.ExcludeMember("X");
asPropertyGrid.ExcludeMember("Y");
asPropertyGrid.ExcludeMember("Z");
asPropertyGrid.Name = "Positioned Node";
}
#endregion
#region Methods
#region Public Methods
public static void Initialize()
{
mMenuStrip = new Menu();
mToolsWindow = new ToolsWindow();
CreatePropertyGrids();
mCommandDisplay = new CommandDisplay();
CreateListDisplayWindows();
}
public static void Update()
{
if (EditorData.Scene != mScenePropertyGrid.SelectedObject)
{
mScenePropertyGrid.SelectedObject = EditorData.Scene;
}
mScenePropertyGrid.UpdateDisplayedProperties();
mNodeNetworkPropertyGrid.Update();
mCameraPropertyGrid.UpdateDisplayedProperties();
// This can be slow. We can speed it up by only doing it every X frames
const int updateEveryXFrames = 30;
mFramesSinceLastExpensiveGuiUpdate++;
if (mFramesSinceLastExpensiveGuiUpdate >= updateEveryXFrames)
{
mNodeNetworkPropertyGrid.UpdateDisplayedProperties();
mFramesSinceLastExpensiveGuiUpdate = 0;
}
#region Update the ShapeCollection PropertyGrid
if (mShapeCollectionPropertyGrid.Visible)
{
if (mShapeCollectionPropertyGrid.SelectedObject != EditorData.ShapeCollection)
{
mShapeCollectionPropertyGrid.SelectedObject = EditorData.ShapeCollection;
}
mShapeCollectionPropertyGrid.UpdateDisplayedProperties();
}
#endregion
}
#endregion
#region Private Methods
private static void CreateListDisplayWindows()
{
}
private static void CreatePropertyGrids()
{
#region CamerPropertyGrid
mCameraPropertyGrid = new CameraPropertyGrid(GuiManager.Cursor);
GuiManager.AddWindow(mCameraPropertyGrid);
mCameraPropertyGrid.SelectedObject = SpriteManager.Camera;
mCameraPropertyGrid.X = mCameraPropertyGrid.ScaleX;
mCameraPropertyGrid.Y = 40;
mCameraPropertyGrid.HasCloseButton = true;
mCameraPropertyGrid.UndoInstructions =
UndoManager.Instructions;
#endregion
#region NodeNetwork PropertyGrid
mNodeNetworkPropertyGrid = new NodeNetworkPropertyGrid();
mNodeNetworkPropertyGrid.SelectedObject = EditorData.NodeNetwork;
mNodeNetworkPropertyGrid.X = mNodeNetworkPropertyGrid.ScaleX;
mNodeNetworkPropertyGrid.Y = 61;
mNodeNetworkPropertyGrid.HasCloseButton = true;
mNodeNetworkPropertyGrid.UndoInstructions =
UndoManager.Instructions;
#endregion
#region ScenePropertyGrid
mScenePropertyGrid = new ScenePropertyGrid(GuiManager.Cursor);
GuiManager.AddWindow(mScenePropertyGrid);
mScenePropertyGrid.X = mScenePropertyGrid.ScaleX;
mScenePropertyGrid.Y = 75.7f;
mScenePropertyGrid.ShowPropertyGridOnStrongSelect = true;
mScenePropertyGrid.HasCloseButton = true;
mScenePropertyGrid.Visible = false;
mScenePropertyGrid.UndoInstructions = UndoManager.Instructions;
#endregion
#region ShapeCollectionPropertyGrid
mShapeCollectionPropertyGrid = new ShapeCollectionPropertyGrid(GuiManager.Cursor);
GuiManager.AddWindow(mShapeCollectionPropertyGrid);
mShapeCollectionPropertyGrid.ShowPropertyGridOnStrongSelectAxisAlignedCube = true;
mShapeCollectionPropertyGrid.ShowPropertyGridOnStrongSelectAxisAlignedRectangle = true;
mShapeCollectionPropertyGrid.ShowPropertyGridOnStrongSelectCircle = true;
mShapeCollectionPropertyGrid.ShowPropertyGridOnStrongSelectPolygon = true;
mShapeCollectionPropertyGrid.ShowPropertyGridOnStrongSelectSphere = true;
mShapeCollectionPropertyGrid.HasCloseButton = true;
mShapeCollectionPropertyGrid.Visible = false;
mShapeCollectionPropertyGrid.UndoInstructions = UndoManager.Instructions;
#endregion
PropertyGrid.SetNewWindowEvent<FlatRedBall.AI.Pathfinding.PositionedNode>(CreatePositionedNodePropertyGrid);
PropertyGrid.SetNewWindowEvent<Color>(CreateColorPropertyGrid);
#region EditorPropertiesGrid
mEditorPropertiesGrid = new EditorPropertiesGrid();
mEditorPropertiesGrid.Visible = false;
#endregion
}
#endregion
#endregion
}
}
|
Java
|
// flow-typed signature: 573c576fe34eb3c3c65dd7a9c90a46d2
// flow-typed version: b43dff3e0e/http-errors_v1.x.x/flow_>=v0.25.x
declare module 'http-errors' {
declare class SpecialHttpError extends HttpError {
constructor(): SpecialHttpError;
}
declare class HttpError extends Error {
expose: bool;
message: string;
status: number;
statusCode: number;
}
declare module.exports: {
(status?: number, message?: string, props?: Object): HttpError;
HttpError: typeof HttpError;
BadRequest: typeof SpecialHttpError;
Unauthorized: typeof SpecialHttpError;
PaymentRequired: typeof SpecialHttpError;
Forbidden: typeof SpecialHttpError;
NotFound: typeof SpecialHttpError;
MethodNotAllowed: typeof SpecialHttpError;
NotAcceptable: typeof SpecialHttpError;
ProxyAuthenticationRequired: typeof SpecialHttpError;
RequestTimeout: typeof SpecialHttpError;
Conflict: typeof SpecialHttpError;
Gone: typeof SpecialHttpError;
LengthRequired: typeof SpecialHttpError;
PreconditionFailed: typeof SpecialHttpError;
PayloadTooLarge: typeof SpecialHttpError;
URITooLong: typeof SpecialHttpError;
UnsupportedMediaType: typeof SpecialHttpError;
RangeNotStatisfiable: typeof SpecialHttpError;
ExpectationFailed: typeof SpecialHttpError;
ImATeapot: typeof SpecialHttpError;
MisdirectedRequest: typeof SpecialHttpError;
UnprocessableEntity: typeof SpecialHttpError;
Locked: typeof SpecialHttpError;
FailedDependency: typeof SpecialHttpError;
UnorderedCollection: typeof SpecialHttpError;
UpgradeRequired: typeof SpecialHttpError;
PreconditionRequired: typeof SpecialHttpError;
TooManyRequests: typeof SpecialHttpError;
RequestHeaderFieldsTooLarge: typeof SpecialHttpError;
UnavailableForLegalReasons: typeof SpecialHttpError;
InternalServerError: typeof SpecialHttpError;
NotImplemented: typeof SpecialHttpError;
BadGateway: typeof SpecialHttpError;
ServiceUnavailable: typeof SpecialHttpError;
GatewayTimeout: typeof SpecialHttpError;
HTTPVersionNotSupported: typeof SpecialHttpError;
VariantAlsoNegotiates: typeof SpecialHttpError;
InsufficientStorage: typeof SpecialHttpError;
LoopDetected: typeof SpecialHttpError;
BandwidthLimitExceeded: typeof SpecialHttpError;
NotExtended: typeof SpecialHttpError;
NetworkAuthenticationRequired: typeof SpecialHttpError;
}
}
|
Java
|
---
layout: nav_menu_item
title: Sales/Billing Document Integration
date: 2016-03-07 06:18
author: jeremy.buller
comments: true
categories: [AvaTax 16 Certification navigation]
---
|
Java
|
/*!
* Start Bootstrap - New Age v3.3.7 (http://startbootstrap.com/template-overviews/new-age)
* Copyright 2013-2016 Start Bootstrap
* Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE)
*/
.heading-font {
font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
font-weight: 200;
letter-spacing: 1px;
}
.body-font {
font-family: 'Muli', 'Helvetica', 'Arial', 'sans-serif';
}
.alt-font {
font-family: 'Lato', 'Helvetica', 'Arial', 'sans-serif';
text-transform: uppercase;
letter-spacing: 2px;
}
html,
body {
height: 100%;
width: 100%;
}
body {
font-family: 'Muli', 'Helvetica', 'Arial', 'sans-serif';
}
a {
-webkit-transition: all 0.35s;
-moz-transition: all 0.35s;
transition: all 0.35s;
color: #fdcc52;
}
a:hover,
a:focus {
color: #fcbd20;
}
hr {
max-width: 100px;
margin: 25px auto 0;
border-width: 1px;
border-color: rgba(34, 34, 34, 0.1);
}
hr.light {
border-color: white;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
font-weight: 200;
letter-spacing: 1px;
}
p {
font-size: 18px;
line-height: 1.5;
margin-bottom: 20px;
}
.navbar-default {
background-color: white;
border-color: rgba(34, 34, 34, 0.05);
-webkit-transition: all 0.35s;
-moz-transition: all 0.35s;
transition: all 0.35s;
font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
font-weight: 200;
letter-spacing: 1px;
}
.navbar-default .navbar-header .navbar-brand {
font-family: 'Catamaran', 'Helvetica', 'Arial', 'sans-serif';
font-weight: 200;
letter-spacing: 1px;
color: #fdcc52;
}
.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
color: #fcbd20;
}
.navbar-default .navbar-header .navbar-toggle {
font-size: 12px;
color: #222222;
padding: 8px 10px;
}
.navbar-default .nav > li > a {
font-family: 'Lato', 'Helvetica', 'Arial', 'sans-serif';
text-transform: uppercase;
letter-spacing: 2px;
font-size: 11px;
}
.navbar-default .nav > li > a,
.navbar-default .nav > li > a:focus {
color: #222222;
}
.navbar-default .nav > li > a:hover,
.navbar-default .nav > li > a:focus:hover {
color: #fdcc52;
}
.navbar-default .nav > li.active > a,
.navbar-default .nav > li.active > a:focus {
color: #fdcc52 !important;
background-color: transparent;
}
.navbar-default .nav > li.active > a:hover,
.navbar-default .nav > li.active > a:focus:hover {
background-color: transparent;
}
@media (min-width: 768px) {
.navbar-default {
background-color: transparent;
border-color: transparent;
}
.navbar-default .navbar-header .navbar-brand {
color: rgba(255, 255, 255, 0.7);
}
.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
color: white;
}
.navbar-default .nav > li > a,
.navbar-default .nav > li > a:focus {
color: rgba(255, 255, 255, 0.7);
}
.navbar-default .nav > li > a:hover,
.navbar-default .nav > li > a:focus:hover {
color: white;
}
.navbar-default.affix {
background-color: white;
border-color: rgba(34, 34, 34, 0.1);
}
.navbar-default.affix .navbar-header .navbar-brand {
color: #222222;
}
.navbar-default.affix .navbar-header .navbar-brand:hover,
.navbar-default.affix .navbar-header .navbar-brand:focus {
color: #fdcc52;
}
.navbar-default.affix .nav > li > a,
.navbar-default.affix .nav > li > a:focus {
color: #222222;
}
.navbar-default.affix .nav > li > a:hover,
.navbar-default.affix .nav > li > a:focus:hover {
color: #fdcc52;
}
}
header {
position: relative;
width: 100%;
min-height: auto;
overflow-y: hidden;
background: url("../img/bg-pattern.png"), #7b4397;
/* fallback for old browsers */
background: url("../img/bg-pattern.png"), -webkit-linear-gradient(to left, #7b4397, #dc2430);
/* Chrome 10-25, Safari 5.1-6 */
background: url("../img/bg-pattern.png"), linear-gradient(to left, #7b4397, #dc2430);
/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
color: white;
}
header .header-content {
text-align: center;
padding: 150px 0 50px;
position: relative;
}
header .header-content .header-content-inner {
position: relative;
max-width: 500px;
margin: 0 auto;
}
header .header-content .header-content-inner h1 {
margin-top: 0;
margin-bottom: 30px;
font-size: 30px;
}
header .header-content .header-content-inner .list-badges {
margin-bottom: 25px;
}
header .header-content .header-content-inner .list-badges img {
height: 50px;
margin-bottom: 25px;
}
header .device-container {
max-width: 300px;
margin: 0 auto 100px;
}
header .device-container .screen img {
border-radius: 3px;
}
@media (min-width: 768px) {
header {
min-height: 100%;
}
header .header-content {
text-align: left;
padding: 0;
height: 100vh;
}
header .header-content .header-content-inner {
max-width: none;
margin: 0;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
header .header-content .header-content-inner h1 {
font-size: 35px;
}
header .device-container {
max-width: none;
max-height: calc(0vh);
margin: 100px auto 0;
}
}
@media (min-width: 992px) {
header .header-content .header-content-inner h1 {
font-size: 50px;
}
}
section {
padding: 100px 0;
}
section h2 {
font-size: 50px;
}
section.download {
padding: 150px 0;
position: relative;
}
section.download h2 {
margin-top: 0;
font-size: 50px;
}
section.download .badges .badge-link {
display: block;
margin-bottom: 25px;
}
section.download .badges .badge-link:last-child {
margin-bottom: 0;
}
section.download .badges .badge-link img {
height: 60px;
}
@media (min-width: 768px) {
section.download .badges .badge-link {
display: inline-block;
margin-bottom: 0;
}
}
@media (min-width: 768px) {
section.download h2 {
font-size: 70px;
}
}
section.projects .section-heading {
margin-bottom: 100px;
}
section.projects .section-heading h2 {
margin-top: 0;
}
section.projects .section-heading p {
margin-bottom: 0;
}
section.projects .device-container,
section.projects .feature-item {
max-width: 300px;
margin: 0 auto;
}
section.projects .device-container {
margin-bottom: 100px;
}
@media (min-width: 992px) {
section.projects .device-container {
margin-bottom: 0;
}
}
section.projects .feature-item {
text-align: center;
margin-bottom: 100px;
}
section.projects .feature-item h3 {
font-size: 30px;
}
section.projects .feature-item i {
font-size: 80px;
background: -webkit-linear-gradient(to left, #7b4397, #dc2430);
background: linear-gradient(to left, #7b4397, #dc2430);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
@media (min-width: 992px) {
section.projects .device-container,
section.projects .feature-item {
max-width: none;
}
}
section.cta {
position: relative;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
background-position: center;
background-image: url('../img/bg-cta.jpg');
padding: 250px 0;
}
section.cta .cta-content {
position: relative;
z-index: 1;
}
section.cta .cta-content h2 {
margin-top: 0;
margin-bottom: 25px;
color: white;
max-width: 450px;
font-size: 50px;
}
@media (min-width: 768px) {
section.cta .cta-content h2 {
font-size: 80px;
}
}
section.cta .overlay {
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, 0.5);
position: absolute;
top: 0;
left: 0;
}
section.contact {
text-align: center;
}
section.contact h2 {
margin-top: 0;
margin-bottom: 25px;
}
section.contact h2 i {
color: #dd4b39;
}
section.contact ul.list-social {
margin-bottom: 0;
}
section.contact ul.list-social li a {
display: block;
height: 80px;
width: 80px;
line-height: 80px;
font-size: 40px;
border-radius: 100%;
color: white;
}
section.contact ul.list-social li.social-twitter a {
background-color: #1da1f2;
}
section.contact ul.list-social li.social-twitter a:hover {
background-color: #0d95e8;
}
section.contact ul.list-social li.social-facebook a {
background-color: #3b5998;
}
section.contact ul.list-social li.social-facebook a:hover {
background-color: #344e86;
}
section.contact ul.list-social li.social-google-plus a {
background-color: #dd4b39;
}
section.contact ul.list-social li.social-google-plus a:hover {
background-color: #d73925;
}
footer {
background-color: #222222;
padding: 25px 0;
color: rgba(255, 255, 255, 0.3);
text-align: center;
}
footer p {
font-size: 12px;
margin: 0;
}
footer ul {
margin-bottom: 0;
}
footer ul li a {
font-size: 12px;
color: rgba(255, 255, 255, 0.3);
}
footer ul li a:hover,
footer ul li a:focus,
footer ul li a:active,
footer ul li a.active {
text-decoration: none;
}
.bg-primary {
background: #fdcc52;
background: -webkit-linear-gradient(#fdcc52, #fdc539);
background: linear-gradient(#fdcc52, #fdc539);
}
.text-primary {
color: #fdcc52;
}
.no-gutter > [class*='col-'] {
padding-right: 0;
padding-left: 0;
}
.btn-outline {
color: white;
border-color: white;
border: 1px solid;
}
.btn-outline:hover,
.btn-outline:focus,
.btn-outline:active,
.btn-outline.active {
color: white;
background-color: #fdcc52;
border-color: #fdcc52;
}
.btn {
font-family: 'Lato', 'Helvetica', 'Arial', 'sans-serif';
text-transform: uppercase;
letter-spacing: 2px;
border-radius: 300px;
}
.btn-xl {
padding: 15px 45px;
font-size: 11px;
}
::-moz-selection {
color: white;
text-shadow: none;
background: #222222;
}
::selection {
color: white;
text-shadow: none;
background: #222222;
}
img::selection {
color: white;
background: transparent;
}
img::-moz-selection {
color: white;
background: transparent;
}
body {
webkit-tap-highlight-color: #222222;
}
|
Java
|
using System;
namespace Microsoft.eShopOnContainers.Services.Catalog.API.Model
{
public class CatalogItem
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string PictureUri { get; set; }
public int CatalogTypeId { get; set; }
public CatalogType CatalogType { get; set; }
public int CatalogBrandId { get; set; }
public CatalogBrand CatalogBrand { get; set; }
public CatalogItem() { }
}
}
|
Java
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Class: Gem::Package::TarReader::UnexpectedEOF</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
// ]]>
</script>
</head>
<body>
<div id="classHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Class</strong></td>
<td class="class-name-in-header">Gem::Package::TarReader::UnexpectedEOF</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
<a href="../../../../files/lib/rubygems/package/tar_reader_rb.html">
lib/rubygems/package/tar_reader.rb
</a>
<br />
</td>
</tr>
<tr class="top-aligned-row">
<td><strong>Parent:</strong></td>
<td>
StandardError
</td>
</tr>
</table>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
<div id="description">
<p>
Raised if the tar IO is not seekable
</p>
</div>
</div>
</div>
<!-- if includes -->
<div id="section">
<!-- if method_list -->
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
|
Java
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: flags.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: flags.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>/**
* just.js extension package
*
* @author danikas2k2 (danikas2k2@gmail.com)
*/
"use strict";
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
require("./global");
module.exports = (function () {
var Flags = (function () {
/**
*
* @param flag {number|Flags}
* @return {Flags}
* @constructor
*/
function Flags(flag) {
_classCallCheck(this, Flags);
this.reset(flag);
}
_createClass(Flags, [{
key: "valueOf",
/**
*
* @return {number}
*/
value: function valueOf() {
return this.flags;
}
}, {
key: "toString",
/**
*
* @return {string}
*/
value: function toString() {
return this.flags.toString();
}
}, {
key: "is",
/**
*
* @param flag {number|Flags}
* @return {boolean}
*/
value: function is(flag) {
return (this.flags & flag) == flag;
}
}, {
key: "set",
/**
*
* @param flag {number|Flags}
* @return {Flags}
*/
value: function set(flag) {
this.flags = this.flags | flag;
return this;
}
}, {
key: "unset",
/**
*
* @param flag {number|Flags}
* @return {Flags}
*/
value: function unset(flag) {
this.flags = this.flags & ~flag;
return this;
}
}, {
key: "reset",
/**
*
* @param flag {number|Flags}
* @return {Flags}
*/
value: function reset(flag) {
this.flags = isNaN(flag) ? 0 : +flag;
return this;
}
}]);
return Flags;
})();
return globalScope().Flags = Flags;
})();
</code></pre>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Home</a></h2><h3>Global</h3><ul><li><a href="global.html#value">value</a></li></ul>
</nav>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.2</a> on Thu Jul 09 2015 00:27:28 GMT+0300 (EEST)
</footer>
<script> prettyPrint(); </script>
<script src="scripts/linenumber.js"> </script>
</body>
</html>
|
Java
|
require 'cgi'
require 'nkf'
class Mechanize::Util
# default mime type data for Page::Image#mime_type.
# You can use another Apache-compatible mimetab.
# mimetab = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types')
# Mechanize::Util::DefaultMimeTypes.replace(mimetab)
DefaultMimeTypes = WEBrick::HTTPUtils::DefaultMimeTypes
class << self
# Builds a query string from a given enumerable object
# +parameters+. This method uses Mechanize::Util.each_parameter
# as preprocessor, which see.
def build_query_string(parameters, enc = nil)
each_parameter(parameters).inject(nil) { |s, (k, v)|
# WEBrick::HTTP.escape* has some problems about m17n on ruby-1.9.*.
(s.nil? ? '' : s << '&') << [CGI.escape(k.to_s), CGI.escape(v.to_s)].join('=')
} || ''
end
# Parses an enumerable object +parameters+ and iterates over the
# key-value pairs it contains.
#
# +parameters+ may be a hash, or any enumerable object which
# iterates over [key, value] pairs, typically an array of arrays.
#
# If a key is paired with an array-like object, the pair is
# expanded into multiple occurrences of the key, one for each
# element of the array. e.g. { a: [1, 2] } => [:a, 1], [:a, 2]
#
# If a key is paired with a hash-like object, the pair is expanded
# into hash-like multiple pairs, one for each pair of the hash.
# e.g. { a: { x: 1, y: 2 } } => ['a[x]', 1], ['a[y]', 2]
#
# An array-like value is allowed to be specified as hash value.
# e.g. { a: { q: [1, 2] } } => ['a[q]', 1], ['a[q]', 2]
#
# For a non-array-like, non-hash-like value, the key-value pair is
# yielded as is.
def each_parameter(parameters, &block)
return to_enum(__method__, parameters) if block.nil?
parameters.each { |key, value|
each_parameter_1(key, value, &block)
}
end
private
def each_parameter_1(key, value, &block)
return if key.nil?
case
when s = String.try_convert(value)
yield [key, s]
when a = Array.try_convert(value)
a.each { |avalue|
yield [key, avalue]
}
when h = Hash.try_convert(value)
h.each { |hkey, hvalue|
each_parameter_1('%s[%s]' % [key, hkey], hvalue, &block)
}
else
yield [key, value]
end
end
end
# Converts string +s+ from +code+ to UTF-8.
def self.from_native_charset(s, code, ignore_encoding_error = false, log = nil)
return s unless s && code
return s unless Mechanize.html_parser == Nokogiri::HTML
begin
s.encode(code)
rescue EncodingError => ex
log.debug("from_native_charset: #{ex.class}: form encoding: #{code.inspect} string: #{s}") if log
if ignore_encoding_error
s
else
raise
end
end
end
def self.html_unescape(s)
return s unless s
s.gsub(/&(\w+|#[0-9]+);/) { |match|
number = case match
when /&(\w+);/
Mechanize.html_parser::NamedCharacters[$1]
when /&#([0-9]+);/
$1.to_i
end
number ? ([number].pack('U') rescue match) : match
}
end
case NKF::BINARY
when Encoding
def self.guess_encoding(src)
# NKF.guess of JRuby may return nil
NKF.guess(src) || Encoding::US_ASCII
end
else
# Old NKF from 1.8, still bundled with Rubinius
NKF_ENCODING_MAP = {
NKF::UNKNOWN => Encoding::US_ASCII,
NKF::BINARY => Encoding::ASCII_8BIT,
NKF::ASCII => Encoding::US_ASCII,
NKF::JIS => Encoding::ISO_2022_JP,
NKF::EUC => Encoding::EUC_JP,
NKF::SJIS => Encoding::Shift_JIS,
NKF::UTF8 => Encoding::UTF_8,
NKF::UTF16 => Encoding::UTF_16BE,
NKF::UTF32 => Encoding::UTF_32BE,
}
def self.guess_encoding(src)
NKF_ENCODING_MAP[NKF.guess(src)]
end
end
def self.detect_charset(src)
if src
guess_encoding(src).name.upcase
else
Encoding::ISO8859_1.name
end
end
def self.uri_escape str, unsafe = nil
@parser ||= begin
URI::Parser.new
rescue NameError
URI
end
if URI == @parser then
unsafe ||= URI::UNSAFE
else
unsafe ||= @parser.regexp[:UNSAFE]
end
@parser.escape str, unsafe
end
def self.uri_unescape str
@parser ||= begin
URI::Parser.new
rescue NameError
URI
end
@parser.unescape str
end
end
|
Java
|
require 'english/class'
class English
# = Noun Number Inflections
#
# This module provides english singular <-> plural noun inflections.
module Inflect
@singular_of = {}
@plural_of = {}
@singular_rules = []
@plural_rules = []
# This class provides the DSL for creating inflections, you can add additional rules.
# Examples:
#
# word "ox", "oxen"
# word "octopus", "octopi"
# word "man", "men"
#
# rule "lf", "lves"
#
# word "equipment"
#
# Rules are evaluated by size, so rules you add to override specific cases should be longer than the rule
# it overrides. For instance, if you want "pta" to pluralize to "ptas", even though a general purpose rule
# for "ta" => "tum" already exists, simply add a new rule for "pta" => "ptas", and it will automatically win
# since it is longer than the old rule.
#
# Also, single-word exceptions win over general words ("ox" pluralizes to "oxen", because it's a single word
# exception, even though "fox" pluralizes to "foxes")
class << self
# Define a general two-way exception.
#
# This also defines a general rule, so foo_child will correctly become
# foo_children.
#
# Whole words also work if they are capitalized (Goose => Geese).
def word(singular, plural=nil)
plural = singular unless plural
singular_word(singular, plural)
plural_word(singular, plural)
rule(singular, plural)
end
# Define a singularization exception.
def singular_word(singular, plural)
@singular_of[plural] = singular
@singular_of[plural.capitalize] = singular.capitalize
end
# Define a pluralization exception.
def plural_word(singular, plural)
@plural_of[singular] = plural
@plural_of[singular.capitalize] = plural.capitalize
end
# Define a general rule.
def rule(singular, plural)
singular_rule(singular, plural)
plural_rule(singular, plural)
end
# Define a singularization rule.
def singular_rule(singular, plural)
@singular_rules << [singular, plural]
end
# Define a plurualization rule.
def plural_rule(singular, plural)
@plural_rules << [singular, plural]
end
# Read prepared singularization rules.
def singularization_rules
if defined?(@singularization_regex) && @singularization_regex
return [@singularization_regex, @singularization_hash]
end
# No sorting needed: Regexen match on longest string
@singularization_regex = Regexp.new("(" + @singular_rules.map {|s,p| p}.join("|") + ")$", "i")
@singularization_hash = Hash[*@singular_rules.flatten].invert
[@singularization_regex, @singularization_hash]
end
# Read prepared singularization rules.
#def singularization_rules
# return @singularization_rules if @singularization_rules
# sorted = @singular_rules.sort_by{ |s, p| "#{p}".size }.reverse
# @singularization_rules = sorted.collect do |s, p|
# [ /#{p}$/, "#{s}" ]
# end
#end
# Read prepared pluralization rules.
def pluralization_rules
if defined?(@pluralization_regex) && @pluralization_regex
return [@pluralization_regex, @pluralization_hash]
end
@pluralization_regex = Regexp.new("(" + @plural_rules.map {|s,p| s}.join("|") + ")$", "i")
@pluralization_hash = Hash[*@plural_rules.flatten]
[@pluralization_regex, @pluralization_hash]
end
# Read prepared pluralization rules.
#def pluralization_rules
# return @pluralization_rules if @pluralization_rules
# sorted = @plural_rules.sort_by{ |s, p| "#{s}".size }.reverse
# @pluralization_rules = sorted.collect do |s, p|
# [ /#{s}$/, "#{p}" ]
# end
#end
#
def singular_of ; @singular_of ; end
#
def plural_of ; @plural_of ; end
# Convert an English word from plurel to singular.
#
# "boys".singular #=> boy
# "tomatoes".singular #=> tomato
#
def singular(word)
return "" if word == ""
if result = singular_of[word]
return result.dup
end
result = word.dup
regex, hash = singularization_rules
result.sub!(regex) {|m| hash[m]}
singular_of[word] = result
return result
#singularization_rules.each do |(match, replacement)|
# break if result.gsub!(match, replacement)
#end
#return result
end
# Alias for #singular (a Railism).
#
alias_method(:singularize, :singular)
# Convert an English word from singular to plurel.
#
# "boy".plural #=> boys
# "tomato".plural #=> tomatoes
#
def plural(word)
return "" if word == ""
if result = plural_of[word]
return result.dup
end
#return self.dup if /s$/ =~ self # ???
result = word.dup
regex, hash = pluralization_rules
result.sub!(regex) {|m| hash[m]}
plural_of[word] = result
return result
#pluralization_rules.each do |(match, replacement)|
# break if result.gsub!(match, replacement)
#end
#return result
end
# Alias for #plural (a Railism).
alias_method(:pluralize, :plural)
# Clear all rules.
def clear(type = :all)
if type == :singular || type == :all
@singular_of = {}
@singular_rules = []
@singularization_rules, @singularization_regex = nil, nil
end
if type == :plural || type == :all
@singular_of = {}
@singular_rules = []
@singularization_rules, @singularization_regex = nil, nil
end
end
end
# One argument means singular and plural are the same.
word 'equipment'
word 'information'
word 'money'
word 'species'
word 'series'
word 'fish'
word 'sheep'
word 'moose'
word 'hovercraft'
word 'news'
word 'rice'
word 'plurals'
# Two arguments defines a singular and plural exception.
word 'Swiss' , 'Swiss'
word 'alias' , 'aliases'
word 'analysis' , 'analyses'
#word 'axis' , 'axes'
word 'basis' , 'bases'
word 'buffalo' , 'buffaloes'
word 'child' , 'children'
#word 'cow' , 'kine'
word 'crisis' , 'crises'
word 'criterion' , 'criteria'
word 'datum' , 'data'
word 'goose' , 'geese'
word 'hive' , 'hives'
word 'index' , 'indices'
word 'life' , 'lives'
word 'louse' , 'lice'
word 'man' , 'men'
word 'matrix' , 'matrices'
word 'medium' , 'media'
word 'mouse' , 'mice'
word 'movie' , 'movies'
word 'octopus' , 'octopi'
word 'ox' , 'oxen'
word 'person' , 'people'
word 'potato' , 'potatoes'
word 'quiz' , 'quizzes'
word 'shoe' , 'shoes'
word 'status' , 'statuses'
word 'testis' , 'testes'
word 'thesis' , 'theses'
word 'thief' , 'thieves'
word 'tomato' , 'tomatoes'
word 'torpedo' , 'torpedoes'
word 'vertex' , 'vertices'
word 'virus' , 'viri'
word 'wife' , 'wives'
# One-way singularization exception (convert plural to singular).
singular_word 'cactus', 'cacti'
# One-way pluralizaton exception (convert singular to plural).
plural_word 'axis', 'axes'
# General rules.
rule 'rf' , 'rves'
rule 'ero' , 'eroes'
rule 'ch' , 'ches'
rule 'sh' , 'shes'
rule 'ss' , 'sses'
#rule 'ess' , 'esses'
rule 'ta' , 'tum'
rule 'ia' , 'ium'
rule 'ra' , 'rum'
rule 'ay' , 'ays'
rule 'ey' , 'eys'
rule 'oy' , 'oys'
rule 'uy' , 'uys'
rule 'y' , 'ies'
rule 'x' , 'xes'
rule 'lf' , 'lves'
rule 'ffe' , 'ffes'
rule 'af' , 'aves'
rule 'us' , 'uses'
rule 'ouse' , 'ouses'
rule 'osis' , 'oses'
rule 'ox' , 'oxes'
rule '' , 's'
# One-way singular rules.
singular_rule 'of' , 'ofs' # proof
singular_rule 'o' , 'oes' # hero, heroes
#singular_rule 'f' , 'ves'
# One-way plural rules.
plural_rule 's' , 'ses'
plural_rule 'ive' , 'ives' # don't want to snag wife
plural_rule 'fe' , 'ves' # don't want to snag perspectives
end
#
def self.singular(string)
English::Inflect.singular(string)
end
#
def self.plural(string)
English::Inflect.plural(string)
end
# Convert an English word from plurel to singular.
#
# "boys".singular #=> boy
# "tomatoes".singular #=> tomato
#
def singular
self.class.singular(@self)
end
# Alias for #singular.
alias_method(:singularize, :singular)
# Convert an English word from plurel to singular.
#
# "boys".singular #=> boy
# "tomatoes".singular #=> tomato
#
def plural
self.class.plural(@self)
end
# Alias for #plural.
alias_method(:pluralize, :plural)
end
|
Java
|
#ifndef MOAISPINEANIMATIONMIXTABLE_H
#define MOAISPINEANIMATIONMIXTABLE_H
#include <moai-core/headers.h>
//----------------------------------------------------------------//
class MOAISpineAnimationMixEntry
{
public:
STLString mSrc;
STLString mTarget;
// STLString mOverlay;
float mDuration;
float mDelay; //delay before playing target animation, should be < mDuration
};
//----------------------------------------------------------------//
class MOAISpineAnimationMixTable :
public virtual MOAILuaObject
{
private:
typedef STLMap < STLString, MOAISpineAnimationMixEntry* >::iterator MixMapIt;
STLMap < STLString, MOAISpineAnimationMixEntry* > mMixMap ;
static int _setMix ( lua_State* L );
static int _getMix ( lua_State* L );
MOAISpineAnimationMixEntry* AffirmMix( STLString src, STLString target );
public:
MOAISpineAnimationMixEntry* GetMix( STLString src, STLString target );
// void SetMix();
DECL_LUA_FACTORY( MOAISpineAnimationMixTable )
MOAISpineAnimationMixTable();
~MOAISpineAnimationMixTable();
void RegisterLuaClass ( MOAILuaState& state );
void RegisterLuaFuncs ( MOAILuaState& state );
};
#endif
|
Java
|
var PixiText = require('../../lib/pixi/src/core/text/Text'),
utils = require('../core/utils'),
math = require('../../lib/pixi/src/core/math'),
Sprite = require('../display/Sprite'),
CONST = require('../core/const');
function Text(text, style, resolution){
this._init(text, style, resolution);
}
Text.prototype = Object.create(PixiText.prototype);
Text.prototype.constructor = Text;
Text.fontPropertiesCache = {};
Text.fontPropertiesCanvas = document.createElement('canvas');
Text.fontPropertiesContext = Text.fontPropertiesCanvas.getContext('2d');
Text.prototype._init = function(text, style, resolution){
text = text || ' ';
PixiText.call(this, text, style, resolution);
this.speed = new math.Point();
this.anchor = new math.Point(0.5, 0.5);
this.pivot = new math.Point(0.5, 0.5);
};
Text.prototype.displayObjectUpdateTransform = function(){
// create some matrix refs for easy access
var pt = this.parent.worldTransform;
var wt = this.worldTransform;
//anchor, pivot, and flip variables
var sx = (this.flipX) ? -this.scale.x : this.scale.x,
sy = (this.flipY) ? -this.scale.y : this.scale.y,
ax = (this.flipX) ? 1-this.anchor.x : this.anchor.x,
ay = (this.flipY) ? 1-this.anchor.y : this.anchor.y,
px = (this.flipX) ? 1-this.pivot.x : this.pivot.x,
py = (this.flipY) ? 1-this.pivot.y : this.pivot.y;
// temporary matrix variables
var a, b, c, d, tx, ty;
//Avoid use _width or _height when are 0
if(!this._width||!this._height){
this._width = this.width/this.scale.x;
this._height = this.height/this.scale.y;
}
var anchorWidth = ax * this._width * sx,
anchorHeight = ay * this._height * sy,
pivotWidth = px * this._width * sx,
pivotHeight = py * this._height * sy;
// so if rotation is between 0 then we can simplify the multiplication process...
if (this.rotation % CONST.PI_2)
{
// check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes
if (this.rotation !== this.rotationCache)
{
this.rotationCache = this.rotation;
this._sr = Math.sin(this.rotation);
this._cr = Math.cos(this.rotation);
}
// get the matrix values of the displayobject based on its transform properties..
a = this._cr * sx;
b = this._sr * sx;
c = -this._sr * sy;
d = this._cr * sy;
tx = this.position.x + pivotWidth - anchorWidth;
ty = this.position.y + pivotHeight - anchorHeight;
if (pivotWidth || pivotHeight)
{
tx -= pivotWidth * this._cr + pivotHeight * -this._sr;
ty -= pivotWidth * this._sr + pivotHeight * this._cr;
}
// concat the parent matrix with the objects transform.
wt.a = a * pt.a + b * pt.c;
wt.b = a * pt.b + b * pt.d;
wt.c = c * pt.a + d * pt.c;
wt.d = c * pt.b + d * pt.d;
wt.tx = tx * pt.a + ty * pt.c + pt.tx;
wt.ty = tx * pt.b + ty * pt.d + pt.ty;
}
else
{
// lets do the fast version as we know there is no rotation..
a = sx;
d = sy;
tx = this.position.x - anchorWidth;
ty = this.position.y - anchorHeight;
wt.a = a * pt.a;
wt.b = a * pt.b;
wt.c = d * pt.c;
wt.d = d * pt.d;
wt.tx = tx * pt.a + ty * pt.c + pt.tx;
wt.ty = tx * pt.b + ty * pt.d + pt.ty;
}
// multiply the alphas..
this.worldAlpha = this.alpha * this.parent.worldAlpha;
// reset the bounds each time this is called!
this._currentBounds = null;
};
Text.prototype._renderCanvas = function (renderer)
{
if (this.dirty)
{
// this.resolution = 1//renderer.resolution;
this.updateText();
}
//Sprite.prototype._renderCanvas.call(this, renderer);
this._customRenderCanvas(renderer);
};
Text.prototype._customRenderCanvas = function(renderer){
if (this.texture.crop.width <= 0 || this.texture.crop.height <= 0)
{
return;
}
if (this.blendMode !== renderer.currentBlendMode)
{
renderer.currentBlendMode = this.blendMode;
renderer.context.globalCompositeOperation = renderer.blendModes[renderer.currentBlendMode];
}
// Ignore null sources
if (this.texture.valid)
{
var texture = this._texture,
wt = this.worldTransform,
dx,
dy,
width,
height;
var resolution = texture.baseTexture.resolution / renderer.resolution;
renderer.context.globalAlpha = this.worldAlpha;
// If smoothingEnabled is supported and we need to change the smoothing property for this texture
if (renderer.smoothProperty && renderer.currentScaleMode !== texture.baseTexture.scaleMode)
{
renderer.currentScaleMode = texture.baseTexture.scaleMode;
renderer.context[renderer.smoothProperty] = (renderer.currentScaleMode === CONST.SCALE_MODES.LINEAR);
}
// If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions
if(texture.rotate)
{
// cheeky rotation!
var a = wt.a;
var b = wt.b;
wt.a = -wt.c;
wt.b = -wt.d;
wt.c = a;
wt.d = b;
width = texture.crop.height; //TODO: Width assigned to height???
height = texture.crop.width;
dx = (texture.trim) ? texture.trim.y - this.anchor.y * texture.trim.height : this.anchor.y * -texture._frame.height;
dy = (texture.trim) ? texture.trim.x - this.anchor.x * texture.trim.width : this.anchor.x * -texture._frame.width;
}
else
{
width = texture.crop.width;
height = texture.crop.height;
dx = (texture.trim) ? texture.trim.x - this.anchor.x * texture.trim.width : this.anchor.x * -texture._frame.width;
dy = (texture.trim) ? texture.trim.y - this.anchor.y * texture.trim.height : this.anchor.y * -texture._frame.height;
}
// Allow for pixel rounding
if (renderer.roundPixels)
{
renderer.context.setTransform(
wt.a,
wt.b,
wt.c,
wt.d,
(wt.tx * renderer.resolution) | 0,
(wt.ty * renderer.resolution) | 0
);
dx = dx | 0;
dy = dy | 0;
}
else
{
renderer.context.setTransform(
wt.a,
wt.b,
wt.c,
wt.d,
wt.tx * renderer.resolution,
wt.ty * renderer.resolution
);
}
var anchorWidth = this.anchor.x * this._width/resolution,
anchorHeight = this.anchor.y * this._height/resolution;
if (this.tint !== 0xFFFFFF)
{
if (this.cachedTint !== this.tint)
{
this.cachedTint = this.tint;
// TODO clean up caching - how to clean up the caches?
// TODO: dont works with spritesheets
this.tintedTexture = CanvasTinter.getTintedTexture(this, this.tint);
}
renderer.context.drawImage(
this.tintedTexture,
0,
0,
width * resolution * renderer.resolution,
height * resolution * renderer.resolution,
dx / resolution,
dy / resolution,
width * renderer.resolution,
height * renderer.resolution
);
}
else
{
//TODO: cuando la resolución del renderer es mayor a 1 los sprites se muestran mal
renderer.context.drawImage(
texture.baseTexture.source,
texture.crop.x * resolution,
texture.crop.y * resolution,
width * resolution * renderer.resolution,
height * resolution * renderer.resolution,
dx / resolution + anchorWidth,
dy / resolution + anchorHeight,
width * renderer.resolution,
height * renderer.resolution
);
}
}
};
Text.prototype.renderWebGL = function (renderer)
{
if (this.dirty)
{
//this.resolution = 1//renderer.resolution;
this.updateText();
}
Sprite.prototype.renderWebGL.call(this, renderer);
};
Text.prototype.updateText = function (){
var style = this._style;
this.context.font = style.font;
// word wrap
// preserve original text
var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text;
// split text into lines
var lines = outputText.split(/(?:\r\n|\r|\n)/);
// calculate text width
var lineWidths = new Array(lines.length);
var maxLineWidth = 0;
var fontProperties = this.determineFontProperties(style.font);
for (var i = 0; i < lines.length; i++)
{
var lineWidth = this.context.measureText(lines[i]).width;
lineWidths[i] = lineWidth;
maxLineWidth = Math.max(maxLineWidth, lineWidth);
}
var width = maxLineWidth + style.strokeThickness;
if (style.dropShadow)
{
width += style.dropShadowDistance;
}
this.canvas.width = ( width + this.context.lineWidth ) * this.resolution;
// calculate text height
var lineHeight = this.style.lineHeight || fontProperties.fontSize + style.strokeThickness;
var height = lineHeight * lines.length;
if (style.dropShadow)
{
height += style.dropShadowDistance;
}
this.canvas.height = ( height + this._style.padding * 2 ) * this.resolution;
this.context.scale( this.resolution, this.resolution);
if (navigator.isCocoonJS)
{
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
//this.context.fillStyle="#FF0000";
//this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.font = style.font;
this.context.strokeStyle = (typeof style.stroke === "number") ? utils.hex2string(style.stroke) : style.stroke;
this.context.lineWidth = style.strokeThickness;
this.context.textBaseline = style.textBaseline;
this.context.lineJoin = style.lineJoin;
this.context.miterLimit = style.miterLimit;
var linePositionX;
var linePositionY;
if (style.dropShadow)
{
this.context.fillStyle = style.dropShadowColor;
var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance;
var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance;
for (i = 0; i < lines.length; i++)
{
linePositionX = style.strokeThickness / 2;
linePositionY = (style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent;
if (style.align === 'right')
{
linePositionX += maxLineWidth - lineWidths[i];
}
else if (style.align === 'center')
{
linePositionX += (maxLineWidth - lineWidths[i]) / 2;
}
if (style.fill)
{
this.context.fillText(lines[i], linePositionX + xShadowOffset, linePositionY + yShadowOffset + this._style.padding);
}
}
}
//set canvas text styles
this.context.fillStyle = (typeof style.fill === "number") ? utils.hex2string(style.fill) : style.fill;
//draw lines line by line
for (i = 0; i < lines.length; i++)
{
linePositionX = style.strokeThickness / 2;
linePositionY = (style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent;
if (style.align === 'right')
{
linePositionX += maxLineWidth - lineWidths[i];
}
else if (style.align === 'center')
{
linePositionX += (maxLineWidth - lineWidths[i]) / 2;
}
if (style.stroke && style.strokeThickness)
{
this.context.strokeText(lines[i], linePositionX, linePositionY + this._style.padding);
}
if (style.fill)
{
this.context.fillText(lines[i], linePositionX, linePositionY + this._style.padding);
}
}
this.updateTexture();
};
Text.prototype.setStyle = function(style){
this.style = style;
return this;
};
Text.prototype.setText = function(text, keys){
if(keys)text = utils.parseTextKeys(text, keys);
this.text = text;
return this;
};
Text.prototype.setWordWrap = function(value){
if(value === false){
this.style.wordWrap = value;
}else{
this.style.wordWrap = true;
this.style.wordWrapWidth = value;
}
this.dirty = true;
return this;
};
Text.prototype.containsPoint = Sprite.prototype.containsPoint;
Text.prototype.getLocalBounds = Sprite.prototype.getLocalBounds;
module.exports = Text;
|
Java
|
/**
* A wrapper around JSLint to drop things into the console
*
* Copyright (C) 2011 Nikolay Nemshilov
*/
var RightJS = require('./right-server.js');
var JSLint = require('./jslint').JSLINT;
var fs = require('fs');
exports.Linter = new RightJS.Class({
extend: {
Options: {
debug: false, // no debug
devel: false, // no console.log s
evil: false, // no evals
passfail: false, // don't stop on errors
onevar: false, // allow more than one 'var' definition
forin: true , // allow for in without ownershipt checks
indent: 2 , // enforce 2 spaces indent
maxerr: 12 , // max number of errors
},
Okays: [
"Move 'var' declarations to the top of the function.",
"Do not use 'new' for side effects.",
"The Function constructor is eval."
]
},
/**
* Basic constructor
*
* @param {String} the source
* @param {String} the linter options
* @return void
*/
initialize: function(src, options) {
this.source = src;
this.options = options;
},
/**
* Runs the linter
*
* @return {Linter} this
*/
run: function() {
var options = {}, okays = [], patches = '';
// extracting the additional options
try { // skipping non-existing patch files
patches = fs.readFileSync(this.options).toString();
} catch(e) {}
eval(patches);
JSLint.okays = this.constructor.Okays.concat(okays);
JSLint(
fs.readFileSync(this.source).toString(),
Object.merge(this.constructor.Options, options)
);
this.errors = JSLint.errors.compact();
this.failed = this.errors.length > 0;
return this;
},
/**
* Prints out the check report
*
* @return {Linter} this
*/
report: function() {
if (this.errors.empty()) {
console.log("\u001B[32m - JSLint check successfully passed\u001B[0m");
} else {
console.log("\u001B[31m - JSLint check failed in: "+ this.source + "\u001B[0m");
this.errors.each(function(error) {
var report = "\n", j=0, pointer='';
for (; j < error.character-1; j++) { pointer += '-'; }
report += " \u001B[35m"+ error.reason +"\u001B[0m ";
if (error.evidence) {
report += "Line: "+ error.line + ", Char: "+ error.character + "\n";
report += " "+ error.evidence + "\n";
report += " \u001B[33m"+ pointer + "^\u001B[0m";
}
console.log(report);
});
console.log("\n")
}
return this;
}
});
|
Java
|
# coding=utf-8
import pygame
import pygame.locals
class Board(object):
"""
Plansza do gry. Odpowiada za rysowanie okna gry.
"""
def __init__(self, width, height):
"""
Konstruktor planszy do gry. Przygotowuje okienko gry.
:param width: szerokość w pikselach
:param height: wysokość w pikselach
"""
self.surface = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('Game of life')
def draw(self, *args):
"""
Rysuje okno gry
:param args: lista obiektów do narysowania
"""
background = (0, 0, 0)
self.surface.fill(background)
for drawable in args:
drawable.draw_on(self.surface)
# dopiero w tym miejscu następuje fatyczne rysowanie
# w oknie gry, wcześniej tylko ustalaliśmy co i jak ma zostać narysowane
pygame.display.update()
class GameOfLife(object):
"""
Łączy wszystkie elementy gry w całość.
"""
def __init__(self, width, height, cell_size=10):
"""
Przygotowanie ustawień gry
:param width: szerokość planszy mierzona liczbą komórek
:param height: wysokość planszy mierzona liczbą komórek
:param cell_size: bok komórki w pikselach
"""
pygame.init()
self.board = Board(width * cell_size, height * cell_size)
# zegar którego użyjemy do kontrolowania szybkości rysowania
# kolejnych klatek gry
self.fps_clock = pygame.time.Clock()
def run(self):
"""
Główna pętla gry
"""
while not self.handle_events():
# działaj w pętli do momentu otrzymania sygnału do wyjścia
self.board.draw()
self.fps_clock.tick(15)
def handle_events(self):
"""
Obsługa zdarzeń systemowych, tutaj zinterpretujemy np. ruchy myszką
:return True jeżeli pygame przekazał zdarzenie wyjścia z gry
"""
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
pygame.quit()
return True
# magiczne liczby używane do określenia czy komórka jest żywa
DEAD = 0
ALIVE = 1
class Population(object):
"""
Populacja komórek
"""
def __init__(self, width, height, cell_size=10):
"""
Przygotowuje ustawienia populacji
:param width: szerokość planszy mierzona liczbą komórek
:param height: wysokość planszy mierzona liczbą komórek
:param cell_size: bok komórki w pikselach
"""
self.box_size = cell_size
self.height = height
self.width = width
self.generation = self.reset_generation()
def reset_generation(self):
"""
Tworzy i zwraca macierz pustej populacji
"""
# w pętli wypełnij listę kolumnami
# które także w pętli zostają wypełnione wartością 0 (DEAD)
return [[DEAD for y in xrange(self.height)] for x in xrange(self.width)]
def handle_mouse(self):
# pobierz stan guzików myszki z wykorzystaniem funcji pygame
buttons = pygame.mouse.get_pressed()
if not any(buttons):
# ignoruj zdarzenie jeśli żaden z guzików nie jest wciśnięty
return
# dodaj żywą komórką jeśli wciśnięty jest pierwszy guzik myszki
# będziemy mogli nie tylko dodawać żywe komórki ale także je usuwać
alive = True if buttons[0] else False
# pobierz pozycję kursora na planszy mierzoną w pikselach
x, y = pygame.mouse.get_pos()
# przeliczamy współrzędne komórki z pikseli na współrzędne komórki w macierz
# gracz może kliknąć w kwadracie o szerokości box_size by wybrać komórkę
x /= self.box_size
y /= self.box_size
# ustaw stan komórki na macierzy
self.generation[x][y] = ALIVE if alive else DEAD
def draw_on(self, surface):
"""
Rysuje komórki na planszy
"""
for x, y in self.alive_cells():
size = (self.box_size, self.box_size)
position = (x * self.box_size, y * self.box_size)
color = (255, 255, 255)
thickness = 1
pygame.draw.rect(surface, color, pygame.locals.Rect(position, size), thickness)
def alive_cells(self):
"""
Generator zwracający współrzędne żywych komórek.
"""
for x in range(len(self.generation)):
column = self.generation[x]
for y in range(len(column)):
if column[y] == ALIVE:
# jeśli komórka jest żywa zwrócimy jej współrzędne
yield x, y
# Ta część powinna być zawsze na końcu modułu (ten plik jest modułem)
# chcemy uruchomić naszą grę dopiero po tym jak wszystkie klasy zostaną zadeklarowane
if __name__ == "__main__":
game = GameOfLife(80, 40)
game.run()
|
Java
|
using System.Linq.Expressions;
using System.Collections.Generic;
namespace Bermuda.ExpressionGeneration
{
public partial class ValueExpression : ExpressionTreeBase
{
public long Value { get; private set; }
public ValueExpression(long value)
{
Value = value;
}
public override string ToString()
{
return string.Format("@{0}", Value.ToString());
}
public override IEnumerable<ExpressionTreeBase> GetChildren()
{
yield break;
}
public override Expression CreateExpression(object context)
{
return Expression.Constant(Value);
}
}
}
|
Java
|
// String literal types are only valid in overload signatures
function foo(x: any);
function foo(x: 'hi') { }
class C {
foo(x: string);
foo(x: 'hi') { }
}
interface I {
(x: 'a');
(x: 'hi');
foo(x: 'a', y: 'a');
foo(x: 'hi', y: 'hi');
}
var a: {
(x: 'hi');
(x: 'a');
foo(x: 'hi');
foo(x: 'a');
}
var b = {
foo(x: 'hi') { },
foo(x: 'a') { },
}
|
Java
|
<?php
namespace PhraseanetSDK\Tests\Cache;
use PhraseanetSDK\Cache\BackendCacheFactory;
use PhraseanetSDK\Exception\RuntimeException;
class BackendCacheFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider provideValidParameters
*/
public function testCreateSuccess($type, $host, $port, $instanceOf, $classExists)
{
if (null !== $classExists) {
if (!class_exists($classExists)) {
$this->markTestSkipped(sprintf('Unable to find class %s', $classExists));
}
}
$factory = new BackendCacheFactory();
try {
$this->assertInstanceOf($instanceOf, $factory->create($type, $host, $port));
} catch (RuntimeException $e) {
$this->assertContains(ucfirst(strtolower($type)), $e->getMessage());
}
}
public function provideValidParameters()
{
return array(
array('memcache', '127.0.0.1', 11211, 'Doctrine\Common\Cache\MemcacheCache', 'Memcache'),
array('memcache', null, null, 'Doctrine\Common\Cache\MemcacheCache', 'Memcache'),
array('memcached', '127.0.0.1', 11211, 'Doctrine\Common\Cache\MemcachedCache', 'Memcached'),
array('memcached', null, null, 'Doctrine\Common\Cache\MemcachedCache', 'Memcached'),
array('array', '127.0.0.1', 11211, 'Doctrine\Common\Cache\ArrayCache', null),
array('array', null, null, 'Doctrine\Common\Cache\ArrayCache', null),
);
}
/**
* @dataProvider provideInvalidParameters
* @expectedException PhraseanetSDK\Exception\RuntimeException
*/
public function testCreateFailure($type, $host, $port, $classExists)
{
if (null !== $classExists) {
if (!class_exists($classExists)) {
$this->markTestSkipped(sprintf('Unable to find class %s', $classExists));
}
}
$factory = new BackendCacheFactory();
$factory->create($type, $host, $port);
}
public function provideInvalidParameters()
{
return array(
array('memcache', 'nohost', 'noport', 'Memcache'),
array('memcached', 'nohost', 'noport', 'Memcache'),
array('unknown', 'nohost', 'noport', null),
array('unknown', null, null, null),
);
}
}
|
Java
|
"""
File-based Checkpoints implementations.
"""
import os
import shutil
from tornado.web import HTTPError
from .checkpoints import (
Checkpoints,
GenericCheckpointsMixin,
)
from .fileio import FileManagerMixin
from IPython.utils import tz
from IPython.utils.path import ensure_dir_exists
from IPython.utils.py3compat import getcwd
from IPython.utils.traitlets import Unicode
class FileCheckpoints(FileManagerMixin, Checkpoints):
"""
A Checkpoints that caches checkpoints for files in adjacent
directories.
Only works with FileContentsManager. Use GenericFileCheckpoints if
you want file-based checkpoints with another ContentsManager.
"""
checkpoint_dir = Unicode(
'.ipynb_checkpoints',
config=True,
help="""The directory name in which to keep file checkpoints
This is a path relative to the file's own directory.
By default, it is .ipynb_checkpoints
""",
)
root_dir = Unicode(config=True)
def _root_dir_default(self):
try:
return self.parent.root_dir
except AttributeError:
return getcwd()
# ContentsManager-dependent checkpoint API
def create_checkpoint(self, contents_mgr, path):
"""Create a checkpoint."""
checkpoint_id = u'checkpoint'
src_path = contents_mgr._get_os_path(path)
dest_path = self.checkpoint_path(checkpoint_id, path)
self._copy(src_path, dest_path)
return self.checkpoint_model(checkpoint_id, dest_path)
def restore_checkpoint(self, contents_mgr, checkpoint_id, path):
"""Restore a checkpoint."""
src_path = self.checkpoint_path(checkpoint_id, path)
dest_path = contents_mgr._get_os_path(path)
self._copy(src_path, dest_path)
# ContentsManager-independent checkpoint API
def rename_checkpoint(self, checkpoint_id, old_path, new_path):
"""Rename a checkpoint from old_path to new_path."""
old_cp_path = self.checkpoint_path(checkpoint_id, old_path)
new_cp_path = self.checkpoint_path(checkpoint_id, new_path)
if os.path.isfile(old_cp_path):
self.log.debug(
"Renaming checkpoint %s -> %s",
old_cp_path,
new_cp_path,
)
with self.perm_to_403():
shutil.move(old_cp_path, new_cp_path)
def delete_checkpoint(self, checkpoint_id, path):
"""delete a file's checkpoint"""
path = path.strip('/')
cp_path = self.checkpoint_path(checkpoint_id, path)
if not os.path.isfile(cp_path):
self.no_such_checkpoint(path, checkpoint_id)
self.log.debug("unlinking %s", cp_path)
with self.perm_to_403():
os.unlink(cp_path)
def list_checkpoints(self, path):
"""list the checkpoints for a given file
This contents manager currently only supports one checkpoint per file.
"""
path = path.strip('/')
checkpoint_id = "checkpoint"
os_path = self.checkpoint_path(checkpoint_id, path)
if not os.path.isfile(os_path):
return []
else:
return [self.checkpoint_model(checkpoint_id, os_path)]
# Checkpoint-related utilities
def checkpoint_path(self, checkpoint_id, path):
"""find the path to a checkpoint"""
path = path.strip('/')
parent, name = ('/' + path).rsplit('/', 1)
parent = parent.strip('/')
basename, ext = os.path.splitext(name)
filename = u"{name}-{checkpoint_id}{ext}".format(
name=basename,
checkpoint_id=checkpoint_id,
ext=ext,
)
os_path = self._get_os_path(path=parent)
cp_dir = os.path.join(os_path, self.checkpoint_dir)
with self.perm_to_403():
ensure_dir_exists(cp_dir)
cp_path = os.path.join(cp_dir, filename)
return cp_path
def checkpoint_model(self, checkpoint_id, os_path):
"""construct the info dict for a given checkpoint"""
stats = os.stat(os_path)
last_modified = tz.utcfromtimestamp(stats.st_mtime)
info = dict(
id=checkpoint_id,
last_modified=last_modified,
)
return info
# Error Handling
def no_such_checkpoint(self, path, checkpoint_id):
raise HTTPError(
404,
u'Checkpoint does not exist: %s@%s' % (path, checkpoint_id)
)
class GenericFileCheckpoints(GenericCheckpointsMixin, FileCheckpoints):
"""
Local filesystem Checkpoints that works with any conforming
ContentsManager.
"""
def create_file_checkpoint(self, content, format, path):
"""Create a checkpoint from the current content of a file."""
path = path.strip('/')
# only the one checkpoint ID:
checkpoint_id = u"checkpoint"
os_checkpoint_path = self.checkpoint_path(checkpoint_id, path)
self.log.debug("creating checkpoint for %s", path)
with self.perm_to_403():
self._save_file(os_checkpoint_path, content, format=format)
# return the checkpoint info
return self.checkpoint_model(checkpoint_id, os_checkpoint_path)
def create_notebook_checkpoint(self, nb, path):
"""Create a checkpoint from the current content of a notebook."""
path = path.strip('/')
# only the one checkpoint ID:
checkpoint_id = u"checkpoint"
os_checkpoint_path = self.checkpoint_path(checkpoint_id, path)
self.log.debug("creating checkpoint for %s", path)
with self.perm_to_403():
self._save_notebook(os_checkpoint_path, nb)
# return the checkpoint info
return self.checkpoint_model(checkpoint_id, os_checkpoint_path)
def get_notebook_checkpoint(self, checkpoint_id, path):
"""Get a checkpoint for a notebook."""
path = path.strip('/')
self.log.info("restoring %s from checkpoint %s", path, checkpoint_id)
os_checkpoint_path = self.checkpoint_path(checkpoint_id, path)
if not os.path.isfile(os_checkpoint_path):
self.no_such_checkpoint(path, checkpoint_id)
return {
'type': 'notebook',
'content': self._read_notebook(
os_checkpoint_path,
as_version=4,
),
}
def get_file_checkpoint(self, checkpoint_id, path):
"""Get a checkpoint for a file."""
path = path.strip('/')
self.log.info("restoring %s from checkpoint %s", path, checkpoint_id)
os_checkpoint_path = self.checkpoint_path(checkpoint_id, path)
if not os.path.isfile(os_checkpoint_path):
self.no_such_checkpoint(path, checkpoint_id)
content, format = self._read_file(os_checkpoint_path, format=None)
return {
'type': 'file',
'content': content,
'format': format,
}
|
Java
|
import React, { PropTypes } from 'react'
import ActionDelete from 'material-ui/svg-icons/action/delete'
import { colors } from '/styles'
import moduleStyles from '/styles/fileTree'
const RemoveBtn = ({ onClick }) => (
<ActionDelete
onClick={onClick}
style={moduleStyles.listIcon.base}
color={colors.light}
hoverColor={colors.hover.red} />
)
export default RemoveBtn
|
Java
|
// Source : https://leetcode.com/problems/longest-substring-without-repeating-characters/
// Author : codeyu
// Date : 2016-09-20
/**********************************************************************************
*
* Given a string, find the length of the longest substring without repeating characters.
*
* Examples:
*
* Given "abcabcbb", the answer is "abc", which the length is 3.
*
* Given "bbbbb", the answer is "b", with the length of 1.
*
* Given "pwwkew", the answer is "wke", with the length of 3.
*
* Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
*
**********************************************************************************/
using System.Collections.Generic;
using System;
namespace Algorithms
{
public class Solution003
{
public static int LengthOfLongestSubstring(string s)
{
var n = s.Length;
var charSet = new HashSet<char>();
int maxLength = 0, i = 0, j = 0;
while (i < n && j < n)
{
if (charSet.Add(s[j]))
{
j++;
maxLength = Math.Max(maxLength, j - i);
}
else
{
charSet.Remove(s[i]);
i++;
}
}
return maxLength;
}
}
}
|
Java
|
using System.Collections.ObjectModel;
namespace SimpleBackgroundUploadWebAPI.Areas.HelpPage.ModelDescriptions
{
public class ComplexTypeModelDescription : ModelDescription
{
public ComplexTypeModelDescription()
{
Properties = new Collection<ParameterDescription>();
}
public Collection<ParameterDescription> Properties { get; private set; }
}
}
|
Java
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!-- end header part -->
<!-- Generated by Doxygen 1.8.4 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="a00237.html">tbb</a></li><li class="navelem"><b>interface5</b></li><li class="navelem"><a class="el" href="a00046.html">concurrent_unordered_multimap</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator > Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>allocator_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>concurrent_unordered_multimap</b>(size_type n_of_buckets=base_type::initial_bucket_number, const hasher &_Hasher=hasher(), const key_equal &_Key_equality=key_equal(), const allocator_type &a=allocator_type()) (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">explicit</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>concurrent_unordered_multimap</b>(const Allocator &a) (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">explicit</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>concurrent_unordered_multimap</b>(Iterator first, Iterator last, size_type n_of_buckets=base_type::initial_bucket_number, const hasher &_Hasher=hasher(), const key_equal &_Key_equality=key_equal(), const allocator_type &a=allocator_type()) (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="a00046.html#a5957d29e5fa9f8c53538de3f7a41ebc9">concurrent_unordered_multimap</a>(std::initializer_list< value_type > il, size_type n_of_buckets=base_type::initial_bucket_number, const hasher &_Hasher=hasher(), const key_equal &_Key_equality=key_equal(), const allocator_type &a=allocator_type())</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>concurrent_unordered_multimap</b>(const concurrent_unordered_multimap &table) (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>concurrent_unordered_multimap</b>(concurrent_unordered_multimap &&table) (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>concurrent_unordered_multimap</b>(concurrent_unordered_multimap &&table, const Allocator &a) (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>concurrent_unordered_multimap</b>(const concurrent_unordered_multimap &table, const Allocator &a) (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>const_iterator</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>const_local_iterator</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>const_pointer</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>const_reference</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>difference_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>hasher</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>iterator</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>key_compare</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>key_equal</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>key_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>local_iterator</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>mapped_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>operator=</b>(const concurrent_unordered_multimap &table) (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>operator=</b>(concurrent_unordered_multimap &&table) (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>pointer</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>reference</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>size_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>value_type</b> typedef (defined in <a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a>)</td><td class="entry"><a class="el" href="a00046.html">tbb::interface5::concurrent_unordered_multimap< Key, T, Hasher, Key_equality, Allocator ></a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<hr>
<p></p>
Copyright © 2005-2017 Intel Corporation. All Rights Reserved.
<p></p>
Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.
<p></p>
* Other names and brands may be claimed as the property of others.
|
Java
|
#require File.dirname(__FILE__) + '/formats/email'
module DataMapper
module Validate
##
#
# @author Guy van den Berg
# @since 0.9
class CustomValidator < GenericValidator
def initialize(field_name, options = {}, &b)
#super(field_name, options)
#@field_name, @options = field_name, options
#@options[:allow_nil] = false unless @options.has_key?(:allow_nil)
end
def call(target)
#field_value = target.instance_variable_get("@#{@field_name}")
#return true if @options[:allow_nil] && field_value.nil?
#validation = (@options[:as] || @options[:with])
#error_message = nil
# Figure out what to use as the actual validator.
# If a symbol is passed to :as, look up
# the canned validation in FORMATS.
#
#validator = if validation.is_a? Symbol
# if FORMATS[validation].is_a? Array
# error_message = FORMATS[validation][1]
# FORMATS[validation][0]
# else
# FORMATS[validation] || validation
# end
#else
# validation
#end
#valid = case validator
#when Proc then validator.call(field_value)
#when Regexp then validator =~ field_value
#else raise UnknownValidationFormat, "Can't determine how to validate #{target.class}##{@field_name} with #{validator.inspect}"
#end
#unless valid
# field = Inflector.humanize(@field_name)
# value = field_value
#
# error_message = @options[:message] || error_message || '%s is invalid'.t(field)
# error_message = error_message.call(field, value) if Proc === error_message
#
# add_error(target, error_message , @field_name)
#end
#return valid
end
#class UnknownValidationFormat < StandardError; end
end # class CustomValidator
module ValidatesFormatOf
#def validates_format_of(*fields)
#opts = opts_from_validator_args(fields)
#add_validator_to_context(opts, fields, DataMapper::Validate::FormatValidator)
#end
end # module ValidatesFormatOf
end # module Validate
end # module DataMapper
|
Java
|
lib: node_modules $(shell find src)
rm -rf lib
node_modules/.bin/coffee --output lib --compile src
test: node_modules
node_modules/.bin/mocha test/suite
coverage: node_modules
node_modules/.bin/mocha --require test/coverage test/suite
node_modules/.bin/istanbul report
lint: node_modules
node_modules/.bin/coffeelint --file coffeelint.json src
node_modules/.bin/coffeelint --file test/coffeelint.json test/suite
ci: coverage
.PHONY: test coverage lint ci
node_modules:
npm install
|
Java
|
## Django 示例
|
Java
|
#!/usr/bin/ruby
require "fileutils"
require 'json'
require_relative "BibleReader.rb"
reader = BibleReader.new
translation_names = ['개역개정', '새번역', 'NIV']#BibleInfo.translation_name_to_code.keys
translation_names.each do |translation_name|
translation_code = BibleInfo.translation_name_to_code[translation_name]
BibleInfo.bible_name_to_chapter_len.each do |bible_name, chapter_len|
# puts "#{translation_name}, #{bible_name}, #{chapter_len}"
bible_shortname = BibleInfo.bible_name_to_shortname[bible_name]
db_name = "db/#{translation_name}/#{"%02d_" % BibleInfo.bible_name_to_code[bible_name]}#{bible_name}"
unless Dir.exist? db_name
FileUtils.mkdir_p(db_name)
end
(1..chapter_len).each do |chapter|
file = File.open "#{db_name}/#{chapter}", 'w'
chapter_content = reader.get_chapter_from_web(translation_name, bible_shortname, chapter)
file.write(chapter_content.to_json)
file.close()
end
end
end
|
Java
|
<?php
/**
* TOP API: taobao.hotel.order.face.deal request
*
* @author auto create
* @since 1.0, 2013-09-13 16:51:03
*/
class Taobao_Request_HotelOrderFaceDealRequest {
/**
* 酒店订单oid
**/
private $oid;
/**
* 操作类型,1:确认预订,2:取消订单
**/
private $operType;
/**
* 取消订单时的取消原因备注信息
**/
private $reasonText;
/**
* 取消订单时的取消原因,可选值:1,2,3,4;
* 1:无房,2:价格变动,3:买家原因,4:其它原因
**/
private $reasonType;
private $apiParas = array();
public function setOid($oid) {
$this->oid = $oid;
$this->apiParas["oid"] = $oid;
}
public function getOid() {
return $this->oid;
}
public function setOperType($operType) {
$this->operType = $operType;
$this->apiParas["oper_type"] = $operType;
}
public function getOperType() {
return $this->operType;
}
public function setReasonText($reasonText) {
$this->reasonText = $reasonText;
$this->apiParas["reason_text"] = $reasonText;
}
public function getReasonText() {
return $this->reasonText;
}
public function setReasonType($reasonType) {
$this->reasonType = $reasonType;
$this->apiParas["reason_type"] = $reasonType;
}
public function getReasonType() {
return $this->reasonType;
}
public function getApiMethodName() {
return "taobao.hotel.order.face.deal";
}
public function getApiParas() {
return $this->apiParas;
}
public function check() {
Taobao_RequestCheckUtil::checkNotNull($this->oid, "oid");
Taobao_RequestCheckUtil::checkNotNull($this->operType, "operType");
Taobao_RequestCheckUtil::checkMaxLength($this->operType, 1, "operType");
Taobao_RequestCheckUtil::checkMaxLength($this->reasonText, 500, "reasonText");
Taobao_RequestCheckUtil::checkMaxLength($this->reasonType, 1, "reasonType");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
|
Java
|
import { Observable } from './observable'
export default function drop(count, source) {
return Observable(add => {
let dropped = 0
return source.subscribe((val, name) => {
if (dropped++ >= count) add(val, name)
})
})
}
|
Java
|
package schoolprojects;
import java.util.Random;
import java.util.Scanner;
/**
* Piedra, papel o tijera es un juego infantil.
* Un juego de manos en el cual existen tres elementos.
* La piedra que vence a la tijera rompiéndola; la tijera que vencen al papel cortándolo;
* y el papel que vence a la piedra envolviéndola. Esto representa un ciclo, el cual
* le da su esencia al juego. Este juego es muy utilizado para decidir quien de dos
* personas hará algo, tal y como a veces se hace usando una moneda, o para dirimir algún asunto.
*
* En esta version del juego habra un Jugador Humano y un jugador artificial ( es decir el ordenador )
*
* @author Velik Georgiev Chelebiev
* @version 0.0.1
*/
public class Juego {
/**
* @param args Argumentos de la linea de comandos
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
/**
* Movimientos disponibles en forma de cadena.
*/
String[] movimientos = {"Piedra", "Papel", "Tijera"};
/**
* Moviemiento elegido por el usuario en forma de numero entero.
*/
int entradaUsuario = 0;
/**
* Un numero aleatorio que representara el movimiento del ordenador.
*/
int movimientoAleatorio = 0;
/**
* Los resultados posibles de la partida. 0 EMPATE 1 El jugador gana 2
* El jugador pierde
*/
String[] resultados = {"Empate", "Ganas", "Pierdes"};
/**
* El resultado de la partida respecto el jugador.
*/
int resultadoJugador = -1;
/**
* Aqui es donde epieza el juego.
*
* Pedimos al usuario que elija uno de los movimientos disponibles
* y generamos un movimiento aleatorio, que sera el movimiento del ordenador.
* Despues comptrobamos si el jugador gana al ordenador , si pierde o si hay un empate.
* Mostramos el resultado en la pantalla y el bucle se repite hasta que
* el jugador no introduce -1 como movimiento.
*/
do {
// Mostramos informacion sobre los movimientos validos y
// los numeros que le corresponden.
for (int i = 0; i < movimientos.length; i++) {
System.out.print("(" + (i + 1) + ") " + movimientos[i] + "\n");
}
// Valor predeterminado ( o entrada no valida, por si el usuario no introduce ningun valor )
entradaUsuario = 0;
// Leemos la entrada ( el moviemiento ) del usuario
try {
System.out.print("Movimiento: ");
entradaUsuario = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException ex) {
// Si la entrada no tiene un formato valido, mostraremos un mensaje de error
// y le pediremos al usuario que introduzca un movimiento nuevamente.
entradaUsuario = 0;
}
// Si la opcion elegida por el usuario no es valida imprimimos un
// mensaje de error y le volvemos a pedir que introduzca una opcion
if (entradaUsuario < 1 || entradaUsuario > 3) {
System.out.println("\n*** El movimiento elegido no es valido. ***");
continue;
}
// Restamos 1 a la entrada del usuario.
// Esto lo hacemos para que sea un indice de vector valido.
entradaUsuario -= 1;
// Generamos un movimiento aleatorio
movimientoAleatorio = rand.nextInt(movimientos.length);
// Para separar el "menu" de moviemientos y la entrada del usuario
// con la salida/resultado de la partida marco
System.out.println("\n*******************************\n");
// Imprimimos las jugadas del jugador y del ordenador
System.out.println("Tu: (" + movimientos[entradaUsuario] + ") [VS] PC: (" + movimientos[movimientoAleatorio] + ")");
// Comprobamos si el jugador gana
if ((entradaUsuario == 0 && movimientoAleatorio == 2) ||
(entradaUsuario == 1 && movimientoAleatorio == 0) ||
(entradaUsuario == 2 && movimientoAleatorio == 1)) {
resultadoJugador = 1;
} else if(entradaUsuario == movimientoAleatorio) { // Comprobamos si es un empate
resultadoJugador = 0;
} else { // en el resto de los casos el jugador pierde
resultadoJugador = 2;
}
// Imprimimos el resultado de la partida
System.out.println("Resultado: " + resultados[resultadoJugador]);
// Para separar el "menu" de moviemientos y la entrada del usuario
// con la salida/resultado de la partida marco
System.out.println("\n*******************************\n");
} while (entradaUsuario != -1);
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (version 1.7.0_01) on Thu Mar 07 20:40:25 CET 2013 -->
<title>Uses of Class com.tyrlib2.graphics.renderables.BoundingBox</title>
<meta name="date" content="2013-03-07">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.tyrlib2.graphics.renderables.BoundingBox";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/tyrlib2/graphics/renderables/BoundingBox.html" title="class in com.tyrlib2.graphics.renderables">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/tyrlib2/graphics/renderables/\class-useBoundingBox.html" target="_top">Frames</a></li>
<li><a href="BoundingBox.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.tyrlib2.graphics.renderables.BoundingBox" class="title">Uses of Class<br>com.tyrlib2.graphics.renderables.BoundingBox</h2>
</div>
<div class="classUseContainer">No usage of com.tyrlib2.graphics.renderables.BoundingBox</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/tyrlib2/graphics/renderables/BoundingBox.html" title="class in com.tyrlib2.graphics.renderables">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/tyrlib2/graphics/renderables/\class-useBoundingBox.html" target="_top">Frames</a></li>
<li><a href="BoundingBox.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
Java
|
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#.rst:
# FindZLIB
# --------
#
# Find the native ZLIB includes and library.
#
# IMPORTED Targets
# ^^^^^^^^^^^^^^^^
#
# This module defines :prop_tgt:`IMPORTED` target ``ZLIB::ZLIB``, if
# ZLIB has been found.
#
# Result Variables
# ^^^^^^^^^^^^^^^^
#
# This module defines the following variables:
#
# ::
#
# ZLIB_INCLUDE_DIRS - where to find zlib.h, etc.
# ZLIB_LIBRARIES - List of libraries when using zlib.
# ZLIB_FOUND - True if zlib found.
#
# ::
#
# ZLIB_VERSION_STRING - The version of zlib found (x.y.z)
# ZLIB_VERSION_MAJOR - The major version of zlib
# ZLIB_VERSION_MINOR - The minor version of zlib
# ZLIB_VERSION_PATCH - The patch version of zlib
# ZLIB_VERSION_TWEAK - The tweak version of zlib
#
# Backward Compatibility
# ^^^^^^^^^^^^^^^^^^^^^^
#
# The following variable are provided for backward compatibility
#
# ::
#
# ZLIB_MAJOR_VERSION - The major version of zlib
# ZLIB_MINOR_VERSION - The minor version of zlib
# ZLIB_PATCH_VERSION - The patch version of zlib
#
# Hints
# ^^^^^
#
# A user may set ``ZLIB_ROOT`` to a zlib installation root to tell this
# module where to look.
set(_ZLIB_SEARCHES)
# Search ZLIB_ROOT first if it is set.
if(ZLIB_ROOT)
set(_ZLIB_SEARCH_ROOT PATHS ${ZLIB_ROOT} NO_DEFAULT_PATH)
list(APPEND _ZLIB_SEARCHES _ZLIB_SEARCH_ROOT)
endif()
# Normal search.
set(_ZLIB_SEARCH_NORMAL
PATHS "[HKEY_LOCAL_MACHINE\\SOFTWARE\\GnuWin32\\Zlib;InstallPath]"
"$ENV{PROGRAMFILES}/zlib"
)
list(APPEND _ZLIB_SEARCHES _ZLIB_SEARCH_NORMAL)
set(ZLIB_NAMES z zlib zdll zlib1)
set(ZLIB_NAMES_DEBUG zlibd zlibd1)
# Try each search configuration.
foreach(search ${_ZLIB_SEARCHES})
find_path(ZLIB_INCLUDE_DIR NAMES zlib.h ${${search}} PATH_SUFFIXES include)
endforeach()
# Allow ZLIB_LIBRARY to be set manually, as the location of the zlib library
if(NOT ZLIB_LIBRARY)
foreach(search ${_ZLIB_SEARCHES})
find_library(ZLIB_LIBRARY_RELEASE NAMES ${ZLIB_NAMES} ${${search}} PATH_SUFFIXES lib)
find_library(ZLIB_LIBRARY_DEBUG NAMES ${ZLIB_NAMES_DEBUG} ${${search}} PATH_SUFFIXES lib)
endforeach()
include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
select_library_configurations(ZLIB)
endif()
unset(ZLIB_NAMES)
unset(ZLIB_NAMES_DEBUG)
mark_as_advanced(ZLIB_INCLUDE_DIR)
if(ZLIB_INCLUDE_DIR AND EXISTS "${ZLIB_INCLUDE_DIR}/zlib.h")
file(STRINGS "${ZLIB_INCLUDE_DIR}/zlib.h" ZLIB_H REGEX "^#define ZLIB_VERSION \"[^\"]*\"$")
string(REGEX REPLACE "^.*ZLIB_VERSION \"([0-9]+).*$" "\\1" ZLIB_VERSION_MAJOR "${ZLIB_H}")
string(REGEX REPLACE "^.*ZLIB_VERSION \"[0-9]+\\.([0-9]+).*$" "\\1" ZLIB_VERSION_MINOR "${ZLIB_H}")
string(REGEX REPLACE "^.*ZLIB_VERSION \"[0-9]+\\.[0-9]+\\.([0-9]+).*$" "\\1" ZLIB_VERSION_PATCH "${ZLIB_H}")
set(ZLIB_VERSION_STRING "${ZLIB_VERSION_MAJOR}.${ZLIB_VERSION_MINOR}.${ZLIB_VERSION_PATCH}")
# only append a TWEAK version if it exists:
set(ZLIB_VERSION_TWEAK "")
if( "${ZLIB_H}" MATCHES "ZLIB_VERSION \"[0-9]+\\.[0-9]+\\.[0-9]+\\.([0-9]+)")
set(ZLIB_VERSION_TWEAK "${CMAKE_MATCH_1}")
string(APPEND ZLIB_VERSION_STRING ".${ZLIB_VERSION_TWEAK}")
endif()
set(ZLIB_MAJOR_VERSION "${ZLIB_VERSION_MAJOR}")
set(ZLIB_MINOR_VERSION "${ZLIB_VERSION_MINOR}")
set(ZLIB_PATCH_VERSION "${ZLIB_VERSION_PATCH}")
endif()
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(ZLIB REQUIRED_VARS ZLIB_LIBRARY ZLIB_INCLUDE_DIR
VERSION_VAR ZLIB_VERSION_STRING)
if(ZLIB_FOUND)
set(ZLIB_INCLUDE_DIRS ${ZLIB_INCLUDE_DIR})
if(NOT ZLIB_LIBRARIES)
set(ZLIB_LIBRARIES ${ZLIB_LIBRARY})
endif()
if(NOT TARGET ZLIB::ZLIB)
add_library(ZLIB::ZLIB UNKNOWN IMPORTED)
set_target_properties(ZLIB::ZLIB PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${ZLIB_INCLUDE_DIRS}")
if(ZLIB_LIBRARY_RELEASE)
set_property(TARGET ZLIB::ZLIB APPEND PROPERTY
IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(ZLIB::ZLIB PROPERTIES
IMPORTED_LOCATION_RELEASE "${ZLIB_LIBRARY_RELEASE}")
endif()
if(ZLIB_LIBRARY_DEBUG)
set_property(TARGET ZLIB::ZLIB APPEND PROPERTY
IMPORTED_CONFIGURATIONS DEBUG)
set_target_properties(ZLIB::ZLIB PROPERTIES
IMPORTED_LOCATION_DEBUG "${ZLIB_LIBRARY_DEBUG}")
endif()
if(NOT ZLIB_LIBRARY_RELEASE AND NOT ZLIB_LIBRARY_DEBUG)
set_property(TARGET ZLIB::ZLIB APPEND PROPERTY
IMPORTED_LOCATION "${ZLIB_LIBRARY}")
endif()
endif()
endif()
|
Java
|
"""Support for monitoring emoncms feeds."""
from __future__ import annotations
from datetime import timedelta
from http import HTTPStatus
import logging
import requests
import voluptuous as vol
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorDeviceClass,
SensorEntity,
SensorStateClass,
)
from homeassistant.const import (
CONF_API_KEY,
CONF_ID,
CONF_SCAN_INTERVAL,
CONF_UNIT_OF_MEASUREMENT,
CONF_URL,
CONF_VALUE_TEMPLATE,
POWER_WATT,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import template
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
ATTR_FEEDID = "FeedId"
ATTR_FEEDNAME = "FeedName"
ATTR_LASTUPDATETIME = "LastUpdated"
ATTR_LASTUPDATETIMESTR = "LastUpdatedStr"
ATTR_SIZE = "Size"
ATTR_TAG = "Tag"
ATTR_USERID = "UserId"
CONF_EXCLUDE_FEEDID = "exclude_feed_id"
CONF_ONLY_INCLUDE_FEEDID = "include_only_feed_id"
CONF_SENSOR_NAMES = "sensor_names"
DECIMALS = 2
DEFAULT_UNIT = POWER_WATT
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5)
ONLY_INCL_EXCL_NONE = "only_include_exclude_or_none"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Required(CONF_ID): cv.positive_int,
vol.Exclusive(CONF_ONLY_INCLUDE_FEEDID, ONLY_INCL_EXCL_NONE): vol.All(
cv.ensure_list, [cv.positive_int]
),
vol.Exclusive(CONF_EXCLUDE_FEEDID, ONLY_INCL_EXCL_NONE): vol.All(
cv.ensure_list, [cv.positive_int]
),
vol.Optional(CONF_SENSOR_NAMES): vol.All(
{cv.positive_int: vol.All(cv.string, vol.Length(min=1))}
),
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_UNIT_OF_MEASUREMENT, default=DEFAULT_UNIT): cv.string,
}
)
def get_id(sensorid, feedtag, feedname, feedid, feeduserid):
"""Return unique identifier for feed / sensor."""
return f"emoncms{sensorid}_{feedtag}_{feedname}_{feedid}_{feeduserid}"
def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Emoncms sensor."""
apikey = config.get(CONF_API_KEY)
url = config.get(CONF_URL)
sensorid = config.get(CONF_ID)
value_template = config.get(CONF_VALUE_TEMPLATE)
config_unit = config.get(CONF_UNIT_OF_MEASUREMENT)
exclude_feeds = config.get(CONF_EXCLUDE_FEEDID)
include_only_feeds = config.get(CONF_ONLY_INCLUDE_FEEDID)
sensor_names = config.get(CONF_SENSOR_NAMES)
interval = config.get(CONF_SCAN_INTERVAL)
if value_template is not None:
value_template.hass = hass
data = EmonCmsData(hass, url, apikey, interval)
data.update()
if data.data is None:
return
sensors = []
for elem in data.data:
if exclude_feeds is not None and int(elem["id"]) in exclude_feeds:
continue
if include_only_feeds is not None and int(elem["id"]) not in include_only_feeds:
continue
name = None
if sensor_names is not None:
name = sensor_names.get(int(elem["id"]), None)
if unit := elem.get("unit"):
unit_of_measurement = unit
else:
unit_of_measurement = config_unit
sensors.append(
EmonCmsSensor(
hass,
data,
name,
value_template,
unit_of_measurement,
str(sensorid),
elem,
)
)
add_entities(sensors)
class EmonCmsSensor(SensorEntity):
"""Implementation of an Emoncms sensor."""
def __init__(
self, hass, data, name, value_template, unit_of_measurement, sensorid, elem
):
"""Initialize the sensor."""
if name is None:
# Suppress ID in sensor name if it's 1, since most people won't
# have more than one EmonCMS source and it's redundant to show the
# ID if there's only one.
id_for_name = "" if str(sensorid) == "1" else sensorid
# Use the feed name assigned in EmonCMS or fall back to the feed ID
feed_name = elem.get("name") or f"Feed {elem['id']}"
self._name = f"EmonCMS{id_for_name} {feed_name}"
else:
self._name = name
self._identifier = get_id(
sensorid, elem["tag"], elem["name"], elem["id"], elem["userid"]
)
self._hass = hass
self._data = data
self._value_template = value_template
self._unit_of_measurement = unit_of_measurement
self._sensorid = sensorid
self._elem = elem
if unit_of_measurement == "kWh":
self._attr_device_class = SensorDeviceClass.ENERGY
self._attr_state_class = SensorStateClass.TOTAL_INCREASING
elif unit_of_measurement == "W":
self._attr_device_class = SensorDeviceClass.POWER
self._attr_state_class = SensorStateClass.MEASUREMENT
if self._value_template is not None:
self._state = self._value_template.render_with_possible_json_value(
elem["value"], STATE_UNKNOWN
)
else:
self._state = round(float(elem["value"]), DECIMALS)
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def native_unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
@property
def native_value(self):
"""Return the state of the device."""
return self._state
@property
def extra_state_attributes(self):
"""Return the attributes of the sensor."""
return {
ATTR_FEEDID: self._elem["id"],
ATTR_TAG: self._elem["tag"],
ATTR_FEEDNAME: self._elem["name"],
ATTR_SIZE: self._elem["size"],
ATTR_USERID: self._elem["userid"],
ATTR_LASTUPDATETIME: self._elem["time"],
ATTR_LASTUPDATETIMESTR: template.timestamp_local(float(self._elem["time"])),
}
def update(self):
"""Get the latest data and updates the state."""
self._data.update()
if self._data.data is None:
return
elem = next(
(
elem
for elem in self._data.data
if get_id(
self._sensorid,
elem["tag"],
elem["name"],
elem["id"],
elem["userid"],
)
== self._identifier
),
None,
)
if elem is None:
return
self._elem = elem
if self._value_template is not None:
self._state = self._value_template.render_with_possible_json_value(
elem["value"], STATE_UNKNOWN
)
else:
self._state = round(float(elem["value"]), DECIMALS)
class EmonCmsData:
"""The class for handling the data retrieval."""
def __init__(self, hass, url, apikey, interval):
"""Initialize the data object."""
self._apikey = apikey
self._url = f"{url}/feed/list.json"
self._interval = interval
self._hass = hass
self.data = None
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data from Emoncms."""
try:
parameters = {"apikey": self._apikey}
req = requests.get(
self._url, params=parameters, allow_redirects=True, timeout=5
)
except requests.exceptions.RequestException as exception:
_LOGGER.error(exception)
return
else:
if req.status_code == HTTPStatus.OK:
self.data = req.json()
else:
_LOGGER.error(
"Please verify if the specified configuration value "
"'%s' is correct! (HTTP Status_code = %d)",
CONF_URL,
req.status_code,
)
|
Java
|
#include "MotionStreakTest.h"
#include "../testResource.h"
enum {
kTagLabel = 1,
kTagSprite1 = 2,
kTagSprite2 = 3,
};
Layer* nextMotionAction();
Layer* backMotionAction();
Layer* restartMotionAction();
static int sceneIdx = -1;
static std::function<Layer*()> createFunctions[] =
{
CL(MotionStreakTest1),
CL(MotionStreakTest2),
CL(Issue1358),
};
#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0]))
Layer* nextMotionAction()
{
sceneIdx++;
sceneIdx = sceneIdx % MAX_LAYER;
auto layer = (createFunctions[sceneIdx])();
layer->autorelease();
return layer;
}
Layer* backMotionAction()
{
sceneIdx--;
int total = MAX_LAYER;
if( sceneIdx < 0 )
sceneIdx += total;
auto layer = (createFunctions[sceneIdx])();
layer->autorelease();
return layer;
}
Layer* restartMotionAction()
{
auto layer = (createFunctions[sceneIdx])();
layer->autorelease();
return layer;
}
//------------------------------------------------------------------
//
// MotionStreakTest1
//
//------------------------------------------------------------------
void MotionStreakTest1::onEnter()
{
MotionStreakTest::onEnter();
auto s = Director::getInstance()->getWinSize();
// the root object just rotates around
_root = Sprite::create(s_pathR1);
addChild(_root, 1);
_root->setPosition(Point(s.width/2, s.height/2));
// the target object is offset from root, and the streak is moved to follow it
_target = Sprite::create(s_pathR1);
_root->addChild(_target);
_target->setPosition(Point(s.width/4, 0));
// create the streak object and add it to the scene
streak = MotionStreak::create(2, 3, 32, Color3B::GREEN, s_streak);
addChild(streak);
// schedule an update on each frame so we can syncronize the streak with the target
schedule(schedule_selector(MotionStreakTest1::onUpdate));
auto a1 = RotateBy::create(2, 360);
auto action1 = RepeatForever::create(a1);
auto motion = MoveBy::create(2, Point(100,0) );
_root->runAction( RepeatForever::create(Sequence::create(motion, motion->reverse(), NULL) ) );
_root->runAction( action1 );
auto colorAction = RepeatForever::create(Sequence::create(
TintTo::create(0.2f, 255, 0, 0),
TintTo::create(0.2f, 0, 255, 0),
TintTo::create(0.2f, 0, 0, 255),
TintTo::create(0.2f, 0, 255, 255),
TintTo::create(0.2f, 255, 255, 0),
TintTo::create(0.2f, 255, 0, 255),
TintTo::create(0.2f, 255, 255, 255),
NULL));
streak->runAction(colorAction);
}
void MotionStreakTest1::onUpdate(float delta)
{
streak->setPosition( _target->convertToWorldSpace(Point::ZERO) );
}
std::string MotionStreakTest1::title()
{
return "MotionStreak test 1";
}
//------------------------------------------------------------------
//
// MotionStreakTest2
//
//------------------------------------------------------------------
void MotionStreakTest2::onEnter()
{
MotionStreakTest::onEnter();
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesMoved = CC_CALLBACK_2(MotionStreakTest2::onTouchesMoved, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
auto s = Director::getInstance()->getWinSize();
// create the streak object and add it to the scene
streak = MotionStreak::create(3, 3, 64, Color3B::WHITE, s_streak );
addChild(streak);
streak->setPosition( Point(s.width/2, s.height/2) );
}
void MotionStreakTest2::onTouchesMoved(const std::vector<Touch*>& touches, Event* event)
{
auto touchLocation = touches[0]->getLocation();
streak->setPosition( touchLocation );
}
std::string MotionStreakTest2::title()
{
return "MotionStreak test";
}
//------------------------------------------------------------------
//
// Issue1358
//
//------------------------------------------------------------------
void Issue1358::onEnter()
{
MotionStreakTest::onEnter();
// ask director the the window size
auto size = Director::getInstance()->getWinSize();
streak = MotionStreak::create(2.0f, 1.0f, 50.0f, Color3B(255, 255, 0), "Images/Icon.png");
addChild(streak);
_center = Point(size.width/2, size.height/2);
_radius = size.width/3;
_angle = 0.0f;
schedule(schedule_selector(Issue1358::update), 0);
}
void Issue1358::update(float dt)
{
_angle += 1.0f;
streak->setPosition(Point(_center.x + cosf(_angle/180 * M_PI)*_radius,
_center.y + sinf(_angle/ 180 * M_PI)*_radius));
}
std::string Issue1358::title()
{
return "Issue 1358";
}
std::string Issue1358::subtitle()
{
return "The tail should use the texture";
}
//------------------------------------------------------------------
//
// MotionStreakTest
//
//------------------------------------------------------------------
MotionStreakTest::MotionStreakTest(void)
{
}
MotionStreakTest::~MotionStreakTest(void)
{
}
std::string MotionStreakTest::title()
{
return "No title";
}
std::string MotionStreakTest::subtitle()
{
return "";
}
void MotionStreakTest::onEnter()
{
BaseTest::onEnter();
auto s = Director::getInstance()->getWinSize();
auto itemMode = MenuItemToggle::createWithCallback( CC_CALLBACK_1(MotionStreakTest::modeCallback, this),
MenuItemFont::create("Use High Quality Mode"),
MenuItemFont::create("Use Fast Mode"),
NULL);
auto menuMode = Menu::create(itemMode, NULL);
addChild(menuMode);
menuMode->setPosition(Point(s.width/2, s.height/4));
}
void MotionStreakTest::modeCallback(Object *pSender)
{
bool fastMode = streak->isFastMode();
streak->setFastMode(! fastMode);
}
void MotionStreakTest::restartCallback(Object* sender)
{
auto s = new MotionStreakTestScene();//CCScene::create();
s->addChild(restartMotionAction());
Director::getInstance()->replaceScene(s);
s->release();
}
void MotionStreakTest::nextCallback(Object* sender)
{
auto s = new MotionStreakTestScene();//CCScene::create();
s->addChild( nextMotionAction() );
Director::getInstance()->replaceScene(s);
s->release();
}
void MotionStreakTest::backCallback(Object* sender)
{
auto s = new MotionStreakTestScene;//CCScene::create();
s->addChild( backMotionAction() );
Director::getInstance()->replaceScene(s);
s->release();
}
void MotionStreakTestScene::runThisTest()
{
auto layer = nextMotionAction();
addChild(layer);
Director::getInstance()->replaceScene(this);
}
|
Java
|
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace DoctrineMongoODMModuleTest\Service;
use DoctrineMongoODMModule\Service\ConfigurationFactory;
use DoctrineMongoODMModuleTest\AbstractTest;
class ConfigurationFactoryTest extends AbstractTest
{
public function testRetryConnectValueIsSetFromConfigurationOptions()
{
$config = $this->getDocumentManager()->getConfiguration();
$this->assertSame(123, $config->getRetryConnect());
}
public function testRetryQueryValueIsSetFromConfigurationOptions()
{
$config = $this->getDocumentManager()->getConfiguration();
$this->assertSame(456, $config->getRetryQuery());
}
public function testCreation()
{
$logger = $this->getMockForAbstractClass('DoctrineMongoODMModule\Logging\Logger');
$metadataCache = $this->getMockForAbstractClass('Doctrine\Common\Cache\Cache');
$mappingDriver = $this->getMockForAbstractClass('Doctrine\Common\Persistence\Mapping\Driver\MappingDriver');
$serviceLocator = $this->getMockForAbstractClass('Zend\ServiceManager\ServiceLocatorInterface');
$serviceLocator->expects($this->exactly(4))->method('get')->withConsecutive(
array('Configuration'),
array('stubbed_logger'),
array('doctrine.cache.stubbed_metadatacache'),
array('doctrine.driver.stubbed_driver')
)->willReturnOnConsecutiveCalls(
array(
'doctrine' => array(
'configuration' => array(
'odm_test' => array(
'logger' => 'stubbed_logger',
'metadata_cache' => 'stubbed_metadatacache',
'driver' => 'stubbed_driver',
'generate_proxies' => true,
'proxy_dir' => 'data/DoctrineMongoODMModule/Proxy',
'proxy_namespace' => 'DoctrineMongoODMModule\Proxy',
'generate_hydrators' => true,
'hydrator_dir' => 'data/DoctrineMongoODMModule/Hydrator',
'hydrator_namespace' => 'DoctrineMongoODMModule\Hydrator',
'default_db' => 'default_db',
'filters' => array(), // array('filterName' => 'BSON\Filter\Class')
// custom types
'types' => array(
'CustomType' => 'DoctrineMongoODMModuleTest\Assets\CustomType'
),
'classMetadataFactoryName' => 'stdClass'
)
)
)
),
$logger,
$metadataCache,
$mappingDriver
);
$factory = new ConfigurationFactory('odm_test');
$config = $factory->createService($serviceLocator);
$this->assertInstanceOf('Doctrine\ODM\MongoDB\Configuration', $config);
$this->assertNotNull($config->getLoggerCallable());
$this->assertSame($metadataCache, $config->getMetadataCacheImpl());
$this->assertSame($mappingDriver, $config->getMetadataDriverImpl());
$this->assertInstanceOf(
'DoctrineMongoODMModuleTest\Assets\CustomType',
\Doctrine\ODM\MongoDB\Types\Type::getType('CustomType')
);
}
}
|
Java
|
.date-menu {
background-color: #fcfcfc;
height: 59px;
border-bottom: 1px solid #eee;
}
.date-menu-contents {
@mixin content-padding;
display: flex;
justify-content: space-between;
align-items: center;
height: 59px;
}
.date-menu-current-date {
height: 20px;
line-height: 20px;
}
.date-menu-next,
.date-menu-prev {
color: #8f8f8f;
text-decoration: none;
}
.date-menu-icon-calendar {
margin-right: 5px;
display: inline-block;
}
.date-menu-next-disabled {
pointer-events: none;
color: #ccc;
}
|
Java
|
import React, { Component } from 'react'
import {
FlexGrid, Content, Container,
AdminItemsViewTable,
Table, Button
} from 'components'
import {
AddItemAboutContainer,
AddItemPhotoContainer,
SpecialSetupContainer
} from 'containers'
import { adminLink } from 'config'
import s from './AdminItemsView.sass'
class ToggleButton extends Component {
state = {value: this.props.value};
componentWillMount() {
this.setState({value: this.props.value})
}
componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.props.value) {
this.setState({value: nextProps.value});
}
}
onClick = () => {
if (!this.props.onChange)
return;
const { field, id, value } = this.props;
const newValue = !value;
this.props.onChange({
[field]: newValue,
id
});
this.setState({value: newValue})
};
render() {
const { children } = this.props;
const { onClick } = this;
const { value } = this.state;
return (
<FlexGrid className={s.toggle} direction="column"
justify="center" align="center">
<Content size="5" center gray>{children}</Content>
<Table.RowItem className={s.toggle__icon} tag="span"
onClick={onClick}
circle circleActive={value}/>
</FlexGrid>
)
}
}
export default class AdminItemsView extends Component {
render() {
const {
data, parent_id, brands, categories,
onChange, onDelete, onAboutChange,
aboutData, onSave, onColorChange, onSpecialChange
} = this.props;
if (!data || data.id == null)
return null;
const { id } = data;
return (
<div className={s.wrapper}>
<AdminItemsViewTable data={data} brands={brands}
onChange={onChange}
categories={categories} />
<div className={s.line} />
<Container className={s.content}>
<FlexGrid justify="start" align="start">
<div className={s.grid}>
<FlexGrid className={s.toggle__wrapper}
justify="start" align="start">
<ToggleButton id={id} onChange={onChange} field="is_top"
value={data.is_top}>Топ</ToggleButton>
<ToggleButton id={id} onChange={onChange} field="is_new"
value={data.is_new}>Новинка</ToggleButton>
<ToggleButton id={id} onChange={onChange} field="is_special_active"
value={data.is_special_active}>Акция</ToggleButton>
<ToggleButton id={id} onChange={onChange} field="warranty"
value={data.warranty}>Гарантия</ToggleButton>
</FlexGrid>
<Content className={s.title} regular size="5">
Изображения
</Content>
<AddItemPhotoContainer __onChange={onColorChange} color={data.color} custom/>
<SpecialSetupContainer onChange={onSpecialChange} />
</div>
<div className={s.grid}>
<AddItemAboutContainer data={aboutData} custom
onSave={onSave}
__onChange={onAboutChange}/>
</div>
</FlexGrid>
<div className={s.actions}>
<Button type="blue" to={`${adminLink.path}/items/${parent_id}`}>
Отредактировать модель
</Button>
<Button className={s.btn} type="pink"
onClick={onDelete}>
Удалить
</Button>
</div>
</Container>
</div>
)
}
}
|
Java
|
version https://git-lfs.github.com/spec/v1
oid sha256:19eb3ffef04271f29432990f05ab086d7741a17b915b1703347b21f79b44cef2
size 2655
|
Java
|
package main
import (
"reflect"
"strconv"
"unsafe"
"github.com/STNS/STNS/stns"
"github.com/STNS/libnss_stns/libstns"
)
/*
#include <grp.h>
#include <sys/types.h>
*/
import "C"
type Group struct {
grp *C.struct_group
result **C.struct_group
}
func (s Group) Set(groups stns.Attributes) int {
for n, g := range groups {
if g.ID != 0 {
s.grp.gr_gid = C.__gid_t(g.ID)
s.grp.gr_name = C.CString(n)
s.grp.gr_passwd = C.CString("x")
if g.Group != nil && !reflect.ValueOf(g.Group).IsNil() {
work := make([]*C.char, len(g.Users)+1)
if len(g.Users) > 0 {
for i, u := range g.Users {
work[i] = C.CString(u)
}
}
s.grp.gr_mem = (**C.char)(unsafe.Pointer(&work[0]))
} else {
work := make([]*C.char, 1)
s.grp.gr_mem = (**C.char)(unsafe.Pointer(&work[0]))
}
s.result = &s.grp
return libstns.NSS_STATUS_SUCCESS
}
}
return libstns.NSS_STATUS_NOTFOUND
}
//export _nss_stns_getgrnam_r
func _nss_stns_getgrnam_r(name *C.char, grp *C.struct_group, buffer *C.char, bufsize C.size_t, result **C.struct_group) C.int {
g := Group{grp, result}
return set(grpNss, g, "name", C.GoString(name))
}
//export _nss_stns_getgrgid_r
func _nss_stns_getgrgid_r(gid C.__gid_t, grp *C.struct_group, buffer *C.char, bufsize C.size_t, result **C.struct_group) C.int {
g := Group{grp, result}
return set(grpNss, g, "id", strconv.Itoa(int(gid)))
}
//export _nss_stns_setgrent
func _nss_stns_setgrent() C.int {
return initList(grpNss, libstns.NSS_LIST_PRESET)
}
//export _nss_stns_endgrent
func _nss_stns_endgrent() {
initList(grpNss, libstns.NSS_LIST_PURGE)
}
//export _nss_stns_getgrent_r
func _nss_stns_getgrent_r(grp *C.struct_group, buffer *C.char, bufsize C.size_t, result **C.struct_group) C.int {
g := Group{grp, result}
return setByList(grpNss, g)
}
|
Java
|
const LogTestPlugin = require("../../helpers/LogTestPlugin");
/** @type {import("../../../").Configuration} */
module.exports = {
mode: "production",
entry: "./index",
stats: "normal",
plugins: [new LogTestPlugin()]
};
|
Java
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
namespace NetOffice.DeveloperToolbox.Utils.Registry
{
public class UtilsRegistryEntry
{
#region Fields
private UtilsRegistryKey _parent;
private string _valueName;
private UtilsRegistryEntryType _type;
#endregion
#region Construction
internal UtilsRegistryEntry(UtilsRegistryKey parent, string valueName)
{
_parent = parent;
_valueName = valueName;
_type = UtilsRegistryEntryType.Normal;
}
internal UtilsRegistryEntry(UtilsRegistryKey parent, string valueName, UtilsRegistryEntryType type)
{
_parent = parent;
_valueName = valueName;
_type = type;
}
#endregion
#region Properties
public UtilsRegistryEntryType Type
{
get
{
return _type;
}
}
public string Name
{
get
{
if(string.IsNullOrEmpty(_valueName))
return "(Standard)";
else
return _valueName;
}
set
{
RegistryKey key = _parent.Open(true);
RegistryValueKind regKind = key.GetValueKind(_valueName);
object regValue = key.GetValue(_valueName);
key.DeleteValue(_valueName);
key.SetValue(value, regValue, regKind);
key.Close();
_valueName = value;
}
}
public object Value
{
get
{
if (_type == UtilsRegistryEntryType.Faked)
return null;
RegistryKey key = _parent.Open();
object regValue = key.GetValue(_valueName);
key.Close();
return regValue;
}
set
{
if (_type == UtilsRegistryEntryType.Faked)
{
RegistryKey key = _parent.Open(true);
key.SetValue(_valueName, value, ValueKind);
key.Close();
_type = UtilsRegistryEntryType.Default;
}
else
{
RegistryKey key = _parent.Open(true);
key.SetValue(_valueName, value, ValueKind);
key.Close();
}
}
}
public RegistryValueKind ValueKind
{
get
{
if (_type == UtilsRegistryEntryType.Faked)
return RegistryValueKind.String;
RegistryKey key = _parent.Open();
RegistryValueKind kind = key.GetValueKind(_valueName);
key.Close();
return kind;
}
}
#endregion
#region Methods
public static string ByteArrayToBinaryString(byte[] byteArray)
{
StringBuilder builder = new StringBuilder(byteArray.Length * 2);
foreach (byte value in byteArray)
{
builder.AppendFormat("{0:X2}", value);
builder.Append(" ");
}
return builder.ToString();
}
public static string ShiftHexValue(string value)
{
int lenght = value.Length;
if ((10 - lenght) >= 2)
value = "0x" + value;
lenght = value.Length;
if ((10 - lenght) > 0)
{
for (int i = 0; i < (10 - lenght); i++)
{
string first = value.Substring(0, 2);
string last = value.Substring(2);
value = first + "0" + last;
}
}
return value;
}
public string GetValue(int lcid = 1033)
{
RegistryValueKind kind = ValueKind;
switch (kind)
{
case RegistryValueKind.DWord:
case RegistryValueKind.QWord:
return ShiftHexValue(String.Format("{0:x4}", Value)) + " (" + Convert.ToString(Value) + ")";
case RegistryValueKind.Binary:
return ByteArrayToBinaryString((Value as byte[])).ToLower();
case RegistryValueKind.ExpandString:
case RegistryValueKind.MultiString:
case RegistryValueKind.String:
case RegistryValueKind.Unknown:
if (_type == UtilsRegistryEntryType.Faked)
return lcid == 1033 ? "(Value not set)" : "(Wert nicht gesetzt)";
else if ((_type == UtilsRegistryEntryType.Default) && (null == Value))
return lcid == 1033 ? "(Value not set)" : "(Wert nicht gesetzt)";
return Value as string;
default:
throw new ArgumentException(kind.ToString() + " is out of range");
}
}
public void Delete()
{
RegistryKey key = _parent.Open(true);
key.DeleteValue(_valueName);
key.Close();
}
#endregion
#region Static Methods
private static byte[] StringToByteArray(string str)
{
if (null == str)
return null;
System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
return enc.GetBytes(str);
}
private static string ByteArrayToString(byte[] arr)
{
if (null == arr)
return null;
System.Text.UnicodeEncoding enc = new System.Text.UnicodeEncoding();
return enc.GetString(arr);
}
#endregion
#region Overrides
public override string ToString()
{
return String.Format("UtilsRegistryEntry {0}", Name);
}
#endregion
}
}
|
Java
|
import { expect } from 'chai'
import browser from '../../src/util/browser'
describe('util (node)', () => {
describe('browser', () => {
it('is false', () => {
expect(browser).to.be.false
})
})
})
|
Java
|
// Seriously awesome GLSL noise functions. (C) Credits and kudos go to
// Copyright (C) Stefan Gustavson, Ian McEwan Ashima Arts
// MIT License.
define(function(require, exports){
exports.permute1 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.permute3 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.permute4 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.isqrtT1 = function(r){
return 1.79284291400159 - 0.85373472095314 * r
}
exports.isqrtT4 = function(r){
return vec4(1.79284291400159 - 0.85373472095314 * r)
}
exports.snoise2 = function(x, y){
return snoise2v(vec2(x,y,z))
}
exports.noise2d =
exports.s2d =
exports.snoise2v = function(v){
var C = vec4(0.211324865405187,0.366025403784439,-0.577350269189626,0.024390243902439)
var i = floor(v + dot(v, C.yy) )
var x0 = v - i + dot(i, C.xx)
var i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0)
var x12 = x0.xyxy + C.xxzz
x12.xy -= i1
i = mod(i, 289.0) // Avoid truncation effects in permutation
var p = permute3(permute3(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0 ))
var m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0)
m = m*m
m = m*m
var x = 2.0 * fract(p * C.www) - 1.0
var h = abs(x) - 0.5
var ox = floor(x + 0.5)
var a0 = x - ox
m *= (1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ))
var g = vec3()
g.x = a0.x * x0.x + h.x * x0.y
g.yz = a0.yz * x12.xz + h.yz * x12.yw
return 130.0 * dot(m, g)
}
exports.snoise3 = function(x, y, z){
return snoise3v(vec3(x,y,z))
}
exports.noise3d =
exports.snoise3v = function(v){
var C = vec2(1.0/6.0, 1.0/3.0)
var D = vec4(0.0, 0.5, 1.0, 2.0)
// First corner
var i = floor(v + dot(v, C.yyy))
var x0 = v - i + dot(i, C.xxx)
var g = step(x0.yzx, x0.xyz)
var l = 1.0 - g
var i1 = min(g.xyz, l.zxy)
var i2 = max(g.xyz, l.zxy)
var x1 = x0 - i1 + 1.0 * C.xxx
var x2 = x0 - i2 + 2.0 * C.xxx
var x3 = x0 - 1. + 3.0 * C.xxx
// Permutations
i = mod(i, 289.0)
var p = permute4(permute4(permute4(
i.z + vec4(0.0, i1.z, i2.z, 1.0))
+ i.y + vec4(0.0, i1.y, i2.y, 1.0))
+ i.x + vec4(0.0, i1.x, i2.x, 1.0))
// ( N*N points uniformly over a square, mapped onto an octahedron.)
var n_ = 1.0/7.0
var ns = n_ * D.wyz - D.xzx
var j = p - 49.0 * floor(p * ns.z *ns.z)
var x_ = floor(j * ns.z)
var y_ = floor(j - 7.0 * x_)
var x = x_ * ns.x + ns.yyyy
var y = y_ * ns.x + ns.yyyy
var h = 1.0 - abs(x) - abs(y)
var b0 = vec4( x.xy, y.xy )
var b1 = vec4( x.zw, y.zw )
var s0 = floor(b0)*2.0 + 1.0
var s1 = floor(b1)*2.0 + 1.0
var sh = -step(h, vec4(0.0))
var a0 = b0.xzyw + s0.xzyw*sh.xxyy
var a1 = b1.xzyw + s1.xzyw*sh.zzww
var p0 = vec3(a0.xy, h.x)
var p1 = vec3(a0.zw, h.y)
var p2 = vec3(a1.xy, h.z)
var p3 = vec3(a1.zw, h.w)
//Normalise gradients
var norm = isqrtT4(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)))
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
// Mix final noise value
var m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0)
m = m * m
return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),
dot(p2,x2), dot(p3,x3) ) )
}
exports.snoise4_g = function(j, ip){
var p = vec4()
p.xyz = floor( fract (vec3(j) * ip.xyz) * 7.0) * ip.z - 1.0
p.w = 1.5 - dot(abs(p.xyz), vec3(1.0,1.0,1.0))
var s = vec4(lessThan(p, vec4(0.0)))
p.xyz = p.xyz + (s.xyz*2.0 - 1.0) * s.www
return p
}
exports.snoise4 = function(x, y, z, w){
return snoise4v(vec4(x,y,z,w))
}
exports.snoise4v = function(v){
var C = vec4(0.138196601125011,0.276393202250021,0.414589803375032,-0.447213595499958)
// First corner
var i = floor(v + dot(v, vec4(0.309016994374947451)) )
var x0 = v - i + dot(i, C.xxxx)
var i0 = vec4()
var isX = step( x0.yzw, x0.xxx )
var isYZ = step( x0.zww, x0.yyz )
i0.x = isX.x + isX.y + isX.z
i0.yzw = 1.0 - isX
i0.y += isYZ.x + isYZ.y
i0.zw += 1.0 - isYZ.xy
i0.z += isYZ.z
i0.w += 1.0 - isYZ.z
var i3 = clamp( i0, 0.0, 1.0 )
var i2 = clamp( i0-1.0, 0.0, 1.0 )
var i1 = clamp( i0-2.0, 0.0, 1.0 )
var x1 = x0 - i1 + C.xxxx
var x2 = x0 - i2 + C.yyyy
var x3 = x0 - i3 + C.zzzz
var x4 = x0 + C.wwww
// Permutations
i = mod(i, 289.0 )
var j0 = permute1( permute1( permute1( permute1(i.w) + i.z) + i.y) + i.x)
var j1 = permute4( permute4( permute4( permute4(
i.w + vec4(i1.w, i2.w, i3.w, 1.0 ))
+ i.z + vec4(i1.z, i2.z, i3.z, 1.0 ))
+ i.y + vec4(i1.y, i2.y, i3.y, 1.0 ))
+ i.x + vec4(i1.x, i2.x, i3.x, 1.0 ))
// Gradients: 7x7x6 points over a cube, mapped onto a 4-cross polytope
// 7*7*6 = 294, which is close to the ring size 17*17 = 289.
var ip = vec4(1.0/294.0, 1.0/49.0, 1.0/7.0, 0.0)
var p0 = snoise4_g(j0, ip)
var p1 = snoise4_g(j1.x, ip)
var p2 = snoise4_g(j1.y, ip)
var p3 = snoise4_g(j1.z, ip)
var p4 = snoise4_g(j1.w, ip)
// Normalise gradients
var nr = isqrtT4(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)))
p0 *= nr.x
p1 *= nr.y
p2 *= nr.z
p3 *= nr.w
p4 *= isqrtT1(dot(p4,p4))
// Mix contributions from the five corners
var m0 = max(0.6 - vec3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0)
var m1 = max(0.6 - vec2(dot(x3,x3), dot(x4,x4)), 0.0)
m0 = m0 * m0
m1 = m1 * m1
return 49.0 * (dot(m0*m0, vec3(dot( p0, x0 ), dot(p1, x1), dot(p2, x2)))
+ dot(m1*m1, vec2( dot(p3, x3), dot(p4, x4))))
}
exports.cell2v = function(v){
return cell3v(vec3(v.x, v.y,0))
}
exports.cell3v = function(P){
var K = 0.142857142857 // 1/7
var Ko = 0.428571428571 // 1/2-K/2
var K2 = 0.020408163265306 // 1/(7*7)
var Kz = 0.166666666667 // 1/6
var Kzo = 0.416666666667 // 1/2-1/6*2
var ji = 0.8 // smaller jitter gives less errors in F2
var Pi = mod(floor(P), 289.0)
var Pf = fract(P)
var Pfx = Pf.x + vec4(0.0, -1.0, 0.0, -1.0)
var Pfy = Pf.y + vec4(0.0, 0.0, -1.0, -1.0)
var p = permute4(Pi.x + vec4(0.0, 1.0, 0.0, 1.0))
p = permute4(p + Pi.y + vec4(0.0, 0.0, 1.0, 1.0))
var p1 = permute4(p + Pi.z) // z+0
var p2 = permute4(p + Pi.z + vec4(1.0)) // z+1
var ox1 = fract(p1*K) - Ko
var oy1 = mod(floor(p1*K), 7.0)*K - Ko
var oz1 = floor(p1*K2)*Kz - Kzo // p1 < 289 guaranteed
var ox2 = fract(p2*K) - Ko
var oy2 = mod(floor(p2*K), 7.0)*K - Ko
var oz2 = floor(p2*K2)*Kz - Kzo
var dx1 = Pfx + ji*ox1
var dy1 = Pfy + ji*oy1
var dz1 = Pf.z + ji*oz1
var dx2 = Pfx + ji*ox2
var dy2 = Pfy + ji*oy2
var dz2 = Pf.z - 1.0 + ji*oz2
var d1 = dx1 * dx1 + dy1 * dy1 + dz1 * dz1 // z+0
var d2 = dx2 * dx2 + dy2 * dy2 + dz2 * dz2 // z+1
var d = min(d1,d2) // F1 is now in d
d2 = max(d1,d2) // Make sure we keep all candidates for F2
d.xy = (d.x < d.y) ? d.xy : d.yx // Swap smallest to d.x
d.xz = (d.x < d.z) ? d.xz : d.zx
d.xw = (d.x < d.w) ? d.xw : d.wx // F1 is now in d.x
d.yzw = min(d.yzw, d2.yzw) // F2 now not in d2.yzw
d.y = min(d.y, d.z) // nor in d.z
d.y = min(d.y, d.w) // nor in d.w
d.y = min(d.y, d2.x) // F2 is now in d.y
return sqrt(d.xy) // F1 and F2
},
exports.cell3w = function(P){
var K = 0.142857142857
var Ko = 0.428571428571 // 1/2-K/2
var K2 = 0.020408163265306// 1/(7*7)
var Kz = 0.166666666667// 1/6
var Kzo = 0.416666666667// 1/2-1/6*2
var ji = 1.0// smaller jitter gives more regular pattern
var Pi = mod(floor(P), 289.0)
var Pf = fract(P) - 0.5
var Pfx = Pf.x + vec3(1.0, 0.0, -1.0)
var Pfy = Pf.y + vec3(1.0, 0.0, -1.0)
var Pfz = Pf.z + vec3(1.0, 0.0, -1.0)
var p = permute3(Pi.x + vec3(-1.0, 0.0, 1.0))
var p1 = permute3(p + Pi.y - 1.0)
var p2 = permute3(p + Pi.y)
var p3 = permute3(p + Pi.y + 1.0)
var p11 = permute3(p1 + Pi.z - 1.0)
var p12 = permute3(p1 + Pi.z)
var p13 = permute3(p1 + Pi.z + 1.0)
var p21 = permute3(p2 + Pi.z - 1.0)
var p22 = permute3(p2 + Pi.z)
var p23 = permute3(p2 + Pi.z + 1.0)
var p31 = permute3(p3 + Pi.z - 1.0)
var p32 = permute3(p3 + Pi.z)
var p33 = permute3(p3 + Pi.z + 1.0)
var ox11 = fract(p11*K) - Ko
var oy11 = mod(floor(p11*K), 7.0)*K - Ko
var oz11 = floor(p11*K2)*Kz - Kzo // p11 < 289 guaranteed
var ox12 = fract(p12*K) - Ko
var oy12 = mod(floor(p12*K), 7.0)*K - Ko
var oz12 = floor(p12*K2)*Kz - Kzo
var ox13 = fract(p13*K) - Ko
var oy13 = mod(floor(p13*K), 7.0)*K - Ko
var oz13 = floor(p13*K2)*Kz - Kzo
var ox21 = fract(p21*K) - Ko
var oy21 = mod(floor(p21*K), 7.0)*K - Ko
var oz21 = floor(p21*K2)*Kz - Kzo
var ox22 = fract(p22*K) - Ko
var oy22 = mod(floor(p22*K), 7.0)*K - Ko
var oz22 = floor(p22*K2)*Kz - Kzo
var ox23 = fract(p23*K) - Ko
var oy23 = mod(floor(p23*K), 7.0)*K - Ko
var oz23 = floor(p23*K2)*Kz - Kzo
var ox31 = fract(p31*K) - Ko
var oy31 = mod(floor(p31*K), 7.0)*K - Ko
var oz31 = floor(p31*K2)*Kz - Kzo
var ox32 = fract(p32*K) - Ko
var oy32 = mod(floor(p32*K), 7.0)*K - Ko
var oz32 = floor(p32*K2)*Kz - Kzo
var ox33 = fract(p33*K) - Ko
var oy33 = mod(floor(p33*K), 7.0)*K - Ko
var oz33 = floor(p33*K2)*Kz - Kzo
var dx11 = Pfx + ji*ox11
var dy11 = Pfy.x + ji*oy11
var dz11 = Pfz.x + ji*oz11
var dx12 = Pfx + ji*ox12
var dy12 = Pfy.x + ji*oy12
var dz12 = Pfz.y + ji*oz12
var dx13 = Pfx + ji*ox13
var dy13 = Pfy.x + ji*oy13
var dz13 = Pfz.z + ji*oz13
var dx21 = Pfx + ji*ox21
var dy21 = Pfy.y + ji*oy21
var dz21 = Pfz.x + ji*oz21
var dx22 = Pfx + ji*ox22
var dy22 = Pfy.y + ji*oy22
var dz22 = Pfz.y + ji*oz22
var dx23 = Pfx + ji*ox23
var dy23 = Pfy.y + ji*oy23
var dz23 = Pfz.z + ji*oz23
var dx31 = Pfx + ji*ox31
var dy31 = Pfy.z + ji*oy31
var dz31 = Pfz.x + ji*oz31
var dx32 = Pfx + ji*ox32
var dy32 = Pfy.z + ji*oy32
var dz32 = Pfz.y + ji*oz32
var dx33 = Pfx + ji*ox33
var dy33 = Pfy.z + ji*oy33
var dz33 = Pfz.z + ji*oz33
var d11 = dx11 * dx11 + dy11 * dy11 + dz11 * dz11
var d12 = dx12 * dx12 + dy12 * dy12 + dz12 * dz12
var d13 = dx13 * dx13 + dy13 * dy13 + dz13 * dz13
var d21 = dx21 * dx21 + dy21 * dy21 + dz21 * dz21
var d22 = dx22 * dx22 + dy22 * dy22 + dz22 * dz22
var d23 = dx23 * dx23 + dy23 * dy23 + dz23 * dz23
var d31 = dx31 * dx31 + dy31 * dy31 + dz31 * dz31
var d32 = dx32 * dx32 + dy32 * dy32 + dz32 * dz32
var d33 = dx33 * dx33 + dy33 * dy33 + dz33 * dz33
var d1a = min(d11, d12)
d12 = max(d11, d12)
d11 = min(d1a, d13) // Smallest now not in d12 or d13
d13 = max(d1a, d13)
d12 = min(d12, d13) // 2nd smallest now not in d13
var d2a = min(d21, d22)
d22 = max(d21, d22)
d21 = min(d2a, d23) // Smallest now not in d22 or d23
d23 = max(d2a, d23)
d22 = min(d22, d23) // 2nd smallest now not in d23
var d3a = min(d31, d32)
d32 = max(d31, d32)
d31 = min(d3a, d33) // Smallest now not in d32 or d33
d33 = max(d3a, d33)
d32 = min(d32, d33) // 2nd smallest now not in d33
var da = min(d11, d21)
d21 = max(d11, d21)
d11 = min(da, d31) // Smallest now in d11
d31 = max(da, d31) // 2nd smallest now not in d31
d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx
d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx // d11.x now smallest
d12 = min(d12, d21) // 2nd smallest now not in d21
d12 = min(d12, d22) // nor in d22
d12 = min(d12, d31) // nor in d31
d12 = min(d12, d32) // nor in d32
d11.yz = min(d11.yz, d12.xy) // nor in d12.yz
d11.y = min(d11.y, d12.z) // Only two more to go
d11.y = min(d11.y, d11.z) // Done! (Phew!)
return sqrt(d11.xy) // F1, F2
}
})
|
Java
|
#pragma once
namespace Game
{
namespace Light
{
constexpr unsigned int MAX_POINT_LIGHT_NUM = 384U;
constexpr unsigned int MAX_LINE_LIGHT_NUM = 64U;
constexpr unsigned int MAX_SPOT_LIGHT_NUM = 16U;
}
}
|
Java
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Version;
class ORMQueryBuilderLoaderTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
* @group legacy
*/
public function testItOnlyWorksWithQueryBuilderOrClosure()
{
new ORMQueryBuilderLoader(new \stdClass());
}
/**
* @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
* @group legacy
*/
public function testClosureRequiresTheEntityManager()
{
$closure = function () {};
new ORMQueryBuilderLoader($closure);
}
public function testIdentifierTypeIsStringArray()
{
$this->checkIdentifierType('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity', Connection::PARAM_STR_ARRAY);
}
public function testIdentifierTypeIsIntegerArray()
{
$this->checkIdentifierType('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', Connection::PARAM_INT_ARRAY);
}
protected function checkIdentifierType($classname, $expectedType)
{
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array(1, 2), $expectedType)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->getMock();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$qb->select('e')
->from($classname, 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id', array(1, 2));
}
public function testFilterNonIntegerValues()
{
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array(1, 2, 3), Connection::PARAM_INT_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->getMock();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$qb->select('e')
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id', array(1, '', 2, 3, 'foo'));
}
public function testEmbeddedIdentifierName()
{
if (Version::compare('2.5.0') > 0) {
$this->markTestSkipped('Applicable only for Doctrine >= 2.5.0');
return;
}
$em = DoctrineTestHelper::createTestEntityManager();
$query = $this->getMockBuilder('QueryMock')
->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
->getMock();
$query->expects($this->once())
->method('setParameter')
->with('ORMQueryBuilderLoader_getEntitiesByIds_id_value', array(1, 2, 3), Connection::PARAM_INT_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
->setConstructorArgs(array($em))
->setMethods(array('getQuery'))
->getMock();
$qb->expects($this->once())
->method('getQuery')
->willReturn($query);
$qb->select('e')
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\EmbeddedIdentifierEntity', 'e');
$loader = new ORMQueryBuilderLoader($qb);
$loader->getEntitiesByIds('id.value', array(1, '', 2, 3, 'foo'));
}
}
|
Java
|
var $ = require('jquery');
var keymaster = require('keymaster');
var ChartEditor = require('./component-chart-editor.js');
var DbInfo = require('./component-db-info.js');
var AceSqlEditor = require('./component-ace-sql-editor.js');
var DataGrid = require('./component-data-grid.js');
var QueryEditor = function () {
var chartEditor = new ChartEditor();
var dbInfo = new DbInfo();
var aceSqlEditor = new AceSqlEditor("ace-editor");
var dataGrid = new DataGrid();
function runQuery () {
$('#server-run-time').html('');
$('#rowcount').html('');
dataGrid.emptyDataGrid();
var data = {
queryText: aceSqlEditor.getSelectedOrAllText(),
connectionId: $('#connection').val(),
cacheKey: $('#cache-key').val(),
queryName: getQueryName()
};
dataGrid.startRunningTimer();
$.ajax({
type: "POST",
url: "/run-query",
data: data
}).done(function (data) {
chartEditor.setData(data);
// TODO - if vis tab is active, render chart
dataGrid.stopRunningTimer();
$('#server-run-time').html(data.serverMs/1000 + " sec.");
if (data.success) {
$('.hide-while-running').show();
if (data.incomplete) {
$('.incomplete-notification').removeClass("hidden");
} else {
$('.incomplete-notification').addClass("hidden");
}
dataGrid.renderGridData(data);
} else {
dataGrid.renderError(data.error);
}
}).fail(function () {
dataGrid.stopRunningTimer();
dataGrid.renderError("Something is broken :(");
});
}
function getQueryName () {
return $('#header-query-name').val();
}
function getQueryTags () {
return $.map($('#tags').val().split(','), $.trim);
}
function saveQuery () {
var $queryId = $('#query-id');
var query = {
name: getQueryName(),
queryText: aceSqlEditor.getEditorText(),
tags: getQueryTags(),
connectionId: dbInfo.getConnectionId(),
chartConfiguration: chartEditor.getChartConfiguration()
};
$('#btn-save-result').text('saving...').show();
$.ajax({
type: "POST",
url: "/queries/" + $queryId.val(),
data: query
}).done(function (data) {
if (data.success) {
window.history.replaceState({}, "query " + data.query._id, "/queries/" + data.query._id);
$queryId.val(data.query._id);
$('#btn-save-result').removeClass('label-info').addClass('label-success').text('Success');
setTimeout(function () {
$('#btn-save-result').fadeOut(400, function () {
$('#btn-save-result').removeClass('label-success').addClass('label-info').text('');
});
}, 1000);
} else {
$('#btn-save-result').removeClass('label-info').addClass('label-danger').text('Failed');
}
}).fail(function () {
alert('ajax fail');
});
}
$('#btn-save').click(function (event) {
event.preventDefault();
event.stopPropagation();
saveQuery();
});
$('#btn-run-query').click(function (event) {
event.preventDefault();
event.stopPropagation();
runQuery();
});
/* (re-)render the chart when the viz tab is pressed,
TODO: only do this if necessary
==============================================================================*/
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
// if shown tab was the chart tab, rerender the chart
// e.target is the activated tab
if (e.target.getAttribute("href") == "#tab-content-visualize") {
chartEditor.rerenderChart();
} else if (e.target.getAttribute("href") == "#tab-content-sql") {
dataGrid.resize();
}
});
/* get query again, because not all the data is in the HTML
TODO: do most the workflow this way?
==============================================================================*/
var $queryId = $('#query-id');
$.ajax({
type: "GET",
url: "/queries/" + $queryId.val() + "?format=json"
}).done(function (data) {
console.log(data);
chartEditor.loadChartConfiguration(data.chartConfiguration);
}).fail(function () {
alert('Failed to get additional Query info');
});
/* Tags Typeahead
==============================================================================*/
var Bloodhound = require('Bloodhound');
var bloodhoundTags = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: '/tags', // array of tagnames
ttl: 0,
filter: function(list) {
return $.map(list, function(tag) {
return { name: tag }; });
}
}
});
bloodhoundTags.initialize();
$('#tags').tagsinput({
typeaheadjs: {
//name: 'tags',
displayKey: 'name',
valueKey: 'name',
source: bloodhoundTags.ttAdapter()
}
});
/* Shortcuts
==============================================================================*/
// keymaster doesn't fire on input/textarea events by default
// since we are only using command/ctrl shortcuts,
// we want the event to fire all the time for any element
keymaster.filter = function (event) {
return true;
};
keymaster('ctrl+s, command+s', function() {
saveQuery();
return false;
});
keymaster('ctrl+r, command+r, ctrl+e, command+e', function() {
runQuery();
return false;
});
};
module.exports = function () {
if ($('#ace-editor').length) {
new QueryEditor();
}
};
|
Java
|
package PracticeLeetCode;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class _127WordLadder {
psvm
}
|
Java
|
<?php
namespace Illuminate\Tests\Integration\Database\EloquentModelLoadMissingTest;
use DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
/**
* @group integration
*/
class EloquentModelLoadMissingTest extends DatabaseTestCase
{
protected function setUp(): void
{
parent::setUp();
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
});
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('parent_id')->nullable();
$table->unsignedInteger('post_id');
});
Post::create();
Comment::create(['parent_id' => null, 'post_id' => 1]);
Comment::create(['parent_id' => 1, 'post_id' => 1]);
}
public function testLoadMissing()
{
$post = Post::with('comments')->first();
DB::enableQueryLog();
$post->loadMissing('comments.parent');
$this->assertCount(1, DB::getQueryLog());
$this->assertTrue($post->comments[0]->relationLoaded('parent'));
}
}
class Comment extends Model
{
public $timestamps = false;
protected $guarded = ['id'];
public function parent()
{
return $this->belongsTo(Comment::class);
}
}
class Post extends Model
{
public $timestamps = false;
public function comments()
{
return $this->hasMany(Comment::class);
}
}
|
Java
|
import glob
import logging
import os
import subprocess
from plugins import BaseAligner
from yapsy.IPlugin import IPlugin
from assembly import get_qual_encoding
class Bowtie2Aligner(BaseAligner, IPlugin):
def run(self):
"""
Map READS to CONTIGS and return alignment.
Set MERGED_PAIR to True if reads[1] is a merged
paired end file
"""
contig_file = self.data.contigfiles[0]
reads = self.data.readfiles
## Index contigs
prefix = os.path.join(self.outpath, 'bt2')
cmd_args = [self.build_bin, '-f', contig_file, prefix]
self.arast_popen(cmd_args, overrides=False)
### Align reads
bamfiles = []
for i, readset in enumerate(self.data.readsets):
samfile = os.path.join(self.outpath, 'align.sam')
reads = readset.files
cmd_args = [self.executable, '-x', prefix, '-S', samfile,
'-p', self.process_threads_allowed]
if len(reads) == 2:
cmd_args += ['-1', reads[0], '-2', reads[1]]
elif len(reads) == 1:
cmd_args += ['-U', reads[0]]
else:
raise Exception('Bowtie plugin error')
self.arast_popen(cmd_args, overrides=False)
if not os.path.exists(samfile):
raise Exception('Unable to complete alignment')
## Convert to BAM
bamfile = samfile.replace('.sam', '.bam')
cmd_args = ['samtools', 'view',
'-bSho', bamfile, samfile]
self.arast_popen(cmd_args)
bamfiles.append(bamfile)
### Merge samfiles if multiple
if len(bamfiles) > 1:
bamfile = os.path.join(self.outpath, '{}_{}.bam'.format(os.path.basename(contig_file), i))
self.arast_popen(['samtools', 'merge', bamfile] + bamfiles)
if not os.path.exists(bamfile):
raise Exception('Unable to complete alignment')
else:
bamfile = bamfiles[0]
if not os.path.exists(bamfile):
raise Exception('Unable to complete alignment')
## Convert back to sam
samfile = bamfile.replace('.bam', '.sam')
self.arast_popen(['samtools', 'view', '-h', '-o', samfile, bamfile])
return {'alignment': samfile,
'alignment_bam': bamfile}
|
Java
|
namespace EventCloud.Events.Dtos
{
public class GetEventListInput
{
public bool IncludeCanceledEvents { get; set; }
}
}
|
Java
|
// # Frontend Route tests
// As it stands, these tests depend on the database, and as such are integration tests.
// Mocking out the models to not touch the DB would turn these into unit tests, and should probably be done in future,
// But then again testing real code, rather than mock code, might be more useful...
const should = require('should');
const sinon = require('sinon');
const supertest = require('supertest');
const moment = require('moment');
const cheerio = require('cheerio');
const _ = require('lodash');
const testUtils = require('../../utils');
const configUtils = require('../../utils/configUtils');
const urlUtils = require('../../utils/urlUtils');
const config = require('../../../core/shared/config');
const settingsCache = require('../../../core/server/services/settings/cache');
const origCache = _.cloneDeep(settingsCache);
const ghost = testUtils.startGhost;
let request;
describe('Frontend Routing', function () {
function doEnd(done) {
return function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
should.not.exist(res.headers['X-CSRF-Token']);
should.not.exist(res.headers['set-cookie']);
should.exist(res.headers.date);
done();
};
}
function addPosts(done) {
testUtils.clearData().then(function () {
return testUtils.initData();
}).then(function () {
return testUtils.fixtures.insertPostsAndTags();
}).then(function () {
done();
});
}
afterEach(function () {
sinon.restore();
});
before(function () {
return ghost()
.then(function () {
request = supertest.agent(config.get('url'));
});
});
describe('Test with Initial Fixtures', function () {
describe('Error', function () {
it('should 404 for unknown post with invalid characters', function (done) {
request.get('/$pec+acular~/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
it('should 404 for unknown frontend route', function (done) {
request.get('/spectacular/marvellous/')
.set('Accept', 'application/json')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
it('should 404 for encoded char not 301 from uncapitalise', function (done) {
request.get('/|/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
});
describe('Default Redirects (clean URLS)', function () {
it('Single post should redirect without slash', function (done) {
request.get('/welcome')
.expect('Location', '/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('Single post should redirect uppercase', function (done) {
request.get('/Welcome/')
.expect('Location', '/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('Single post should sanitize double slashes when redirecting uppercase', function (done) {
request.get('///Google.com/')
.expect('Location', '/google.com/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('AMP post should redirect without slash', function (done) {
request.get('/welcome/amp')
.expect('Location', '/welcome/amp/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('AMP post should redirect uppercase', function (done) {
request.get('/Welcome/AMP/')
.expect('Location', '/welcome/amp/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
});
});
describe('Test with added posts', function () {
before(addPosts);
describe('Static page', function () {
it('should respond with html', function (done) {
request.get('/static-page-test/')
.expect('Content-Type', /html/)
.expect('Cache-Control', testUtils.cacheRules.public)
.expect(200)
.end(function (err, res) {
const $ = cheerio.load(res.text);
should.not.exist(res.headers['x-cache-invalidate']);
should.not.exist(res.headers['X-CSRF-Token']);
should.not.exist(res.headers['set-cookie']);
should.exist(res.headers.date);
$('title').text().should.equal('This is a static page');
$('body.page-template').length.should.equal(1);
$('article.post').length.should.equal(1);
doEnd(done)(err, res);
});
});
it('should redirect without slash', function (done) {
request.get('/static-page-test')
.expect('Location', '/static-page-test/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
describe('edit', function () {
it('should redirect without slash', function (done) {
request.get('/static-page-test/edit')
.expect('Location', '/static-page-test/edit/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('should redirect to editor', function (done) {
request.get('/static-page-test/edit/')
.expect('Location', /ghost\/#\/editor\/\w+/)
.expect('Cache-Control', testUtils.cacheRules.public)
.expect(302)
.end(doEnd(done));
});
it('should 404 for non-edit parameter', function (done) {
request.get('/static-page-test/notedit/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Page not found/)
.end(doEnd(done));
});
});
describe('edit with admin redirects disabled', function () {
before(function (done) {
configUtils.set('admin:redirects', false);
ghost({forceStart: true})
.then(function () {
request = supertest.agent(config.get('url'));
addPosts(done);
});
});
after(function (done) {
configUtils.restore();
ghost({forceStart: true})
.then(function () {
request = supertest.agent(config.get('url'));
addPosts(done);
});
});
it('should redirect without slash', function (done) {
request.get('/static-page-test/edit')
.expect('Location', '/static-page-test/edit/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
it('should not redirect to editor', function (done) {
request.get('/static-page-test/edit/')
.expect(404)
.expect('Cache-Control', testUtils.cacheRules.private)
.end(doEnd(done));
});
});
describe('amp', function () {
it('should 404 for amp parameter', function (done) {
// NOTE: only post pages are supported so the router doesn't have a way to distinguish if
// the request was done after AMP 'Page' or 'Post'
request.get('/static-page-test/amp/')
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.expect(/Post not found/)
.end(doEnd(done));
});
});
});
describe('Post preview', function () {
it('should display draft posts accessed via uuid', function (done) {
request.get('/p/d52c42ae-2755-455c-80ec-70b2ec55c903/')
.expect('Content-Type', /html/)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
const $ = cheerio.load(res.text);
should.not.exist(res.headers['x-cache-invalidate']);
should.not.exist(res.headers['X-CSRF-Token']);
should.not.exist(res.headers['set-cookie']);
should.exist(res.headers.date);
$('title').text().should.equal('Not finished yet');
// @TODO: use theme from fixtures and don't rely on content/themes/casper
// $('.content .post').length.should.equal(1);
// $('.poweredby').text().should.equal('Proudly published with Ghost');
// $('body.post-template').length.should.equal(1);
// $('article.post').length.should.equal(1);
done();
});
});
it('should redirect published posts to their live url', function (done) {
request.get('/p/2ac6b4f6-e1f3-406c-9247-c94a0496d39d/')
.expect(301)
.expect('Location', '/short-and-sweet/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('404s unknown uuids', function (done) {
request.get('/p/aac6b4f6-e1f3-406c-9247-c94a0496d39f/')
.expect(404)
.end(doEnd(done));
});
});
describe('Post with Ghost in the url', function () {
// All of Ghost's admin depends on the /ghost/ in the url to work properly
// Badly formed regexs can cause breakage if a post slug starts with the 5 letters ghost
it('should retrieve a blog post with ghost at the start of the url', function (done) {
request.get('/ghostly-kitchen-sink/')
.expect('Cache-Control', testUtils.cacheRules.public)
.expect(200)
.end(doEnd(done));
});
});
});
describe('Subdirectory (no slash)', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost/blog');
urlUtils.stubUrlUtilsFromConfig();
return ghost({forceStart: true, subdir: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
it('http://localhost should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('http://localhost/ should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('http://localhost/blog should 301 to http://localhost/blog/', function (done) {
request.get('/blog')
.expect(301)
.expect('Location', '/blog/')
.end(doEnd(done));
});
it('http://localhost/blog/ should 200', function (done) {
request.get('/blog/')
.expect(200)
.end(doEnd(done));
});
it('http://localhost/blog/welcome should 301 to http://localhost/blog/welcome/', function (done) {
request.get('/blog/welcome')
.expect(301)
.expect('Location', '/blog/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('http://localhost/blog/welcome/ should 200', function (done) {
request.get('/blog/welcome/')
.expect(200)
.end(doEnd(done));
});
it('/blog/tag/getting-started should 301 to /blog/tag/getting-started/', function (done) {
request.get('/blog/tag/getting-started')
.expect(301)
.expect('Location', '/blog/tag/getting-started/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('/blog/tag/getting-started/ should 200', function (done) {
request.get('/blog/tag/getting-started/')
.expect(200)
.end(doEnd(done));
});
it('/blog/welcome/amp/ should 200', function (done) {
request.get('/blog/welcome/amp/')
.expect(200)
.end(doEnd(done));
});
});
describe('Subdirectory (with slash)', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost/blog/');
urlUtils.stubUrlUtilsFromConfig();
return ghost({forceStart: true, subdir: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
it('http://localhost should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('http://localhost/ should 404', function (done) {
request.get('/')
.expect(404)
.end(doEnd(done));
});
it('/blog should 301 to /blog/', function (done) {
request.get('/blog')
.expect(301)
.expect('Location', '/blog/')
.end(doEnd(done));
});
it('/blog/ should 200', function (done) {
request.get('/blog/')
.expect(200)
.end(doEnd(done));
});
it('/blog/welcome should 301 to /blog/welcome/', function (done) {
request.get('/blog/welcome')
.expect(301)
.expect('Location', '/blog/welcome/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('/blog/welcome/ should 200', function (done) {
request.get('/blog/welcome/')
.expect(200)
.end(doEnd(done));
});
it('/blog/tag/getting-started should 301 to /blog/tag/getting-started/', function (done) {
request.get('/blog/tag/getting-started')
.expect(301)
.expect('Location', '/blog/tag/getting-started/')
.expect('Cache-Control', testUtils.cacheRules.year)
.end(doEnd(done));
});
it('/blog/tag/getting-started/ should 200', function (done) {
request.get('/blog/tag/getting-started/')
.expect(200)
.end(doEnd(done));
});
it('/blog/welcome/amp/ should 200', function (done) {
request.get('/blog/welcome/amp/')
.expect(200)
.end(doEnd(done));
});
it('should uncapitalise correctly with 301 to subdir', function (done) {
request.get('/blog/AAA/')
.expect('Location', '/blog/aaa/')
.expect('Cache-Control', testUtils.cacheRules.year)
.expect(301)
.end(doEnd(done));
});
});
// we'll use X-Forwarded-Proto: https to simulate an 'https://' request behind a proxy
describe('HTTPS', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost:2370/');
urlUtils.stubUrlUtilsFromConfig();
return ghost({forceStart: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
it('should set links to url over non-HTTPS', function (done) {
request.get('/')
.expect(200)
.expect(/<link rel="canonical" href="http:\/\/localhost:2370\/" \/\>/)
.expect(/<a href="http:\/\/localhost:2370">Ghost<\/a\>/)
.end(doEnd(done));
});
it('should set links over HTTPS besides canonical', function (done) {
request.get('/')
.set('X-Forwarded-Proto', 'https')
.expect(200)
.expect(/<link rel="canonical" href="http:\/\/localhost:2370\/" \/\>/)
.expect(/<a href="https:\/\/localhost:2370">Ghost<\/a\>/)
.end(doEnd(done));
});
});
// TODO: convert to unit tests
describe('Redirects (use redirects.json from test/utils/fixtures/data)', function () {
let ghostServer;
before(function () {
configUtils.set('url', 'http://localhost:2370/');
urlUtils.stubUrlUtilsFromConfig();
return ghost({forceStart: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
describe('1 case', function () {
it('with trailing slash', function (done) {
request.get('/post/10/a-nice-blog-post')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/a-nice-blog-post');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/post/10/a-nice-blog-post/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/a-nice-blog-post');
doEnd(done)(err, res);
});
});
it('with query params', function (done) {
request.get('/topic?something=good')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/?something=good');
doEnd(done)(err, res);
});
});
it('with query params', function (done) {
request.get('/post/10/a-nice-blog-post?a=b')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/a-nice-blog-post?a=b');
doEnd(done)(err, res);
});
});
it('with case insensitive', function (done) {
request.get('/CaSe-InSeNsItIvE')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/redirected-insensitive');
doEnd(done)(err, res);
});
});
it('with case sensitive', function (done) {
request.get('/Case-Sensitive')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/redirected-sensitive');
doEnd(done)(err, res);
});
});
it('defaults to case sensitive', function (done) {
request.get('/Default-Sensitive')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/redirected-default');
doEnd(done)(err, res);
});
});
it('should not redirect with case sensitive', function (done) {
request.get('/casE-sensitivE')
.end(function (err, res) {
res.headers.location.should.not.eql('/redirected-sensitive');
res.statusCode.should.not.eql(302);
doEnd(done)(err, res);
});
});
it('should not redirect with default case sensitive', function (done) {
request.get('/defaulT-sensitivE')
.end(function (err, res) {
res.headers.location.should.not.eql('/redirected-default');
res.statusCode.should.not.eql(302);
doEnd(done)(err, res);
});
});
});
describe('2 case', function () {
it('with trailing slash', function (done) {
request.get('/my-old-blog-post/')
.expect(301)
.expect('Cache-Control', testUtils.cacheRules.year)
.end(function (err, res) {
res.headers.location.should.eql('/revamped-url/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/my-old-blog-post')
.expect(301)
.expect('Cache-Control', testUtils.cacheRules.year)
.end(function (err, res) {
res.headers.location.should.eql('/revamped-url/');
doEnd(done)(err, res);
});
});
});
describe('3 case', function () {
it('with trailing slash', function (done) {
request.get('/what/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/what-does-god-say');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/what')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/what-does-god-say');
doEnd(done)(err, res);
});
});
});
describe('4 case', function () {
it('with trailing slash', function (done) {
request.get('/search/label/&&&/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/tag/&&&/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/search/label/&&&/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/tag/&&&/');
doEnd(done)(err, res);
});
});
});
describe('5 case', function () {
it('with trailing slash', function (done) {
request.get('/topic/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/topic')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/');
doEnd(done)(err, res);
});
});
});
describe('6 case', function () {
it('with trailing slash', function (done) {
request.get('/resources/download/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/shubal-stearns');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/resources/download')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/shubal-stearns');
doEnd(done)(err, res);
});
});
});
describe('7 case', function () {
it('with trailing slash', function (done) {
request.get('/2016/11/welcome.html')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/welcome');
doEnd(done)(err, res);
});
});
});
describe('last case', function () {
it('default', function (done) {
request.get('/prefix/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/blog/');
doEnd(done)(err, res);
});
});
it('with a custom path', function (done) {
request.get('/prefix/expect-redirect')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/blog/expect-redirect');
doEnd(done)(err, res);
});
});
});
describe('external url redirect', function () {
it('with trailing slash', function (done) {
request.get('/external-url/')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/');
doEnd(done)(err, res);
});
});
it('without trailing slash', function (done) {
request.get('/external-url')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/');
doEnd(done)(err, res);
});
});
it('with capturing group', function (done) {
request.get('/external-url/docs')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/docs');
doEnd(done)(err, res);
});
});
});
});
describe('Subdirectory redirects (use redirects.json from test/utils/fixtures/data)', function () {
var ghostServer;
before(function () {
configUtils.set('url', 'http://localhost:2370/blog/');
urlUtils.stubUrlUtilsFromConfig();
return ghost({forceStart: true, subdir: true})
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('server:host') + ':' + config.get('server:port'));
});
});
after(function () {
configUtils.restore();
urlUtils.restore();
});
describe('internal url redirect', function () {
it('should include the subdirectory', function (done) {
request.get('/blog/my-old-blog-post/')
.expect(301)
.expect('Cache-Control', testUtils.cacheRules.year)
.end(function (err, res) {
res.headers.location.should.eql('/blog/revamped-url/');
doEnd(done)(err, res);
});
});
it('should work with regex "from" redirects', function (done) {
request.get('/blog/capture1/whatever')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('/blog/whatever');
doEnd(done)(err, res);
});
});
});
describe('external url redirect', function () {
it('should not include the subdirectory', function (done) {
request.get('/blog/external-url/docs')
.expect(302)
.expect('Cache-Control', testUtils.cacheRules.public)
.end(function (err, res) {
res.headers.location.should.eql('https://ghost.org/docs');
doEnd(done)(err, res);
});
});
});
});
});
|
Java
|
# wealth-view
Single page application for viewing your financial portfolio
|
Java
|
require 'mkmf'
extension_name = 'fortitude_native_ext'
dir_config(extension_name)
create_makefile(extension_name)
|
Java
|
import { browser, by, element } from 'protractor';
describe('App', () => {
beforeEach(() => {
// change hash depending on router LocationStrategy
browser.get('/#/home');
});
it('should have a title', () => {
let subject = browser.getTitle();
let result = 'Chroma An Interactive Palette tool';
expect(subject).toEqual(result);
});
it('should have `your content here` x-large', () => {
let subject = element(by.css('[x-large]')).getText();
let result = 'Your Content Here';
expect(subject).toEqual(result);
});
});
|
Java
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M21 5H3c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-2 12H5V7h14v10zm-9-1h4c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1v-1c0-1.11-.9-2-2-2-1.11 0-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1zm.8-6c0-.66.54-1.2 1.2-1.2s1.2.54 1.2 1.2v1h-2.4v-1z"
}), 'ScreenLockLandscapeOutlined');
exports.default = _default;
|
Java
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Persistence;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.WebApi.Filters;
using umbraco;
using umbraco.BusinessLogic.Actions;
using System.Globalization;
namespace Umbraco.Web.Trees
{
public abstract class ContentTreeControllerBase : TreeController
{
#region Actions
/// <summary>
/// Gets an individual tree node
/// </summary>
/// <param name="id"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
[HttpQueryStringFilter("queryStrings")]
public TreeNode GetTreeNode(string id, FormDataCollection queryStrings)
{
int asInt;
Guid asGuid = Guid.Empty;
if (int.TryParse(id, out asInt) == false)
{
if (Guid.TryParse(id, out asGuid) == false)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
}
var entity = asGuid == Guid.Empty
? Services.EntityService.Get(asInt, UmbracoObjectType)
: Services.EntityService.GetByKey(asGuid, UmbracoObjectType);
if (entity == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
var node = GetSingleTreeNode(entity, entity.ParentId.ToInvariantString(), queryStrings);
//add the tree alias to the node since it is standalone (has no root for which this normally belongs)
node.AdditionalData["treeAlias"] = TreeAlias;
return node;
}
#endregion
/// <summary>
/// Ensure the noAccess metadata is applied for the root node if in dialog mode and the user doesn't have path access to it
/// </summary>
/// <param name="queryStrings"></param>
/// <returns></returns>
protected override TreeNode CreateRootNode(FormDataCollection queryStrings)
{
var node = base.CreateRootNode(queryStrings);
if (IsDialog(queryStrings) && UserStartNodes.Contains(Constants.System.Root) == false)
{
node.AdditionalData["noAccess"] = true;
}
return node;
}
protected abstract TreeNode GetSingleTreeNode(IUmbracoEntity e, string parentId, FormDataCollection queryStrings);
/// <summary>
/// Returns a <see cref="TreeNode"/> for the <see cref="IUmbracoEntity"/> and
/// attaches some meta data to the node if the user doesn't have start node access to it when in dialog mode
/// </summary>
/// <param name="e"></param>
/// <param name="parentId"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
internal TreeNode GetSingleTreeNodeWithAccessCheck(IUmbracoEntity e, string parentId, FormDataCollection queryStrings)
{
bool hasPathAccess;
var entityIsAncestorOfStartNodes = Security.CurrentUser.IsInBranchOfStartNode(e, Services.EntityService, RecycleBinId, out hasPathAccess);
if (entityIsAncestorOfStartNodes == false)
return null;
var treeNode = GetSingleTreeNode(e, parentId, queryStrings);
if (treeNode == null)
{
//this means that the user has NO access to this node via permissions! They at least need to have browse permissions to see
//the node so we need to return null;
return null;
}
if (hasPathAccess == false)
{
treeNode.AdditionalData["noAccess"] = true;
}
return treeNode;
}
/// <summary>
/// Returns the
/// </summary>
protected abstract int RecycleBinId { get; }
/// <summary>
/// Returns true if the recycle bin has items in it
/// </summary>
protected abstract bool RecycleBinSmells { get; }
/// <summary>
/// Returns the user's start node for this tree
/// </summary>
protected abstract int[] UserStartNodes { get; }
protected virtual TreeNodeCollection PerformGetTreeNodes(string id, FormDataCollection queryStrings)
{
var nodes = new TreeNodeCollection();
var rootIdString = Constants.System.Root.ToString(CultureInfo.InvariantCulture);
var hasAccessToRoot = UserStartNodes.Contains(Constants.System.Root);
var startNodeId = queryStrings.HasKey(TreeQueryStringParameters.StartNodeId)
? queryStrings.GetValue<string>(TreeQueryStringParameters.StartNodeId)
: string.Empty;
if (string.IsNullOrEmpty(startNodeId) == false && startNodeId != "undefined" && startNodeId != rootIdString)
{
// request has been made to render from a specific, non-root, start node
id = startNodeId;
// ensure that the user has access to that node, otherwise return the empty tree nodes collection
// TODO: in the future we could return a validation statement so we can have some UI to notify the user they don't have access
if (HasPathAccess(id, queryStrings) == false)
{
LogHelper.Warn<ContentTreeControllerBase>("User " + Security.CurrentUser.Username + " does not have access to node with id " + id);
return nodes;
}
// if the tree is rendered...
// - in a dialog: render only the children of the specific start node, nothing to do
// - in a section: if the current user's start nodes do not contain the root node, we need
// to include these start nodes in the tree too, to provide some context - i.e. change
// start node back to root node, and then GetChildEntities method will take care of the rest.
if (IsDialog(queryStrings) == false && hasAccessToRoot == false)
id = rootIdString;
}
// get child entities - if id is root, but user's start nodes do not contain the
// root node, this returns the start nodes instead of root's children
var entities = GetChildEntities(id).ToList();
nodes.AddRange(entities.Select(x => GetSingleTreeNodeWithAccessCheck(x, id, queryStrings)).Where(x => x != null));
// if the user does not have access to the root node, what we have is the start nodes,
// but to provide some context we also need to add their topmost nodes when they are not
// topmost nodes themselves (level > 1).
if (id == rootIdString && hasAccessToRoot == false)
{
var topNodeIds = entities.Where(x => x.Level > 1).Select(GetTopNodeId).Where(x => x != 0).Distinct().ToArray();
if (topNodeIds.Length > 0)
{
var topNodes = Services.EntityService.GetAll(UmbracoObjectType, topNodeIds.ToArray());
nodes.AddRange(topNodes.Select(x => GetSingleTreeNodeWithAccessCheck(x, id, queryStrings)).Where(x => x != null));
}
}
return nodes;
}
private static readonly char[] Comma = { ',' };
private int GetTopNodeId(IUmbracoEntity entity)
{
int id;
var parts = entity.Path.Split(Comma, StringSplitOptions.RemoveEmptyEntries);
return parts.Length >= 2 && int.TryParse(parts[1], out id) ? id : 0;
}
protected abstract MenuItemCollection PerformGetMenuForNode(string id, FormDataCollection queryStrings);
protected abstract UmbracoObjectTypes UmbracoObjectType { get; }
protected IEnumerable<IUmbracoEntity> GetChildEntities(string id)
{
// try to parse id as an integer else use GetEntityFromId
// which will grok Guids, Udis, etc and let use obtain the id
if (int.TryParse(id, out var entityId) == false)
{
var entity = GetEntityFromId(id);
if (entity == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
entityId = entity.Id;
}
return Services.EntityService.GetChildren(entityId, UmbracoObjectType).ToArray();
}
/// <summary>
/// Returns true or false if the current user has access to the node based on the user's allowed start node (path) access
/// </summary>
/// <param name="id"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
//we should remove this in v8, it's now here for backwards compat only
protected abstract bool HasPathAccess(string id, FormDataCollection queryStrings);
/// <summary>
/// Returns true or false if the current user has access to the node based on the user's allowed start node (path) access
/// </summary>
/// <param name="entity"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
protected bool HasPathAccess(IUmbracoEntity entity, FormDataCollection queryStrings)
{
if (entity == null) return false;
return Security.CurrentUser.HasPathAccess(entity, Services.EntityService, RecycleBinId);
}
/// <summary>
/// Ensures the recycle bin is appended when required (i.e. user has access to the root and it's not in dialog mode)
/// </summary>
/// <param name="id"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
/// <remarks>
/// This method is overwritten strictly to render the recycle bin, it should serve no other purpose
/// </remarks>
protected sealed override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
{
//check if we're rendering the root
if (id == Constants.System.Root.ToInvariantString() && UserStartNodes.Contains(Constants.System.Root))
{
var altStartId = string.Empty;
if (queryStrings.HasKey(TreeQueryStringParameters.StartNodeId))
altStartId = queryStrings.GetValue<string>(TreeQueryStringParameters.StartNodeId);
//check if a request has been made to render from a specific start node
if (string.IsNullOrEmpty(altStartId) == false && altStartId != "undefined" && altStartId != Constants.System.Root.ToString(CultureInfo.InvariantCulture))
{
id = altStartId;
}
var nodes = GetTreeNodesInternal(id, queryStrings);
//only render the recycle bin if we are not in dialog and the start id id still the root
if (IsDialog(queryStrings) == false && id == Constants.System.Root.ToInvariantString())
{
nodes.Add(CreateTreeNode(
RecycleBinId.ToInvariantString(),
id,
queryStrings,
ui.GetText("general", "recycleBin"),
"icon-trash",
RecycleBinSmells,
queryStrings.GetValue<string>("application") + TreeAlias.EnsureStartsWith('/') + "/recyclebin"));
}
return nodes;
}
return GetTreeNodesInternal(id, queryStrings);
}
/// <summary>
/// Before we make a call to get the tree nodes we have to check if they can actually be rendered
/// </summary>
/// <param name="id"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
/// <remarks>
/// Currently this just checks if it is a container type, if it is we cannot render children. In the future this might check for other things.
/// </remarks>
private TreeNodeCollection GetTreeNodesInternal(string id, FormDataCollection queryStrings)
{
var current = GetEntityFromId(id);
//before we get the children we need to see if this is a container node
//test if the parent is a listview / container
if (current != null && current.IsContainer())
{
//no children!
return new TreeNodeCollection();
}
return PerformGetTreeNodes(id, queryStrings);
}
/// <summary>
/// Checks if the menu requested is for the recycle bin and renders that, otherwise renders the result of PerformGetMenuForNode
/// </summary>
/// <param name="id"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
protected sealed override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings)
{
if (RecycleBinId.ToInvariantString() == id)
{
var menu = new MenuItemCollection();
menu.Items.Add<ActionEmptyTranscan>(ui.Text("actions", "emptyTrashcan"));
menu.Items.Add<ActionRefresh>(ui.Text("actions", ActionRefresh.Instance.Alias), true);
return menu;
}
return PerformGetMenuForNode(id, queryStrings);
}
/// <summary>
/// Based on the allowed actions, this will filter the ones that the current user is allowed
/// </summary>
/// <param name="menuWithAllItems"></param>
/// <param name="userAllowedMenuItems"></param>
/// <returns></returns>
protected void FilterUserAllowedMenuItems(MenuItemCollection menuWithAllItems, IEnumerable<MenuItem> userAllowedMenuItems)
{
var userAllowedActions = userAllowedMenuItems.Where(x => x.Action != null).Select(x => x.Action).ToArray();
var notAllowed = menuWithAllItems.Items.Where(
a => (a.Action != null
&& a.Action.CanBePermissionAssigned
&& (a.Action.CanBePermissionAssigned == false || userAllowedActions.Contains(a.Action) == false)))
.ToArray();
//remove the ones that aren't allowed.
foreach (var m in notAllowed)
{
menuWithAllItems.Items.Remove(m);
}
}
internal IEnumerable<MenuItem> GetAllowedUserMenuItemsForNode(IUmbracoEntity dd)
{
var actions = ActionsResolver.Current.FromActionSymbols(Security.CurrentUser.GetPermissions(dd.Path, Services.UserService))
.ToList();
// A user is allowed to delete their own stuff
if (dd.CreatorId == Security.GetUserId() && actions.Contains(ActionDelete.Instance) == false)
actions.Add(ActionDelete.Instance);
return actions.Select(x => new MenuItem(x));
}
/// <summary>
/// Determins if the user has access to view the node/document
/// </summary>
/// <param name="doc">The Document to check permissions against</param>
/// <param name="allowedUserOptions">A list of MenuItems that the user has permissions to execute on the current document</param>
/// <remarks>By default the user must have Browse permissions to see the node in the Content tree</remarks>
/// <returns></returns>
internal bool CanUserAccessNode(IUmbracoEntity doc, IEnumerable<MenuItem> allowedUserOptions)
{
return allowedUserOptions.Select(x => x.Action).OfType<ActionBrowse>().Any();
}
/// <summary>
/// this will parse the string into either a GUID or INT
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
internal Tuple<Guid?, int?> GetIdentifierFromString(string id)
{
Guid idGuid;
int idInt;
Udi idUdi;
if (Guid.TryParse(id, out idGuid))
{
return new Tuple<Guid?, int?>(idGuid, null);
}
if (int.TryParse(id, out idInt))
{
return new Tuple<Guid?, int?>(null, idInt);
}
if (Udi.TryParse(id, out idUdi))
{
var guidUdi = idUdi as GuidUdi;
if (guidUdi != null)
return new Tuple<Guid?, int?>(guidUdi.Guid, null);
}
return null;
}
/// <summary>
/// Get an entity via an id that can be either an integer, Guid or UDI
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <remarks>
/// This object has it's own contextual cache for these lookups
/// </remarks>
internal IUmbracoEntity GetEntityFromId(string id)
{
return _entityCache.GetOrAdd(id, s =>
{
IUmbracoEntity entity;
Guid idGuid;
int idInt;
Udi idUdi;
if (Guid.TryParse(s, out idGuid))
{
entity = Services.EntityService.GetByKey(idGuid, UmbracoObjectType);
}
else if (int.TryParse(s, out idInt))
{
entity = Services.EntityService.Get(idInt, UmbracoObjectType);
}
else if (Udi.TryParse(s, out idUdi))
{
var guidUdi = idUdi as GuidUdi;
entity = guidUdi != null ? Services.EntityService.GetByKey(guidUdi.Guid, UmbracoObjectType) : null;
}
else
{
return null;
}
return entity;
});
}
private readonly ConcurrentDictionary<string, IUmbracoEntity> _entityCache = new ConcurrentDictionary<string, IUmbracoEntity>();
}
}
|
Java
|
#### Scripts
##### SalesforceAskUser
- Updated the Docker image to: *demisto/python:2.7.18.24398*.
|
Java
|
const BaseStep = require('../step');
const EntryProxy = require('../../entry-proxy');
const analyze = require('../../helpers/analytics/analytics')('gst');
// TODO pull below out to (variation) helper
function convertVariationalPath(variations, from, toVariationId) {
const toDir = variations.find(variation => variation.id === toVariationId).dir;
const pattern = new RegExp(`(${variations.map(variation => variation.dir).join('|')})`);
return from.replace(pattern, toDir);
}
function isNodeModule(id) {
return id.indexOf('node_modules') >= 0;
}
class GraphSourceTransform extends BaseStep {
/**
* @param {MendelRegistry} tool.registry
* @param {DepsManager} tool.depsResolver
*/
constructor({registry, cache}, options) {
super();
this._cache = cache;
this._registry = registry;
this._baseVariationId = options.baseConfig.id;
this._variations = options.variationConfig.variations;
this._gsts = [];
this._transforms = options.transforms;
options.types.forEach(type => {
const gsts = type.transforms.filter((transformId) => {
const transform = this._transforms.find(({id}) => id === transformId);
return transform && transform.mode === 'gst';
});
this._gsts = this._gsts.concat(gsts);
});
this._curGstIndex = 0;
this._processed = new Set();
this._virtual = new Set();
this.clear();
this._cache.on('entryRemoved', () => this.clear());
}
clear() {
this._curGstIndex = 0;
this._processed.clear();
this._virtual.forEach(entryId => this._registry.removeEntry(entryId));
this._virtual.clear();
this._canceled = true;
}
addTransform({id, source='', map='', deps={}}) {
// This will add source to the "rawSource" so it does not have to
// go through fs-reader (which should fail as it can be a virtual entry)
this._registry.addTransformedSource({id, source, deps, map});
}
getContext() {
return {
addVirtualEntry: ({source, id, map}) => {
this._virtual.add(id);
// TODO make sure virtual entries can be cleaned up with changes in source entry
this.addTransform({id, source, map});
},
removeEntry: (entry) => {
this._registry.removeEntry(entry.id);
},
};
}
gstDone(entry) {
this._processed.add(entry.id);
if (this._processed.size >= this._cache.size()) {
this._processed.clear();
if (++this._curGstIndex >= this._gsts.length) {
this._cache.entries().forEach(({id}) => {
this.emit('done', {entryId: id});
});
} else {
this._cache.entries().forEach(entry => this.performHelper(entry));
}
}
}
// this is conforming to the steps API
perform(entry) {
this._canceled = false;
if (this._gsts.length <= this._curGstIndex || isNodeModule(entry.id))
return this.gstDone(entry);
this.performHelper(entry);
}
explorePermutation(graph, onPermutation) {
const configVariations = new Set();
this._variations.forEach(variation => configVariations.add(variation.id));
// graph has array of arrays. First, make a pass and gather all variation info
const variations = new Set();
graph.forEach(nodes => {
nodes.forEach(node => {
variations.add(node.variation);
});
});
Array.from(variations.keys())
// Filter out undeclared (in config) variations
.filter(varKey => configVariations.has(varKey))
// We do not yet support multi-variation.
.forEach(variation => {
const chain = graph.map((nodes) => {
return nodes.find(node => node.variation === variation) ||
nodes.find(node => {
return node.variation === this._baseVariationId ||
node.variation === false;
});
});
// In case a new entry is introduced in variations without one
// in the base folder, the main file won't exist.
// In that case, we should not explore the permutation.
if (!chain[0]) return;
onPermutation(chain, variation);
});
}
performHelper(entry) {
const proxy = EntryProxy.getFromEntry(entry);
const currentGstConfig = this._transforms.find(({id}) => id === this._gsts[this._curGstIndex]);
const currentGst = require(currentGstConfig.plugin);
// If no GST is planned for this type, abort.
// If plugin doesn't want to deal with it, abort.
if (this._processed.has(entry.id) || this._virtual.has(entry.id) || !currentGst.predicate(proxy)) {
return this.gstDone(entry);
}
const graph = this._registry.getDependencyGraph(entry.normalizedId, (depEntry) => {
// In fs-change case, we can start over from the ist and
// "deps" can be wrong. We want the ist version in such case.
const dependecyMap = this._curGstIndex === 0 ?
depEntry.istDeps : depEntry.deps;
return Object.keys(dependecyMap).map(literal => {
// FIXME GST can be difference for main and browser.
// The difference can lead to different SHA if done poorly.
// Currently, we just apply main version but browser version
// may be needed. Address this.
return dependecyMap[literal].main;
});
});
this.explorePermutation(graph, (chain, variation) => {
const [main] = chain;
// We need to create proxy for limiting API surface for plugin writers.
const context = this.getContext();
const chainProxy = chain
.filter(Boolean)
.map(dep => EntryProxy.getFromEntry(dep));
const [proxiedMain] = chainProxy;
proxiedMain.filename = convertVariationalPath(
this._variations,
main.id,
variation
);
Promise.resolve()
.then(analyze.tic.bind(analyze, currentGstConfig.id))
.then(() => {
return currentGst.transform(
chainProxy,
currentGstConfig,
context
);
})
.then(analyze.toc.bind(analyze, currentGstConfig.id))
.then(result => {
if (this._canceled) return;
if (result && result.source) {
if (main.variation === variation) {
this.addTransform({
id: proxiedMain.filename,
source: result.source,
map: result.map,
deps: result.deps,
});
} else {
context.addVirtualEntry({
id: proxiedMain.filename,
originatingEntry: entry,
source: result.source,
deps: result.deps,
});
}
}
this.gstDone(main);
})
.catch(error => {
error.message = `Errored while transforming ${main.id}:\n` + error.message;
this.emit('error', {error, id: main.id});
});
});
}
}
module.exports = GraphSourceTransform;
|
Java
|
'use strict';
// MODULES //
var tape = require( 'tape' );
var pow = require( 'math-power' );
var MAX_INT16 = require( './../lib' );
// TESTS //
tape( 'the main export is a number', function test( t ) {
t.ok( true, __filename );
t.equal( typeof MAX_INT16, 'number', 'main export is a number' );
t.end();
});
tape( 'the value equals 2**15 - 1', function test( t ) {
t.equal( MAX_INT16, pow(2,15) - 1, 'equals 2**15 - 1' );
t.end();
});
|
Java
|
/*!
* iScroll v4.1.8 ~ Copyright (c) 2011 Matteo Spinelli, http://cubiq.org
* Released under MIT license, http://cubiq.org/license
*/
(function(){
var m = Math,
vendor = (/webkit/i).test(navigator.appVersion) ? 'webkit' :
(/firefox/i).test(navigator.userAgent) ? 'Moz' :
'opera' in window ? 'O' : '',
// Browser capabilities
has3d = 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(),
hasTouch = 'ontouchstart' in window,
hasTransform = vendor + 'Transform' in document.documentElement.style,
isAndroid = (/android/gi).test(navigator.appVersion),
isIDevice = (/iphone|ipad/gi).test(navigator.appVersion),
isPlaybook = (/playbook/gi).test(navigator.appVersion),
hasTransitionEnd = isIDevice || isPlaybook,
nextFrame = (function() {
return window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.oRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { return setTimeout(callback, 1); }
})(),
cancelFrame = (function () {
return window.cancelRequestAnimationFrame
|| window.webkitCancelRequestAnimationFrame
|| window.mozCancelRequestAnimationFrame
|| window.oCancelRequestAnimationFrame
|| window.msCancelRequestAnimationFrame
|| clearTimeout
})(),
// Events
RESIZE_EV = 'onorientationchange' in window ? 'orientationchange' : 'resize',
START_EV = hasTouch ? 'touchstart' : 'mousedown',
MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
END_EV = hasTouch ? 'touchend' : 'mouseup',
CANCEL_EV = hasTouch ? 'touchcancel' : 'mouseup',
WHEEL_EV = vendor == 'Moz' ? 'DOMMouseScroll' : 'mousewheel',
// Helpers
trnOpen = 'translate' + (has3d ? '3d(' : '('),
trnClose = has3d ? ',0)' : ')',
// Constructor
iScroll = function (el, options) {
var that = this,
doc = document,
i;
that.wrapper = typeof el == 'object' ? el : doc.getElementById(el);
that.wrapper.style.overflow = 'hidden';
that.scroller = that.wrapper.children[0];
// Default options
that.options = {
hScroll: true,
vScroll: true,
bounce: true,
bounceLock: false,
momentum: true,
lockDirection: true,
useTransform: true,
useTransition: false,
topOffset: 0,
checkDOMChanges: false, // Experimental
// Scrollbar
hScrollbar: true,
vScrollbar: true,
fixedScrollbar: isAndroid,
hideScrollbar: isIDevice,
fadeScrollbar: isIDevice && has3d,
scrollbarClass: '',
// Zoom
zoom: false,
zoomMin: 1,
zoomMax: 4,
doubleTapZoom: 2,
wheelAction: 'scroll',
// Snap
snap: false,
snapThreshold: 1,
// Events
onRefresh: null,
onBeforeScrollStart: function (e) { e.preventDefault(); },
onScrollStart: null,
onBeforeScrollMove: null,
onScrollMove: null,
onBeforeScrollEnd: null,
onScrollEnd: null,
onTouchEnd: null,
onDestroy: null,
onZoomStart: null,
onZoom: null,
onZoomEnd: null,
// Added by Lissa
scrollOffsetLeft: 0,
scrollOffsetTop: 0
};
// User defined options
for (i in options) that.options[i] = options[i];
// Normalize options
that.options.useTransform = hasTransform ? that.options.useTransform : false;
that.options.hScrollbar = that.options.hScroll && that.options.hScrollbar;
that.options.vScrollbar = that.options.vScroll && that.options.vScrollbar;
that.options.zoom = that.options.useTransform && that.options.zoom;
that.options.useTransition = hasTransitionEnd && that.options.useTransition;
// Set some default styles
that.scroller.style[vendor + 'TransitionProperty'] = that.options.useTransform ? '-' + vendor.toLowerCase() + '-transform' : 'top left';
that.scroller.style[vendor + 'TransitionDuration'] = '0';
that.scroller.style[vendor + 'TransformOrigin'] = '0 0';
if (that.options.useTransition) that.scroller.style[vendor + 'TransitionTimingFunction'] = 'cubic-bezier(0.33,0.66,0.66,1)';
if (that.options.useTransform) that.scroller.style[vendor + 'Transform'] = trnOpen + '0,0' + trnClose;
else that.scroller.style.cssText += ';position:absolute;top:0;left:0';
if (that.options.useTransition) that.options.fixedScrollbar = true;
that.refresh();
that._bind(RESIZE_EV, window);
that._bind(START_EV);
if (!hasTouch) {
that._bind('mouseout', that.wrapper);
that._bind(WHEEL_EV);
}
if (that.options.checkDOMChanges) that.checkDOMTime = setInterval(function () {
that._checkDOMChanges();
}, 500);
};
// Prototype
iScroll.prototype = {
enabled: true,
x: 0,
y: 0,
steps: [],
scale: 1,
currPageX: 0, currPageY: 0,
pagesX: [], pagesY: [],
aniTime: null,
wheelZoomCount: 0,
handleEvent: function (e) {
var that = this;
switch(e.type) {
case START_EV:
if (!hasTouch && e.button !== 0) return;
that._start(e);
break;
case MOVE_EV: that._move(e); break;
case END_EV:
case CANCEL_EV: that._end(e); break;
case RESIZE_EV: that._resize(); break;
case WHEEL_EV: that._wheel(e); break;
case 'mouseout': that._mouseout(e); break;
case 'webkitTransitionEnd': that._transitionEnd(e); break;
}
},
_checkDOMChanges: function () {
if (this.moved || this.zoomed || this.animating ||
(this.scrollerW == this.scroller.offsetWidth * this.scale && this.scrollerH == this.scroller.offsetHeight * this.scale)) return;
this.refresh();
},
_scrollbar: function (dir) {
var that = this,
doc = document,
bar;
if (!that[dir + 'Scrollbar']) {
if (that[dir + 'ScrollbarWrapper']) {
if (hasTransform) that[dir + 'ScrollbarIndicator'].style[vendor + 'Transform'] = '';
that[dir + 'ScrollbarWrapper'].parentNode.removeChild(that[dir + 'ScrollbarWrapper']);
that[dir + 'ScrollbarWrapper'] = null;
that[dir + 'ScrollbarIndicator'] = null;
}
return;
}
if (!that[dir + 'ScrollbarWrapper']) {
// Create the scrollbar wrapper
bar = doc.createElement('div');
if (that.options.scrollbarClass) bar.className = that.options.scrollbarClass + dir.toUpperCase();
else bar.style.cssText = 'position:absolute;z-index:100;' + (dir == 'h' ? 'height:7px;bottom:1px;left:2px;right:' + (that.vScrollbar ? '7' : '2') + 'px' : 'width:7px;bottom:' + (that.hScrollbar ? '7' : '2') + 'px;top:2px;right:1px');
bar.style.cssText += ';pointer-events:none;-' + vendor + '-transition-property:opacity;-' + vendor + '-transition-duration:' + (that.options.fadeScrollbar ? '350ms' : '0') + ';overflow:hidden;opacity:' + (that.options.hideScrollbar ? '0' : '1');
that.wrapper.appendChild(bar);
that[dir + 'ScrollbarWrapper'] = bar;
// Create the scrollbar indicator
bar = doc.createElement('div');
if (!that.options.scrollbarClass) {
bar.style.cssText = 'position:absolute;z-index:100;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);-' + vendor + '-background-clip:padding-box;-' + vendor + '-box-sizing:border-box;' + (dir == 'h' ? 'height:100%' : 'width:100%') + ';-' + vendor + '-border-radius:3px;border-radius:3px';
}
bar.style.cssText += ';pointer-events:none;-' + vendor + '-transition-property:-' + vendor + '-transform;-' + vendor + '-transition-timing-function:cubic-bezier(0.33,0.66,0.66,1);-' + vendor + '-transition-duration:0;-' + vendor + '-transform:' + trnOpen + '0,0' + trnClose;
if (that.options.useTransition) bar.style.cssText += ';-' + vendor + '-transition-timing-function:cubic-bezier(0.33,0.66,0.66,1)';
that[dir + 'ScrollbarWrapper'].appendChild(bar);
that[dir + 'ScrollbarIndicator'] = bar;
}
if (dir == 'h') {
that.hScrollbarSize = that.hScrollbarWrapper.clientWidth;
that.hScrollbarIndicatorSize = m.max(m.round(that.hScrollbarSize * that.hScrollbarSize / that.scrollerW), 8);
that.hScrollbarIndicator.style.width = that.hScrollbarIndicatorSize + 'px';
that.hScrollbarMaxScroll = that.hScrollbarSize - that.hScrollbarIndicatorSize;
that.hScrollbarProp = that.hScrollbarMaxScroll / that.maxScrollX;
} else {
that.vScrollbarSize = that.vScrollbarWrapper.clientHeight;
that.vScrollbarIndicatorSize = m.max(m.round(that.vScrollbarSize * that.vScrollbarSize / that.scrollerH), 8);
that.vScrollbarIndicator.style.height = that.vScrollbarIndicatorSize + 'px';
that.vScrollbarMaxScroll = that.vScrollbarSize - that.vScrollbarIndicatorSize;
that.vScrollbarProp = that.vScrollbarMaxScroll / that.maxScrollY;
}
// Reset position
that._scrollbarPos(dir, true);
},
_resize: function () {
var that = this;
setTimeout(function () { that.refresh(); }, isAndroid ? 200 : 0);
},
_pos: function (x, y) {
x = this.hScroll ? x : 0;
y = this.vScroll ? y : 0;
if (this.options.useTransform) {
this.scroller.style[vendor + 'Transform'] = trnOpen + x + 'px,' + y + 'px' + trnClose + ' scale(' + this.scale + ')';
} else {
x = m.round(x);
y = m.round(y);
this.scroller.style.left = x + 'px';
this.scroller.style.top = y + 'px';
}
this.x = x;
this.y = y;
this._scrollbarPos('h');
this._scrollbarPos('v');
},
_scrollbarPos: function (dir, hidden) {
var that = this,
pos = dir == 'h' ? that.x : that.y,
size;
if (!that[dir + 'Scrollbar']) return;
pos = that[dir + 'ScrollbarProp'] * pos;
if (pos < 0) {
if (!that.options.fixedScrollbar) {
size = that[dir + 'ScrollbarIndicatorSize'] + m.round(pos * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
}
pos = 0;
} else if (pos > that[dir + 'ScrollbarMaxScroll']) {
if (!that.options.fixedScrollbar) {
size = that[dir + 'ScrollbarIndicatorSize'] - m.round((pos - that[dir + 'ScrollbarMaxScroll']) * 3);
if (size < 8) size = 8;
that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
pos = that[dir + 'ScrollbarMaxScroll'] + (that[dir + 'ScrollbarIndicatorSize'] - size);
} else {
pos = that[dir + 'ScrollbarMaxScroll'];
}
}
that[dir + 'ScrollbarWrapper'].style[vendor + 'TransitionDelay'] = '0';
that[dir + 'ScrollbarWrapper'].style.opacity = hidden && that.options.hideScrollbar ? '0' : '1';
that[dir + 'ScrollbarIndicator'].style[vendor + 'Transform'] = trnOpen + (dir == 'h' ? pos + 'px,0' : '0,' + pos + 'px') + trnClose;
},
_start: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
matrix, x, y,
c1, c2;
if (!that.enabled) return;
if (that.options.onBeforeScrollStart) that.options.onBeforeScrollStart.call(that, e);
if (that.options.useTransition || that.options.zoom) that._transitionTime(0);
that.moved = false;
that.animating = false;
that.zoomed = false;
that.distX = 0;
that.distY = 0;
that.absDistX = 0;
that.absDistY = 0;
that.dirX = 0;
that.dirY = 0;
// Gesture start
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX-e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY-e.touches[1].pageY);
that.touchesDistStart = m.sqrt(c1 * c1 + c2 * c2);
that.originX = m.abs(e.touches[0].pageX + e.touches[1].pageX - that.wrapperOffsetLeft * 2) / 2 - that.x;
that.originY = m.abs(e.touches[0].pageY + e.touches[1].pageY - that.wrapperOffsetTop * 2) / 2 - that.y;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
}
if (that.options.momentum) {
if (that.options.useTransform) {
// Very lame general purpose alternative to CSSMatrix
matrix = getComputedStyle(that.scroller, null)[vendor + 'Transform'].replace(/[^0-9-.,]/g, '').split(',');
x = matrix[4] * 1;
y = matrix[5] * 1;
} else {
x = getComputedStyle(that.scroller, null).left.replace(/[^0-9-]/g, '') * 1;
y = getComputedStyle(that.scroller, null).top.replace(/[^0-9-]/g, '') * 1;
}
if (x != that.x || y != that.y) {
if (that.options.useTransition) that._unbind('webkitTransitionEnd');
else cancelFrame(that.aniTime);
that.steps = [];
that._pos(x, y);
}
}
that.absStartX = that.x; // Needed by snap threshold
that.absStartY = that.y;
that.startX = that.x;
that.startY = that.y;
that.pointX = point.pageX;
that.pointY = point.pageY;
that.startTime = e.timeStamp || (new Date()).getTime();
if (that.options.onScrollStart) that.options.onScrollStart.call(that, e);
that._bind(MOVE_EV);
that._bind(END_EV);
that._bind(CANCEL_EV);
},
_move: function (e) {
var that = this,
point = hasTouch ? e.touches[0] : e,
deltaX = point.pageX - that.pointX,
deltaY = point.pageY - that.pointY,
newX = that.x + deltaX,
newY = that.y + deltaY,
c1, c2, scale,
timestamp = e.timeStamp || (new Date()).getTime();
if (that.options.onBeforeScrollMove) that.options.onBeforeScrollMove.call(that, e);
// Zoom
if (that.options.zoom && hasTouch && e.touches.length > 1) {
c1 = m.abs(e.touches[0].pageX - e.touches[1].pageX);
c2 = m.abs(e.touches[0].pageY - e.touches[1].pageY);
that.touchesDist = m.sqrt(c1*c1+c2*c2);
that.zoomed = true;
scale = 1 / that.touchesDistStart * that.touchesDist * this.scale;
if (scale < that.options.zoomMin) scale = 0.5 * that.options.zoomMin * Math.pow(2.0, scale / that.options.zoomMin);
else if (scale > that.options.zoomMax) scale = 2.0 * that.options.zoomMax * Math.pow(0.5, that.options.zoomMax / scale);
that.lastScale = scale / this.scale;
newX = this.originX - this.originX * that.lastScale + this.x,
newY = this.originY - this.originY * that.lastScale + this.y;
this.scroller.style[vendor + 'Transform'] = trnOpen + newX + 'px,' + newY + 'px' + trnClose + ' scale(' + scale + ')';
if (that.options.onZoom) that.options.onZoom.call(that, e);
return;
}
that.pointX = point.pageX;
that.pointY = point.pageY;
// Slow down if outside of the boundaries
if (newX > 0 || newX < that.maxScrollX) {
newX = that.options.bounce ? that.x + (deltaX / 2) : newX >= 0 || that.maxScrollX >= 0 ? 0 : that.maxScrollX;
}
if (newY > that.minScrollY || newY < that.maxScrollY) {
newY = that.options.bounce ? that.y + (deltaY / 2) : newY >= that.minScrollY || that.maxScrollY >= 0 ? that.minScrollY : that.maxScrollY;
}
if (that.absDistX < 6 && that.absDistY < 6) {
that.distX += deltaX;
that.distY += deltaY;
that.absDistX = m.abs(that.distX);
that.absDistY = m.abs(that.distY);
return;
}
// Lock direction
if (that.options.lockDirection) {
if (that.absDistX > that.absDistY + 5) {
newY = that.y;
deltaY = 0;
} else if (that.absDistY > that.absDistX + 5) {
newX = that.x;
deltaX = 0;
}
}
that.moved = true;
that._pos(newX, newY);
that.dirX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
that.dirY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
if (timestamp - that.startTime > 300) {
that.startTime = timestamp;
that.startX = that.x;
that.startY = that.y;
}
if (that.options.onScrollMove) that.options.onScrollMove.call(that, e);
},
_end: function (e) {
if (hasTouch && e.touches.length != 0) return;
var that = this,
point = hasTouch ? e.changedTouches[0] : e,
target, ev,
momentumX = { dist:0, time:0 },
momentumY = { dist:0, time:0 },
duration = (e.timeStamp || (new Date()).getTime()) - that.startTime,
newPosX = that.x,
newPosY = that.y,
distX, distY,
newDuration,
snap,
scale;
that._unbind(MOVE_EV);
that._unbind(END_EV);
that._unbind(CANCEL_EV);
if (that.options.onBeforeScrollEnd) that.options.onBeforeScrollEnd.call(that, e);
if (that.zoomed) {
scale = that.scale * that.lastScale;
scale = Math.max(that.options.zoomMin, scale);
scale = Math.min(that.options.zoomMax, scale);
that.lastScale = scale / that.scale;
that.scale = scale;
that.x = that.originX - that.originX * that.lastScale + that.x;
that.y = that.originY - that.originY * that.lastScale + that.y;
that.scroller.style[vendor + 'TransitionDuration'] = '200ms';
that.scroller.style[vendor + 'Transform'] = trnOpen + that.x + 'px,' + that.y + 'px' + trnClose + ' scale(' + that.scale + ')';
that.zoomed = false;
that.refresh();
if (that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
return;
}
if (!that.moved) {
if (hasTouch) {
if (that.doubleTapTimer && that.options.zoom) {
// Double tapped
clearTimeout(that.doubleTapTimer);
that.doubleTapTimer = null;
if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.zoom(that.pointX, that.pointY, that.scale == 1 ? that.options.doubleTapZoom : 1);
if (that.options.onZoomEnd) {
setTimeout(function() {
that.options.onZoomEnd.call(that, e);
}, 200); // 200 is default zoom duration
}
} else {
that.doubleTapTimer = setTimeout(function () {
that.doubleTapTimer = null;
// Find the last touched element
target = point.target;
while (target.nodeType != 1) target = target.parentNode;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
ev = document.createEvent('MouseEvents');
ev.initMouseEvent('click', true, true, e.view, 1,
point.screenX, point.screenY, point.clientX, point.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
0, null);
ev._fake = true;
target.dispatchEvent(ev);
}
}, that.options.zoom ? 250 : 0);
}
}
that._resetPos(200);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
if (duration < 300 && that.options.momentum) {
momentumX = newPosX ? that._momentum(newPosX - that.startX, duration, -that.x, that.scrollerW - that.wrapperW + that.x, that.options.bounce ? that.wrapperW : 0) : momentumX;
momentumY = newPosY ? that._momentum(newPosY - that.startY, duration, -that.y, (that.maxScrollY < 0 ? that.scrollerH - that.wrapperH + that.y - that.minScrollY : 0), that.options.bounce ? that.wrapperH : 0) : momentumY;
newPosX = that.x + momentumX.dist;
newPosY = that.y + momentumY.dist;
if ((that.x > 0 && newPosX > 0) || (that.x < that.maxScrollX && newPosX < that.maxScrollX)) momentumX = { dist:0, time:0 };
if ((that.y > that.minScrollY && newPosY > that.minScrollY) || (that.y < that.maxScrollY && newPosY < that.maxScrollY)) momentumY = { dist:0, time:0 };
}
if (momentumX.dist || momentumY.dist) {
newDuration = m.max(m.max(momentumX.time, momentumY.time), 10);
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) { that.scrollTo(that.absStartX, that.absStartY, 200); }
else {
snap = that._snap(newPosX, newPosY);
newPosX = snap.x;
newPosY = snap.y;
newDuration = m.max(snap.time, newDuration);
}
}
that.scrollTo(newPosX, newPosY, newDuration);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
// Do we need to snap?
if (that.options.snap) {
distX = newPosX - that.absStartX;
distY = newPosY - that.absStartY;
if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) that.scrollTo(that.absStartX, that.absStartY, 200);
else {
snap = that._snap(that.x, that.y);
if (snap.x != that.x || snap.y != that.y) that.scrollTo(snap.x, snap.y, snap.time);
}
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
return;
}
that._resetPos(200);
if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
},
_resetPos: function (time) {
var that = this,
resetX = that.x >= 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x,
resetY = that.y >= that.minScrollY || that.maxScrollY > 0 ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
if (resetX == that.x && resetY == that.y) {
if (that.moved) {
that.moved = false;
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that); // Execute custom code on scroll end
}
/*
if (that.hScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.hScrollbarWrapper.style[vendor + 'TransitionDelay'] = '300ms';
that.hScrollbarWrapper.style.opacity = '0';
}
if (that.vScrollbar && that.options.hideScrollbar) {
if (vendor == 'webkit') that.vScrollbarWrapper.style[vendor + 'TransitionDelay'] = '300ms';
that.vScrollbarWrapper.style.opacity = '0';
}
*/
return;
}
that.scrollTo(resetX, resetY, time || 0);
},
_wheel: function (e) {
var that = this,
wheelDeltaX, wheelDeltaY,
deltaX, deltaY,
deltaScale;
if ('wheelDeltaX' in e) {
wheelDeltaX = e.wheelDeltaX / 12;
wheelDeltaY = e.wheelDeltaY / 12;
} else if ('detail' in e) {
wheelDeltaX = wheelDeltaY = -e.detail * 3;
} else {
wheelDeltaX = wheelDeltaY = -e.wheelDelta;
}
if (that.options.wheelAction == 'zoom') {
deltaScale = that.scale * Math.pow(2, 1/3 * (wheelDeltaY ? wheelDeltaY / Math.abs(wheelDeltaY) : 0));
if (deltaScale < that.options.zoomMin) deltaScale = that.options.zoomMin;
if (deltaScale > that.options.zoomMax) deltaScale = that.options.zoomMax;
if (deltaScale != that.scale) {
if (!that.wheelZoomCount && that.options.onZoomStart) that.options.onZoomStart.call(that, e);
that.wheelZoomCount++;
that.zoom(e.pageX, e.pageY, deltaScale, 400);
setTimeout(function() {
that.wheelZoomCount--;
if (!that.wheelZoomCount && that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
}, 400);
}
return;
}
deltaX = that.x + wheelDeltaX;
deltaY = that.y + wheelDeltaY;
if (deltaX > 0) deltaX = 0;
else if (deltaX < that.maxScrollX) deltaX = that.maxScrollX;
if (deltaY > that.minScrollY) deltaY = that.minScrollY;
else if (deltaY < that.maxScrollY) deltaY = that.maxScrollY;
that.scrollTo(deltaX, deltaY, 0);
},
_mouseout: function (e) {
var t = e.relatedTarget;
if (!t) {
this._end(e);
return;
}
while (t = t.parentNode) if (t == this.wrapper) return;
this._end(e);
},
_transitionEnd: function (e) {
var that = this;
if (e.target != that.scroller) return;
that._unbind('webkitTransitionEnd');
that._startAni();
},
/**
*
* Utilities
*
*/
_startAni: function () {
var that = this,
startX = that.x, startY = that.y,
startTime = (new Date).getTime(),
step, easeOut;
if (that.animating) return;
if (!that.steps.length) {
that._resetPos(400);
return;
}
step = that.steps.shift();
if (step.x == startX && step.y == startY) step.time = 0;
that.animating = true;
that.moved = true;
if (that.options.useTransition) {
that._transitionTime(step.time);
that._pos(step.x, step.y);
that.animating = false;
if (step.time) that._bind('webkitTransitionEnd');
else that._resetPos(0);
return;
}
(function animate () {
var now = (new Date).getTime(),
newX, newY;
if (now >= startTime + step.time) {
that._pos(step.x, step.y);
that.animating = false;
if (that.options.onAnimationEnd) that.options.onAnimationEnd.call(that); // Execute custom code on animation end
that._startAni();
return;
}
now = (now - startTime) / step.time - 1;
easeOut = m.sqrt(1 - now * now);
newX = (step.x - startX) * easeOut + startX;
newY = (step.y - startY) * easeOut + startY;
that._pos(newX, newY);
if (that.animating) that.aniTime = nextFrame(animate);
})();
},
_transitionTime: function (time) {
time += 'ms';
this.scroller.style[vendor + 'TransitionDuration'] = time;
if (this.hScrollbar) this.hScrollbarIndicator.style[vendor + 'TransitionDuration'] = time;
if (this.vScrollbar) this.vScrollbarIndicator.style[vendor + 'TransitionDuration'] = time;
},
_momentum: function (dist, time, maxDistUpper, maxDistLower, size) {
var deceleration = 0.0006,
speed = m.abs(dist) / time,
newDist = (speed * speed) / (2 * deceleration),
newTime = 0, outsideDist = 0;
// Proportinally reduce speed if we are outside of the boundaries
if (dist > 0 && newDist > maxDistUpper) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistUpper = maxDistUpper + outsideDist;
speed = speed * maxDistUpper / newDist;
newDist = maxDistUpper;
} else if (dist < 0 && newDist > maxDistLower) {
outsideDist = size / (6 / (newDist / speed * deceleration));
maxDistLower = maxDistLower + outsideDist;
speed = speed * maxDistLower / newDist;
newDist = maxDistLower;
}
newDist = newDist * (dist < 0 ? -1 : 1);
newTime = speed / deceleration;
return { dist: newDist, time: m.round(newTime) };
},
_offset: function (el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
if (el != this.wrapper) {
left *= this.scale;
top *= this.scale;
}
return { left: left, top: top };
},
_snap: function (x, y) {
var that = this,
i, l,
page, time,
sizeX, sizeY;
// Check page X
page = that.pagesX.length - 1;
for (i=0, l=that.pagesX.length; i<l; i++) {
if (x >= that.pagesX[i]) {
page = i;
break;
}
}
if (page == that.currPageX && page > 0 && that.dirX < 0) page--;
x = that.pagesX[page];
sizeX = m.abs(x - that.pagesX[that.currPageX]);
sizeX = sizeX ? m.abs(that.x - x) / sizeX * 500 : 0;
that.currPageX = page;
// Check page Y
page = that.pagesY.length-1;
for (i=0; i<page; i++) {
if (y >= that.pagesY[i]) {
page = i;
break;
}
}
if (page == that.currPageY && page > 0 && that.dirY < 0) page--;
y = that.pagesY[page];
sizeY = m.abs(y - that.pagesY[that.currPageY]);
sizeY = sizeY ? m.abs(that.y - y) / sizeY * 500 : 0;
that.currPageY = page;
// Snap with constant speed (proportional duration)
time = m.round(m.max(sizeX, sizeY)) || 200;
return { x: x, y: y, time: time };
},
_bind: function (type, el, bubble) {
(el || this.scroller).addEventListener(type, this, !!bubble);
},
_unbind: function (type, el, bubble) {
(el || this.scroller).removeEventListener(type, this, !!bubble);
},
/**
*
* Public methods
*
*/
destroy: function () {
var that = this;
that.scroller.style[vendor + 'Transform'] = '';
// Remove the scrollbars
that.hScrollbar = false;
that.vScrollbar = false;
that._scrollbar('h');
that._scrollbar('v');
// Remove the event listeners
that._unbind(RESIZE_EV, window);
that._unbind(START_EV);
that._unbind(MOVE_EV);
that._unbind(END_EV);
that._unbind(CANCEL_EV);
if (that.options.hasTouch) {
that._unbind('mouseout', that.wrapper);
that._unbind(WHEEL_EV);
}
if (that.options.useTransition) that._unbind('webkitTransitionEnd');
if (that.options.checkDOMChanges) clearInterval(that.checkDOMTime);
if (that.options.onDestroy) that.options.onDestroy.call(that);
},
refresh: function () {
var that = this,
offset,
i, l,
els,
pos = 0,
page = 0;
if (that.scale < that.options.zoomMin) that.scale = that.options.zoomMin;
that.wrapperW = that.wrapper.clientWidth || 1;
that.wrapperH = that.wrapper.clientHeight || 1;
that.minScrollY = -that.options.topOffset || 0;
that.scrollerW = m.round(that.scroller.offsetWidth * that.scale);
that.scrollerH = m.round((that.scroller.offsetHeight + that.minScrollY) * that.scale);
that.maxScrollX = that.wrapperW - that.scrollerW;
that.maxScrollY = that.wrapperH - that.scrollerH + that.minScrollY;
that.dirX = 0;
that.dirY = 0;
if (that.options.onRefresh) that.options.onRefresh.call(that);
that.hScroll = that.options.hScroll && that.maxScrollX < 0;
that.vScroll = that.options.vScroll && (!that.options.bounceLock && !that.hScroll || that.scrollerH > that.wrapperH);
that.hScrollbar = that.hScroll && that.options.hScrollbar;
that.vScrollbar = that.vScroll && that.options.vScrollbar && that.scrollerH > that.wrapperH;
offset = that._offset(that.wrapper);
that.wrapperOffsetLeft = -offset.left;
that.wrapperOffsetTop = -offset.top;
// Prepare snap
if (typeof that.options.snap == 'string') {
that.pagesX = [];
that.pagesY = [];
els = that.scroller.querySelectorAll(that.options.snap);
for (i=0, l=els.length; i<l; i++) {
pos = that._offset(els[i]);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
that.pagesX[i] = pos.left < that.maxScrollX ? that.maxScrollX : pos.left * that.scale;
that.pagesY[i] = pos.top < that.maxScrollY ? that.maxScrollY : pos.top * that.scale;
}
} else if (that.options.snap) {
that.pagesX = [];
while (pos >= that.maxScrollX) {
that.pagesX[page] = pos;
pos = pos - that.wrapperW;
page++;
}
if (that.maxScrollX%that.wrapperW) that.pagesX[that.pagesX.length] = that.maxScrollX - that.pagesX[that.pagesX.length-1] + that.pagesX[that.pagesX.length-1];
pos = 0;
page = 0;
that.pagesY = [];
while (pos >= that.maxScrollY) {
that.pagesY[page] = pos;
pos = pos - that.wrapperH;
page++;
}
if (that.maxScrollY%that.wrapperH) that.pagesY[that.pagesY.length] = that.maxScrollY - that.pagesY[that.pagesY.length-1] + that.pagesY[that.pagesY.length-1];
}
// Prepare the scrollbars
that._scrollbar('h');
that._scrollbar('v');
if (!that.zoomed) {
that.scroller.style[vendor + 'TransitionDuration'] = '0';
that._resetPos(200);
}
},
scrollTo: function (x, y, time, relative) {
var that = this,
step = x,
i, l;
that.stop();
if (!step.length) step = [{ x: x, y: y, time: time, relative: relative }];
for (i=0, l=step.length; i<l; i++) {
if (step[i].relative) { step[i].x = that.x - step[i].x; step[i].y = that.y - step[i].y; }
that.steps.push({ x: step[i].x, y: step[i].y, time: step[i].time || 0 });
}
that._startAni();
},
scrollToElement: function (el, time) {
var that = this, pos;
el = el.nodeType ? el : that.scroller.querySelector(el);
if (!el) return;
pos = that._offset(el);
pos.left += that.wrapperOffsetLeft;
pos.top += that.wrapperOffsetTop;
pos.left = pos.left > 0 ? 0 : pos.left < that.maxScrollX ? that.maxScrollX : pos.left;
pos.top = pos.top > that.minScrollY ? that.minScrollY : pos.top < that.maxScrollY ? that.maxScrollY : pos.top;
time = time === undefined ? m.max(m.abs(pos.left)*2, m.abs(pos.top)*2) : time;
// Added for scroll offset by Lissa
pos.left -= that.options.scrollOffsetLeft;
pos.top -= that.options.scrollOffsetTop;
that.scrollTo(pos.left, pos.top, time);
},
scrollToPage: function (pageX, pageY, time) {
var that = this, x, y;
if (that.options.snap) {
pageX = pageX == 'next' ? that.currPageX+1 : pageX == 'prev' ? that.currPageX-1 : pageX;
pageY = pageY == 'next' ? that.currPageY+1 : pageY == 'prev' ? that.currPageY-1 : pageY;
pageX = pageX < 0 ? 0 : pageX > that.pagesX.length-1 ? that.pagesX.length-1 : pageX;
pageY = pageY < 0 ? 0 : pageY > that.pagesY.length-1 ? that.pagesY.length-1 : pageY;
that.currPageX = pageX;
that.currPageY = pageY;
x = that.pagesX[pageX];
y = that.pagesY[pageY];
} else {
x = -that.wrapperW * pageX;
y = -that.wrapperH * pageY;
if (x < that.maxScrollX) x = that.maxScrollX;
if (y < that.maxScrollY) y = that.maxScrollY;
}
that.scrollTo(x, y, time || 400);
},
disable: function () {
this.stop();
this._resetPos(0);
this.enabled = false;
// If disabled after touchstart we make sure that there are no left over events
this._unbind(MOVE_EV);
this._unbind(END_EV);
this._unbind(CANCEL_EV);
},
enable: function () {
this.enabled = true;
},
stop: function () {
if (this.options.useTransition) this._unbind('webkitTransitionEnd');
else cancelFrame(this.aniTime);
this.steps = [];
this.moved = false;
this.animating = false;
},
zoom: function (x, y, scale, time) {
var that = this,
relScale = scale / that.scale;
if (!that.options.useTransform) return;
that.zoomed = true;
time = time === undefined ? 200 : time;
x = x - that.wrapperOffsetLeft - that.x;
y = y - that.wrapperOffsetTop - that.y;
that.x = x - x * relScale + that.x;
that.y = y - y * relScale + that.y;
that.scale = scale;
that.refresh();
that.x = that.x > 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x;
that.y = that.y > that.minScrollY ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
that.scroller.style[vendor + 'TransitionDuration'] = time + 'ms';
that.scroller.style[vendor + 'Transform'] = trnOpen + that.x + 'px,' + that.y + 'px' + trnClose + ' scale(' + scale + ')';
that.zoomed = false;
},
isReady: function () {
return !this.moved && !this.zoomed && !this.animating;
}
};
if (typeof exports !== 'undefined') exports.iScroll = iScroll;
else window.iScroll = iScroll;
})();
|
Java
|
<div class="header">
<i class="fa fa-angle-left" ng-click="previous()"></i>
<span>{{month.format("MMMM, YYYY")}}</span>
<i class="fa fa-angle-right" ng-click="next()"></i>
</div>
<div class="week">
<span class="day">Sun</span>
<span class="day">Mon</span>
<span class="day">Tue</span>
<span class="day">Wed</span>
<span class="day">Thu</span>
<span class="day">Fri</span>
<span class="day">Sat</span>
</div>
<div class="week" ng-repeat="week in weeks">
<span class="day" ng-class="{ today: day.isToday, 'different-month': !day.isCurrentMonth, selected: day.date.isSame(selected) }" ng-click="select(day)" ng-repeat="day in week.days">{{day.number}}</span>
</div>
|
Java
|
<?php
/**
* Part of the Fuel framework.
*
* @package Fuel
* @version 1.6
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2013 Fuel Development Team
* @link http://fuelphp.com
*/
namespace Fuel\Core;
/**
* The Arr class provides a few nice functions for making
* dealing with arrays easier
*
* @package Fuel
* @subpackage Core
*/
class Arr
{
/**
* Gets a dot-notated key from an array, with a default value if it does
* not exist.
*
* @param array $array The search array
* @param mixed $key The dot-notated key or array of keys
* @param string $default The default value
* @return mixed
*/
public static function get($array, $key, $default = null)
{
if ( ! is_array($array) and ! $array instanceof \ArrayAccess)
{
throw new \InvalidArgumentException('First parameter must be an array or ArrayAccess object.');
}
if (is_null($key))
{
return $array;
}
if (is_array($key))
{
$return = array();
foreach ($key as $k)
{
$return[$k] = static::get($array, $k, $default);
}
return $return;
}
foreach (explode('.', $key) as $key_part)
{
if (($array instanceof \ArrayAccess and isset($array[$key_part])) === false)
{
if ( ! is_array($array) or ! array_key_exists($key_part, $array))
{
return \Fuel::value($default);
}
}
$array = $array[$key_part];
}
return $array;
}
/**
* Set an array item (dot-notated) to the value.
*
* @param array $array The array to insert it into
* @param mixed $key The dot-notated key to set or array of keys
* @param mixed $value The value
* @return void
*/
public static function set(&$array, $key, $value = null)
{
if (is_null($key))
{
$array = $value;
return;
}
if (is_array($key))
{
foreach ($key as $k => $v)
{
static::set($array, $k, $v);
}
}
else
{
$keys = explode('.', $key);
while (count($keys) > 1)
{
$key = array_shift($keys);
if ( ! isset($array[$key]) or ! is_array($array[$key]))
{
$array[$key] = array();
}
$array =& $array[$key];
}
$array[array_shift($keys)] = $value;
}
}
/**
* Pluck an array of values from an array.
*
* @param array $array collection of arrays to pluck from
* @param string $key key of the value to pluck
* @param string $index optional return array index key, true for original index
* @return array array of plucked values
*/
public static function pluck($array, $key, $index = null)
{
$return = array();
$get_deep = strpos($key, '.') !== false;
if ( ! $index)
{
foreach ($array as $i => $a)
{
$return[] = (is_object($a) and ! ($a instanceof \ArrayAccess)) ? $a->{$key} :
($get_deep ? static::get($a, $key) : $a[$key]);
}
}
else
{
foreach ($array as $i => $a)
{
$index !== true and $i = (is_object($a) and ! ($a instanceof \ArrayAccess)) ? $a->{$index} : $a[$index];
$return[$i] = (is_object($a) and ! ($a instanceof \ArrayAccess)) ? $a->{$key} :
($get_deep ? static::get($a, $key) : $a[$key]);
}
}
return $return;
}
/**
* Array_key_exists with a dot-notated key from an array.
*
* @param array $array The search array
* @param mixed $key The dot-notated key or array of keys
* @return mixed
*/
public static function key_exists($array, $key)
{
foreach (explode('.', $key) as $key_part)
{
if ( ! is_array($array) or ! array_key_exists($key_part, $array))
{
return false;
}
$array = $array[$key_part];
}
return true;
}
/**
* Unsets dot-notated key from an array
*
* @param array $array The search array
* @param mixed $key The dot-notated key or array of keys
* @return mixed
*/
public static function delete(&$array, $key)
{
if (is_null($key))
{
return false;
}
if (is_array($key))
{
$return = array();
foreach ($key as $k)
{
$return[$k] = static::delete($array, $k);
}
return $return;
}
$key_parts = explode('.', $key);
if ( ! is_array($array) or ! array_key_exists($key_parts[0], $array))
{
return false;
}
$this_key = array_shift($key_parts);
if ( ! empty($key_parts))
{
$key = implode('.', $key_parts);
return static::delete($array[$this_key], $key);
}
else
{
unset($array[$this_key]);
}
return true;
}
/**
* Converts a multi-dimensional associative array into an array of key => values with the provided field names
*
* @param array $assoc the array to convert
* @param string $key_field the field name of the key field
* @param string $val_field the field name of the value field
* @return array
* @throws \InvalidArgumentException
*/
public static function assoc_to_keyval($assoc, $key_field, $val_field)
{
if ( ! is_array($assoc) and ! $assoc instanceof \Iterator)
{
throw new \InvalidArgumentException('The first parameter must be an array.');
}
$output = array();
foreach ($assoc as $row)
{
if (isset($row[$key_field]) and isset($row[$val_field]))
{
$output[$row[$key_field]] = $row[$val_field];
}
}
return $output;
}
/**
* Converts the given 1 dimensional non-associative array to an associative
* array.
*
* The array given must have an even number of elements or null will be returned.
*
* Arr::to_assoc(array('foo','bar'));
*
* @param string $arr the array to change
* @return array|null the new array or null
* @throws \BadMethodCallException
*/
public static function to_assoc($arr)
{
if (($count = count($arr)) % 2 > 0)
{
throw new \BadMethodCallException('Number of values in to_assoc must be even.');
}
$keys = $vals = array();
for ($i = 0; $i < $count - 1; $i += 2)
{
$keys[] = array_shift($arr);
$vals[] = array_shift($arr);
}
return array_combine($keys, $vals);
}
/**
* Checks if the given array is an assoc array.
*
* @param array $arr the array to check
* @return bool true if its an assoc array, false if not
*/
public static function is_assoc($arr)
{
if ( ! is_array($arr))
{
throw new \InvalidArgumentException('The parameter must be an array.');
}
$counter = 0;
foreach ($arr as $key => $unused)
{
if ( ! is_int($key) or $key !== $counter++)
{
return true;
}
}
return false;
}
/**
* Flattens a multi-dimensional associative array down into a 1 dimensional
* associative array.
*
* @param array the array to flatten
* @param string what to glue the keys together with
* @param bool whether to reset and start over on a new array
* @param bool whether to flatten only associative array's, or also indexed ones
* @return array
*/
public static function flatten($array, $glue = ':', $reset = true, $indexed = true)
{
static $return = array();
static $curr_key = array();
if ($reset)
{
$return = array();
$curr_key = array();
}
foreach ($array as $key => $val)
{
$curr_key[] = $key;
if (is_array($val) and ($indexed or array_values($val) !== $val))
{
static::flatten_assoc($val, $glue, false);
}
else
{
$return[implode($glue, $curr_key)] = $val;
}
array_pop($curr_key);
}
return $return;
}
/**
* Flattens a multi-dimensional associative array down into a 1 dimensional
* associative array.
*
* @param array the array to flatten
* @param string what to glue the keys together with
* @param bool whether to reset and start over on a new array
* @return array
*/
public static function flatten_assoc($array, $glue = ':', $reset = true)
{
return static::flatten($array, $glue, $reset, false);
}
/**
* Reverse a flattened array in its original form.
*
* @param array $array flattened array
* @param string $glue glue used in flattening
* @return array the unflattened array
*/
public static function reverse_flatten($array, $glue = ':')
{
$return = array();
foreach ($array as $key => $value)
{
if (stripos($key, $glue) !== false)
{
$keys = explode($glue, $key);
$temp =& $return;
while (count($keys) > 1)
{
$key = array_shift($keys);
$key = is_numeric($key) ? (int) $key : $key;
if ( ! isset($temp[$key]) or ! is_array($temp[$key]))
{
$temp[$key] = array();
}
$temp =& $temp[$key];
}
$key = array_shift($keys);
$key = is_numeric($key) ? (int) $key : $key;
$temp[$key] = $value;
}
else
{
$key = is_numeric($key) ? (int) $key : $key;
$return[$key] = $value;
}
}
return $return;
}
/**
* Filters an array on prefixed associative keys.
*
* @param array the array to filter.
* @param string prefix to filter on.
* @param bool whether to remove the prefix.
* @return array
*/
public static function filter_prefixed($array, $prefix, $remove_prefix = true)
{
$return = array();
foreach ($array as $key => $val)
{
if (preg_match('/^'.$prefix.'/', $key))
{
if ($remove_prefix === true)
{
$key = preg_replace('/^'.$prefix.'/','',$key);
}
$return[$key] = $val;
}
}
return $return;
}
/**
* Recursive version of PHP's array_filter()
*
* @param array the array to filter.
* @param callback the callback that determines whether or not a value is filtered
* @return array
*/
public static function filter_recursive($array, $callback = null)
{
foreach ($array as &$value)
{
if (is_array($value))
{
$value = $callback === null ? static::filter_recursive($value) : static::filter_recursive($value, $callback);
}
}
return $callback === null ? array_filter($array) : array_filter($array, $callback);
}
/**
* Removes items from an array that match a key prefix.
*
* @param array the array to remove from
* @param string prefix to filter on
* @return array
*/
public static function remove_prefixed($array, $prefix)
{
foreach ($array as $key => $val)
{
if (preg_match('/^'.$prefix.'/', $key))
{
unset($array[$key]);
}
}
return $array;
}
/**
* Filters an array on suffixed associative keys.
*
* @param array the array to filter.
* @param string suffix to filter on.
* @param bool whether to remove the suffix.
* @return array
*/
public static function filter_suffixed($array, $suffix, $remove_suffix = true)
{
$return = array();
foreach ($array as $key => $val)
{
if (preg_match('/'.$suffix.'$/', $key))
{
if ($remove_suffix === true)
{
$key = preg_replace('/'.$suffix.'$/','',$key);
}
$return[$key] = $val;
}
}
return $return;
}
/**
* Removes items from an array that match a key suffix.
*
* @param array the array to remove from
* @param string suffix to filter on
* @return array
*/
public static function remove_suffixed($array, $suffix)
{
foreach ($array as $key => $val)
{
if (preg_match('/'.$suffix.'$/', $key))
{
unset($array[$key]);
}
}
return $array;
}
/**
* Filters an array by an array of keys
*
* @param array the array to filter.
* @param array the keys to filter
* @param bool if true, removes the matched elements.
* @return array
*/
public static function filter_keys($array, $keys, $remove = false)
{
$return = array();
foreach ($keys as $key)
{
if (array_key_exists($key, $array))
{
$remove or $return[$key] = $array[$key];
if($remove)
{
unset($array[$key]);
}
}
}
return $remove ? $array : $return;
}
/**
* Insert value(s) into an array, mostly an array_splice alias
* WARNING: original array is edited by reference, only boolean success is returned
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param int the numeric position at which to insert, negative to count from the end backwards
* @return bool false when array shorter then $pos, otherwise true
*/
public static function insert(array &$original, $value, $pos)
{
if (count($original) < abs($pos))
{
\Error::notice('Position larger than number of elements in array in which to insert.');
return false;
}
array_splice($original, $pos, 0, $value);
return true;
}
/**
* Insert value(s) into an array, mostly an array_splice alias
* WARNING: original array is edited by reference, only boolean success is returned
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param int the numeric position at which to insert, negative to count from the end backwards
* @return bool false when array shorter then $pos, otherwise true
*/
public static function insert_assoc(array &$original, array $values, $pos)
{
if (count($original) < abs($pos))
{
return false;
}
$original = array_slice($original, 0, $pos, true) + $values + array_slice($original, $pos, null, true);
return true;
}
/**
* Insert value(s) into an array before a specific key
* WARNING: original array is edited by reference, only boolean success is returned
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param string|int the key before which to insert
* @param bool wether the input is an associative array
* @return bool false when key isn't found in the array, otherwise true
*/
public static function insert_before_key(array &$original, $value, $key, $is_assoc = false)
{
$pos = array_search($key, array_keys($original));
if ($pos === false)
{
\Error::notice('Unknown key before which to insert the new value into the array.');
return false;
}
return $is_assoc ? static::insert_assoc($original, $value, $pos) : static::insert($original, $value, $pos);
}
/**
* Insert value(s) into an array after a specific key
* WARNING: original array is edited by reference, only boolean success is returned
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param string|int the key after which to insert
* @param bool wether the input is an associative array
* @return bool false when key isn't found in the array, otherwise true
*/
public static function insert_after_key(array &$original, $value, $key, $is_assoc = false)
{
$pos = array_search($key, array_keys($original));
if ($pos === false)
{
\Error::notice('Unknown key after which to insert the new value into the array.');
return false;
}
return $is_assoc ? static::insert_assoc($original, $value, $pos + 1) : static::insert($original, $value, $pos + 1);
}
/**
* Insert value(s) into an array after a specific value (first found in array)
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param string|int the value after which to insert
* @param bool wether the input is an associative array
* @return bool false when value isn't found in the array, otherwise true
*/
public static function insert_after_value(array &$original, $value, $search, $is_assoc = false)
{
$key = array_search($search, $original);
if ($key === false)
{
\Error::notice('Unknown value after which to insert the new value into the array.');
return false;
}
return static::insert_after_key($original, $value, $key, $is_assoc);
}
/**
* Insert value(s) into an array before a specific value (first found in array)
*
* @param array the original array (by reference)
* @param array|mixed the value(s) to insert, if you want to insert an array it needs to be in an array itself
* @param string|int the value after which to insert
* @param bool wether the input is an associative array
* @return bool false when value isn't found in the array, otherwise true
*/
public static function insert_before_value(array &$original, $value, $search, $is_assoc = false)
{
$key = array_search($search, $original);
if ($key === false)
{
\Error::notice('Unknown value before which to insert the new value into the array.');
return false;
}
return static::insert_before_key($original, $value, $key, $is_assoc);
}
/**
* Sorts a multi-dimensional array by it's values.
*
* @access public
* @param array The array to fetch from
* @param string The key to sort by
* @param string The order (asc or desc)
* @param int The php sort type flag
* @return array
*/
public static function sort($array, $key, $order = 'asc', $sort_flags = SORT_REGULAR)
{
if ( ! is_array($array))
{
throw new \InvalidArgumentException('Arr::sort() - $array must be an array.');
}
if (empty($array))
{
return $array;
}
foreach ($array as $k => $v)
{
$b[$k] = static::get($v, $key);
}
switch ($order)
{
case 'asc':
asort($b, $sort_flags);
break;
case 'desc':
arsort($b, $sort_flags);
break;
default:
throw new \InvalidArgumentException('Arr::sort() - $order must be asc or desc.');
break;
}
foreach ($b as $key => $val)
{
$c[] = $array[$key];
}
return $c;
}
/**
* Sorts an array on multitiple values, with deep sorting support.
*
* @param array $array collection of arrays/objects to sort
* @param array $conditions sorting conditions
* @param bool @ignore_case wether to sort case insensitive
*/
public static function multisort($array, $conditions, $ignore_case = false)
{
$temp = array();
$keys = array_keys($conditions);
foreach($keys as $key)
{
$temp[$key] = static::pluck($array, $key, true);
is_array($conditions[$key]) or $conditions[$key] = array($conditions[$key]);
}
$args = array();
foreach ($keys as $key)
{
$args[] = $ignore_case ? array_map('strtolower', $temp[$key]) : $temp[$key];
foreach($conditions[$key] as $flag)
{
$args[] = $flag;
}
}
$args[] = &$array;
call_user_func_array('array_multisort', $args);
return $array;
}
/**
* Find the average of an array
*
* @param array the array containing the values
* @return numeric the average value
*/
public static function average($array)
{
// No arguments passed, lets not divide by 0
if ( ! ($count = count($array)) > 0)
{
return 0;
}
return (array_sum($array) / $count);
}
/**
* Replaces key names in an array by names in $replace
*
* @param array the array containing the key/value combinations
* @param array|string key to replace or array containing the replacement keys
* @param string the replacement key
* @return array the array with the new keys
*/
public static function replace_key($source, $replace, $new_key = null)
{
if(is_string($replace))
{
$replace = array($replace => $new_key);
}
if ( ! is_array($source) or ! is_array($replace))
{
throw new \InvalidArgumentException('Arr::replace_key() - $source must an array. $replace must be an array or string.');
}
$result = array();
foreach ($source as $key => $value)
{
if (array_key_exists($key, $replace))
{
$result[$replace[$key]] = $value;
}
else
{
$result[$key] = $value;
}
}
return $result;
}
/**
* Merge 2 arrays recursively, differs in 2 important ways from array_merge_recursive()
* - When there's 2 different values and not both arrays, the latter value overwrites the earlier
* instead of merging both into an array
* - Numeric keys that don't conflict aren't changed, only when a numeric key already exists is the
* value added using array_push()
*
* @param array multiple variables all of which must be arrays
* @return array
* @throws \InvalidArgumentException
*/
public static function merge()
{
$array = func_get_arg(0);
$arrays = array_slice(func_get_args(), 1);
if ( ! is_array($array))
{
throw new \InvalidArgumentException('Arr::merge() - all arguments must be arrays.');
}
foreach ($arrays as $arr)
{
if ( ! is_array($arr))
{
throw new \InvalidArgumentException('Arr::merge() - all arguments must be arrays.');
}
foreach ($arr as $k => $v)
{
// numeric keys are appended
if (is_int($k))
{
array_key_exists($k, $array) ? array_push($array, $v) : $array[$k] = $v;
}
elseif (is_array($v) and array_key_exists($k, $array) and is_array($array[$k]))
{
$array[$k] = static::merge($array[$k], $v);
}
else
{
$array[$k] = $v;
}
}
}
return $array;
}
/**
* Prepends a value with an asociative key to an array.
* Will overwrite if the value exists.
*
* @param array $arr the array to prepend to
* @param string|array $key the key or array of keys and values
* @param mixed $valye the value to prepend
*/
public static function prepend(&$arr, $key, $value = null)
{
$arr = (is_array($key) ? $key : array($key => $value)) + $arr;
}
/**
* Recursive in_array
*
* @param mixed $needle what to search for
* @param array $haystack array to search in
* @return bool wether the needle is found in the haystack.
*/
public static function in_array_recursive($needle, $haystack, $strict = false)
{
foreach ($haystack as $value)
{
if ( ! $strict and $needle == $value)
{
return true;
}
elseif ($needle === $value)
{
return true;
}
elseif (is_array($value) and static::in_array_recursive($needle, $value, $strict))
{
return true;
}
}
return false;
}
/**
* Checks if the given array is a multidimensional array.
*
* @param array $arr the array to check
* @param array $all_keys if true, check that all elements are arrays
* @return bool true if its a multidimensional array, false if not
*/
public static function is_multi($arr, $all_keys = false)
{
$values = array_filter($arr, 'is_array');
return $all_keys ? count($arr) === count($values) : count($values) > 0;
}
/**
* Searches the array for a given value and returns the
* corresponding key or default value.
* If $recursive is set to true, then the Arr::search()
* function will return a delimiter-notated key using $delimiter.
*
* @param array $array The search array
* @param mixed $value The searched value
* @param string $default The default value
* @param bool $recursive Whether to get keys recursive
* @param string $delimiter The delimiter, when $recursive is true
* @return mixed
*/
public static function search($array, $value, $default = null, $recursive = true, $delimiter = '.')
{
if ( ! is_array($array) and ! $array instanceof \ArrayAccess)
{
throw new \InvalidArgumentException('First parameter must be an array or ArrayAccess object.');
}
if ( ! is_null($default) and ! is_int($default) and ! is_string($default))
{
throw new \InvalidArgumentException('Expects parameter 3 to be an string or integer or null.');
}
if ( ! is_string($delimiter))
{
throw new \InvalidArgumentException('Expects parameter 5 must be an string.');
}
$key = array_search($value, $array);
if ($recursive and $key === false)
{
$keys = array();
foreach ($array as $k => $v)
{
if (is_array($v))
{
$rk = static::search($v, $value, $default, true, $delimiter);
if ($rk !== $default)
{
$keys = array($k, $rk);
break;
}
}
}
$key = count($keys) ? implode($delimiter, $keys) : false;
}
return $key === false ? $default : $key;
}
/**
* Returns only unique values in an array. It does not sort. First value is used.
*
* @param array $arr the array to dedup
* @return array array with only de-duped values
*/
public static function unique($arr)
{
// filter out all duplicate values
return array_filter($arr, function($item)
{
// contrary to popular belief, this is not as static as you think...
static $vars = array();
if (in_array($item, $vars, true))
{
// duplicate
return false;
}
else
{
// record we've had this value
$vars[] = $item;
// unique
return true;
}
});
}
/**
* Calculate the sum of an array
*
* @param array $array the array containing the values
* @param string $key key of the value to pluck
* @return numeric the sum value
*/
public static function sum($array, $key)
{
if ( ! is_array($array) and ! $array instanceof \ArrayAccess)
{
throw new \InvalidArgumentException('First parameter must be an array or ArrayAccess object.');
}
return array_sum(static::pluck($array, $key));
}
}
|
Java
|
<?php
/*
* Created by tpay.com.
* Date: 19.06.2017
* Time: 11:13
*/
namespace tpayLibs\src\_class_tpay\Validators\PaymentTypes;
use tpayLibs\src\_class_tpay\Validators\PaymentTypesInterface;
use tpayLibs\src\Dictionaries\Payments\CardFieldsDictionary;
class PaymentTypeCard implements PaymentTypesInterface
{
public function getRequestFields()
{
return CardFieldsDictionary::REQUEST_FIELDS;
}
public function getResponseFields()
{
return CardFieldsDictionary::RESPONSE_FIELDS;
}
}
|
Java
|
package de.hilling.maven.release.testprojects.versioninheritor;
public class App {
public static void main(String[] args) {
System.out.println("1 + 2 = 3");
}
}
|
Java
|
#pragma once
#include <stack>
#include <queue>
#include <vector>
class ExpressionParser {
public:
ExpressionParser(const std::string &expr);
~ExpressionParser();
double eval();
private:
struct token {
char c;
double d;
bool isNum;
bool isOp;
token() : c(0), isNum(false), isOp(true) {};
};
const std::string m_expr;
std::vector<token> tokens;
std::stack<token> m_opstack;
std::queue<token> m_revpol;
std::stack<double> m_output;
void tokenizeExpr();
void shuntingYard();
void evalRevPol();
};
|
Java
|
from __future__ import unicode_literals
import os
import os.path
import subprocess
from pre_commit.util import cmd_output
class PrefixedCommandRunner(object):
"""A PrefixedCommandRunner allows you to run subprocess commands with
comand substitution.
For instance:
PrefixedCommandRunner('/tmp/foo').run(['{prefix}foo.sh', 'bar', 'baz'])
will run ['/tmp/foo/foo.sh', 'bar', 'baz']
"""
def __init__(
self,
prefix_dir,
popen=subprocess.Popen,
makedirs=os.makedirs
):
self.prefix_dir = prefix_dir.rstrip(os.sep) + os.sep
self.__popen = popen
self.__makedirs = makedirs
def _create_path_if_not_exists(self):
if not os.path.exists(self.prefix_dir):
self.__makedirs(self.prefix_dir)
def run(self, cmd, **kwargs):
self._create_path_if_not_exists()
replaced_cmd = [
part.replace('{prefix}', self.prefix_dir) for part in cmd
]
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
def path(self, *parts):
path = os.path.join(self.prefix_dir, *parts)
return os.path.normpath(path)
def exists(self, *parts):
return os.path.exists(self.path(*parts))
@classmethod
def from_command_runner(cls, command_runner, path_end):
"""Constructs a new command runner from an existing one by appending
`path_end` to the command runner's prefix directory.
"""
return cls(
command_runner.path(path_end),
popen=command_runner.__popen,
makedirs=command_runner.__makedirs,
)
|
Java
|
pub use self::arp::ArpScheme;
pub use self::config::NetConfigScheme;
pub use self::ethernet::EthernetScheme;
pub use self::icmp::IcmpScheme;
pub use self::ip::IpScheme;
pub use self::tcp::TcpScheme;
pub use self::udp::UdpScheme;
pub mod arp;
pub mod config;
pub mod ethernet;
pub mod icmp;
pub mod ip;
pub mod tcp;
pub mod udp;
|
Java
|
class Child
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
belongs_to :parent, optional: true
end
|
Java
|
using System;
using System.Text;
using ECommon.Components;
using ECommon.Remoting;
using ECommon.Serializing;
using EQueue.Protocols;
using EQueue.Protocols.Brokers;
using EQueue.Protocols.Brokers.Requests;
using EQueue.Protocols.NameServers.Requests;
using EQueue.Utils;
namespace EQueue.NameServer.RequestHandlers
{
public class SetQueueConsumerVisibleForClusterRequestHandler : IRequestHandler
{
private NameServerController _nameServerController;
private IBinarySerializer _binarySerializer;
public SetQueueConsumerVisibleForClusterRequestHandler(NameServerController nameServerController)
{
_binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
_nameServerController = nameServerController;
}
public RemotingResponse HandleRequest(IRequestHandlerContext context, RemotingRequest remotingRequest)
{
var request = _binarySerializer.Deserialize<SetQueueConsumerVisibleForClusterRequest>(remotingRequest.Body);
var requestService = new BrokerRequestService(_nameServerController);
requestService.ExecuteActionToAllClusterBrokers(request.ClusterName, async remotingClient =>
{
var requestData = _binarySerializer.Serialize(new SetQueueConsumerVisibleRequest(request.Topic, request.QueueId, request.Visible));
var remotingResponse = await remotingClient.InvokeAsync(new RemotingRequest((int)BrokerRequestCode.SetQueueConsumerVisible, requestData), 30000);
context.SendRemotingResponse(remotingResponse);
});
return RemotingResponseFactory.CreateResponse(remotingRequest);
}
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.