code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import sublime, sublime_plugin, os class ExpandTabsOnSave(sublime_plugin.EventListener): def on_pre_save(self, view): if view.settings().get('expand_tabs_on_save') == 1: view.window().run_command('expand_tabs')
edonet/package
Edoner/expand_tabs_on_save.py
Python
isc
236
// Copyright 2012-2015 Apcera Inc. All rights reserved. package server import ( "bufio" "encoding/json" "fmt" "math/rand" "net" "sync" "sync/atomic" "time" "github.com/nats-io/gnatsd/hashmap" "github.com/nats-io/gnatsd/sublist" ) const ( // The size of the bufio reader/writer on top of the socket. defaultBufSize = 32768 // Scratch buffer size for the processMsg() calls. msgScratchSize = 512 msgHeadProto = "MSG " ) // Type of client const ( // CLIENT is an end user. CLIENT = iota // ROUTER is another router in the cluster. ROUTER ) type client struct { mu sync.Mutex typ int cid uint64 lang string opts clientOpts nc net.Conn mpay int ncs string bw *bufio.Writer srv *Server subs *hashmap.HashMap pcd map[*client]struct{} atmr *time.Timer ptmr *time.Timer pout int msgb [msgScratchSize]byte parseState stats route *route } func (c *client) String() (id string) { return c.ncs } func (c *client) GetOpts() *clientOpts { return &c.opts } type subscription struct { client *client subject []byte queue []byte sid []byte nm int64 max int64 } type clientOpts struct { Verbose bool `json:"verbose"` Pedantic bool `json:"pedantic"` SslRequired bool `json:"ssl_required"` Authorization string `json:"auth_token"` Username string `json:"user"` Password string `json:"pass"` Name string `json:"name"` Lang string `json:"lang"` Version string `json:"version"` } var defaultOpts = clientOpts{Verbose: true, Pedantic: true} func init() { rand.Seed(time.Now().UnixNano()) } // Lock should be held func (c *client) initClient() { s := c.srv c.cid = atomic.AddUint64(&s.gcid, 1) c.bw = bufio.NewWriterSize(c.nc, defaultBufSize) c.subs = hashmap.New() // This is a scratch buffer used for processMsg() // The msg header starts with "MSG ", // in bytes that is [77 83 71 32]. c.msgb = [msgScratchSize]byte{77, 83, 71, 32} // This is to track pending clients that have data to be flushed // after we process inbound msgs from our own connection. c.pcd = make(map[*client]struct{}) // snapshot the string version of the connection conn := "-" if ip, ok := c.nc.(*net.TCPConn); ok { addr := ip.RemoteAddr().(*net.TCPAddr) conn = fmt.Sprintf("%s:%d", addr.IP, addr.Port) } switch c.typ { case CLIENT: c.ncs = fmt.Sprintf("%s - cid:%d", conn, c.cid) case ROUTER: c.ncs = fmt.Sprintf("%s - rid:%d", conn, c.cid) } // No clue why, but this stalls and kills performance on Mac (Mavericks). // // if ip, ok := c.nc.(*net.TCPConn); ok { // ip.SetReadBuffer(defaultBufSize) // ip.SetWriteBuffer(2 * defaultBufSize) // } // Set the Ping timer c.setPingTimer() // Spin up the read loop. go c.readLoop() } func (c *client) readLoop() { // Grab the connection off the client, it will be cleared on a close. // We check for that after the loop, but want to avoid a nil dereference c.mu.Lock() nc := c.nc c.mu.Unlock() if nc == nil { return } b := make([]byte, defaultBufSize) for { n, err := nc.Read(b) if err != nil { c.closeConnection() return } if err := c.parse(b[:n]); err != nil { // handled inline if err != ErrMaxPayload && err != ErrAuthorization { c.Errorf("Error reading from client: %s", err.Error()) c.sendErr("Parser Error") c.closeConnection() } return } // Check pending clients for flush. for cp := range c.pcd { // Flush those in the set cp.mu.Lock() if cp.nc != nil { cp.nc.SetWriteDeadline(time.Now().Add(DEFAULT_FLUSH_DEADLINE)) err := cp.bw.Flush() cp.nc.SetWriteDeadline(time.Time{}) if err != nil { c.Debugf("Error flushing: %v", err) cp.mu.Unlock() cp.closeConnection() cp.mu.Lock() } } cp.mu.Unlock() delete(c.pcd, cp) } // Check to see if we got closed, e.g. slow consumer c.mu.Lock() nc := c.nc c.mu.Unlock() if nc == nil { return } } } func (c *client) traceMsg(msg []byte) { if trace == 0 { return } // FIXME(dlc), allow limits to printable payload c.Tracef("->> MSG_PAYLOAD: [%s]", string(msg[:len(msg)-LEN_CR_LF])) } func (c *client) traceInOp(op string, arg []byte) { c.traceOp("->> %s", op, arg) } func (c *client) traceOutOp(op string, arg []byte) { c.traceOp("<<- %s", op, arg) } func (c *client) traceOp(format, op string, arg []byte) { if trace == 0 { return } opa := []interface{}{} if op != "" { opa = append(opa, op) } if arg != nil { opa = append(opa, string(arg)) } c.Tracef(format, opa) } // Process the info message if we are a route. func (c *client) processRouteInfo(info *Info) { c.mu.Lock() if c.route == nil { c.mu.Unlock() return } c.route.remoteID = info.ID // Check to see if we have this remote already registered. // This can happen when both servers have routes to each other. s := c.srv c.mu.Unlock() if s.addRoute(c) { c.Debugf("Registering remote route %q", info.ID) // Send our local subscriptions to this route. s.sendLocalSubsToRoute(c) } else { c.Debugf("Detected duplicate remote route %q", info.ID) c.closeConnection() } } // Process the information messages from Clients and other routes. func (c *client) processInfo(arg []byte) error { info := Info{} if err := json.Unmarshal(arg, &info); err != nil { return err } if c.typ == ROUTER { c.processRouteInfo(&info) } return nil } func (c *client) processErr(errStr string) { c.Errorf("Client error %s", errStr) c.closeConnection() } func (c *client) processConnect(arg []byte) error { c.traceInOp("CONNECT", arg) // This will be resolved regardless before we exit this func, // so we can just clear it here. c.clearAuthTimer() if err := json.Unmarshal(arg, &c.opts); err != nil { return err } if c.srv != nil { // Check for Auth if ok := c.srv.checkAuth(c); !ok { c.authViolation() return ErrAuthorization } } // Grab connection name of remote route. if c.typ == ROUTER && c.route != nil { c.route.remoteID = c.opts.Name } if c.opts.Verbose { c.sendOK() } return nil } func (c *client) authTimeout() { c.sendErr("Authorization Timeout") c.closeConnection() } func (c *client) authViolation() { c.Errorf(ErrAuthorization.Error()) c.sendErr("Authorization Violation") c.closeConnection() } func (c *client) maxPayloadViolation(sz int) { c.Errorf("%s: %d vs %d", ErrMaxPayload.Error(), sz, c.mpay) c.sendErr("Maximum Payload Violation") c.closeConnection() } func (c *client) sendErr(err string) { c.mu.Lock() if c.bw != nil { c.bw.WriteString(fmt.Sprintf("-ERR '%s'\r\n", err)) c.pcd[c] = needFlush } c.mu.Unlock() } func (c *client) sendOK() { c.mu.Lock() c.bw.WriteString("+OK\r\n") c.pcd[c] = needFlush c.mu.Unlock() } func (c *client) processPing() { c.traceInOp("PING", nil) if c.nc == nil { return } c.traceOutOp("PONG", nil) c.mu.Lock() c.bw.WriteString("PONG\r\n") err := c.bw.Flush() if err != nil { c.clearConnection() c.Debugf("Error on Flush, error %s", err.Error()) } c.mu.Unlock() } func (c *client) processPong() { c.traceInOp("PONG", nil) c.mu.Lock() c.pout -= 1 c.mu.Unlock() } func (c *client) processMsgArgs(arg []byte) error { if trace == 1 { c.traceInOp("MSG", arg) } // Unroll splitArgs to avoid runtime/heap issues a := [MAX_MSG_ARGS][]byte{} args := a[:0] start := -1 for i, b := range arg { switch b { case ' ', '\t', '\r', '\n': if start >= 0 { args = append(args, arg[start:i]) start = -1 } default: if start < 0 { start = i } } } if start >= 0 { args = append(args, arg[start:]) } c.pa.subject = args[0] c.pa.sid = args[1] switch len(args) { case 3: c.pa.reply = nil c.pa.szb = args[2] c.pa.size = parseSize(args[2]) case 4: c.pa.reply = args[2] c.pa.szb = args[3] c.pa.size = parseSize(args[3]) default: return fmt.Errorf("processMsgArgs Parse Error: '%s'", arg) } if c.pa.size < 0 { return fmt.Errorf("processMsgArgs Bad or Missing Size: '%s'", arg) } return nil } func (c *client) processPub(arg []byte) error { if trace == 1 { c.traceInOp("PUB", arg) } // Unroll splitArgs to avoid runtime/heap issues a := [MAX_PUB_ARGS][]byte{} args := a[:0] start := -1 for i, b := range arg { switch b { case ' ', '\t', '\r', '\n': if start >= 0 { args = append(args, arg[start:i]) start = -1 } default: if start < 0 { start = i } } } if start >= 0 { args = append(args, arg[start:]) } switch len(args) { case 2: c.pa.subject = args[0] c.pa.reply = nil c.pa.size = parseSize(args[1]) c.pa.szb = args[1] case 3: c.pa.subject = args[0] c.pa.reply = args[1] c.pa.size = parseSize(args[2]) c.pa.szb = args[2] default: return fmt.Errorf("processPub Parse Error: '%s'", arg) } if c.pa.size < 0 { return fmt.Errorf("processPub Bad or Missing Size: '%s'", arg) } if c.mpay > 0 && c.pa.size > c.mpay { c.maxPayloadViolation(c.pa.size) return ErrMaxPayload } if c.opts.Pedantic && !sublist.IsValidLiteralSubject(c.pa.subject) { c.sendErr("Invalid Subject") } return nil } func splitArg(arg []byte) [][]byte { a := [MAX_MSG_ARGS][]byte{} args := a[:0] start := -1 for i, b := range arg { switch b { case ' ', '\t', '\r', '\n': if start >= 0 { args = append(args, arg[start:i]) start = -1 } default: if start < 0 { start = i } } } if start >= 0 { args = append(args, arg[start:]) } return args } func (c *client) processSub(argo []byte) (err error) { c.traceInOp("SUB", argo) // Copy so we do not reference a potentially large buffer arg := make([]byte, len(argo)) copy(arg, argo) args := splitArg(arg) sub := &subscription{client: c} switch len(args) { case 2: sub.subject = args[0] sub.queue = nil sub.sid = args[1] case 3: sub.subject = args[0] sub.queue = args[1] sub.sid = args[2] default: return fmt.Errorf("processSub Parse Error: '%s'", arg) } c.mu.Lock() if c.nc == nil { c.mu.Unlock() return nil } c.subs.Set(sub.sid, sub) if c.srv != nil { err = c.srv.sl.Insert(sub.subject, sub) } shouldForward := c.typ != ROUTER && c.srv != nil c.mu.Unlock() if err != nil { c.sendErr("Invalid Subject") } else if c.opts.Verbose { c.sendOK() } if shouldForward { c.srv.broadcastSubscribe(sub) } return nil } func (c *client) unsubscribe(sub *subscription) { c.mu.Lock() defer c.mu.Unlock() if sub.max > 0 && sub.nm < sub.max { c.Debugf( "Deferring actual UNSUB(%s): %d max, %d received\n", string(sub.subject), sub.max, sub.nm) return } c.traceOp("<-> %s", "DELSUB", sub.sid) c.subs.Remove(sub.sid) if c.srv != nil { c.srv.sl.Remove(sub.subject, sub) } } func (c *client) processUnsub(arg []byte) error { c.traceInOp("UNSUB", arg) args := splitArg(arg) var sid []byte max := -1 switch len(args) { case 1: sid = args[0] case 2: sid = args[0] max = parseSize(args[1]) default: return fmt.Errorf("processUnsub Parse Error: '%s'", arg) } if sub, ok := (c.subs.Get(sid)).(*subscription); ok { if max > 0 { sub.max = int64(max) } else { // Clear it here to override sub.max = 0 } c.unsubscribe(sub) if shouldForward := c.typ != ROUTER && c.srv != nil; shouldForward { c.srv.broadcastUnSubscribe(sub) } } if c.opts.Verbose { c.sendOK() } return nil } func (c *client) msgHeader(mh []byte, sub *subscription) []byte { mh = append(mh, sub.sid...) mh = append(mh, ' ') if c.pa.reply != nil { mh = append(mh, c.pa.reply...) mh = append(mh, ' ') } mh = append(mh, c.pa.szb...) mh = append(mh, "\r\n"...) return mh } // Used to treat maps as efficient set var needFlush = struct{}{} var routeSeen = struct{}{} func (c *client) deliverMsg(sub *subscription, mh, msg []byte) { if sub.client == nil { return } client := sub.client client.mu.Lock() sub.nm++ // Check if we should auto-unsubscribe. if sub.max > 0 { // For routing.. shouldForward := client.typ != ROUTER && client.srv != nil // If we are at the exact number, unsubscribe but // still process the message in hand, otherwise // unsubscribe and drop message on the floor. if sub.nm == sub.max { c.Debugf("Auto-unsubscribe limit of %d reached for sid '%s'\n", sub.max, string(sub.sid)) defer client.unsubscribe(sub) if shouldForward { defer client.srv.broadcastUnSubscribe(sub) } } else if sub.nm > sub.max { c.Debugf("Auto-unsubscribe limit [%d] exceeded\n", sub.max) client.mu.Unlock() client.unsubscribe(sub) if shouldForward { client.srv.broadcastUnSubscribe(sub) } return } } if client.nc == nil { client.mu.Unlock() return } // Update statistics // The msg includes the CR_LF, so pull back out for accounting. msgSize := int64(len(msg) - LEN_CR_LF) client.outMsgs++ client.outBytes += msgSize atomic.AddInt64(&c.srv.outMsgs, 1) atomic.AddInt64(&c.srv.outBytes, msgSize) // Check to see if our writes will cause a flush // in the underlying bufio. If so limit time we // will wait for flush to complete. deadlineSet := false if client.bw.Available() < (len(mh) + len(msg) + len(CR_LF)) { client.nc.SetWriteDeadline(time.Now().Add(DEFAULT_FLUSH_DEADLINE)) deadlineSet = true } // Deliver to the client. _, err := client.bw.Write(mh) if err != nil { goto writeErr } _, err = client.bw.Write(msg) if err != nil { goto writeErr } if trace == 1 { client.traceOutOp(string(mh[:len(mh)-LEN_CR_LF]), nil) } // TODO(dlc) - Do we need this or can we just call always? if deadlineSet { client.nc.SetWriteDeadline(time.Time{}) } client.mu.Unlock() c.pcd[client] = needFlush return writeErr: if deadlineSet { client.nc.SetWriteDeadline(time.Time{}) } client.mu.Unlock() if ne, ok := err.(net.Error); ok && ne.Timeout() { atomic.AddInt64(&client.srv.slowConsumers, 1) client.Noticef("Slow Consumer Detected") client.closeConnection() } else { c.Debugf("Error writing msg: %v", err) } } // processMsg is called to process an inbound msg from a client. func (c *client) processMsg(msg []byte) { // Update statistics // The msg includes the CR_LF, so pull back out for accounting. msgSize := int64(len(msg) - LEN_CR_LF) c.inMsgs++ c.inBytes += msgSize // Snapshot server. srv := c.srv if srv != nil { atomic.AddInt64(&srv.inMsgs, 1) atomic.AddInt64(&srv.inBytes, msgSize) } if trace == 1 { c.traceMsg(msg) } if c.opts.Verbose { c.sendOK() } if srv == nil { return } r := srv.sl.Match(c.pa.subject) if len(r) <= 0 { return } // Scratch buffer.. msgh := c.msgb[:len(msgHeadProto)] // msg header msgh = append(msgh, c.pa.subject...) msgh = append(msgh, ' ') si := len(msgh) var qmap map[string][]*subscription var qsubs []*subscription isRoute := c.typ == ROUTER var rmap map[string]struct{} // If we are a route and we have a queue subscription, deliver direct // since they are sent direct via L2 semantics. If the match is a queue // subscription, we will return from here regardless if we find a sub. if isRoute { if sub, ok := srv.routeSidQueueSubscriber(c.pa.sid); ok { if sub != nil { mh := c.msgHeader(msgh[:si], sub) c.deliverMsg(sub, mh, msg) } return } } // Loop over all subscriptions that match. for _, v := range r { sub := v.(*subscription) // Process queue group subscriptions by gathering them all up // here. We will pick the winners when we are done processing // all of the subscriptions. if sub.queue != nil { // Queue subscriptions handled from routes directly above. if isRoute { continue } // FIXME(dlc), this can be more efficient if qmap == nil { qmap = make(map[string][]*subscription) } qname := string(sub.queue) qsubs = qmap[qname] if qsubs == nil { qsubs = make([]*subscription, 0, 4) } qsubs = append(qsubs, sub) qmap[qname] = qsubs continue } // Process normal, non-queue group subscriptions. // If this is a send to a ROUTER, make sure we only send it // once. The other side will handle the appropriate re-processing. // Also enforce 1-Hop. if sub.client.typ == ROUTER { // Skip if sourced from a ROUTER and going to another ROUTER. // This is 1-Hop semantics for ROUTERs. if isRoute { continue } // Check to see if we have already sent it here. if rmap == nil { rmap = make(map[string]struct{}, srv.numRoutes()) } sub.client.mu.Lock() if sub.client.nc == nil || sub.client.route == nil || sub.client.route.remoteID == "" { c.Debugf("Bad or Missing ROUTER Identity, not processing msg") sub.client.mu.Unlock() continue } if _, ok := rmap[sub.client.route.remoteID]; ok { c.Debugf("Ignoring route, already processed") sub.client.mu.Unlock() continue } rmap[sub.client.route.remoteID] = routeSeen sub.client.mu.Unlock() } mh := c.msgHeader(msgh[:si], sub) c.deliverMsg(sub, mh, msg) } if qmap != nil { for _, qsubs := range qmap { index := rand.Int() % len(qsubs) sub := qsubs[index] mh := c.msgHeader(msgh[:si], sub) c.deliverMsg(sub, mh, msg) } } } func (c *client) processPingTimer() { c.mu.Lock() defer c.mu.Unlock() c.ptmr = nil // Check if we are ready yet.. if _, ok := c.nc.(*net.TCPConn); !ok { return } c.Debugf("%s Ping Timer", c.typeString()) // Check for violation c.pout += 1 if c.pout > c.srv.opts.MaxPingsOut { c.Debugf("Stale Client Connection - Closing") if c.bw != nil { c.bw.WriteString(fmt.Sprintf("-ERR '%s'\r\n", "Stale Connection")) c.bw.Flush() } c.clearConnection() return } c.traceOutOp("PING", nil) // Send PING c.bw.WriteString("PING\r\n") err := c.bw.Flush() if err != nil { c.Debugf("Error on Client Ping Flush, error %s", err) c.clearConnection() } else { // Reset to fire again if all OK. c.setPingTimer() } } func (c *client) setPingTimer() { if c.srv == nil { return } d := c.srv.opts.PingInterval c.ptmr = time.AfterFunc(d, c.processPingTimer) } // Lock should be held func (c *client) clearPingTimer() { if c.ptmr == nil { return } c.ptmr.Stop() c.ptmr = nil } // Lock should be held func (c *client) setAuthTimer(d time.Duration) { c.atmr = time.AfterFunc(d, func() { c.authTimeout() }) } // Lock should be held func (c *client) clearAuthTimer() { if c.atmr == nil { return } c.atmr.Stop() c.atmr = nil } func (c *client) isAuthTimerSet() bool { c.mu.Lock() isSet := c.atmr != nil c.mu.Unlock() return isSet } // Lock should be held func (c *client) clearConnection() { if c.nc == nil { return } c.bw.Flush() c.nc.Close() } func (c *client) typeString() string { switch c.typ { case CLIENT: return "Client" case ROUTER: return "Router" } return "Unknown Type" } func (c *client) closeConnection() { c.mu.Lock() if c.nc == nil { c.mu.Unlock() return } c.Debugf("%s connection closed", c.typeString()) c.clearAuthTimer() c.clearPingTimer() c.clearConnection() c.nc = nil // Snapshot for use. subs := c.subs.All() srv := c.srv c.mu.Unlock() if srv != nil { // Unregister srv.removeClient(c) // Remove clients subscriptions. for _, s := range subs { if sub, ok := s.(*subscription); ok { srv.sl.Remove(sub.subject, sub) // Forward on unsubscribes if we are not // a router ourselves. if c.typ != ROUTER { srv.broadcastUnSubscribe(sub) } } } } // Check for a solicited route. If it was, start up a reconnect unless // we are already connected to the other end. if c.isSolicitedRoute() { srv.mu.Lock() defer srv.mu.Unlock() rid := c.route.remoteID if rid != "" && srv.remotes[rid] != nil { Debugf("Not attempting reconnect for solicited route, already connected to \"%s\"", rid) return } else { Debugf("Attempting reconnect for solicited route \"%s\"", c.route.url) go srv.reConnectToRoute(c.route.url) } } } // Logging functionality scoped to a client or route. func (c *client) Errorf(format string, v ...interface{}) { format = fmt.Sprintf("%s - %s", c, format) Errorf(format, v...) } func (c *client) Debugf(format string, v ...interface{}) { format = fmt.Sprintf("%s - %s", c, format) Debugf(format, v...) } func (c *client) Noticef(format string, v ...interface{}) { format = fmt.Sprintf("%s - %s", c, format) Noticef(format, v...) } func (c *client) Tracef(format string, v ...interface{}) { format = fmt.Sprintf("%s - %s", c, format) Tracef(format, v...) }
dockbiz/gnatsd
server/client.go
GO
mit
20,486
/** */ package gluemodel.CIM.IEC61970.impl; import gluemodel.CIM.IEC61970.IEC61970CIMVersion; import gluemodel.CIM.IEC61970.IEC61970Package; import gluemodel.CIM.impl.ElementImpl; import java.util.Date; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>CIM Version</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link gluemodel.CIM.IEC61970.impl.IEC61970CIMVersionImpl#getDate <em>Date</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.impl.IEC61970CIMVersionImpl#getVersion <em>Version</em>}</li> * </ul> * * @generated */ public class IEC61970CIMVersionImpl extends ElementImpl implements IEC61970CIMVersion { /** * The default value of the '{@link #getDate() <em>Date</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDate() * @generated * @ordered */ protected static final Date DATE_EDEFAULT = null; /** * The cached value of the '{@link #getDate() <em>Date</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDate() * @generated * @ordered */ protected Date date = DATE_EDEFAULT; /** * The default value of the '{@link #getVersion() <em>Version</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVersion() * @generated * @ordered */ protected static final String VERSION_EDEFAULT = null; /** * The cached value of the '{@link #getVersion() <em>Version</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVersion() * @generated * @ordered */ protected String version = VERSION_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IEC61970CIMVersionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return IEC61970Package.Literals.IEC61970_CIM_VERSION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Date getDate() { return date; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDate(Date newDate) { Date oldDate = date; date = newDate; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, IEC61970Package.IEC61970_CIM_VERSION__DATE, oldDate, date)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getVersion() { return version; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setVersion(String newVersion) { String oldVersion = version; version = newVersion; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, IEC61970Package.IEC61970_CIM_VERSION__VERSION, oldVersion, version)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case IEC61970Package.IEC61970_CIM_VERSION__DATE: return getDate(); case IEC61970Package.IEC61970_CIM_VERSION__VERSION: return getVersion(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case IEC61970Package.IEC61970_CIM_VERSION__DATE: setDate((Date)newValue); return; case IEC61970Package.IEC61970_CIM_VERSION__VERSION: setVersion((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case IEC61970Package.IEC61970_CIM_VERSION__DATE: setDate(DATE_EDEFAULT); return; case IEC61970Package.IEC61970_CIM_VERSION__VERSION: setVersion(VERSION_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case IEC61970Package.IEC61970_CIM_VERSION__DATE: return DATE_EDEFAULT == null ? date != null : !DATE_EDEFAULT.equals(date); case IEC61970Package.IEC61970_CIM_VERSION__VERSION: return VERSION_EDEFAULT == null ? version != null : !VERSION_EDEFAULT.equals(version); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (date: "); result.append(date); result.append(", version: "); result.append(version); result.append(')'); return result.toString(); } } //IEC61970CIMVersionImpl
georghinkel/ttc2017smartGrids
solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/impl/IEC61970CIMVersionImpl.java
Java
mit
5,104
<?php /** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup Protean Protean template * @ingroup UnaModules * * @{ */ $aConfig = array( /** * Main Section. */ 'type' => BX_DOL_MODULE_TYPE_TEMPLATE, 'name' => 'bx_protean', 'title' => 'Protean', 'note' => 'Design template', 'version' => '9.0.10', 'vendor' => 'Boonex', 'help_url' => 'http://feed.una.io/?section={module_name}', 'compatible_with' => array( '9.0.0-RC10' ), /** * 'home_dir' and 'home_uri' - should be unique. Don't use spaces in 'home_uri' and the other special chars. */ 'home_dir' => 'boonex/protean/', 'home_uri' => 'protean', 'db_prefix' => 'bx_protean_', 'class_prefix' => 'BxProtean', /** * Category for language keys. */ 'language_category' => 'Boonex Protean Template', /** * Installation/Uninstallation Section. */ 'install' => array( 'execute_sql' => 1, 'update_languages' => 1, 'clear_db_cache' => 1 ), 'uninstall' => array ( 'execute_sql' => 1, 'update_languages' => 1, 'clear_db_cache' => 1 ), 'enable' => array( 'execute_sql' => 1 ), 'disable' => array( 'execute_sql' => 1 ), /** * Dependencies Section */ 'dependencies' => array(), ); /** @} */
unaio/una
modules/boonex/protean/updates/9.0.9_9.0.10/source/install/config.php
PHP
mit
1,429
CodeMirror.ternLint = function(cm, updateLinting, options) { function addAnnotation(error, found) { var startLine = error.startLine; var startChar = error.startChar; var endLine = error.endLine; var endChar = error.endChar; var message = error.message; found.push({ from : error.start, to : error.end, message : message }); } var getServer = (typeof options.server == "function") ? options.server : function(cm) {return options.server}; var query = { type : "lint", file : "#0", lineCharPositions : true }; var files = []; files.push({ type : "full", name : "[doc]", text : cm.getValue() }); var doc = { query : query, files : files }; getServer(cm).server.request(doc, function(error, response) { if (error) { updateLinting(cm, []); } else { var messages = response.messages; updateLinting(cm, messages); } }); };
daniel-lundin/tern-snabbt
demos/resources/tern-lint/codemirror/addon/lint/tern-lint.js
JavaScript
mit
952
import { D2ManifestDefinitions } from 'app/destiny2/d2-definitions'; import { PluggableInventoryItemDefinition } from 'app/inventory/item-types'; import { startWordRegexp } from './search-filters/freeform'; export function createPlugSearchPredicate( query: string, language: string, defs: D2ManifestDefinitions ) { if (!query.length) { return (_plug: PluggableInventoryItemDefinition) => true; } const regexp = startWordRegexp(query, language); return (plug: PluggableInventoryItemDefinition) => regexp.test(plug.displayProperties.name) || regexp.test(plug.displayProperties.description) || regexp.test(plug.itemTypeDisplayName) || plug.perks.some((perk) => { const perkDef = defs.SandboxPerk.get(perk.perkHash); return ( perkDef && (regexp.test(perkDef.displayProperties.name) || regexp.test(perkDef.displayProperties.description) || regexp.test(perk.requirementDisplayString)) ); }); }
DestinyItemManager/DIM
src/app/search/plug-search.ts
TypeScript
mit
982
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {animate, animation, AnimationMetadata, AnimationMetadataType, AnimationOptions, AUTO_STYLE, group, keyframes, query, sequence, state, style, transition, trigger, useAnimation, ɵStyleDataMap} from '@angular/animations'; import {Animation} from '../../src/dsl/animation'; import {buildAnimationAst} from '../../src/dsl/animation_ast_builder'; import {AnimationTimelineInstruction} from '../../src/dsl/animation_timeline_instruction'; import {ElementInstructionMap} from '../../src/dsl/element_instruction_map'; import {MockAnimationDriver} from '../../testing'; function createDiv() { return document.createElement('div'); } { describe('Animation', () => { // these tests are only meant to be run within the DOM (for now) if (isNode) return; let rootElement: any; let subElement1: any; let subElement2: any; beforeEach(() => { rootElement = createDiv(); subElement1 = createDiv(); subElement2 = createDiv(); document.body.appendChild(rootElement); rootElement.appendChild(subElement1); rootElement.appendChild(subElement2); }); afterEach(() => { document.body.removeChild(rootElement); }); describe('validation', () => { it('should throw an error if one or more but not all keyframes() styles contain offsets', () => { const steps = animate(1000, keyframes([ style({opacity: 0}), style({opacity: 1, offset: 1}), ])); expect(() => { validateAndThrowAnimationSequence(steps); }) .toThrowError( /Not all style\(\) steps within the declared keyframes\(\) contain offsets/); }); it('should throw an error if not all offsets are between 0 and 1', () => { let steps = animate(1000, keyframes([ style({opacity: 0, offset: -1}), style({opacity: 1, offset: 1}), ])); expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/Please ensure that all keyframe offsets are between 0 and 1/); steps = animate(1000, keyframes([ style({opacity: 0, offset: 0}), style({opacity: 1, offset: 1.1}), ])); expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/Please ensure that all keyframe offsets are between 0 and 1/); }); it('should throw an error if a smaller offset shows up after a bigger one', () => { let steps = animate(1000, keyframes([ style({opacity: 0, offset: 1}), style({opacity: 1, offset: 0}), ])); expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/Please ensure that all keyframe offsets are in order/); }); it('should throw an error if any styles overlap during parallel animations', () => { const steps = group([ sequence([ // 0 -> 2000ms style({opacity: 0}), animate('500ms', style({opacity: .25})), animate('500ms', style({opacity: .5})), animate('500ms', style({opacity: .75})), animate('500ms', style({opacity: 1})) ]), animate('1s 500ms', keyframes([ // 0 -> 1500ms style({width: 0}), style({opacity: 1, width: 1000}), ])) ]); expect(() => { validateAndThrowAnimationSequence(steps); }) .toThrowError( /The CSS property "opacity" that exists between the times of "0ms" and "2000ms" is also being animated in a parallel animation between the times of "0ms" and "1500ms"/); }); it('should not throw an error if animations overlap in different query levels within different transitions', () => { const steps = trigger('myAnimation', [ transition('a => b', group([ query('h1', animate('1s', style({opacity: 0}))), query('h2', animate('1s', style({opacity: 1}))), ])), transition('b => a', group([ query('h1', animate('1s', style({opacity: 0}))), query('h2', animate('1s', style({opacity: 1}))), ])), ]); expect(() => validateAndThrowAnimationSequence(steps)).not.toThrow(); }); it('should not allow triggers to be defined with a prefixed `@` symbol', () => { const steps = trigger('@foo', []); expect(() => validateAndThrowAnimationSequence(steps)) .toThrowError( /animation triggers cannot be prefixed with an `@` sign \(e\.g\. trigger\('@foo', \[...\]\)\)/); }); it('should throw an error if an animation time is invalid', () => { const steps = [animate('500xs', style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/The provided timing value "500xs" is invalid/); const steps2 = [animate('500ms 500ms 500ms ease-out', style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps2); }).toThrowError(/The provided timing value "500ms 500ms 500ms ease-out" is invalid/); }); it('should throw if negative durations are used', () => { const steps = [animate(-1000, style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/Duration values below 0 are not allowed for this animation step/); const steps2 = [animate('-1s', style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps2); }).toThrowError(/Duration values below 0 are not allowed for this animation step/); }); it('should throw if negative delays are used', () => { const steps = [animate('1s -500ms', style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/Delay values below 0 are not allowed for this animation step/); const steps2 = [animate('1s -0.5s', style({opacity: 1}))]; expect(() => { validateAndThrowAnimationSequence(steps2); }).toThrowError(/Delay values below 0 are not allowed for this animation step/); }); it('should throw if keyframes() is not used inside of animate()', () => { const steps = [keyframes([])]; expect(() => { validateAndThrowAnimationSequence(steps); }).toThrowError(/keyframes\(\) must be placed inside of a call to animate\(\)/); const steps2 = [group([keyframes([])])]; expect(() => { validateAndThrowAnimationSequence(steps2); }).toThrowError(/keyframes\(\) must be placed inside of a call to animate\(\)/); }); it('should throw if dynamic style substitutions are used without defaults within state() definitions', () => { const steps = [ state('final', style({ 'width': '{{ one }}px', 'borderRadius': '{{ two }}px {{ three }}px', })), ]; expect(() => { validateAndThrowAnimationSequence(steps); }) .toThrowError( /state\("final", ...\) must define default values for all the following style substitutions: one, two, three/); const steps2 = [state( 'panfinal', style({ 'color': '{{ greyColor }}', 'borderColor': '1px solid {{ greyColor }}', 'backgroundColor': '{{ redColor }}', }), {params: {redColor: 'maroon'}})]; expect(() => { validateAndThrowAnimationSequence(steps2); }) .toThrowError( /state\("panfinal", ...\) must define default values for all the following style substitutions: greyColor/); }); it('should throw an error if an invalid CSS property is used in the animation', () => { const steps = [animate(1000, style({abc: '500px'}))]; expect(() => { validateAndThrowAnimationSequence(steps); }) .toThrowError( /The provided animation property "abc" is not a supported CSS property for animations/); }); it('should allow a vendor-prefixed property to be used in an animation sequence without throwing an error', () => { const steps = [ style({webkitTransform: 'translateX(0px)'}), animate(1000, style({webkitTransform: 'translateX(100px)'})) ]; expect(() => validateAndThrowAnimationSequence(steps)).not.toThrow(); }); it('should allow for old CSS properties (like transform) to be auto-prefixed by webkit', () => { const steps = [ style({transform: 'translateX(-100px)'}), animate(1000, style({transform: 'translateX(500px)'})) ]; expect(() => validateAndThrowAnimationSequence(steps)).not.toThrow(); }); }); describe('keyframe building', () => { describe('style() / animate()', () => { it('should produce a balanced series of keyframes given a sequence of animate steps', () => { const steps = [ style({width: 0}), animate(1000, style({height: 50})), animate(1000, style({width: 100})), animate(1000, style({height: 150})), animate(1000, style({width: 200})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players[0].keyframes).toEqual([ new Map<string, string|number>( [['height', AUTO_STYLE], ['width', 0], ['offset', 0]]), new Map<string, string|number>([['height', 50], ['width', 0], ['offset', .25]]), new Map<string, string|number>([['height', 50], ['width', 100], ['offset', .5]]), new Map<string, string|number>([['height', 150], ['width', 100], ['offset', .75]]), new Map<string, string|number>([['height', 150], ['width', 200], ['offset', 1]]), ]); }); it('should fill in missing starting steps when a starting `style()` value is not used', () => { const steps = [animate(1000, style({width: 999}))]; const players = invokeAnimationSequence(rootElement, steps); expect(players[0].keyframes).toEqual([ new Map<string, string|number>([['width', AUTO_STYLE], ['offset', 0]]), new Map<string, string|number>([['width', 999], ['offset', 1]]), ]); }); it('should merge successive style() calls together before an animate() call', () => { const steps = [ style({width: 0}), style({height: 0}), style({width: 200}), style({opacity: 0}), animate(1000, style({width: 100, height: 400, opacity: 1})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players[0].keyframes).toEqual([ new Map<string, string|number>( [['width', 200], ['height', 0], ['opacity', 0], ['offset', 0]]), new Map<string, string|number>( [['width', 100], ['height', 400], ['opacity', 1], ['offset', 1]]) ]); }); it('should not merge in successive style() calls to the previous animate() keyframe', () => { const steps = [ style({opacity: 0}), animate(1000, style({opacity: .5})), style({opacity: .6}), animate(1000, style({opacity: 1})) ]; const players = invokeAnimationSequence(rootElement, steps); const keyframes = humanizeOffsets(players[0].keyframes, 4); expect(keyframes).toEqual([ new Map<string, string|number>([['opacity', 0], ['offset', 0]]), new Map<string, string|number>([['opacity', .5], ['offset', .4998]]), new Map<string, string|number>([['opacity', .6], ['offset', .5002]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]), ]); }); it('should support an easing value that uses cubic-bezier(...)', () => { const steps = [ style({opacity: 0}), animate('1s cubic-bezier(.29, .55 ,.53 ,1.53)', style({opacity: 1})) ]; const player = invokeAnimationSequence(rootElement, steps)[0]; const firstKeyframe = player.keyframes[0]; const firstKeyframeEasing = firstKeyframe.get('easing') as string; expect(firstKeyframeEasing.replace(/\s+/g, '')).toEqual('cubic-bezier(.29,.55,.53,1.53)'); }); }); describe('sequence()', () => { it('should not produce extra timelines when multiple sequences are used within each other', () => { const steps = [ style({width: 0}), animate(1000, style({width: 100})), sequence([ animate(1000, style({width: 200})), sequence([ animate(1000, style({width: 300})), ]), ]), animate(1000, style({width: 400})), sequence([ animate(1000, style({width: 500})), ]), ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const player = players[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['width', 0], ['offset', 0]]), new Map<string, string|number>([['width', 100], ['offset', .2]]), new Map<string, string|number>([['width', 200], ['offset', .4]]), new Map<string, string|number>([['width', 300], ['offset', .6]]), new Map<string, string|number>([['width', 400], ['offset', .8]]), new Map<string, string|number>([['width', 500], ['offset', 1]]) ]); }); it('should create a new timeline after a sequence if group() or keyframe() commands are used within', () => { const steps = [ style({width: 100, height: 100}), animate(1000, style({width: 150, height: 150})), sequence([ group([ animate(1000, style({height: 200})), ]), animate(1000, keyframes([style({width: 180}), style({width: 200})])) ]), animate(1000, style({width: 500, height: 500})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(4); const finalPlayer = players[players.length - 1]; expect(finalPlayer.keyframes).toEqual([ new Map<string, string|number>([['width', 200], ['height', 200], ['offset', 0]]), new Map<string, string|number>([['width', 500], ['height', 500], ['offset', 1]]) ]); }); it('should push the start of a sequence if a delay option is provided', () => { const steps = [ style({width: '0px'}), animate(1000, style({width: '100px'})), sequence( [ animate(1000, style({width: '200px'})), ], {delay: 500}) ]; const players = invokeAnimationSequence(rootElement, steps); const finalPlayer = players[players.length - 1]; expect(finalPlayer.keyframes).toEqual([ new Map<string, string|number>([['width', '100px'], ['offset', 0]]), new Map<string, string|number>([['width', '200px'], ['offset', 1]]), ]); expect(finalPlayer.delay).toEqual(1500); }); it('should allow a float-based delay value to be used', () => { let steps: any[] = [ animate('.75s 0.75s', style({width: '300px'})), ]; let players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); let p1 = players.pop()!; expect(p1.duration).toEqual(1500); expect(p1.keyframes).toEqual([ new Map<string, string|number>([['width', '*'], ['offset', 0]]), new Map<string, string|number>([['width', '*'], ['offset', 0.5]]), new Map<string, string|number>([['width', '300px'], ['offset', 1]]), ]); steps = [ style({width: '100px'}), animate('.5s .5s', style({width: '200px'})), ]; players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); p1 = players.pop()!; expect(p1.duration).toEqual(1000); expect(p1.keyframes).toEqual([ new Map<string, string|number>([['width', '100px'], ['offset', 0]]), new Map<string, string|number>([['width', '100px'], ['offset', 0.5]]), new Map<string, string|number>([['width', '200px'], ['offset', 1]]), ]); }); }); describe('substitutions', () => { it('should allow params to be substituted even if they are not defaulted in a reusable animation', () => { const myAnimation = animation([ style({left: '{{ start }}'}), animate(1000, style({left: '{{ end }}'})), ]); const steps = [ useAnimation(myAnimation, {params: {start: '0px', end: '100px'}}), ]; const players = invokeAnimationSequence(rootElement, steps, {}); expect(players.length).toEqual(1); const player = players[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['left', '0px'], ['offset', 0]]), new Map<string, string|number>([['left', '100px'], ['offset', 1]]), ]); }); it('should substitute in timing values', () => { function makeAnimation(exp: string, options: {[key: string]: any}) { const steps = [style({opacity: 0}), animate(exp, style({opacity: 1}))]; return invokeAnimationSequence(rootElement, steps, options); } let players = makeAnimation('{{ duration }}', buildParams({duration: '1234ms'})); expect(players[0].duration).toEqual(1234); players = makeAnimation('{{ duration }}', buildParams({duration: '9s 2s'})); expect(players[0].duration).toEqual(11000); players = makeAnimation('{{ duration }} 1s', buildParams({duration: '1.5s'})); expect(players[0].duration).toEqual(2500); players = makeAnimation( '{{ duration }} {{ delay }}', buildParams({duration: '1s', delay: '2s'})); expect(players[0].duration).toEqual(3000); }); it('should allow multiple substitutions to occur within the same style value', () => { const steps = [ style({borderRadius: '100px 100px'}), animate(1000, style({borderRadius: '{{ one }}px {{ two }}'})), ]; const players = invokeAnimationSequence(rootElement, steps, buildParams({one: '200', two: '400px'})); expect(players[0].keyframes).toEqual([ new Map<string, string|number>([['offset', 0], ['borderRadius', '100px 100px']]), new Map<string, string|number>([['offset', 1], ['borderRadius', '200px 400px']]) ]); }); it('should substitute in values that are defined as parameters for inner areas of a sequence', () => { const steps = sequence( [ sequence( [ sequence( [ style({height: '{{ x0 }}px'}), animate(1000, style({height: '{{ x2 }}px'})), ], buildParams({x2: '{{ x1 }}3'})), ], buildParams({x1: '{{ x0 }}2'})), ], buildParams({x0: '1'})); const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const [player] = players; expect(player.keyframes).toEqual([ new Map<string, string|number>([['offset', 0], ['height', '1px']]), new Map<string, string|number>([['offset', 1], ['height', '123px']]) ]); }); it('should substitute in values that are defined as parameters for reusable animations', () => { const anim = animation([ style({height: '{{ start }}'}), animate(1000, style({height: '{{ end }}'})), ]); const steps = sequence( [ sequence( [ useAnimation(anim, buildParams({start: '{{ a }}', end: '{{ b }}'})), ], buildParams({a: '100px', b: '200px'})), ], buildParams({a: '0px'})); const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const [player] = players; expect(player.keyframes).toEqual([ new Map<string, string|number>([['offset', 0], ['height', '100px']]), new Map<string, string|number>([['offset', 1], ['height', '200px']]), ]); }); it('should throw an error when an input variable is not provided when invoked and is not a default value', () => { expect(() => invokeAnimationSequence(rootElement, [style({color: '{{ color }}'})])) .toThrowError(/Please provide a value for the animation param color/); expect( () => invokeAnimationSequence( rootElement, [ style({color: '{{ start }}'}), animate('{{ time }}', style({color: '{{ end }}'})), ], buildParams({start: 'blue', end: 'red'}))) .toThrowError(/Please provide a value for the animation param time/); }); }); describe('keyframes()', () => { it('should produce a sub timeline when `keyframes()` is used within a sequence', () => { const steps = [ animate(1000, style({opacity: .5})), animate(1000, style({opacity: 1})), animate( 1000, keyframes([style({height: 0}), style({height: 100}), style({height: 50})])), animate(1000, style({height: 0, opacity: 0})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(3); const player0 = players[0]; expect(player0.delay).toEqual(0); expect(player0.keyframes).toEqual([ new Map<string, string|number>([['opacity', AUTO_STYLE], ['offset', 0]]), new Map<string, string|number>([['opacity', .5], ['offset', .5]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]), ]); const subPlayer = players[1]; expect(subPlayer.delay).toEqual(2000); expect(subPlayer.keyframes).toEqual([ new Map<string, string|number>([['height', 0], ['offset', 0]]), new Map<string, string|number>([['height', 100], ['offset', .5]]), new Map<string, string|number>([['height', 50], ['offset', 1]]), ]); const player1 = players[2]; expect(player1.delay).toEqual(3000); expect(player1.keyframes).toEqual([ new Map<string, string|number>([['opacity', 1], ['height', 50], ['offset', 0]]), new Map<string, string|number>([['opacity', 0], ['height', 0], ['offset', 1]]) ]); }); it('should propagate inner keyframe style data to the parent timeline if used afterwards', () => { const steps = [ style({opacity: 0}), animate(1000, style({opacity: .5})), animate(1000, style({opacity: 1})), animate(1000, keyframes([ style({color: 'red'}), style({color: 'blue'}), ])), animate(1000, style({color: 'green', opacity: 0})) ]; const players = invokeAnimationSequence(rootElement, steps); const finalPlayer = players[players.length - 1]; expect(finalPlayer.keyframes).toEqual([ new Map<string, string|number>([['opacity', 1], ['color', 'blue'], ['offset', 0]]), new Map<string, string|number>([['opacity', 0], ['color', 'green'], ['offset', 1]]) ]); }); it('should feed in starting data into inner keyframes if used in an style step beforehand', () => { const steps = [ animate(1000, style({opacity: .5})), animate(1000, keyframes([ style({opacity: .8, offset: .5}), style({opacity: 1, offset: 1}), ])) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(2); const topPlayer = players[0]; expect(topPlayer.keyframes).toEqual([ new Map<string, string|number>([['opacity', AUTO_STYLE], ['offset', 0]]), new Map<string, string|number>([['opacity', .5], ['offset', 1]]) ]); const subPlayer = players[1]; expect(subPlayer.keyframes).toEqual([ new Map<string, string|number>([['opacity', .5], ['offset', 0]]), new Map<string, string|number>([['opacity', .8], ['offset', 0.5]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]) ]); }); it('should set the easing value as an easing value for the entire timeline', () => { const steps = [ style({opacity: 0}), animate(1000, style({opacity: .5})), animate( '1s ease-out', keyframes([style({opacity: .8, offset: .5}), style({opacity: 1, offset: 1})])) ]; const player = invokeAnimationSequence(rootElement, steps)[1]; expect(player.easing).toEqual('ease-out'); }); it('should combine the starting time + the given delay as the delay value for the animated keyframes', () => { const steps = [ style({opacity: 0}), animate(500, style({opacity: .5})), animate( '1s 2s ease-out', keyframes([style({opacity: .8, offset: .5}), style({opacity: 1, offset: 1})])) ]; const player = invokeAnimationSequence(rootElement, steps)[1]; expect(player.delay).toEqual(2500); }); it('should not leak in additional styles used later on after keyframe styles have already been declared', () => { const steps = [ animate(1000, style({height: '50px'})), animate(2000, keyframes([ style({left: '0', top: '0', offset: 0}), style({left: '40%', top: '50%', offset: .33}), style({left: '60%', top: '80%', offset: .66}), style({left: 'calc(100% - 100px)', top: '100%', offset: 1}), ])), group([animate('2s', style({width: '200px'}))]), animate('2s', style({height: '300px'})), group([animate('2s', style({height: '500px', width: '500px'}))]) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(5); const firstPlayerKeyframes = players[0].keyframes; expect(firstPlayerKeyframes[0].get('width')).toBeFalsy(); expect(firstPlayerKeyframes[1].get('width')).toBeFalsy(); expect(firstPlayerKeyframes[0].get('height')).toEqual(AUTO_STYLE); expect(firstPlayerKeyframes[1].get('height')).toEqual('50px'); const keyframePlayerKeyframes = players[1].keyframes; expect(keyframePlayerKeyframes[0].get('width')).toBeFalsy(); expect(keyframePlayerKeyframes[0].get('height')).toBeFalsy(); const groupPlayerKeyframes = players[2].keyframes; expect(groupPlayerKeyframes[0].get('width')).toEqual(AUTO_STYLE); expect(groupPlayerKeyframes[1].get('width')).toEqual('200px'); expect(groupPlayerKeyframes[0].get('height')).toBeFalsy(); expect(groupPlayerKeyframes[1].get('height')).toBeFalsy(); const secondToFinalAnimatePlayerKeyframes = players[3].keyframes; expect(secondToFinalAnimatePlayerKeyframes[0].get('width')).toBeFalsy(); expect(secondToFinalAnimatePlayerKeyframes[1].get('width')).toBeFalsy(); expect(secondToFinalAnimatePlayerKeyframes[0].get('height')).toEqual('50px'); expect(secondToFinalAnimatePlayerKeyframes[1].get('height')).toEqual('300px'); const finalAnimatePlayerKeyframes = players[4].keyframes; expect(finalAnimatePlayerKeyframes[0].get('width')).toEqual('200px'); expect(finalAnimatePlayerKeyframes[1].get('width')).toEqual('500px'); expect(finalAnimatePlayerKeyframes[0].get('height')).toEqual('300px'); expect(finalAnimatePlayerKeyframes[1].get('height')).toEqual('500px'); }); it('should respect offsets if provided directly within the style data', () => { const steps = animate(1000, keyframes([ style({opacity: 0, offset: 0}), style({opacity: .6, offset: .6}), style({opacity: 1, offset: 1}) ])); const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const player = players[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['opacity', 0], ['offset', 0]]), new Map<string, string|number>([['opacity', .6], ['offset', .6]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]), ]); }); it('should respect offsets if provided directly within the style metadata type', () => { const steps = animate(1000, keyframes([ {type: AnimationMetadataType.Style, offset: 0, styles: {opacity: 0}}, {type: AnimationMetadataType.Style, offset: .4, styles: {opacity: .4}}, {type: AnimationMetadataType.Style, offset: 1, styles: {opacity: 1}}, ])); const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const player = players[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['opacity', 0], ['offset', 0]]), new Map<string, string|number>([['opacity', .4], ['offset', .4]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]), ]); }); }); describe('group()', () => { it('should properly tally style data within a group() for use in a follow-up animate() step', () => { const steps = [ style({width: 0, height: 0}), animate(1000, style({width: 20, height: 50})), group([animate('1s 1s', style({width: 200})), animate('1s', style({height: 500}))]), animate(1000, style({width: 1000, height: 1000})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(4); const player0 = players[0]; expect(player0.duration).toEqual(1000); expect(player0.keyframes).toEqual([ new Map<string, string|number>([['width', 0], ['height', 0], ['offset', 0]]), new Map<string, string|number>([['width', 20], ['height', 50], ['offset', 1]]) ]); const gPlayer1 = players[1]; expect(gPlayer1.duration).toEqual(2000); expect(gPlayer1.delay).toEqual(1000); expect(gPlayer1.keyframes).toEqual([ new Map<string, string|number>([['width', 20], ['offset', 0]]), new Map<string, string|number>([['width', 20], ['offset', .5]]), new Map<string, string|number>([['width', 200], ['offset', 1]]) ]); const gPlayer2 = players[2]; expect(gPlayer2.duration).toEqual(1000); expect(gPlayer2.delay).toEqual(1000); expect(gPlayer2.keyframes).toEqual([ new Map<string, string|number>([['height', 50], ['offset', 0]]), new Map<string, string|number>([['height', 500], ['offset', 1]]) ]); const player1 = players[3]; expect(player1.duration).toEqual(1000); expect(player1.delay).toEqual(3000); expect(player1.keyframes).toEqual([ new Map<string, string|number>([['width', 200], ['height', 500], ['offset', 0]]), new Map<string, string|number>([['width', 1000], ['height', 1000], ['offset', 1]]) ]); }); it('should support groups with nested sequences', () => { const steps = [group([ sequence([ style({opacity: 0}), animate(1000, style({opacity: 1})), ]), sequence([ style({width: 0}), animate(1000, style({width: 200})), ]) ])]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(2); const gPlayer1 = players[0]; expect(gPlayer1.delay).toEqual(0); expect(gPlayer1.keyframes).toEqual([ new Map<string, string|number>([['opacity', 0], ['offset', 0]]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]), ]); const gPlayer2 = players[1]; expect(gPlayer1.delay).toEqual(0); expect(gPlayer2.keyframes).toEqual([ new Map<string, string|number>([['width', 0], ['offset', 0]]), new Map<string, string|number>([['width', 200], ['offset', 1]]) ]); }); it('should respect delays after group entries', () => { const steps = [ style({width: 0, height: 0}), animate(1000, style({width: 50, height: 50})), group([ animate(1000, style({width: 100})), animate(1000, style({height: 100})), ]), animate('1s 1s', style({height: 200, width: 200})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(4); const finalPlayer = players[players.length - 1]; expect(finalPlayer.delay).toEqual(2000); expect(finalPlayer.duration).toEqual(2000); expect(finalPlayer.keyframes).toEqual([ new Map<string, string|number>([['width', 100], ['height', 100], ['offset', 0]]), new Map<string, string|number>([['width', 100], ['height', 100], ['offset', .5]]), new Map<string, string|number>([['width', 200], ['height', 200], ['offset', 1]]), ]); }); it('should respect delays after multiple calls to group()', () => { const steps = [ group([animate('2s', style({opacity: 1})), animate('2s', style({width: '100px'}))]), animate(2000, style({width: 0, opacity: 0})), group([animate('2s', style({opacity: 1})), animate('2s', style({width: '200px'}))]), animate(2000, style({width: 0, opacity: 0})) ]; const players = invokeAnimationSequence(rootElement, steps); const middlePlayer = players[2]; expect(middlePlayer.delay).toEqual(2000); expect(middlePlayer.duration).toEqual(2000); const finalPlayer = players[players.length - 1]; expect(finalPlayer.delay).toEqual(6000); expect(finalPlayer.duration).toEqual(2000); }); it('should push the start of a group if a delay option is provided', () => { const steps = [ style({width: '0px', height: '0px'}), animate(1500, style({width: '100px', height: '100px'})), group( [ animate(1000, style({width: '200px'})), animate(2000, style({height: '200px'})), ], {delay: 300}) ]; const players = invokeAnimationSequence(rootElement, steps); const finalWidthPlayer = players[players.length - 2]; const finalHeightPlayer = players[players.length - 1]; expect(finalWidthPlayer.delay).toEqual(1800); expect(finalWidthPlayer.keyframes).toEqual([ new Map<string, string|number>([['width', '100px'], ['offset', 0]]), new Map<string, string|number>([['width', '200px'], ['offset', 1]]), ]); expect(finalHeightPlayer.delay).toEqual(1800); expect(finalHeightPlayer.keyframes).toEqual([ new Map<string, string|number>([['height', '100px'], ['offset', 0]]), new Map<string, string|number>([['height', '200px'], ['offset', 1]]), ]); }); }); describe('query()', () => { it('should delay the query operation if a delay option is provided', () => { const steps = [ style({opacity: 0}), animate(1000, style({opacity: 1})), query( 'div', [ style({width: 0}), animate(500, style({width: 200})), ], {delay: 200}) ]; const players = invokeAnimationSequence(rootElement, steps); const finalPlayer = players[players.length - 1]; expect(finalPlayer.delay).toEqual(1200); }); it('should throw an error when an animation query returns zero elements', () => { const steps = [query('somethingFake', [style({opacity: 0}), animate(1000, style({opacity: 1}))])]; expect(() => { invokeAnimationSequence(rootElement, steps); }) .toThrowError( /`query\("somethingFake"\)` returned zero elements\. \(Use `query\("somethingFake", \{ optional: true \}\)` if you wish to allow this\.\)/); }); it('should allow a query to be skipped if it is set as optional and returns zero elements', () => { const steps = [query( 'somethingFake', [style({opacity: 0}), animate(1000, style({opacity: 1}))], {optional: true})]; expect(() => { invokeAnimationSequence(rootElement, steps); }).not.toThrow(); const steps2 = [query( 'fakeSomethings', [style({opacity: 0}), animate(1000, style({opacity: 1}))], {optional: true})]; expect(() => { invokeAnimationSequence(rootElement, steps2); }).not.toThrow(); }); it('should delay the query operation if a delay option is provided', () => { const steps = [ style({opacity: 0}), animate(1300, style({opacity: 1})), query( 'div', [ style({width: 0}), animate(500, style({width: 200})), ], {delay: 300}) ]; const players = invokeAnimationSequence(rootElement, steps); const fp1 = players[players.length - 2]; const fp2 = players[players.length - 1]; expect(fp1.delay).toEqual(1600); expect(fp2.delay).toEqual(1600); }); }); describe('timing values', () => { it('should properly combine an easing value with a delay into a set of three keyframes', () => { const steps: AnimationMetadata[] = [style({opacity: 0}), animate('3s 1s ease-out', style({opacity: 1}))]; const player = invokeAnimationSequence(rootElement, steps)[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['opacity', 0], ['offset', 0]]), new Map<string, string|number>( [['opacity', 0], ['offset', .25], ['easing', 'ease-out']]), new Map<string, string|number>([['opacity', 1], ['offset', 1]]) ]); }); it('should allow easing values to exist for each animate() step', () => { const steps: AnimationMetadata[] = [ style({width: 0}), animate('1s linear', style({width: 10})), animate('2s ease-out', style({width: 20})), animate('1s ease-in', style({width: 30})) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players.length).toEqual(1); const player = players[0]; expect(player.keyframes).toEqual([ new Map<string, string|number>([['width', 0], ['offset', 0], ['easing', 'linear']]), new Map<string, string|number>( [['width', 10], ['offset', .25], ['easing', 'ease-out']]), new Map<string, string|number>([['width', 20], ['offset', .75], ['easing', 'ease-in']]), new Map<string, string|number>([['width', 30], ['offset', 1]]) ]); }); it('should produce a top-level timeline only for the duration that is set as before a group kicks in', () => { const steps: AnimationMetadata[] = [ style({width: 0, height: 0, opacity: 0}), animate('1s', style({width: 100, height: 100, opacity: .2})), group([ animate('500ms 1s', style({width: 500})), animate('1s', style({height: 500})), sequence([ animate(500, style({opacity: .5})), animate(500, style({opacity: .6})), animate(500, style({opacity: .7})), animate(500, style({opacity: 1})), ]) ]) ]; const player = invokeAnimationSequence(rootElement, steps)[0]; expect(player.duration).toEqual(1000); expect(player.delay).toEqual(0); }); it('should offset group() and keyframe() timelines with a delay which is the current time of the previous player when called', () => { const steps: AnimationMetadata[] = [ style({width: 0, height: 0}), animate('1500ms linear', style({width: 10, height: 10})), group([ animate(1000, style({width: 500, height: 500})), animate(2000, style({width: 500, height: 500})) ]), animate(1000, keyframes([ style({width: 200}), style({width: 500}), ])) ]; const players = invokeAnimationSequence(rootElement, steps); expect(players[0].delay).toEqual(0); // top-level animation expect(players[1].delay).toEqual(1500); // first entry in group() expect(players[2].delay).toEqual(1500); // second entry in group() expect(players[3].delay).toEqual(3500); // animate(...keyframes()) }); }); describe('state based data', () => { it('should create an empty animation if there are zero animation steps', () => { const steps: AnimationMetadata[] = []; const fromStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'blue'], ['height', 100]])]; const toStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'red']])]; const player = invokeAnimationSequence(rootElement, steps, {}, fromStyles, toStyles)[0]; expect(player.duration).toEqual(0); expect(player.keyframes).toEqual([]); }); it('should produce an animation from start to end between the to and from styles if there are animate steps in between', () => { const steps: AnimationMetadata[] = [animate(1000)]; const fromStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'blue'], ['height', 100]])]; const toStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'red']])]; const players = invokeAnimationSequence(rootElement, steps, {}, fromStyles, toStyles); expect(players[0].keyframes).toEqual([ new Map<string, string|number>( [['background', 'blue'], ['height', 100], ['offset', 0]]), new Map<string, string|number>( [['background', 'red'], ['height', AUTO_STYLE], ['offset', 1]]) ]); }); it('should produce an animation from start to end between the to and from styles if there are animate steps in between with an easing value', () => { const steps: AnimationMetadata[] = [animate('1s ease-out')]; const fromStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'blue']])]; const toStyles: Array<ɵStyleDataMap> = [new Map<string, string|number>([['background', 'red']])]; const players = invokeAnimationSequence(rootElement, steps, {}, fromStyles, toStyles); expect(players[0].keyframes).toEqual([ new Map<string, string|number>( [['background', 'blue'], ['offset', 0], ['easing', 'ease-out']]), new Map<string, string|number>([['background', 'red'], ['offset', 1]]) ]); }); }); }); }); } function humanizeOffsets( keyframes: Array<ɵStyleDataMap>, digits: number = 3): Array<ɵStyleDataMap> { return keyframes.map(keyframe => { keyframe.set('offset', Number(parseFloat(<any>keyframe.get('offset')).toFixed(digits))); return keyframe; }); } function invokeAnimationSequence( element: any, steps: AnimationMetadata|AnimationMetadata[], locals: {[key: string]: any} = {}, startingStyles: Array<ɵStyleDataMap> = [], destinationStyles: Array<ɵStyleDataMap> = [], subInstructions?: ElementInstructionMap): AnimationTimelineInstruction[] { const driver = new MockAnimationDriver(); return new Animation(driver, steps) .buildTimelines(element, startingStyles, destinationStyles, locals, subInstructions); } function validateAndThrowAnimationSequence(steps: AnimationMetadata|AnimationMetadata[]) { const driver = new MockAnimationDriver(); const errors: string[] = []; const ast = buildAnimationAst(driver, steps, errors); if (errors.length) { throw new Error(errors.join('\n')); } } function buildParams(params: {[name: string]: any}): AnimationOptions { return <AnimationOptions>{params}; }
shairez/angular
packages/animations/browser/test/dsl/animation_spec.ts
TypeScript
mit
48,978
/* * Copyright 2015 the original author or phly. * 未经正式书面同意,其他任何个人、团体不得使用、复制、修改或发布本软件. */ package com.phly.ttw.manage.supplier.action; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.directwebremoting.annotations.RemoteProxy; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.phly.common.base.action.BaseAction; import com.phly.common.exceptionhandler.annotation.ExceptionMessage; import com.phly.ttw.manage.order.facade.OrderFacade; import com.phly.ttw.manage.order.model.OrderVO; /** * 订单Action类(供应商使用) * * @author LGP */ @Controller @RemoteProxy public class SupplierOrderAction extends BaseAction { @Resource private OrderFacade orderFacade; /** * 查询订单列表 * * @param orderVO * @return 订单集合 */ @ExceptionMessage("查询订单列表失败,请联系管理员") @RequestMapping("/page/ttw/manage/supplier/order") @ResponseBody public ModelMap queryOrderList(HttpServletRequest request, OrderVO orderVO) { String method = request.getParameter("m"); String[] orders = null; if (method.equals("finish")) { orders = new String[1]; orders[0] = "7"; } if (method.equals("unfinish")) { orders = new String[5]; orders[0] = "2"; orders[1] = "3"; orders[2] = "4"; orders[3] = "5"; orders[4] = "6"; } if (method.equals("all")) { orders = new String[6]; orders[0] = "2"; orders[1] = "3"; orders[2] = "4"; orders[3] = "5"; orders[4] = "6"; orders[4] = "7"; } orderVO.setInOrderStatus(orders); return this.orderFacade.queryOrderList(orderVO); } }
linmuxi/ttw
src/com/phly/ttw/manage/supplier/action/SupplierOrderAction.java
Java
mit
1,854
import $ from 'cafy'; import ID from '../../../../misc/cafy-id'; import Note from '../../../../models/note'; import Mute from '../../../../models/mute'; import { pack } from '../../../../models/note'; import UserList from '../../../../models/user-list'; import { ILocalUser } from '../../../../models/user'; import getParams from '../../get-params'; export const meta = { desc: { ja: '指定したユーザーリストのタイムラインを取得します。', en: 'Get timeline of a user list.' }, requireCredential: true, params: { listId: $.type(ID).note({ desc: { ja: 'リストのID' } }), limit: $.num.optional.range(1, 100).note({ default: 10, desc: { ja: '最大数' } }), sinceId: $.type(ID).optional.note({ desc: { ja: '指定すると、この投稿を基点としてより新しい投稿を取得します' } }), untilId: $.type(ID).optional.note({ desc: { ja: '指定すると、この投稿を基点としてより古い投稿を取得します' } }), sinceDate: $.num.optional.note({ desc: { ja: '指定した時間を基点としてより新しい投稿を取得します。数値は、1970年1月1日 00:00:00 UTC から指定した日時までの経過時間をミリ秒単位で表します。' } }), untilDate: $.num.optional.note({ desc: { ja: '指定した時間を基点としてより古い投稿を取得します。数値は、1970年1月1日 00:00:00 UTC から指定した日時までの経過時間をミリ秒単位で表します。' } }), includeMyRenotes: $.bool.optional.note({ default: true, desc: { ja: '自分の行ったRenoteを含めるかどうか' } }), includeRenotedMyNotes: $.bool.optional.note({ default: true, desc: { ja: 'Renoteされた自分の投稿を含めるかどうか' } }), includeLocalRenotes: $.bool.optional.note({ default: true, desc: { ja: 'Renoteされたローカルの投稿を含めるかどうか' } }), mediaOnly: $.bool.optional.note({ desc: { ja: 'true にすると、メディアが添付された投稿だけ取得します' } }), } }; export default async (params: any, user: ILocalUser) => { const [ps, psErr] = getParams(meta, params); if (psErr) throw psErr; const [list, mutedUserIds] = await Promise.all([ // リストを取得 // Fetch the list UserList.findOne({ _id: ps.listId, userId: user._id }), // ミュートしているユーザーを取得 Mute.find({ muterId: user._id }).then(ms => ms.map(m => m.muteeId)) ]); if (list.userIds.length == 0) { return []; } //#region Construct query const sort = { _id: -1 }; const listQuery = list.userIds.map(u => ({ userId: u, // リプライは含めない(ただし投稿者自身の投稿へのリプライ、自分の投稿へのリプライ、自分のリプライは含める) $or: [{ // リプライでない replyId: null }, { // または // リプライだが返信先が投稿者自身の投稿 $expr: { $eq: ['$_reply.userId', '$userId'] } }, { // または // リプライだが返信先が自分(フォロワー)の投稿 '_reply.userId': user._id }, { // または // 自分(フォロワー)が送信したリプライ userId: user._id }] })); const query = { $and: [{ // リストに入っている人のタイムラインへの投稿 $or: listQuery, // mute userId: { $nin: mutedUserIds }, '_reply.userId': { $nin: mutedUserIds }, '_renote.userId': { $nin: mutedUserIds }, }] } as any; // MongoDBではトップレベルで否定ができないため、De Morganの法則を利用してクエリします。 // つまり、「『自分の投稿かつRenote』ではない」を「『自分の投稿ではない』または『Renoteではない』」と表現します。 // for details: https://en.wikipedia.org/wiki/De_Morgan%27s_laws if (ps.includeMyRenotes === false) { query.$and.push({ $or: [{ userId: { $ne: user._id } }, { renoteId: null }, { text: { $ne: null } }, { mediaIds: { $ne: [] } }, { poll: { $ne: null } }] }); } if (ps.includeRenotedMyNotes === false) { query.$and.push({ $or: [{ '_renote.userId': { $ne: user._id } }, { renoteId: null }, { text: { $ne: null } }, { mediaIds: { $ne: [] } }, { poll: { $ne: null } }] }); } if (ps.includeLocalRenotes === false) { query.$and.push({ $or: [{ '_renote.user.host': { $ne: null } }, { renoteId: null }, { text: { $ne: null } }, { mediaIds: { $ne: [] } }, { poll: { $ne: null } }] }); } if (ps.mediaOnly) { query.$and.push({ mediaIds: { $exists: true, $ne: [] } }); } if (ps.sinceId) { sort._id = 1; query._id = { $gt: ps.sinceId }; } else if (ps.untilId) { query._id = { $lt: ps.untilId }; } else if (ps.sinceDate) { sort._id = 1; query.createdAt = { $gt: new Date(ps.sinceDate) }; } else if (ps.untilDate) { query.createdAt = { $lt: new Date(ps.untilDate) }; } //#endregion // Issue query const timeline = await Note .find(query, { limit: ps.limit, sort: sort }); // Serialize return await Promise.all(timeline.map(note => pack(note, user))); };
ha-dai/Misskey
src/server/api/endpoints/notes/user-list-timeline.ts
TypeScript
mit
5,368
using System; namespace SharpCompress.Compressors.Xz { public class XZIndexMarkerReachedException : Exception { } }
adamhathcock/sharpcompress
src/SharpCompress/Compressors/Xz/XZIndexMarkerReachedException.cs
C#
mit
132
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014-2019 British Columbia Institute of Technology * Copyright (c) 2019 CodeIgniter Foundation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author CodeIgniter Dev Team * @copyright 2019 CodeIgniter Foundation * @license https://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 4.0.0 * @filesource */ namespace CodeIgniter\HTTP; use CodeIgniter\HTTP\Exceptions\HTTPException; /** * Class Negotiate * * Provides methods to negotiate with the HTTP headers to determine the best * type match between what the application supports and what the requesting * getServer wants. * * @see http://tools.ietf.org/html/rfc7231#section-5.3 * @package CodeIgniter\HTTP */ class Negotiate { /** * Request * * @var \CodeIgniter\HTTP\RequestInterface|\CodeIgniter\HTTP\IncomingRequest */ protected $request; //-------------------------------------------------------------------- /** * Constructor * * @param \CodeIgniter\HTTP\RequestInterface $request */ public function __construct(RequestInterface $request = null) { if (! is_null($request)) { $this->request = $request; } } //-------------------------------------------------------------------- /** * Stores the request instance to grab the headers from. * * @param RequestInterface $request * * @return $this */ public function setRequest(RequestInterface $request) { $this->request = $request; return $this; } //-------------------------------------------------------------------- /** * Determines the best content-type to use based on the $supported * types the application says it supports, and the types requested * by the client. * * If no match is found, the first, highest-ranking client requested * type is returned. * * @param array $supported * @param boolean $strictMatch If TRUE, will return an empty string when no match found. * If FALSE, will return the first supported element. * * @return string */ public function media(array $supported, bool $strictMatch = false): string { return $this->getBestMatch($supported, $this->request->getHeaderLine('accept'), true, $strictMatch); } //-------------------------------------------------------------------- /** * Determines the best charset to use based on the $supported * types the application says it supports, and the types requested * by the client. * * If no match is found, the first, highest-ranking client requested * type is returned. * * @param array $supported * * @return string */ public function charset(array $supported): string { $match = $this->getBestMatch($supported, $this->request->getHeaderLine('accept-charset'), false, true); // If no charset is shown as a match, ignore the directive // as allowed by the RFC, and tell it a default value. if (empty($match)) { return 'utf-8'; } return $match; } //-------------------------------------------------------------------- /** * Determines the best encoding type to use based on the $supported * types the application says it supports, and the types requested * by the client. * * If no match is found, the first, highest-ranking client requested * type is returned. * * @param array $supported * * @return string */ public function encoding(array $supported = []): string { array_push($supported, 'identity'); return $this->getBestMatch($supported, $this->request->getHeaderLine('accept-encoding')); } //-------------------------------------------------------------------- /** * Determines the best language to use based on the $supported * types the application says it supports, and the types requested * by the client. * * If no match is found, the first, highest-ranking client requested * type is returned. * * @param array $supported * * @return string */ public function language(array $supported): string { return $this->getBestMatch($supported, $this->request->getHeaderLine('accept-language')); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // Utility Methods //-------------------------------------------------------------------- /** * Does the grunt work of comparing any of the app-supported values * against a given Accept* header string. * * Portions of this code base on Aura.Accept library. * * @param array $supported App-supported values * @param string $header header string * @param boolean $enforceTypes If TRUE, will compare media types and sub-types. * @param boolean $strictMatch If TRUE, will return empty string on no match. * If FALSE, will return the first supported element. * * @return string Best match */ protected function getBestMatch(array $supported, string $header = null, bool $enforceTypes = false, bool $strictMatch = false): string { if (empty($supported)) { throw HTTPException::forEmptySupportedNegotiations(); } if (empty($header)) { return $strictMatch ? '' : $supported[0]; } $acceptable = $this->parseHeader($header); foreach ($acceptable as $accept) { // if acceptable quality is zero, skip it. if ($accept['q'] === 0.0) { continue; } // if acceptable value is "anything", return the first available if ($accept['value'] === '*' || $accept['value'] === '*/*') { return $supported[0]; } // If an acceptable value is supported, return it foreach ($supported as $available) { if ($this->match($accept, $available, $enforceTypes)) { return $available; } } } // No matches? Return the first supported element. return $strictMatch ? '' : $supported[0]; } //-------------------------------------------------------------------- /** * Parses an Accept* header into it's multiple values. * * This is based on code from Aura.Accept library. * * @param string $header * * @return array */ public function parseHeader(string $header): array { $results = []; $acceptable = explode(',', $header); foreach ($acceptable as $value) { $pairs = explode(';', $value); $value = $pairs[0]; unset($pairs[0]); $parameters = []; foreach ($pairs as $pair) { $param = []; preg_match( '/^(?P<name>.+?)=(?P<quoted>"|\')?(?P<value>.*?)(?:\k<quoted>)?$/', $pair, $param ); $parameters[trim($param['name'])] = trim($param['value']); } $quality = 1.0; if (array_key_exists('q', $parameters)) { $quality = $parameters['q']; unset($parameters['q']); } $results[] = [ 'value' => trim($value), 'q' => (float) $quality, 'params' => $parameters, ]; } // Sort to get the highest results first usort($results, function ($a, $b) { if ($a['q'] === $b['q']) { $a_ast = substr_count($a['value'], '*'); $b_ast = substr_count($b['value'], '*'); // '*/*' has lower precedence than 'text/*', // and 'text/*' has lower priority than 'text/plain' // // This seems backwards, but needs to be that way // due to the way PHP7 handles ordering or array // elements created by reference. if ($a_ast > $b_ast) { return 1; } // If the counts are the same, but one element // has more params than another, it has higher precedence. // // This seems backwards, but needs to be that way // due to the way PHP7 handles ordering or array // elements created by reference. if ($a_ast === $b_ast) { return count($b['params']) - count($a['params']); } return 0; } // Still here? Higher q values have precedence. return ($a['q'] > $b['q']) ? -1 : 1; }); return $results; } //-------------------------------------------------------------------- /** * Match-maker * * @param array $acceptable * @param string $supported * @param boolean $enforceTypes * @return boolean */ protected function match(array $acceptable, string $supported, bool $enforceTypes = false): bool { $supported = $this->parseHeader($supported); if (is_array($supported) && count($supported) === 1) { $supported = $supported[0]; } // Is it an exact match? if ($acceptable['value'] === $supported['value']) { return $this->matchParameters($acceptable, $supported); } // Do we need to compare types/sub-types? Only used // by negotiateMedia(). if ($enforceTypes) { return $this->matchTypes($acceptable, $supported); } return false; } //-------------------------------------------------------------------- /** * Checks two Accept values with matching 'values' to see if their * 'params' are the same. * * @param array $acceptable * @param array $supported * * @return boolean */ protected function matchParameters(array $acceptable, array $supported): bool { if (count($acceptable['params']) !== count($supported['params'])) { return false; } foreach ($supported['params'] as $label => $value) { if (! isset($acceptable['params'][$label]) || $acceptable['params'][$label] !== $value) { return false; } } return true; } //-------------------------------------------------------------------- /** * Compares the types/subtypes of an acceptable Media type and * the supported string. * * @param array $acceptable * @param array $supported * * @return boolean */ public function matchTypes(array $acceptable, array $supported): bool { list($aType, $aSubType) = explode('/', $acceptable['value']); list($sType, $sSubType) = explode('/', $supported['value']); // If the types don't match, we're done. if ($aType !== $sType) { return false; } // If there's an asterisk, we're cool if ($aSubType === '*') { return true; } // Otherwise, subtypes must match also. return $aSubType === $sSubType; } //-------------------------------------------------------------------- }
jim-parry/CodeIgniter4
system/HTTP/Negotiate.php
PHP
mit
11,335
class CreateUsers < ActiveRecord::Migration[5.1] def change create_table :users do |t| t.string :first_name t.string :last_name t.string :spire t.string :email t.string :phone t.timestamps null: false end end end
umts/garrulous-garbanzo
db/migrate/20150909204238_create_users.rb
Ruby
mit
262
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpCodeSnippets { public class DoubleArrayCreation { public double[][] ScaleArrays(double[][] arrays, double scalingFactor) { var result = new double[arrays.Length][]; for (int i = 0; i < arrays.Length; i++) { result[i] = ScaleArray(arrays[i], scalingFactor); } return result; } public double[] ScaleArray(double[] array, double scalingFactor) { var result = new double[array.Length]; for (int i = 0; i < array.Length; i++) result[i] = array[i] * scalingFactor; return result; } private const int Zero = 0; private static readonly double[] Empty = new double[Zero]; private static readonly double[] Empty2 = new double[Zero2]; private const int Zero2 = 0; public void EmptyArray() { const int Two = 2; var result = new double[Two]; } } }
liebharc/VerifyBuffer
VerifyBuffering/CSharpCodeSnippets/DoubleArrayCreation.cs
C#
mit
1,190
//Copyright (C) <2012> <Jon Baker, Glenn Mariën and Lao Tszy> //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. //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, see <http://www.gnu.org/licenses/>. //Copyright (C) <2012> Jon Baker(http://au70.net) using System; using System.Collections.Generic; namespace fCraft.Drawing { public sealed class WallsDrawOperation : DrawOperation { bool fillInner; public override string Name { get { return "Walls"; } } public override string Description { get { return Name; } } public WallsDrawOperation(Player player) : base(player){ } public override bool Prepare(Vector3I[] marks) { if (!base.Prepare(marks)) return false; fillInner = Brush.HasAlternateBlock && Bounds.Width > 2 && Bounds.Length > 2 && Bounds.Height > 2; BlocksTotalEstimate = Bounds.Volume; if (!fillInner) { BlocksTotalEstimate -= Math.Max(0, Bounds.Width - 2) * Math.Max(0, Bounds.Length - 2) * Math.Max(0, Bounds.Height - 2); } coordEnumerator = BlockEnumerator().GetEnumerator(); return true; } IEnumerator<Vector3I> coordEnumerator; public override int DrawBatch(int maxBlocksToDraw) { int blocksDone = 0; while (coordEnumerator.MoveNext()) { Coords = coordEnumerator.Current; if (DrawOneBlock()) { blocksDone++; if (blocksDone >= maxBlocksToDraw) return blocksDone; } } IsDone = true; return blocksDone; } //all works. Maybe look at Block estimation. IEnumerable<Vector3I> BlockEnumerator() { for (int x = Bounds.XMin; x <= Bounds.XMax; x++) { for (int z = Bounds.ZMin - 1; z < Bounds.ZMax; z++) { yield return new Vector3I(x, Bounds.YMin, z + 1); if (Bounds.YMin != Bounds.YMax) { yield return new Vector3I(x, Bounds.YMax, z + 1); } } for (int y = Bounds.YMin; y < Bounds.YMax; y++) { for (int z = Bounds.ZMin - 1; z < Bounds.ZMax; z++) { yield return new Vector3I(Bounds.XMin, y, z + 1); if (Bounds.XMin != Bounds.XMax) { yield return new Vector3I(Bounds.XMax, y, z + 1); } } } } if (fillInner) { UseAlternateBlock = true; for (int x = Bounds.XMin + 1; x < Bounds.XMax; x++) { for (int y = Bounds.YMin + 1; y < Bounds.YMax; y++) { for (int z = Bounds.ZMin; z < Bounds.ZMax + 1; z++) { yield return new Vector3I(x, y, z); } } } } } } }
LeChosenOne/LegendCraft
fCraft/Drawing/DrawOps/WallsOp.cs
C#
mit
3,853
<?php // FILE: xtemplate.class (part of MiniMediaEducation, https://github.com/aleph3d/MiniMediaEducation.git) // TYPE: funciton/class Library (PHP5) // LICENSE: BSD and LGPL ////// Copyright (c) 2000-2001 Barnab�s Debreceni [cranx@users.sourceforge.net] XTemplate ////// Copyright (c) 2002-2007 Jeremy Coates [cocomp@users.sourceforge.net] XTemplate & CachingXTemplate // When developing uncomment the line below, re-comment before making public //error_reporting(E_ALL); /** * XTemplate PHP templating engine * * @package XTemplate * @author Barnabas Debreceni [cranx@users.sourceforge.net] * @copyright Barnabas Debreceni 2000-2001 * @author Jeremy Coates [cocomp@users.sourceforge.net] * @copyright Jeremy Coates 2002-2007 * @see license.txt LGPL / BSD license * @since PHP 5 * @link $HeadURL: https://xtpl.svn.sourceforge.net/svnroot/xtpl/trunk/xtemplate.class.php $ * @version $Id: xtemplate.class.php 21 2007-05-29 18:01:15Z cocomp $ * * * XTemplate class - http://www.phpxtemplate.org/ (x)html / xml generation with templates - fast & easy * Latest stable & Subversion versions available @ http://sourceforge.net/projects/xtpl/ * License: LGPL / BSD - see license.txt * Changelog: see changelog.txt */ proCheck() or die(); class XTemplate { /** * Properties */ /** * Raw contents of the template file * * @access public * @var string */ public $filecontents = ''; /** * Unparsed blocks * * @access public * @var array */ public $blocks = array(); /** * Parsed blocks * * @var unknown_type */ public $parsed_blocks = array(); /** * Preparsed blocks (for file includes) * * @access public * @var array */ public $preparsed_blocks = array(); /** * Block parsing order for recursive parsing * (Sometimes reverse :) * * @access public * @var array */ public $block_parse_order = array(); /** * Store sub-block names * (For fast resetting) * * @access public * @var array */ public $sub_blocks = array(); /** * Variables array * * @access public * @var array */ public $vars = array(); /** * File variables array * * @access public * @var array */ public $filevars = array(); /** * Filevars' parent block * * @access public * @var array */ public $filevar_parent = array(); /** * File caching during duration of script * e.g. files only cached to speed {FILE "filename"} repeats * * @access public * @var array */ public $filecache = array(); /** * Location of template files * * @access public * @var string */ public $tpldir = ''; /** * Filenames lookup table * * @access public * @var null */ public $files = null; /** * Template filename * * @access public * @var string */ public $filename = ''; // moved to setup method so uses the tag_start & end_delims /** * RegEx for file includes * * "/\{FILE\s*\"([^\"]+)\"\s*\}/m"; * * @access public * @var string */ public $file_delim = ''; /** * RegEx for file include variable * * "/\{FILE\s*\{([A-Za-z0-9\._]+?)\}\s*\}/m"; * * @access public * @var string */ public $filevar_delim = ''; /** * RegEx for file includes with newlines * * "/^\s*\{FILE\s*\{([A-Za-z0-9\._]+?)\}\s*\}\s*\n/m"; * * @access public * @var string */ public $filevar_delim_nl = ''; /** * Template block start delimiter * * @access public * @var string */ public $block_start_delim = '<!-- '; /** * Template block end delimiter * * @access public * @var string */ public $block_end_delim = '-->'; /** * Template block start word * * @access public * @var string */ public $block_start_word = 'BEGIN:'; /** * Template block end word * * The last 3 properties and this make the delimiters look like: * @example <!-- BEGIN: block_name --> * if you use the default syntax. * * @access public * @var string */ public $block_end_word = 'END:'; /** * Template tag start delimiter * * This makes the delimiters look like: * @example {tagname} * if you use the default syntax. * * @access public * @var string */ public $tag_start_delim = '{'; /** * Template tag end delimiter * * This makes the delimiters look like: * @example {tagname} * if you use the default syntax. * * @access public * @var string */ public $tag_end_delim = '}'; /* this makes the delimiters look like: {tagname} if you use my syntax. */ /** * Regular expression element for comments within tags and blocks * * @example {tagname#My Comment} * @example {tagname #My Comment} * @example <!-- BEGIN: blockname#My Comment --> * @example <!-- BEGIN: blockname #My Comment --> * * @access public * @var string */ public $comment_preg = '( ?#.*?)?'; /** * Default main template block name * * @access public * @var string */ public $mainblock = 'main'; /** * Script output type * * @access public * @var string */ public $output_type = 'HTML'; /** * Debug mode * * @access public * @var boolean */ public $debug = false; /** * Null string for unassigned vars * * @access protected * @var array */ protected $_null_string = array('' => ''); /** * Null string for unassigned blocks * * @access protected * @var array */ protected $_null_block = array('' => ''); /** * Errors * * @access protected * @var string */ protected $_error = ''; /** * Auto-reset sub blocks * * @access protected * @var boolean */ protected $_autoreset = true; /** * Set to FALSE to generate errors if a non-existant blocks is referenced * * @author NW * @since 2002/10/17 * @access protected * @var boolean */ protected $_ignore_missing_blocks = true; /** * PHP 5 Constructor - Instantiate the object * * @param string $file Template file to work on * @param string/array $tpldir Location of template files (useful for keeping files outside web server root) * @param array $files Filenames lookup * @param string $mainblock Name of main block in the template * @param boolean $autosetup If true, run setup() as part of constuctor * @return XTemplate */ public function __construct($file, $tpldir = '', $files = null, $mainblock = 'main', $autosetup = true) { $this->restart($file, $tpldir, $files, $mainblock, $autosetup, $this->tag_start_delim, $this->tag_end_delim); } /** * PHP 4 Constructor - Instantiate the object * * @deprecated Use PHP 5 constructor instead * @param string $file Template file to work on * @param string/array $tpldir Location of template files (useful for keeping files outside web server root) * @param array $files Filenames lookup * @param string $mainblock Name of main block in the template * @param boolean $autosetup If true, run setup() as part of constuctor * @return XTemplate */ public function XTemplate ($file, $tpldir = '', $files = null, $mainblock = 'main', $autosetup = true) { assert('Deprecated - use PHP 5 constructor'); } /***************************************************************************/ /***[ public stuff ]********************************************************/ /***************************************************************************/ /** * Restart the class - allows one instantiation with several files processed by restarting * e.g. $xtpl = new XTemplate('file1.xtpl'); * $xtpl->parse('main'); * $xtpl->out('main'); * $xtpl->restart('file2.xtpl'); * $xtpl->parse('main'); * $xtpl->out('main'); * (Added in response to sf:641407 feature request) * * @param string $file Template file to work on * @param string/array $tpldir Location of template files * @param array $files Filenames lookup * @param string $mainblock Name of main block in the template * @param boolean $autosetup If true, run setup() as part of restarting * @param string $tag_start { * @param string $tag_end } */ public function restart ($file, $tpldir = '', $files = null, $mainblock = 'main', $autosetup = true, $tag_start = '{', $tag_end = '}') { $this->filename = $file; // From SF Feature request 1202027 // Kenneth Kalmer $this->tpldir = $tpldir; if (defined('XTPL_DIR') && empty($this->tpldir)) { $this->tpldir = XTPL_DIR; } if (is_array($files)) { $this->files = $files; } $this->mainblock = $mainblock; $this->tag_start_delim = $tag_start; $this->tag_end_delim = $tag_end; // Start with fresh file contents $this->filecontents = ''; // Reset the template arrays $this->blocks = array(); $this->parsed_blocks = array(); $this->preparsed_blocks = array(); $this->block_parse_order = array(); $this->sub_blocks = array(); $this->vars = array(); $this->filevars = array(); $this->filevar_parent = array(); $this->filecache = array(); if ($autosetup) { $this->setup(); } } /** * setup - the elements that were previously in the constructor * * @access public * @param boolean $add_outer If true is passed when called, it adds an outer main block to the file */ public function setup ($add_outer = false) { $this->tag_start_delim = preg_quote($this->tag_start_delim); $this->tag_end_delim = preg_quote($this->tag_end_delim); // Setup the file delimiters // regexp for file includes $this->file_delim = "/" . $this->tag_start_delim . "FILE\s*\"([^\"]+)\"" . $this->comment_preg . $this->tag_end_delim . "/m"; // regexp for file includes $this->filevar_delim = "/" . $this->tag_start_delim . "FILE\s*" . $this->tag_start_delim . "([A-Za-z0-9\._]+?)" . $this->comment_preg . $this->tag_end_delim . $this->comment_preg . $this->tag_end_delim . "/m"; // regexp for file includes w/ newlines $this->filevar_delim_nl = "/^\s*" . $this->tag_start_delim . "FILE\s*" . $this->tag_start_delim . "([A-Za-z0-9\._]+?)" . $this->comment_preg . $this->tag_end_delim . $this->comment_preg . $this->tag_end_delim . "\s*\n/m"; if (empty($this->filecontents)) { // read in template file $this->filecontents = $this->_r_getfile($this->filename); } if ($add_outer) { $this->_add_outer_block(); } // preprocess some stuff $this->blocks = $this->_maketree($this->filecontents, ''); $this->filevar_parent = $this->_store_filevar_parents($this->blocks); $this->scan_globals(); } /** * assign a variable * * @example Simplest case: * @example $xtpl->assign('name', 'value'); * @example {name} in template * * @example Array assign: * @example $xtpl->assign(array('name' => 'value', 'name2' => 'value2')); * @example {name} {name2} in template * * @example Value as array assign: * @example $xtpl->assign('name', array('key' => 'value', 'key2' => 'value2')); * @example {name.key} {name.key2} in template * * @example Reset array: * @example $xtpl->assign('name', array('key' => 'value', 'key2' => 'value2')); * @example // Other code then: * @example $xtpl->assign('name', array('key3' => 'value3'), false); * @example {name.key} {name.key2} {name.key3} in template * * @access public * @param string $name Variable to assign $val to * @param string / array $val Value to assign to $name * @param boolean $reset_array Reset the variable array if $val is an array */ public function assign ($name, $val = '', $reset_array = true) { if (is_array($name)) { foreach ($name as $k => $v) { $this->vars[$k] = $v; } } elseif (is_array($val)) { // Clear the existing values if ($reset_array) { $this->vars[$name] = array(); } foreach ($val as $k => $v) { $this->vars[$name][$k] = $v; } } else { $this->vars[$name] = $val; } } /** * assign a file variable * * @access public * @param string $name Variable to assign $val to * @param string / array $val Values to assign to $name */ public function assign_file ($name, $val = '') { if (is_array($name)) { foreach ($name as $k => $v) { $this->_assign_file_sub($k, $v); } } else { $this->_assign_file_sub($name, $val); } } /** * parse a block * * @access public * @param string $bname Block name to parse */ public function parse ($bname) { if (isset($this->preparsed_blocks[$bname])) { $copy = $this->preparsed_blocks[$bname]; } elseif (isset($this->blocks[$bname])) { $copy = $this->blocks[$bname]; } elseif ($this->_ignore_missing_blocks) { // ------------------------------------------------------ // NW : 17 Oct 2002. Added default of ignore_missing_blocks // to allow for generalised processing where some // blocks may be removed from the HTML without the // processing code needing to be altered. // ------------------------------------------------------ // JRC: 3/1/2003 added set error to ignore missing functionality $this->_set_error("parse: blockname [$bname] does not exist"); return; } else { $this->_set_error("parse: blockname [$bname] does not exist"); } /* from there we should have no more {FILE } directives */ if (!isset($copy)) { die('Block: ' . $bname); } $copy = preg_replace($this->filevar_delim_nl, '', $copy); $var_array = array(); /* find & replace variables+blocks */ preg_match_all("|" . $this->tag_start_delim . "([A-Za-z0-9\._]+?" . $this->comment_preg . ")" . $this->tag_end_delim. "|", $copy, $var_array); $var_array = $var_array[1]; foreach ($var_array as $k => $v) { // Are there any comments in the tags {tag#a comment for documenting the template} $any_comments = explode('#', $v); $v = rtrim($any_comments[0]); if (sizeof($any_comments) > 1) { $comments = $any_comments[1]; } else { $comments = ''; } $sub = explode('.', $v); if ($sub[0] == '_BLOCK_') { unset($sub[0]); $bname2 = implode('.', $sub); // trinary operator eliminates assign error in E_ALL reporting $var = isset($this->parsed_blocks[$bname2]) ? $this->parsed_blocks[$bname2] : null; $nul = (!isset($this->_null_block[$bname2])) ? $this->_null_block[''] : $this->_null_block[$bname2]; if ($var === '') { if ($nul == '') { // ----------------------------------------------------------- // Removed requirement for blocks to be at the start of string // ----------------------------------------------------------- // $copy=preg_replace("/^\s*\{".$v."\}\s*\n*/m","",$copy); // Now blocks don't need to be at the beginning of a line, //$copy=preg_replace("/\s*" . $this->tag_start_delim . $v . $this->tag_end_delim . "\s*\n*/m","",$copy); $copy = preg_replace("|" . $this->tag_start_delim . $v . $this->tag_end_delim . "|m", '', $copy); } else { $copy = preg_replace("|" . $this->tag_start_delim . $v . $this->tag_end_delim . "|m", "$nul", $copy); } } else { //$var = trim($var); switch (true) { case preg_match('/^\n/', $var) && preg_match('/\n$/', $var): $var = substr($var, 1, -1); break; case preg_match('/^\n/', $var): $var = substr($var, 1); break; case preg_match('/\n$/', $var): $var = substr($var, 0, -1); break; } // SF Bug no. 810773 - thanks anonymous $var = str_replace('\\', '\\\\', $var); // Ensure dollars in strings are not evaluated reported by SadGeezer 31/3/04 $var = str_replace('$', '\\$', $var); // Replaced str_replaces with preg_quote //$var = preg_quote($var); $var = str_replace('\\|', '|', $var); $copy = preg_replace("|" . $this->tag_start_delim . $v . $this->tag_end_delim . "|m", "$var", $copy); if (preg_match('/^\n/', $copy) && preg_match('/\n$/', $copy)) { $copy = substr($copy, 1, -1); } } } else { $var = $this->vars; foreach ($sub as $v1) { // NW 4 Oct 2002 - Added isset and is_array check to avoid NOTICE messages // JC 17 Oct 2002 - Changed EMPTY to stlen=0 // if (empty($var[$v1])) { // this line would think that zeros(0) were empty - which is not true if (!isset($var[$v1]) || (!is_array($var[$v1]) && strlen($var[$v1]) == 0)) { // Check for constant, when variable not assigned if (defined($v1)) { $var[$v1] = constant($v1); } else { $var[$v1] = null; } } $var = $var[$v1]; } $nul = (!isset($this->_null_string[$v])) ? ($this->_null_string[""]) : ($this->_null_string[$v]); $var = (!isset($var)) ? $nul : $var; if ($var === '') { // ----------------------------------------------------------- // Removed requriement for blocks to be at the start of string // ----------------------------------------------------------- // $copy=preg_replace("|^\s*\{".$v." ?#?".$comments."\}\s*\n|m","",$copy); $copy = preg_replace("|" . $this->tag_start_delim . $v . "( ?#" . $comments . ")?" . $this->tag_end_delim . "|m", '', $copy); } $var = trim($var); // SF Bug no. 810773 - thanks anonymous $var = str_replace('\\', '\\\\', $var); // Ensure dollars in strings are not evaluated reported by SadGeezer 31/3/04 $var = str_replace('$', '\\$', $var); // Replace str_replaces with preg_quote //$var = preg_quote($var); $var = str_replace('\\|', '|', $var); $copy = preg_replace("|" . $this->tag_start_delim . $v . "( ?#" . $comments . ")?" . $this->tag_end_delim . "|m", "$var", $copy); if (preg_match('/^\n/', $copy) && preg_match('/\n$/', $copy)) { $copy = substr($copy, 1); } } } if (isset($this->parsed_blocks[$bname])) { $this->parsed_blocks[$bname] .= $copy; } else { $this->parsed_blocks[$bname] = $copy; } /* reset sub-blocks */ if ($this->_autoreset && (!empty($this->sub_blocks[$bname]))) { reset($this->sub_blocks[$bname]); foreach ($this->sub_blocks[$bname] as $k => $v) { $this->reset($v); } } } /** * returns the parsed text for a block, including all sub-blocks. * * @access public * @param string $bname Block name to parse */ public function rparse ($bname) { if (!empty($this->sub_blocks[$bname])) { reset($this->sub_blocks[$bname]); foreach ($this->sub_blocks[$bname] as $k => $v) { if (!empty($v)) { $this->rparse($v); } } } $this->parse($bname); } /** * inserts a loop ( call assign & parse ) * * @access public * @param string $bname Block name to assign * @param string $var Variable to assign values to * @param string / array $value Value to assign to $var */ public function insert_loop ($bname, $var, $value = '') { $this->assign($var, $value); $this->parse($bname); } /** * parses a block for every set of data in the values array * * @access public * @param string $bname Block name to loop * @param string $var Variable to assign values to * @param array $values Values to assign to $var */ public function array_loop ($bname, $var, &$values) { if (is_array($values)) { foreach($values as $v) { $this->insert_loop($bname, $var, $v); } } } /** * returns the parsed text for a block * * @access public * @param string $bname Block name to return * @return string */ public function text ($bname = '') { $text = ''; if ($this->debug && $this->output_type == 'HTML') { // JC 20/11/02 echo the template filename if in development as // html comment $text .= '<!-- XTemplate: ' . realpath($this->filename) . " -->\n"; } $bname = !empty($bname) ? $bname : $this->mainblock; $text .= isset($this->parsed_blocks[$bname]) ? $this->parsed_blocks[$bname] : $this->get_error(); return $text; } /** * prints the parsed text * * @access public * @param string $bname Block name to echo out */ public function out ($bname) { $out = $this->text($bname); // $length=strlen($out); //header("Content-Length: ".$length); // TODO: Comment this back in later echo $out; } public function VariableOut ($bname) { $out = $this->text($bname); // $length=strlen($out); //header("Content-Length: ".$length); // TODO: Comment this back in later return $out; } /** * prints the parsed text to a specified file * * @access public * @param string $bname Block name to write out * @param string $fname File name to write to */ public function out_file ($bname, $fname) { if (!empty($bname) && !empty($fname) && is_writeable($fname)) { $fp = fopen($fname, 'w'); fwrite($fp, $this->text($bname)); fclose($fp); } } /** * resets the parsed text * * @access public * @param string $bname Block to reset */ public function reset ($bname) { $this->parsed_blocks[$bname] = ''; } /** * returns true if block was parsed, false if not * * @access public * @param string $bname Block name to test * @return boolean */ public function parsed ($bname) { return (!empty($this->parsed_blocks[$bname])); } /** * sets the string to replace in case the var was not assigned * * @access public * @param string $str Display string for null block * @param string $varname Variable name to apply $str to */ public function set_null_string($str, $varname = '') { $this->_null_string[$varname] = $str; } /** * Backwards compatibility only * * @param string $str * @param string $varname * @deprecated Change to set_null_string to keep in with rest of naming convention */ public function SetNullString ($str, $varname = '') { $this->set_null_string($str, $varname); } /** * sets the string to replace in case the block was not parsed * * @access public * @param string $str Display string for null block * @param string $bname Block name to apply $str to */ public function set_null_block ($str, $bname = '') { $this->_null_block[$bname] = $str; } /** * Backwards compatibility only * * @param string $str * @param string $bname * @deprecated Change to set_null_block to keep in with rest of naming convention */ public function SetNullBlock ($str, $bname = '') { $this->set_null_block($str, $bname); } /** * sets AUTORESET to 1. (default is 1) * if set to 1, parse() automatically resets the parsed blocks' sub blocks * (for multiple level blocks) * * @access public */ public function set_autoreset () { $this->_autoreset = true; } /** * sets AUTORESET to 0. (default is 1) * if set to 1, parse() automatically resets the parsed blocks' sub blocks * (for multiple level blocks) * * @access public */ public function clear_autoreset () { $this->_autoreset = false; } /** * scans global variables and assigns to PHP array * * @access public */ public function scan_globals () { reset($GLOBALS); foreach ($GLOBALS as $k => $v) { $GLOB[$k] = $v; } /** * Access global variables as: * @example {PHP._SERVER.HTTP_HOST} * in your template! */ $this->assign('PHP', $GLOB); } /** * gets error condition / string * * @access public * @return boolean / string */ public function get_error () { // JRC: 3/1/2003 Added ouptut wrapper and detection of output type for error message output $retval = false; if ($this->_error != '') { switch ($this->output_type) { case 'HTML': case 'html': $retval = '<b>[XTemplate]</b><ul>' . nl2br(str_replace('* ', '<li>', str_replace(" *\n", "</li>\n", $this->_error))) . '</ul>'; break; default: $retval = '[XTemplate] ' . str_replace(' *\n', "\n", $this->_error); break; } } return $retval; } /***************************************************************************/ /***[ private stuff ]*******************************************************/ /***************************************************************************/ /** * generates the array containing to-be-parsed stuff: * $blocks["main"],$blocks["main.table"],$blocks["main.table.row"], etc. * also builds the reverse parse order. * * @access public - aiming for private * @param string $con content to be processed * @param string $parentblock name of the parent block in the block hierarchy */ public function _maketree ($con, $parentblock='') { $blocks = array(); $con2 = explode($this->block_start_delim, $con); if (!empty($parentblock)) { $block_names = explode('.', $parentblock); $level = sizeof($block_names); } else { $block_names = array(); $level = 0; } // JRC 06/04/2005 Added block comments (on BEGIN or END) <!-- BEGIN: block_name#Comments placed here --> //$patt = "($this->block_start_word|$this->block_end_word)\s*(\w+)\s*$this->block_end_delim(.*)"; $patt = "(" . $this->block_start_word . "|" . $this->block_end_word . ")\s*(\w+)" . $this->comment_preg . "\s*" . $this->block_end_delim . "(.*)"; foreach($con2 as $k => $v) { $res = array(); if (preg_match_all("/$patt/ims", $v, $res, PREG_SET_ORDER)) { // $res[0][1] = BEGIN or END // $res[0][2] = block name // $res[0][3] = comment // $res[0][4] = kinda content $block_word = $res[0][1]; $block_name = $res[0][2]; $comment = $res[0][3]; $content = $res[0][4]; if (strtoupper($block_word) == $this->block_start_word) { $parent_name = implode('.', $block_names); // add one level - array("main","table","row") $block_names[++$level] = $block_name; // make block name (main.table.row) $cur_block_name=implode('.', $block_names); // build block parsing order (reverse) $this->block_parse_order[] = $cur_block_name; //add contents. trinary operator eliminates assign error in E_ALL reporting $blocks[$cur_block_name] = isset($blocks[$cur_block_name]) ? $blocks[$cur_block_name] . $content : $content; // add {_BLOCK_.blockname} string to parent block $blocks[$parent_name] .= str_replace('\\', '', $this->tag_start_delim) . '_BLOCK_.' . $cur_block_name . str_replace('\\', '', $this->tag_end_delim); // store sub block names for autoresetting and recursive parsing $this->sub_blocks[$parent_name][] = $cur_block_name; // store sub block names for autoresetting $this->sub_blocks[$cur_block_name][] = ''; } else if (strtoupper($block_word) == $this->block_end_word) { unset($block_names[$level--]); $parent_name = implode('.', $block_names); // add rest of block to parent block $blocks[$parent_name] .= $content; } } else { // no block delimiters found // Saves doing multiple implodes - less overhead $tmp = implode('.', $block_names); if ($k) { $blocks[$tmp] .= $this->block_start_delim; } // trinary operator eliminates assign error in E_ALL reporting $blocks[$tmp] = isset($blocks[$tmp]) ? $blocks[$tmp] . $v : $v; } } return $blocks; } /** * Sub processing for assign_file method * * @access private * @param string $name * @param string $val */ private function _assign_file_sub ($name, $val) { if (isset($this->filevar_parent[$name])) { if ($val != '') { $val = $this->_r_getfile($val); foreach($this->filevar_parent[$name] as $parent) { if (isset($this->preparsed_blocks[$parent]) && !isset($this->filevars[$name])) { $copy = $this->preparsed_blocks[$parent]; } elseif (isset($this->blocks[$parent])) { $copy = $this->blocks[$parent]; } $res = array(); preg_match_all($this->filevar_delim, $copy, $res, PREG_SET_ORDER); if (is_array($res) && isset($res[0])) { // Changed as per solution in SF bug ID #1261828 foreach ($res as $v) { // Changed as per solution in SF bug ID #1261828 if ($v[1] == $name) { // Changed as per solution in SF bug ID #1261828 $copy = preg_replace("/" . preg_quote($v[0]) . "/", "$val", $copy); $this->preparsed_blocks = array_merge($this->preparsed_blocks, $this->_maketree($copy, $parent)); $this->filevar_parent = array_merge($this->filevar_parent, $this->_store_filevar_parents($this->preparsed_blocks)); } } } } } } $this->filevars[$name] = $val; } /** * store container block's name for file variables * * @access public - aiming for private * @param array $blocks * @return array */ public function _store_filevar_parents ($blocks){ $parents = array(); foreach ($blocks as $bname => $con) { $res = array(); preg_match_all($this->filevar_delim, $con, $res); foreach ($res[1] as $k => $v) { $parents[$v][] = $bname; } } return $parents; } /** * Set the error string * * @access private * @param string $str */ private function _set_error ($str) { // JRC: 3/1/2003 Made to append the error messages $this->_error .= '* ' . $str . " *\n"; // JRC: 3/1/2003 Removed trigger error, use this externally if you want it eg. trigger_error($xtpl->get_error()) //trigger_error($this->get_error()); } /** * returns the contents of a file * * @access protected * @param string $file * @return string */ protected function _getfile ($file) { if (!isset($file)) { // JC 19/12/02 added $file to error message $this->_set_error('!isset file name!' . $file); return ''; } // check if filename is mapped to other filename if (isset($this->files)) { if (isset($this->files[$file])) { $file = $this->files[$file]; } } // prepend template dir if (!empty($this->tpldir)) { /** * Support hierarchy of file locations to search * * @example Supply array of filepaths when instantiating * First path supplied that has the named file is prioritised * $xtpl = new XTemplate('myfile.xtpl', array('.','/mypath', '/mypath2')); * @since 29/05/2007 */ if (is_array($this->tpldir)) { foreach ($this->tpldir as $dir) { if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) { $file = $dir . DIRECTORY_SEPARATOR . $file; break; } } } else { $file = $this->tpldir. DIRECTORY_SEPARATOR . $file; } } $file_text = ''; if (isset($this->filecache[$file])) { $file_text .= $this->filecache[$file]; if ($this->debug) { $file_text = '<!-- XTemplate debug cached: ' . realpath($file) . ' -->' . "\n" . $file_text; } } else { if (is_file($file) && is_readable($file)) { if (filesize($file)) { if (!($fh = fopen($file, 'r'))) { $this->_set_error('Cannot open file: ' . realpath($file)); return ''; } $file_text .= fread($fh,filesize($file)); fclose($fh); } if ($this->debug) { $file_text = '<!-- XTemplate debug: ' . realpath($file) . ' -->' . "\n" . $file_text; } } elseif (str_replace('.', '', phpversion()) >= '430' && $file_text = @file_get_contents($file, true)) { // Enable use of include path by using file_get_contents // Implemented at suggestion of SF Feature Request ID #1529478 michaelgroh if ($file_text === false) { $this->_set_error("[" . realpath($file) . "] ($file) does not exist"); $file_text = "<b>__XTemplate fatal error: file [$file] does not exist in the include path__</b>"; } elseif ($this->debug) { $file_text = '<!-- XTemplate debug: ' . realpath($file) . ' (via include path) -->' . "\n" . $file_text; } } elseif (!is_file($file)) { // NW 17 Oct 2002 : Added realpath around the file name to identify where the code is searching. $this->_set_error("[" . realpath($file) . "] ($file) does not exist"); $file_text .= "<b>__XTemplate fatal error: file [$file] does not exist__</b>"; } elseif (!is_readable($file)) { $this->_set_error("[" . realpath($file) . "] ($file) is not readable"); $file_text .= "<b>__XTemplate fatal error: file [$file] is not readable__</b>"; } $this->filecache[$file] = $file_text; } return $file_text; } /** * recursively gets the content of a file with {FILE "filename.tpl"} directives * * @access public - aiming for private * @param string $file * @return string */ public function _r_getfile ($file) { $text = $this->_getfile($file); $res = array(); while (preg_match($this->file_delim,$text,$res)) { $text2 = $this->_getfile($res[1]); $text = preg_replace("'".preg_quote($res[0])."'",$text2,$text); } return $text; } /** * add an outer block delimiter set useful for rtfs etc - keeps them editable in word * * @access private */ private function _add_outer_block () { $before = $this->block_start_delim . $this->block_start_word . ' ' . $this->mainblock . ' ' . $this->block_end_delim; $after = $this->block_start_delim . $this->block_end_word . ' ' . $this->mainblock . ' ' . $this->block_end_delim; $this->filecontents = $before . "\n" . $this->filecontents . "\n" . $after; } /** * Debug function - var_dump wrapped in '<pre></pre>' tags * * @access private * @param multiple var_dumps all the supplied arguments */ private function _pre_var_dump ($args) { if ($this->debug) { echo '<pre>'; var_dump(func_get_args()); echo '</pre>'; } } } /* end of XTemplate class. */ ?>
aleph3d/MiniMediaEducation
MasterServer/MSmmc-ps/plugins/plg-template/lib/xtemplate.class.php
PHP
mit
35,089
--TEST-- ldap_search() - operation that should fail --CREDITS-- Davide Mendolia <idaf1er@gmail.com> Belgian PHP Testfest 2009 --SKIPIF-- <?php require_once dirname(__FILE__) .'/skipif.inc'; ?> <?php require_once dirname(__FILE__) .'/skipifbindfailure.inc'; ?> --FILE-- <?php include "connect.inc"; $link = ldap_connect($host, $port); $dn = "dc=not-found,$base"; $filter = "(dc=*)"; $result = ldap_search(); var_dump($result); $result = ldap_search($link, $dn, $filter); var_dump($result); $result = ldap_search($link, $dn, $filter, NULL); var_dump($result); $result = ldap_search($link, $dn, $filter, array(1 => 'top')); var_dump($result); $result = ldap_search(array(), $dn, $filter, array('top')); var_dump($result); $result = ldap_search(array($link, $link), array($dn), $filter, array('top')); var_dump($result); $result = ldap_search(array($link, $link), $dn, array($filter), array('top')); var_dump($result); ?> ===DONE=== --EXPECTF-- Warning: ldap_search() expects at least 3 parameters, 0 given in %s on line %d NULL Warning: ldap_search(): Search: No such object in %s on line %d bool(false) Warning: ldap_search() expects parameter 4 to be array, null given in %s on line %d NULL Warning: ldap_search(): Array initialization wrong in %s on line %d bool(false) Warning: ldap_search(): No links in link array in %s on line %d bool(false) Warning: ldap_search(): Base must either be a string, or an array with the same number of elements as the links array in %s on line %d bool(false) Warning: ldap_search(): Filter must either be a string, or an array with the same number of elements as the links array in %s on line %d bool(false) ===DONE===
lunaczp/learning
language/c/testPhpSrc/php-5.6.17/ext/ldap/tests/ldap_search_error.phpt
PHP
mit
1,668
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\View; class DesignLoader { /** * Request * * @var \Magento\Framework\App\RequestInterface */ protected $_request; /** * Application * * @var \Magento\Framework\App\AreaList */ protected $_areaList; /** * Layout * * @var \Magento\Framework\App\State */ protected $appState; /** * @param \Magento\Framework\App\RequestInterface $request * @param \Magento\Framework\App\AreaList $areaList * @param \Magento\Framework\App\State $appState */ public function __construct( \Magento\Framework\App\RequestInterface $request, \Magento\Framework\App\AreaList $areaList, \Magento\Framework\App\State $appState ) { $this->_request = $request; $this->_areaList = $areaList; $this->appState = $appState; } /** * Load design * * @return void */ public function load() { $area = $this->_areaList->getArea($this->appState->getAreaCode()); $area->load(\Magento\Framework\App\Area::PART_DESIGN); $area->load(\Magento\Framework\App\Area::PART_TRANSLATE); $area->detectDesign($this->_request); } }
j-froehlich/magento2_wk
vendor/magento/framework/View/DesignLoader.php
PHP
mit
1,360
/** * Fixes an issue with Bootstrap Date Picker * @see https://github.com/angular-ui/bootstrap/issues/2659 * * How does it work? AngularJS allows multiple directives with the same name, * and each is treated independently though they are instantiated based on the * same element/attribute/comment. * * So this directive goes along with ui.bootstrap's datepicker-popup directive. * @see http://angular-ui.github.io/bootstrap/versioned-docs/0.12.0/#/datepicker */ export default function datepickerPopup() { return { restrict: 'EAC', require: 'ngModel', link: function(scope, element, attr, controller) { //remove the default formatter from the input directive to prevent conflict controller.$formatters.shift(); } }; } datepickerPopup.$inject = [];
manekinekko/ng-admin
src/javascripts/ng-admin/Crud/field/datepickerPopup.js
JavaScript
mit
823
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datamigration.v2018_03_31_preview; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * Database specific information for SQL to SQL migration task inputs. */ public class MigrateSqlServerSqlServerDatabaseInput { /** * Name of the database. */ @JsonProperty(value = "name") private String name; /** * Name of the database at destination. */ @JsonProperty(value = "restoreDatabaseName") private String restoreDatabaseName; /** * Backup file share information for this database. */ @JsonProperty(value = "backupFileShare") private FileShare backupFileShare; /** * The list of database files. */ @JsonProperty(value = "databaseFiles") private List<DatabaseFileInput> databaseFiles; /** * Get name of the database. * * @return the name value */ public String name() { return this.name; } /** * Set name of the database. * * @param name the name value to set * @return the MigrateSqlServerSqlServerDatabaseInput object itself. */ public MigrateSqlServerSqlServerDatabaseInput withName(String name) { this.name = name; return this; } /** * Get name of the database at destination. * * @return the restoreDatabaseName value */ public String restoreDatabaseName() { return this.restoreDatabaseName; } /** * Set name of the database at destination. * * @param restoreDatabaseName the restoreDatabaseName value to set * @return the MigrateSqlServerSqlServerDatabaseInput object itself. */ public MigrateSqlServerSqlServerDatabaseInput withRestoreDatabaseName(String restoreDatabaseName) { this.restoreDatabaseName = restoreDatabaseName; return this; } /** * Get backup file share information for this database. * * @return the backupFileShare value */ public FileShare backupFileShare() { return this.backupFileShare; } /** * Set backup file share information for this database. * * @param backupFileShare the backupFileShare value to set * @return the MigrateSqlServerSqlServerDatabaseInput object itself. */ public MigrateSqlServerSqlServerDatabaseInput withBackupFileShare(FileShare backupFileShare) { this.backupFileShare = backupFileShare; return this; } /** * Get the list of database files. * * @return the databaseFiles value */ public List<DatabaseFileInput> databaseFiles() { return this.databaseFiles; } /** * Set the list of database files. * * @param databaseFiles the databaseFiles value to set * @return the MigrateSqlServerSqlServerDatabaseInput object itself. */ public MigrateSqlServerSqlServerDatabaseInput withDatabaseFiles(List<DatabaseFileInput> databaseFiles) { this.databaseFiles = databaseFiles; return this; } }
navalev/azure-sdk-for-java
sdk/datamigration/mgmt-v2018_03_31_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_03_31_preview/MigrateSqlServerSqlServerDatabaseInput.java
Java
mit
3,305
/* YUI 3.7.2 (build 5639) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('editor-base', function (Y, NAME) { /** * Base class for Editor. Handles the business logic of Editor, no GUI involved only utility methods and events. * * var editor = new Y.EditorBase({ * content: 'Foo' * }); * editor.render('#demo'); * * @class EditorBase * @extends Base * @module editor * @main editor * @submodule editor-base * @constructor */ var EditorBase = function() { EditorBase.superclass.constructor.apply(this, arguments); }, LAST_CHILD = ':last-child', BODY = 'body'; Y.extend(EditorBase, Y.Base, { /** * Internal reference to the Y.Frame instance * @property frame */ frame: null, initializer: function() { var frame = new Y.Frame({ designMode: true, title: EditorBase.STRINGS.title, use: EditorBase.USE, dir: this.get('dir'), extracss: this.get('extracss'), linkedcss: this.get('linkedcss'), defaultblock: this.get('defaultblock'), host: this }).plug(Y.Plugin.ExecCommand); frame.after('ready', Y.bind(this._afterFrameReady, this)); frame.addTarget(this); this.frame = frame; this.publish('nodeChange', { emitFacade: true, bubbles: true, defaultFn: this._defNodeChangeFn }); //this.plug(Y.Plugin.EditorPara); }, destructor: function() { this.frame.destroy(); this.detachAll(); }, /** * Copy certain styles from one node instance to another (used for new paragraph creation mainly) * @method copyStyles * @param {Node} from The Node instance to copy the styles from * @param {Node} to The Node instance to copy the styles to */ copyStyles: function(from, to) { if (from.test('a')) { //Don't carry the A styles return; } var styles = ['color', 'fontSize', 'fontFamily', 'backgroundColor', 'fontStyle' ], newStyles = {}; Y.each(styles, function(v) { newStyles[v] = from.getStyle(v); }); if (from.ancestor('b,strong')) { newStyles.fontWeight = 'bold'; } if (from.ancestor('u')) { if (!newStyles.textDecoration) { newStyles.textDecoration = 'underline'; } } to.setStyles(newStyles); }, /** * Holder for the selection bookmark in IE. * @property _lastBookmark * @private */ _lastBookmark: null, /** * Resolves the e.changedNode in the nodeChange event if it comes from the document. If * the event came from the document, it will get the last child of the last child of the document * and return that instead. * @method _resolveChangedNode * @param {Node} n The node to resolve * @private */ _resolveChangedNode: function(n) { var inst = this.getInstance(), lc, lc2, found; if (n && n.test(BODY)) { var sel = new inst.EditorSelection(); if (sel && sel.anchorNode) { n = sel.anchorNode; } } if (inst && n && n.test('html')) { lc = inst.one(BODY).one(LAST_CHILD); while (!found) { if (lc) { lc2 = lc.one(LAST_CHILD); if (lc2) { lc = lc2; } else { found = true; } } else { found = true; } } if (lc) { if (lc.test('br')) { if (lc.previous()) { lc = lc.previous(); } else { lc = lc.get('parentNode'); } } if (lc) { n = lc; } } } if (!n) { //Fallback to make sure a node is attached to the event n = inst.one(BODY); } return n; }, /** * The default handler for the nodeChange event. * @method _defNodeChangeFn * @param {Event} e The event * @private */ _defNodeChangeFn: function(e) { var startTime = (new Date()).getTime(); //Y.log('Default nodeChange function: ' + e.changedType, 'info', 'editor'); var inst = this.getInstance(), sel, cur, btag = inst.EditorSelection.DEFAULT_BLOCK_TAG; if (Y.UA.ie) { try { sel = inst.config.doc.selection.createRange(); if (sel.getBookmark) { this._lastBookmark = sel.getBookmark(); } } catch (ie) {} } e.changedNode = this._resolveChangedNode(e.changedNode); /* * @TODO * This whole method needs to be fixed and made more dynamic. * Maybe static functions for the e.changeType and an object bag * to walk through and filter to pass off the event to before firing.. */ switch (e.changedType) { case 'keydown': if (!Y.UA.gecko) { if (!EditorBase.NC_KEYS[e.changedEvent.keyCode] && !e.changedEvent.shiftKey && !e.changedEvent.ctrlKey && (e.changedEvent.keyCode !== 13)) { //inst.later(100, inst, inst.EditorSelection.cleanCursor); } } break; case 'tab': if (!e.changedNode.test('li, li *') && !e.changedEvent.shiftKey) { e.changedEvent.frameEvent.preventDefault(); Y.log('Overriding TAB key to insert HTML: HALTING', 'info', 'editor'); if (Y.UA.webkit) { this.execCommand('inserttext', '\t'); } else if (Y.UA.gecko) { this.frame.exec._command('inserthtml', EditorBase.TABKEY); } else if (Y.UA.ie) { this.execCommand('inserthtml', EditorBase.TABKEY); } } break; case 'backspace-up': // Fixes #2531090 - Joins text node strings so they become one for bidi if (Y.UA.webkit && e.changedNode) { e.changedNode.set('innerHTML', e.changedNode.get('innerHTML')); } break; } if (Y.UA.webkit && e.commands && (e.commands.indent || e.commands.outdent)) { /* * When executing execCommand 'indent or 'outdent' Webkit applies * a class to the BLOCKQUOTE that adds left/right margin to it * This strips that style so it is just a normal BLOCKQUOTE */ var bq = inst.all('.webkit-indent-blockquote, blockquote'); if (bq.size()) { bq.setStyle('margin', ''); } } var changed = this.getDomPath(e.changedNode, false), cmds = {}, family, fsize, classes = [], fColor = '', bColor = ''; if (e.commands) { cmds = e.commands; } var normal = false; Y.each(changed, function(el) { var tag = el.tagName.toLowerCase(), cmd = EditorBase.TAG2CMD[tag]; if (cmd) { cmds[cmd] = 1; } //Bold and Italic styles var s = el.currentStyle || el.style; if ((''+s.fontWeight) == 'normal') { normal = true; } if ((''+s.fontWeight) == 'bold') { //Cast this to a string cmds.bold = 1; } if (Y.UA.ie) { if (s.fontWeight > 400) { cmds.bold = 1; } } if (s.fontStyle == 'italic') { cmds.italic = 1; } if (s.textDecoration.indexOf('underline') > -1) { cmds.underline = 1; } if (s.textDecoration.indexOf('line-through') > -1) { cmds.strikethrough = 1; } var n = inst.one(el); if (n.getStyle('fontFamily')) { var family2 = n.getStyle('fontFamily').split(',')[0].toLowerCase(); if (family2) { family = family2; } if (family) { family = family.replace(/'/g, '').replace(/"/g, ''); } } fsize = EditorBase.NORMALIZE_FONTSIZE(n); var cls = el.className.split(' '); Y.each(cls, function(v) { if (v !== '' && (v.substr(0, 4) !== 'yui_')) { classes.push(v); } }); fColor = EditorBase.FILTER_RGB(n.getStyle('color')); var bColor2 = EditorBase.FILTER_RGB(s.backgroundColor); if (bColor2 !== 'transparent') { if (bColor2 !== '') { bColor = bColor2; } } }); if (normal) { delete cmds.bold; delete cmds.italic; } e.dompath = inst.all(changed); e.classNames = classes; e.commands = cmds; //TODO Dont' like this, not dynamic enough.. if (!e.fontFamily) { e.fontFamily = family; } if (!e.fontSize) { e.fontSize = fsize; } if (!e.fontColor) { e.fontColor = fColor; } if (!e.backgroundColor) { e.backgroundColor = bColor; } var endTime = (new Date()).getTime(); Y.log('_defNodeChangeTimer 2: ' + (endTime - startTime) + 'ms', 'info', 'selection'); }, /** * Walk the dom tree from this node up to body, returning a reversed array of parents. * @method getDomPath * @param {Node} node The Node to start from */ getDomPath: function(node, nodeList) { var domPath = [], domNode, inst = this.frame.getInstance(); domNode = inst.Node.getDOMNode(node); //return inst.all(domNode); while (domNode !== null) { if ((domNode === inst.config.doc.documentElement) || (domNode === inst.config.doc) || !domNode.tagName) { domNode = null; break; } if (!inst.DOM.inDoc(domNode)) { domNode = null; break; } //Check to see if we get el.nodeName and nodeType if (domNode.nodeName && domNode.nodeType && (domNode.nodeType == 1)) { domPath.push(domNode); } if (domNode == inst.config.doc.body) { domNode = null; break; } domNode = domNode.parentNode; } /*{{{ Using Node while (node !== null) { if (node.test('html') || node.test('doc') || !node.get('tagName')) { node = null; break; } if (!node.inDoc()) { node = null; break; } //Check to see if we get el.nodeName and nodeType if (node.get('nodeName') && node.get('nodeType') && (node.get('nodeType') == 1)) { domPath.push(inst.Node.getDOMNode(node)); } if (node.test('body')) { node = null; break; } node = node.get('parentNode'); } }}}*/ if (domPath.length === 0) { domPath[0] = inst.config.doc.body; } if (nodeList) { return inst.all(domPath.reverse()); } else { return domPath.reverse(); } }, /** * After frame ready, bind mousedown & keyup listeners * @method _afterFrameReady * @private */ _afterFrameReady: function() { var inst = this.frame.getInstance(); this.frame.on('dom:mouseup', Y.bind(this._onFrameMouseUp, this)); this.frame.on('dom:mousedown', Y.bind(this._onFrameMouseDown, this)); this.frame.on('dom:keydown', Y.bind(this._onFrameKeyDown, this)); if (Y.UA.ie) { this.frame.on('dom:activate', Y.bind(this._onFrameActivate, this)); this.frame.on('dom:beforedeactivate', Y.bind(this._beforeFrameDeactivate, this)); } this.frame.on('dom:keyup', Y.bind(this._onFrameKeyUp, this)); this.frame.on('dom:keypress', Y.bind(this._onFrameKeyPress, this)); this.frame.on('dom:paste', Y.bind(this._onPaste, this)); inst.EditorSelection.filter(); this.fire('ready'); }, /** * Caches the current cursor position in IE. * @method _beforeFrameDeactivate * @private */ _beforeFrameDeactivate: function(e) { if (e.frameTarget.test('html')) { //Means it came from a scrollbar return; } var inst = this.getInstance(), sel = inst.config.doc.selection.createRange(); if (sel.compareEndPoints && !sel.compareEndPoints('StartToEnd', sel)) { sel.pasteHTML('<var id="yui-ie-cursor">'); } }, /** * Moves the cached selection bookmark back so IE can place the cursor in the right place. * @method _onFrameActivate * @private */ _onFrameActivate: function(e) { if (e.frameTarget.test('html')) { //Means it came from a scrollbar return; } var inst = this.getInstance(), sel = new inst.EditorSelection(), range = sel.createRange(), cur = inst.all('#yui-ie-cursor'); if (cur.size()) { cur.each(function(n) { n.set('id', ''); if (range.moveToElementText) { try { range.moveToElementText(n._node); var moved = range.move('character', -1); if (moved === -1) { //Only move up if we actually moved back. range.move('character', 1); } range.select(); range.text = ''; } catch (e) {} } n.remove(); }); } }, /** * Fires nodeChange event * @method _onPaste * @private */ _onPaste: function(e) { this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'paste', changedEvent: e.frameEvent }); }, /** * Fires nodeChange event * @method _onFrameMouseUp * @private */ _onFrameMouseUp: function(e) { this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mouseup', changedEvent: e.frameEvent }); }, /** * Fires nodeChange event * @method _onFrameMouseDown * @private */ _onFrameMouseDown: function(e) { this.fire('nodeChange', { changedNode: e.frameTarget, changedType: 'mousedown', changedEvent: e.frameEvent }); }, /** * Caches a copy of the selection for key events. Only creating the selection on keydown * @property _currentSelection * @private */ _currentSelection: null, /** * Holds the timer for selection clearing * @property _currentSelectionTimer * @private */ _currentSelectionTimer: null, /** * Flag to determine if we can clear the selection or not. * @property _currentSelectionClear * @private */ _currentSelectionClear: null, /** * Fires nodeChange event * @method _onFrameKeyDown * @private */ _onFrameKeyDown: function(e) { var inst, sel; if (!this._currentSelection) { if (this._currentSelectionTimer) { this._currentSelectionTimer.cancel(); } this._currentSelectionTimer = Y.later(850, this, function() { this._currentSelectionClear = true; }); inst = this.frame.getInstance(); sel = new inst.EditorSelection(e); this._currentSelection = sel; } else { sel = this._currentSelection; } inst = this.frame.getInstance(); sel = new inst.EditorSelection(); this._currentSelection = sel; if (sel && sel.anchorNode) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keydown', changedEvent: e.frameEvent }); if (EditorBase.NC_KEYS[e.keyCode]) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode], changedEvent: e.frameEvent }); this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-down', changedEvent: e.frameEvent }); } } }, /** * Fires nodeChange event * @method _onFrameKeyPress * @private */ _onFrameKeyPress: function(e) { var sel = this._currentSelection; if (sel && sel.anchorNode) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keypress', changedEvent: e.frameEvent }); if (EditorBase.NC_KEYS[e.keyCode]) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-press', changedEvent: e.frameEvent }); } } }, /** * Fires nodeChange event for keyup on specific keys * @method _onFrameKeyUp * @private */ _onFrameKeyUp: function(e) { var inst = this.frame.getInstance(), sel = new inst.EditorSelection(e); if (sel && sel.anchorNode) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: 'keyup', selection: sel, changedEvent: e.frameEvent }); if (EditorBase.NC_KEYS[e.keyCode]) { this.fire('nodeChange', { changedNode: sel.anchorNode, changedType: EditorBase.NC_KEYS[e.keyCode] + '-up', selection: sel, changedEvent: e.frameEvent }); } } if (this._currentSelectionClear) { this._currentSelectionClear = this._currentSelection = null; } }, /** * Pass through to the frame.execCommand method * @method execCommand * @param {String} cmd The command to pass: inserthtml, insertimage, bold * @param {String} val The optional value of the command: Helvetica * @return {Node/NodeList} The Node or Nodelist affected by the command. Only returns on override commands, not browser defined commands. */ execCommand: function(cmd, val) { var ret = this.frame.execCommand(cmd, val), inst = this.frame.getInstance(), sel = new inst.EditorSelection(), cmds = {}, e = { changedNode: sel.anchorNode, changedType: 'execcommand', nodes: ret }; switch (cmd) { case 'forecolor': e.fontColor = val; break; case 'backcolor': e.backgroundColor = val; break; case 'fontsize': e.fontSize = val; break; case 'fontname': e.fontFamily = val; break; } cmds[cmd] = 1; e.commands = cmds; this.fire('nodeChange', e); return ret; }, /** * Get the YUI instance of the frame * @method getInstance * @return {YUI} The YUI instance bound to the frame. */ getInstance: function() { return this.frame.getInstance(); }, /** * Renders the Y.Frame to the passed node. * @method render * @param {Selector/HTMLElement/Node} node The node to append the Editor to * @return {EditorBase} * @chainable */ render: function(node) { this.frame.set('content', this.get('content')); this.frame.render(node); return this; }, /** * Focus the contentWindow of the iframe * @method focus * @param {Function} fn Callback function to execute after focus happens * @return {EditorBase} * @chainable */ focus: function(fn) { this.frame.focus(fn); return this; }, /** * Handles the showing of the Editor instance. Currently only handles the iframe * @method show * @return {EditorBase} * @chainable */ show: function() { this.frame.show(); return this; }, /** * Handles the hiding of the Editor instance. Currently only handles the iframe * @method hide * @return {EditorBase} * @chainable */ hide: function() { this.frame.hide(); return this; }, /** * (Un)Filters the content of the Editor, cleaning YUI related code. //TODO better filtering * @method getContent * @return {String} The filtered content of the Editor */ getContent: function() { var html = '', inst = this.getInstance(); if (inst && inst.EditorSelection) { html = inst.EditorSelection.unfilter(); } //Removing the _yuid from the objects in IE html = html.replace(/ _yuid="([^>]*)"/g, ''); return html; } }, { /** * @static * @method NORMALIZE_FONTSIZE * @description Pulls the fontSize from a node, then checks for string values (x-large, x-small) * and converts them to pixel sizes. If the parsed size is different from the original, it calls * node.setStyle to update the node with a pixel size for normalization. */ NORMALIZE_FONTSIZE: function(n) { var size = n.getStyle('fontSize'), oSize = size; switch (size) { case '-webkit-xxx-large': size = '48px'; break; case 'xx-large': size = '32px'; break; case 'x-large': size = '24px'; break; case 'large': size = '18px'; break; case 'medium': size = '16px'; break; case 'small': size = '13px'; break; case 'x-small': size = '10px'; break; } if (oSize !== size) { n.setStyle('fontSize', size); } return size; }, /** * @static * @property TABKEY * @description The HTML markup to use for the tabkey */ TABKEY: '<span class="tab">&nbsp;&nbsp;&nbsp;&nbsp;</span>', /** * @static * @method FILTER_RGB * @param String css The CSS string containing rgb(#,#,#); * @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00 * @return String */ FILTER_RGB: function(css) { if (css.toLowerCase().indexOf('rgb') != -1) { var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi"); var rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(','); if (rgb.length == 5) { var r = parseInt(rgb[1], 10).toString(16); var g = parseInt(rgb[2], 10).toString(16); var b = parseInt(rgb[3], 10).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; css = "#" + r + g + b; } } return css; }, /** * @static * @property TAG2CMD * @description A hash table of tags to their execcomand's */ TAG2CMD: { 'b': 'bold', 'strong': 'bold', 'i': 'italic', 'em': 'italic', 'u': 'underline', 'sup': 'superscript', 'sub': 'subscript', 'img': 'insertimage', 'a' : 'createlink', 'ul' : 'insertunorderedlist', 'ol' : 'insertorderedlist' }, /** * Hash table of keys to fire a nodeChange event for. * @static * @property NC_KEYS * @type Object */ NC_KEYS: { 8: 'backspace', 9: 'tab', 13: 'enter', 32: 'space', 33: 'pageup', 34: 'pagedown', 35: 'end', 36: 'home', 37: 'left', 38: 'up', 39: 'right', 40: 'down', 46: 'delete' }, /** * The default modules to use inside the Frame * @static * @property USE * @type Array */ USE: ['substitute', 'node', 'selector-css3', 'editor-selection', 'stylesheet'], /** * The Class Name: editorBase * @static * @property NAME */ NAME: 'editorBase', /** * Editor Strings. By default contains only the `title` property for the * Title of frame document (default "Rich Text Editor"). * * @static * @property STRINGS */ STRINGS: { title: 'Rich Text Editor' }, ATTRS: { /** * The content to load into the Editor Frame * @attribute content */ content: { value: '<br class="yui-cursor">', setter: function(str) { if (str.substr(0, 1) === "\n") { Y.log('Stripping first carriage return from content before injecting', 'warn', 'editor'); str = str.substr(1); } if (str === '') { str = '<br class="yui-cursor">'; } if (str === ' ') { if (Y.UA.gecko) { str = '<br class="yui-cursor">'; } } return this.frame.set('content', str); }, getter: function() { return this.frame.get('content'); } }, /** * The value of the dir attribute on the HTML element of the frame. Default: ltr * @attribute dir */ dir: { writeOnce: true, value: 'ltr' }, /** * @attribute linkedcss * @description An array of url's to external linked style sheets * @type String */ linkedcss: { value: '', setter: function(css) { if (this.frame) { this.frame.set('linkedcss', css); } return css; } }, /** * @attribute extracss * @description A string of CSS to add to the Head of the Editor * @type String */ extracss: { value: false, setter: function(css) { if (this.frame) { this.frame.set('extracss', css); } return css; } }, /** * @attribute defaultblock * @description The default tag to use for block level items, defaults to: p * @type String */ defaultblock: { value: 'p' } } }); Y.EditorBase = EditorBase; /** * @event nodeChange * @description Fired from several mouse/key/paste event points. * @param {Event.Facade} event An Event Facade object with the following specific properties added: * <dl> * <dt>changedEvent</dt><dd>The event that caused the nodeChange</dd> * <dt>changedNode</dt><dd>The node that was interacted with</dd> * <dt>changedType</dt><dd>The type of change: mousedown, mouseup, right, left, backspace, tab, enter, etc..</dd> * <dt>commands</dt><dd>The list of execCommands that belong to this change and the dompath that's associated with the changedNode</dd> * <dt>classNames</dt><dd>An array of classNames that are applied to the changedNode and all of it's parents</dd> * <dt>dompath</dt><dd>A sorted array of node instances that make up the DOM path from the changedNode to body.</dd> * <dt>backgroundColor</dt><dd>The cascaded backgroundColor of the changedNode</dd> * <dt>fontColor</dt><dd>The cascaded fontColor of the changedNode</dd> * <dt>fontFamily</dt><dd>The cascaded fontFamily of the changedNode</dd> * <dt>fontSize</dt><dd>The cascaded fontSize of the changedNode</dd> * </dl> * @type {Event.Custom} */ /** * @event ready * @description Fired after the frame is ready. * @param {Event.Facade} event An Event Facade object. * @type {Event.Custom} */ }, '3.7.2', {"requires": ["base", "frame", "node", "exec-command", "editor-selection"]});
spadin/coverphoto
node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/editor-base/editor-base-debug.js
JavaScript
mit
32,357
// Copyright (c) The HLSL2GLSLFork Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE.txt file. #include "localintermediate.h" // // Two purposes: // 1. Show an example of how to iterate tree. Functions can // also directly call Traverse() on children themselves to // have finer grained control over the process than shown here. // See the last function for how to get started. // 2. Print out a text based description of the tree. // // // Use this class to carry along data from node to node in // the traversal // class TOutputTraverser : public TIntermTraverser { public: TOutputTraverser(TInfoSink& i) : infoSink(i) { } TInfoSink& infoSink; }; TString TType::getCompleteString() const { char buf[100]; char *p = &buf[0]; if (qualifier != EvqTemporary && qualifier != EvqGlobal) p += sprintf(p, "%s ", getQualifierString()); sprintf(p, "%s", getBasicString()); if (array) p += sprintf(p, " array"); if (matrix) p += sprintf(p, "matrix%dX%d", matcols, matrows); else if (matrows > 1) p += sprintf(p, "vec%d", matrows); return TString(buf); } // // Helper functions for printing, not part of traversing. // void OutputTreeText(TInfoSink& infoSink, TIntermNode* node, const int depth) { int i; infoSink.debug << node->getLine(); for (i = 0; i < depth; ++i) infoSink.debug << " "; } // // The rest of the file are the traversal functions. The last one // is the one that starts the traversal. // // Return true from interior nodes to have the external traversal // continue on to children. If you process children yourself, // return false. // void OutputSymbol(TIntermSymbol* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); OutputTreeText(oit->infoSink, node, oit->depth); char buf[100]; sprintf(buf, "'%s' (%s)\n", node->getSymbol().c_str(), node->getCompleteString().c_str()); oit->infoSink.debug << buf; } bool OutputBinary(bool, /* preVisit */ TIntermBinary* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; OutputTreeText(out, node, oit->depth); switch (node->getOp()) { case EOpAssign: out.debug << "="; break; case EOpAddAssign: out.debug << "+="; break; case EOpSubAssign: out.debug << "-="; break; case EOpMulAssign: out.debug << "*="; break; case EOpVectorTimesMatrixAssign: out.debug << "vec *= matrix"; break; case EOpVectorTimesScalarAssign: out.debug << "vec *= scalar"; break; case EOpMatrixTimesScalarAssign: out.debug << "matrix *= scalar"; break; case EOpMatrixTimesMatrixAssign: out.debug << "matrix *= matrix"; break; case EOpDivAssign: out.debug << "/="; break; case EOpModAssign: out.debug << "%="; break; case EOpAndAssign: out.debug << "&="; break; case EOpInclusiveOrAssign: out.debug << "|="; break; case EOpExclusiveOrAssign: out.debug << "^="; break; case EOpLeftShiftAssign: out.debug << "<<="; break; case EOpRightShiftAssign: out.debug << ">>="; break; case EOpIndexDirect: out.debug << "index"; break; case EOpIndexIndirect: out.debug << "indirect index"; break; case EOpIndexDirectStruct: out.debug << "struct index"; break; case EOpVectorSwizzle: out.debug << "swizzle"; break; case EOpAdd: out.debug << "+"; break; case EOpSub: out.debug << "-"; break; case EOpMul: out.debug << "*"; break; case EOpDiv: out.debug << "/"; break; case EOpMod: out.debug << "%"; break; case EOpRightShift: out.debug << ">>"; break; case EOpLeftShift: out.debug << "<<"; break; case EOpAnd: out.debug << "&"; break; case EOpInclusiveOr: out.debug << "|"; break; case EOpExclusiveOr: out.debug << "^"; break; case EOpEqual: out.debug << "=="; break; case EOpNotEqual: out.debug << "!="; break; case EOpLessThan: out.debug << "<"; break; case EOpGreaterThan: out.debug << ">"; break; case EOpLessThanEqual: out.debug << "<="; break; case EOpGreaterThanEqual: out.debug << ">="; break; case EOpVectorTimesScalar: out.debug << "vec*scalar"; break; case EOpVectorTimesMatrix: out.debug << "vec*matrix"; break; case EOpMatrixTimesVector: out.debug << "matrix*vec"; break; case EOpMatrixTimesScalar: out.debug << "matrix*scalar"; break; case EOpMatrixTimesMatrix: out.debug << "matrix*matrix"; break; case EOpLogicalOr: out.debug << "||"; break; case EOpLogicalXor: out.debug << "^^"; break; case EOpLogicalAnd: out.debug << "&&"; break; default: out.debug << "<unknown op>"; } out.debug << " (" << node->getCompleteString() << ")"; out.debug << "\n"; return true; } bool OutputUnary(bool, /* preVisit */ TIntermUnary* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; OutputTreeText(out, node, oit->depth); switch (node->getOp()) { case EOpNegative: out.debug << "Negate value"; break; case EOpVectorLogicalNot: case EOpLogicalNot: out.debug << "Negate conditional"; break; case EOpBitwiseNot: out.debug << "Bitwise not"; break; case EOpPostIncrement: out.debug << "Post-Increment"; break; case EOpPostDecrement: out.debug << "Post-Decrement"; break; case EOpPreIncrement: out.debug << "Pre-Increment"; break; case EOpPreDecrement: out.debug << "Pre-Decrement"; break; case EOpConvIntToBool: out.debug << "Convert int to bool"; break; case EOpConvFloatToBool:out.debug << "Convert float to bool";break; case EOpConvBoolToFloat:out.debug << "Convert bool to float";break; case EOpConvIntToFloat: out.debug << "Convert int to float"; break; case EOpConvFloatToInt: out.debug << "Convert float to int"; break; case EOpConvBoolToInt: out.debug << "Convert bool to int"; break; case EOpRadians: out.debug << "radians"; break; case EOpDegrees: out.debug << "degrees"; break; case EOpSin: out.debug << "sine"; break; case EOpCos: out.debug << "cosine"; break; case EOpTan: out.debug << "tangent"; break; case EOpAsin: out.debug << "arc sine"; break; case EOpAcos: out.debug << "arc cosine"; break; case EOpAtan: out.debug << "arc tangent"; break; case EOpAtan2: out.debug << "arc tangent 2"; break; case EOpExp: out.debug << "exp"; break; case EOpLog: out.debug << "log"; break; case EOpExp2: out.debug << "exp2"; break; case EOpLog2: out.debug << "log2"; break; case EOpLog10: out.debug << "log10"; break; case EOpSqrt: out.debug << "sqrt"; break; case EOpInverseSqrt: out.debug << "inverse sqrt"; break; case EOpAbs: out.debug << "Absolute value"; break; case EOpSign: out.debug << "Sign"; break; case EOpFloor: out.debug << "Floor"; break; case EOpCeil: out.debug << "Ceiling"; break; case EOpFract: out.debug << "Fraction"; break; case EOpLength: out.debug << "length"; break; case EOpNormalize: out.debug << "normalize"; break; case EOpDPdx: out.debug << "dPdx"; break; case EOpDPdy: out.debug << "dPdy"; break; case EOpFwidth: out.debug << "fwidth"; break; case EOpFclip: out.debug << "clip"; break; case EOpAny: out.debug << "any"; break; case EOpAll: out.debug << "all"; break; case EOpD3DCOLORtoUBYTE4: out.debug << "D3DCOLORtoUBYTE4"; break; default: out.debug.message(EPrefixError, "Bad unary op"); } out.debug << " (" << node->getCompleteString() << ")"; out.debug << "\n"; return true; } bool OutputAggregate(bool, /* preVisit */ TIntermAggregate* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; if (node->getOp() == EOpNull) { out.debug.message(EPrefixError, "node is still EOpNull!"); return true; } OutputTreeText(out, node, oit->depth); switch (node->getOp()) { case EOpSequence: out.debug << "Sequence\n"; return true; case EOpComma: out.debug << "Comma\n"; return true; case EOpFunction: out.debug << "Func Def: " << node->getName(); break; case EOpFunctionCall: out.debug << "Func Call: " << node->getName(); break; case EOpParameters: out.debug << "Func Params: "; break; case EOpConstructFloat: out.debug << "Construct float"; break; case EOpConstructVec2: out.debug << "Construct vec2"; break; case EOpConstructVec3: out.debug << "Construct vec3"; break; case EOpConstructVec4: out.debug << "Construct vec4"; break; case EOpConstructBool: out.debug << "Construct bool"; break; case EOpConstructBVec2: out.debug << "Construct bvec2"; break; case EOpConstructBVec3: out.debug << "Construct bvec3"; break; case EOpConstructBVec4: out.debug << "Construct bvec4"; break; case EOpConstructInt: out.debug << "Construct int"; break; case EOpConstructIVec2: out.debug << "Construct ivec2"; break; case EOpConstructIVec3: out.debug << "Construct ivec3"; break; case EOpConstructIVec4: out.debug << "Construct ivec4"; break; case EOpConstructMat2x2: out.debug << "Construct mat2x2"; break; case EOpConstructMat2x3: out.debug << "Construct mat2x3"; break; case EOpConstructMat2x4: out.debug << "Construct mat2x4"; break; case EOpConstructMat3x2: out.debug << "Construct mat3x2"; break; case EOpConstructMat3x3: out.debug << "Construct mat3x3"; break; case EOpConstructMat3x4: out.debug << "Construct mat3x4"; break; case EOpConstructMat4x2: out.debug << "Construct mat4x2"; break; case EOpConstructMat4x3: out.debug << "Construct mat4x3"; break; case EOpConstructMat4x4: out.debug << "Construct mat4x4"; break; case EOpConstructStruct: out.debug << "Construct struc"; break; case EOpConstructMat2x2FromMat: out.debug << "Construct mat2 from mat"; break; case EOpConstructMat3x3FromMat: out.debug << "Construct mat3 from mat"; break; case EOpMatrixIndex: out.debug << "Matrix index"; break; case EOpMatrixIndexDynamic: out.debug << "Matrix index dynamic"; break; case EOpLessThan: out.debug << "Compare Less Than"; break; case EOpGreaterThan: out.debug << "Compare Greater Than"; break; case EOpLessThanEqual: out.debug << "Compare Less Than or Equal"; break; case EOpGreaterThanEqual: out.debug << "Compare Greater Than or Equal"; break; case EOpVectorEqual: out.debug << "Equal"; break; case EOpVectorNotEqual: out.debug << "NotEqual"; break; case EOpMod: out.debug << "mod"; break; case EOpPow: out.debug << "pow"; break; case EOpAtan: out.debug << "atan"; break; case EOpAtan2: out.debug << "atan2"; break; case EOpSinCos: out.debug << "sincos"; break; case EOpMin: out.debug << "min"; break; case EOpMax: out.debug << "max"; break; case EOpClamp: out.debug << "clamp"; break; case EOpMix: out.debug << "mix"; break; case EOpStep: out.debug << "step"; break; case EOpSmoothStep: out.debug << "smoothstep"; break; case EOpLit: out.debug << "lit"; break; case EOpDistance: out.debug << "distance"; break; case EOpDot: out.debug << "dot"; break; case EOpCross: out.debug << "cross"; break; case EOpFaceForward: out.debug << "faceforward"; break; case EOpReflect: out.debug << "reflect"; break; case EOpRefract: out.debug << "refract"; break; case EOpMul: out.debug << "mul"; break; case EOpTex1D: out.debug << "tex1D"; break; case EOpTex1DProj: out.debug << "tex1Dproj"; break; case EOpTex1DLod: out.debug << "tex1Dlod"; break; case EOpTex1DBias: out.debug << "tex1Dbias"; break; case EOpTex1DGrad: out.debug << "tex1Dgrad"; break; case EOpTex2D: out.debug << "tex2D"; break; case EOpTex2DProj: out.debug << "tex2Dproj"; break; case EOpTex2DLod: out.debug << "tex2Dlod"; break; case EOpTex2DBias: out.debug << "tex2Dbias"; break; case EOpTex2DGrad: out.debug << "tex2Dgrad"; break; case EOpTex3D: out.debug << "tex3D"; break; case EOpTex3DProj: out.debug << "tex3Dproj"; break; case EOpTex3DLod: out.debug << "tex3Dlod"; break; case EOpTex3DBias: out.debug << "tex3Dbias"; break; case EOpTex3DGrad: out.debug << "tex3Dgrad"; break; case EOpTexCube: out.debug << "texCUBE"; break; case EOpTexCubeProj: out.debug << "texCUBEproj"; break; case EOpTexCubeLod: out.debug << "texCUBElod"; break; case EOpTexCubeBias: out.debug << "texCUBEbias"; break; case EOpTexCubeGrad: out.debug << "texCUBEgrad"; break; case EOpTexRect: out.debug << "texRECT"; break; case EOpTexRectProj: out.debug << "texRECTproj"; break; case EOpShadow2D: out.debug << "shadow2D"; break; case EOpShadow2DProj:out.debug << "shadow2Dproj"; break; case EOpTex2DArray: out.debug << "tex2DArray"; break; case EOpTex2DArrayLod: out.debug << "tex2DArrayLod"; break; case EOpTex2DArrayBias: out.debug << "tex2DArrayBias"; break; default: out.debug.message(EPrefixError, "Bad aggregation op"); } if (node->getOp() != EOpSequence && node->getOp() != EOpParameters) out.debug << " (" << node->getCompleteString() << ")"; out.debug << "\n"; return true; } bool OutputSelection(bool, /* preVisit */ TIntermSelection* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; OutputTreeText(out, node, oit->depth); out.debug << "ternary ?:"; out.debug << " (" << node->getCompleteString() << ")\n"; ++oit->depth; OutputTreeText(oit->infoSink, node, oit->depth); out.debug << "Condition\n"; node->getCondition()->traverse(it); OutputTreeText(oit->infoSink, node, oit->depth); if (node->getTrueBlock()) { out.debug << "true case\n"; node->getTrueBlock()->traverse(it); } else out.debug << "true case is null\n"; if (node->getFalseBlock()) { OutputTreeText(oit->infoSink, node, oit->depth); out.debug << "false case\n"; node->getFalseBlock()->traverse(it); } --oit->depth; return false; } void OutputConstant(TIntermConstant* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; int size = node->getCount(); for (int i = 0; i < size; i++) { OutputTreeText(out, node, oit->depth); switch (node->getValue(i).type) { case EbtBool: if (node->toBool(i)) out.debug << "true"; else out.debug << "false"; out.debug << " (" << "const bool" << ")"; out.debug << "\n"; break; case EbtFloat: { char buf[300]; sprintf(buf, "%f (%s)", node->toFloat(i), "const float"); out.debug << buf << "\n"; } break; case EbtInt: { char buf[300]; sprintf(buf, "%d (%s)", node->toInt(i), "const int"); out.debug << buf << "\n"; break; } default: out.info.message(EPrefixInternalError, "Unknown constant", node->getLine()); break; } } } bool OutputLoop(bool, /* preVisit */ TIntermLoop* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; OutputTreeText(out, node, oit->depth); out.debug << "Loop with condition "; if (node->getType() == ELoopDoWhile) out.debug << "not "; out.debug << "tested first\n"; ++oit->depth; OutputTreeText(oit->infoSink, node, oit->depth); if (node->getCondition()) { out.debug << "Loop Condition\n"; node->getCondition()->traverse(it); } else out.debug << "No loop condition\n"; OutputTreeText(oit->infoSink, node, oit->depth); if (node->getBody()) { out.debug << "Loop Body\n"; node->getBody()->traverse(it); } else out.debug << "No loop body\n"; if (node->getExpression()) { OutputTreeText(oit->infoSink, node, oit->depth); out.debug << "Loop Terminal Expression\n"; node->getExpression()->traverse(it); } --oit->depth; return false; } bool OutputBranch(bool, /* previsit*/ TIntermBranch* node, TIntermTraverser* it) { TOutputTraverser* oit = static_cast<TOutputTraverser*>(it); TInfoSink& out = oit->infoSink; OutputTreeText(out, node, oit->depth); switch (node->getFlowOp()) { case EOpKill: out.debug << "Branch: Kill"; break; case EOpBreak: out.debug << "Branch: Break"; break; case EOpContinue: out.debug << "Branch: Continue"; break; case EOpReturn: out.debug << "Branch: Return"; break; default: out.debug << "Branch: Unknown Branch"; break; } if (node->getExpression()) { out.debug << " with expression\n"; ++oit->depth; node->getExpression()->traverse(it); --oit->depth; } else out.debug << "\n"; return false; } void ir_output_tree(TIntermNode* root, TInfoSink& infoSink) { if (root == 0) return; TOutputTraverser it(infoSink); it.visitAggregate = OutputAggregate; it.visitBinary = OutputBinary; it.visitConstant = OutputConstant; it.visitSelection = OutputSelection; it.visitSymbol = OutputSymbol; it.visitUnary = OutputUnary; it.visitLoop = OutputLoop; it.visitBranch = OutputBranch; root->traverse(&it); }
lriki/LNSL
src/hlsl2glslfork/hlslang/MachineIndependent/intermOut.cpp
C++
mit
18,856
/** * Copyright 2017 Google Inc. * * 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. */ import { fail } from '../util/assert'; /** * PersistencePromise<> is essentially a re-implementation of Promise<> except * it has a .next() method instead of .then() and .next() and .catch() callbacks * are executed synchronously when a PersistencePromise resolves rather than * asynchronously (Promise<> implementations use setImmediate() or similar). * * This is necessary to interoperate with IndexedDB which will automatically * commit transactions if control is returned to the event loop without * synchronously initiating another operation on the transaction. * * NOTE: .then() and .catch() only allow a single consumer, unlike normal * Promises. */ var PersistencePromise = /** @class */ (function () { function PersistencePromise(callback) { var _this = this; // NOTE: next/catchCallback will always point to our own wrapper functions, // not the user's raw next() or catch() callbacks. this.nextCallback = null; this.catchCallback = null; // When the operation resolves, we'll set result or error and mark isDone. this.result = undefined; this.error = null; this.isDone = false; // Set to true when .then() or .catch() are called and prevents additional // chaining. this.callbackAttached = false; callback(function (value) { _this.isDone = true; _this.result = value; if (_this.nextCallback) { // value should be defined unless T is Void, but we can't express // that in the type system. _this.nextCallback(value); } }, function (error) { _this.isDone = true; _this.error = error; if (_this.catchCallback) { _this.catchCallback(error); } }); } PersistencePromise.prototype.catch = function (fn) { return this.next(undefined, fn); }; PersistencePromise.prototype.next = function (nextFn, catchFn) { var _this = this; if (this.callbackAttached) { fail('Called next() or catch() twice for PersistencePromise'); } this.callbackAttached = true; if (this.isDone) { if (!this.error) { return this.wrapSuccess(nextFn, this.result); } else { return this.wrapFailure(catchFn, this.error); } } else { return new PersistencePromise(function (resolve, reject) { _this.nextCallback = function (value) { _this.wrapSuccess(nextFn, value).next(resolve, reject); }; _this.catchCallback = function (error) { _this.wrapFailure(catchFn, error).next(resolve, reject); }; }); } }; PersistencePromise.prototype.toPromise = function () { var _this = this; return new Promise(function (resolve, reject) { _this.next(resolve, reject); }); }; PersistencePromise.prototype.wrapUserFunction = function (fn) { try { var result = fn(); if (result instanceof PersistencePromise) { return result; } else { return PersistencePromise.resolve(result); } } catch (e) { return PersistencePromise.reject(e); } }; PersistencePromise.prototype.wrapSuccess = function (nextFn, value) { if (nextFn) { return this.wrapUserFunction(function () { return nextFn(value); }); } else { // If there's no nextFn, then R must be the same as T but we // can't express that in the type system. return PersistencePromise.resolve(value); } }; PersistencePromise.prototype.wrapFailure = function (catchFn, error) { if (catchFn) { return this.wrapUserFunction(function () { return catchFn(error); }); } else { return PersistencePromise.reject(error); } }; PersistencePromise.resolve = function (result) { return new PersistencePromise(function (resolve, reject) { resolve(result); }); }; PersistencePromise.reject = function (error) { return new PersistencePromise(function (resolve, reject) { reject(error); }); }; PersistencePromise.waitFor = function (all) { return all.reduce(function (promise, nextPromise, idx) { return promise.next(function () { return nextPromise; }); }, PersistencePromise.resolve()); }; PersistencePromise.map = function (all) { var results = []; var first = true; // initial is ignored, so we can cheat on the type. var initial = PersistencePromise.resolve(null); return all .reduce(function (promise, nextPromise) { return promise.next(function (result) { if (!first) { results.push(result); } first = false; return nextPromise; }); }, initial) .next(function (result) { results.push(result); return results; }); }; return PersistencePromise; }()); export { PersistencePromise }; //# sourceMappingURL=persistence_promise.js.map
aggiedefenders/aggiedefenders.github.io
node_modules/@firebase/firestore/dist/esm/src/local/persistence_promise.js
JavaScript
mit
6,111
MainIndexEstablishmentsListView = Backbone.View.extend({ events: { 'click .nav': 'navigate' }, initialize: function () { this.listenTo(this.collection, 'reset', this.render); }, render: function (e) { this.$el.html(''); if (this.collection.length > 0) { this.collection.each(function (establishment) { this.renderEstablishment(establishment); }, this); } else { this.$el.html(''); this.$el.html(render('establishments/index_no_results')); } }, renderEstablishment: function (establishment) { var establishment_view = new EstablishmentsIndexEstablishmentView({ tagName: 'li', model: establishment }); this.$el.append(establishment_view.el); }, navigate: function (e) { e.preventDefault(); App.navigate(e.target.pathname, { trigger: true }); } });
sealocal/yumhacker
app/assets/javascripts/views/main/index_establishments_list_view.js
JavaScript
mit
825
/* * BOOOS.h * * Created on: Aug 14, 2014 */ #ifndef TASK_CC_ #define TASK_CC_ #include "BOOOS.h" #include <iostream> namespace BOOOS { BOOOS * BOOOS::__booos = 0; BOOOS::SchedulerType BOOOS::SCHED_POLICY = BOOOS::SCHED_FCFS; // ou outro escalonador. Ajustem como necessário bool BOOOS::SCHED_PREEMPT = false; // pode ser preemptivo ou não bool BOOOS::SCHED_AGING = false; // apenas alguns escalonadores usam aging. Ajustem como necessário BOOOS::BOOOS(bool verbose) : _verbose(verbose) { if(_verbose) std::cout << "Welcome to BOOOS - Basic Object Oriented Operating System!" << std::endl; // Call init routines of other components this->init(); } BOOOS::~BOOOS() { // Call finish routines of other components (if any) if(_verbose) std::cout << "BOOOS ended... Bye!" << std::endl; } void BOOOS::init() { Task::init(); Scheduler::init(); } void BOOOS::panic() { std::cerr << "BOOOSta! Panic!" << std::endl; while(true); } } /* namespace BOOOS */ #endif
paladini/UFSC-so1-2015-01
trabalhos/atividadePratica2/final/lib/BOOOS.cc
C++
mit
979
using System; using System.Linq; using System.Text; using Abp.Collections.Extensions; using Abp.Extensions; using Abp.Web.Api.Modeling; namespace Abp.Web.Api.ProxyScripting.Generators { internal static class ProxyScriptingJsFuncHelper { private const string ValidJsVariableNameChars = "abcdefghijklmnopqrstuxwvyzABCDEFGHIJKLMNOPQRSTUXWVYZ0123456789_"; public static string NormalizeJsVariableName(string name, string additionalChars = "") { var validChars = ValidJsVariableNameChars + additionalChars; var sb = new StringBuilder(name); sb.Replace('-', '_'); //Delete invalid chars foreach (var c in name) { if (!validChars.Contains(c)) { sb.Replace(c.ToString(), ""); } } if (sb.Length == 0) { return "_" + Guid.NewGuid().ToString("N").Left(8); } return sb.ToString(); } public static string GetParamNameInJsFunc(ParameterApiDescriptionModel parameterInfo) { return parameterInfo.Name == parameterInfo.NameOnMethod ? NormalizeJsVariableName(parameterInfo.Name.ToCamelCase(), ".") : NormalizeJsVariableName(parameterInfo.NameOnMethod.ToCamelCase()) + "." + NormalizeJsVariableName(parameterInfo.Name.ToCamelCase(), "."); } public static string CreateJsObjectLiteral(ParameterApiDescriptionModel[] parameters, int indent = 0) { var sb = new StringBuilder(); sb.AppendLine("{"); foreach (var prm in parameters) { sb.AppendLine($"{new string(' ', indent)} '{prm.Name}': {GetParamNameInJsFunc(prm)}"); } sb.Append(new string(' ', indent) + "}"); return sb.ToString(); } public static string GenerateJsFuncParameterList(ActionApiDescriptionModel action, string ajaxParametersName) { var methodParamNames = action.Parameters.Select(p => p.NameOnMethod).Distinct().ToList(); methodParamNames.Add(ajaxParametersName); return methodParamNames.Select(prmName => NormalizeJsVariableName(prmName.ToCamelCase())).JoinAsString(", "); } } }
liuxx001/BodeAbp
src/frame/Abp.Web.Common/Web/Api/ProxyScripting/Generators/ProxyScriptingJsFuncHelper.cs
C#
mit
2,365
/*! \file */ // Copyright 2011-2020 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights. #ifndef SAPI_VAR_STACK_HPP_ #define SAPI_VAR_STACK_HPP_ #include <new> #include <cstdio> #include <deque> #include "../arg/Argument.hpp" namespace var { /*! \brief Queue Class * \details The Queue class is a FIFO data structure * that allows data to be pushed on the back * and popped from the front. It is similar to the * std::queue container class. * */ template<typename T> class Stack : public api::WorkObject { public: /*! \details Constructs a new Queue. */ Stack(){} ~Stack(){ } /*! \details Returns a reference to the back item. * * The back item is the one that has most recently * been pushed using push(). * */ T & top(){ return m_deque.back(); } /*! \details Returns a read-only reference to the back item. * * The back item is the one that has most recently * been pushed using push(). * */ const T & top() const { return m_deque.back(); } /*! \details Pushes an item on the queue. * * @param value The item to push * */ Stack& push(const T & value){ m_deque.push_back(value); return *this; } /*! \details Pops an item from the front of the queue. */ Stack& pop(){ m_deque.pop_back(); return *this; } /*! \details Returns true if the queue is empty. */ bool is_empty() const { return m_deque.empty(); } /*! \details Returns the number of items in the queue. */ u32 count() const { return m_deque.size(); } /*! \details Clears the contents of the queue. * * This will empty the queue and free all the * resources associated with it. * */ Stack& clear(){ //deconstruct objects in the list using pop m_deque.clear(); return *this; } private: std::deque<T> m_deque; }; } #endif // SAPI_VAR_STACK_HPP_
StratifyLabs/StratifyAPI
include/var/Stack.hpp
C++
mit
1,819
using DataCloner.Core.Metadata; using System.Collections.Generic; using System.Linq; using System.Text; using System; namespace DataCloner.Core.Data.Generator { public class InsertWriter : IInsertWriter { private string IdentifierDelemiterStart { get; } private string IdentifierDelemiterEnd { get; } private string StringDelemiter { get; } private string NamedParameterPrefix { get; } private readonly StringBuilder _sb = new StringBuilder(); public InsertWriter(string identifierDelemiterStart, string identifierDelemiterEnd , string stringDelemiter, string namedParameterPrefix) { IdentifierDelemiterStart = identifierDelemiterStart; IdentifierDelemiterEnd = identifierDelemiterEnd; StringDelemiter = stringDelemiter; NamedParameterPrefix = namedParameterPrefix; } public IInsertWriter AppendColumns(TableIdentifier table, List<ColumnDefinition> columns) { _sb.Append("INSERT INTO ") .Append(IdentifierDelemiterStart).Append(table.Database).Append(IdentifierDelemiterEnd).Append("."); if (!String.IsNullOrWhiteSpace(table.Schema)) _sb.Append(IdentifierDelemiterStart).Append(table.Schema).Append(IdentifierDelemiterEnd).Append("."); _sb.Append(IdentifierDelemiterStart).Append(table.Table).Append(IdentifierDelemiterEnd) .Append("("); //Nom des colonnes for (var i = 0; i < columns.Count(); i++) { if (!columns[i].IsAutoIncrement) _sb.Append(IdentifierDelemiterStart).Append(columns[i].Name).Append(IdentifierDelemiterEnd).Append(","); } _sb.Remove(_sb.Length - 1, 1); _sb.Append(")VALUES("); return this; } public IInsertWriter Append(string value) { _sb.Append(value); return this; } public IInsertWriter AppendValue(object value) { _sb.Append(StringDelemiter).Append(value).Append(StringDelemiter).Append(","); return this; } public IInsertWriter AppendVariable(string varName) { _sb.Append(NamedParameterPrefix).Append(varName).Append(","); return this; } public IInsertWriter Complete() { _sb.Remove(_sb.Length - 1, 1); _sb.Append(");\r\n"); return this; } public StringBuilder ToStringBuilder() { return _sb; } } }
naster01/DataCloner
archive/DataCloner.Core/Data/Generator/InsertWriter.cs
C#
mit
2,629
(function () { var KEY = { ENTER: 13, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 }; function normalizeTokens(tokens) { return tokens.filter(function (token) { return !!token; }).map(function (token) { return token.toLowerCase(); }); } function newIndexNode() { return { ids: [], children: {} }; } function buildIndex(options) { var index = newIndexNode(); options.forEach(function (option, id) { var val = option.text || option.value, tokens = normalizeTokens(val.split(/\s+/)); tokens.forEach(function (token) { var ch, chars = token.split(''), node = index; while (ch = chars.shift()) { node = node.children[ch] || (node.children[ch] = newIndexNode()); node.ids.push(id); } }); }); return index; } function find(query, index, options) { var matches, tokens = normalizeTokens(query.split(/\s+/)); tokens.forEach(function (token) { var node = index, ch, chars = token.split(''); if (matches && matches.length === 0) { return false; } while (node && (ch = chars.shift())) { node = node.children[ch]; } if (node && chars.length === 0) { ids = node.ids.slice(0); matches = matches ? getIntersection(matches, ids) : ids; } else { matches = []; return false; } }); return matches ? unique(matches).map(function (id) { return options[id]; }) : []; } function unique(array) { var seen = {}, uniques = []; for (var i = 0; i < array.length; i++) { if (!seen[array[i]]) { seen[array[i]] = true; uniques.push(array[i]); } } return uniques; } function getIntersection(arrayA, arrayB) { var ai = 0, bi = 0, intersection = []; arrayA = arrayA.sort(compare); arrayB = arrayB.sort(compare); while (ai < arrayA.length && bi < arrayB.length) { if (arrayA[ai] < arrayB[bi]) { ai++; } else if (arrayA[ai] > arrayB[bi]) { bi++; } else { intersection.push(arrayA[ai]); ai++; bi++; } } return intersection; function compare(a, b) { return a - b; } } var BAutocompletePrototype = Object.create(HTMLElement.prototype, { options: { enumerable: true, get: function () { var list = document.querySelector('#' + this.getAttribute('list')); if (list && list.options) { CustomElements.upgrade(list); return Array.prototype.slice.call(list.options, 0); } return []; } }, index: { enumerable: true, get: function () { if (!this.__index) { this.__index = buildIndex(this.options); } return this.__index; } }, suggestionList: { enumerable: true, get: function () { return this.querySelector('ul'); } }, selectable: { enumerable: true, get: function () { return this.querySelector('b-selectable'); } }, input: { enumerable: true, get: function () { return this.querySelector('input[type=text]'); } }, createdCallback: { enumerable: true, value: function () { this.appendChild(this.template.content.cloneNode(true)); this.input.addEventListener('input', this.onInputChange.bind(this), false); this.input.addEventListener('focus', this.onInputFocus.bind(this), false); this.input.addEventListener('blur', this.onInputBlur.bind(this), false); this.selectable.addEventListener('mousedown', this.onSuggestionPick.bind(this), false); this.selectable.addEventListener('b-activate', this.pickSuggestion.bind(this), false); } }, handleAria: { enumerable: true, value: function () { this.setAttribute('role', 'combobox'); this.setAttribute('aria-autocomplete', 'list'); } }, onInputFocus: { enumerable: true, value: function (e) { this.keydownListener = this.keydownHandler.bind(this); this.input.addEventListener('keydown', this.keydownListener, false); } }, onInputBlur: { enumerable: true, value: function (e) { if (this.cancelBlur) { this.cancelBlur = false; return; } this.input.removeEventListener('keydown', this.keydownListener, false); this.hideSuggestionList(); } }, onSuggestionPick: { enumerable: true, value: function (e) { e.preventDefault(); this.cancelBlur = true; } }, keydownHandler: { enumerable: true, value: function (e) { e.stopPropagation(); switch (e.keyCode) { case KEY.ENTER: { this.selectable.activate(); break; } case KEY.DOWN: { if (!this.areSuggestionsVisible()) { this.showSuggestionList(); } else { this.selectable.selectNextItem(); } break; } case KEY.UP: { if (!this.areSuggestionsVisible()) { this.showSuggestionList(); } else { this.selectable.selectPreviousItem(); } break; } default: return; } e.preventDefault(); } }, onInputChange: { enumerable: true, value: function (e) { e.stopPropagation(); if (!this.areSuggestionsVisible()) { this.showSuggestionList(); this.input.focus(); } else { this.refreshSuggestionList(); } this.selectFirstSuggestion(); } }, filterOptions: { enumerable: true, value: function () { var query = this.input.value; if (!query) return this.options; return find(query, this.index, this.options); } }, paintSuggestionList: { enumerable: true, value: function () { this.selectable.unselect(); var list = this.suggestionList, options = this.filterOptions(); while (list.childNodes.length > 0) { list.removeChild(list.childNodes[0]); } options.forEach(function (option) { var li = document.createElement('li'); li.innerHTML = option.text || option.value; list.appendChild(li); }); } }, refreshSuggestionList: { enumerable: true, value: function () { this.paintSuggestionList(); } }, toggleSuggestionList: { enumerable: true, value: function (e) { if (e) { e.stopPropagation(); } this.areSuggestionsVisible() ? this.hideSuggestionList() : this.showSuggestionList(); this.input.focus(); } }, showSuggestionList: { enumerable: true, value: function () { this.paintSuggestionList(); this.selectable.setAttribute('visible', ''); } }, hideSuggestionList: { enumerable: true, value: function () { if (this.areSuggestionsVisible()) { this.selectable.removeAttribute('visible'); } } }, selectFirstSuggestion: { enumerable: true, value: function () { this.selectable.selectFirst(); } }, areSuggestionsVisible: { enumerable: true, value: function () { return this.selectable.hasAttribute('visible'); } }, pickSuggestion: { enumerable: true, value: function (e) { this.cancelBlur = false; this.input.value = this.getItemValue(e.detail.item); this.hideSuggestionList(); } }, getItemValue: { enumerable: true, value: function (itemIndex) { return this.querySelectorAll('li')[itemIndex].innerHTML; } } }); window.BAutocomplete = document.registerElement('b-autocomplete', { prototype: BAutocompletePrototype }); Object.defineProperty(BAutocompletePrototype, 'template', { get: function () { var fragment = document.createDocumentFragment(); var div = fragment.appendChild(document.createElement('div')); div.innerHTML = ' <input type="text" autocomplete="off" role="textbox" value=""> <b-selectable target="li"> <ul></ul> </b-selectable> '; while (child = div.firstChild) { fragment.insertBefore(child, div); } fragment.removeChild(div); return { content: fragment }; } }); }()); (function () { var BComboBoxPrototype = Object.create(BAutocomplete.prototype, { listToggle: { enumerable: true, get: function () { return this.querySelector('.b-combo-box-toggle'); } }, createdCallback: { enumerable: true, value: function () { this._super.createdCallback.call(this); this.listToggle.addEventListener('click', this.toggleSuggestionList.bind(this), false); } } }); window.BComboBox = document.registerElement('b-combo-box', { prototype: BComboBoxPrototype }); Object.defineProperty(BComboBox.prototype, '_super', { enumerable: false, writable: false, configurable: false, value: BAutocomplete.prototype }); Object.defineProperty(BComboBoxPrototype, 'template', { get: function () { var fragment = document.createDocumentFragment(); var div = fragment.appendChild(document.createElement('div')); div.innerHTML = ' <input type="text" autocomplete="off" role="textbox" value=""> <a class="b-combo-box-toggle"></a> <b-selectable target="li"> <ul></ul> </b-selectable> '; while (child = div.firstChild) { fragment.insertBefore(child, div); } fragment.removeChild(div); return { content: fragment }; } }); }());
bosonic-labs/b-autocomplete
dist/b-autocomplete.js
JavaScript
mit
12,927
<?php /** * Checkout.com * Authorised and regulated as an electronic money institution * by the UK Financial Conduct Authority (FCA) under number 900816. * * PHP version 7 * * @category SDK * @package Checkout.com * @author Platforms Development Team <platforms@checkout.com> * @copyright 2010-2019 Checkout.com * @license https://opensource.org/licenses/mit-license.html MIT License * @link https://docs.checkout.com/ */ namespace Checkout\Models\Payments; /** * Payment method Bancontact. * * @category SDK * @package Checkout.com * @author Platforms Development Team <platforms@checkout.com> * @license https://opensource.org/licenses/mit-license.html MIT License * @link https://docs.checkout.com/ */ class BancontactSource extends Source { /** * Qualified name of the class. * * @var string */ const QUALIFIED_NAME = __CLASS__; /** * Name of the model. * * @var string */ const MODEL_NAME = 'bancontact'; /** * Magic Methods */ /** * Initialise bancontact. * * @param string $name The account_holder_name * @param string $country The payment_country * @param string $descriptor The billing_descriptor */ public function __construct($name, $country, $descriptor = '') { $this->type = static::MODEL_NAME; $this->account_holder_name = $name; $this->payment_country = $country; $this->billing_descriptor = $descriptor; } }
checkout/checkout-woocommerce-plugin
woocommerce-gateway-checkout-com/includes/lib/checkout-sdk-php/src/Models/Payments/BancontactSource.php
PHP
mit
1,552
#import SYS import ShareYourSystem as SYS #Definition MyBrianer=SYS.BrianerClass( ).collect( "Neurongroupers", 'P', SYS.NeurongrouperClass( #Here are defined the brian classic shared arguments for each pop **{ 'NeurongroupingKwargVariablesDict': { 'N':2, 'model': ''' Jr : 1 dr/dt = (-r+Jr)/(20*ms) : 1 ''' }, 'ConnectingGraspClueVariablesList': [ SYS.GraspDictClass( { 'HintVariable':'/NodePointDeriveNoder/<Neurongroupers>PNeurongrouper', 'SynapsingKwargVariablesDict': { 'model': ''' J : 1 Jr_post=J*r_pre : 1 (summed) ''' }, 'SynapsingWeigthSymbolStr':'J', 'SynapsingWeigthFloatsArray':SYS.array( [ [0.,-2.], [4.,0.] ] ), "SynapsingDelayDict":{'r':1.*SYS.brian2.ms} } ) ] } ).collect( "StateMoniters", 'Rate', SYS.MoniterClass( **{ 'MoniteringVariableStr':'r', 'MoniteringRecordTimeIndexIntsArray':[0,1] } ) ) ).network( **{ 'RecruitingConcludeConditionVariable':[ ( 'MroClassesList', SYS.contains, SYS.NeurongrouperClass ) ] } ).brian() #init variables map( lambda __BrianedNeuronGroup: __BrianedNeuronGroup.__setattr__( 'r', 1.+SYS.array(map(float,xrange(__BrianedNeuronGroup.N))) ), MyBrianer.BrianedNeuronGroupsList ) #run MyBrianer.run(100) #plot M=MyBrianer['<Neurongroupers>PNeurongrouper']['<StateMoniters>RateMoniter'].StateMonitor SYS.plot(M.t, M.r.T) SYS.show()
Ledoux/ShareYourSystem
Pythonlogy/draft/Simulaters/Brianer/draft/07_ExampleDoc.py
Python
mit
1,597
package tactician; /** * This class is responsible for converting between a {@link Move} object and chess algebraic * notation. {@link #algebraicToMove(Board, String)} converts a string in algebraic notation to a * {@link Move} and {@link #moveToAlgebraic(Board, Move)} does the opposite. * * @see <a href="https://en.wikipedia.org/wiki/Algebraic_notation_(chess)">Algebraic Notation</a> * @author Phil Leszczynski */ public class AlgebraicNotation { /** * Returns a move where the player castles kingside if it is legal, or null otherwise. * * @param board the board containing the position * @return a move that castles kingside if one is legal, null otherwise */ private static Move findCastleKingsideMove(Board board) { for (Move move : board.legalMoves()) { if (move.source + 2 == move.destination) { return move; } } return null; } /** * Returns a move where the player castles queenside if it is legal, or null otherwise. * * @param board the board containing the position * @return a move that castles queenside if one is legal, null otherwise */ private static Move findCastleQueensideMove(Board board) { for (Move move : board.legalMoves()) { if (move.source - 2 == move.destination) { return move; } } return null; } /** * Returns a pawn move given a board, a starting file for the pawn, a destination square, and a * piece to promote to (null if the pawn does not promote). If there is no such legal move * available on the board, returns null. * * @param board the board containing the position * @param file the starting file for the pawn, e.g. 'c' * @param destination the square where the pawn moves to * @param promoteTo the type of piece if the pawn promotes, null otherwise * @return a pawn move on the board that meets the criteria, null if no such move is found */ private static Move findPawnMove(Board board, char file, Square destination, Piece promoteTo) { for (Move move : board.legalMoves()) { Square sourceSquare = new Square(move.source); Square destinationSquare = new Square(move.destination); Piece sourcePiece = board.pieceOnSquare(sourceSquare); char sourceFile = sourceSquare.getName().charAt(0); if (sourcePiece != Piece.PAWN) { continue; } if (sourceFile != file) { continue; } if (destination != destinationSquare) { continue; } if (move.promoteTo != promoteTo) { continue; } return move; } return null; } /** * Returns a non-pawn move given a board, the type of piece to move, a destination square, a * start file for the piece if specified, and a start rank for the piece if specified. The start * file and start rank may be needed to resolve ambiguity since for example it is possible for * the white player's b1 and e2 knights to go to c3. If the start file is set to 'e', that means * the e2-knight is intended as the mover. If either the start file or start rank is not needed, * it should be passed in as '_'. * * @param board the board containing the position * @param mover the type of piece to move * @param destination the square where the piece moves to * @param startFile the name of the file if more than one piece of the given type on different * files can reach the destination square, '_' otherwise * @param startRank the name of the rank if more than one piece of the given type on different * ranks can reach the destination square (and startFile is not sufficient to tell the * difference), '_' otherwise * @return a non-pawn move on the board that meets the criteria, null if no such move is found */ private static Move findNonPawnMove(Board board, Piece mover, Square destination, char startFile, char startRank) { for (Move move : board.legalMoves()) { Square sourceSquare = new Square(move.source); Square destinationSquare = new Square(move.destination); Piece sourcePiece = board.pieceOnSquare(sourceSquare); if (sourcePiece != mover) { continue; } if (destination != destinationSquare) { continue; } if (startFile != '_' && startFile != destinationSquare.getFile()) { continue; } if (startRank != '_' && startRank != destinationSquare.getRank()) { continue; } return move; } return null; } /** * Given a board and a move string in algebraic notation, returns a {@link Move} object * corresponding to that move. It first deals with the special cases for castling moves, "O-O" * and "O-O-O". Otherwise if the first character is a lowercase letter it is a pawn move and it * delegates to {@link #findPawnMove(Board, char, Square, Piece)}. Otherwise it is a non-pawn * move and we look for ambiguity resolving characters such as the 'e' in "Nec3". Finally we * delegate to {@link #findNonPawnMove(Board, Piece, Square, char, char)}. * * @param board the board containing the position * @param algebraic the string describing the move in algebraic notation * @return a {@link Move} object if such a legal move is found on the board, null otherwise */ public static Move algebraicToMove(Board board, String algebraic) { if (algebraic.length() < 2) { System.err.println("Illegal move: too short: " + algebraic); return null; } if (algebraic.equals("O-O")) { return findCastleKingsideMove(board); } if (algebraic.equals("O-O-O")) { return findCastleQueensideMove(board); } String destinationName = ""; Piece promoteTo = null; if (algebraic.charAt(algebraic.length() - 2) == '=') { // The move is a pawn promotion and ends with, for example "=Q". So the destination string is // the last two digits before the equals sign. destinationName = algebraic.substring(algebraic.length() - 4, algebraic.length() - 2); promoteTo = Piece.initialToPiece(algebraic.charAt(algebraic.length() - 1)); } else { destinationName = algebraic.substring(algebraic.length() - 2, algebraic.length()); } Square destination = new Square(destinationName); char algebraicPrefix = algebraic.charAt(0); if (algebraicPrefix >= 'a' && algebraicPrefix <= 'h') { return findPawnMove(board, algebraicPrefix, destination, promoteTo); } Piece mover = Piece.initialToPiece(algebraicPrefix); String algebraicTrimmed = algebraic.replace("x", ""); int algebraicTrimmedLength = algebraicTrimmed.length(); char matchFile = '_'; char matchRank = '_'; if (algebraicTrimmedLength == 4) { // The second character is used to resolve ambiguity when two of the same type of piece can // go to the same destination square. For example if two knights can go to c3, the move can // be disambiguated as Nbc3 or Nec3. Similarly the first character can be a rank such as // R1e7. char resolver = algebraicTrimmed.charAt(1); if (resolver >= 'a' && resolver <= 'h') { matchFile = resolver; } else { matchRank = resolver; } } else if (algebraicTrimmedLength == 5) { // This is a rare case when both the file and rank are needed to resolve ambiguity. For // example if there are three white queens on a1, a3, and c1, and the player wishes to move // the a1-queen to c3, the move would be written as Qa1c3. matchFile = algebraicTrimmed.charAt(1); matchRank = algebraicTrimmed.charAt(2); } return findNonPawnMove(board, mover, destination, matchFile, matchRank); } /** * Given a board and a move on the board, gets the ambiguity string containing the file and/or * rank if other pieces of the same type can move to the same destination square. For example if * there are white knights on b1 and e2, and we wish to move the e2-knight, the ambiguity string * would be "e". If there are black rooks on g3 and g7, and we wish to move the g7-rook, the * ambiguity string would be "7". If there are white queens on a1, a3, and c1, and we wish to * move the a1-queen to c3, the ambiguity string would be "a1" since neither "a" nor "1" is * sufficient to describe which queen should move. Finally if there are black bishops on a8 and * b8, and we wish to move the b8-bishop to c7, then the ambiguity string would be "" since only * one bishop is able to move to c7. * * @param board the board containing the position * @param moveToMatch the move on the board we wish to match, i.e. find other pieces of the same * type that can move to the same destination square * @see <a href="https://en.wikipedia.org/wiki/Algebraic_notation_(chess)">Algebraic Notation</a> * @return the ambiguity string for the board and move, e.g. "e", "7", "a1", or "" */ private static String getAmbiguity(Board board, Move moveToMatch) { Square sourceToMatch = new Square(moveToMatch.source); Piece moverToMatch = board.pieceOnSquare(sourceToMatch); char fileToMatch = sourceToMatch.getFile(); char rankToMatch = sourceToMatch.getRank(); boolean matchingFileFound = false; boolean matchingRankFound = false; for (Move move : board.legalMoves()) { Piece mover = board.pieceOnSquare(new Square(move.source)); if (move == moveToMatch) { // Only search for moves different than the move requested. continue; } if (mover != moverToMatch) { continue; } Square source = new Square(move.source); char file = source.getFile(); char rank = source.getRank(); if (file == fileToMatch) { matchingFileFound = true; } if (rank == rankToMatch) { matchingRankFound = true; } } String result = ""; if (matchingFileFound) { result += fileToMatch; } if (matchingRankFound) { result += rankToMatch; } return result; } /** * Given a board and a move on the board, returns the string representing the move in algebraic * notation. It first deals with the special case castling moves "O-O" and "O-O-O". It then gets * the prefix which is either the pawn file or the type of piece. It then gets the ambiguity * string through {@link #getAmbiguity(Board, Move)}. It then inserts the character 'x' if the * move is a capture. Next it puts in the destination square. Finally it adds in the promotion * string if there is one, for example "=Q". * * @param board the board containing the position * @param move the move to convert to algebraic notation * @return a string representing the move in algebraic notation */ public static String moveToAlgebraic(Board board, Move move) { Square sourceSquare = new Square(move.source); Piece mover = board.pieceOnSquare(sourceSquare); if (mover == Piece.KING && move.source + 2 == move.destination) { return "O-O"; } if (mover == Piece.KING && move.source - 2 == move.destination) { return "O-O-O"; } String algebraicPrefix; if (mover == Piece.PAWN) { algebraicPrefix = "" + sourceSquare.getFile(); } else { algebraicPrefix = "" + mover.initial(); } String ambiguity = getAmbiguity(board, move); Square destinationSquare = new Square(move.destination); String captureStr = ""; if (board.allPieces.intersects(destinationSquare)) { captureStr = "x"; } else if (mover == Piece.PAWN && board.enPassantTarget == (1L << move.destination)) { captureStr = "x"; } String destinationSquareName = destinationSquare.getName(); String promoteToStr = ""; if (move.promoteTo != null) { promoteToStr = "=" + move.promoteTo.initial(); } return algebraicPrefix + ambiguity + captureStr + destinationSquareName + promoteToStr; } }
philleski/tactician
src/tactician/AlgebraicNotation.java
Java
mit
11,982
/** */ package rgse.ttc17.emoflon.tgg.task2; import gluemodel.CIM.IEC61970.LoadModel.ConformLoadGroup; import org.eclipse.emf.ecore.EObject; import org.moflon.tgg.runtime.AbstractCorrespondence; // <-- [user defined imports] // [user defined imports] --> /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Conform Load Group To Conform Load Group</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link rgse.ttc17.emoflon.tgg.task2.ConformLoadGroupToConformLoadGroup#getSource <em>Source</em>}</li> * <li>{@link rgse.ttc17.emoflon.tgg.task2.ConformLoadGroupToConformLoadGroup#getTarget <em>Target</em>}</li> * </ul> * </p> * * @see rgse.ttc17.emoflon.tgg.task2.Task2Package#getConformLoadGroupToConformLoadGroup() * @model * @generated */ public interface ConformLoadGroupToConformLoadGroup extends EObject, AbstractCorrespondence { /** * Returns the value of the '<em><b>Source</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Source</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Source</em>' reference. * @see #setSource(ConformLoadGroup) * @see rgse.ttc17.emoflon.tgg.task2.Task2Package#getConformLoadGroupToConformLoadGroup_Source() * @model required="true" * @generated */ ConformLoadGroup getSource(); /** * Sets the value of the '{@link rgse.ttc17.emoflon.tgg.task2.ConformLoadGroupToConformLoadGroup#getSource <em>Source</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Source</em>' reference. * @see #getSource() * @generated */ void setSource(ConformLoadGroup value); /** * Returns the value of the '<em><b>Target</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Target</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Target</em>' reference. * @see #setTarget(outagePreventionJointarget.ConformLoadGroup) * @see rgse.ttc17.emoflon.tgg.task2.Task2Package#getConformLoadGroupToConformLoadGroup_Target() * @model required="true" * @generated */ outagePreventionJointarget.ConformLoadGroup getTarget(); /** * Sets the value of the '{@link rgse.ttc17.emoflon.tgg.task2.ConformLoadGroupToConformLoadGroup#getTarget <em>Target</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Target</em>' reference. * @see #getTarget() * @generated */ void setTarget(outagePreventionJointarget.ConformLoadGroup value); // <-- [user code injected with eMoflon] // [user code injected with eMoflon] --> } // ConformLoadGroupToConformLoadGroup
georghinkel/ttc2017smartGrids
solutions/eMoflon/rgse.ttc17.emoflon.tgg.task2/gen/rgse/ttc17/emoflon/tgg/task2/ConformLoadGroupToConformLoadGroup.java
Java
mit
2,906
require 'spec_helper' describe Maxmind::ChargebackRequest do before do Maxmind.user_id = 'user' Maxmind.license_key = 'key' @request = Maxmind::ChargebackRequest.new(:client_ip => '198.51.100.2') end it "requires a License Key" do Maxmind.license_key = nil expect { @request.send(:validate) }.to raise_error(ArgumentError) Maxmind.license_key = 'key' end it "requires a User ID" do Maxmind.user_id = nil expect { @request.send(:validate) }.to raise_error(ArgumentError) Maxmind.user_id = 'user' end it "requires a client IP" do @request.client_ip = nil expect { @request.send(:validate) }.to raise_error(ArgumentError) end end
jack-trikeapps/maxmind
spec/maxmind/chargeback_request_spec.rb
Ruby
mit
691
package infrastructure import ( "database/sql" _ "github.com/mattn/go-sqlite3" "log" ) type SqliteHandler struct { Path string Connect *sql.DB } func (handler *SqliteHandler) Open() error { db, err := sql.Open("sqlite3", handler.Path) if err != nil { log.Panic(err) } handler.Connect = db return err } func (handler *SqliteHandler) Close() { if handler.Connect != nil { handler.Connect.Close() handler.Connect = nil } } func (handler SqliteHandler) Db() *sql.DB { return handler.Connect } func NewSqliteHandler(path string) *SqliteHandler { sqliteHandler := new(SqliteHandler) sqliteHandler.Path = path return sqliteHandler }
orleans-tech/s01e03-discover-node-js
07-api-rest-go/src/server/src/infrastructure/sqlitehandler.go
GO
mit
657
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Paypal\Block\Payment\Form\Billing; /** * Paypal Billing Agreement form block */ class Agreement extends \Magento\Payment\Block\Form { /** * @var string */ protected $_template = 'Magento_Paypal::payment/form/billing/agreement.phtml'; /** * @var \Magento\Paypal\Model\Billing\AgreementFactory */ protected $_agreementFactory; /** * @param \Magento\Framework\View\Element\Template\Context $context * @param \Magento\Paypal\Model\Billing\AgreementFactory $agreementFactory * @param array $data */ public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Paypal\Model\Billing\AgreementFactory $agreementFactory, array $data = [] ) { $this->_agreementFactory = $agreementFactory; parent::__construct($context, $data); $this->_isScopePrivate = true; } /** * @return void */ protected function _construct() { parent::_construct(); $this->setTransportName( \Magento\Paypal\Model\Payment\Method\Billing\AbstractAgreement::TRANSPORT_BILLING_AGREEMENT_ID ); } /** * Retrieve available customer billing agreements * * @return array */ public function getBillingAgreements() { $data = []; /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->getParentBlock()->getQuote(); if (!$quote || !$quote->getCustomerId()) { return $data; } $collection = $this->_agreementFactory->create()->getAvailableCustomerBillingAgreements( $quote->getCustomerId() ); foreach ($collection as $item) { $data[$item->getId()] = $item->getReferenceId(); } return $data; } }
j-froehlich/magento2_wk
vendor/magento/module-paypal/Block/Payment/Form/Billing/Agreement.php
PHP
mit
1,961
const template = require("../../../layouts/hbs-loader")("base.ftl"); module.exports = template({ body: require("./html/body.ftl") });
chenwenzhang/frontend-scaffolding
src/pages/freemarker/index/html.js
JavaScript
mit
137
package com.thebluealliance.androidclient.gcm; import com.thebluealliance.androidclient.TbaLogger; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; public class GCMBroadcastReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { TbaLogger.d("Got GCM Message. " + intent); // Explicitly specify that GcmIntentService will handle the intent. ComponentName comp = new ComponentName(context.getPackageName(), GCMMessageHandler.class.getName()); // Start the service, keeping the device awake while it is launching. startWakefulService(context, intent.setComponent(comp)); setResultCode(Activity.RESULT_OK); } }
1fish2/the-blue-alliance-android
android/src/main/java/com/thebluealliance/androidclient/gcm/GCMBroadcastReceiver.java
Java
mit
881
export * from './login-form';
javlaking/testangular2ci
src/components/login/index.ts
TypeScript
mit
30
//1. consider terminate and return when found a bound condition. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *deleteDuplicates(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() function if (head == NULL) return head; ListNode *p = head; ListNode *b = new ListNode(-1); b->next = head; ListNode *preprev = b; ListNode *prev = p; p = p->next; while (p) { if (p->val == prev->val) { while (p && p->val == prev->val) { p = p->next; } preprev->next = p; if (p == NULL) return b->next; prev = p; p = p->next; } else { preprev = prev; prev = p; p = p->next; } } return b->next; } };
Xe0n0/LeetCode
Remove Duplicates from Sorted List II.cpp
C++
mit
1,211
<?php /** * @Created By ECMall PhpCacheServer * @Time:2015-01-23 00:46:43 */ if(filemtime(__FILE__) + 1800 < time())return false; return array ( 'id' => 2397, 'goods' => array ( 'goods_id' => '2397', 'store_id' => '131', 'type' => 'material', 'goods_name' => '烤干熟虾皮100g', 'description' => '<p style="text-align: center;"><img src="http://wap.bqmart.cn/data/files/store_131/goods_167/201412171822472737.jpg" alt="6925979200319_01.jpg" /><img src="http://wap.bqmart.cn/data/files/store_131/goods_172/201412171822527262.jpg" alt="6925979200319_02.jpg" /><img src="http://wap.bqmart.cn/data/files/store_131/goods_177/201412171822575660.jpg" alt="6925979200319_03.jpg" /></p>', 'cate_id' => '810', 'cate_name' => '生鲜 冷冻食品', 'brand' => '', 'spec_qty' => '0', 'spec_name_1' => '', 'spec_name_2' => '', 'if_show' => '1', 'if_seckill' => '0', 'closed' => '0', 'close_reason' => NULL, 'add_time' => '1418782986', 'last_update' => '1418782986', 'default_spec' => '2401', 'default_image' => 'data/files/store_131/goods_160/small_201412171822404085.jpg', 'recommended' => '0', 'cate_id_1' => '780', 'cate_id_2' => '810', 'cate_id_3' => '0', 'cate_id_4' => '0', 'price' => '18.00', 'tags' => array ( 0 => '虾皮', ), 'cuxiao_ids' => NULL, 'from_goods_id' => '0', 'quanzhong' => NULL, 'state' => '1', '_specs' => array ( 0 => array ( 'spec_id' => '2401', 'goods_id' => '2397', 'spec_1' => '', 'spec_2' => '', 'color_rgb' => '', 'price' => '18.00', 'stock' => '1000', 'sku' => '6925979200319', ), ), '_images' => array ( 0 => array ( 'image_id' => '3506', 'goods_id' => '2397', 'image_url' => 'data/files/store_131/goods_160/201412171822404085.jpg', 'thumbnail' => 'data/files/store_131/goods_160/small_201412171822404085.jpg', 'sort_order' => '1', 'file_id' => '14400', ), ), '_scates' => array ( ), 'views' => '2', 'collects' => '0', 'carts' => '0', 'orders' => '0', 'sales' => '0', 'comments' => '0', 'related_info' => array ( ), ), 'store_data' => array ( 'store_id' => '131', 'store_name' => '海尔绿城店', 'owner_name' => '倍全', 'owner_card' => '370832200104057894', 'region_id' => '2213', 'region_name' => '中国 山东 济南 历下区', 'address' => '', 'zipcode' => '', 'tel' => '0531-86940405', 'sgrade' => '系统默认', 'apply_remark' => '', 'credit_value' => '0', 'praise_rate' => '0.00', 'domain' => '', 'state' => '1', 'close_reason' => '', 'add_time' => '1418929047', 'end_time' => '0', 'certification' => 'autonym,material', 'sort_order' => '65535', 'recommended' => '0', 'theme' => '', 'store_banner' => NULL, 'store_logo' => 'data/files/store_131/other/store_logo.jpg', 'description' => '', 'image_1' => '', 'image_2' => '', 'image_3' => '', 'im_qq' => '', 'im_ww' => '', 'im_msn' => '', 'hot_search' => '', 'business_scope' => '', 'online_service' => array ( ), 'hotline' => '', 'pic_slides' => '', 'pic_slides_wap' => '{"1":{"url":"data/files/store_131/pic_slides_wap/pic_slides_wap_1.jpg","link":"http://wap.bqmart.cn/index.php?app=zhuanti&id=6"},"2":{"url":"data/files/store_131/pic_slides_wap/pic_slides_wap_2.jpg","link":"http://wap.bqmart.cn/index.php?keyword= %E6%B4%97%E8%A1%A3%E5%B9%B2%E6%B4%97&app=store&act=search&id=131"},"3":{"url":"data/files/store_131/pic_slides_wap/pic_slides_wap_3.jpg","link":"http://wap.bqmart.cn/index.php?app=search&cate_id=691&id=131"}}', 'enable_groupbuy' => '0', 'enable_radar' => '1', 'waptheme' => '', 'is_open_pay' => '0', 'area_peisong' => NULL, 'power_coupon' => '0', 's_long' => '117.131236', 's_lat' => '36.644393', 'user_name' => 'bq4053', 'email' => '111111111@qq.com', 'certifications' => array ( 0 => 'autonym', 1 => 'material', ), 'credit_image' => 'http://wap.bqmart.cn/themes/store/default/styles/default/images/heart_1.gif', 'store_owner' => array ( 'user_id' => '131', 'user_name' => 'bq4053', 'email' => '111111111@qq.com', 'password' => '9cbf8a4dcb8e30682b927f352d6559a0', 'real_name' => '新生活家园', 'gender' => '0', 'birthday' => '', 'phone_tel' => NULL, 'phone_mob' => NULL, 'im_qq' => '', 'im_msn' => '', 'im_skype' => NULL, 'im_yahoo' => NULL, 'im_aliww' => NULL, 'reg_time' => '1418928900', 'last_login' => '1421877406', 'last_ip' => '119.162.42.80', 'logins' => '126', 'ugrade' => '0', 'portrait' => NULL, 'outer_id' => '0', 'activation' => NULL, 'feed_config' => NULL, 'uin' => '0', 'parentid' => '0', 'user_level' => '0', 'from_weixin' => '0', 'wx_openid' => NULL, 'wx_nickname' => NULL, 'wx_city' => NULL, 'wx_country' => NULL, 'wx_province' => NULL, 'wx_language' => NULL, 'wx_headimgurl' => NULL, 'wx_subscribe_time' => '0', 'wx_id' => '0', 'from_public' => '0', 'm_storeid' => '0', ), 'store_navs' => array ( ), 'kmenus' => false, 'kmenusinfo' => array ( ), 'radio_new' => 1, 'radio_recommend' => 1, 'radio_hot' => 1, 'goods_count' => '1109', 'store_gcates' => array ( ), 'functions' => array ( 'editor_multimedia' => 'editor_multimedia', 'coupon' => 'coupon', 'groupbuy' => 'groupbuy', 'enable_radar' => 'enable_radar', 'seckill' => 'seckill', ), 'hot_saleslist' => array ( 2483 => array ( 'goods_id' => '2483', 'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状', 'default_image' => 'data/files/store_131/goods_110/small_201412180915101043.jpg', 'price' => '9.60', 'sales' => '7', ), 2067 => array ( 'goods_id' => '2067', 'goods_name' => '黑牛高钙豆奶粉480g', 'default_image' => 'data/files/store_131/goods_19/small_201412171103393194.gif', 'price' => '15.80', 'sales' => '7', ), 2674 => array ( 'goods_id' => '2674', 'goods_name' => '美汁源果粒橙450ml果汁', 'default_image' => 'data/files/store_131/goods_5/small_201412181056459752.jpg', 'price' => '3.00', 'sales' => '5', ), 2481 => array ( 'goods_id' => '2481', 'goods_name' => '心相印红卷纸单包装120g卫生纸', 'default_image' => 'data/files/store_131/goods_71/small_201412180914313610.jpg', 'price' => '2.50', 'sales' => '4', ), 2690 => array ( 'goods_id' => '2690', 'goods_name' => '乐百氏脉动水蜜桃600ml', 'default_image' => 'data/files/store_131/goods_101/small_201412181105019926.jpg', 'price' => '4.00', 'sales' => '3', ), 2732 => array ( 'goods_id' => '2732', 'goods_name' => '怡泉+c500ml功能饮料', 'default_image' => 'data/files/store_131/goods_115/small_201412181125154319.jpg', 'price' => '4.00', 'sales' => '1', ), 3036 => array ( 'goods_id' => '3036', 'goods_name' => '【39元区】羊毛外套 羊绒大衣', 'default_image' => 'data/files/store_131/goods_186/small_201501041619467368.jpg', 'price' => '39.00', 'sales' => '1', ), 2254 => array ( 'goods_id' => '2254', 'goods_name' => '圣牧全程有机奶1X12X250ml', 'default_image' => 'data/files/store_131/goods_69/small_201412171617496624.jpg', 'price' => '98.00', 'sales' => '1', ), 2505 => array ( 'goods_id' => '2505', 'goods_name' => '康师傅香辣牛肉面五连包103gx5方便面', 'default_image' => 'data/files/store_131/goods_70/small_201412180931105307.jpg', 'price' => '12.80', 'sales' => '0', ), 2100 => array ( 'goods_id' => '2100', 'goods_name' => '蜡笔小新雪梨味可吸果冻80g', 'default_image' => 'data/files/store_131/goods_29/small_201412171350295329.jpg', 'price' => '1.00', 'sales' => '0', ), ), 'collect_goodslist' => array ( 2824 => array ( 'goods_id' => '2824', 'goods_name' => '蒙牛冠益乳草莓味风味发酵乳450g', 'default_image' => 'data/files/store_131/goods_12/small_201412181310121305.jpg', 'price' => '13.50', 'collects' => '1', ), 2481 => array ( 'goods_id' => '2481', 'goods_name' => '心相印红卷纸单包装120g卫生纸', 'default_image' => 'data/files/store_131/goods_71/small_201412180914313610.jpg', 'price' => '2.50', 'collects' => '1', ), 5493 => array ( 'goods_id' => '5493', 'goods_name' => '青岛啤酒奥古特500ml', 'default_image' => 'data/files/store_42/goods_0/small_201412181433205122.jpg', 'price' => '9.80', 'collects' => '1', ), 2895 => array ( 'goods_id' => '2895', 'goods_name' => '品食客手抓饼葱香味400g速冻食品', 'default_image' => 'data/files/store_131/goods_103/small_201412181421434694.jpg', 'price' => '11.80', 'collects' => '1', ), 2483 => array ( 'goods_id' => '2483', 'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状', 'default_image' => 'data/files/store_131/goods_110/small_201412180915101043.jpg', 'price' => '9.60', 'collects' => '1', ), 2067 => array ( 'goods_id' => '2067', 'goods_name' => '黑牛高钙豆奶粉480g', 'default_image' => 'data/files/store_131/goods_19/small_201412171103393194.gif', 'price' => '15.80', 'collects' => '1', ), 2594 => array ( 'goods_id' => '2594', 'goods_name' => '康师傅蜂蜜绿茶490ml', 'default_image' => 'data/files/store_131/goods_10/small_201412181016503047.jpg', 'price' => '3.00', 'collects' => '1', ), 2154 => array ( 'goods_id' => '2154', 'goods_name' => '迪士尼巧克力味心宠杯25g', 'default_image' => 'data/files/store_131/goods_110/small_201412171515106856.jpg', 'price' => '2.50', 'collects' => '1', ), 2801 => array ( 'goods_id' => '2801', 'goods_name' => '海天苹果醋450ml', 'default_image' => 'data/files/store_131/goods_47/small_201412181157271271.jpg', 'price' => '6.50', 'collects' => '1', ), 2505 => array ( 'goods_id' => '2505', 'goods_name' => '康师傅香辣牛肉面五连包103gx5方便面', 'default_image' => 'data/files/store_131/goods_70/small_201412180931105307.jpg', 'price' => '12.80', 'collects' => '0', ), ), 'left_rec_goods' => array ( 2067 => array ( 'goods_name' => '黑牛高钙豆奶粉480g', 'default_image' => 'data/files/store_131/goods_19/small_201412171103393194.gif', 'price' => '15.80', 'sales' => '7', 'goods_id' => '2067', ), 2481 => array ( 'goods_name' => '心相印红卷纸单包装120g卫生纸', 'default_image' => 'data/files/store_131/goods_71/small_201412180914313610.jpg', 'price' => '2.50', 'sales' => '4', 'goods_id' => '2481', ), 2594 => array ( 'goods_name' => '康师傅蜂蜜绿茶490ml', 'default_image' => 'data/files/store_131/goods_10/small_201412181016503047.jpg', 'price' => '3.00', 'sales' => '0', 'goods_id' => '2594', ), 2483 => array ( 'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状', 'default_image' => 'data/files/store_131/goods_110/small_201412180915101043.jpg', 'price' => '9.60', 'sales' => '7', 'goods_id' => '2483', ), 5493 => array ( 'goods_name' => '青岛啤酒奥古特500ml', 'default_image' => 'data/files/store_42/goods_0/small_201412181433205122.jpg', 'price' => '9.80', 'sales' => '0', 'goods_id' => '5493', ), ), ), 'cur_local' => array ( 0 => array ( 'text' => '所有分类', 'url' => 'index.php?app=category', ), 1 => array ( 'text' => '生鲜', 'url' => 'index.php?app=search&amp;cate_id=780', ), 2 => array ( 'text' => '冷冻食品', 'url' => 'index.php?app=search&amp;cate_id=810', ), 3 => array ( 'text' => '商品详情', ), ), 'share' => array ( 4 => array ( 'title' => '开心网', 'link' => 'http://www.kaixin001.com/repaste/share.php?rtitle=%E7%83%A4%E5%B9%B2%E7%86%9F%E8%99%BE%E7%9A%AE100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E&rurl=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D2397', 'type' => 'share', 'sort_order' => 255, 'logo' => 'data/system/kaixin001.gif', ), 3 => array ( 'title' => 'QQ书签', 'link' => 'http://shuqian.qq.com/post?from=3&title=%E7%83%A4%E5%B9%B2%E7%86%9F%E8%99%BE%E7%9A%AE100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&uri=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D2397&jumpback=2&noui=1', 'type' => 'collect', 'sort_order' => 255, 'logo' => 'data/system/qqshuqian.gif', ), 2 => array ( 'title' => '人人网', 'link' => 'http://share.renren.com/share/buttonshare.do?link=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D2397&title=%E7%83%A4%E5%B9%B2%E7%86%9F%E8%99%BE%E7%9A%AE100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E', 'type' => 'share', 'sort_order' => 255, 'logo' => 'data/system/renren.gif', ), 1 => array ( 'title' => '百度收藏', 'link' => 'http://cang.baidu.com/do/add?it=%E7%83%A4%E5%B9%B2%E7%86%9F%E8%99%BE%E7%9A%AE100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&iu=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D2397&fr=ien#nw=1', 'type' => 'collect', 'sort_order' => 255, 'logo' => 'data/system/baidushoucang.gif', ), ), ); ?>
guotao2000/ecmall
temp/caches/0090/c71737c6413b27861acfd0ee34eefe35.cache.php
PHP
mit
14,910
Jx().package("T.UI.Controls", function(J){ // 严格模式 'use strict'; var _crrentPluginId = 0; var defaults = { // 选项 // fooOption: true, // 覆写 类方法 // parseData: undefined, // 事件 // onFooSelected: undefined, // onFooChange: function(e, data){} timeZone: 'Etc/UTC', // format: false, format: 'YYYY-MM-DD HH:mm:ss', dayViewHeaderFormat: 'MMMM YYYY', // extraFormats: false, stepping: 1, minDate: false, maxDate: false, useCurrent: true, // collapse: true, // locale: moment.locale(), defaultDate: false, disabledDates: false, enabledDates: false, icons: { time: 'glyphicon glyphicon-time', date: 'glyphicon glyphicon-calendar', up: 'glyphicon glyphicon-chevron-up', down: 'glyphicon glyphicon-chevron-down', previous: 'glyphicon glyphicon-chevron-left', next: 'glyphicon glyphicon-chevron-right', today: 'glyphicon glyphicon-screenshot', clear: 'glyphicon glyphicon-trash', close: 'glyphicon glyphicon-remove' }, tooltips: { today: '现在', clear: '清除', close: '关闭', selectMonth: '选择月份', prevMonth: '上一月', nextMonth: '下一月', selectYear: '选择年份', prevYear: '上一年', nextYear: '下一年', selectDecade: '选择年代', prevDecade: '上一年代', nextDecade: '下一年代', prevCentury: '上一世纪', nextCentury: '下一世纪', pickHour: '选择小时', incrementHour: '增加小时', decrementHour: '减少小时', pickMinute: '选择分钟', incrementMinute: '增加分钟', decrementMinute: '减少分钟', pickSecond: '选择秒', incrementSecond: '增加秒', decrementSecond: '减少秒', togglePeriod: 'AM/PM', selectTime: '选择时间' }, // useStrict: false, // sideBySide: false, daysOfWeekDisabled: false, calendarWeeks: false, viewMode: 'days', // toolbarPlacement: 'default', showTodayButton: true, showClear: true, showClose: true, // widgetPositioning: { // horizontal: 'auto', // vertical: 'auto' // }, // widgetParent: null, ignoreReadonly: false, keepOpen: false, focusOnShow: true, inline: false, keepInvalid: false, datepickerInput: '.datepickerinput', // debug: false, allowInputToggle: false, disabledTimeIntervals: false, disabledHours: false, enabledHours: false, // viewValue: false }; var attributeMap = { // fooOption: 'foo-option' format: 'format' }; // 常量 var viewModes = ['days', 'months', 'years', 'decades'], keyMap = { 'up': 38, 38: 'up', 'down': 40, 40: 'down', 'left': 37, 37: 'left', 'right': 39, 39: 'right', 'tab': 9, 9: 'tab', 'escape': 27, 27: 'escape', 'enter': 13, 13: 'enter', 'pageUp': 33, 33: 'pageUp', 'pageDown': 34, 34: 'pageDown', 'shift': 16, 16: 'shift', 'control': 17, 17: 'control', 'space': 32, 32: 'space', 't': 84, 84: 't', 'delete': 46, 46: 'delete' }, keyState = {}; // moment.js 接口 function getMoment (format, d) { // var tzEnabled = false, // returnMoment, // currentZoneOffset, // incomingZoneOffset, // timeZoneIndicator, // dateWithTimeZoneInfo; // if (moment.tz !== undefined && this.settings.timeZone !== undefined && this.settings.timeZone !== null && this.settings.timeZone !== '') { // tzEnabled = true; // } // if (d === undefined || d === null) { // if (tzEnabled) { // returnMoment = moment().tz(this.settings.timeZone).startOf('d'); // } else { // returnMoment = moment().startOf('d'); // } // } else { // if (tzEnabled) { // currentZoneOffset = moment().tz(this.settings.timeZone).utcOffset(); // incomingZoneOffset = moment(d, parseFormats, this.settings.useStrict).utcOffset(); // if (incomingZoneOffset !== currentZoneOffset) { // timeZoneIndicator = moment().tz(this.settings.timeZone).format('Z'); // dateWithTimeZoneInfo = moment(d, parseFormats, this.settings.useStrict).format('YYYY-MM-DD[T]HH:mm:ss') + timeZoneIndicator; // returnMoment = moment(dateWithTimeZoneInfo, parseFormats, this.settings.useStrict).tz(this.settings.timeZone); // } else { // returnMoment = moment(d, parseFormats, this.settings.useStrict).tz(this.settings.timeZone); // } // } else { // returnMoment = moment(d, parseFormats, this.settings.useStrict); // } // } var returnMoment; if (d === undefined || d === null) { returnMoment= moment().startOf('d'); } else{ // returnMoment = moment(d, format, this.settings.useStrict); // Moment's parser is very forgiving, and this can lead to undesired behavior. // As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. // Strict parsing requires that the format and input match exactly. returnMoment = moment(d, format, false); } return returnMoment; } // 格式,细粒度 function isEnabled(format, granularity) { switch (granularity) { case 'y': return format.indexOf('Y') !== -1; case 'M': return format.indexOf('M') !== -1; case 'd': return format.toLowerCase().indexOf('d') !== -1; case 'h': case 'H': return format.toLowerCase().indexOf('h') !== -1; case 'm': return format.indexOf('m') !== -1; case 's': return format.indexOf('s') !== -1; default: return false; } } function hasTime(format) { return (isEnabled(format, 'h') || isEnabled(format, 'm') || isEnabled(format, 's')); } function hasDate(format) { return (isEnabled(format, 'y') || isEnabled(format, 'M') || isEnabled(format, 'd')); } function isValid(settings, targetMoment, granularity) { if (!targetMoment.isValid()) { return false; } if (settings.disabledDates && granularity === 'd' && settings.disabledDates[targetMoment.format('YYYY-MM-DD')] === true) { return false; } if (settings.enabledDates && granularity === 'd' && (settings.enabledDates[targetMoment.format('YYYY-MM-DD')] !== true)) { return false; } if (settings.minDate && targetMoment.isBefore(settings.minDate, granularity)) { return false; } if (settings.maxDate && targetMoment.isAfter(settings.maxDate, granularity)) { return false; } if (settings.daysOfWeekDisabled && granularity === 'd' && settings.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) { return false; } if (settings.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && settings.disabledHours[targetMoment.format('H')] === true) { return false; } if (settings.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && (settings.enabledHours[targetMoment.format('H')] !== true)) { return false; } if (settings.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) { var found = false; $.each(settings.disabledTimeIntervals, function () { if (targetMoment.isBetween(this[0], this[1])) { found = true; return false; } }); if (found) { return false; } } return true; } // notifyEvent: function (e) { // if (e.type === 'dp.change' && ((e.date && e.date.isSame(e.oldDate)) || (!e.date && !e.oldDate))) { // return; // } // element.trigger(e); // }, var Widget=new J.Class({ defaults: defaults, attributeMap: attributeMap, settings: {}, value: null, // data: {}, // templates: {}, use24Hours: false, minViewModeNumber: 0, // 最小视图模式,选到这个模式以后关闭弹出窗口。 currentViewMode: 0, // 构造函数 init: function(elements, options){ this.inputElements = elements; // 直接使用容器类实例的设置 this.settings=options; // // TODO:临时措施 // this.use24Hours= false; // this.currentViewMode= 0; this.initFormatting(); // this.initSettings(options); // // this.value= this.element.val(); var now= getMoment(this.settings.format); this.value= now; this.viewValue=this.value; this.buildHtml(); this.initElements(); this.buildObservers(); this.bindEvents(); // this.bindEventsInterface(); this.refresh(); }, initFormatting: function () { // Time LT 8:30 PM // Time with seconds LTS 8:30:25 PM // Month numeral, day of month, year L 09/04/1986 // l 9/4/1986 // Month name, day of month, year LL September 4 1986 // ll Sep 4 1986 // Month name, day of month, year, time LLL September 4 1986 8:30 PM // lll Sep 4 1986 8:30 PM // Month name, day of month, day of week, year, time LLLL Thursday, September 4 1986 8:30 PM // llll Thu, Sep 4 1986 8:30 PM // var format= this.settings.format || 'L LT'; // var context= this; // this.actualFormat = format.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) { // var value= context.getValue(); // var newinput = value.localeData().longDateFormat(formatInput) || formatInput; // return newinput.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput2) { //temp fix for #740 // return value.localeData().longDateFormat(formatInput2) || formatInput2; // }); // }); // parseFormats = this.settings.extraFormats ? this.settings.extraFormats.slice() : []; // parseFormats = []; // if (parseFormats.indexOf(format) < 0 && parseFormats.indexOf(this.actualFormat) < 0) { // parseFormats.push(this.actualFormat); // } // this.use24Hours = (this.actualFormat.toLowerCase().indexOf('a') < 1 && this.actualFormat.replace(/\[.*?\]/g, '').indexOf('h') < 1); this.use24Hours = (this.settings.format.toLowerCase().indexOf('a') < 1 && this.settings.format.replace(/\[.*?\]/g, '').indexOf('h') < 1); if (isEnabled(this.settings.format, 'y')) { this.minViewModeNumber = 2; } if (isEnabled(this.settings.format, 'M')) { this.minViewModeNumber = 1; } if (isEnabled(this.settings.format, 'd')) { this.minViewModeNumber = 0; } this.currentViewMode = Math.max(this.minViewModeNumber, this.currentViewMode); }, buildHtml: function(){ // 星期表头 var currentDate= this.viewValue.clone().startOf('w').startOf('d'); var htmlDow= this.settings.calendarWeeks === true ? '<th class="cw">#</th>' : ''; while (currentDate.isBefore(this.viewValue.clone().endOf('w'))) { htmlDow += '<th class="dow">'+currentDate.format('dd')+'</th>'; currentDate.add(1, 'd'); } htmlDow= '<tr>'+htmlDow+'</tr>'; // 月份 var monthsShort = this.viewValue.clone().startOf('y').startOf('d'); var htmlMonths= ''; while (monthsShort.isSame(this.viewValue, 'y')) { htmlMonths += '<span class="month" data-action="selectMonth">'+monthsShort.format('MMM')+'</span>'; monthsShort.add(1, 'M'); } // 日期视图 var dateView = ''+ '<div class="datepicker'+((hasDate(this.settings.format) && hasTime(this.settings.format)) ? ' col-md-6' : '')+'">'+ ' <div class="datepicker-days">'+ ' <table class="table-condensed">'+ ' <thead>'+ ' <tr>'+ ' <th class="prev" data-action="previous"><span class="'+this.settings.icons.previous+'" title="'+this.settings.tooltips.prevMonth+'"></span></th>'+ ' <th class="picker-switch" data-action="pickerSwitch" colspan="'+(this.settings.calendarWeeks ? '6' : '5')+'" title="'+this.settings.tooltips.selectMonth+'"></th>'+ ' <th class="next" data-action="next"><span class="'+this.settings.icons.next+'" title="'+this.settings.tooltips.nextMonth+'"></span></th>'+ ' </tr>'+ htmlDow+ ' </thead>'+ ' <tbody>'+ ' </tbody>'+ ' <table/>'+ ' </div>'+ ' <div class="datepicker-months">'+ ' <table class="table-condensed">'+ ' <thead>'+ ' <tr>'+ ' <th class="prev" data-action="previous"><span class="'+this.settings.icons.previous+'" title="'+this.settings.tooltips.prevYear+'"></span></th>'+ ' <th class="picker-switch" data-action="pickerSwitch" colspan="'+(this.settings.calendarWeeks ? '6' : '5')+'" title="'+this.settings.tooltips.selectYear+'"></th>'+ ' <th class="next" data-action="next"><span class="'+this.settings.icons.next+'" title="'+this.settings.tooltips.nextYear+'"></span></th>'+ ' </tr>'+ ' </thead>'+ ' <tbody>'+ ' <tr><td colspan="'+(this.settings.calendarWeeks ? '8' : '7')+'">'+htmlMonths+'</td></tr>'+ ' </tbody>'+ ' <table/>'+ ' </div>'+ ' <div class="datepicker-years">'+ ' <table class="table-condensed">'+ ' <thead>'+ ' <tr>'+ ' <th class="prev" data-action="previous"><span class="'+this.settings.icons.previous+'" title="'+this.settings.tooltips.prevDecade+'"></span></th>'+ ' <th class="picker-switch" data-action="pickerSwitch" colspan="'+(this.settings.calendarWeeks ? '6' : '5')+'" title="'+this.settings.tooltips.selectDecade+'"></th>'+ ' <th class="next" data-action="next"><span class="'+this.settings.icons.next+'" title="'+this.settings.tooltips.nextDecade+'"></span></th>'+ ' </tr>'+ ' </thead>'+ ' <tbody>'+ ' <tr><td colspan="'+(this.settings.calendarWeeks ? '8' : '7')+'"></td></tr>'+ ' </tbody>'+ ' <table/>'+ ' </div>'+ ' <div class="datepicker-decades">'+ ' <table class="table-condensed">'+ ' <thead>'+ ' <tr>'+ ' <th class="prev" data-action="previous"><span class="'+this.settings.icons.previous+'" title="'+this.settings.tooltips.prevCentury+'"></span></th>'+ ' <th class="picker-switch" data-action="pickerSwitch" colspan="'+(this.settings.calendarWeeks ? '6' : '5')+'"></th>'+ ' <th class="next" data-action="next"><span class="'+this.settings.icons.next+'" title="'+this.settings.tooltips.nextCentury+'"></span></th>'+ ' </tr>'+ ' </thead>'+ ' <tbody>'+ ' <tr><td colspan="'+(this.settings.calendarWeeks ? '8' : '7')+'"></td></tr>'+ ' </tbody>'+ ' <table/>'+ ' </div>'+ '</div>'; // 小时选择按钮 var htmlHours= ''; if(isEnabled(this.settings.format, 'h')){ var currentHour = this.viewValue.clone().startOf('d'); if (this.viewValue.hour() > 11 && !this.use24Hours) { currentHour.hour(12); } while (currentHour.isSame(this.viewValue, 'd') && (this.use24Hours || (this.viewValue.hour() < 12 && currentHour.hour() < 12) || this.viewValue.hour() > 11)) { if (currentHour.hour() % 4 === 0) { htmlHours += '<tr>'; } htmlHours += ''+ '<td data-action="selectHour" class="hour' + (!isValid(this.settings,currentHour, 'h') ? ' disabled' : '') + '">' + currentHour.format(this.use24Hours ? 'HH' : 'hh') + '</td>'; if (currentHour.hour() % 4 === 3) { htmlHours += '</tr>'; } currentHour.add(1, 'h'); } } // 分钟选择按钮 var htmlMinutes= ''; if(isEnabled(this.settings.format, 'm')){ var currentMinute = this.viewValue.clone().startOf('h'); var step = this.settings.stepping === 1 ? 5 : this.settings.stepping; while (this.viewValue.isSame(currentMinute, 'h')) { if (currentMinute.minute() % (step * 4) === 0) { htmlMinutes += '<tr>'; } htmlMinutes +=''+ '<td data-action="selectMinute" class="minute' + (!isValid(this.settings,currentMinute, 'm') ? ' disabled' : '') + '">' + currentMinute.format('mm') + '</td>'; if (currentMinute.minute() % (step * 4) === step * 3) { htmlMinutes += '</tr>'; } currentMinute.add(step, 'm'); } } // 秒选择按钮 var htmlSeconds= ''; if(isEnabled(this.settings.format, 's')){ var currentSecond = this.viewValue.clone().startOf('m'); while (this.viewValue.isSame(currentSecond, 'm')) { if (currentSecond.second() % 20 === 0) { htmlSeconds += '<tr>'; } htmlSeconds += ''+ '<td data-action="selectSecond" class="second' + (!isValid(this.settings,currentSecond, 's') ? ' disabled' : '') + '">' + currentSecond.format('ss') + '</td>'; if (currentSecond.second() % 20 === 15) { htmlSeconds += '</tr>'; } currentSecond.add(5, 's'); } } // 时间视图 var timeView = ''+ '<div class="timepicker'+((hasDate(this.settings.format) && hasTime(this.settings.format)) ? ' col-md-6' : '')+'">'+ ' <div class="timepicker-picker">'+ ' <table class="table-condensed">'+ ' <tr>'+ (isEnabled(this.settings.format, 'h') ? ' <td>'+ ' <a href="#" class="btn" data-action="incrementHours" tabindex="-1" title="'+this.settings.tooltips.incrementHour+'">'+ ' <span class="'+this.settings.icons.up+'"></span>'+ ' </a>'+ ' </td>' : '')+ (isEnabled(this.settings.format, 'm') ? ((isEnabled(this.settings.format, 'h') ? ' <td class="separator"></td>' : '')+ ' <td>'+ ' <a href="#" class="btn" data-action="incrementMinutes" tabindex="-1" title="'+this.settings.tooltips.incrementMinute+'">'+ ' <span class="'+this.settings.icons.up+'"></span>'+ ' </a>'+ ' </td>') : '')+ (isEnabled(this.settings.format, 's') ? ((isEnabled(this.settings.format, 'm') ? ' <td class="separator"></td>' : '')+ ' <td>'+ ' <a href="#" class="btn" data-action="incrementSeconds" tabindex="-1" title="'+this.settings.tooltips.incrementSecond+'">'+ ' <span class="'+this.settings.icons.up+'"></span>'+ ' </a>'+ ' </td>') : '')+ (this.use24Hours ? ' <td class="separator"></td>' : '')+ ' </tr>'+ ' <tr>'+ (isEnabled(this.settings.format, 'h') ? ' <td>'+ ' <span class="timepicker-hour" data-action="showHours" data-time-component="hours" title="'+this.settings.tooltips.pickHour+'"></span>'+ ' </td>' : '')+ (isEnabled(this.settings.format, 'm') ? ((isEnabled(this.settings.format, 'h') ? ' <td class="separator">:</td>' : '')+ ' <td>'+ ' <span class="timepicker-minute" data-action="showMinutes" data-time-component="minutes" title="'+this.settings.tooltips.pickMinute+'"></span>'+ ' </td>') : '')+ (isEnabled(this.settings.format, 's') ? ((isEnabled(this.settings.format, 'm') ? ' <td class="separator">:</td>' : '')+ ' <td>'+ ' <span class="timepicker-second" data-action="showSeconds" data-time-component="seconds" title="'+this.settings.tooltips.pickSecond+'"></span>'+ ' </td>') : '')+ (this.use24Hours ? ' <td class="separator">'+ ' <button class="btn btn-primary" data-action="togglePeriod" tabindex="-1" title="'+this.settings.tooltips.togglePeriod+'"></button>'+ ' </td>' : '')+ ' </tr>'+ ' <tr>'+ ' <td>'+ ' <a href="#" class="btn" data-action="decrementHours" tabindex="-1" title="'+this.settings.tooltips.decrementHour+'">'+ ' <span class="'+this.settings.icons.down+'"></span>'+ ' </a>'+ ' </td>'+ (isEnabled(this.settings.format, 'm') ? ((isEnabled(this.settings.format, 'h') ? ' <td class="separator"></td>' : '')+ ' <td>'+ ' <a href="#" class="btn" data-action="decrementMinutes" tabindex="-1" title="'+this.settings.tooltips.decrementMinute+'">'+ ' <span class="'+this.settings.icons.down+'"></span>'+ ' </a>'+ ' </td>') : '')+ (isEnabled(this.settings.format, 's') ? ((isEnabled(this.settings.format, 'm') ? ' <td class="separator"></td>' : '')+ ' <td>'+ ' <a href="#" class="btn" data-action="decrementSeconds" tabindex="-1" title="'+this.settings.tooltips.decrementSecond+'">'+ ' <span class="'+this.settings.icons.down+'"></span>'+ ' </a>'+ ' </td>') : '')+ (this.use24Hours ? ' <td class="separator"></td>' : '')+ ' </tr>'+ ' </table>'+ ' </div>'+ (isEnabled(this.settings.format, 'h') ? ' <div class="timepicker-hours">'+ ' <table class="table-condensed">'+htmlHours+'</table>'+ ' </div>' : '')+ (isEnabled(this.settings.format, 'm') ? ' <div class="timepicker-minutes">'+ ' <table class="table-condensed">'+htmlMinutes+'</table>'+ ' </div>' : '')+ (isEnabled(this.settings.format, 's') ? ' <div class="timepicker-seconds">'+ ' <table class="table-condensed">'+htmlSeconds+'</table>'+ ' </div>' : '')+ '</div>'; var toolbar2 = ''+ '<table class="table-condensed">'+ ' <tbody>'+ ' <tr>'+ (this.settings.showTodayButton ? ' <td><a data-action="today" title="'+this.settings.tooltips.today+'"><span class="'+this.settings.icons.today+'"></span></a></td>' : '')+ // ((!this.settings.sideBySide && hasDate(this.settings.format) && hasTime(this.settings.format))? // ' <td><a data-action="togglePicker" title="'+this.settings.tooltips.selectTime+'"><span class="'+this.settings.icons.time+'"></span></a></td>' : '')+ (this.settings.showClear ? ' <td><a data-action="clear" title="'+this.settings.tooltips.clear+'"><span class="'+this.settings.icons.clear+'"></span></a></td>' : '')+ (this.settings.showClose ? ' <td><a data-action="close" title="'+this.settings.tooltips.close+'"><span class="'+this.settings.icons.close+'"></span></a></td>' : '')+ ' </tr>'+ ' </tbody>'+ '</table>'; // var toolbar = '<li class="'+'picker-switch' + (this.settings.collapse ? ' accordion-toggle' : '')+'">'+toolbar2+'<li>'; var toolbar = '<li class="picker-switch">'+toolbar2+'<li>'; var templateCssClass= 't-dtpicker-widget'; if (!this.settings.inline) { templateCssClass += ' dropdown-menu'; } if (this.use24Hours) { templateCssClass += ' usetwentyfour'; } if (isEnabled(this.settings.format, 's') && !this.use24Hours) { templateCssClass += ' wider'; } var htmlTemplate = ''; if (hasDate(this.settings.format) && hasTime(this.settings.format)) { htmlTemplate = ''+ '<div class="'+templateCssClass+' timepicker-sbs">'+ ' <div class="row">'+ dateView+ timeView+ toolbar+ ' </div>'+ '</div>'; } else{ htmlTemplate = ''+ '<div class="'+templateCssClass+'">'+ ' <ul class="list-unstyled">'+ (hasDate(this.settings.format) ? ' <li>'+dateView+'</li>' : '')+ // '+(this.settings.collapse && hasTime(this.settings.format) ? ' class="collapse in"' : '')+' (hasTime(this.settings.format) ? ' <li>'+dateView+'</li>' : '')+ // '+(this.settings.collapse && hasTime(this.settings.format) ? ' class="collapse in"' : '')+' ' <li>'+toolbar+'</li>'+ ' </ul>'+ '</div>'; } this.container= $(htmlTemplate); this.inputElements.view.after(this.container); // this.inputElements.widgetContainer.append(this.container); }, initElements: function(){ // var context= this; this.elements={ // original: this.element//, decades: $('.datepicker-decades', this.container), years: $('.datepicker-years', this.container), months: $('.datepicker-months', this.container), days: $('.datepicker-days', this.container), hour: $('.timepicker-hour', this.container), hours: $('.timepicker-hours', this.container), minute: $('.timepicker-minute', this.container), minutes: $('.timepicker-minutes', this.container), second: $('.timepicker-second', this.container), seconds: $('.timepicker-seconds', this.container)//, // view: $('input[type=text]', this.container) // getTab: function(levelIndex){ // var tabSelector='.t-level-tab-'+levelIndex; // return $(tabSelector, context.container); // } }; if(this.settings.inline){ this.show(); } this.elements.hours.hide(); this.elements.minutes.hide(); this.elements.seconds.hide(); }, buildObservers: function(){ var context= this; var datePickerModes= [ { navFnc: 'M', navStep: 1 }, { navFnc: 'y', navStep: 1 }, { navFnc: 'y', navStep: 10 }, { navFnc: 'y', navStep: 100 } ]; this.observers= { next: function () { var navStep = datePickerModes[this.currentViewMode].navStep; var navFnc = datePickerModes[this.currentViewMode].navFnc; this.viewValue.add(navStep, navFnc); // TODO: with ViewMode this.refreshDate(); // viewUpdate(navFnc); }, previous: function () { var navFnc = datePickerModes[this.currentViewMode].navFnc; var navStep = datePickerModes[this.currentViewMode].navStep; this.viewValue.subtract(navStep, navFnc); // TODO: with ViewMode this.refreshDate(); // viewUpdate(navFnc); }, pickerSwitch: function () { this.showMode(1); }, selectMonth: function (e) { var month = $(e.target).closest('tbody').find('span').index($(e.target)); this.viewValue.month(month); if (this.currentViewMode === this.minViewModeNumber) { this.setValue(this.value.clone().year(this.viewValue.year()).month(this.viewValue.month())); if (!this.settings.inline) { this.hide(); } } else { this.showMode(-1); // fillDate(); this.refreshDays(); } // viewUpdate('M'); }, selectYear: function (e) { var year = parseInt($(e.target).text(), 10) || 0; this.viewValue.year(year); if (this.currentViewMode === this.minViewModeNumber) { this.setValue(this.value.clone().year(this.viewValue.year())); if (!this.settings.inline) { this.hide(); } } else { this.showMode(-1); this.refreshMonths(); } // viewUpdate('YYYY'); }, selectDecade: function (e) { var year = parseInt($(e.target).data('selection'), 10) || 0; this.viewValue.year(year); if (this.currentViewMode === this.minViewModeNumber) { this.setValue(this.value.clone().year(this.viewValue.year())); if (!this.settings.inline) { this.hide(); } } else { this.showMode(-1); this.refreshYears(); } // viewUpdate('YYYY'); }, selectDay: function (e) { var day = this.viewValue.clone(); if ($(e.target).is('.old')) { day.subtract(1, 'M'); } if ($(e.target).is('.new')) { day.add(1, 'M'); } this.setValue(day.date(parseInt($(e.target).text(), 10))); if (!hasTime(this.settings.format) && !this.settings.keepOpen && !this.settings.inline) { this.hide(); } }, incrementHours: function () { var newDate = this.value.clone().add(1, 'h'); if (isValid(this.settings,newDate, 'h')) { this.setValue(newDate); } }, incrementMinutes: function () { var newDate = this.value.clone().add(this.settings.stepping, 'm'); if (isValid(this.settings,newDate, 'm')) { this.setValue(newDate); } }, incrementSeconds: function () { var newDate = this.value.clone().add(1, 's'); if (isValid(this.settings,newDate, 's')) { this.setValue(newDate); } }, decrementHours: function () { var newDate = this.value.clone().subtract(1, 'h'); if (isValid(this.settings,newDate, 'h')) { this.setValue(newDate); } }, decrementMinutes: function () { var newDate = this.value.clone().subtract(this.settings.stepping, 'm'); if (isValid(this.settings,newDate, 'm')) { this.setValue(newDate); } }, decrementSeconds: function () { var newDate = this.value.clone().subtract(1, 's'); if (isValid(this.settings,newDate, 's')) { this.setValue(newDate); } }, togglePeriod: function () { this.setValue(this.value.clone().add((this.value.hours() >= 12) ? -12 : 12, 'h')); }, // togglePicker: function (e) { // var $this = $(e.target), // $parent = $this.closest('ul'), // expanded = $parent.find('.in'), // closed = $parent.find('.collapse:not(.in)'), // collapseData; // if (expanded && expanded.length) { // collapseData = expanded.data('collapse'); // if (collapseData && collapseData.transitioning) { // return; // } // if (expanded.collapse) { // if collapse plugin is available through bootstrap.js then use it // expanded.collapse('hide'); // closed.collapse('show'); // } else { // otherwise just toggle in class on the two views // expanded.removeClass('in'); // closed.addClass('in'); // } // if ($this.is('span')) { // $this.toggleClass(this.settings.icons.time + ' ' + this.settings.icons.date); // } else { // $this.find('span').toggleClass(this.settings.icons.time + ' ' + this.settings.icons.date); // } // // NOTE: uncomment if toggled state will be restored in show() // //if (component) { // // component.find('span').toggleClass(this.settings.icons.time + ' ' + this.settings.icons.date); // //} // } // }, showPicker: function () { context.container.find('.timepicker > div:not(.timepicker-picker)').hide(); context.container.find('.timepicker .timepicker-picker').show(); }, showHours: function () { context.container.find('.timepicker .timepicker-picker').hide(); context.container.find('.timepicker .timepicker-hours').show(); }, showMinutes: function () { context.container.find('.timepicker .timepicker-picker').hide(); context.container.find('.timepicker .timepicker-minutes').show(); }, showSeconds: function () { context.container.find('.timepicker .timepicker-picker').hide(); context.container.find('.timepicker .timepicker-seconds').show(); }, selectHour: function (e) { var hour = parseInt($(e.target).text(), 10); if (!this.use24Hours) { if (this.value.hours() >= 12) { if (hour !== 12) { hour += 12; } } else { if (hour === 12) { hour = 0; } } } this.setValue(this.value.clone().hours(hour)); this.observers.showPicker.call(this); }, selectMinute: function (e) { this.setValue(this.value.clone().minutes(parseInt($(e.target).text(), 10))); this.observers.showPicker(); }, selectSecond: function (e) { this.setValue(this.value.clone().seconds(parseInt($(e.target).text(), 10))); this.observers.showPicker(); }, clear: function(){ this.clear(); }, today: function () { var todaysDate = getMoment(); if (isValid(this.settings,todaysDate, 'd')) { this.setValue(todaysDate); } }, close: function(){ this.hide(); } }; this.keyBinds= { up: function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(7, 'd')); } else { this.date(d.clone().add(this.stepping(), 'm')); } }, down: function (widget) { if (!widget) { this.show(); return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(7, 'd')); } else { this.date(d.clone().subtract(this.stepping(), 'm')); } }, 'control up': function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'y')); } else { this.date(d.clone().add(1, 'h')); } }, 'control down': function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'y')); } else { this.date(d.clone().subtract(1, 'h')); } }, left: function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'd')); } }, right: function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'd')); } }, pageUp: function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'M')); } }, pageDown: function (widget) { if (!widget) { return; } var d = this.date() || getMoment(this.settings.format); if (widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'M')); } }, enter: function () { this.hide(); }, escape: function () { this.hide(); }, //tab: function (widget) { //this break the flow of the form. disabling for now // var toggle = widget.find('.picker-switch a[data-action="togglePicker"]'); // if(toggle.length > 0) toggle.click(); //}, 'control space': function (widget) { if (widget.find('.timepicker').is(':visible')) { widget.find('.btn[data-action="togglePeriod"]').click(); } }, t: function () { this.date(getMoment(this.settings.format)); }, 'delete': function () { this.clear(); } }; }, bindEvents: function(){ var context= this; var element= this.element; this.inputElements.button.on('click', $.proxy(this.show, this)); this.container.on('click', '[data-action]', $.proxy(this.doAction, this)); // this handles clicks on the widget this.container.on('mousedown', false); $(window).on('resize', $.proxy(this.place, this)); // element.on('click', $.proxy(this.onFooClick, this)); }, // bindEventsInterface: function(){ // var context= this; // var element= this.element; // if(this.settings.onFooSelected){ // element.on('click.t.template', $.proxy(this.settings.onFooSelected, this)); // } // }, render: function(){}, // 事件处理 // onFooClick: function(e, data){ // ; // }, place: function () { // var position = (component || element).position(), // offset = (component || element).offset(), var position = this.inputElements.view.position(); var offset = this.inputElements.view.offset(); // vertical = this.settings.widgetPositioning.vertical, // horizontal = this.settings.widgetPositioning.horizontal, var vertical; var horizontal; var parent; // if (this.settings.widgetParent) { // parent = this.settings.widgetParent.append(widget); // } else if (element.is('input')) { // parent = this.inputElements.view.after(this.container).parent(); // } else if (this.settings.inline) { // parent = this.inputElements.view.append(widget); // return; // } else { // parent = this.inputElements.view; // this.inputElements.view.children().first().after(widget); // } parent = this.inputElements.view.parent(); // Top and bottom logic // if (vertical === 'auto') { if (offset.top + this.container.height() * 1.5 >= $(window).height() + $(window).scrollTop() && this.container.height() + this.inputElements.view.outerHeight() < offset.top) { vertical = 'top'; } else { vertical = 'bottom'; } // } // // Left and right logic // if (horizontal === 'auto') { if (parent.width() < offset.left + this.container.outerWidth() / 2 && offset.left + this.container.outerWidth() > $(window).width()) { horizontal = 'right'; } else { horizontal = 'left'; } // } if (vertical === 'top') { this.container.addClass('top').removeClass('bottom'); } else { this.container.addClass('bottom').removeClass('top'); } if (horizontal === 'right') { this.container.addClass('pull-right'); } else { this.container.removeClass('pull-right'); } // find the first parent element that has a relative css positioning if (parent.css('position') !== 'relative') { parent = parent.parents().filter(function () { return $(this).css('position') === 'relative'; }).first(); } // if (parent.length === 0) { // throw new Error('datetimepicker component should be placed within a relative positioned container'); // } this.container.css({ top: vertical === 'top' ? 'auto' : position.top + this.inputElements.view.outerHeight(), bottom: vertical === 'top' ? position.top + this.inputElements.view.outerHeight() : 'auto', left: horizontal === 'left' ? (parent === this.inputElements.view ? 0 : position.left) : 'auto', right: horizontal === 'left' ? 'auto' : parent.outerWidth() - this.inputElements.view.outerWidth() - (parent === this.inputElements.view ? 0 : position.left) }); }, // viewUpdate: function (e) { // if (e === 'y') { // e = 'YYYY'; // } // // notifyEvent({ // // type: 'dp.update', // // change: e, // // viewValue: this.viewValue.clone() // // }); // }, // dir 方向 加一或减一 showMode: function (dir) { if (dir) { this.currentViewMode = Math.max(this.minViewModeNumber, Math.min(3, this.currentViewMode + dir)); } // this.container.find('.datepicker > div').hide().filter('.datepicker-' + datePickerModes[this.currentViewMode].clsName).show(); this.container.find('.datepicker > div').hide().filter('.datepicker-' + viewModes[this.currentViewMode]).show(); }, fillDate: function () { }, fillTime: function () { }, // update: function () { // if (!widget) { // return; // } // fillDate(); // fillTime(); // }, // setValue: function (targetMoment) { // var oldDate = unset ? null : this.value; // // case of calling setValue(null or false) // if (!targetMoment) { // unset = true; // input.val(''); // element.data('date', ''); // notifyEvent({ // type: 'dp.change', // date: false, // oldDate: oldDate // }); // update(); // return; // } // targetMoment = targetMoment.clone().locale(this.settings.locale); // if (this.settings.stepping !== 1) { // targetMoment.minutes((Math.round(targetMoment.minutes() / this.settings.stepping) * this.settings.stepping) % 60).seconds(0); // } // if (isValid(this.settings,targetMoment)) { // this.value = targetMoment; // this.viewValue = this.value.clone(); // input.val(this.value.format(this.actualFormat)); // element.data('date', this.value.format(this.actualFormat)); // unset = false; // update(); // notifyEvent({ // type: 'dp.change', // date: this.value.clone(), // oldDate: oldDate // }); // } else { // if (!this.settings.keepInvalid) { // input.val(unset ? '' : this.value.format(this.actualFormat)); // } // notifyEvent({ // type: 'dp.error', // date: targetMoment // }); // } // }, hide: function () { ///<summary>Hides the widget. Possibly will emit dp.hide</summary> // var transitioning = false; // if (!widget) { // return picker; // } // Ignore event if in the middle of a picker transition // this.container.find('.collapse').each(function () { // var collapseData = $(this).data('collapse'); // if (collapseData && collapseData.transitioning) { // transitioning = true; // return false; // } // return true; // }); // if (transitioning) { // return;// picker; // } // if (component && component.hasClass('btn')) { // component.toggleClass('active'); this.inputElements.button.toggleClass('active'); // } this.container.hide(); $(window).off('resize', this.place); this.container.off('click', '[data-action]'); this.container.off('mousedown', false); // this.container.remove(); // widget = false; // notifyEvent({ // type: 'dp.hide', // date: this.value.clone() // }); this.inputElements.view.blur(); // return picker; }, clear: function () { this.setValue(null); this.viewValue= getMoment(this.settings.format); }, /******************************************************************************** * * Widget UI interaction functions * ********************************************************************************/ doAction: function (e) { var jqTarget= $(e.currentTarget); if (jqTarget.is('.disabled')) { return false; } var action= jqTarget.data('action'); this.observers[action].apply(this, arguments); return false; }, show: function () { if(this.inputElements.original.prop('disabled')){ return; } // ///<summary>Shows the widget. Possibly will emit dp.show and dp.change</summary> // var currentMoment, // useCurrentGranularity = { // 'year': function (m) { // return m.month(0).date(1).hours(0).seconds(0).minutes(0); // }, // 'month': function (m) { // return m.date(1).hours(0).seconds(0).minutes(0); // }, // 'day': function (m) { // return m.hours(0).seconds(0).minutes(0); // }, // 'hour': function (m) { // return m.seconds(0).minutes(0); // }, // 'minute': function (m) { // return m.seconds(0); // } // }; // if (input.prop('disabled') || (!this.settings.ignoreReadonly && input.prop('readonly')) || widget) { // return picker; // } // if (input.val() !== undefined && input.val().trim().length !== 0) { // setValue(this.parseInputDate(input.val().trim())); // // } else if (this.settings.useCurrent && unset && ((input.is('input') && input.val().trim().length === 0) || this.settings.inline)) { // } else if (this.settings.useCurrent && ((input.is('input') && input.val().trim().length === 0) || this.settings.inline)) { // currentMoment = getMoment(); // if (typeof this.settings.useCurrent === 'string') { // currentMoment = useCurrentGranularity[this.settings.useCurrent](currentMoment); // } // setValue(currentMoment); // } // widget = getTemplate(); // fillDow(); // fillMonths(); // widget.find('.timepicker-hours').hide(); // widget.find('.timepicker-minutes').hide(); // widget.find('.timepicker-seconds').hide(); // update(); // if (component && component.hasClass('btn')) { // component.toggleClass('active'); // } // widget.show(); this.showMode(); this.place(); this.container.show(); // if (this.settings.focusOnShow && !input.is(':focus')) { // input.focus(); // } // notifyEvent({ // type: 'dp.show' // }); // return picker; }, toggle: function () { /// <summary>Shows or hides the widget</summary> return (widget ? hide() : show()); }, keydown: function (e) { var handler = null, index, index2, pressedKeys = [], pressedModifiers = {}, currentKey = e.which, keyBindKeys, allModifiersPressed, pressed = 'p'; keyState[currentKey] = pressed; for (index in keyState) { if (keyState.hasOwnProperty(index) && keyState[index] === pressed) { pressedKeys.push(index); if (parseInt(index, 10) !== currentKey) { pressedModifiers[index] = true; } } } for (index in this.settings.keyBinds) { if (this.settings.keyBinds.hasOwnProperty(index) && typeof (this.settings.keyBinds[index]) === 'function') { keyBindKeys = index.split(' '); if (keyBindKeys.length === pressedKeys.length && keyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) { allModifiersPressed = true; for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) { if (!(keyMap[keyBindKeys[index2]] in pressedModifiers)) { allModifiersPressed = false; break; } } if (allModifiersPressed) { handler = this.settings.keyBinds[index]; break; } } } } if (handler) { handler.call(picker, widget); e.stopPropagation(); e.preventDefault(); } }, keyup: function (e) { keyState[e.which] = 'r'; e.stopPropagation(); e.preventDefault(); }, change: function (e) { var val = $(e.target).val().trim(), parsedDate = val ? this.parseInputDate(val) : null; setValue(parsedDate); e.stopImmediatePropagation(); return false; }, indexGivenDates: function (givenDatesArray) { // Store given enabledDates and disabledDates as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledDates['2014-02-27'] === true) var givenDatesIndexed = {}; $.each(givenDatesArray, function () { var dDate = this.parseInputDate(this); if (dDate.isValid()) { givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true; } }); return (Object.keys(givenDatesIndexed).length) ? givenDatesIndexed : false; }, indexGivenHours: function (givenHoursArray) { // Store given enabledHours and disabledHours as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledHours['2014-02-27'] === true) var givenHoursIndexed = {}; $.each(givenHoursArray, function () { givenHoursIndexed[this] = true; }); return (Object.keys(givenHoursIndexed).length) ? givenHoursIndexed : false; }, // API refresh: function(){ this.refreshDate(); this.refreshTime(); }, refreshDate: function(){ if (!hasDate(this.settings.format)) { return; } this.refreshDecades(); this.refreshYears(); this.refreshMonths(); this.refreshDays(); }, refreshDecades: function(){ var decadesViewHeader = this.elements.decades.find('th'); var startDecade = moment({y: this.viewValue.year() - (this.viewValue.year() % 100) - 1}); var startedAt = startDecade.clone(); var endDecade = startDecade.clone().add(100, 'y'); this.elements.decades.find('.disabled').removeClass('disabled'); if (startDecade.isSame(moment({y: 1900})) || (this.settings.minDate && this.settings.minDate.isAfter(startDecade, 'y'))) { decadesViewHeader.eq(0).addClass('disabled'); } decadesViewHeader.eq(1).text(startDecade.year() + '-' + endDecade.year()); if (startDecade.isSame(moment({y: 2000})) || (this.settings.maxDate && this.settings.maxDate.isBefore(endDecade, 'y'))) { decadesViewHeader.eq(2).addClass('disabled'); } var htmlTemplate = ''; while (!startDecade.isAfter(endDecade, 'y')) { htmlTemplate += ''+ '<span '+ ' data-action="selectDecade" '+ ' class="decade' + (startDecade.isSame(this.value, 'y') ? ' active' : '') + (!isValid(this.settings,startDecade, 'y') ? ' disabled' : '') + '" '+ ' data-selection="' + (startDecade.year() + 6) + '">' + (startDecade.year() + 1) + ' - ' + (startDecade.year() + 12) + '</span>'; startDecade.add(12, 'y'); } htmlTemplate += '<span></span><span></span><span></span>'; //push the dangling block over, at least this way it's even this.elements.decades.find('td').html(htmlTemplate); decadesViewHeader.eq(1).text((startedAt.year() + 1) + '-' + (startDecade.year())); }, refreshYears: function(){ var yearsViewHeader = this.elements.years.find('th'); var startYear = this.viewValue.clone().subtract(5, 'y'); var endYear = this.viewValue.clone().add(6, 'y'); this.elements.years.find('.disabled').removeClass('disabled'); if (this.settings.minDate && this.settings.minDate.isAfter(startYear, 'y')) { yearsViewHeader.eq(0).addClass('disabled'); } yearsViewHeader.eq(1).text(startYear.year() + '-' + endYear.year()); if (this.settings.maxDate && this.settings.maxDate.isBefore(endYear, 'y')) { yearsViewHeader.eq(2).addClass('disabled'); } var htmlTemplate = ''; while (!startYear.isAfter(endYear, 'y')) { htmlTemplate += ''+ '<span '+ ' data-action="selectYear" '+ ' class="year' + (startYear.isSame(this.value, 'y') ? ' active' : '') + (!isValid(this.settings,startYear, 'y') ? ' disabled' : '') + '">' + startYear.year() + '</span>'; startYear.add(1, 'y'); } this.elements.years.find('td').html(htmlTemplate); }, refreshMonths: function(){ var monthsViewHeader = this.elements.months.find('th'); var months = this.elements.months.find('tbody').find('span'); this.elements.months.find('.disabled').removeClass('disabled'); if (!isValid(this.settings,this.viewValue.clone().subtract(1, 'y'), 'y')) { monthsViewHeader.eq(0).addClass('disabled'); } monthsViewHeader.eq(1).text(this.viewValue.year()); if (!isValid(this.settings,this.viewValue.clone().add(1, 'y'), 'y')) { monthsViewHeader.eq(2).addClass('disabled'); } // 当前月 months.removeClass('active'); if (this.value.isSame(this.viewValue, 'y')) { months.eq(this.value.month()).addClass('active'); } var context= this; months.each(function (index) { if (!isValid(context.settings,context.viewValue.clone().month(index), 'M')) { $(this).addClass('disabled'); } }); }, refreshDays: function(){ var daysViewHeader = this.elements.days.find('th'); this.elements.days.find('.disabled').removeClass('disabled'); if (!isValid(this.settings,this.viewValue.clone().subtract(1, 'M'), 'M')) { daysViewHeader.eq(0).addClass('disabled'); } daysViewHeader.eq(1).text(this.viewValue.format(this.settings.dayViewHeaderFormat)); if (!isValid(this.settings,this.viewValue.clone().add(1, 'M'), 'M')) { daysViewHeader.eq(2).addClass('disabled'); } // 本月第一个星期的第一天 var currentDate = this.viewValue.clone().startOf('M').startOf('w').startOf('d'); var htmlTemplate= ''; for (var i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks) var clsName = ''; if (currentDate.isBefore(this.viewValue, 'M')) { clsName += ' old'; } if (currentDate.isAfter(this.viewValue, 'M')) { clsName += ' new'; } if (currentDate.isSame(this.value, 'd')) { clsName += ' active'; } if (!isValid(this.settings,currentDate, 'd')) { clsName += ' disabled'; } if (currentDate.isSame(getMoment(), 'd')) { clsName += ' today'; } if (currentDate.day() === 0 || currentDate.day() === 6) { clsName += ' weekend'; } htmlTemplate += ''+ (currentDate.weekday() === 0 ? '<tr>' : '')+ (this.settings.calendarWeeks ? ' <td class="cw">'+currentDate.week()+'</td>' : '')+ ' <td '+ ' data-action="selectDay" '+ ' data-day="' + currentDate.format('L') + '" '+ ' class="day' + clsName + '">' + currentDate.date() + ' </td>'+ (currentDate.weekday() === 6 ? '</tr>' : ''); currentDate.add(1, 'd'); } this.elements.days.find('tbody').empty().append(htmlTemplate); }, refreshTime: function(){ if (!hasTime(this.settings.format)) { return; } if (!this.use24Hours) { var toggle = this.container.find('.timepicker [data-action=togglePeriod]'); var newDate = this.value.clone().add((this.value.hours() >= 12) ? -12 : 12, 'h'); toggle.text(this.value.format('A')); if (isValid(this.settings,newDate, 'h')) { toggle.removeClass('disabled'); } else { toggle.addClass('disabled'); } } this.refreshHours(); this.refreshMinutes(); this.refreshSeconds(); }, refreshHours: function(){ var currentHour = this.viewValue.clone().startOf('d'); this.elements.hour.text(currentHour.format(this.use24Hours ? 'HH' : 'hh')); }, refreshMinutes: function(){ var currentMinute = this.viewValue.clone().startOf('h'); this.elements.minute.text(currentMinute.format('mm')); }, refreshSeconds: function(){ var currentSecond = this.viewValue.clone().startOf('m'); this.elements.second.text(currentSecond.format('ss')); }, setValue: function(value){ // var oValue= this.parseInputDate(value); if(!value || !isValid(this.settings,value)){ this.inputElements.original.val(''); this.inputElements.view.val(''); this.value=null; } else{ this.inputElements.original.val(value.format(this.settings.format)); this.inputElements.view.val(value.format(this.settings.format)); this.value=value; } }, enable: function(){}, disable: function(){}, destroy: function(){} }); this.DTPicker = new J.Class({extend: T.UI.BaseControl},{ defaults: defaults, attributeMap: attributeMap, settings: {}, templates: {}, elements: {}, // minViewModeNumber: 0, // 最小视图模式,选到这个模式以后关闭弹出窗口。 // currentViewMode: 0, // use24Hours: true, // viewValue: false, // widget: false, // picker: {}, // date, // input, // component: false, // actualFormat, // parseFormats, // datePickerModes: [ // { // clsName: 'days', // navFnc: 'M', // navStep: 1 // }, // { // clsName: 'months', // navFnc: 'y', // navStep: 1 // }, // { // clsName: 'years', // navFnc: 'y', // navStep: 10 // }, // { // clsName: 'decades', // navFnc: 'y', // navStep: 100 // } // ], // verticalModes: ['top', 'bottom', 'auto'], // horizontalModes: ['left', 'right', 'auto'], // toolbarPlacements: ['default', 'top', 'bottom'], // 构造函数 init: function(element, options){ var jqElement=$(element); // this.elements.original= $(element); // // 防止多次初始化 // if (this.isInitialized()) { // return this.getRef(); // } // this.initialize(element); // $.extend(true, options, dataToOptions()); // picker.options(options); this.initSettings(jqElement, options); this.initStates(jqElement); this.buildHtml(jqElement); this.initElements(); this.buildObservers(); this.bindEvents(); // this.bindEventsInterface(); // if (!this.settings.inline && !input.is('input')) { // throw new Error('Could not initialize DateTimePicker without an input element'); // } if (this.settings.inline) { this.show(); } }, initStates: function(element){ // this.value= this.element.val(); // Set defaults for date here now instead of in var declaration // this.initFormatting(); // if (input.is('input') && input.val().trim().length !== 0) { // this.setValue(this.parseInputDate(input.val().trim())); // } // else if (this.settings.defaultDate && input.attr('placeholder') === undefined) { // this.setValue(this.settings.defaultDate); // } // this.setValue(this.parseInputDate(this.element.val().trim())); // this.setValue(this.parseInputDate(element.val().trim())); var value= this.parseInputDate(element.val().trim()); if(!value || !isValid(this.settings,value)){ element.val(''); } else{ element.val(value.format(this.settings.format)); } }, buildHtml: function(element){ var htmlTemplate = ''+ '<div class="t-dtpicker-container input-group">' + ' <input type="text" class="form-control">' + // data-toggle="dropdown" ' <div class="input-group-btn">' + ' <button type="button" class="btn btn-default">' + // data-toggle="modal" data-target="#myModal"> ' <span class="glyphicon glyphicon-calendar"></span>' + ' </button>' + ' </div>' + // ' <div class="t-dtpicker-widget-container">'+ // dropdown-menu // ' </div>'+ '</div>'; var container = $(htmlTemplate); this.elements={ original: element, container: container, view: $('input[type=text]', container), button: $('button', container)//, // widgetContainer: $('.t-dtpicker-widget-container', container)//, // getTab: function(levelIndex){ // var tabSelector='.t-level-tab-'+levelIndex; // return $(tabSelector, context.container); // } }; // this.element.after(this.container); }, initElements: function(){ // var context= this; // // initializing element and component attributes // if (this.element.is('input')) { // input = element; // } else { // input = element.find(this.settings.datepickerInput); // if (input.size() === 0) { // input = element.find('input'); // } else if (!input.is('input')) { // throw new Error('CSS class "' + this.settings.datepickerInput + '" cannot be applied to non input element'); // } // } // if (element.hasClass('input-group')) { // // in case there is more then one 'input-group-addon' Issue #48 // if (element.find('.datepickerbutton').size() === 0) { // component = element.find('.input-group-addon'); // } else { // component = element.find('.datepickerbutton'); // } // } // var elements={ // // original: this.element, // view: $('input[type=text]', this.container), // button: $('button', this.container), // widgetContainer: $('.t-dtpicker-widget-container', this.container)//, // // getTab: function(levelIndex){ // // var tabSelector='.t-level-tab-'+levelIndex; // // return $(tabSelector, context.container); // // } // }; // this.elements= $.extend(true, {}, this.elements, elements); this.elements.original.before(this.elements.container); this.elements.original.hide(); this.elements.view.val(this.elements.original.val()); if (this.elements.original.prop('disabled')) { this.disable(); } this.widget= new Widget(this.elements, this.settings); }, transferAttributes: function(){ //this.settings.placeholder = this.$source.attr('data-placeholder') || this.settings.placeholder //this.$element.attr('placeholder', this.settings.placeholder) // this.elements.target.attr('name', this.elements.original.attr('name')) // this.elements.target.val(this.elements.original.val()) // this.elements.original.removeAttr('name') // Remove from source otherwise form will pass parameter twice. this.elements.view.attr('required', this.elements.original.attr('required')) this.elements.view.attr('rel', this.elements.original.attr('rel')) this.elements.view.attr('title', this.elements.original.attr('title')) this.elements.view.attr('class', this.elements.original.attr('class')) this.elements.view.attr('tabindex', this.elements.original.attr('tabindex')) this.elements.original.removeAttr('tabindex') if (this.elements.original.attr('disabled')!==undefined){ this.disable(); } }, buildObservers: function(){}, bindEvents: function(){ var context= this; var element= this.elements.original; this.elements.view.on({ 'change': $.proxy(this.change, this), // 'blur': this.settings.debug ? '' : hide, 'blur': $.proxy(this.hide, this), 'keydown': $.proxy(this.keydown, this), 'keyup': $.proxy(this.keyup, this), // 'focus': this.settings.allowInputToggle ? show : '' 'focus': $.proxy(this.widget.show, this.widget), 'click': $.proxy(this.widget.show, this.widget) }); // if (this.elements.original.is('input')) { // input.on({ // 'focus': show // }); // } else if (component) { // component.on('click', toggle); // component.on('mousedown', false); // } // element.on('click', $.proxy(this.onFooClick, this)); }, // bindEventsInterface: function(){ // var context= this; // var element= this.elements.original; // if(this.settings.onFooSelected){ // element.on('click.t.template', $.proxy(this.settings.onFooSelected, this)); // } // }, render: function(){}, // 事件处理 // onFooClick: function(e, data){ // ; // }, parseInputDate: function (inputDate) { if (this.settings.parseInputDate === undefined) { if (moment.isMoment(inputDate) || inputDate instanceof Date) { inputDate = moment(inputDate); } else { inputDate = getMoment(this.settings.format, inputDate); } } else { inputDate = this.settings.parseInputDate(inputDate); } // inputDate.locale(this.settings.locale); return inputDate; }, // API getValue: function(){ var sValue= this.elements.original.val(); var oValue= this.parseInputDate(sValue); return oValue; }, setValue: function(value){ // var oValue= this.parseInputDate(value); if(!value || !isValid(this.settings,value)){ this.elements.original.val(''); } else{ this.elements.original.val(value.format(this.settings.format)); } }, refresh: function(){}, enable: function(){ this.elements.original.prop('disabled', false); this.elements.button.removeClass('disabled'); }, disable: function(){ this.hide(); this.elements.original.prop('disabled', true); this.elements.button.addClass('disabled'); }, destroy: function(){ this.hide(); this.elements.original.off({ 'change': change, 'blur': blur, 'keydown': keydown, 'keyup': keyup, 'focus': this.settings.allowInputToggle ? hide : '' }); // if (this.elements.original.is('input')) { // input.off({ // 'focus': show // }); // } else if (component) { // component.off('click', toggle); // component.off('mousedown', false); // } // this.elements.original.removeData('DateTimePicker'); // this.elements.original.removeData('date'); } }); });
staticmatrix/Triangle
src/framework/controls/dtpicker/dtpicker.js
JavaScript
mit
82,149
using System; namespace Webhooks.API.Exceptions { public class WebhooksDomainException : Exception { } }
albertodall/eShopOnContainers
src/Services/Webhooks/Webhooks.API/Exceptions/WebhooksDomainException.cs
C#
mit
121
using ZKWeb.Plugins.Common.Currency.src.Components.Interfaces; using ZKWebStandard.Ioc; namespace ZKWeb.Plugins.Common.Currency.src.Components.Currencies { /// <summary> /// 卢布 /// </summary> [ExportMany] public class RUB : ICurrency { public string Type { get { return "RUB"; } } public string Prefix { get { return "₽"; } } public string Suffix { get { return null; } } } }
zkweb-framework/ZKWeb.Plugins
src/ZKWeb.Plugins/Common.Currency/src/Components/Currencies/RUB.cs
C#
mit
412
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.security.keyvault.keys.cryptography.models; import com.azure.core.annotation.Immutable; import com.azure.core.util.CoreUtils; /** * Represents the details of decrypt operation result. */ @Immutable public final class DecryptResult { /** * The decrypted content. */ private final byte[] plainText; /** * The encrypyion algorithm used for the encryption operation. */ private final EncryptionAlgorithm algorithm; /** * The identifier of the key used for the decryption operation. */ private final String keyId; /** * Creates the instance of Decrypt Result holding decrypted content. * @param plainText The decrypted content. * @param algorithm The algorithm used to decrypt the content. * @param keyId The identifier of the key usd for the decryption operation. */ public DecryptResult(byte[] plainText, EncryptionAlgorithm algorithm, String keyId) { this.plainText = CoreUtils.clone(plainText); this.algorithm = algorithm; this.keyId = keyId; } /** * Get the identifier of the key used for the decryption operation * @return the key identifier */ public String getKeyId() { return keyId; } /** * Get the encrypted content. * @return The decrypted content. */ public byte[] getPlainText() { return CoreUtils.clone(plainText); } /** * Get the algorithm used for decryption. * @return The algorithm used. */ public EncryptionAlgorithm getAlgorithm() { return algorithm; } }
selvasingh/azure-sdk-for-java
sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/models/DecryptResult.java
Java
mit
1,715
<?php namespace App\Controller; use App\Controller\AppController; /** * CatsAdoptionEvents Controller * * @property \App\Model\Table\CatsAdoptionEventsTable $CatsAdoptionEvents */ class CatsAdoptionEventsController extends AppController { /** * Index method * * @return \Cake\Network\Response|null */ public function index() { $this->paginate = [ 'contain' => ['Cats', 'AdoptionEvents'] ]; $catsAdoptionEvents = $this->paginate($this->CatsAdoptionEvents); $this->set(compact('catsAdoptionEvents')); $this->set('_serialize', ['catsAdoptionEvents']); } /** * View method * * @param string|null $id Cats Adoption Event id. * @return \Cake\Network\Response|null * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function view($id = null) { $catsAdoptionEvent = $this->CatsAdoptionEvents->get($id, [ 'contain' => ['Cats', 'AdoptionEvents'] ]); $this->set('catsAdoptionEvent', $catsAdoptionEvent); $this->set('_serialize', ['catsAdoptionEvent']); } /** * Add method * * @return \Cake\Network\Response|null Redirects on successful add, renders view otherwise. */ public function add() { $catsAdoptionEvent = $this->CatsAdoptionEvents->newEntity(); if ($this->request->is('post')) { $catsAdoptionEvent = $this->CatsAdoptionEvents->patchEntity($catsAdoptionEvent, $this->request->data); if ($this->CatsAdoptionEvents->save($catsAdoptionEvent)) { $this->Flash->success(__('The cats adoption event has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The cats adoption event could not be saved. Please, try again.')); } $cats = $this->CatsAdoptionEvents->Cats->find('list', ['limit' => 200]); $adoptionEvents = $this->CatsAdoptionEvents->AdoptionEvents->find('list', ['limit' => 200]); $this->set(compact('catsAdoptionEvent', 'cats', 'adoptionEvents')); $this->set('_serialize', ['catsAdoptionEvent']); } /** * Edit method * * @param string|null $id Cats Adoption Event id. * @return \Cake\Network\Response|null Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */ public function edit($id = null) { $catsAdoptionEvent = $this->CatsAdoptionEvents->get($id, [ 'contain' => [] ]); if ($this->request->is(['patch', 'post', 'put'])) { $catsAdoptionEvent = $this->CatsAdoptionEvents->patchEntity($catsAdoptionEvent, $this->request->data); if ($this->CatsAdoptionEvents->save($catsAdoptionEvent)) { $this->Flash->success(__('The cats adoption event has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The cats adoption event could not be saved. Please, try again.')); } $cats = $this->CatsAdoptionEvents->Cats->find('list', ['limit' => 200]); $adoptionEvents = $this->CatsAdoptionEvents->AdoptionEvents->find('list', ['limit' => 200]); $this->set(compact('catsAdoptionEvent', 'cats', 'adoptionEvents')); $this->set('_serialize', ['catsAdoptionEvent']); } /** * Delete method * * @param string|null $id Cats Adoption Event id. * @return \Cake\Network\Response|null Redirects to index. * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. */ public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $catsAdoptionEvent = $this->CatsAdoptionEvents->get($id); if ($this->CatsAdoptionEvents->delete($catsAdoptionEvent)) { $this->Flash->success(__('The cats adoption event has been deleted.')); } else { $this->Flash->error(__('The cats adoption event could not be deleted. Please, try again.')); } return $this->redirect(['action' => 'index']); } }
TheParrotsAreComing/PAWS
src/Controller/CatsAdoptionEventsController.php
PHP
mit
4,276
module kotlin.graphics.imgui.glfw { requires kotlin.stdlib; requires kotlin.graphics.imgui.core; requires kotlin.graphics.uno.core; requires kotlin.graphics.glm; requires kotlin.graphics.kool; requires org.lwjgl.glfw; exports imgui.impl.glfw; }
kotlin-graphics/imgui
glfw/src/main/java/module-info.java
Java
mit
276
class Solution { public: bool stoneGame(vector<int>& piles) { return true; } };
gzc/leetcode
cpp/871-880/Stone Game.cpp
C++
mit
96
/* * $Id$ * Copyright (C) 2006 Klaus Reimer <k@ailis.de> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package de.ailis.wlandsuite.io; import java.io.IOException; import java.io.OutputStream; /** * The bit output stream can be used to write a stream bit by bit. But it also * provides other useful methods like writing 16 or 32 bit values which also * works in a not-byte aligned stream. So if you write 4 bits then you are still * able to write the next 16 bits as a word. * * If you have written not-byte aligned data (for example just 7 bits instead of * 8) then you MUST flush() the stream so these 8 bits are written (With an * appended zero bit). If you close() the stream then flush() is called * automatically. * * @author Klaus Reimer (k@ailis.de) * @version $Revision$ */ public abstract class BitOutputStream extends OutputStream { /** The current byte */ private int currentByte; /** The current bit */ private byte currentBit = 0; /** * Writes a bit to the output stream. * * @param bit * The bit to write * @throws IOException * When file operation fails. */ public void writeBit(final byte bit) throws IOException { writeBit(bit, false); } /** * Writes a bit to the output stream. This method can write the bits in * reversed order. * * @param bit * The bit to write * @param reverse * If bits should be written in reversed order * @throws IOException * When file operation fails. */ public void writeBit(final byte bit, final boolean reverse) throws IOException { if (reverse) { this.currentByte = this.currentByte | (((bit & 1) << this.currentBit)); } else { this.currentByte = (this.currentByte << 1) | (bit & 1); } this.currentBit++; if (this.currentBit > 7) { write(this.currentByte); this.currentByte = 0; this.currentBit = 0; } } /** * Writes the specified number of bits. The bits can be written in reverse * order if the reverse flag is set. * * @param value * The value containing the bits to write * @param quantity * The number of bits to write * @param reverse * If the bits should be written reversed. * @throws IOException * When file operation fails. */ public void writeBits(final int value, final int quantity, final boolean reverse) throws IOException { byte b; for (int i = 0; i < quantity; i++) { if (reverse) { b = (byte) ((value >> i) & 1); } else { b = (byte) ((value >> (quantity - i - 1)) & 1); } writeBit(b, reverse); } } /** * Writes a bit to the output stream. * * @param bit * The bit to write * @throws IOException * When file operation fails. */ public void writeBit(final boolean bit) throws IOException { writeBit((byte) (bit ? 1 : 0)); } /** * Writes a byte to the stream. * * @param b * The byte to write * @throws IOException * When file operation fails. */ public void writeByte(final int b) throws IOException { if (this.currentBit == 0) { write(b); } else { for (int i = 7; i >= 0; i--) { writeBit((byte) ((b >> i) & 1)); } } } /** * Writes a signed byte. * * @param b * The byte to write * @throws IOException * When file operation fails. */ public void writeSignedByte(final int b) throws IOException { if (b < 0) { writeByte(b + 256); } else { writeByte(b); } } /** * Writes a 2-byte word to the stream. * * @param word * The word to write * @throws IOException * When file operation fails. */ public void writeWord(final int word) throws IOException { writeByte(word & 0xff); writeByte((word >> 8) & 0xff); } /** * Writes a 4-byte integer to the stream. * * @param integer * The integer to write * @throws IOException * When file operation fails. */ public void writeInt(final long integer) throws IOException { writeByte((int) (integer & 0xff)); writeByte((int) ((integer >> 8) & 0xff)); writeByte((int) ((integer >> 16) & 0xff)); writeByte((int) ((integer >> 24) & 0xff)); } /** * Writes a 3-byte integer to the stream. * * @param integer * The integer to write * @throws IOException * When file operation fails. */ public void writeInt3(final int integer) throws IOException { writeByte(integer & 0xff); writeByte((integer >> 8) & 0xff); writeByte((integer >> 16) & 0xff); } /** * Flush the output to make sure all bits are written even if they don't * fill a whole byte. * * @throws IOException * When file operation fails. */ @Override public void flush() throws IOException { flush(false); } /** * Flush the output to make sure all bits are written even if they don't * fill a whole byte. * * @param reverse In bits are written in reverese order * @throws IOException * When file operation fails. */ public void flush(final boolean reverse) throws IOException { if (this.currentBit != 0) { if (!reverse) { this.currentByte = this.currentByte << (8 - this.currentBit); } write(this.currentByte); } } /** * Closes the connected output stream and makes sure the last byte is * written. * * @throws IOException * When file operation fails. */ @Override public void close() throws IOException { flush(); super.close(); } }
delMar43/wlandsuite
src/main/java/de/ailis/wlandsuite/io/BitOutputStream.java
Java
mit
7,613
'use strict'; angular.module('contactServices', []) // Factory responsible for assembling the form data before it's passed over the php .factory('assembleFormDataService', function(){ return { populateFormData: function(fname, lname, address, city, zipcode, mnumber, lnumber, relation, email, photoSubmit){ var formData = new FormData(); formData.append("fname", fname); formData.append("lname", lname); formData.append("address", address); formData.append("city", city); formData.append("zipcode", zipcode); formData.append("mnumber", mnumber); formData.append("lnumber", lnumber); formData.append("relation", relation); formData.append("email", email); formData.append("photo", photoSubmit); return formData; } }; }) // One big team service that handles the individual components we'll need for the teams .factory('contactService', ['$http', function($http){ return { contactsList: function(callback){ $http.get('contacts/contacts.php?action=list').success(callback); }, contactsDetails: function(id, callback){ $http.get('contacts/contacts.php?action=detail&id=' + id).success(callback); }, addContacts: function(readyFormData, callback){ $http.post('contacts/contacts.php?action=add', readyFormData, { transformRequest: angular.identity, headers: { "Content-Type": undefined } }).success(callback); }, editContact: function(id, readyFormData, callback){ $http.post('contacts/contacts.php?action=edit&id=' + id, readyFormData, { transformRequest: angular.identity, headers: { "Content-Type": undefined } }).success(callback); }, deleteContact: function(id, callback){ $http.post('contacts/contacts.php?action=delete&id=' + id).success(callback); } } }]);
andrewwiik/VTHSCompSciClub
admin/contacts/js/contactServices.js
JavaScript
mit
1,741
# -*- coding: utf-8 -*- import datetime from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ class RegisterToken(models.Model): user = models.ForeignKey(User) token = models.CharField(_(u'token'), max_length=32) created = models.DateTimeField(_(u'created'), editable=False, auto_now_add=True) @property def is_valid(self): valid_period = datetime.timedelta(days=1) now = datetime.datetime.now() return now < self.created + valid_period class Meta: verbose_name = _(u'register token') verbose_name_plural = _(u'register tokens')
dotKom/studlan
apps/authentication/models.py
Python
mit
674
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Using Statements using System; using DotNetNuke.Entities.Modules; #endregion namespace _OWNER_._MODULE_ { public partial class _CONTROL_ : PortalModuleBase { #region Event Handlers protected override void OnInit(EventArgs e) { base.OnInit(e); cmdSave.Click += cmdSave_Click; cmdCancel.Click += cmdCancel_Click; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Page.IsPostBack) { txtField.Text = (string)Settings["field"]; } } protected void cmdSave_Click(object sender, EventArgs e) { ModuleController.Instance.UpdateModuleSetting(ModuleId, "field", txtField.Text); DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, "Update Successful", DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess); } protected void cmdCancel_Click(object sender, EventArgs e) { } #endregion } }
nvisionative/Dnn.Platform
DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Templates/C#/Module - User Control/_CONTROL_.ascx.cs
C#
mit
1,111
vti_encoding:SR|utf8-nl vti_timelastmodified:TR|31 Jul 2007 14:34:52 -0000 vti_extenderversion:SR|4.0.2.7802
tauheedahmed/ecosys
project_files/_vti_cnf/frmMainAppts.aspx.cs
C#
mit
109
<?php /* * This file is part of the DunglasApiBundle package. * * (c) Kévin Dunglas <dunglas@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dunglas\ApiBundle\Api\Operation; use Symfony\Component\Routing\Route; /** * {@inheritdoc} * * @author Kévin Dunglas <dunglas@gmail.com> */ class Operation implements OperationInterface { /** * @var Route */ private $route; /** * @var string */ private $routeName; /** * @var array */ private $context; /** * @param Route $route * @param string $routeName * @param array $context */ public function __construct(Route $route, $routeName, array $context = []) { $this->route = $route; $this->routeName = $routeName; $this->context = $context; } /** * {@inheritdoc} */ public function getRoute() { return $this->route; } /** * {@inheritdoc} */ public function getRouteName() { return $this->routeName; } /** * {@inheritdoc} */ public function getContext() { return $this->context; } }
yelmontaser/DunglasApiBundle
Api/Operation/Operation.php
PHP
mit
1,264
# frozen_string_literal: false begin require '-test-/iseq_load/iseq_load' rescue LoadError end require 'tempfile' class RubyVM::InstructionSequence def disasm_if_possible begin self.disasm rescue Encoding::CompatibilityError, EncodingError, SecurityError nil end end def self.compare_dump_and_load i1, dumper, loader dump = dumper.call(i1) return i1 unless dump i2 = loader.call(dump) # compare disassembled result d1 = i1.disasm_if_possible d2 = i2.disasm_if_possible if d1 != d2 STDERR.puts "expected:" STDERR.puts d1 STDERR.puts "actual:" STDERR.puts d2 t1 = Tempfile.new("expected"); t1.puts d1; t1.close t2 = Tempfile.new("actual"); t2.puts d2; t2.close system("diff -u #{t1.path} #{t2.path}") # use diff if available exit(1) end i2 end CHECK_TO_A = ENV['RUBY_ISEQ_DUMP_DEBUG'] == 'to_a' CHECK_TO_BINARY = ENV['RUBY_ISEQ_DUMP_DEBUG'] == 'to_binary' def self.translate i1 # check to_a/load_iseq i2_ary = compare_dump_and_load(i1, proc{|iseq| ary = iseq.to_a ary[9] == :top ? ary : nil }, proc{|ary| RubyVM::InstructionSequence.iseq_load(ary) }) if CHECK_TO_A && defined?(RubyVM::InstructionSequence.iseq_load) # check to_binary i2_bin = compare_dump_and_load(i1, proc{|iseq| begin iseq.to_binary rescue RuntimeError => e # not a toplevel # STDERR.puts [:failed, e, iseq].inspect nil end }, proc{|bin| iseq = RubyVM::InstructionSequence.load_from_binary(bin) # STDERR.puts iseq.inspect iseq }) if CHECK_TO_BINARY # return value i2_bin if CHECK_TO_BINARY end if CHECK_TO_A || CHECK_TO_BINARY end #require_relative 'x'; exit(1)
rokn/Count_Words_2015
fetched_code/ruby/iseq_loader_checker.rb
Ruby
mit
2,424
class Good { public int Max(int a, int b) { return a > b ? a : b; } }
github/codeql
csharp/ql/test/query-tests/Bad Practices/Control-Flow/ConstantCondition/ConstantConditionGood.cs
C#
mit
90
#!/usr/bin/ruby # # Demonstation for Ruby # puts $LOAD_PATH # extend the load path for wosg $LOAD_PATH << '../../bin/ruby' # include all necessary libs require 'wosg' require 'wosgDB' require 'wosgProducer' class Viewer def initialize() # open a viewer @viewer = WosgProducer::Viewer.new # open @viewer.setUpViewer(WosgProducer::Viewer::STANDARD_SETTINGS) puts "Reading Data ... " n = WosgDB::readNodeFile("cow.osg") root = Wosg::Group.new() root.addChild(n) @viewer.setSceneData(root) puts "Show the Window ... " @viewer.realize() end def run() while !@viewer.done() @viewer.sync @viewer.update @viewer.frame end end end v = Viewer.new v.run
cmbruns/osgswig
examples/ruby/viewer.rb
Ruby
mit
711
var searchData= [ ['basepath',['BASEPATH',['../index_8php.html#ad39801cabfd338dc5524466fe793fda9',1,'index.php']]] ];
forstermatth/LIIS
refman/search/variables_62.js
JavaScript
mit
120
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, Link, browserHistory } from 'react-router'; import App from './App'; import NotFound from './Pages/NotFound/NotFound'; import Users from './Pages/Users/Users'; import Chats from './Pages/Chats/Chats'; import './index.css'; ReactDOM.render( <Router history={browserHistory}> <Route path="/" component={App}> <Route path="users" component={Users}/> <Route path="chats" component={Chats}/> </Route> <Route path="*" component={NotFound}/> </Router>, document.getElementById('root'));
ParkDyel/practice
WebDev/FE/JS/Reactjs/PRWF/src/index.js
JavaScript
mit
599
require 'celluloid/current' require 'celluloid/io' module Celluloid module SMTP require 'celluloid/smtp/constants' require 'celluloid/smtp/logging' require 'celluloid/smtp/version' require 'celluloid/smtp/extensions' class Server include SMTP::Extensions require 'celluloid/smtp/server' require 'celluloid/smtp/server/protector' require 'celluloid/smtp/server/handler' require 'celluloid/smtp/server/transporter' end class Connection include SMTP::Extensions require 'celluloid/smtp/connection/errors' require 'celluloid/smtp/connection/events' require 'celluloid/smtp/connection/parser' require 'celluloid/smtp/connection/automata' require 'celluloid/smtp/connection' end end end
abstractive/celluloid-smtp
lib/celluloid/smtp.rb
Ruby
mit
784
<div class="col-md-6 col-md-offset-3"> <div class="box box-success direct-chat direct-chat-success"> <div class="box-header with-border"> <h1 class="box-title"><i class="fa fa-file-text-o"></i> <?php echo $title; ?></h1> <div class="pull-right"> <i class="fa fa-close" onclick="closeModal()"></i> </div> </div> <form id="ff" class=""> <input type="hidden" name="dest_number" value="<?php echo $title; ?>"> <div class="box-body"> <div class="direct-chat-messages" style="height: 400px; overflow-x: hidden; word-break: break-all"> <?php $udh = ''; $sms_type = 1; $i=0; $img = base_url('assets/images/employee/male.png'); foreach ($sms as $value) { if ($value->udh != '' && $value->sms_type == $sms_type && $value->udh == $udh) { echo "<script>$('#msg-{$i}').append('{$value->sms_text}');</script>"; } else { $i++; if ($value->sms_type == 3) { // inbox echo " <div class='direct-chat-msg col-md-11'> <div class='direct-chat-info clearfix'> <span class='direct-chat-name pull-left'>{$value->sender_id}</span> <span class='direct-chat-timestamp pull-right'>{$value->sms_date} <i class='fa fa-arrow-circle-down'></i></span> </div> <img class='direct-chat-img' src='{$img}' alt='message user image'> <div class='direct-chat-text' id='msg-{$i}'> {$value->sms_text} </div> </div> "; } else { //outbox & sentitems if ($value->sms_type == 1) { $status = 'fa fa-clock-o'; } else if ($value->sms_type == 2) { if (strripos($value->status, 'SendingOk') !== FALSE) { $status = 'fa fa-check-circle'; } else { $status = 'fa fa-exclamation-circle'; } } echo " <div class='direct-chat-msg col-md-11 right pull-right'> <div class='direct-chat-info clearfix'> <span class='direct-chat-name pull-right'>{$value->sender_id}</span> <span class='direct-chat-timestamp pull-left'>{$value->sms_date} <i class='{$status}'></i></span> </div> <img class='direct-chat-img' src='{$img}' alt='message user image'> <div class='direct-chat-text text-right' id='msg-{$i}'> {$value->sms_text} </div> </div> "; } } $sms_type = $value->sms_type; $udh = $value->udh; } ?> </div> </div> <div class="box-footer text-right"> <div class="col-md-1 form-control-static" id="char-count"> </div> <div class="col-md-11"> <div class="input-group input-group-"> <input name="sms_text" id="sms_text" type="text" class="form-control" autofocus="" required="" autocomplete="off"> <span class="input-group-btn"> <button class="btn btn-success" id="save_btn" type="submit" data-loading-text="<i class='fa fa-refresh fa-spin'></i> Mengirim..."><i class="fa fa-send"></i> Kirim</button> </span> </div> </div> </div> </form> </div> </div> <script> $(document).ready(function() { $('#sms_text').keyup(function() { var smsText = $(this).val(); $('#char-count').html(smsText.length); console.log(smsText); }); autoScroll(); $('#ff').submit(function(e) { e.preventDefault(); var btn = $('#save_btn'); $.ajax({ url: '<?php echo base_url('messaging/inbox/sending'); ?>', type: 'post', data: $('#ff').serialize(), dataType: 'json', beforeSend: function() { btn.button('loading'); }, success: function(data) { var img = '<?php echo base_url('assets/images/employee/male.png'); ?>'; var html = '<div class="direct-chat-msg right col-md-11 pull-right">\n\ <div class="direct-chat-info clearfix">\n\ <span class="direct-chat-name pull-right">' + data.sender_id + '</span>\n\ <span class="direct-chat-timestamp pull-left">' + data.sms_date + ' <i class="fa fa-clock-o"></i></span>\n\ </div>\n\ <img class="direct-chat-img" src="'+img+'" alt="message user image">\n\ <div class="direct-chat-text text-right">\n\ ' + data.sms_text + '\n\ </div>\n\ </div>'; $('.direct-chat-messages').append(html); autoScroll(); $('#sms_text').val(''); }, complete: function() { btn.button('reset'); reloadTable('dataTable'); $('#char-count').html(0); } }); }); }); function autoScroll() { $('.direct-chat-messages').scrollTop($('.direct-chat-messages')[0].scrollHeight); } </script>
Gincusoft/aksi
application/modules/messaging/views/outbox/detail.php
PHP
mit
5,440
/** * @license * Visual Blocks Editor * * Copyright 2016 Google Inc. * https://developers.google.com/blockly/ * * 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. */ /** * @fileoverview Events fired as a result of actions in Blockly's editor. * @author fraser@google.com (Neil Fraser) */ 'use strict'; /** * Events fired as a result of actions in Blockly's editor. * @namespace Blockly.Events */ goog.provide('Blockly.Events'); goog.require('Blockly.utils'); /** * Group ID for new events. Grouped events are indivisible. * @type {string} * @private */ Blockly.Events.group_ = ''; /** * Sets whether the next event should be added to the undo stack. * @type {boolean} */ Blockly.Events.recordUndo = true; /** * Allow change events to be created and fired. * @type {number} * @private */ Blockly.Events.disabled_ = 0; /** * Name of event that creates a block. Will be deprecated for BLOCK_CREATE. * @const */ Blockly.Events.CREATE = 'create'; /** * Name of event that creates a block. * @const */ Blockly.Events.BLOCK_CREATE = Blockly.Events.CREATE; /** * Name of event that deletes a block. Will be deprecated for BLOCK_DELETE. * @const */ Blockly.Events.DELETE = 'delete'; /** * Name of event that deletes a block. * @const */ Blockly.Events.BLOCK_DELETE = Blockly.Events.DELETE; /** * Name of event that changes a block. Will be deprecated for BLOCK_CHANGE. * @const */ Blockly.Events.CHANGE = 'change'; /** * Name of event that changes a block. * @const */ Blockly.Events.BLOCK_CHANGE = Blockly.Events.CHANGE; /** * Name of event that moves a block. Will be deprecated for BLOCK_MOVE. * @const */ Blockly.Events.MOVE = 'move'; /** * Name of event that moves a block. * @const */ Blockly.Events.BLOCK_MOVE = Blockly.Events.MOVE; /** * Name of event that creates a variable. * @const */ Blockly.Events.VAR_CREATE = 'var_create'; /** * Name of event that deletes a variable. * @const */ Blockly.Events.VAR_DELETE = 'var_delete'; /** * Name of event that renames a variable. * @const */ Blockly.Events.VAR_RENAME = 'var_rename'; /** * Name of event that records a UI change. * @const */ Blockly.Events.UI = 'ui'; /** * Name of event that creates a comment. * @const */ Blockly.Events.COMMENT_CREATE = 'comment_create'; /** * Name of event that deletes a comment. * @const */ Blockly.Events.COMMENT_DELETE = 'comment_delete'; /** * Name of event that changes a comment. * @const */ Blockly.Events.COMMENT_CHANGE = 'comment_change'; /** * Name of event that moves a comment. * @const */ Blockly.Events.COMMENT_MOVE = 'comment_move'; /** * List of events queued for firing. * @private */ Blockly.Events.FIRE_QUEUE_ = []; /** * Create a custom event and fire it. * @param {!Blockly.Events.Abstract} event Custom data for event. */ Blockly.Events.fire = function(event) { if (!Blockly.Events.isEnabled()) { return; } if (!Blockly.Events.FIRE_QUEUE_.length) { // First event added; schedule a firing of the event queue. setTimeout(Blockly.Events.fireNow_, 0); } Blockly.Events.FIRE_QUEUE_.push(event); }; /** * Fire all queued events. * @private */ Blockly.Events.fireNow_ = function() { var queue = Blockly.Events.filter(Blockly.Events.FIRE_QUEUE_, true); Blockly.Events.FIRE_QUEUE_.length = 0; for (var i = 0, event; event = queue[i]; i++) { var workspace = Blockly.Workspace.getById(event.workspaceId); if (workspace) { workspace.fireChangeListener(event); } } }; /** * Filter the queued events and merge duplicates. * @param {!Array.<!Blockly.Events.Abstract>} queueIn Array of events. * @param {boolean} forward True if forward (redo), false if backward (undo). * @return {!Array.<!Blockly.Events.Abstract>} Array of filtered events. */ Blockly.Events.filter = function(queueIn, forward) { var queue = queueIn.slice(); // Shallow copy of queue. if (!forward) { // Undo is merged in reverse order. queue.reverse(); } var mergedQueue = []; var hash = Object.create(null); // Merge duplicates. for (var i = 0, event; event = queue[i]; i++) { if (!event.isNull()) { var key = [event.type, event.blockId, event.workspaceId].join(' '); var lastEntry = hash[key]; var lastEvent = lastEntry ? lastEntry.event : null; if (!lastEntry) { // Each item in the hash table has the event and the index of that event // in the input array. This lets us make sure we only merge adjacent // move events. hash[key] = { event: event, index: i}; mergedQueue.push(event); } else if (event.type == Blockly.Events.MOVE && lastEntry.index == i - 1) { // Merge move events. lastEvent.newParentId = event.newParentId; lastEvent.newInputName = event.newInputName; lastEvent.newCoordinate = event.newCoordinate; lastEntry.index = i; } else if (event.type == Blockly.Events.CHANGE && event.element == lastEvent.element && event.name == lastEvent.name) { // Merge change events. lastEvent.newValue = event.newValue; } else if (event.type == Blockly.Events.UI && event.element == 'click' && (lastEvent.element == 'commentOpen' || lastEvent.element == 'mutatorOpen' || lastEvent.element == 'warningOpen')) { // Merge click events. lastEvent.newValue = event.newValue; } else { // Collision: newer events should merge into this event to maintain order hash[key] = { event: event, index: 1}; mergedQueue.push(event); } } } // Filter out any events that have become null due to merging. queue = mergedQueue.filter(function(e) { return !e.isNull(); }); if (!forward) { // Restore undo order. queue.reverse(); } // Move mutation events to the top of the queue. // Intentionally skip first event. for (var i = 1, event; event = queue[i]; i++) { if (event.type == Blockly.Events.CHANGE && event.element == 'mutation') { queue.unshift(queue.splice(i, 1)[0]); } } return queue; }; /** * Modify pending undo events so that when they are fired they don't land * in the undo stack. Called by Blockly.Workspace.clearUndo. */ Blockly.Events.clearPendingUndo = function() { for (var i = 0, event; event = Blockly.Events.FIRE_QUEUE_[i]; i++) { event.recordUndo = false; } }; /** * Stop sending events. Every call to this function MUST also call enable. */ Blockly.Events.disable = function() { Blockly.Events.disabled_++; }; /** * Start sending events. Unless events were already disabled when the * corresponding call to disable was made. */ Blockly.Events.enable = function() { Blockly.Events.disabled_--; }; /** * Returns whether events may be fired or not. * @return {boolean} True if enabled. */ Blockly.Events.isEnabled = function() { return Blockly.Events.disabled_ == 0; }; /** * Current group. * @return {string} ID string. */ Blockly.Events.getGroup = function() { return Blockly.Events.group_; }; /** * Start or stop a group. * @param {boolean|string} state True to start new group, false to end group. * String to set group explicitly. */ Blockly.Events.setGroup = function(state) { if (typeof state == 'boolean') { Blockly.Events.group_ = state ? Blockly.utils.genUid() : ''; } else { Blockly.Events.group_ = state; } }; /** * Compute a list of the IDs of the specified block and all its descendants. * @param {!Blockly.Block} block The root block. * @return {!Array.<string>} List of block IDs. * @private */ Blockly.Events.getDescendantIds_ = function(block) { var ids = []; var descendants = block.getDescendants(false); for (var i = 0, descendant; descendant = descendants[i]; i++) { ids[i] = descendant.id; } return ids; }; /** * Decode the JSON into an event. * @param {!Object} json JSON representation. * @param {!Blockly.Workspace} workspace Target workspace for event. * @return {!Blockly.Events.Abstract} The event represented by the JSON. */ Blockly.Events.fromJson = function(json, workspace) { // TODO: Should I have a way to register a new event into here? var event; switch (json.type) { case Blockly.Events.CREATE: event = new Blockly.Events.Create(null); break; case Blockly.Events.DELETE: event = new Blockly.Events.Delete(null); break; case Blockly.Events.CHANGE: event = new Blockly.Events.Change(null, '', '', '', ''); break; case Blockly.Events.MOVE: event = new Blockly.Events.Move(null); break; case Blockly.Events.VAR_CREATE: event = new Blockly.Events.VarCreate(null); break; case Blockly.Events.VAR_DELETE: event = new Blockly.Events.VarDelete(null); break; case Blockly.Events.VAR_RENAME: event = new Blockly.Events.VarRename(null, ''); break; case Blockly.Events.UI: event = new Blockly.Events.Ui(null); break; case Blockly.Events.COMMENT_CREATE: event = new Blockly.Events.CommentCreate(null); break; case Blockly.Events.COMMENT_CHANGE: event = new Blockly.Events.CommentChange(null); break; case Blockly.Events.COMMENT_MOVE: event = new Blockly.Events.CommentMove(null); break; case Blockly.Events.COMMENT_DELETE: event = new Blockly.Events.CommentDelete(null); break; default: throw Error('Unknown event type.'); } event.fromJson(json); event.workspaceId = workspace.id; return event; }; /** * Enable/disable a block depending on whether it is properly connected. * Use this on applications where all blocks should be connected to a top block. * Recommend setting the 'disable' option to 'false' in the config so that * users don't try to reenable disabled orphan blocks. * @param {!Blockly.Events.Abstract} event Custom data for event. */ Blockly.Events.disableOrphans = function(event) { if (event.type == Blockly.Events.MOVE || event.type == Blockly.Events.CREATE) { var workspace = Blockly.Workspace.getById(event.workspaceId); var block = workspace.getBlockById(event.blockId); if (block) { if (block.getParent() && !block.getParent().disabled) { var children = block.getDescendants(false); for (var i = 0, child; child = children[i]; i++) { child.setDisabled(false); } } else if ((block.outputConnection || block.previousConnection) && !workspace.isDragging()) { do { block.setDisabled(true); block = block.getNextBlock(); } while (block); } } } };
NTUTVisualScript/Visual_Script
static/javascript/blockly/core/events.js
JavaScript
mit
11,197
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911 // .1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.07.16 at 03:24:22 PM EEST // package org.ecloudmanager.tmrk.cloudapi.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.util.ArrayList; import java.util.List; /** * <p>Java class for ArrayOfInternetServiceType complex type. * <p/> * <p>The following schema fragment specifies the expected content contained within this class. * <p/> * <pre> * &lt;complexType name="ArrayOfInternetServiceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="InternetService" type="{}InternetServiceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ArrayOfInternetServiceType", propOrder = { "internetService" }) public class ArrayOfInternetServiceType { @XmlElement(name = "InternetService", nillable = true) protected List<InternetServiceType> internetService; /** * Gets the value of the internetService property. * <p/> * <p/> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the internetService property. * <p/> * <p/> * For example, to add a new item, do as follows: * <pre> * getInternetService().add(newItem); * </pre> * <p/> * <p/> * <p/> * Objects of the following type(s) are allowed in the list * {@link InternetServiceType } */ public List<InternetServiceType> getInternetService() { if (internetService == null) { internetService = new ArrayList<InternetServiceType>(); } return this.internetService; } }
AltisourceLabs/ecloudmanager
tmrk-cloudapi/src/main/java/org/ecloudmanager/tmrk/cloudapi/model/ArrayOfInternetServiceType.java
Java
mit
2,395
from py_word_suggest.utils import * import pytest raw_json = """ {"lang:nl:0:ben":[["ik", 22.0], ["er", 8.0], ["een", 7.0], ["je", 5.0]],"lang:nl:0:Ik":[["heb", 66.0], ["ben", 52.0], ["denk", 15.0], [ "wil", 13.0], ["acht", 1.0]],"lang:eng:0:I":[["am", 100], ["want", 246], ["love", 999]],"lang:eng:0:am":[["the",100], ["Alice", 50],["Bob", 45]]} """ invalid_json = """ test """ @pytest.fixture(scope="session") def invalid_json_file(tmpdir_factory): fn = tmpdir_factory.mktemp("data_tmp").join("test_invalid.json") fn.write(invalid_json) invalid_json_fn = fn return fn @pytest.fixture(scope="session") def raw_json_file(tmpdir_factory): f = tmpdir_factory.mktemp("data_tmp").join("test.json") f.write(raw_json) return f def setUp(invalid_json_file): invalid_json_file @pytest.mark.parametrize("testInput, expectedOutput, state", [ (b'{"lang:nl:0:Ik":[["heb", 66.0], ["ben", 52.0], ["denk", 15.0], ["wil", 13.0], ["acht", 1.0]]}', { 'lang:nl:0:Ik': [['heb', 66.0], ['ben', 52.0], ['denk', 15.0], ['wil', 13.0], ['acht', 1.0]]}, 'normalState'), ('{"lang:nl:0:Ik":[["heb", 66.0], ["ben", 52.0], ["denk", 15.0], ["wil", 13.0], ["acht", 1.0]]}', { 'lang:nl:0:Ik': [['heb', 66.0], ['ben', 52.0], ['denk', 15.0], ['wil', 13.0], ['acht', 1.0]]}, 'normalState'), ('"lang:nl"', "Error load_json_string, jsonString, '\"lang:nl\"' needs to be a string represetation of a json object, jsonString needs to be set between braces. A str item needs to be set between double quotes.", 'errorState'), (b'"lang:nl"', "Error load_json_string, jsonString, 'b'\"lang:nl\"'' needs to be a string represetation of a json object, jsonString needs to be set between braces. A str item needs to be set between double quotes.", 'errorState'), (b'\'lang\':0"', "Error load_json_string, jsonString, 'b'\\'lang\\':0\"'' needs to be a string represetation of a json object, jsonString needs to be set between braces. A str item needs to be set between double quotes.", 'errorState'), (0, "Error load_json_string, jsonString, '0' needs to be a string represetation of a json object, jsonString needs to be set between braces. A str item needs to be set between double quotes.", 'errorState'), ] ) def test_load_json_from_string(testInput, expectedOutput, state): """utils, Json from string""" # Test normal behavior if state == 'normalState': assert load_json_string(testInput) == expectedOutput # Test expect error if state == 'errorState': with pytest.raises(utilsError) as e: load_json_string(testInput) assert str(e.value) == expectedOutput @pytest.mark.parametrize("testInput, expectedOutput, state", [ ('\"lang:nl:0:Ik\"', {"lang:nl:0:Ik": [["heb", 66.0], ["ben", 52.0], [ "denk", 15.0], ["wil", 13.0], ["acht", 1.0]]}, 'normalState'), ('\"lang:nl:0:Ik', "Error, grep_jsonstring_from_system: '\"lang:nl:0:Ik' needs to be a str type and need to be between double quotes.", 'errorState'), ('lang:nl:0:Ik\"', "Error, grep_jsonstring_from_system: 'lang:nl:0:Ik\"' needs to be a str type and need to be between double quotes.", 'errorState'), ('lang:nl:0:Ik', "Error, grep_jsonstring_from_system: 'lang:nl:0:Ik' needs to be a str type and need to be between double quotes.", 'errorState'), (0, "Error, grep_jsonstring_from_system: '0' needs to be a str type and need to be between double quotes.", 'errorState'), ('\"NoKeyFound\"', False, 'normalState'), ('\"NO-MATCH\"', False, 'normalState'), ('\"NOEXISTINGFILE\"', "Error, grep_jsonstring_from_system: File NOEXISTINGFILE not exists or is busy.", 'fileError'), # ('lang:nl:0:Ik' ,b'"lang:nl:0:Ik":[["heb", 66.0], ["ben", 52.0], ["denk", 15.0], ["wil", 13.0], ["acht", 1.0]]','":.*]]','defaultArguments'), ] ) def test_grep_jsonstring_from_system(raw_json_file, testInput, expectedOutput, state): """utils, Grep bigram from file with system jq util""" # Test default argument if state == 'fileError': raw_json_file = 'NOEXISTINGFILE' with pytest.raises(utilsError) as e: grep_jsonstring_from_system(testInput, raw_json_file) assert str(e.value) == expectedOutput # Test normal behavior if state == 'normalState': assert grep_jsonstring_from_system( testInput, raw_json_file) == expectedOutput # Test expect error if state == 'errorState': # pudb.set_trace() with pytest.raises(utilsError) as e: grep_jsonstring_from_system(testInput, raw_json_file) # pudb.set_trace() assert str(e.value) == expectedOutput @pytest.mark.parametrize("testInput,expected_output", [ ('', True), (None, True), ('NonWwhiteSpaces', False), ('String with white-space', True), (10, False) ] ) def test_is_empty(testInput, expected_output): """utils, is_empty: Check if an object is empty or contains spaces""" assert is_empty(testInput) == expected_output @pytest.mark.parametrize("testInput,expectedOutput", [ ("String", True), (['lol,lol2'], True), (('lol', 'lol2'), True), ({'lol', 'lol2'}, True), (10, False), (None, False) ] ) def test_is_iterable(testInput, expectedOutput): """utils, is_iterable Check if an object is iterable""" assert is_iterable(testInput) == expectedOutput @pytest.mark.parametrize("testInput, collection, expectedOutput, errorState", [ ('Love', ['I', 'Love', 'python'], True, False), ('love', ['I', 'Love', 'python'], False, False), ('', ['I', 'Love', 'python'], False, False), (None, ['I', 'Love', 'python'], False, False), (None, "String", "Error: collection is not iterable or is a string", True), ('Love', 8, "Error: collection is not iterable or is a string", True), ( 'Love', None, "Error: collection is not iterable or is a string", True), ] ) def test_containing(testInput, collection, expectedOutput, errorState): """utils: Check if collection contains an item""" if errorState is False: assert containing(collection, testInput) == expectedOutput else: with pytest.raises(utilsError) as e: containing(collection, testInput) assert str(e.value) == expectedOutput @pytest.mark.parametrize("testInput, expectedOutput, state", [ (None, {"lang:nl:0:ben": [["ik", 22.0], ["er", 8.0], ["een", 7.0], ["je", 5.0]], "lang:nl:0:Ik":[["heb", 66.0], ["ben", 52.0], ["denk", 15.0], [ "wil", 13.0], ["acht", 1.0]], "lang:eng:0:I":[["am", 100], ["want", 246], ["love", 999]], "lang:eng:0:am":[["the", 100], ["Alice", 50], ["Bob", 45]]}, 'normalState'), (None, "Error, load_data_from_json: \'NOEXISTINGFILE\' does not exists.", 'noFileExistState'), (None, "Error, load_data_from_json: '{}' needs to be a json object.", 'invalidJsonState'), (None, "Error, load_data_from_json: Function recuires a filename (str).", 'ValueErrorState'), (13458, "Error, load_data_from_json: Function recuires a filename (str).", 'ValueErrorState'), (True, "Error, load_data_from_json: Function recuires a filename (str).", 'ValueErrorState'), (False, "Error, load_data_from_json: Function recuires a filename (str).", 'ValueErrorState'), ] ) def test_load_json_from_file(raw_json_file, invalid_json_file, testInput, expectedOutput, state): """utils, load json data from file""" # Test default argument # Test normal behavior if state == 'normalState': assert load_data_from_json(str(raw_json_file)) == expectedOutput # Test noFileExistState if state == 'noFileExistState': raw_json_file = 'NOEXISTINGFILE' with pytest.raises(FileNotFoundError) as e: load_data_from_json(raw_json_file) assert str(e.value) == expectedOutput # Test invalid_json_file error if state == 'invalidJsonState': with pytest.raises(utilsError) as e: load_data_from_json(str(invalid_json_file)) assert str(e.value) == expectedOutput.format(str(invalid_json_file)) # Test noFileExistState if state == 'ValueErrorState': with pytest.raises(ValueError) as e: load_data_from_json(testInput) assert str(e.value) == expectedOutput
eronde/vim_suggest
tests/test_utils.py
Python
mit
9,992
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ar" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About KappaCoin</source> <translation>عن KappaCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;KappaCoin&lt;/b&gt; version</source> <translation>نسخة &lt;b&gt;KappaCoin&lt;/b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The KappaCoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>دفتر العناوين</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>أنقر على الماوس مرتين لتعديل عنوان</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>قم بعمل عنوان جديد</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>قم بنسخ القوانين المختارة لحافظة النظام</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your KappaCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a KappaCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified KappaCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;أمسح</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your KappaCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>(no label)</source> <translation type="unfinished"/> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR KAPPACOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>KappaCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your kappacoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Show information about KappaCoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a KappaCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for KappaCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>KappaCoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About KappaCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your KappaCoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified KappaCoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>KappaCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to KappaCoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid KappaCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. KappaCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid KappaCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>KappaCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start KappaCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start KappaCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the KappaCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the KappaCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting KappaCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show KappaCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting KappaCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the KappaCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start kappacoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the KappaCoin-Qt help message to get a list with possible KappaCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>KappaCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>KappaCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the KappaCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the KappaCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a KappaCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this KappaCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified KappaCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a KappaCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter KappaCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The KappaCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>KappaCoin version</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Send command to -server or kappacoind</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Specify configuration file (default: kappacoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: kappacoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=kappacoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;KappaCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. KappaCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong KappaCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the KappaCoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of KappaCoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart KappaCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. KappaCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
kombatcoin/KAP
src/qt/locale/bitcoin_ar.ts
TypeScript
mit
97,707
var x = require("x-view"); var Raw = x.createClass({ propTypes: { html: x.type.string }, init: function() { x.event.on(this, "updated", this.updateHTML); }, updateHTML: function() { this.root.innerHTML = this.props.html; } }); x.register("x-raw", Raw);
lixiaoyan/x-view
tags/raw.js
JavaScript
mit
279
// <copyright file="SparseMatrix.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2013 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using MathNet.Numerics.LinearAlgebra.Storage; namespace MathNet.Numerics.LinearAlgebra.Complex { #if NOSYSNUMERICS using Numerics; #else using System.Numerics; #endif /// <summary> /// A Matrix with sparse storage, intended for very large matrices where most of the cells are zero. /// The underlying storage scheme is 3-array compressed-sparse-row (CSR) Format. /// <a href="http://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_.28CSR_or_CRS.29">Wikipedia - CSR</a>. /// </summary> [Serializable] [DebuggerDisplay("SparseMatrix {RowCount}x{ColumnCount}-Complex {NonZerosCount}-NonZero")] public class SparseMatrix : Matrix { readonly SparseCompressedRowMatrixStorage<Complex> _storage; /// <summary> /// Gets the number of non zero elements in the matrix. /// </summary> /// <value>The number of non zero elements.</value> public int NonZerosCount { get { return _storage.ValueCount; } } /// <summary> /// Create a new sparse matrix straight from an initialized matrix storage instance. /// The storage is used directly without copying. /// Intended for advanced scenarios where you're working directly with /// storage for performance or interop reasons. /// </summary> public SparseMatrix(SparseCompressedRowMatrixStorage<Complex> storage) : base(storage) { _storage = storage; } /// <summary> /// Create a new square sparse matrix with the given number of rows and columns. /// All cells of the matrix will be initialized to zero. /// Zero-length matrices are not supported. /// </summary> /// <exception cref="ArgumentException">If the order is less than one.</exception> public SparseMatrix(int order) : this(order, order) { } /// <summary> /// Create a new sparse matrix with the given number of rows and columns. /// All cells of the matrix will be initialized to zero. /// Zero-length matrices are not supported. /// </summary> /// <exception cref="ArgumentException">If the row or column count is less than one.</exception> public SparseMatrix(int rows, int columns) : this(new SparseCompressedRowMatrixStorage<Complex>(rows, columns)) { } /// <summary> /// Create a new sparse matrix as a copy of the given other matrix. /// This new matrix will be independent from the other matrix. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfMatrix(Matrix<Complex> matrix) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfMatrix(matrix.Storage)); } /// <summary> /// Create a new sparse matrix as a copy of the given two-dimensional array. /// This new matrix will be independent from the provided array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfArray(Complex[,] array) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfArray(array)); } /// <summary> /// Create a new sparse matrix as a copy of the given indexed enumerable. /// Keys must be provided at most once, zero is assumed if a key is omitted. /// This new matrix will be independent from the enumerable. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfIndexed(int rows, int columns, IEnumerable<Tuple<int, int, Complex>> enumerable) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfIndexedEnumerable(rows, columns, enumerable)); } /// <summary> /// Create a new sparse matrix as a copy of the given enumerable. /// The enumerable is assumed to be in row-major order (row by row). /// This new matrix will be independent from the enumerable. /// A new memory block will be allocated for storing the vector. /// </summary> /// <seealso href="http://en.wikipedia.org/wiki/Row-major_order"/> public static SparseMatrix OfRowMajor(int rows, int columns, IEnumerable<Complex> rowMajor) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfRowMajorEnumerable(rows, columns, rowMajor)); } /// <summary> /// Create a new sparse matrix with the given number of rows and columns as a copy of the given array. /// The array is assumed to be in column-major order (column by column). /// This new matrix will be independent from the provided array. /// A new memory block will be allocated for storing the matrix. /// </summary> /// <seealso href="http://en.wikipedia.org/wiki/Row-major_order"/> public static SparseMatrix OfColumnMajor(int rows, int columns, IList<Complex> columnMajor) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfColumnMajorList(rows, columns, columnMajor)); } /// <summary> /// Create a new sparse matrix as a copy of the given enumerable of enumerable columns. /// Each enumerable in the master enumerable specifies a column. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfColumns(IEnumerable<IEnumerable<Complex>> data) { return OfColumnArrays(data.Select(v => v.ToArray()).ToArray()); } /// <summary> /// Create a new sparse matrix as a copy of the given enumerable of enumerable columns. /// Each enumerable in the master enumerable specifies a column. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfColumns(int rows, int columns, IEnumerable<IEnumerable<Complex>> data) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfColumnEnumerables(rows, columns, data)); } /// <summary> /// Create a new sparse matrix as a copy of the given column arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfColumnArrays(params Complex[][] columns) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfColumnArrays(columns)); } /// <summary> /// Create a new sparse matrix as a copy of the given column arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfColumnArrays(IEnumerable<Complex[]> columns) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfColumnArrays((columns as Complex[][]) ?? columns.ToArray())); } /// <summary> /// Create a new sparse matrix as a copy of the given column vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfColumnVectors(params Vector<Complex>[] columns) { var storage = new VectorStorage<Complex>[columns.Length]; for (int i = 0; i < columns.Length; i++) { storage[i] = columns[i].Storage; } return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfColumnVectors(storage)); } /// <summary> /// Create a new sparse matrix as a copy of the given column vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfColumnVectors(IEnumerable<Vector<Complex>> columns) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfColumnVectors(columns.Select(c => c.Storage).ToArray())); } /// <summary> /// Create a new sparse matrix as a copy of the given enumerable of enumerable rows. /// Each enumerable in the master enumerable specifies a row. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfRows(IEnumerable<IEnumerable<Complex>> data) { return OfRowArrays(data.Select(v => v.ToArray()).ToArray()); } /// <summary> /// Create a new sparse matrix as a copy of the given enumerable of enumerable rows. /// Each enumerable in the master enumerable specifies a row. /// This new matrix will be independent from the enumerables. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfRows(int rows, int columns, IEnumerable<IEnumerable<Complex>> data) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfRowEnumerables(rows, columns, data)); } /// <summary> /// Create a new sparse matrix as a copy of the given row arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfRowArrays(params Complex[][] rows) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfRowArrays(rows)); } /// <summary> /// Create a new sparse matrix as a copy of the given row arrays. /// This new matrix will be independent from the arrays. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfRowArrays(IEnumerable<Complex[]> rows) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfRowArrays((rows as Complex[][]) ?? rows.ToArray())); } /// <summary> /// Create a new sparse matrix as a copy of the given row vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfRowVectors(params Vector<Complex>[] rows) { var storage = new VectorStorage<Complex>[rows.Length]; for (int i = 0; i < rows.Length; i++) { storage[i] = rows[i].Storage; } return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfRowVectors(storage)); } /// <summary> /// Create a new sparse matrix as a copy of the given row vectors. /// This new matrix will be independent from the vectors. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfRowVectors(IEnumerable<Vector<Complex>> rows) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfRowVectors(rows.Select(r => r.Storage).ToArray())); } /// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfDiagonalVector(Vector<Complex> diagonal) { var m = new SparseMatrix(diagonal.Count, diagonal.Count); m.SetDiagonal(diagonal); return m; } /// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given vector. /// This new matrix will be independent from the vector. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfDiagonalVector(int rows, int columns, Vector<Complex> diagonal) { var m = new SparseMatrix(rows, columns); m.SetDiagonal(diagonal); return m; } /// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfDiagonalArray(Complex[] diagonal) { var m = new SparseMatrix(diagonal.Length, diagonal.Length); m.SetDiagonal(diagonal); return m; } /// <summary> /// Create a new sparse matrix with the diagonal as a copy of the given array. /// This new matrix will be independent from the array. /// A new memory block will be allocated for storing the matrix. /// </summary> public static SparseMatrix OfDiagonalArray(int rows, int columns, Complex[] diagonal) { var m = new SparseMatrix(rows, columns); m.SetDiagonal(diagonal); return m; } /// <summary> /// Create a new sparse matrix and initialize each value to the same provided value. /// </summary> public static SparseMatrix Create(int rows, int columns, Complex value) { if (value == Complex.Zero) return new SparseMatrix(rows, columns); return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfValue(rows, columns, value)); } /// <summary> /// Create a new sparse matrix and initialize each value using the provided init function. /// </summary> public static SparseMatrix Create(int rows, int columns, Func<int, int, Complex> init) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfInit(rows, columns, init)); } /// <summary> /// Create a new diagonal sparse matrix and initialize each diagonal value to the same provided value. /// </summary> public static SparseMatrix CreateDiagonal(int rows, int columns, Complex value) { if (value == Complex.Zero) return new SparseMatrix(rows, columns); return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfDiagonalInit(rows, columns, i => value)); } /// <summary> /// Create a new diagonal sparse matrix and initialize each diagonal value using the provided init function. /// </summary> public static SparseMatrix CreateDiagonal(int rows, int columns, Func<int, Complex> init) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfDiagonalInit(rows, columns, init)); } /// <summary> /// Create a new square sparse identity matrix where each diagonal value is set to One. /// </summary> public static SparseMatrix CreateIdentity(int order) { return new SparseMatrix(SparseCompressedRowMatrixStorage<Complex>.OfDiagonalInit(order, order, i => One)); } /// <summary> /// Returns a new matrix containing the lower triangle of this matrix. /// </summary> /// <returns>The lower triangle of this matrix.</returns> public override Matrix<Complex> LowerTriangle() { var result = Build.SameAs(this); LowerTriangleImpl(result); return result; } /// <summary> /// Puts the lower triangle of this matrix into the result matrix. /// </summary> /// <param name="result">Where to store the lower triangle.</param> /// <exception cref="ArgumentNullException">If <paramref name="result"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">If the result matrix's dimensions are not the same as this matrix.</exception> public override void LowerTriangle(Matrix<Complex> result) { if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != RowCount || result.ColumnCount != ColumnCount) { throw DimensionsDontMatch<ArgumentException>(this, result); } if (ReferenceEquals(this, result)) { var tmp = Build.SameAs(result); LowerTriangle(tmp); tmp.CopyTo(result); } else { result.Clear(); LowerTriangleImpl(result); } } /// <summary> /// Puts the lower triangle of this matrix into the result matrix. /// </summary> /// <param name="result">Where to store the lower triangle.</param> private void LowerTriangleImpl(Matrix<Complex> result) { var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var row = 0; row < result.RowCount; row++) { var endIndex = rowPointers[row + 1]; for (var j = rowPointers[row]; j < endIndex; j++) { if (row >= columnIndices[j]) { result.At(row, columnIndices[j], values[j]); } } } } /// <summary> /// Returns a new matrix containing the upper triangle of this matrix. /// </summary> /// <returns>The upper triangle of this matrix.</returns> public override Matrix<Complex> UpperTriangle() { var result = Build.SameAs(this); UpperTriangleImpl(result); return result; } /// <summary> /// Puts the upper triangle of this matrix into the result matrix. /// </summary> /// <param name="result">Where to store the lower triangle.</param> /// <exception cref="ArgumentNullException">If <paramref name="result"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">If the result matrix's dimensions are not the same as this matrix.</exception> public override void UpperTriangle(Matrix<Complex> result) { if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != RowCount || result.ColumnCount != ColumnCount) { throw DimensionsDontMatch<ArgumentException>(this, result); } if (ReferenceEquals(this, result)) { var tmp = Build.SameAs(result); UpperTriangle(tmp); tmp.CopyTo(result); } else { result.Clear(); UpperTriangleImpl(result); } } /// <summary> /// Puts the upper triangle of this matrix into the result matrix. /// </summary> /// <param name="result">Where to store the lower triangle.</param> private void UpperTriangleImpl(Matrix<Complex> result) { var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var row = 0; row < result.RowCount; row++) { var endIndex = rowPointers[row + 1]; for (var j = rowPointers[row]; j < endIndex; j++) { if (row <= columnIndices[j]) { result.At(row, columnIndices[j], values[j]); } } } } /// <summary> /// Returns a new matrix containing the lower triangle of this matrix. The new matrix /// does not contain the diagonal elements of this matrix. /// </summary> /// <returns>The lower triangle of this matrix.</returns> public override Matrix<Complex> StrictlyLowerTriangle() { var result = Build.SameAs(this); StrictlyLowerTriangleImpl(result); return result; } /// <summary> /// Puts the strictly lower triangle of this matrix into the result matrix. /// </summary> /// <param name="result">Where to store the lower triangle.</param> /// <exception cref="ArgumentNullException">If <paramref name="result"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">If the result matrix's dimensions are not the same as this matrix.</exception> public override void StrictlyLowerTriangle(Matrix<Complex> result) { if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != RowCount || result.ColumnCount != ColumnCount) { throw DimensionsDontMatch<ArgumentException>(this, result); } if (ReferenceEquals(this, result)) { var tmp = Build.SameAs(result); StrictlyLowerTriangle(tmp); tmp.CopyTo(result); } else { result.Clear(); StrictlyLowerTriangleImpl(result); } } /// <summary> /// Puts the strictly lower triangle of this matrix into the result matrix. /// </summary> /// <param name="result">Where to store the lower triangle.</param> private void StrictlyLowerTriangleImpl(Matrix<Complex> result) { var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var row = 0; row < result.RowCount; row++) { var endIndex = rowPointers[row + 1]; for (var j = rowPointers[row]; j < endIndex; j++) { if (row > columnIndices[j]) { result.At(row, columnIndices[j], values[j]); } } } } /// <summary> /// Returns a new matrix containing the upper triangle of this matrix. The new matrix /// does not contain the diagonal elements of this matrix. /// </summary> /// <returns>The upper triangle of this matrix.</returns> public override Matrix<Complex> StrictlyUpperTriangle() { var result = Build.SameAs(this); StrictlyUpperTriangleImpl(result); return result; } /// <summary> /// Puts the strictly upper triangle of this matrix into the result matrix. /// </summary> /// <param name="result">Where to store the lower triangle.</param> /// <exception cref="ArgumentNullException">If <paramref name="result"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">If the result matrix's dimensions are not the same as this matrix.</exception> public override void StrictlyUpperTriangle(Matrix<Complex> result) { if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != RowCount || result.ColumnCount != ColumnCount) { throw DimensionsDontMatch<ArgumentException>(this, result); } if (ReferenceEquals(this, result)) { var tmp = Build.SameAs(result); StrictlyUpperTriangle(tmp); tmp.CopyTo(result); } else { result.Clear(); StrictlyUpperTriangleImpl(result); } } /// <summary> /// Puts the strictly upper triangle of this matrix into the result matrix. /// </summary> /// <param name="result">Where to store the lower triangle.</param> private void StrictlyUpperTriangleImpl(Matrix<Complex> result) { var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var row = 0; row < result.RowCount; row++) { var endIndex = rowPointers[row + 1]; for (var j = rowPointers[row]; j < endIndex; j++) { if (row < columnIndices[j]) { result.At(row, columnIndices[j], values[j]); } } } } /// <summary> /// Negate each element of this matrix and place the results into the result matrix. /// </summary> /// <param name="result">The result of the negation.</param> protected override void DoNegate(Matrix<Complex> result) { CopyTo(result); DoMultiply(-1, result); } /// <summary>Calculates the induced infinity norm of this matrix.</summary> /// <returns>The maximum absolute row sum of the matrix.</returns> public override double InfinityNorm() { var rowPointers = _storage.RowPointers; var values = _storage.Values; var norm = 0d; for (var i = 0; i < RowCount; i++) { var startIndex = rowPointers[i]; var endIndex = rowPointers[i + 1]; if (startIndex == endIndex) { continue; } var s = 0d; for (var j = startIndex; j < endIndex; j++) { s += values[j].Magnitude; } norm = Math.Max(norm, s); } return norm; } /// <summary>Calculates the entry-wise Frobenius norm of this matrix.</summary> /// <returns>The square root of the sum of the squared values.</returns> public override double FrobeniusNorm() { var aat = (SparseCompressedRowMatrixStorage<Complex>) (this*ConjugateTranspose()).Storage; var norm = 0d; for (var i = 0; i < aat.RowCount; i++) { var startIndex = aat.RowPointers[i]; var endIndex = aat.RowPointers[i + 1]; if (startIndex == endIndex) { continue; } for (var j = startIndex; j < endIndex; j++) { if (i == aat.ColumnIndices[j]) { norm += aat.Values[j].Magnitude; } } } return Math.Sqrt(norm); } /// <summary> /// Adds another matrix to this matrix. /// </summary> /// <param name="other">The matrix to add to this matrix.</param> /// <param name="result">The matrix to store the result of the addition.</param> /// <exception cref="ArgumentNullException">If the other matrix is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException">If the two matrices don't have the same dimensions.</exception> protected override void DoAdd(Matrix<Complex> other, Matrix<Complex> result) { var sparseOther = other as SparseMatrix; var sparseResult = result as SparseMatrix; if (sparseOther == null || sparseResult == null) { base.DoAdd(other, result); return; } if (ReferenceEquals(this, other)) { if (!ReferenceEquals(this, result)) { CopyTo(result); } Control.LinearAlgebraProvider.ScaleArray(2.0, sparseResult._storage.Values, sparseResult._storage.Values); return; } SparseMatrix left; if (ReferenceEquals(sparseOther, sparseResult)) { left = this; } else if (ReferenceEquals(this, sparseResult)) { left = sparseOther; } else { CopyTo(sparseResult); left = sparseOther; } var leftStorage = left._storage; for (var i = 0; i < leftStorage.RowCount; i++) { var endIndex = leftStorage.RowPointers[i + 1]; for (var j = leftStorage.RowPointers[i]; j < endIndex; j++) { var columnIndex = leftStorage.ColumnIndices[j]; var resVal = leftStorage.Values[j] + result.At(i, columnIndex); result.At(i, columnIndex, resVal); } } } /// <summary> /// Subtracts another matrix from this matrix. /// </summary> /// <param name="other">The matrix to subtract to this matrix.</param> /// <param name="result">The matrix to store the result of subtraction.</param> /// <exception cref="ArgumentNullException">If the other matrix is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException">If the two matrices don't have the same dimensions.</exception> protected override void DoSubtract(Matrix<Complex> other, Matrix<Complex> result) { var sparseOther = other as SparseMatrix; var sparseResult = result as SparseMatrix; if (sparseOther == null || sparseResult == null) { base.DoSubtract(other, result); return; } if (ReferenceEquals(this, other)) { result.Clear(); return; } var otherStorage = sparseOther._storage; if (ReferenceEquals(this, sparseResult)) { for (var i = 0; i < otherStorage.RowCount; i++) { var endIndex = otherStorage.RowPointers[i + 1]; for (var j = otherStorage.RowPointers[i]; j < endIndex; j++) { var columnIndex = otherStorage.ColumnIndices[j]; var resVal = sparseResult.At(i, columnIndex) - otherStorage.Values[j]; result.At(i, columnIndex, resVal); } } } else { if (!ReferenceEquals(sparseOther, sparseResult)) { sparseOther.CopyTo(sparseResult); } sparseResult.Negate(sparseResult); var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var i = 0; i < RowCount; i++) { var endIndex = rowPointers[i + 1]; for (var j = rowPointers[i]; j < endIndex; j++) { var columnIndex = columnIndices[j]; var resVal = sparseResult.At(i, columnIndex) + values[j]; result.At(i, columnIndex, resVal); } } } } /// <summary> /// Multiplies each element of the matrix by a scalar and places results into the result matrix. /// </summary> /// <param name="scalar">The scalar to multiply the matrix with.</param> /// <param name="result">The matrix to store the result of the multiplication.</param> protected override void DoMultiply(Complex scalar, Matrix<Complex> result) { if (scalar == 1.0) { CopyTo(result); return; } if (scalar == 0.0 || NonZerosCount == 0) { result.Clear(); return; } var sparseResult = result as SparseMatrix; if (sparseResult == null) { result.Clear(); var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var row = 0; row < RowCount; row++) { var start = rowPointers[row]; var end = rowPointers[row + 1]; if (start == end) { continue; } for (var index = start; index < end; index++) { var column = columnIndices[index]; result.At(row, column, values[index] * scalar); } } } else { if (!ReferenceEquals(this, result)) { CopyTo(sparseResult); } Control.LinearAlgebraProvider.ScaleArray(scalar, sparseResult._storage.Values, sparseResult._storage.Values); } } /// <summary> /// Multiplies this matrix with another matrix and places the results into the result matrix. /// </summary> /// <param name="other">The matrix to multiply with.</param> /// <param name="result">The result of the multiplication.</param> protected override void DoMultiply(Matrix<Complex> other, Matrix<Complex> result) { var sparseOther = other as SparseMatrix; var sparseResult = result as SparseMatrix; if (sparseOther != null && sparseResult != null) { DoMultiplySparse(sparseOther, sparseResult); return; } var diagonalOther = other.Storage as DiagonalMatrixStorage<Complex>; if (diagonalOther != null && sparseResult != null) { var diagonal = diagonalOther.Data; if (other.ColumnCount == other.RowCount) { Storage.MapIndexedTo(result.Storage, (i, j, x) => x*diagonal[j], Zeros.AllowSkip, ExistingData.Clear); } else { result.Storage.Clear(); Storage.MapSubMatrixIndexedTo(result.Storage, (i, j, x) => x*diagonal[j], 0, 0, RowCount, 0, 0, ColumnCount, Zeros.AllowSkip, ExistingData.AssumeZeros); } return; } result.Clear(); var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; var denseOther = other.Storage as DenseColumnMajorMatrixStorage<Complex>; if (denseOther != null) { // in this case we can directly address the underlying data-array for (var row = 0; row < RowCount; row++) { var startIndex = rowPointers[row]; var endIndex = rowPointers[row + 1]; if (startIndex == endIndex) { continue; } for (var column = 0; column < other.ColumnCount; column++) { int otherColumnStartPosition = column * other.RowCount; var sum = Complex.Zero; for (var index = startIndex; index < endIndex; index++) { sum += values[index] * denseOther.Data[otherColumnStartPosition + columnIndices[index]]; } result.At(row, column, sum); } } return; } var columnVector = new DenseVector(other.RowCount); for (var row = 0; row < RowCount; row++) { var startIndex = rowPointers[row]; var endIndex = rowPointers[row + 1]; if (startIndex == endIndex) { continue; } for (var column = 0; column < other.ColumnCount; column++) { // Multiply row of matrix A on column of matrix B other.Column(column, columnVector); var sum = Complex.Zero; for (var index = startIndex; index < endIndex; index++) { sum += values[index] * columnVector[columnIndices[index]]; } result.At(row, column, sum); } } } void DoMultiplySparse(SparseMatrix other, SparseMatrix result) { result.Clear(); var ax = _storage.Values; var ap = _storage.RowPointers; var ai = _storage.ColumnIndices; var bx = other._storage.Values; var bp = other._storage.RowPointers; var bi = other._storage.ColumnIndices; int rows = RowCount; int cols = other.ColumnCount; int[] cp = result._storage.RowPointers; var marker = new int[cols]; for (int ib = 0; ib < cols; ib++) { marker[ib] = -1; } int count = 0; for (int i = 0; i < rows; i++) { // For each row of A for (int j = ap[i]; j < ap[i + 1]; j++) { // Row number to be added int a = ai[j]; for (int k = bp[a]; k < bp[a + 1]; k++) { int b = bi[k]; if (marker[b] != i) { marker[b] = i; count++; } } } // Record non-zero count. cp[i + 1] = count; } var ci = new int[count]; var cx = new Complex[count]; for (int ib = 0; ib < cols; ib++) { marker[ib] = -1; } count = 0; for (int i = 0; i < rows; i++) { int rowStart = cp[i]; for (int j = ap[i]; j < ap[i + 1]; j++) { int a = ai[j]; Complex aEntry = ax[j]; for (int k = bp[a]; k < bp[a + 1]; k++) { int b = bi[k]; Complex bEntry = bx[k]; if (marker[b] < rowStart) { marker[b] = count; ci[marker[b]] = b; cx[marker[b]] = aEntry * bEntry; count++; } else { cx[marker[b]] += aEntry * bEntry; } } } } result._storage.Values = cx; result._storage.ColumnIndices = ci; result._storage.Normalize(); } /// <summary> /// Multiplies this matrix with a vector and places the results into the result vector. /// </summary> /// <param name="rightSide">The vector to multiply with.</param> /// <param name="result">The result of the multiplication.</param> protected override void DoMultiply(Vector<Complex> rightSide, Vector<Complex> result) { var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var row = 0; row < RowCount; row++) { var startIndex = rowPointers[row]; var endIndex = rowPointers[row + 1]; if (startIndex == endIndex) { continue; } var sum = Complex.Zero; for (var index = startIndex; index < endIndex; index++) { sum += values[index] * rightSide[columnIndices[index]]; } result[row] = sum; } } /// <summary> /// Multiplies this matrix with transpose of another matrix and places the results into the result matrix. /// </summary> /// <param name="other">The matrix to multiply with.</param> /// <param name="result">The result of the multiplication.</param> protected override void DoTransposeAndMultiply(Matrix<Complex> other, Matrix<Complex> result) { var otherSparse = other as SparseMatrix; var resultSparse = result as SparseMatrix; if (otherSparse == null || resultSparse == null) { base.DoTransposeAndMultiply(other, result); return; } resultSparse.Clear(); var rowPointers = _storage.RowPointers; var values = _storage.Values; var otherStorage = otherSparse._storage; for (var j = 0; j < RowCount; j++) { var startIndexOther = otherStorage.RowPointers[j]; var endIndexOther = otherStorage.RowPointers[j + 1]; if (startIndexOther == endIndexOther) { continue; } for (var i = 0; i < RowCount; i++) { // Multiply row of matrix A on row of matrix B var startIndexThis = rowPointers[i]; var endIndexThis = rowPointers[i + 1]; if (startIndexThis == endIndexThis) { continue; } var sum = Complex.Zero; for (var index = startIndexOther; index < endIndexOther; index++) { var ind = _storage.FindItem(i, otherStorage.ColumnIndices[index]); if (ind >= 0) { sum += otherStorage.Values[index] * values[ind]; } } resultSparse._storage.At(i, j, sum + result.At(i, j)); } } } /// <summary> /// Pointwise multiplies this matrix with another matrix and stores the result into the result matrix. /// </summary> /// <param name="other">The matrix to pointwise multiply with this one.</param> /// <param name="result">The matrix to store the result of the pointwise multiplication.</param> protected override void DoPointwiseMultiply(Matrix<Complex> other, Matrix<Complex> result) { result.Clear(); var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var i = 0; i < RowCount; i++) { var endIndex = rowPointers[i + 1]; for (var j = rowPointers[i]; j < endIndex; j++) { var resVal = values[j]*other.At(i, columnIndices[j]); if (!resVal.IsZero()) { result.At(i, columnIndices[j], resVal); } } } } /// <summary> /// Pointwise divide this matrix by another matrix and stores the result into the result matrix. /// </summary> /// <param name="divisor">The matrix to pointwise divide this one by.</param> /// <param name="result">The matrix to store the result of the pointwise division.</param> protected override void DoPointwiseDivide(Matrix<Complex> divisor, Matrix<Complex> result) { result.Clear(); var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var i = 0; i < RowCount; i++) { var endIndex = rowPointers[i + 1]; for (var j = rowPointers[i]; j < endIndex; j++) { if (!values[j].IsZero()) { result.At(i, columnIndices[j], values[j]/divisor.At(i, columnIndices[j])); } } } } public override void KroneckerProduct(Matrix<Complex> other, Matrix<Complex> result) { if (other == null) { throw new ArgumentNullException("other"); } if (result == null) { throw new ArgumentNullException("result"); } if (result.RowCount != (RowCount*other.RowCount) || result.ColumnCount != (ColumnCount*other.ColumnCount)) { throw DimensionsDontMatch<ArgumentOutOfRangeException>(this, other, result); } var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var i = 0; i < RowCount; i++) { var endIndex = rowPointers[i + 1]; for (var j = rowPointers[i]; j < endIndex; j++) { if (!values[j].IsZero()) { result.SetSubMatrix(i*other.RowCount, other.RowCount, columnIndices[j]*other.ColumnCount, other.ColumnCount, values[j]*other); } } } } /// <summary> /// Evaluates whether this matrix is symmetric. /// </summary> public override bool IsSymmetric() { if (RowCount != ColumnCount) { return false; } var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var row = 0; row < RowCount; row++) { var start = rowPointers[row]; var end = rowPointers[row + 1]; if (start == end) { continue; } for (var index = start; index < end; index++) { var column = columnIndices[index]; if (!values[index].Equals(At(column, row))) { return false; } } } return true; } /// <summary> /// Evaluates whether this matrix is hermitian (conjugate symmetric). /// </summary> public override bool IsHermitian() { if (RowCount != ColumnCount) { return false; } var rowPointers = _storage.RowPointers; var columnIndices = _storage.ColumnIndices; var values = _storage.Values; for (var row = 0; row < RowCount; row++) { var start = rowPointers[row]; var end = rowPointers[row + 1]; if (start == end) { continue; } for (var index = start; index < end; index++) { var column = columnIndices[index]; if (!values[index].Equals(At(column, row).Conjugate())) { return false; } } } return true; } /// <summary> /// Adds two matrices together and returns the results. /// </summary> /// <remarks>This operator will allocate new memory for the result. It will /// choose the representation of either <paramref name="leftSide"/> or <paramref name="rightSide"/> depending on which /// is denser.</remarks> /// <param name="leftSide">The left matrix to add.</param> /// <param name="rightSide">The right matrix to add.</param> /// <returns>The result of the addition.</returns> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="leftSide"/> and <paramref name="rightSide"/> don't have the same dimensions.</exception> /// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> or <paramref name="rightSide"/> is <see langword="null" />.</exception> public static SparseMatrix operator +(SparseMatrix leftSide, SparseMatrix rightSide) { if (rightSide == null) { throw new ArgumentNullException("rightSide"); } if (leftSide == null) { throw new ArgumentNullException("leftSide"); } if (leftSide.RowCount != rightSide.RowCount || leftSide.ColumnCount != rightSide.ColumnCount) { throw DimensionsDontMatch<ArgumentOutOfRangeException>(leftSide, rightSide); } return (SparseMatrix)leftSide.Add(rightSide); } /// <summary> /// Returns a <strong>Matrix</strong> containing the same values of <paramref name="rightSide"/>. /// </summary> /// <param name="rightSide">The matrix to get the values from.</param> /// <returns>A matrix containing a the same values as <paramref name="rightSide"/>.</returns> /// <exception cref="ArgumentNullException">If <paramref name="rightSide"/> is <see langword="null" />.</exception> public static SparseMatrix operator +(SparseMatrix rightSide) { if (rightSide == null) { throw new ArgumentNullException("rightSide"); } return (SparseMatrix)rightSide.Clone(); } /// <summary> /// Subtracts two matrices together and returns the results. /// </summary> /// <remarks>This operator will allocate new memory for the result. It will /// choose the representation of either <paramref name="leftSide"/> or <paramref name="rightSide"/> depending on which /// is denser.</remarks> /// <param name="leftSide">The left matrix to subtract.</param> /// <param name="rightSide">The right matrix to subtract.</param> /// <returns>The result of the addition.</returns> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="leftSide"/> and <paramref name="rightSide"/> don't have the same dimensions.</exception> /// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> or <paramref name="rightSide"/> is <see langword="null" />.</exception> public static SparseMatrix operator -(SparseMatrix leftSide, SparseMatrix rightSide) { if (rightSide == null) { throw new ArgumentNullException("rightSide"); } if (leftSide == null) { throw new ArgumentNullException("leftSide"); } if (leftSide.RowCount != rightSide.RowCount || leftSide.ColumnCount != rightSide.ColumnCount) { throw DimensionsDontMatch<ArgumentOutOfRangeException>(leftSide, rightSide); } return (SparseMatrix)leftSide.Subtract(rightSide); } /// <summary> /// Negates each element of the matrix. /// </summary> /// <param name="rightSide">The matrix to negate.</param> /// <returns>A matrix containing the negated values.</returns> /// <exception cref="ArgumentNullException">If <paramref name="rightSide"/> is <see langword="null" />.</exception> public static SparseMatrix operator -(SparseMatrix rightSide) { if (rightSide == null) { throw new ArgumentNullException("rightSide"); } return (SparseMatrix)rightSide.Negate(); } /// <summary> /// Multiplies a <strong>Matrix</strong> by a constant and returns the result. /// </summary> /// <param name="leftSide">The matrix to multiply.</param> /// <param name="rightSide">The constant to multiply the matrix by.</param> /// <returns>The result of the multiplication.</returns> /// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> is <see langword="null" />.</exception> public static SparseMatrix operator *(SparseMatrix leftSide, Complex rightSide) { if (leftSide == null) { throw new ArgumentNullException("leftSide"); } return (SparseMatrix)leftSide.Multiply(rightSide); } /// <summary> /// Multiplies a <strong>Matrix</strong> by a constant and returns the result. /// </summary> /// <param name="leftSide">The matrix to multiply.</param> /// <param name="rightSide">The constant to multiply the matrix by.</param> /// <returns>The result of the multiplication.</returns> /// <exception cref="ArgumentNullException">If <paramref name="rightSide"/> is <see langword="null" />.</exception> public static SparseMatrix operator *(Complex leftSide, SparseMatrix rightSide) { if (rightSide == null) { throw new ArgumentNullException("rightSide"); } return (SparseMatrix)rightSide.Multiply(leftSide); } /// <summary> /// Multiplies two matrices. /// </summary> /// <remarks>This operator will allocate new memory for the result. It will /// choose the representation of either <paramref name="leftSide"/> or <paramref name="rightSide"/> depending on which /// is denser.</remarks> /// <param name="leftSide">The left matrix to multiply.</param> /// <param name="rightSide">The right matrix to multiply.</param> /// <returns>The result of multiplication.</returns> /// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> or <paramref name="rightSide"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">If the dimensions of <paramref name="leftSide"/> or <paramref name="rightSide"/> don't conform.</exception> public static SparseMatrix operator *(SparseMatrix leftSide, SparseMatrix rightSide) { if (leftSide == null) { throw new ArgumentNullException("leftSide"); } if (rightSide == null) { throw new ArgumentNullException("rightSide"); } if (leftSide.ColumnCount != rightSide.RowCount) { throw DimensionsDontMatch<ArgumentException>(leftSide, rightSide); } return (SparseMatrix)leftSide.Multiply(rightSide); } /// <summary> /// Multiplies a <strong>Matrix</strong> and a Vector. /// </summary> /// <param name="leftSide">The matrix to multiply.</param> /// <param name="rightSide">The vector to multiply.</param> /// <returns>The result of multiplication.</returns> /// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> or <paramref name="rightSide"/> is <see langword="null" />.</exception> public static SparseVector operator *(SparseMatrix leftSide, SparseVector rightSide) { if (leftSide == null) { throw new ArgumentNullException("leftSide"); } return (SparseVector)leftSide.Multiply(rightSide); } /// <summary> /// Multiplies a Vector and a <strong>Matrix</strong>. /// </summary> /// <param name="leftSide">The vector to multiply.</param> /// <param name="rightSide">The matrix to multiply.</param> /// <returns>The result of multiplication.</returns> /// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> or <paramref name="rightSide"/> is <see langword="null" />.</exception> public static SparseVector operator *(SparseVector leftSide, SparseMatrix rightSide) { if (rightSide == null) { throw new ArgumentNullException("rightSide"); } return (SparseVector)rightSide.LeftMultiply(leftSide); } /// <summary> /// Multiplies a <strong>Matrix</strong> by a constant and returns the result. /// </summary> /// <param name="leftSide">The matrix to multiply.</param> /// <param name="rightSide">The constant to multiply the matrix by.</param> /// <returns>The result of the multiplication.</returns> /// <exception cref="ArgumentNullException">If <paramref name="leftSide"/> is <see langword="null" />.</exception> public static SparseMatrix operator %(SparseMatrix leftSide, Complex rightSide) { if (leftSide == null) { throw new ArgumentNullException("leftSide"); } return (SparseMatrix)leftSide.Remainder(rightSide); } public override string ToTypeString() { return string.Format("SparseMatrix {0}x{1}-Complex {2:P2} Filled", RowCount, ColumnCount, NonZerosCount / (RowCount * (double)ColumnCount)); } } }
albertp007/mathnet-numerics
src/Numerics/LinearAlgebra/Complex/SparseMatrix.cs
C#
mit
60,593
type SerializeOptions = { domain?: string, encode?: (stringToDecode: string) => string, expires?: Date, httpOnly?: boolean, maxAge?: number, path?: string, sameSite?: boolean | 'lax' | 'strict', secure?: boolean, ... }; type ParseOptions = { // Library itself does not specify output for decode function. // Because of simplicity is output set to string which is default settings and best for working with cookies. decode?: (stringToDecode: string) => string, ... }; declare module 'cookie' { declare module.exports: { serialize(name: string, val: string, options: ?SerializeOptions): string, parse(data: string, options: ?ParseOptions): { [string]: string, ... }, ... }; };
flowtype/flow-typed
definitions/npm/cookie_v0.3.x/flow_v0.104.x-/cookie_v0.3.x.js
JavaScript
mit
711
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Security.Permissions; namespace StaThreadSyncronizer { [SecurityPermission(SecurityAction.Demand, ControlThread = true)] public class StaSynchronizationContext : SynchronizationContext, IDisposable { private BlockingQueue<SendOrPostCallbackItem> mQueue; private StaThread mStaThread; public StaSynchronizationContext() : base() { mQueue = new BlockingQueue<SendOrPostCallbackItem>(); mStaThread = new StaThread(mQueue); mStaThread.Start(); } public override void Send(SendOrPostCallback action, object state) { // to avoid deadlock! if (Thread.CurrentThread.ManagedThreadId == mStaThread.ManagedThreadId) { action(state); return; } // create an item for execution SendOrPostCallbackItem item = new SendOrPostCallbackItem(action, state, ExecutionType.Send); // queue the item mQueue.Enqueue(item); // wait for the item execution to end item.ExecutionCompleteWaitHandle.WaitOne(); // if there was an exception, throw it on the caller thread, not the // sta thread. if (item.ExecutedWithException) throw item.Exception; } public override void Post(SendOrPostCallback d, object state) { // queue the item and don't wait for its execution. This is risky because // an unhandled exception will terminate the STA thread. Use with caution. SendOrPostCallbackItem item = new SendOrPostCallbackItem(d, state, ExecutionType.Post); mQueue.Enqueue(item); } public void Dispose() { mStaThread.Stop(); } public override SynchronizationContext CreateCopy() { return this; } } }
jmptrader/JRIAppTS
RIAppDemo/RIAPP.DataService/Utils/STAThreadSync/StaSynchronizationContext.cs
C#
mit
1,996
<TS language="sv" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Högerklicka för att ändra adressen eller etiketten.</translation> </message> <message> <source>Create a new address</source> <translation>Skapa ny adress</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Ny</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiera den markerade adressen till systemets Urklipp</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Kopiera</translation> </message> <message> <source>C&amp;lose</source> <translation>S&amp;täng</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Ta bort den valda adressen från listan</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Exportera informationen i den nuvarande fliken till en fil</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Exportera</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Radera</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Välj en adress att sända betalning till</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Välj en adress att ta emot betalning till</translation> </message> <message> <source>C&amp;hoose</source> <translation>V&amp;älj</translation> </message> <message> <source>Sending addresses</source> <translation>Avsändaradresser</translation> </message> <message> <source>Receiving addresses</source> <translation>Mottagaradresser</translation> </message> <message> <source>These are your Mincoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Detta är dina Mincoin adresser för att skicka betalningar. Kolla alltid summan och den mottagande adressen innan du skickar Mincoins.</translation> </message> <message> <source>These are your Mincoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Detta är dina Mincoin adresser för att ta emot betalningar. Det rekommenderas att använda en ny mottagningsadress för varje transaktion.</translation> </message> <message> <source>&amp;Copy Address</source> <translation>&amp;Kopiera adress</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Kopiera &amp;etikett</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Redigera</translation> </message> <message> <source>Export Address List</source> <translation>Exportera adresslista</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Exporting Failed</source> <translation>Export misslyckades</translation> </message> <message> <source>There was an error trying to save the address list to %1. Please try again.</source> <translation>Det inträffade ett fel när adresslistan skulle sparas till %1. Var vänlig och försök igen.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Etikett</translation> </message> <message> <source>Address</source> <translation>Adress</translation> </message> <message> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Lösenordsdialog</translation> </message> <message> <source>Enter passphrase</source> <translation>Ange lösenord</translation> </message> <message> <source>New passphrase</source> <translation>Nytt lösenord</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Upprepa nytt lösenord</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Ange plånbokens nya lösenord. &lt;br/&gt; Använd ett lösenord på &lt;b&gt;tio eller fler slumpmässiga tecken,&lt;/b&gt; eller &lt;b&gt;åtta eller fler ord.&lt;/b&gt;.</translation> </message> <message> <source>Encrypt wallet</source> <translation>Kryptera plånbok</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Denna operation behöver din plånboks lösenord för att låsa upp plånboken.</translation> </message> <message> <source>Unlock wallet</source> <translation>Lås upp plånbok</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Denna operation behöver din plånboks lösenord för att dekryptera plånboken.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Dekryptera plånbok</translation> </message> <message> <source>Change passphrase</source> <translation>Ändra lösenord</translation> </message> <message> <source>Enter the old passphrase and new passphrase to the wallet.</source> <translation>Ge det gamla lösenordet och det nya lösenordet för plånboken.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Bekräfta kryptering av plånbok</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR MINCOINS&lt;/b&gt;!</source> <translation>VARNING: Om du krypterar din plånbok och glömmer ditt lösenord, kommer du att &lt;b&gt;FÖRLORA ALLA DINA MINCOIN&lt;/b&gt;!</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Är du säker på att du vill kryptera din plånbok?</translation> </message> <message> <source>Wallet encrypted</source> <translation>Plånbok krypterad</translation> </message> <message> <source>%1 will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your mincoins from being stolen by malware infecting your computer.</source> <translation>%1 kommer nu att stänga ner för att färdigställa krypteringen. Tänk på att en krypterad plånbok inte skyddar mot stöld om din dator är infekterad med en keylogger.</translation> </message> <message> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>VIKTIGT: Alla tidigare säkerhetskopior du har gjort av plånboksfilen ska ersättas med den nya genererade, krypterade plånboksfilen. Av säkerhetsskäl kommer tidigare säkerhetskopior av den okrypterade plånboksfilen blir oanvändbara när du börjar använda en ny, krypterad plånbok.</translation> </message> <message> <source>Wallet encryption failed</source> <translation>Kryptering av plånbok misslyckades</translation> </message> <message> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Kryptering av plånbok misslyckades på grund av ett internt fel. Din plånbok blev inte krypterad.</translation> </message> <message> <source>The supplied passphrases do not match.</source> <translation>De angivna lösenorden överensstämmer inte.</translation> </message> <message> <source>Wallet unlock failed</source> <translation>Misslyckades låsa upp plånboken</translation> </message> <message> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Lösenordet för dekryptering av plånboken var felaktig.</translation> </message> <message> <source>Wallet decryption failed</source> <translation>Dekryptering av plånbok misslyckades</translation> </message> <message> <source>Wallet passphrase was successfully changed.</source> <translation>Plånbokens lösenord har ändrats.</translation> </message> <message> <source>Warning: The Caps Lock key is on!</source> <translation>Varning: Caps Lock är påslaget!</translation> </message> </context> <context> <name>BanTableModel</name> <message> <source>IP/Netmask</source> <translation>IP/nätmask</translation> </message> <message> <source>Banned Until</source> <translation>Bannad tills</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Sign &amp;message...</source> <translation>Signera &amp;meddelande...</translation> </message> <message> <source>Synchronizing with network...</source> <translation>Synkroniserar med nätverk...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Översikt</translation> </message> <message> <source>Node</source> <translation>Nod</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Visa generell översikt av plånboken</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transaktioner</translation> </message> <message> <source>Browse transaction history</source> <translation>Bläddra i transaktionshistorik</translation> </message> <message> <source>E&amp;xit</source> <translation>&amp;Avsluta</translation> </message> <message> <source>Quit application</source> <translation>Avsluta programmet</translation> </message> <message> <source>&amp;About %1</source> <translation>&amp;Om %1</translation> </message> <message> <source>Show information about %1</source> <translation>Visa information om %1</translation> </message> <message> <source>About &amp;Qt</source> <translation>Om &amp;Qt</translation> </message> <message> <source>Show information about Qt</source> <translation>Visa information om Qt</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Alternativ...</translation> </message> <message> <source>Modify configuration options for %1</source> <translation>Ändra konfigurationsalternativ för %1</translation> </message> <message> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Kryptera plånbok...</translation> </message> <message> <source>&amp;Backup Wallet...</source> <translation>&amp;Säkerhetskopiera plånbok...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Byt lösenord...</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>Av&amp;sändaradresser...</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>Mottaga&amp;radresser...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Öppna &amp;URI...</translation> </message> <message> <source>Click to disable network activity.</source> <translation>Klicka för att inaktivera nätverksaktivitet.</translation> </message> <message> <source>Network activity disabled.</source> <translation>Nätverksaktivitet inaktiverad.</translation> </message> <message> <source>Click to enable network activity again.</source> <translation>Klicka för att aktivera nätverksaktivitet igen.</translation> </message> <message> <source>Syncing Headers (%1%)...</source> <translation>Synkar huvuden (%1%)...</translation> </message> <message> <source>Reindexing blocks on disk...</source> <translation>Återindexerar block på disken...</translation> </message> <message> <source>Send coins to a Mincoin address</source> <translation>Skicka mincoins till en Mincoin-adress</translation> </message> <message> <source>Backup wallet to another location</source> <translation>Säkerhetskopiera plånboken till en annan plats</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Byt lösenfras för kryptering av plånbok</translation> </message> <message> <source>&amp;Debug window</source> <translation>&amp;Debug-fönster</translation> </message> <message> <source>Open debugging and diagnostic console</source> <translation>Öppna debug- och diagnostikkonsolen</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Verifiera meddelande...</translation> </message> <message> <source>Mincoin</source> <translation>Mincoin</translation> </message> <message> <source>Wallet</source> <translation>Plånbok</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Skicka</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Ta emot</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Visa / Göm</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Visa eller göm huvudfönstret</translation> </message> <message> <source>Encrypt the private keys that belong to your wallet</source> <translation>Kryptera de privata nycklar som tillhör din plånbok</translation> </message> <message> <source>Sign messages with your Mincoin addresses to prove you own them</source> <translation>Signera meddelanden med din Mincoin-adress för att bevisa att du äger dem</translation> </message> <message> <source>Verify messages to ensure they were signed with specified Mincoin addresses</source> <translation>Verifiera meddelanden för att vara säker på att de var signerade med specificerade Mincoin-adresser</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Arkiv</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Inställningar</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Hjälp</translation> </message> <message> <source>Tabs toolbar</source> <translation>Verktygsfält för tabbar</translation> </message> <message> <source>Request payments (generates QR codes and mincoin: URIs)</source> <translation>Begär betalning (genererar QR-koder och mincoin-URI)</translation> </message> <message> <source>Show the list of used sending addresses and labels</source> <translation>Visa listan av använda avsändaradresser och etiketter</translation> </message> <message> <source>Show the list of used receiving addresses and labels</source> <translation>Visa listan av använda mottagningsadresser och etiketter</translation> </message> <message> <source>Open a mincoin: URI or payment request</source> <translation>Öppna en mincoin: URI eller betalningsbegäran</translation> </message> <message> <source>&amp;Command-line options</source> <translation>&amp;Kommandoradsalternativ</translation> </message> <message numerus="yes"> <source>%n active connection(s) to Mincoin network</source> <translation><numerusform>%n aktiva anslutningar till Mincoin-nätverket.</numerusform><numerusform>%n aktiva anslutningar till Mincoin-nätverket.</numerusform></translation> </message> <message> <source>Indexing blocks on disk...</source> <translation>Indexerar block på disken...</translation> </message> <message> <source>Processing blocks on disk...</source> <translation>Bearbetar block på disken...</translation> </message> <message numerus="yes"> <source>Processed %n block(s) of transaction history.</source> <translation><numerusform>Bearbetade %n block av transaktionshistoriken.</numerusform><numerusform>Bearbetade %n block av transaktionshistoriken.</numerusform></translation> </message> <message> <source>%1 behind</source> <translation>%1 efter</translation> </message> <message> <source>Last received block was generated %1 ago.</source> <translation>Senast mottagna block genererades för %1 sen.</translation> </message> <message> <source>Transactions after this will not yet be visible.</source> <translation>Transaktioner efter denna kommer inte ännu vara synliga.</translation> </message> <message> <source>Error</source> <translation>Fel</translation> </message> <message> <source>Warning</source> <translation>Varning</translation> </message> <message> <source>Information</source> <translation>Information</translation> </message> <message> <source>Up to date</source> <translation>Uppdaterad</translation> </message> <message> <source>Show the %1 help message to get a list with possible Mincoin command-line options</source> <translation>Visa %1 hjälpmeddelande för att få en lista med möjliga Mincoin kommandoradsalternativ.</translation> </message> <message> <source>%1 client</source> <translation>%1-klient</translation> </message> <message> <source>Connecting to peers...</source> <translation>Ansluter till noder...</translation> </message> <message> <source>Catching up...</source> <translation>Hämtar senaste...</translation> </message> <message> <source>Date: %1 </source> <translation>Datum: %1 </translation> </message> <message> <source>Amount: %1 </source> <translation>Belopp: %1 </translation> </message> <message> <source>Type: %1 </source> <translation>Typ: %1 </translation> </message> <message> <source>Label: %1 </source> <translation>Etikett: %1 </translation> </message> <message> <source>Address: %1 </source> <translation>Adress: %1 </translation> </message> <message> <source>Sent transaction</source> <translation>Transaktion skickad</translation> </message> <message> <source>Incoming transaction</source> <translation>Inkommande transaktion</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Denna plånbok är &lt;b&gt;krypterad&lt;/b&gt; och för närvarande &lt;b&gt;olåst&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Denna plånbok är &lt;b&gt;krypterad&lt;/b&gt; och för närvarande &lt;b&gt;låst&lt;/b&gt;</translation> </message> <message> <source>A fatal error occurred. Mincoin can no longer continue safely and will quit.</source> <translation>Ett kritiskt fel uppstod. Mincoin kan inte fortsätta att köra säkert och kommer att avslutas.</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Selection</source> <translation>Myntval</translation> </message> <message> <source>Quantity:</source> <translation>Kvantitet:</translation> </message> <message> <source>Bytes:</source> <translation>Antal byte:</translation> </message> <message> <source>Amount:</source> <translation>Belopp:</translation> </message> <message> <source>Fee:</source> <translation>Avgift:</translation> </message> <message> <source>Dust:</source> <translation>Damm:</translation> </message> <message> <source>After Fee:</source> <translation>Efter avgift:</translation> </message> <message> <source>Change:</source> <translation>Växel:</translation> </message> <message> <source>(un)select all</source> <translation>(av)markera allt</translation> </message> <message> <source>Tree mode</source> <translation>Trädvy</translation> </message> <message> <source>List mode</source> <translation>Listvy</translation> </message> <message> <source>Amount</source> <translation>Mängd</translation> </message> <message> <source>Received with label</source> <translation>Mottagen med etikett</translation> </message> <message> <source>Received with address</source> <translation>Mottagen med adress</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Confirmations</source> <translation>Bekräftelser</translation> </message> <message> <source>Confirmed</source> <translation>Bekräftad</translation> </message> <message> <source>Copy address</source> <translation>Kopiera adress</translation> </message> <message> <source>Copy label</source> <translation>Kopiera etikett</translation> </message> <message> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> <message> <source>Copy transaction ID</source> <translation>Kopiera transaktions-ID</translation> </message> <message> <source>yes</source> <translation>ja</translation> </message> <message> <source>no</source> <translation>nej</translation> </message> <message> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Redigera adress</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etikett</translation> </message> <message> <source>The label associated with this address list entry</source> <translation>Etiketten associerad med denna adresslistas post</translation> </message> <message> <source>The address associated with this address list entry. This can only be modified for sending addresses.</source> <translation>Adressen associerad med denna adresslistas post. Detta kan bara ändras för sändningsadresser.</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Adress</translation> </message> <message> <source>Could not unlock wallet.</source> <translation>Kunde inte låsa upp plånboken.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>A new data directory will be created.</source> <translation>En ny datakatalog kommer att skapas.</translation> </message> <message> <source>name</source> <translation>namn</translation> </message> <message> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation>Katalogen finns redan. Lägg till %1 om du vill skapa en ny katalog här.</translation> </message> <message> <source>Path already exists, and is not a directory.</source> <translation>Sökvägen finns redan, och är inte en katalog.</translation> </message> <message> <source>Cannot create data directory here.</source> <translation>Kan inte skapa datakatalog här.</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>version</translation> </message> <message> <source>(%1-bit)</source> <translation>(%1-bit)</translation> </message> <message> <source>About %1</source> <translation>Om %1</translation> </message> <message> <source>Command-line options</source> <translation>Kommandoradsalternativ</translation> </message> <message> <source>Usage:</source> <translation>Användning:</translation> </message> <message> <source>command-line options</source> <translation>kommandoradsalternativ</translation> </message> <message> <source>UI Options:</source> <translation>UI-inställningar:</translation> </message> <message> <source>Choose data directory on startup (default: %u)</source> <translation>Välj datakatalog vid uppstart (standard: %u)</translation> </message> <message> <source>Set language, for example "de_DE" (default: system locale)</source> <translation>Ange språk, till exempel "de_DE" (standard: systemspråk)</translation> </message> <message> <source>Start minimized</source> <translation>Starta minimerad</translation> </message> <message> <source>Set SSL root certificates for payment request (default: -system-)</source> <translation>Ange SSL rotcertifikat för betalningsansökan (standard: -system-)</translation> </message> <message> <source>Show splash screen on startup (default: %u)</source> <translation>Visa startbild vid uppstart (standard: %u)</translation> </message> <message> <source>Reset all settings changed in the GUI</source> <translation>Återställ alla inställningar som gjorts i GUI</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Välkommen</translation> </message> <message> <source>Welcome to %1.</source> <translation>Välkommen till %1.</translation> </message> <message> <source>As this is the first time the program is launched, you can choose where %1 will store its data.</source> <translation>Eftersom detta är första gången programmet startas får du välja var %1 skall lagra sitt data.</translation> </message> <message> <source>%1 will download and store a copy of the Mincoin block chain. At least %2GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation>%1 kommer att ladda ner och spara en kopia av Mincoin blockkedjan. Åtminstone %2GB av data kommer att sparas i denna katalog, och den kommer att växa över tiden. Plånboken kommer också att sparas i denna katalog.</translation> </message> <message> <source>Use the default data directory</source> <translation>Använd den förvalda datakatalogen</translation> </message> <message> <source>Use a custom data directory:</source> <translation>Använd en anpassad datakatalog:</translation> </message> <message> <source>Error: Specified data directory "%1" cannot be created.</source> <translation>Fel: Den angivna datakatalogen "%1" kan inte skapas.</translation> </message> <message> <source>Error</source> <translation>Fel</translation> </message> <message numerus="yes"> <source>%n GB of free space available</source> <translation><numerusform>%n GB fritt utrymme kvar</numerusform><numerusform>%n GB fritt utrymme kvar</numerusform></translation> </message> <message numerus="yes"> <source>(of %n GB needed)</source> <translation><numerusform>(av %n GB behövs)</numerusform><numerusform>(av %n GB behövs)</numerusform></translation> </message> </context> <context> <name>ModalOverlay</name> <message> <source>Form</source> <translation>Formulär</translation> </message> <message> <source>Number of blocks left</source> <translation>Antal block kvar</translation> </message> <message> <source>Unknown...</source> <translation>Okänt...</translation> </message> <message> <source>Last block time</source> <translation>Sista blocktid</translation> </message> <message> <source>Progress</source> <translation>Förlopp</translation> </message> <message> <source>calculating...</source> <translation>beräknar...</translation> </message> <message> <source>Hide</source> <translation>Göm</translation> </message> <message> <source>Unknown. Syncing Headers (%1)...</source> <translation>Okänd. Synkar huvuden (%1)...</translation> </message> </context> <context> <name>OpenURIDialog</name> <message> <source>Open URI</source> <translation>Öppna URI</translation> </message> <message> <source>Open payment request from URI or file</source> <translation>Öppna betalningsbegäran från URI eller fil</translation> </message> <message> <source>URI:</source> <translation>URI:</translation> </message> <message> <source>Select payment request file</source> <translation>Välj betalningsbegäransfil</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Alternativ</translation> </message> <message> <source>&amp;Main</source> <translation>&amp;Allmänt</translation> </message> <message> <source>Automatically start %1 after logging in to the system.</source> <translation>Starta %1 automatiskt efter inloggningen.</translation> </message> <message> <source>&amp;Start %1 on system login</source> <translation>&amp;Starta %1 vid systemlogin</translation> </message> <message> <source>Size of &amp;database cache</source> <translation>Storleken på &amp;databascache</translation> </message> <message> <source>MB</source> <translation>MB</translation> </message> <message> <source>Number of script &amp;verification threads</source> <translation>Antalet skript&amp;verifikationstrådar</translation> </message> <message> <source>Accept connections from outside</source> <translation>Acceptera anslutningar utifrån</translation> </message> <message> <source>Allow incoming connections</source> <translation>Acceptera inkommande anslutningar</translation> </message> <message> <source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source> <translation>Proxyns IP-adress (t.ex. IPv4: 127.0.0.1 / IPv6: ::1)</translation> </message> <message> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Exit in the menu.</source> <translation>Minimera istället för att stänga programmet när fönstret stängs. När detta alternativ är aktiverat stängs programmet endast genom att välja Stäng i menyn.</translation> </message> <message> <source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source> <translation>Tredjeparts URL:er (t.ex. en blockutforskare) som finns i transaktionstabben som ett menyval i sammanhanget. %s i URL:en ersätts med tansaktionshashen. Flera URL:er är separerade med vertikala streck |.</translation> </message> <message> <source>Third party transaction URLs</source> <translation>Tredjeparts transaktions-URL:er</translation> </message> <message> <source>Active command-line options that override above options:</source> <translation>Aktiva kommandoradsalternativ som ersätter alternativen ovan:</translation> </message> <message> <source>Reset all client options to default.</source> <translation>Återställ alla klientinställningar till förvalen.</translation> </message> <message> <source>&amp;Reset Options</source> <translation>&amp;Återställ alternativ</translation> </message> <message> <source>&amp;Network</source> <translation>&amp;Nätverk</translation> </message> <message> <source>(0 = auto, &lt;0 = leave that many cores free)</source> <translation>(0 = auto, &lt;0 = lämna så många kärnor lediga)</translation> </message> <message> <source>W&amp;allet</source> <translation>&amp;Plånbok</translation> </message> <message> <source>Expert</source> <translation>Expert</translation> </message> <message> <source>Enable coin &amp;control features</source> <translation>Aktivera mynt&amp;kontrollfunktioner</translation> </message> <message> <source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source> <translation>Om du avaktiverar betalning med obekräftad växel, kan inte växeln från en transaktion användas förrän den transaktionen har minst en bekräftelse.</translation> </message> <message> <source>&amp;Spend unconfirmed change</source> <translation>&amp;Spendera obekräftad växel</translation> </message> <message> <source>Automatically open the Mincoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Öppna automatiskt Mincoin-klientens port på routern. Detta fungerar endast om din router har UPnP aktiverat.</translation> </message> <message> <source>Map port using &amp;UPnP</source> <translation>Tilldela port med hjälp av &amp;UPnP</translation> </message> <message> <source>Connect to the Mincoin network through a SOCKS5 proxy.</source> <translation>Anslut till Mincoin-nätverket genom en SOCKS5-proxy.</translation> </message> <message> <source>&amp;Connect through SOCKS5 proxy (default proxy):</source> <translation>&amp;Anslut genom SOCKS5-proxy (förvald proxy):</translation> </message> <message> <source>Proxy &amp;IP:</source> <translation>Proxy-&amp;IP: </translation> </message> <message> <source>&amp;Port:</source> <translation>&amp;Port: </translation> </message> <message> <source>Port of the proxy (e.g. 9050)</source> <translation>Proxyns port (t.ex. 9050)</translation> </message> <message> <source>Used for reaching peers via:</source> <translation>Används för att nå noder via:</translation> </message> <message> <source>Shows, if the supplied default SOCKS5 proxy is used to reach peers via this network type.</source> <translation>Visas, om den angivna standard-SOCKS5-proxyn används för att nå noder via den här nätverkstypen.</translation> </message> <message> <source>IPv4</source> <translation>IPv4</translation> </message> <message> <source>IPv6</source> <translation>IPv6</translation> </message> <message> <source>Tor</source> <translation>Tor</translation> </message> <message> <source>Connect to the Mincoin network through a separate SOCKS5 proxy for Tor hidden services.</source> <translation>Anslut till Mincoin-nätverket genom en separat SOCKS5-proxy för dolda tjänster i Tor.</translation> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services:</source> <translation>Använd separat SOCKS5-proxy för att nå noder via dolda tjänster i Tor:</translation> </message> <message> <source>&amp;Window</source> <translation>&amp;Fönster</translation> </message> <message> <source>&amp;Hide the icon from the system tray.</source> <translation>&amp;Göm ikonen från systemfältet.</translation> </message> <message> <source>Hide tray icon</source> <translation>Göm systemfältsikonen</translation> </message> <message> <source>Show only a tray icon after minimizing the window.</source> <translation>Visa endast en systemfältsikon vid minimering.</translation> </message> <message> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimera till systemfältet istället för aktivitetsfältet</translation> </message> <message> <source>M&amp;inimize on close</source> <translation>M&amp;inimera vid stängning</translation> </message> <message> <source>&amp;Display</source> <translation>&amp;Visa</translation> </message> <message> <source>User Interface &amp;language:</source> <translation>Användargränssnittets &amp;språk: </translation> </message> <message> <source>The user interface language can be set here. This setting will take effect after restarting %1.</source> <translation>Användargränssnittets språk kan ställas in här. Denna inställning träder i kraft efter en omstart av %1.</translation> </message> <message> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Måttenhet att visa belopp i: </translation> </message> <message> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Välj en måttenhet att visa i gränssnittet och när du skickar mynt.</translation> </message> <message> <source>Whether to show coin control features or not.</source> <translation>Om myntkontrollfunktioner skall visas eller inte</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Avbryt</translation> </message> <message> <source>default</source> <translation>standard</translation> </message> <message> <source>none</source> <translation>ingen</translation> </message> <message> <source>Confirm options reset</source> <translation>Bekräfta att alternativen ska återställs</translation> </message> <message> <source>Client restart required to activate changes.</source> <translation>Klientomstart är nödvändig för att aktivera ändringarna.</translation> </message> <message> <source>Client will be shut down. Do you want to proceed?</source> <translation>Programmet kommer att stängas. Vill du fortsätta?</translation> </message> <message> <source>This change would require a client restart.</source> <translation>Denna ändring kräver en klientomstart.</translation> </message> <message> <source>The supplied proxy address is invalid.</source> <translation>Den angivna proxy-adressen är ogiltig.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formulär</translation> </message> <message> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Mincoin network after a connection is established, but this process has not completed yet.</source> <translation>Den visade informationen kan vara inaktuell. Plånboken synkroniseras automatiskt med Mincoin-nätverket efter att anslutningen är upprättad, men denna process har inte slutförts ännu.</translation> </message> <message> <source>Watch-only:</source> <translation>Granska-bara:</translation> </message> <message> <source>Available:</source> <translation>Tillgängligt:</translation> </message> <message> <source>Your current spendable balance</source> <translation>Ditt tillgängliga saldo</translation> </message> <message> <source>Pending:</source> <translation>Pågående:</translation> </message> <message> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation>Totalt antal transaktioner som ännu inte bekräftats, och som ännu inte räknas med i aktuellt saldo</translation> </message> <message> <source>Immature:</source> <translation>Omogen:</translation> </message> <message> <source>Mined balance that has not yet matured</source> <translation>Den genererade balansen som ännu inte har mognat</translation> </message> <message> <source>Balances</source> <translation>Balanser</translation> </message> <message> <source>Total:</source> <translation>Totalt:</translation> </message> <message> <source>Your current total balance</source> <translation>Ditt nuvarande totala saldo</translation> </message> <message> <source>Your current balance in watch-only addresses</source> <translation>Ditt nuvarande saldo i granska-bara adresser</translation> </message> <message> <source>Spendable:</source> <translation>Spenderbar:</translation> </message> <message> <source>Recent transactions</source> <translation>Nyligen genomförda transaktioner</translation> </message> <message> <source>Unconfirmed transactions to watch-only addresses</source> <translation>Okonfirmerade transaktioner till granska-bara adresser</translation> </message> <message> <source>Mined balance in watch-only addresses that has not yet matured</source> <translation>Den genererade balansen i granska-bara adresser som ännu inte har mognat</translation> </message> <message> <source>Current total balance in watch-only addresses</source> <translation>Nuvarande total balans i granska-bara adresser</translation> </message> </context> <context> <name>PaymentServer</name> <message> <source>URI handling</source> <translation>URI-hantering</translation> </message> <message> <source>Refund from %1</source> <translation>Återbetalning från %1</translation> </message> <message> <source>Bad response from server %1</source> <translation>Felaktigt svar från server %1</translation> </message> </context> <context> <name>PeerTableModel</name> <message> <source>User Agent</source> <translation>Användaragent</translation> </message> <message> <source>Node/Service</source> <translation>Nod/Tjänst</translation> </message> <message> <source>Ping</source> <translation>Ping</translation> </message> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Mängd</translation> </message> <message> <source>Enter a Mincoin address (e.g. %1)</source> <translation>Ange en Mincoin-adress (t.ex. %1)</translation> </message> <message> <source>%1 d</source> <translation>%1 d</translation> </message> <message> <source>%1 h</source> <translation>%1 h</translation> </message> <message> <source>%1 m</source> <translation>%1 m</translation> </message> <message> <source>%1 s</source> <translation>%1 s</translation> </message> <message> <source>None</source> <translation>Ingen</translation> </message> <message> <source>N/A</source> <translation>ej tillgänglig</translation> </message> <message> <source>%1 ms</source> <translation>%1 ms</translation> </message> <message numerus="yes"> <source>%n second(s)</source> <translation><numerusform>%n sekund</numerusform><numerusform>%n sekunder</numerusform></translation> </message> <message numerus="yes"> <source>%n minute(s)</source> <translation><numerusform>%n minut</numerusform><numerusform>%n minuter</numerusform></translation> </message> <message numerus="yes"> <source>%n hour(s)</source> <translation><numerusform>%n timme</numerusform><numerusform>%n timmar</numerusform></translation> </message> <message numerus="yes"> <source>%n day(s)</source> <translation><numerusform>%n dag</numerusform><numerusform>%n dagar</numerusform></translation> </message> <message numerus="yes"> <source>%n week(s)</source> <translation><numerusform>%n vecka</numerusform><numerusform>%n veckor</numerusform></translation> </message> <message> <source>%1 and %2</source> <translation>%1 och %2</translation> </message> <message numerus="yes"> <source>%n year(s)</source> <translation><numerusform>%n år</numerusform><numerusform>%n år</numerusform></translation> </message> </context> <context> <name>QObject::QObject</name> <message> <source>Error: %1</source> <translation>Fel: %1</translation> </message> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>N/A</source> <translation>ej tillgänglig</translation> </message> <message> <source>Client version</source> <translation>Klient-version</translation> </message> <message> <source>&amp;Information</source> <translation>&amp;Information</translation> </message> <message> <source>Debug window</source> <translation>Debug fönster</translation> </message> <message> <source>General</source> <translation>Generell</translation> </message> <message> <source>Using BerkeleyDB version</source> <translation>Använder BerkeleyDB versionen</translation> </message> <message> <source>Datadir</source> <translation>Datakatalog</translation> </message> <message> <source>Startup time</source> <translation>Uppstartstid</translation> </message> <message> <source>Network</source> <translation>Nätverk</translation> </message> <message> <source>Name</source> <translation>Namn</translation> </message> <message> <source>Number of connections</source> <translation>Antalet anslutningar</translation> </message> <message> <source>Block chain</source> <translation>Blockkedja</translation> </message> <message> <source>Current number of blocks</source> <translation>Aktuellt antal block</translation> </message> <message> <source>Memory Pool</source> <translation>Minnespool</translation> </message> <message> <source>Current number of transactions</source> <translation>Nuvarande antal transaktioner</translation> </message> <message> <source>Memory usage</source> <translation>Minnesåtgång</translation> </message> <message> <source>Received</source> <translation>Mottagen</translation> </message> <message> <source>Sent</source> <translation>Skickad</translation> </message> <message> <source>&amp;Peers</source> <translation>&amp;Klienter</translation> </message> <message> <source>Banned peers</source> <translation>Bannade noder</translation> </message> <message> <source>Select a peer to view detailed information.</source> <translation>Välj en klient för att se detaljerad information.</translation> </message> <message> <source>Whitelisted</source> <translation>Vitlistad</translation> </message> <message> <source>Direction</source> <translation>Riktning</translation> </message> <message> <source>Version</source> <translation>Version</translation> </message> <message> <source>Starting Block</source> <translation>Startblock</translation> </message> <message> <source>Synced Headers</source> <translation>Synkade huvuden</translation> </message> <message> <source>Synced Blocks</source> <translation>Synkade block</translation> </message> <message> <source>User Agent</source> <translation>Användaragent</translation> </message> <message> <source>Open the %1 debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Öppna %1 debug-loggfilen från aktuell datakatalog. Detta kan ta några sekunder för stora loggfiler.</translation> </message> <message> <source>Decrease font size</source> <translation>Minska fontstorleken</translation> </message> <message> <source>Increase font size</source> <translation>Öka fontstorleken</translation> </message> <message> <source>Services</source> <translation>Tjänster</translation> </message> <message> <source>Ban Score</source> <translation>Banpoäng</translation> </message> <message> <source>Connection Time</source> <translation>Anslutningstid</translation> </message> <message> <source>Last Send</source> <translation>Senast sänt</translation> </message> <message> <source>Last Receive</source> <translation>Senast mottagen</translation> </message> <message> <source>Ping Time</source> <translation>Pingtid</translation> </message> <message> <source>The duration of a currently outstanding ping.</source> <translation>Tidsåtgången för en nuvarande utestående ping.</translation> </message> <message> <source>Ping Wait</source> <translation>Pingväntetid</translation> </message> <message> <source>Time Offset</source> <translation>Tidsförskjutning</translation> </message> <message> <source>Last block time</source> <translation>Sista blocktid</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Öppna</translation> </message> <message> <source>&amp;Console</source> <translation>&amp;Konsol</translation> </message> <message> <source>&amp;Network Traffic</source> <translation>&amp;Nätverkstrafik</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;Rensa</translation> </message> <message> <source>Totals</source> <translation>Totalt:</translation> </message> <message> <source>In:</source> <translation>In:</translation> </message> <message> <source>Out:</source> <translation>Ut:</translation> </message> <message> <source>Debug log file</source> <translation>Debugloggfil</translation> </message> <message> <source>Clear console</source> <translation>Rensa konsollen</translation> </message> <message> <source>1 &amp;hour</source> <translation>1 &amp;timme</translation> </message> <message> <source>1 &amp;day</source> <translation>1 &amp;dag</translation> </message> <message> <source>1 &amp;week</source> <translation>1 &amp;vecka</translation> </message> <message> <source>1 &amp;year</source> <translation>1 &amp;år</translation> </message> <message> <source>Welcome to the %1 RPC console.</source> <translation>Välkommen till %1 RPC-konsolen.</translation> </message> <message> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Använd upp- och ner-pilarna för att navigera i historiken, och &lt;b&gt;Ctrl-L&lt;/b&gt; för att rensa skärmen.</translation> </message> <message> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Skriv &lt;b&gt;help&lt;/b&gt; för en översikt av alla kommandon.</translation> </message> <message> <source>%1 B</source> <translation>%1 B</translation> </message> <message> <source>%1 KB</source> <translation>%1 KB</translation> </message> <message> <source>%1 MB</source> <translation>%1 MB</translation> </message> <message> <source>%1 GB</source> <translation>%1 GB</translation> </message> <message> <source>(node id: %1)</source> <translation>(nod-id: %1)</translation> </message> <message> <source>via %1</source> <translation>via %1</translation> </message> <message> <source>never</source> <translation>aldrig</translation> </message> <message> <source>Inbound</source> <translation>Inkommande</translation> </message> <message> <source>Outbound</source> <translation>Utgående</translation> </message> <message> <source>Yes</source> <translation>Ja</translation> </message> <message> <source>No</source> <translation>Nej</translation> </message> <message> <source>Unknown</source> <translation>Okänd</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>&amp;Belopp:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etikett:</translation> </message> <message> <source>&amp;Message:</source> <translation>&amp;Meddelande:</translation> </message> <message> <source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source> <translation>Återanvänd en av tidigare använda mottagningsadresser. Återanvändning av adresser har både säkerhets och integritetsbrister. Använd inte samma mottagningsadress om du inte gör om samma betalningsbegäran.</translation> </message> <message> <source>R&amp;euse an existing receiving address (not recommended)</source> <translation>Åt&amp;eranvänd en existerande mottagningsadress (rekommenderas inte)</translation> </message> <message> <source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Mincoin network.</source> <translation>Ett frivilligt meddelande att bifoga betalningsbegäran, vilket visas när begäran öppnas. NB: Meddelandet kommer inte att sändas med betalningen över Mincoinnätverket.</translation> </message> <message> <source>An optional label to associate with the new receiving address.</source> <translation>En frivillig etikett att associera med den nya mottagningsadressen.</translation> </message> <message> <source>Use this form to request payments. All fields are &lt;b&gt;optional&lt;/b&gt;.</source> <translation>Använd detta formulär för att begära betalningar. Alla fält är &lt;b&gt;frivilliga&lt;/b&gt;.</translation> </message> <message> <source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source> <translation>En valfri summa att begära. Lämna denna tom eller noll för att inte begära en specifik summa.</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Rensa alla formulärfälten</translation> </message> <message> <source>Clear</source> <translation>Rensa</translation> </message> <message> <source>Requested payments history</source> <translation>Historik för begärda betalningar</translation> </message> <message> <source>&amp;Request payment</source> <translation>Begä&amp;r betalning</translation> </message> <message> <source>Show the selected request (does the same as double clicking an entry)</source> <translation>Visa valda begäranden (gör samma som att dubbelklicka på en post)</translation> </message> <message> <source>Show</source> <translation>Visa</translation> </message> <message> <source>Remove the selected entries from the list</source> <translation>Ta bort valda poster från listan</translation> </message> <message> <source>Remove</source> <translation>Ta bort</translation> </message> <message> <source>Copy URI</source> <translation>Kopiera URI</translation> </message> <message> <source>Copy label</source> <translation>Kopiera etikett</translation> </message> <message> <source>Copy message</source> <translation>Kopiera meddelande</translation> </message> <message> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>QR Code</source> <translation>QR-kod</translation> </message> <message> <source>Copy &amp;URI</source> <translation>Kopiera &amp;URI</translation> </message> <message> <source>Copy &amp;Address</source> <translation>Kopiera &amp;Adress</translation> </message> <message> <source>&amp;Save Image...</source> <translation>&amp;Spara Bild...</translation> </message> <message> <source>Payment information</source> <translation>Betalinformaton</translation> </message> <message> <source>URI</source> <translation>URI</translation> </message> <message> <source>Address</source> <translation>Adress</translation> </message> <message> <source>Label</source> <translation>Etikett</translation> </message> <message> <source>Message</source> <translation>Meddelande</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Label</source> <translation>Etikett</translation> </message> <message> <source>Message</source> <translation>Meddelande</translation> </message> <message> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> <message> <source>(no message)</source> <translation>(inget meddelande)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Skicka pengar</translation> </message> <message> <source>Coin Control Features</source> <translation>Myntkontrollfunktioner</translation> </message> <message> <source>Inputs...</source> <translation>Inmatningar...</translation> </message> <message> <source>automatically selected</source> <translation>automatiskt vald</translation> </message> <message> <source>Insufficient funds!</source> <translation>Otillräckliga medel!</translation> </message> <message> <source>Quantity:</source> <translation>Kvantitet:</translation> </message> <message> <source>Bytes:</source> <translation>Antal Byte:</translation> </message> <message> <source>Amount:</source> <translation>Belopp:</translation> </message> <message> <source>Fee:</source> <translation>Avgift:</translation> </message> <message> <source>After Fee:</source> <translation>Efter avgift:</translation> </message> <message> <source>Change:</source> <translation>Växel:</translation> </message> <message> <source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source> <translation>Om denna är aktiverad men växeladressen är tom eller felaktig kommer växeln att sändas till en nygenererad adress.</translation> </message> <message> <source>Custom change address</source> <translation>Specialväxeladress</translation> </message> <message> <source>Transaction Fee:</source> <translation>Transaktionsavgift:</translation> </message> <message> <source>Choose...</source> <translation>Välj...</translation> </message> <message> <source>collapse fee-settings</source> <translation>Fäll ihop avgiftsinställningarna</translation> </message> <message> <source>per kilobyte</source> <translation>per kilobyte</translation> </message> <message> <source>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "total at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</source> <translation>Om den anpassad avgiften är satt till 1000 satoshi och transaktionen bara är 250 byte, betalar "per kilobyte" bara 250 satoshi i avgift, medans "totalt minst" betalar 1000 satoshi. För transaktioner större än en kilobyte betalar både per kilobyte.</translation> </message> <message> <source>Hide</source> <translation>Göm</translation> </message> <message> <source>total at least</source> <translation>totalt minst</translation> </message> <message> <source>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for mincoin transactions than the network can process.</source> <translation>Att betala endast den minsta avgiften är bara bra så länge det är mindre transaktionsvolym än utrymme i blocken. Men tänk på att det kan hamna i en aldrig bekräftar transaktion när det finns mer efterfrågan på mincoin transaktioner än nätverket kan bearbeta.</translation> </message> <message> <source>(read the tooltip)</source> <translation>(läs verktygstips)</translation> </message> <message> <source>Recommended:</source> <translation>Rekommenderad:</translation> </message> <message> <source>Custom:</source> <translation>Anpassad:</translation> </message> <message> <source>(Smart fee not initialized yet. This usually takes a few blocks...)</source> <translation>(Smartavgiften är inte initierad än. Detta tar vanligen några block...)</translation> </message> <message> <source>normal</source> <translation>normal</translation> </message> <message> <source>fast</source> <translation>snabb</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Skicka till flera mottagare samtidigt</translation> </message> <message> <source>Add &amp;Recipient</source> <translation>Lägg till &amp;mottagare</translation> </message> <message> <source>Clear all fields of the form.</source> <translation>Rensa alla formulärfälten</translation> </message> <message> <source>Dust:</source> <translation>Damm:</translation> </message> <message> <source>Clear &amp;All</source> <translation>Rensa &amp;alla</translation> </message> <message> <source>Balance:</source> <translation>Balans:</translation> </message> <message> <source>Confirm the send action</source> <translation>Bekräfta sändordern</translation> </message> <message> <source>S&amp;end</source> <translation>&amp;Skicka</translation> </message> <message> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> <message> <source>%1 to %2</source> <translation>%1 till %2</translation> </message> <message> <source>or</source> <translation>eller</translation> </message> <message numerus="yes"> <source>%n block(s)</source> <translation><numerusform>%n block</numerusform><numerusform>%n block</numerusform></translation> </message> <message> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>&amp;Belopp:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Betala &amp;Till:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etikett:</translation> </message> <message> <source>Choose previously used address</source> <translation>Välj tidigare använda adresser</translation> </message> <message> <source>This is a normal payment.</source> <translation>Detta är en normal betalning.</translation> </message> <message> <source>The Mincoin address to send the payment to</source> <translation>Mincoinadress att sända betalning till</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Klistra in adress från Urklipp</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Remove this entry</source> <translation>Radera denna post</translation> </message> <message> <source>The fee will be deducted from the amount being sent. The recipient will receive less mincoins than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</source> <translation>Avgiften dras från beloppet som skickas. Mottagaren kommer att få mindre mincoins än du angivit i belopp-fältet. Om flera mottagare valts kommer avgiften delas jämt.</translation> </message> <message> <source>S&amp;ubtract fee from amount</source> <translation>S&amp;ubtrahera avgiften från beloppet</translation> </message> <message> <source>Message:</source> <translation>Meddelande:</translation> </message> <message> <source>This is an unauthenticated payment request.</source> <translation>Detta är en oautentiserad betalningsbegäran.</translation> </message> <message> <source>This is an authenticated payment request.</source> <translation>Detta är en autentiserad betalningsbegäran.</translation> </message> <message> <source>Enter a label for this address to add it to the list of used addresses</source> <translation>Ange en etikett för denna adress att adderas till listan över använda adresser</translation> </message> <message> <source>A message that was attached to the mincoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Mincoin network.</source> <translation>Ett meddelande som bifogades mincoin-URI, vilket lagras med transaktionen som referens. NB: Meddelandet kommer inte att sändas över Mincoinnätverket.</translation> </message> <message> <source>Pay To:</source> <translation>Betala Till:</translation> </message> <message> <source>Memo:</source> <translation>PM:</translation> </message> </context> <context> <name>SendConfirmationDialog</name> <message> <source>Yes</source> <translation>Ja</translation> </message> </context> <context> <name>ShutdownWindow</name> <message> <source>%1 is shutting down...</source> <translation>%1 stängs av...</translation> </message> <message> <source>Do not shut down the computer until this window disappears.</source> <translation>Stäng inte av datorn förrän denna ruta försvinner.</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Signatures - Sign / Verify a Message</source> <translation>Signaturer - Signera / Verifiera ett Meddelande</translation> </message> <message> <source>&amp;Sign Message</source> <translation>&amp;Signera Meddelande</translation> </message> <message> <source>You can sign messages/agreements with your addresses to prove you can receive mincoins sent to them. Be careful not to sign anything vague or random, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Du kan underteckna meddelanden/avtal med dina adresser för att bevisa att du kan ta emot mincoins som skickats till dem. Var försiktig så du inte undertecknar något oklart eller konstigt, eftersom phishing-angrepp kan försöka få dig att underteckna din identitet till dem. Underteckna endast väldetaljerade meddelanden som du godkänner.</translation> </message> <message> <source>The Mincoin address to sign the message with</source> <translation>Mincoinadress att signera meddelandet med</translation> </message> <message> <source>Choose previously used address</source> <translation>Välj tidigare använda adresser</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Klistra in adress från Urklipp</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Enter the message you want to sign here</source> <translation>Skriv in meddelandet du vill signera här</translation> </message> <message> <source>Signature</source> <translation>Signatur</translation> </message> <message> <source>Copy the current signature to the system clipboard</source> <translation>Kopiera signaturen till systemets Urklipp</translation> </message> <message> <source>Sign the message to prove you own this Mincoin address</source> <translation>Signera meddelandet för att bevisa att du äger denna adress</translation> </message> <message> <source>Sign &amp;Message</source> <translation>Signera &amp;Meddelande</translation> </message> <message> <source>Reset all sign message fields</source> <translation>Rensa alla fält</translation> </message> <message> <source>Clear &amp;All</source> <translation>Rensa &amp;alla</translation> </message> <message> <source>&amp;Verify Message</source> <translation>&amp;Verifiera Meddelande</translation> </message> <message> <source>Enter the receiver's address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</source> <translation>Ange mottagarens adress, meddelande (kopiera radbrytningar, mellanrum, flikar, etc. exakt) och signatur nedan för att verifiera meddelandet. Undvik att läsa in mera information i signaturen än vad som stod i själva undertecknade meddelandet, för att undvika ett man-in-the-middle-angrepp. Notera att detta endast bevisar att undertecknad tar emot med adressen, det bevisar inte vem som skickat transaktionen!</translation> </message> <message> <source>The Mincoin address the message was signed with</source> <translation>Mincoinadressen som meddelandet signerades med</translation> </message> <message> <source>Verify the message to ensure it was signed with the specified Mincoin address</source> <translation>Verifiera meddelandet för att vara säker på att den var signerad med den angivna Mincoin-adressen</translation> </message> <message> <source>Verify &amp;Message</source> <translation>Verifiera &amp;Meddelande</translation> </message> <message> <source>Reset all verify message fields</source> <translation>Rensa alla fält</translation> </message> <message> <source>Message signed.</source> <translation>Meddelande signerat.</translation> </message> <message> <source>The signature could not be decoded.</source> <translation>Signaturen kunde inte avkodas.</translation> </message> <message> <source>Message verified.</source> <translation>Meddelande verifierat.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <source>KB/s</source> <translation>KB/s</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <source>Status</source> <translation>Status</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Message</source> <translation>Meddelande</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Den här panelen visar en detaljerad beskrivning av transaktionen</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Label</source> <translation>Etikett</translation> </message> <message> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>Enter address or label to search</source> <translation>Ange en adress eller etikett att söka efter</translation> </message> <message> <source>Min amount</source> <translation>Minsta belopp</translation> </message> <message> <source>Abandon transaction</source> <translation>Avbryt transaktionen</translation> </message> <message> <source>Copy address</source> <translation>Kopiera adress</translation> </message> <message> <source>Copy label</source> <translation>Kopiera etikett</translation> </message> <message> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> <message> <source>Copy transaction ID</source> <translation>Kopiera transaktions-ID</translation> </message> <message> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> <message> <source>Label</source> <translation>Etikett</translation> </message> <message> <source>Address</source> <translation>Adress</translation> </message> <message> <source>Exporting Failed</source> <translation>Export misslyckades</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> <message> <source>Unit to show amounts in. Click to select another unit.</source> <translation>&amp;Enhet att visa belopp i. Klicka för att välja annan enhet.</translation> </message> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> </context> <context> <name>bitcoin-core</name> <message> <source>Options:</source> <translation>Inställningar:</translation> </message> <message> <source>Specify data directory</source> <translation>Ange katalog för data</translation> </message> <message> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Anslut till en nod för att hämta klientadresser, och koppla från</translation> </message> <message> <source>Specify your own public address</source> <translation>Ange din egen publika adress</translation> </message> <message> <source>Accept command line and JSON-RPC commands</source> <translation>Tillåt kommandon från kommandotolken och JSON-RPC-kommandon</translation> </message> <message> <source>If &lt;category&gt; is not supplied or if &lt;category&gt; = 1, output all debugging information.</source> <translation>Om &lt;kategori&gt; inte anges eller om &lt;category&gt; = 1, visa all avlusningsinformation.</translation> </message> <message> <source>Prune configured below the minimum of %d MiB. Please use a higher number.</source> <translation>Beskärning konfigurerad under miniminivån %d MiB. Vänligen använd ett högre värde.</translation> </message> <message> <source>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</source> <translation>Beskärning: sista plånbokssynkroniseringen ligger utanför beskuren data. Du måste använda -reindex (ladda ner hela blockkedjan igen eftersom noden beskurits)</translation> </message> <message> <source>Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.</source> <translation>Omskanningar kan inte göras i beskuret läge. Du måste använda -reindex vilket kommer ladda ner hela blockkedjan igen.</translation> </message> <message> <source>Error: A fatal internal error occurred, see debug.log for details</source> <translation>Fel: Ett kritiskt internt fel uppstod, se debug.log för detaljer</translation> </message> <message> <source>Fee (in %s/kB) to add to transactions you send (default: %s)</source> <translation>Avgift (i %s/kB) att lägga till på transaktioner du skickar (förvalt: %s)</translation> </message> <message> <source>Pruning blockstore...</source> <translation>Rensar blockstore...</translation> </message> <message> <source>Run in the background as a daemon and accept commands</source> <translation>Kör i bakgrunden som tjänst och acceptera kommandon</translation> </message> <message> <source>Unable to start HTTP server. See debug log for details.</source> <translation>Kunde inte starta HTTP-server. Se avlusningsloggen för detaljer.</translation> </message> <message> <source>Mincoin Core</source> <translation>Mincoin Core</translation> </message> <message> <source>The %s developers</source> <translation>%s-utvecklarna</translation> </message> <message> <source>A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)</source> <translation>En avgiftskurs (i %s/kB) som används när det inte finns tillräcklig data för att uppskatta avgiften (förvalt: %s)</translation> </message> <message> <source>Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)</source> <translation>Acceptera vidarebefodrade transaktioner från vitlistade noder även när transaktioner inte vidarebefodras (förvalt: %d)</translation> </message> <message> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Bind till given adress och lyssna alltid på den. Använd [värd]:port notation för IPv6</translation> </message> <message> <source>Cannot obtain a lock on data directory %s. %s is probably already running.</source> <translation>Kan inte låsa data-mappen %s. %s körs förmodligen redan.</translation> </message> <message> <source>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</source> <translation>Ta bort alla plånbokstransaktioner och återskapa bara dom som är en del av blockkedjan genom att ange -rescan vid uppstart</translation> </message> <message> <source>Error loading %s: You can't enable HD on a already existing non-HD wallet</source> <translation>Fel vid laddning av %s: Du kan inte aktivera HD på en existerande icke-HD plånbok</translation> </message> <message> <source>Error reading %s! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Fel vid läsning av %s! Alla nycklar lästes korrekt, men transaktionsdatat eller adressbokens poster kanske saknas eller är felaktiga.</translation> </message> <message> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Exekvera kommando när en plånbokstransaktion ändras (%s i cmd är ersatt av TxID)</translation> </message> <message> <source>Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)</source> <translation>Maximalt tillåten median-peer tidsoffset justering. Lokalt perspektiv av tiden kan bli påverkad av partners, framåt eller bakåt denna tidsrymd. (förvalt: %u sekunder)</translation> </message> <message> <source>Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)</source> <translation>Maximal total avgift (i %s) att använda i en plånbokstransaktion eller råa transaktioner. Sätts denna för lågt kan stora transaktioner avbrytas (förvalt: %s)</translation> </message> <message> <source>Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.</source> <translation>Vänligen kolla så att din dators datum och tid är korrekt! Om din klocka går fel kommer %s inte att fungera korrekt.</translation> </message> <message> <source>Please contribute if you find %s useful. Visit %s for further information about the software.</source> <translation>Var snäll och bidra om du finner %s användbar. Besök %s för mer information om mjukvaran.</translation> </message> <message> <source>Set the number of script verification threads (%u to %d, 0 = auto, &lt;0 = leave that many cores free, default: %d)</source> <translation>Ange antalet skriptkontrolltrådar (%u till %d, 0 = auto, &lt;0 = lämna så många kärnor lediga, förval: %d)</translation> </message> <message> <source>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</source> <translation>Blockdatabasen innehåller ett block som verkar vara från framtiden. Detta kan vara på grund av att din dators datum och tid är felaktiga. Bygg bara om blockdatabasen om du är säker på att datorns datum och tid är korrekt</translation> </message> <message> <source>Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain</source> <translation>Kan inte spola tillbaka databasen till obeskärt läge. Du måste ladda ner blockkedjan igen</translation> </message> <message> <source>Use UPnP to map the listening port (default: 1 when listening and no -proxy)</source> <translation>Använd UPnP för att mappa den lyssnande porten (förvalt: 1 när lyssning aktiverat och utan -proxy)</translation> </message> <message> <source>You need to rebuild the database using -reindex-chainstate to change -txindex</source> <translation>Du måste återskapa databasen med -reindex-chainstate för att ändra -txindex</translation> </message> <message> <source>%s corrupt, salvage failed</source> <translation>%s är korrupt, räddning misslyckades</translation> </message> <message> <source>-maxmempool must be at least %d MB</source> <translation>-maxmempool måste vara minst %d MB</translation> </message> <message> <source>&lt;category&gt; can be:</source> <translation>&lt;category&gt; Kan vara:</translation> </message> <message> <source>Append comment to the user agent string</source> <translation>Lägg till kommentar till user-agent-strängen</translation> </message> <message> <source>Attempt to recover private keys from a corrupt wallet on startup</source> <translation>Försök att rädda privata nycklar från en korrupt plånbok vid uppstart</translation> </message> <message> <source>Block creation options:</source> <translation>Block skapande inställningar:</translation> </message> <message> <source>Cannot resolve -%s address: '%s'</source> <translation>Kan inte matcha -%s adress: '%s'</translation> </message> <message> <source>Change index out of range</source> <translation>Förändringsindexet utom räckhåll</translation> </message> <message> <source>Connection options:</source> <translation>Anslutningsalternativ:</translation> </message> <message> <source>Copyright (C) %i-%i</source> <translation>Copyright (C) %i-%i</translation> </message> <message> <source>Corrupted block database detected</source> <translation>Korrupt blockdatabas har upptäckts</translation> </message> <message> <source>Debugging/Testing options:</source> <translation>Avlusnings/Test-alternativ:</translation> </message> <message> <source>Do not load the wallet and disable wallet RPC calls</source> <translation>Ladda inte plånboken och stäng av RPC-anrop till plånboken</translation> </message> <message> <source>Do you want to rebuild the block database now?</source> <translation>Vill du bygga om blockdatabasen nu?</translation> </message> <message> <source>Enable publish hash block in &lt;address&gt;</source> <translation>Aktivera publicering av hashblock i &lt;adress&gt;</translation> </message> <message> <source>Enable publish hash transaction in &lt;address&gt;</source> <translation>Aktivera publicering av hashtransaktion i &lt;adress&gt;</translation> </message> <message> <source>Enable publish raw block in &lt;address&gt;</source> <translation>Aktivera publicering av råa block i &lt;adress&gt;</translation> </message> <message> <source>Enable publish raw transaction in &lt;address&gt;</source> <translation>Aktivera publicering av råa transaktioner i &lt;adress&gt;</translation> </message> <message> <source>Enable transaction replacement in the memory pool (default: %u)</source> <translation>Aktivera byte av transaktioner i minnespoolen (förvalt: %u)</translation> </message> <message> <source>Error initializing block database</source> <translation>Fel vid initiering av blockdatabasen</translation> </message> <message> <source>Error initializing wallet database environment %s!</source> <translation>Fel vid initiering av plånbokens databasmiljö %s!</translation> </message> <message> <source>Error loading %s</source> <translation>Fel vid inläsning av %s</translation> </message> <message> <source>Error loading %s: Wallet corrupted</source> <translation>Fel vid inläsningen av %s: Plånboken är koruppt</translation> </message> <message> <source>Error loading %s: Wallet requires newer version of %s</source> <translation>Fel vid inläsningen av %s: Plånboken kräver en senare version av %s</translation> </message> <message> <source>Error loading %s: You can't disable HD on a already existing HD wallet</source> <translation>Fel vid laddning av %s: Du kan inte avaktivera HD på en redan existerande HD plånbok</translation> </message> <message> <source>Error loading block database</source> <translation>Fel vid inläsning av blockdatabasen</translation> </message> <message> <source>Error opening block database</source> <translation>Fel vid öppning av blockdatabasen</translation> </message> <message> <source>Error: Disk space is low!</source> <translation>Fel: Hårddiskutrymme är lågt!</translation> </message> <message> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Misslyckades att lyssna på någon port. Använd -listen=0 om du vill detta.</translation> </message> <message> <source>Importing...</source> <translation>Importerar...</translation> </message> <message> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation>Felaktig eller inget genesisblock hittades. Fel datadir för nätverket?</translation> </message> <message> <source>Initialization sanity check failed. %s is shutting down.</source> <translation>Initieringschecken fallerade. %s stängs av.</translation> </message> <message> <source>Invalid -onion address: '%s'</source> <translation>Ogiltig -onion adress:'%s'</translation> </message> <message> <source>Invalid amount for -%s=&lt;amount&gt;: '%s'</source> <translation>Ogiltigt belopp för -%s=&lt;belopp&gt;:'%s'</translation> </message> <message> <source>Invalid amount for -fallbackfee=&lt;amount&gt;: '%s'</source> <translation>Ogiltigt belopp för -fallbackfee=&lt;belopp&gt;: '%s'</translation> </message> <message> <source>Keep the transaction memory pool below &lt;n&gt; megabytes (default: %u)</source> <translation>Håll minnespoolen över transaktioner under &lt;n&gt; megabyte (förvalt: %u)</translation> </message> <message> <source>Loading banlist...</source> <translation>Laddar svarta listan...</translation> </message> <message> <source>Location of the auth cookie (default: data dir)</source> <translation>Plats för authcookie (förvalt: datamapp)</translation> </message> <message> <source>Not enough file descriptors available.</source> <translation>Inte tillräckligt med filbeskrivningar tillgängliga.</translation> </message> <message> <source>Only connect to nodes in network &lt;net&gt; (ipv4, ipv6 or onion)</source> <translation>Anslut enbart till noder i nätverket &lt;net&gt; (IPv4, IPv6 eller onion)</translation> </message> <message> <source>Print this help message and exit</source> <translation>Visa denna hjälptext och avsluta</translation> </message> <message> <source>Print version and exit</source> <translation>Visa version och avsluta</translation> </message> <message> <source>Prune cannot be configured with a negative value.</source> <translation>Beskärning kan inte konfigureras med ett negativt värde.</translation> </message> <message> <source>Prune mode is incompatible with -txindex.</source> <translation>Beskärningsläge är inkompatibel med -txindex.</translation> </message> <message> <source>Rebuild chain state and block index from the blk*.dat files on disk</source> <translation>Återskapa blockkedjans status och index från blk*.dat filer på disken</translation> </message> <message> <source>Rebuild chain state from the currently indexed blocks</source> <translation>Återskapa blockkedjans status från aktuella indexerade block</translation> </message> <message> <source>Rewinding blocks...</source> <translation>Spolar tillbaka blocken...</translation> </message> <message> <source>Set database cache size in megabytes (%d to %d, default: %d)</source> <translation>Sätt databasens cachestorlek i megabyte (%d till %d, förvalt: %d)</translation> </message> <message> <source>Set maximum block size in bytes (default: %d)</source> <translation>Sätt maximal blockstorlek i byte (förvalt: %d)</translation> </message> <message> <source>Specify wallet file (within data directory)</source> <translation>Ange plånboksfil (inom datakatalogen)</translation> </message> <message> <source>The source code is available from %s.</source> <translation>Källkoden är tillgänglig från %s.</translation> </message> <message> <source>Unable to bind to %s on this computer. %s is probably already running.</source> <translation>Det går inte att binda till %s på den här datorn. %s är förmodligen redan igång.</translation> </message> <message> <source>Unsupported argument -benchmark ignored, use -debug=bench.</source> <translation>Argumentet -benchmark stöds inte och ignoreras, använd -debug=bench.</translation> </message> <message> <source>Unsupported argument -debugnet ignored, use -debug=net.</source> <translation>Argumentet -debugnet stöds inte och ignoreras, använd -debug=net.</translation> </message> <message> <source>Unsupported argument -tor found, use -onion.</source> <translation>Argumentet -tor hittades men stöds inte, använd -onion.</translation> </message> <message> <source>Use UPnP to map the listening port (default: %u)</source> <translation>Använd UPnP för att mappa den lyssnande porten (förvalt: %u)</translation> </message> <message> <source>User Agent comment (%s) contains unsafe characters.</source> <translation>Kommentaren i användaragent (%s) innehåller osäkra tecken.</translation> </message> <message> <source>Verifying blocks...</source> <translation>Verifierar block...</translation> </message> <message> <source>Verifying wallet...</source> <translation>Verifierar plånboken...</translation> </message> <message> <source>Wallet %s resides outside data directory %s</source> <translation>Plånbok %s ligger utanför datakatalogen %s</translation> </message> <message> <source>Wallet debugging/testing options:</source> <translation>Plånbokens Avlusnings/Testnings optioner:</translation> </message> <message> <source>Wallet needed to be rewritten: restart %s to complete</source> <translation>Plånboken behöver sparas om: Starta om %s för att fullfölja</translation> </message> <message> <source>Wallet options:</source> <translation>Plånboksinställningar:</translation> </message> <message> <source>Allow JSON-RPC connections from specified source. Valid for &lt;ip&gt; are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</source> <translation>Tillåt JSON-RPC-anslutningar från specifik källa. Tillåtna &lt;ip&gt; är enkel IP (t.ex 1.2.3.4), en nätverk/nätmask (t.ex. 1.2.3.4/255.255.255.0) eller ett nätverk/CIDR (t.ex. 1.2.3.4/24). Detta alternativ anges flera gånger</translation> </message> <message> <source>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</source> <translation>Bind till given adress och vitlista klienter som ansluter till den. Använd [värd]:port notation för IPv6</translation> </message> <message> <source>Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)</source> <translation>Bind till angiven adress för att lyssna på JSON-RPC-anslutningar. Använd [värd]:port-format for IPv6. Detta alternativ kan anges flera gånger (förvalt: bind till alla gränssnitt)</translation> </message> <message> <source>Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)</source> <translation>Skapa nya filer med systemets förvalda rättigheter, istället för umask 077 (bara effektivt med avaktiverad plånboks funktionalitet)</translation> </message> <message> <source>Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)</source> <translation>Upptäck egna IP adresser (standard: 1 vid lyssning ingen -externalip eller -proxy)</translation> </message> <message> <source>Error: Listening for incoming connections failed (listen returned error %s)</source> <translation>Fel: Avlyssning av inkommande anslutningar misslyckades (Avlyssningen returnerade felkod %s)</translation> </message> <message> <source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source> <translation>Exekvera kommando när ett relevant meddelande är mottagen eller när vi ser en väldigt lång förgrening (%s i cmd är utbytt med ett meddelande)</translation> </message> <message> <source>Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)</source> <translation>Avgifter (i %s/kB) mindre än detta betraktas som nollavgift för vidarebefordran, mining och transaktionsskapande (förvalt: %s)</translation> </message> <message> <source>If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)</source> <translation>Om paytxfee inte är satt, inkludera tillräcklig avgift så att transaktionen börjar att konfirmeras inom n blocks (förvalt: %u)</translation> </message> <message> <source>Invalid amount for -maxtxfee=&lt;amount&gt;: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</source> <translation>Otillåtet belopp för -maxtxfee=&lt;belopp&gt;: '%s' (måste åtminstånde vara minrelay avgift %s för att förhindra stoppade transkationer)</translation> </message> <message> <source>Maximum size of data in data carrier transactions we relay and mine (default: %u)</source> <translation>Maximal storlek på data i databärartransaktioner som vi reläar och bryter (förvalt: %u) </translation> </message> <message> <source>Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)</source> <translation>Slumpa autentiseringen för varje proxyanslutning. Detta möjliggör Tor ström-isolering (förvalt: %u)</translation> </message> <message> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source> <translation>Sätt den maximala storleken av hög-prioriterade/låg-avgifts transaktioner i byte (förvalt: %d)</translation> </message> <message> <source>The transaction amount is too small to send after the fee has been deducted</source> <translation>Transaktionen är för liten att skicka efter det att avgiften har dragits</translation> </message> <message> <source>Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start</source> <translation>Använd hierarkisk deterministisk nyckel generering (HD) efter BIP32. Har bara effekt under plånbokens skapande/första användning.</translation> </message> <message> <source>Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway</source> <translation>Vitlistade klienter kan inte bli DoS-bannade och deras transaktioner reläas alltid, även om dom redan är i mempoolen, användbart för t.ex en gateway </translation> </message> <message> <source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source> <translation>Du måste bygga om databasen genom att använda -reindex för att återgå till obeskärt läge. Detta kommer att ladda ner hela blockkedjan.</translation> </message> <message> <source>(default: %u)</source> <translation>(förvalt: %u)</translation> </message> <message> <source>Accept public REST requests (default: %u)</source> <translation>Acceptera publika REST förfrågningar (förvalt: %u)</translation> </message> <message> <source>Automatically create Tor hidden service (default: %d)</source> <translation>Skapa automatiskt dold tjänst i Tor (förval: %d)</translation> </message> <message> <source>Connect through SOCKS5 proxy</source> <translation>Anslut genom SOCKS5 proxy</translation> </message> <message> <source>Error reading from database, shutting down.</source> <translation>Fel vid läsning från databas, avslutar.</translation> </message> <message> <source>Imports blocks from external blk000??.dat file on startup</source> <translation>Importera block från extern blk000??.dat-fil vid uppstart</translation> </message> <message> <source>Information</source> <translation>Information</translation> </message> <message> <source>Invalid amount for -paytxfee=&lt;amount&gt;: '%s' (must be at least %s)</source> <translation>Ogiltigt belopp för -paytxfee=&lt;belopp&gt;:'%s' (måste vara minst %s)</translation> </message> <message> <source>Invalid netmask specified in -whitelist: '%s'</source> <translation>Ogiltig nätmask angiven i -whitelist: '%s'</translation> </message> <message> <source>Keep at most &lt;n&gt; unconnectable transactions in memory (default: %u)</source> <translation>Håll som mest &lt;n&gt; oanslutningsbara transaktioner i minnet (förvalt: %u)</translation> </message> <message> <source>Need to specify a port with -whitebind: '%s'</source> <translation>Port måste anges med -whitelist: '%s'</translation> </message> <message> <source>Node relay options:</source> <translation>Nodreläalternativ:</translation> </message> <message> <source>RPC server options:</source> <translation>RPC-serveralternativ:</translation> </message> <message> <source>Reducing -maxconnections from %d to %d, because of system limitations.</source> <translation>Minskar -maxconnections från %d till %d, på grund av systembegränsningar.</translation> </message> <message> <source>Rescan the block chain for missing wallet transactions on startup</source> <translation>Sök i blockkedjan efter saknade plånbokstransaktioner vid uppstart</translation> </message> <message> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Skicka trace-/debuginformation till terminalen istället för till debug.log</translation> </message> <message> <source>Send transactions as zero-fee transactions if possible (default: %u)</source> <translation>Sänd transaktioner som nollavgiftstransaktioner om möjligt (förvalt: %u)</translation> </message> <message> <source>Show all debugging options (usage: --help -help-debug)</source> <translation>Visa alla avlusningsalternativ (använd: --help -help-debug)</translation> </message> <message> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Krymp debug.log filen vid klient start (förvalt: 1 vid ingen -debug)</translation> </message> <message> <source>Signing transaction failed</source> <translation>Signering av transaktion misslyckades</translation> </message> <message> <source>The transaction amount is too small to pay the fee</source> <translation>Transaktionen är för liten för att betala avgiften</translation> </message> <message> <source>This is experimental software.</source> <translation>Detta är experimentmjukvara.</translation> </message> <message> <source>Tor control port password (default: empty)</source> <translation>Lösenord för Tor-kontrollport (förval: inget)</translation> </message> <message> <source>Tor control port to use if onion listening enabled (default: %s)</source> <translation>Tor-kontrollport att använda om onion är aktiverat (förval: %s)</translation> </message> <message> <source>Transaction amount too small</source> <translation>Transaktions belopp för liten</translation> </message> <message> <source>Transaction too large for fee policy</source> <translation>Transaktionen är för stor för avgiftspolicyn</translation> </message> <message> <source>Transaction too large</source> <translation>Transaktionen är för stor</translation> </message> <message> <source>Unable to bind to %s on this computer (bind returned error %s)</source> <translation>Det går inte att binda till %s på den här datorn (bind returnerade felmeddelande %s)</translation> </message> <message> <source>Upgrade wallet to latest format on startup</source> <translation>Uppgradera plånbok till senaste formatet vid uppstart</translation> </message> <message> <source>Username for JSON-RPC connections</source> <translation>Användarnamn för JSON-RPC-anslutningar</translation> </message> <message> <source>Warning</source> <translation>Varning</translation> </message> <message> <source>Warning: unknown new rules activated (versionbit %i)</source> <translation>Varning: okända nya regler aktiverade (versionsbit %i)</translation> </message> <message> <source>Whether to operate in a blocks only mode (default: %u)</source> <translation>Ska allt göras i endast block-läge (förval: %u)</translation> </message> <message> <source>Zapping all transactions from wallet...</source> <translation>Töm plånboken på alla transaktioner...</translation> </message> <message> <source>ZeroMQ notification options:</source> <translation>ZeroMQ-alternativ för notiser:</translation> </message> <message> <source>Password for JSON-RPC connections</source> <translation>Lösenord för JSON-RPC-anslutningar</translation> </message> <message> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Exekvera kommando när det bästa blocket ändras (%s i cmd är utbytt av blockhash)</translation> </message> <message> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Tillåt DNS-sökningar för -addnode, -seednode och -connect</translation> </message> <message> <source>Loading addresses...</source> <translation>Laddar adresser...</translation> </message> <message> <source>(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)</source> <translation>(1 = spara tx metadata t.ex. kontoägare och betalningsbegäransinformation, 2 = släng tx metadata)</translation> </message> <message> <source>-maxtxfee is set very high! Fees this large could be paid on a single transaction.</source> <translation>-maxtxfee är väldigt högt satt! Så höga avgifter kan komma att betalas för en enstaka transaktion.</translation> </message> <message> <source>Do not keep transactions in the mempool longer than &lt;n&gt; hours (default: %u)</source> <translation>Håll inte transaktioner i minnespoolen längre än &lt;n&gt; timmar (förvalt: %u)</translation> </message> <message> <source>Equivalent bytes per sigop in transactions for relay and mining (default: %u)</source> <translation>Samma antal byte per sigop i transaktioner som vi reläar och bryter (förvalt: %u)</translation> </message> <message> <source>Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)</source> <translation>Avgifter (i %s/kB) mindre än detta anses vara nollavgifter vid skapande av transaktion (standard: %s)</translation> </message> <message> <source>How thorough the block verification of -checkblocks is (0-4, default: %u)</source> <translation>Hur grundlig blockverifikationen vid -checkblocks är (0-4, förvalt: %u)</translation> </message> <message> <source>Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)</source> <translation>Upprätthåll ett fullständigt transaktionsindex, som används av getrawtransaction rpc-anrop (förval: %u)</translation> </message> <message> <source>Number of seconds to keep misbehaving peers from reconnecting (default: %u)</source> <translation>Antal sekunder att hindra klienter som missköter sig från att ansluta (förvalt: %u)</translation> </message> <message> <source>Output debugging information (default: %u, supplying &lt;category&gt; is optional)</source> <translation>Skriv ut avlusningsinformation (förvalt: %u, att ange &lt;category&gt; är frivilligt)</translation> </message> <message> <source>Support filtering of blocks and transaction with bloom filters (default: %u)</source> <translation>Stöd filtrering av block och transaktioner med bloomfilter (standard: %u)</translation> </message> <message> <source>Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.</source> <translation>Total längd på strängen för nätverksversion (%i) överskrider maxlängden (%i). Minska numret eller storleken på uacomments.</translation> </message> <message> <source>Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)</source> <translation>Försöker hålla utgående trafik under givet mål (i MiB per 24 timmar), 0 = ingen gräns (förvalt: %d)</translation> </message> <message> <source>Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source> <translation>Argumentet -socks hittades och stöds inte. Det är inte längre möjligt att sätta SOCKS-version längre, bara SOCKS5-proxy stöds.</translation> </message> <message> <source>Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay.</source> <translation>Argumentet -whitelistalwaysrelay stöds inte utan ignoreras, använd -whitelistrelay och/eller -whitelistforcerelay.</translation> </message> <message> <source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)</source> <translation>Använd separat SOCKS5 proxy för att nå kollegor via dolda tjänster i Tor (förvalt: -%s)</translation> </message> <message> <source>Warning: Unknown block versions being mined! It's possible unknown rules are in effect</source> <translation>Varning: Okända blockversioner bryts! Det är möjligt att okända regler används</translation> </message> <message> <source>Warning: Wallet file corrupt, data salvaged! Original %s saved as %s in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Varning: Plånboksfilen var korrupt, datat har räddats! Den ursprungliga %s har sparas som %s i %s. Om ditt saldo eller transaktioner är felaktiga bör du återställa från en säkerhetskopia.</translation> </message> <message> <source>(default: %s)</source> <translation>(förvalt: %s)</translation> </message> <message> <source>Always query for peer addresses via DNS lookup (default: %u)</source> <translation>Sök alltid efter klientadresser med DNS sökningen (förvalt: %u)</translation> </message> <message> <source>How many blocks to check at startup (default: %u, 0 = all)</source> <translation>Hur många block att kontrollera vid uppstart (förvalt: %u, 0 = alla)</translation> </message> <message> <source>Include IP addresses in debug output (default: %u)</source> <translation>Inkludera IP-adresser i debugutskrift (förvalt: %u)</translation> </message> <message> <source>Invalid -proxy address: '%s'</source> <translation>Ogiltig -proxy adress: '%s'</translation> </message> <message> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Lyssna på JSON-RPC-anslutningar på &lt;port&gt; (förval: %u eller testnet: %u)</translation> </message> <message> <source>Listen for connections on &lt;port&gt; (default: %u or testnet: %u)</source> <translation>Lyssna efter anslutningar på &lt;port&gt; (förvalt: %u eller testnet: %u)</translation> </message> <message> <source>Maintain at most &lt;n&gt; connections to peers (default: %u)</source> <translation>Ha som mest &lt;n&gt; anslutningar till andra klienter (förvalt: %u)</translation> </message> <message> <source>Make the wallet broadcast transactions</source> <translation>Gör så att plånboken sänder ut transaktionerna</translation> </message> <message> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: %u)</source> <translation>Maximal mottagningsbuffert per anslutning, &lt;n&gt;*1000 byte (förvalt: %u)</translation> </message> <message> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: %u)</source> <translation>Maximal sändningsbuffert per anslutning, &lt;n&gt;*1000 byte (förvalt: %u)</translation> </message> <message> <source>Prepend debug output with timestamp (default: %u)</source> <translation>Skriv ut tidsstämpel i avlusningsinformationen (förvalt: %u)</translation> </message> <message> <source>Relay and mine data carrier transactions (default: %u)</source> <translation>Reläa och bearbeta databärartransaktioner (förvalt: %u) </translation> </message> <message> <source>Relay non-P2SH multisig (default: %u)</source> <translation>Reläa icke-P2SH multisig (förvalt: %u)</translation> </message> <message> <source>Set key pool size to &lt;n&gt; (default: %u)</source> <translation>Sätt storleken på nyckelpoolen till &lt;n&gt; (förvalt: %u)</translation> </message> <message> <source>Set maximum BIP141 block weight (default: %d)</source> <translation>Sätt maximal BIP141 blockvikt (förvalt: %d)</translation> </message> <message> <source>Set the number of threads to service RPC calls (default: %d)</source> <translation>Ange antalet trådar för att hantera RPC anrop (förvalt: %d)</translation> </message> <message> <source>Specify configuration file (default: %s)</source> <translation>Ange konfigurationsfil (förvalt: %s)</translation> </message> <message> <source>Specify connection timeout in milliseconds (minimum: 1, default: %d)</source> <translation>Ange timeout för uppkoppling i millisekunder (minimum:1, förvalt: %d)</translation> </message> <message> <source>Specify pid file (default: %s)</source> <translation>Ange pid-fil (förvalt: %s)</translation> </message> <message> <source>Spend unconfirmed change when sending transactions (default: %u)</source> <translation>Spendera okonfirmerad växel när transaktioner sänds (förvalt: %u)</translation> </message> <message> <source>Threshold for disconnecting misbehaving peers (default: %u)</source> <translation>Tröskelvärde för att koppla ifrån klienter som missköter sig (förvalt: %u)</translation> </message> <message> <source>Unknown network specified in -onlynet: '%s'</source> <translation>Okänt nätverk som anges i -onlynet: '%s'</translation> </message> <message> <source>Insufficient funds</source> <translation>Otillräckligt med mincoins</translation> </message> <message> <source>Loading block index...</source> <translation>Laddar blockindex...</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Lägg till en nod att koppla upp mot och försök att hålla anslutningen öppen</translation> </message> <message> <source>Loading wallet...</source> <translation>Laddar plånbok...</translation> </message> <message> <source>Cannot downgrade wallet</source> <translation>Kan inte nedgradera plånboken</translation> </message> <message> <source>Cannot write default address</source> <translation>Kan inte skriva standardadress</translation> </message> <message> <source>Rescanning...</source> <translation>Söker igen...</translation> </message> <message> <source>Done loading</source> <translation>Klar med laddning</translation> </message> <message> <source>Error</source> <translation>Fel</translation> </message> </context> </TS>
xieta/mincoin
src/qt/locale/bitcoin_sv.ts
TypeScript
mit
124,283
/** * -------------------------------------------------------------------------- * Bootstrap (v4.3.1): dom/selector-engine.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ import { find as findFn, findOne, matches, closest } from './polyfill' import { makeArray } from '../util/index' /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ const NODE_TEXT = 3 const SelectorEngine = { matches(element, selector) { return matches.call(element, selector) }, find(selector, element = document.documentElement) { if (typeof selector !== 'string') { return null } return findFn.call(element, selector) }, findOne(selector, element = document.documentElement) { if (typeof selector !== 'string') { return null } return findOne.call(element, selector) }, children(element, selector) { if (typeof selector !== 'string') { return null } const children = makeArray(element.children) return children.filter(child => this.matches(child, selector)) }, parents(element, selector) { if (typeof selector !== 'string') { return null } const parents = [] let ancestor = element.parentNode while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT) { if (this.matches(ancestor, selector)) { parents.push(ancestor) } ancestor = ancestor.parentNode } return parents }, closest(element, selector) { if (typeof selector !== 'string') { return null } return closest.call(element, selector) }, prev(element, selector) { if (typeof selector !== 'string') { return null } const siblings = [] let previous = element.previousSibling while (previous && previous.nodeType === Node.ELEMENT_NODE && previous.nodeType !== NODE_TEXT) { if (this.matches(previous, selector)) { siblings.push(previous) } previous = previous.previousSibling } return siblings } } export default SelectorEngine
stanwmusic/bootstrap
js/src/dom/selector-engine.js
JavaScript
mit
2,277
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. package mlog // Standard levels var ( LvlPanic = LogLevel{ID: 0, Name: "panic", Stacktrace: true} LvlFatal = LogLevel{ID: 1, Name: "fatal", Stacktrace: true} LvlError = LogLevel{ID: 2, Name: "error"} LvlWarn = LogLevel{ID: 3, Name: "warn"} LvlInfo = LogLevel{ID: 4, Name: "info"} LvlDebug = LogLevel{ID: 5, Name: "debug"} LvlTrace = LogLevel{ID: 6, Name: "trace"} // used by redirected standard logger LvlStdLog = LogLevel{ID: 10, Name: "stdlog"} // used only by the logger LvlLogError = LogLevel{ID: 11, Name: "logerror", Stacktrace: true} ) // Register custom (discrete) levels here. // !!!!! ID's must not exceed 32,768 !!!!!! var ( // used by the audit system LvlAuditAPI = LogLevel{ID: 100, Name: "audit-api"} LvlAuditContent = LogLevel{ID: 101, Name: "audit-content"} LvlAuditPerms = LogLevel{ID: 102, Name: "audit-permissions"} LvlAuditCLI = LogLevel{ID: 103, Name: "audit-cli"} // used by the TCP log target LvlTcpLogTarget = LogLevel{ID: 120, Name: "TcpLogTarget"} // used by Remote Cluster Service LvlRemoteClusterServiceDebug = LogLevel{ID: 130, Name: "RemoteClusterServiceDebug"} LvlRemoteClusterServiceError = LogLevel{ID: 131, Name: "RemoteClusterServiceError"} LvlRemoteClusterServiceWarn = LogLevel{ID: 132, Name: "RemoteClusterServiceWarn"} // used by Shared Channel Sync Service LvlSharedChannelServiceDebug = LogLevel{ID: 200, Name: "SharedChannelServiceDebug"} LvlSharedChannelServiceError = LogLevel{ID: 201, Name: "SharedChannelServiceError"} LvlSharedChannelServiceWarn = LogLevel{ID: 202, Name: "SharedChannelServiceWarn"} LvlSharedChannelServiceMessagesInbound = LogLevel{ID: 203, Name: "SharedChannelServiceMsgInbound"} LvlSharedChannelServiceMessagesOutbound = LogLevel{ID: 204, Name: "SharedChannelServiceMsgOutbound"} // add more here ... ) // Combinations for LogM (log multi) var ( MLvlAuditAll = []LogLevel{LvlAuditAPI, LvlAuditContent, LvlAuditPerms, LvlAuditCLI} )
42wim/matterircd
vendor/github.com/mattermost/mattermost-server/v5/shared/mlog/levels.go
GO
mit
2,097
version https://git-lfs.github.com/spec/v1 oid sha256:9e5db06495724b6fedb3e06776242c7ddb55da8532eb678a5a5b88757b8108df size 1211
yogeshsaroya/new-cdnjs
ajax/libs/mathjax/1.1a/jax/output/HTML-CSS/fonts/STIX/General/Italic/GeneralPunctuation.js
JavaScript
mit
129
<?php namespace App\Jobs; use App\Classes\NewcomerMatching; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class matchNewcomerGodfather implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; private $force = false; /** * Create a new job instance. * * @return void */ public function __construct($force = false) { $this->force = $force; } /** * Execute the job. * * @return void */ public function handle() { NewcomerMatching::matchReferrals($this->force); } }
ungdev/integration-UTT
app/Jobs/matchNewcomerGodfather.php
PHP
mit
750
using System; using System.Collections.Generic; namespace LightweightInfluxDb { public interface ISeriesPoint { string Name { get; } Dictionary<string, string> Tags { get; } List<string> Fields { get; } List<object> Values { get; } DateTime? Timestamp { get; } } }
N6UDP/LightweightInfluxDb
src/LightweightInfluxDb/ISeriesPoint.cs
C#
mit
312
var spawn = require('child_process').spawn, Promise = require('bluebird'), uuid = require('node-uuid'), path = require('path'), fs = require('fs'), mkdirp = require('mkdirp'), _ = require('underscore'), fs = require('fs'), Sftp = require('sftp-upload'); var rosettaExecutable = path.join(__dirname, '../../sip-generator-2/SIP_Generator/'); var depositExecutable = path.join(__dirname, '../../sip-generator-2/rosetta-connector/dps-sdk-deposit'); var Rosetta = module.exports = function() {}; Rosetta.prototype.deposit = function(sourceDir) { var rosetta = this; console.log('[Rosetta::deposit] configuration: ' + sourceDir); var subDir = sourceDir.replace('/', ''); console.log('[Rosetta::deposit] subdir: ' + subDir); return new Promise(function(resolve, reject) { var cwd = process.cwd(); process.chdir(depositExecutable); var executable = path.join(depositExecutable, 'deposit.jar'); var executable = spawn('java', ['-jar', executable, subDir]); executable.stdout.on('data', function(data) { console.log(data.toString()); }); executable.stderr.on('data', function(data) { console.log('[Rosetta::deposit] Error during programm execution: ' + data.toString()); reject(data.toString()); }); executable.on('close', function(code) { if (code !== 0) { console.log('[Rosetta::deposit] child process exited with code ' + code); return reject('[Rosetta::deposit] child process exited with code ' + code); } console.log('[Rosetta::deposit] Successfully deposit ' + subDir); resolve(code); }); }); }; Rosetta.prototype.upload = function(sourceDir) { return new Promise(function(resolve, reject) { var uuid = sourceDir.split('/').pop(), privateKey = null; try { // FIXXME: add possibility to upload key! privateKey = fs.readFileSync('/home/hecher/.ssh/id_rsa-larissa'); } catch (err) { return reject('Private key for Rosetta upload could not be read.'); } var options = { host: 'exchange.tib.eu', username: 'duraark', path: sourceDir, remoteDir: '/tib_extern_deposit_duraark/tmp/' + uuid, privateKey: privateKey }, sftp = new Sftp(options); try { sftp.on('error', function(err) { console.log('Error connecting to SFTP: ' + err); reject('Error connecting to SFTP: ' + err); }) .on('uploading', function(pgs) { console.log('Uploading', pgs.file); console.log(pgs.percent + '% completed'); }) .on('completed', function() { console.log('Upload Completed'); resolve(sourceDir); }) .upload(); } catch (err) { console.log('Error creating connection to SFTP: ' + err); reject('Error creating connection to SFTP: ' + err); } }); }; Rosetta.prototype.start = function(sourceDir, output) { var rosetta = this; console.log('[Rosetta::start] configuration: ' + sourceDir + " --> " + output); return new Promise(function(resolve, reject) { console.log('[Rosetta::start] creating output Dir'); mkdirp(output, function(err) { if (err) return reject(err); var cwd = process.cwd(); process.chdir(rosettaExecutable); //JAVA -jar SIP _Generator.jar D:\input D:\output /exlibris1/transfer/tib_duraark // var args = [sourceDir, output, '/exlibris1/transfer/tib_duraark'], var executable = path.join(rosettaExecutable, 'SIP_Generator.jar'), args = ['-jar', executable, sourceDir, output, '/exlibris1/transfer/tib_extern_deposit_duraark']; console.log('[Rosetta::start] about to execute: java ' + args.join(' ')); var executable = spawn('java', args); executable.stdout.on('data', function(data) { console.log(data.toString()); }); executable.stderr.on('data', function(data) { console.log('[Rosetta::start] Error during programm execution: ' + data.toString()); }); executable.on('close', function(code) { if (code !== 0) { console.log('[Rosetta::start] child process exited with code ' + code); return reject('[Rosetta::start] child process exited with code ' + code); } console.log('[Rosetta::start] child process exited with code ' + code); rosetta.upload(output).then(function(sourceDir) { var deposits = []; var entities = getDirectories(sourceDir); for (var idx = 0; idx < entities.length; idx++) { var entity = entities[idx]; // var subDir = 'session_physicalasset_fa3a93318f644fe9bc97f781cdc1d501'; // var subDir = 'fa3a93318f644fe9bc97f781cdc1d501'; var subDir = path.join(sourceDir, entity); // var subDir = entity; deposits.push(rosetta.deposit(subDir)); } Promise.all(deposits).then(function() { console.log('deposit finished for all intellectual entities'); return resolve(output); }).catch(function(err) { return reject(err); }); }).catch(function(err) { console.log('Rosetta upload error: ' + err); return reject(err); }); }); }); }); }; function getDirectories(srcpath) { return fs.readdirSync(srcpath).filter(function(file) { return fs.statSync(path.join(srcpath, file)).isDirectory(); }); }
DURAARK/microservice-sipgenerator
bindings/rosetta/app.js
JavaScript
mit
5,477
package main import ( "log" "time" "github.com/spf13/cobra" "github.com/brunetto/goutils/debug" "github.com/brunetto/sltools/slt" ) var ( noGPU, tf, as, noBinaries bool icsFileName string intTime string randomNumber string ) var kiraWrapCmd = &cobra.Command{ Use: "kiraWrap", Short: "Wrapper for the kira integrator", Long: `Wrap the kira integrator providing environment monitoring. The "no-GPU" flag allow you to run the non GPU version of kira if you installed kira-no-GPU in $HOME/bin/. Run with: kiraWrap (--no-GPU)`, Run: func(cmd *cobra.Command, args []string) { if icsFileName == "" || intTime == "" { log.Fatal("Provide an ICs file and the integration time.") } slt.KiraWrap(icsFileName, intTime, randomNumber, noGPU) }, } func InitCommands() { kiraWrapCmd.PersistentFlags().BoolVarP(&noGPU, "no-GPU", "n", false, "Run without GPU support if kira-no-GPU installed in $HOME/bin/.") kiraWrapCmd.PersistentFlags().BoolVarP(&tf, "tf", "f", false, "Run TF version of kira (debug strings).") kiraWrapCmd.PersistentFlags().BoolVarP(&as, "as", "a", false, "Run Allen-Santillan version of kira (debug strings).") kiraWrapCmd.PersistentFlags().BoolVarP(&noBinaries, "no-binaries", "b", false, "Switch off binary evolution.") kiraWrapCmd.PersistentFlags().StringVarP(&icsFileName, "ics", "i", "", "ICs file to start with.") kiraWrapCmd.PersistentFlags().StringVarP(&intTime, "time", "t", "", "Number of timestep to integrate before stop the simulation.") kiraWrapCmd.PersistentFlags().StringVarP(&randomNumber, "random", "s", "", "Random number.") } func main () () { defer debug.TimeMe(time.Now()) InitCommands() kiraWrapCmd.Execute() }
brunetto/sltools-dev
cmd/kiraWrap/kiraWrap.go
GO
mit
1,700
package edu.msudenver.cs3250.group6.msubanner.entities; /** * The professor class. */ public final class Professor extends User { /** * Default constructor, creates blank professor. */ public Professor() { } /** * Constructor. * * @param firstName professors first name * @param lastName professors last name */ public Professor(final String firstName, final String lastName) { super(firstName, lastName); } @Override public boolean equals(final Object other) { return other instanceof Professor && super.equals(other); } @Override public int hashCode() { return super.hashCode(); } }
cs3250-team6/msubanner
src/main/java/edu/msudenver/cs3250/group6/msubanner/entities/Professor.java
Java
mit
698
import elem from "./_elem.js"; import clrPckr from "./_color-picker.js"; var s, x, y, z, colorNum = 0, arrMap = [], c = document.getElementById("canvasGrid"), ctx = c.getContext("2d"); var grid = { //create grid and create boxes createGridIllustrator: () => { //module for creating a grid for(var r = 0; r < elem.s.columnCount; r++) { for(var i = 0; i < elem.s.rowCount; i++) { ctx.strokeStyle = "#262626"; ctx.strokeRect(r * elem.s.pixSize, i * elem.s.pixSize, elem.s.pixSize, elem.s.pixSize); ctx.fillStyle = elem.el.backgroundHexColor.value; ctx.fillRect(r * elem.s.pixSize + 1, i * elem.s.pixSize + 1, elem.s.pixSize - 2, elem.s.pixSize - 2); } } }, //allow individual boxes to be clicked // handleClick is still in prototyping phase handleClick: (e) => { clrPckr.pickBackgroundHexColor(); e = e || window.event; var xVal = Math.floor(e.offsetX === undefined ? e.layerX : e.offsetX / elem.s.pixSize) * elem.s.pixSize; var yVal = Math.floor(e.offsetY === undefined ? e.layerY : e.offsetY / elem.s.pixSize) * elem.s.pixSize; ctx.fillStyle = elem.el.hexColor.value; //get the color for the box clicked on var imgData = ctx.getImageData(Math.floor(e.offsetX / elem.s.pixSize) * elem.s.pixSize + 1, Math.floor(e.offsetY / elem.s.pixSize) * elem.s.pixSize + 1, elem.s.pixSize - 2, elem.s.pixSize - 2); //if it is the background grey/gray remove it //currently does not work with color change if(imgData.data[0] !== parseFloat(elem.el.backgroundRed.value) && imgData.data[1] !== parseFloat(elem.el.backgroundGreen.value) && imgData.data[2] !== parseFloat(elem.el.backgroundBlue.value)){ ctx.fillStyle = `rgba(${elem.el.backgroundRed.value}, ${elem.el.backgroundGreen.value}, ${elem.el.backgroundBlue.value}, 1)`; ctx.clearRect(Math.floor(e.offsetX / elem.s.pixSize) * elem.s.pixSize + 1, Math.floor(e.offsetY / elem.s.pixSize) * elem.s.pixSize + 1, elem.s.pixSize - 2, elem.s.pixSize - 2); ctx.fillRect(Math.floor(e.offsetX / elem.s.pixSize) * elem.s.pixSize + 1, Math.floor(e.offsetY / elem.s.pixSize) * elem.s.pixSize + 1, //accomodate for 2 px border //need to put in a variable down the line elem.s.pixSize - 2, elem.s.pixSize - 2); //elem.s.storeValues.indexOf([xVal, yVal, elem.el.hexColor.value]).pop(); //this return false is causing wonky behavior, should look into it return false; } ctx.fillRect(Math.floor(e.offsetX / elem.s.pixSize) * elem.s.pixSize + 1, Math.floor(e.offsetY / elem.s.pixSize) * elem.s.pixSize + 1, //accomodate for 2 px border //need to put in a variable down the line elem.s.pixSize - 2, elem.s.pixSize - 2); }, updateGridColor: () => { for(let x = 0; x < elem.s.columnCount; x++) { for(let y = 0; y < elem.s.rowCount; y++) { ctx.strokeStyle = `${elem.el.backgroundRed.value + 44}. ${elem.el.backgroundGreen.value + 44}. ${elem.el.backgroundBlue.value + 44}`; ctx.strokeRect(x * elem.s.pixSize, y * elem.s.pixSize, elem.s.pixSize, elem.s.pixSize); ctx.fillStyle = elem.el.backgroundHexColor.value; ctx.fillRect(x * elem.s.pixSize + 1, y * elem.s.pixSize + 1, elem.s.pixSize - 2, elem.s.pixSize - 2); } } for(let x = 0; x < elem.s.storeValues.length; x++){ ctx.fillStyle = elem.s.storeValues[x][2]; ctx.fillRect(parseFloat(elem.s.storeValues[x][0]) + 1, parseFloat(elem.s.storeValues[x][1]) + 1, elem.s.pixSize - 2, elem.s.pixSize - 2); } } }; export default grid;
CharlieGreenman/pixelatorV2_with_react
app/js/_grid.js
JavaScript
mit
3,948
require 'chefspec' describe 'group::create' do platform 'ubuntu' describe 'creates a group with the default action' do it { is_expected.to create_group('default_action') } it { is_expected.to_not create_group('not_default_action') } end describe 'creates a group with an explicit action' do it { is_expected.to create_group('explicit_action') } end describe 'creates a group with attributes' do it { is_expected.to create_group('with_attributes').with(gid: 1234) } it { is_expected.to_not create_group('with_attributes').with(gid: 5678) } end describe 'creates a group when specifying the identity attribute' do it { is_expected.to create_group('identity_attribute') } end end
chefspec/chefspec
examples/group/spec/create_spec.rb
Ruby
mit
724
package collectors import ( "fmt" "math" "regexp" "strings" "time" "bosun.org/_third_party/github.com/StackExchange/wmi" "bosun.org/metadata" "bosun.org/opentsdb" "bosun.org/slog" ) func init() { collectors = append(collectors, &IntervalCollector{F: c_network_windows, init: winNetworkInit}) c := &IntervalCollector{ F: c_network_team_windows, } // Make sure MSFT_NetImPlatAdapter and MSFT_NetAdapterStatisticsSettingData // are valid WMI classes when initializing c_network_team_windows c.init = func() { var dstTeamNic []MSFT_NetLbfoTeamNic var dstStats []MSFT_NetAdapterStatisticsSettingData queryTeamAdapter = wmi.CreateQuery(&dstTeamNic, "") queryTeamStats = wmi.CreateQuery(&dstStats, "") c.Enable = func() bool { errTeamNic := queryWmiNamespace(queryTeamAdapter, &dstTeamNic, namespaceStandardCimv2) errStats := queryWmiNamespace(queryTeamStats, &dstStats, namespaceStandardCimv2) return errTeamNic == nil && errStats == nil } } collectors = append(collectors, c) } var ( queryTeamStats string queryTeamAdapter string namespaceStandardCimv2 = "root\\StandardCimv2" interfaceExclusions = regexp.MustCompile("isatap|Teredo") // instanceNameToUnderscore matches '#' '/' and '\' for replacing with '_'. instanceNameToUnderscore = regexp.MustCompile("[#/\\\\]") mNicInstanceNameToInterfaceIndex = make(map[string]string) ) // winNetworkToInstanceName converts a Network Adapter Name to the InstanceName // that is used in Win32_PerfRawData_Tcpip_NetworkInterface. func winNetworkToInstanceName(Name string) string { instanceName := Name instanceName = strings.Replace(instanceName, "(", "[", -1) instanceName = strings.Replace(instanceName, ")", "]", -1) instanceName = instanceNameToUnderscore.ReplaceAllString(instanceName, "_") return instanceName } // winNetworkInit maintains a mapping of InstanceName to InterfaceIndex func winNetworkInit() { update := func() { var dstNetworkAdapter []Win32_NetworkAdapter q := wmi.CreateQuery(&dstNetworkAdapter, "WHERE PhysicalAdapter=True and MACAddress <> null") err := queryWmi(q, &dstNetworkAdapter) if err != nil { slog.Error(err) return } for _, nic := range dstNetworkAdapter { var iface = fmt.Sprint("Interface", nic.InterfaceIndex) //Get PnPName using Win32_PnPEntity class var pnpname = "" var escapeddeviceid = strings.Replace(nic.PNPDeviceID, "\\", "\\\\", -1) var filter = fmt.Sprintf("WHERE DeviceID='%s'", escapeddeviceid) var dstPnPName []Win32_PnPEntity q = wmi.CreateQuery(&dstPnPName, filter) err = queryWmi(q, &dstPnPName) if err != nil { slog.Error(err) return } for _, pnp := range dstPnPName { //Really should be a single item pnpname = pnp.Name } if pnpname == "" { slog.Errorf("%s cannot find Win32_PnPEntity %s", iface, filter) continue } //Convert to instance name (see http://goo.gl/jfq6pq ) instanceName := winNetworkToInstanceName(pnpname) mNicInstanceNameToInterfaceIndex[instanceName] = iface } } update() go func() { for range time.Tick(time.Minute * 5) { update() } }() } func c_network_windows() (opentsdb.MultiDataPoint, error) { var dstStats []Win32_PerfRawData_Tcpip_NetworkInterface var q = wmi.CreateQuery(&dstStats, "") err := queryWmi(q, &dstStats) if err != nil { return nil, err } var md opentsdb.MultiDataPoint for _, nicStats := range dstStats { if interfaceExclusions.MatchString(nicStats.Name) { continue } iface := mNicInstanceNameToInterfaceIndex[nicStats.Name] if iface == "" { continue } //This does NOT include TEAM network adapters. Those will go to os.net.bond tagsIn := opentsdb.TagSet{"iface": iface, "direction": "in"} tagsOut := opentsdb.TagSet{"iface": iface, "direction": "out"} Add(&md, "win.net.ifspeed", nicStats.CurrentBandwidth, opentsdb.TagSet{"iface": iface}, metadata.Gauge, metadata.BitsPerSecond, descWinNetCurrentBandwidth) Add(&md, "win.net.bytes", nicStats.BytesReceivedPersec, tagsIn, metadata.Counter, metadata.BytesPerSecond, descWinNetBytesReceivedPersec) Add(&md, "win.net.bytes", nicStats.BytesSentPersec, tagsOut, metadata.Counter, metadata.BytesPerSecond, descWinNetBytesSentPersec) Add(&md, "win.net.packets", nicStats.PacketsReceivedPersec, tagsIn, metadata.Counter, metadata.PerSecond, descWinNetPacketsReceivedPersec) Add(&md, "win.net.packets", nicStats.PacketsSentPersec, tagsOut, metadata.Counter, metadata.PerSecond, descWinNetPacketsSentPersec) Add(&md, "win.net.dropped", nicStats.PacketsOutboundDiscarded, tagsOut, metadata.Counter, metadata.PerSecond, descWinNetPacketsOutboundDiscarded) Add(&md, "win.net.dropped", nicStats.PacketsReceivedDiscarded, tagsIn, metadata.Counter, metadata.PerSecond, descWinNetPacketsReceivedDiscarded) Add(&md, "win.net.errs", nicStats.PacketsOutboundErrors, tagsOut, metadata.Counter, metadata.PerSecond, descWinNetPacketsOutboundErrors) Add(&md, "win.net.errs", nicStats.PacketsReceivedErrors, tagsIn, metadata.Counter, metadata.PerSecond, descWinNetPacketsReceivedErrors) Add(&md, osNetBytes, nicStats.BytesReceivedPersec, tagsIn, metadata.Counter, metadata.BytesPerSecond, osNetBytesDesc) Add(&md, osNetBytes, nicStats.BytesSentPersec, tagsOut, metadata.Counter, metadata.BytesPerSecond, osNetBytesDesc) Add(&md, osNetPackets, nicStats.PacketsReceivedPersec, tagsIn, metadata.Counter, metadata.PerSecond, osNetPacketsDesc) Add(&md, osNetPackets, nicStats.PacketsSentPersec, tagsOut, metadata.Counter, metadata.PerSecond, osNetPacketsDesc) Add(&md, osNetDropped, nicStats.PacketsOutboundDiscarded, tagsOut, metadata.Counter, metadata.PerSecond, osNetDroppedDesc) Add(&md, osNetDropped, nicStats.PacketsReceivedDiscarded, tagsIn, metadata.Counter, metadata.PerSecond, osNetDroppedDesc) Add(&md, osNetErrors, nicStats.PacketsOutboundErrors, tagsOut, metadata.Counter, metadata.PerSecond, osNetErrorsDesc) Add(&md, osNetErrors, nicStats.PacketsReceivedErrors, tagsIn, metadata.Counter, metadata.PerSecond, osNetErrorsDesc) } return md, nil } const ( descWinNetCurrentBandwidth = "Estimate of the interface's current bandwidth in bits per second (bps). For interfaces that do not vary in bandwidth or for those where no accurate estimation can be made, this value is the nominal bandwidth." descWinNetBytesReceivedPersec = "Bytes Received/sec is the rate at which bytes are received over each network adapter, including framing characters. Network Interface\\Bytes Received/sec is a subset of Network Interface\\Bytes Total/sec." descWinNetBytesSentPersec = "Bytes Sent/sec is the rate at which bytes are sent over each network adapter, including framing characters. Network Interface\\Bytes Sent/sec is a subset of Network Interface\\Bytes Total/sec." descWinNetPacketsReceivedPersec = "Packets Received/sec is the rate at which packets are received on the network interface." descWinNetPacketsSentPersec = "Packets Sent/sec is the rate at which packets are sent on the network interface." descWinNetPacketsOutboundDiscarded = "Packets Outbound Discarded is the number of outbound packets that were chosen to be discarded even though no errors had been detected to prevent transmission. One possible reason for discarding packets could be to free up buffer space." descWinNetPacketsReceivedDiscarded = "Packets Received Discarded is the number of inbound packets that were chosen to be discarded even though no errors had been detected to prevent their delivery to a higher-layer protocol. One possible reason for discarding packets could be to free up buffer space." descWinNetPacketsOutboundErrors = "Packets Outbound Errors is the number of outbound packets that could not be transmitted because of errors." descWinNetPacketsReceivedErrors = "Packets Received Errors is the number of inbound packets that contained errors preventing them from being deliverable to a higher-layer protocol." ) type Win32_PnPEntity struct { Name string //Intel(R) Gigabit ET Quad Port Server Adapter #3 } type Win32_NetworkAdapter struct { Description string //Intel(R) Gigabit ET Quad Port Server Adapter (no index) InterfaceIndex uint32 PNPDeviceID string } type Win32_PerfRawData_Tcpip_NetworkInterface struct { CurrentBandwidth uint32 BytesReceivedPersec uint32 BytesSentPersec uint32 Name string PacketsOutboundDiscarded uint32 PacketsOutboundErrors uint32 PacketsReceivedDiscarded uint32 PacketsReceivedErrors uint32 PacketsReceivedPersec uint32 PacketsSentPersec uint32 } // c_network_team_windows will add metrics for team network adapters from // MSFT_NetAdapterStatisticsSettingData for any adapters that are in // MSFT_NetLbfoTeamNic and have a valid instanceName. func c_network_team_windows() (opentsdb.MultiDataPoint, error) { var dstTeamNic []*MSFT_NetLbfoTeamNic err := queryWmiNamespace(queryTeamAdapter, &dstTeamNic, namespaceStandardCimv2) if err != nil { return nil, err } var dstStats []MSFT_NetAdapterStatisticsSettingData err = queryWmiNamespace(queryTeamStats, &dstStats, namespaceStandardCimv2) if err != nil { return nil, err } mDescriptionToTeamNic := make(map[string]*MSFT_NetLbfoTeamNic) for _, teamNic := range dstTeamNic { mDescriptionToTeamNic[teamNic.InterfaceDescription] = teamNic } var md opentsdb.MultiDataPoint for _, nicStats := range dstStats { TeamNic := mDescriptionToTeamNic[nicStats.InterfaceDescription] if TeamNic == nil { continue } instanceName := winNetworkToInstanceName(nicStats.InterfaceDescription) iface := mNicInstanceNameToInterfaceIndex[instanceName] if iface == "" { continue } tagsIn := opentsdb.TagSet{"iface": iface, "direction": "in"} tagsOut := opentsdb.TagSet{"iface": iface, "direction": "out"} linkSpeed := math.Min(float64(TeamNic.ReceiveLinkSpeed), float64(TeamNic.Transmitlinkspeed)) Add(&md, "win.net.bond.ifspeed", linkSpeed, opentsdb.TagSet{"iface": iface}, metadata.Gauge, metadata.BitsPerSecond, descWinNetTeamlinkspeed) Add(&md, "win.net.bond.bytes", nicStats.ReceivedBytes, tagsIn, metadata.Counter, metadata.BytesPerSecond, descWinNetTeamReceivedBytes) Add(&md, "win.net.bond.bytes", nicStats.SentBytes, tagsOut, metadata.Counter, metadata.BytesPerSecond, descWinNetTeamSentBytes) Add(&md, "win.net.bond.bytes_unicast", nicStats.ReceivedUnicastBytes, tagsIn, metadata.Counter, metadata.BytesPerSecond, descWinNetTeamReceivedUnicastBytes) Add(&md, "win.net.bond.bytes_unicast", nicStats.SentUnicastBytes, tagsOut, metadata.Counter, metadata.BytesPerSecond, descWinNetTeamSentUnicastBytes) Add(&md, "win.net.bond.bytes_broadcast", nicStats.ReceivedBroadcastBytes, tagsIn, metadata.Counter, metadata.BytesPerSecond, descWinNetTeamReceivedBroadcastBytes) Add(&md, "win.net.bond.bytes_broadcast", nicStats.SentBroadcastBytes, tagsOut, metadata.Counter, metadata.BytesPerSecond, descWinNetTeamSentBroadcastBytes) Add(&md, "win.net.bond.bytes_multicast", nicStats.ReceivedMulticastBytes, tagsIn, metadata.Counter, metadata.BytesPerSecond, descWinNetTeamReceivedMulticastBytes) Add(&md, "win.net.bond.bytes_multicast", nicStats.SentMulticastBytes, tagsOut, metadata.Counter, metadata.BytesPerSecond, descWinNetTeamSentMulticastBytes) Add(&md, "win.net.bond.packets_unicast", nicStats.ReceivedUnicastPackets, tagsIn, metadata.Counter, metadata.PerSecond, descWinNetTeamReceivedUnicastPackets) Add(&md, "win.net.bond.packets_unicast", nicStats.SentUnicastPackets, tagsOut, metadata.Counter, metadata.PerSecond, descWinNetTeamSentUnicastPackets) Add(&md, "win.net.bond.dropped", nicStats.ReceivedDiscardedPackets, tagsIn, metadata.Counter, metadata.PerSecond, descWinNetTeamReceivedDiscardedPackets) Add(&md, "win.net.bond.dropped", nicStats.OutboundDiscardedPackets, tagsOut, metadata.Counter, metadata.PerSecond, descWinNetTeamOutboundDiscardedPackets) Add(&md, "win.net.bond.errs", nicStats.ReceivedPacketErrors, tagsIn, metadata.Counter, metadata.PerSecond, descWinNetTeamReceivedPacketErrors) Add(&md, "win.net.bond.errs", nicStats.OutboundPacketErrors, tagsOut, metadata.Counter, metadata.PerSecond, descWinNetTeamOutboundPacketErrors) Add(&md, "win.net.bond.packets_multicast", nicStats.ReceivedMulticastPackets, tagsIn, metadata.Counter, metadata.PerSecond, descWinNetTeamReceivedMulticastPackets) Add(&md, "win.net.bond.packets_multicast", nicStats.SentMulticastPackets, tagsOut, metadata.Counter, metadata.PerSecond, descWinNetTeamSentMulticastPackets) Add(&md, "win.net.bond.packets_broadcast", nicStats.ReceivedBroadcastPackets, tagsIn, metadata.Counter, metadata.PerSecond, descWinNetTeamReceivedBroadcastPackets) Add(&md, "win.net.bond.packets_broadcast", nicStats.SentBroadcastPackets, tagsOut, metadata.Counter, metadata.PerSecond, descWinNetTeamSentBroadcastPackets) //Todo: add os.net.bond metrics once we confirm they have the same metadata } return md, nil } const ( descWinNetTeamlinkspeed = "The link speed of the adapter in bits per second." descWinNetTeamReceivedBytes = "The number of bytes of data received without errors through this interface. This value includes bytes in unicast, broadcast, and multicast packets." descWinNetTeamReceivedUnicastPackets = "The number of unicast packets received without errors through this interface." descWinNetTeamReceivedMulticastPackets = "The number of multicast packets received without errors through this interface." descWinNetTeamReceivedBroadcastPackets = "The number of broadcast packets received without errors through this interface." descWinNetTeamReceivedUnicastBytes = "The number of unicast bytes received without errors through this interface." descWinNetTeamReceivedMulticastBytes = "The number of multicast bytes received without errors through this interface." descWinNetTeamReceivedBroadcastBytes = "The number of broadcast bytes received without errors through this interface." descWinNetTeamReceivedDiscardedPackets = "The number of inbound packets which were chosen to be discarded even though no errors were detected to prevent the packets from being deliverable to a higher-layer protocol." descWinNetTeamReceivedPacketErrors = "The number of incoming packets that were discarded because of errors." descWinNetTeamSentBytes = "The number of bytes of data transmitted without errors through this interface. This value includes bytes in unicast, broadcast, and multicast packets." descWinNetTeamSentUnicastPackets = "The number of unicast packets transmitted without errors through this interface." descWinNetTeamSentMulticastPackets = "The number of multicast packets transmitted without errors through this interface." descWinNetTeamSentBroadcastPackets = "The number of broadcast packets transmitted without errors through this interface." descWinNetTeamSentUnicastBytes = "The number of unicast bytes transmitted without errors through this interface." descWinNetTeamSentMulticastBytes = "The number of multicast bytes transmitted without errors through this interface." descWinNetTeamSentBroadcastBytes = "The number of broadcast bytes transmitted without errors through this interface." descWinNetTeamOutboundDiscardedPackets = "The number of outgoing packets that were discarded even though they did not have errors." descWinNetTeamOutboundPacketErrors = "The number of outgoing packets that were discarded because of errors." ) type MSFT_NetLbfoTeamNic struct { Team string Name string ReceiveLinkSpeed uint64 Transmitlinkspeed uint64 InterfaceDescription string } type MSFT_NetAdapterStatisticsSettingData struct { InstanceID string Name string InterfaceDescription string ReceivedBytes uint64 ReceivedUnicastPackets uint64 ReceivedMulticastPackets uint64 ReceivedBroadcastPackets uint64 ReceivedUnicastBytes uint64 ReceivedMulticastBytes uint64 ReceivedBroadcastBytes uint64 ReceivedDiscardedPackets uint64 ReceivedPacketErrors uint64 SentBytes uint64 SentUnicastPackets uint64 SentMulticastPackets uint64 SentBroadcastPackets uint64 SentUnicastBytes uint64 SentMulticastBytes uint64 SentBroadcastBytes uint64 OutboundDiscardedPackets uint64 OutboundPacketErrors uint64 }
vimeo/bosun
cmd/scollector/collectors/network_windows.go
GO
mit
16,465
require_relative '../bm_helper' RUN_TIMES = 10 MyBenchmark.group 'Table initialization' do |b| # Current method used by Table#new b.report('String#to_table') do RUN_TIMES.times do File.open('bm/fixtures/table_1.txt').read.to_table end end b.report('Table#row:Hash') do RUN_TIMES.times do fin = File.open('bm/fixtures/table_1.txt') # Fill column names col_names = fin.gets.chomp.split("\t") tab = BioTCM::Table.new(primary_key: col_names.shift, col_keys: col_names) # Insert rows fin.each do |line| col = line.chomp.split("\t", -1) val = { col_names[0] => col[1], col_names[1] => col[2] } tab.row(col[0], val) end end end b.report('Table#row:Array') do RUN_TIMES.times do fin = File.open('bm/fixtures/table_1.txt') # Fill column names col_names = fin.gets.chomp.split("\t") tab = BioTCM::Table.new(primary_key: col_names.shift, col_keys: col_names) # Insert rows fin.each do |line| col = line.chomp.split("\t", -1) tab.row(col.shift, col) end end end end @tab1 = BioTCM::Table.load('bm/fixtures/table_1.txt') @tab2 = BioTCM::Table.load('bm/fixtures/table_2.txt') MyBenchmark.group 'Table operation' do |b| b.report('merge') do RUN_TIMES.times do @tab = @tab1.merge(@tab2) end end b.report('select') do RUN_TIMES.times do @tab.select_col(%w(Name Fullname)) end end end
biotcm/biotcm
bm/biotcm/bm_table.rb
Ruby
mit
1,478
module Github module Representation class PullRequest < Representation::Issuable delegate :user, :repo, :ref, :sha, to: :source_branch, prefix: true delegate :user, :exists?, :repo, :ref, :sha, :short_sha, to: :target_branch, prefix: true def source_project project end def source_branch_name @source_branch_name ||= if cross_project? || !source_branch_exists? source_branch_name_prefixed else source_branch_ref end end def source_branch_exists? return @source_branch_exists if defined?(@source_branch_exists) @source_branch_exists = !cross_project? && source_branch.exists? end def target_project project end def target_branch_name @target_branch_name ||= target_branch_exists? ? target_branch_ref : target_branch_name_prefixed end def target_branch_exists? @target_branch_exists ||= target_branch.exists? end def state return 'merged' if raw['state'] == 'closed' && raw['merged_at'].present? return 'closed' if raw['state'] == 'closed' 'opened' end def opened? state == 'opened' end def valid? source_branch.valid? && target_branch.valid? end def restore_branches! restore_source_branch! restore_target_branch! end def remove_restored_branches! return if opened? remove_source_branch! remove_target_branch! end private def project @project ||= options.fetch(:project) end def source_branch @source_branch ||= Representation::Branch.new(raw['head'], repository: project.repository) end def source_branch_name_prefixed "gh-#{target_branch_short_sha}/#{iid}/#{source_branch_user}/#{source_branch_ref}" end def target_branch @target_branch ||= Representation::Branch.new(raw['base'], repository: project.repository) end def target_branch_name_prefixed "gl-#{target_branch_short_sha}/#{iid}/#{target_branch_user}/#{target_branch_ref}" end def cross_project? return true if source_branch_repo.nil? source_branch_repo.id != target_branch_repo.id end def restore_source_branch! return if source_branch_exists? source_branch.restore!(source_branch_name) end def restore_target_branch! return if target_branch_exists? target_branch.restore!(target_branch_name) end def remove_source_branch! # We should remove the source/target branches only if they were # restored. Otherwise, we'll remove branches like 'master' that # target_branch_exists? returns true. In other words, we need # to clean up only the restored branches that (source|target)_branch_exists? # returns false for the first time it has been called, because of # this that is important to memoize these values. source_branch.remove!(source_branch_name) unless source_branch_exists? end def remove_target_branch! target_branch.remove!(target_branch_name) unless target_branch_exists? end end end end
dplarson/gitlabhq
lib/github/representation/pull_request.rb
Ruby
mit
3,306
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.09.07 at 08:01:35 PM IST // package com.mozu.qbintegration.model.qbmodel.allgen; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for CheckModRsType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CheckModRsType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{}CheckRet" minOccurs="0"/> * &lt;element ref="{}ErrorRecovery" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="requestID" type="{}STRTYPE" /> * &lt;attribute name="statusCode" use="required" type="{}INTTYPE" /> * &lt;attribute name="statusSeverity" use="required" type="{}STRTYPE" /> * &lt;attribute name="statusMessage" type="{}STRTYPE" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CheckModRsType", propOrder = { "checkRet", "errorRecovery" }) public class CheckModRsType { @XmlElement(name = "CheckRet") protected CheckRet checkRet; @XmlElement(name = "ErrorRecovery") protected ErrorRecovery errorRecovery; @XmlAttribute(name = "requestID") protected String requestID; @XmlAttribute(name = "statusCode", required = true) protected BigInteger statusCode; @XmlAttribute(name = "statusSeverity", required = true) protected String statusSeverity; @XmlAttribute(name = "statusMessage") protected String statusMessage; /** * Gets the value of the checkRet property. * * @return * possible object is * {@link CheckRet } * */ public CheckRet getCheckRet() { return checkRet; } /** * Sets the value of the checkRet property. * * @param value * allowed object is * {@link CheckRet } * */ public void setCheckRet(CheckRet value) { this.checkRet = value; } /** * Gets the value of the errorRecovery property. * * @return * possible object is * {@link ErrorRecovery } * */ public ErrorRecovery getErrorRecovery() { return errorRecovery; } /** * Sets the value of the errorRecovery property. * * @param value * allowed object is * {@link ErrorRecovery } * */ public void setErrorRecovery(ErrorRecovery value) { this.errorRecovery = value; } /** * Gets the value of the requestID property. * * @return * possible object is * {@link String } * */ public String getRequestID() { return requestID; } /** * Sets the value of the requestID property. * * @param value * allowed object is * {@link String } * */ public void setRequestID(String value) { this.requestID = value; } /** * Gets the value of the statusCode property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getStatusCode() { return statusCode; } /** * Sets the value of the statusCode property. * * @param value * allowed object is * {@link BigInteger } * */ public void setStatusCode(BigInteger value) { this.statusCode = value; } /** * Gets the value of the statusSeverity property. * * @return * possible object is * {@link String } * */ public String getStatusSeverity() { return statusSeverity; } /** * Sets the value of the statusSeverity property. * * @param value * allowed object is * {@link String } * */ public void setStatusSeverity(String value) { this.statusSeverity = value; } /** * Gets the value of the statusMessage property. * * @return * possible object is * {@link String } * */ public String getStatusMessage() { return statusMessage; } /** * Sets the value of the statusMessage property. * * @param value * allowed object is * {@link String } * */ public void setStatusMessage(String value) { this.statusMessage = value; } }
mozu-customer-success/Mozu.Integrations.Quickbooks
src/main/java/com/mozu/qbintegration/model/qbmodel/allgen/CheckModRsType.java
Java
mit
5,304
require 'rails_helper' describe 'Event', type: :feature do describe 'index page' do it "should link to the show page when an event's read more button is clicked" do event = FactoryGirl.create :event visit events_path click_link event.name expect(page).to have_current_path(event_path(event)) end it 'should have a link to an event archive' do visit events_path expect(page).to have_link(href: events_archive_path) end it 'should not list past events' do current_event = FactoryGirl.create :event past_event = FactoryGirl.create :event, :in_the_past visit events_path expect(page).to have_text(current_event.name) expect(page).to_not have_text(past_event.name) end it 'should mark an event as draft by showing a label' do login_as(FactoryGirl.create(:user, role: :organizer), :scope => :user) FactoryGirl.create :event, published: false visit events_path expect(page).to have_css('.label', text: I18n.t('activerecord.attributes.event.draft')) end it 'should mark an event as hidden by showing a label' do login_as(FactoryGirl.create(:user, role: :organizer), :scope => :user) FactoryGirl.create :event, hidden: true visit events_path expect(page).to have_css('.label', text: I18n.t('activerecord.attributes.event.hidden')) end it 'should not show drafts to pupils or coaches' do %i[coach pupil].each do |role| login_as(FactoryGirl.create(:user, role: role), :scope => :user) FactoryGirl.create :event, published: false visit events_path expect(page).to_not have_css('.label', text: I18n.t('activerecord.attributes.event.draft')) end end it 'should not show hidden events to pupils or coaches' do %i[coach pupil].each do |role| login_as(FactoryGirl.create(:user, role: role), :scope => :user) FactoryGirl.create :event, hidden: true, name: 'Verstecktes Event' visit events_path expect(page).to_not have_text('Verstecktes Event') end end it 'should display the duration of the event' do FactoryGirl.create :event, :over_six_days visit events_path expect(page).to have_text(I18n.t('events.notices.time_span_consecutive', count: 6)) end it 'should display the duration of a sigle day event' do FactoryGirl.create :event, :single_day visit events_path expect(page).to have_text(I18n.t('events.notices.time_span_consecutive', count: 1)) end it 'should display note of non consecutive date ranges' do FactoryGirl.create :event, :with_multiple_date_ranges visit events_path expect(page).to have_text(I18n.t('events.notices.time_span_non_consecutive', count: 16)) end it "should display note of today's deadline" do FactoryGirl.create :event, :is_only_today visit events_path expect(page).to have_text(I18n.t('events.notices.deadline_approaching', count: 0)) end it 'should display the days left to apply' do FactoryGirl.create :event visit events_path expect(page).to have_text(I18n.t('events.notices.deadline_approaching', count: 1)) end it "should not display the days left to apply if it's more than 7" do FactoryGirl.create :event, :application_deadline_in_10_days visit events_path expect(page).to_not have_text(I18n.t('events.notices.deadline_approaching', count: 10)) end it 'should strip markdown from the description' do FactoryGirl.create :event, description: "# Headline Test\nParagraph with a [link](http://portal.edu)." visit events_path expect(page).to_not have_css('h1', text: 'Headline Test') expect(page).to_not have_text('Headline Test') expect(page).to have_text('Paragraph with a link.') end it "should truncate the description text if it's long" do FactoryGirl.create :event, description: ('a' * Event::TRUNCATE_DESCRIPTION_TEXT_LENGTH) + 'blah' visit events_path expect(page).to_not have_text('blah') end end describe 'archive page' do it 'should list past events' do current_event = FactoryGirl.create :event past_event = FactoryGirl.create :event, :in_the_past visit events_archive_path expect(page).to have_text(past_event.name) expect(page).to_not have_text(current_event.name) end end describe 'create page' do before :each do login_as(FactoryGirl.create(:user, role: :organizer), :scope => :user) visit new_event_path fill_in 'event_name', :with => 'Testevent Name' fill_in 'event_description', :with => 'Loooooong description, which is really helpful' end I18n.t('events.type').each do |type| it 'should allow picking the #{type[1]} type' do fill_in 'Maximale Teilnehmerzahl', :with => 25 choose(type[1]) click_button I18n.t 'events.form.draft.publish' expect(page).to have_text(type[1]) end end it 'should not allow an end date before a start date' do visit new_event_path fill_in "event[date_ranges_attributes][][start_date]", with: Date.current fill_in "event[date_ranges_attributes][][end_date]", with: Date.current.prev_day(2) click_button I18n.t 'events.form.draft.publish' expect(page).to have_text('End-Datum kann nicht vor Start-Datum liegen') end it 'should allow entering multiple time spans', js: true do first_from = Date.tomorrow.next_day(1) first_to = Date.tomorrow.next_day(2) second_from = Date.tomorrow.next_day(6) second_to = Date.tomorrow.next_day(8) fill_in 'Maximale Teilnehmerzahl', :with => 25 fill_in "event[date_ranges_attributes][][start_date]", with: I18n.l(first_from) fill_in "event[date_ranges_attributes][][end_date]", with: I18n.l(first_to) click_link 'Zeitspanne hinzufügen' within page.find('#event-date-pickers').all('div')[1] do fill_in "event[date_ranges_attributes][][start_date]", with: I18n.l(second_from) fill_in "event[date_ranges_attributes][][end_date]", with: I18n.l(second_to) end fill_in 'event_application_deadline', :with => I18n.l(Date.tomorrow) click_button I18n.t 'events.form.draft.publish' expect(page).to have_text (DateRange.new start_date: first_from, end_date: first_to) expect(page).to have_text (DateRange.new start_date: second_from, end_date: second_to) end it 'should save application deadline' do deadline = Date.tomorrow fill_in 'event_max_participants', :with => 12 fill_in 'event_application_deadline', :with => I18n.l(deadline) fill_in "event[date_ranges_attributes][][start_date]", :with => Date.current.next_day(2) fill_in "event[date_ranges_attributes][][end_date]", :with => Date.current.next_day(3) click_button I18n.t 'events.form.draft.publish' expect(page).to have_text('Bewerbungsschluss ' + I18n.l(deadline)) end it 'should not allow an application deadline after the start of the event' do fill_in 'event_max_participants', :with => 12 fill_in 'event_application_deadline', :with => Date.tomorrow fill_in "event[date_ranges_attributes][][start_date]", :with => Date.current click_button I18n.t 'events.form.draft.publish' expect(page).to have_text('Bewerbungsschluss muss vor Beginn der Veranstaltung liegen') # TODO end it 'should not display errors on date ranges twice', js: true do fill_in 'Maximale Teilnehmerzahl', :with => 25 within page.find('#event-date-pickers').all('div')[0] do fill_in "event[date_ranges_attributes][][start_date]", with: I18n.l(Date.current.prev_day(7)) fill_in "event[date_ranges_attributes][][end_date]", with: I18n.l(Date.yesterday.prev_day(7)) end click_link 'Zeitspanne hinzufügen' within page.find('#event-date-pickers').all('div')[1] do fill_in "event[date_ranges_attributes][][start_date]", with: I18n.l(Date.current) fill_in "event[date_ranges_attributes][][end_date]", with: I18n.l(Date.yesterday) end click_button I18n.t('events.form.draft.publish') expect(page).to have_css('div.has-error') expect(page).to have_content('kann nicht vor Start-Datum liegen', count: 1) end it 'should allow to add custom fields', js: true do click_link I18n.t 'events.form.add_field' within page.find('#custom-application-fields').all('.input-group')[0] do fill_in "event[custom_application_fields][]", with: 'Lieblingsfarbe' end click_link I18n.t 'events.form.add_field' within page.find('#custom-application-fields').all('.input-group')[1] do fill_in "event[custom_application_fields][]", with: "Lieblings 'Friends' Charakter" end fill_in 'Maximale Teilnehmerzahl', :with => 25 fill_in "event[date_ranges_attributes][][start_date]", :with => I18n.l(Date.tomorrow.next_day(2)) fill_in "event[date_ranges_attributes][][end_date]", :with => I18n.l(Date.tomorrow.next_day(3)) fill_in 'event_application_deadline', :with => I18n.l(Date.tomorrow) click_button I18n.t('events.form.draft.publish') expect(page).to have_text('Lieblingsfarbe') expect(page).to have_text("Lieblings 'Friends' Charakter") end it 'should not allow adding fields after event creation' do event = FactoryGirl.create(:event) visit edit_event_path(event) expect(page).to_not have_text(I18n.t 'events.form.add_field') end end describe 'show page' do it 'should render markdown for the description' do event = FactoryGirl.create(:event, description: '# Test Headline') visit event_path(event) expect(page).to have_css('h1', text: 'Test Headline') end it 'should display a single day date range as a single date' do event = FactoryGirl.create(:event, :single_day) visit event_path(event) expect(page).to have_text(I18n.l(event.date_ranges.first.start_date)) expect(page).to_not have_text(' bis ' + I18n.l(event.date_ranges.first.end_date)) end it 'should display all date ranges' do event = FactoryGirl.create(:event, :with_two_date_ranges) visit event_path(event.id) expect(page).to have_text(event.date_ranges.first) expect(page).to have_text(event.date_ranges.second) end it 'should show that the application deadline is on midnight of the picked date' do event = FactoryGirl.create(:event) visit event_path(event.id) expect(page).to have_text(I18n.l(event.application_deadline) + ' Mitternacht') end end describe 'edit page' do it 'should not be possible to visit as pupil' do login_as(FactoryGirl.create(:user, role: :pupil), :scope => :user) event = FactoryGirl.create(:event, hidden: false) visit edit_event_path(event) expect(page).to have_text('Du bist nicht authorisiert diese Aktion auszuführen.') end it 'should not be possible to visit when logged out' do event = FactoryGirl.create(:event, hidden: false) visit edit_event_path(event) expect(page).to have_text('Du bist nicht authorisiert diese Aktion auszuführen.') end it 'should not be possible to visit as coach' do login_as(FactoryGirl.create(:user, role: :coach), :scope => :user) event = FactoryGirl.create(:event, hidden: false) visit edit_event_path(event) expect(page).to have_text('Du bist nicht authorisiert diese Aktion auszuführen.') end it 'should preselect the event kind' do login_as(FactoryGirl.create(:user, role: :organizer), :scope => :user) event = FactoryGirl.create(:event, hidden: false) visit edit_event_path(event) expect(find_field(I18n.t('events.type.public'))[:checked]).to_not be_nil end it 'should display all existing date ranges' do login_as(FactoryGirl.create(:user, role: :organizer), :scope => :user) event = FactoryGirl.create(:event, :with_two_date_ranges) visit edit_event_path(event.id) page.assert_selector('[name="event[date_ranges_attributes][][start_date]"]', count: 2) end it 'should save edits to the date ranges' do login_as(FactoryGirl.create(:user, role: :organizer), :scope => :user) event = FactoryGirl.create(:event, :with_two_date_ranges) date_start = Date.current.next_year date_end = Date.tomorrow.next_year visit edit_event_path(event.id) within page.find('#event-date-pickers').first('div') do fill_in "event[date_ranges_attributes][][start_date]", with: date_start fill_in "event[date_ranges_attributes][][end_date]", with: date_end end click_button I18n.t('events.form.update') expect(page).to have_text (DateRange.new start_date: date_start, end_date: date_end) end it "should allow editing past events" do login_as(FactoryGirl.create(:user, role: :organizer), :scope => :user) event = FactoryGirl.create(:event) visit edit_event_path(event.id) fill_in 'event_application_deadline', :with => Date.yesterday.prev_day(5) fill_in "event[date_ranges_attributes][][start_date]", with: Date.yesterday.prev_day fill_in "event[date_ranges_attributes][][end_date]", with: Date.yesterday click_button I18n.t('events.form.update') expect(page).to_not have_text(I18n.t('errors.form_invalid.one')) end end describe 'printing badges' do before :each do login_as(FactoryGirl.create(:user, role: :organizer), :scope => :user) @event = FactoryGirl.create(:event) @users = 12.times.collect do user = FactoryGirl.create(:user_with_profile) FactoryGirl.create(:application_letter, :accepted, user: user, event: @event) user end visit badges_event_path(@event) end it 'creates a pdf with the selected names' do @users.each do |u| find(:css, "#selected_ids_[value='#{u.id}']").set(true) if u.id.even? end select(I18n.t('events.badges.full_name')) click_button I18n.t('events.badges.print') strings = PDF::Inspector::Text.analyze(page.body).strings @users.each do |u| if u.id.even? expect(strings).to include(u.profile.name) else expect(strings).not_to include(u.profile.name) end end end it 'uses the correct name format' do all(:css, '#selected_ids_').each { |check| check.set(true) } select(I18n.t('events.badges.last_name')) click_button I18n.t('events.badges.print') strings = PDF::Inspector::Text.analyze(page.body).strings @users.each do |u| expect(strings).to include(u.profile.last_name) expect(strings).not_to include(u.profile.first_name) end end it "selects all participants when the 'select all' checkbox is checked", js: true do check('select-all-print') all('input[type=checkbox].selected_ids').each { |checkbox| expect(checkbox).to be_checked } uncheck('select-all-print') all('input[type=checkbox].selected_ids').each { |checkbox| expect(checkbox).not_to be_checked } end it 'creates a pdf with the correct schools' do all(:css, '#selected_ids_').each { |check| check.set(true) } check('show_organisation') click_button I18n.t('events.badges.print') strings = PDF::Inspector::Text.analyze(page.body).strings @users.each { |u| expect(strings).to include(ApplicationLetter.where(event: @event, user: u).first.organisation) } end it 'does not horribly crash and burn when colors are selected' do #testing if the actual colors are used is kinda hard all(:css, '#selected_ids_').each { |check| check.set(true) } check('show_color') click_button I18n.t('events.badges.print') end it 'does not throw an error with a logo' do attach_file(:logo_upload, './spec/testfiles/actual.jpg') all(:css, '#selected_ids_').each { |check| check.set(true) } click_button I18n.t('events.badges.print') end it 'shows an error message if logo is wrong filetype' do attach_file(:logo_upload, './spec/testfiles/fake.jpg') all(:css, '#selected_ids_').each { |check| check.set(true) } click_button I18n.t('events.badges.print') expect(page).to have_current_path(badges_event_path(@event)) expect(page).to have_text(I18n.t('events.badges.wrong_file_format')) end it 'shows an error message if no participant was selected' do all(:css, '#selected_ids_').each { |check| check.set(false) } click_button I18n.t('events.badges.print') expect(page).to have_current_path(badges_event_path(@event)) expect(page).to have_text(I18n.t('events.badges.no_users_selected')) end end end
hpi-swt2/workshop-portal
spec/features/event_spec.rb
Ruby
mit
16,955
<?php /** * The contents of this file was generated using the WSDLs as provided by eBay. * * DO NOT EDIT THIS FILE! */ namespace DTS\eBaySDK\Trading\Types; /** * * @property \DTS\eBaySDK\Trading\Enums\PaymentStatusCodeType $eBayPaymentStatus * @property \DateTime $LastModifiedTime * @property \DTS\eBaySDK\Trading\Enums\BuyerPaymentMethodCodeType $PaymentMethod * @property \DTS\eBaySDK\Trading\Enums\CompleteStatusCodeType $Status * @property boolean $IntegratedMerchantCreditCardEnabled * @property \DTS\eBaySDK\Trading\Types\EBayPaymentMismatchDetailsType $eBayPaymentMismatchDetails * @property \DTS\eBaySDK\Trading\Enums\BuyerPaymentInstrumentCodeType $PaymentInstrument */ class CheckoutStatusType extends \DTS\eBaySDK\Types\BaseType { /** * @var array Properties belonging to objects of this class. */ private static $propertyTypes = [ 'eBayPaymentStatus' => [ 'type' => 'string', 'repeatable' => false, 'attribute' => false, 'elementName' => 'eBayPaymentStatus' ], 'LastModifiedTime' => [ 'type' => 'DateTime', 'repeatable' => false, 'attribute' => false, 'elementName' => 'LastModifiedTime' ], 'PaymentMethod' => [ 'type' => 'string', 'repeatable' => false, 'attribute' => false, 'elementName' => 'PaymentMethod' ], 'Status' => [ 'type' => 'string', 'repeatable' => false, 'attribute' => false, 'elementName' => 'Status' ], 'IntegratedMerchantCreditCardEnabled' => [ 'type' => 'boolean', 'repeatable' => false, 'attribute' => false, 'elementName' => 'IntegratedMerchantCreditCardEnabled' ], 'eBayPaymentMismatchDetails' => [ 'type' => 'DTS\eBaySDK\Trading\Types\EBayPaymentMismatchDetailsType', 'repeatable' => false, 'attribute' => false, 'elementName' => 'eBayPaymentMismatchDetails' ], 'PaymentInstrument' => [ 'type' => 'string', 'repeatable' => false, 'attribute' => false, 'elementName' => 'PaymentInstrument' ] ]; /** * @param array $values Optional properties and values to assign to the object. */ public function __construct(array $values = []) { list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values); parent::__construct($parentValues); if (!array_key_exists(__CLASS__, self::$properties)) { self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes); } if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) { self::$xmlNamespaces[__CLASS__] = 'xmlns="urn:ebay:apis:eBLBaseComponents"'; } $this->setValues(__CLASS__, $childValues); } }
chain24/ebayprocess-lumen
vendor/dts/ebay-sdk-php/src/Trading/Types/CheckoutStatusType.php
PHP
mit
3,035
class CouldNotSendError(Exception): pass class AlertIDAlreadyInUse(Exception): pass class AlertBackendIDAlreadyInUse(Exception): pass class InvalidApplicableUsers(Exception): pass
jiaaro/django-alert
alert/exceptions.py
Python
mit
180
/* * The MIT License * * Copyright 2015 user. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.fakekoji.core.utils; import java.io.File; import java.io.FileFilter; public class FileFileFilter implements FileFilter { public FileFileFilter() { } @Override public boolean accept(File pathname) { return !pathname.isDirectory(); } }
judovana/jenkins-scm-koji-plugin
fake-koji/src/main/java/org/fakekoji/core/utils/FileFileFilter.java
Java
mit
1,407
#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" // Copyright year (2009-this) // Todo: update this when changing our copyright comments in the source const int ABOUTDIALOG_COPYRIGHT_YEAR = 2014; AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("2011-%1 Litecoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR) + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("%1 The The Panda Coin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR)); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); }
chaosagent/pandacoin
src/qt/aboutdialog.cpp
C++
mit
1,047
require 'yaml' require 'json' require 'cucumber/cucumber_expressions/cucumber_expression_tokenizer' require 'cucumber/cucumber_expressions/errors' module Cucumber module CucumberExpressions describe 'Cucumber expression tokenizer' do Dir['testdata/tokens/*.yaml'].each do |testcase| expectation = YAML.load_file(testcase) # encoding? it "#{testcase}" do tokenizer = CucumberExpressionTokenizer.new if expectation['exception'].nil? tokens = tokenizer.tokenize(expectation['expression']) token_hashes = tokens.map{|token| token.to_hash} expect(token_hashes).to eq(JSON.parse(expectation['expected'])) else expect { tokenizer.tokenize(expectation['expression']) }.to raise_error(expectation['exception']) end end end end end end
cucumber/cucumber-expressions-ruby
spec/cucumber/cucumber_expressions/cucumber_expression_tokenizer_spec.rb
Ruby
mit
863
/* * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <jni.h> #include <webp/demux.h> #include <webp/decode.h> #include "exceptions.h" #include "decoded_image.h" #include "streams.h" #include "webp_codec.h" namespace facebook { namespace imagepipeline { namespace webp { /** * Uses libwebp to extract xmp metadata. */ const std::vector<uint8_t> extractMetadata( JNIEnv* env, std::vector<uint8_t>& image_data) { // Create WebPDemux from provided data. // It is "index" of all chunks. It stores // list of pointers to particular chunks, but does // not copy memory from provided WebPData. WebPData webpdata = {image_data.data(), image_data.size()}; // Thsnks to using RAII we do not need to worry about // releasing WebPDemuxer structure auto demux = std::unique_ptr<WebPDemuxer, decltype(&WebPDemuxDelete)>{ WebPDemux(&webpdata), WebPDemuxDelete}; THROW_AND_RETURNVAL_IF( demux == nullptr, "Could not create WebPDemux from image. This webp might be malformed.", {}); // find xmp chunk WebPChunkIterator chunk_iterator; if (!WebPDemuxGetChunk(demux.get(), "XMP ", 1, &chunk_iterator)) { // we failed to find "XMP " chunk - don't worry, maybe it was not // there. Let the transcode proceed WebPDemuxReleaseChunkIterator(&chunk_iterator); return {}; } // we managed to find "XMP " chunk, let's return its size and pointer to it const unsigned int metadata_length = chunk_iterator.chunk.size; const uint8_t* metadata_ptr = chunk_iterator.chunk.bytes; WebPDemuxReleaseChunkIterator(&chunk_iterator); // If XMP chunk contains no data then return nullptr. if (metadata_length == 0) { return {}; } return {metadata_ptr, metadata_ptr + metadata_length}; } std::unique_ptr<DecodedImage> decodeWebpFromInputStream( JNIEnv* env, jobject is, PixelFormat pixel_format) { // get image into decoded heap auto encoded_image = readStreamFully(env, is); RETURNVAL_IF_EXCEPTION_PENDING({}); // extract metadata auto metadata = extractMetadata(env, encoded_image); RETURNVAL_IF_EXCEPTION_PENDING({}); // get pixels int image_width = 0; int image_height = 0; uint8_t* raw_pixels = nullptr; switch (pixel_format) { case PixelFormat::RGB: raw_pixels = WebPDecodeRGB( encoded_image.data(), encoded_image.size(), &image_width, &image_height); break; case PixelFormat::RGBA: raw_pixels = WebPDecodeRGBA( encoded_image.data(), encoded_image.size(), &image_width, &image_height); break; default: THROW_AND_RETURNVAL_IF(true, "unrecognized pixel format", {}); } auto pixels = pixels_t{raw_pixels, (void(*)(uint8_t*)) &free}; return std::unique_ptr<DecodedImage>{ new DecodedImage{ std::move(pixels), pixel_format, (unsigned int) image_width, (unsigned int) image_height, std::move(metadata)}}; } } } }
s1rius/fresco
static-webp/src/main/jni/static-webp/webp/webp_codec.cpp
C++
mit
3,114
"use strict"; /* * ooiui/static/js/views/science/HighChartsStreamingDataView.js */ var HighchartsStreamingContainerView = Backbone.View.extend({ subviews : [], showControls: true, initialize: function(options) { if (options && 'showControls' in options){ this.showControls = options.showControls; } _.bindAll(this, "render", "add","remove"); this.render(); }, render: function() { this.$el.html("<div class='streaming-plot-container-header'><div class='streaming-plot-container-contents'></div></div>"); }, add: function(streamModel) { var self = this; if (self.subviews.length >= 5){ return false; } var refExists = false; var streamPlotAdded = false; _.each(self.subviews,function(currentView){ var currentRef = currentView.model.get('reference_designator'); var currentStream = currentView.model.get('stream_name'); if (currentRef == streamModel.get('reference_designator') && currentStream == streamModel.get('stream_name') ){ //check to see if the reference designator already exists refExists= true; } }); if (!refExists){ var subview = new HighchartsStreamingDataOptionsView({ model: streamModel, showControls: self.showControls }); subview.render(); this.subviews.push(subview); this.$el.find('.streaming-plot-container-contents').append(subview.el); streamPlotAdded = true; } return streamPlotAdded }, getSelectedStreams : function(){ var self = this; var selectedStreamModelCollection = new StreamCollection(); _.each(self.subviews,function(currentView,i){ selectedStreamModelCollection.add(currentView.model); }); return selectedStreamModelCollection; }, remove: function(streamModel) { var self = this; var streamPlotRemoved = false; _.each(self.subviews,function(currentView,i){ var currentRef = currentView.model.get('reference_designator'); var currentStream = currentView.model.get('stream_name'); if (currentRef == streamModel.get('reference_designator') && currentStream == streamModel.get('stream_name')){ //check to see if the reference designator already exists if (i > -1) { //de render and remove for the list currentView.derender(); self.subviews.splice(i, 1); streamPlotRemoved= true; } } }); return streamPlotRemoved; }, }); var HighchartsStreamingDataOptionsView = Backbone.View.extend({ showControls: true, initialize: function(options) { if (options && options.model){ this.model = options.model; } if (options && 'showControls' in options){ this.showControls = options.showControls; } _.bindAll(this,'render','onPlayClick','onRemoveClick','onPauseClick','onHideChart'); }, events:{ 'click #streamingClose': 'onRemoveClick', 'click #playStream': 'onPlayClick', 'click #pauseStream': 'onPauseClick', 'click #download-plot' : 'plotDownloads', 'click #streamingHide' : 'onHideChart' }, onHideChart:function(){ if (this.$el.find("#streamingHide").hasClass('fa-chevron-circle-down')){ this.$el.find("#streamingHide").removeClass('fa-chevron-circle-down').addClass('fa-chevron-circle-up'); }else{ this.$el.find("#streamingHide").removeClass('fa-chevron-circle-up').addClass('fa-chevron-circle-down'); } this.$el.find('#streamingDataPlot').toggle( "slow"); }, onRemoveClick:function(){ ooi.trigger('streamPlot:removeStream',this.model); }, plotDownloads: function(e) { event.preventDefault(); var self = this; self.onPauseClick(); if ( self.streamingDataView ){ var chart = self.streamingDataView.chart; var fileName = chart.title.textStr + '_' + chart.subtitle.textStr; chart.exportChart({type: 'image/png', filename: fileName}); } }, onPlayClick:function(){ var self = this; if (self.getVariableList().length>0){ this.$el.find('#playStream').prop('disabled', true); if (self.streamingDataView.isRendered){ self.streamingDataView.chart.showLoading(); self.streamingDataView.chart.isLoading=true; self.streamingDataView.updateVariable(self.getVariableList()); self.streamingDataView.resume(); }else{ self.streamingDataView.updateVariable(self.getVariableList()); self.streamingDataView.render(); } this.$el.find('#pauseStream').prop('disabled', false); this.$el.find('#paramSelection').attr('disabled',true); this.$el.find('.selectpicker').selectpicker('refresh'); } }, onPauseClick:function(){ var self = this this.$el.find('#pauseStream').prop('disabled', true); self.streamingDataView.abort(); this.$el.find('#playStream').prop('disabled', false); this.$el.find('#paramSelection').attr('disabled',false); this.$el.find('.selectpicker').selectpicker('refresh'); }, template: JST['ooiui/static/js/partials/HighChartsStreamingDataOptionsView.html'], initialRender: function() { this.$el.html('<i class="fa fa-spinner fa-spin" style="margin-top:80px;margin-left:50%;font-size:90px;"> </i>'); return this; }, getVariableList:function(){ var self = this; var selectedItem = self.$el.find("#paramSelection option:selected"); var selected = []; $(selectedItem).each(function(index){ selected.push({'variable':$(this).data('params'),'prettyname':$(this).text()}); }); return selected; }, render: function() { var self = this; this.$el.html(this.template({streamModel:self.model,showControls:self.showControls})); var param_list = [], parameterhtml = "", shape = self.model.get('variables_shape'), autoPlot = false; var paramCount = 0; parameterhtml += "<optgroup label='Derived'>" for (var i = 0; i < _.uniq(self.model.get('variables')).length; i++) { if (param_list.indexOf(self.model.get('variables')) == -1){ if (shape[i] === "function"){ var parameterId = self.model.get('parameter_id')[i]; var units = self.model.get('units')[i]; var variable = self.model.get('variables')[i]; var displayName; try{ displayName = self.model.get('parameter_display_name')[i]; } catch(err){ displayName = variable; } //for the case when we have "sal"inity in the variable nanem but we want to remove units of "1" var validUnits = false; var validUnitsClass = "class=invalidParam" if (units.toLowerCase() != "s" && units.toLowerCase() != "1" && units.toLowerCase() != "counts" && units.toLowerCase().indexOf("seconds since") == -1 && units.toLowerCase() != "bytes"){ validUnits = true } if (variable.toLowerCase().indexOf("sal") > -1){ validUnits = true; } if (validUnits){ validUnitsClass = 'class=validParam' } if (variable.indexOf("_timestamp") == -1){ if (variable.toLowerCase() != "time"){ if ( paramCount < 4 && validUnits && (variable.indexOf('oxygen') > -1 || variable.indexOf('temperature') > -1 || variable.indexOf('velocity') > -1 || variable.indexOf('conductivity') > -1 || variable.indexOf('current') > -1 || variable.indexOf('voltage') > -1 || variable.indexOf('pressure') > -1 || variable.indexOf('ang_rate') > -1 || variable.indexOf('coefficient') > -1 || variable.indexOf('chlorophyll') > -1 || variable.indexOf('par') > -1 || variable.indexOf('heat') > -1 )){ parameterhtml+= "<option "+validUnitsClass+" selected pid='"+ parameterId +"'data-params='" + variable + "' data-subtext='"+ units +"' >"+ displayName +"</option>"; paramCount++; } else { parameterhtml+= "<option "+validUnitsClass+" pid='"+ parameterId +"'data-params='" + variable + "' data-subtext='"+ units +"' >"+ displayName +"</option>"; } param_list.push(variable); } } } } } parameterhtml += "</optgroup>" //Now get non derived parameters parameterhtml += "<optgroup label='Non Derived'>" for (var i = 0; i < _.uniq(self.model.get('variables')).length; i++) { if (param_list.indexOf(self.model.get('variables')) == -1){ if (shape[i] != "function"){ var parameterId = self.model.get('parameter_id')[i]; var units = self.model.get('units')[i]; var variable = self.model.get('variables')[i]; var displayName; try{ displayName = self.model.get('parameter_display_name')[i]; } catch(err){ displayName = variable; } //for the case when we have "sal"inity in the variable nanem but we want to remove units of "1" var validUnits = false; var validUnitsClass = "class=invalidParam"; if (units.toLowerCase() != "s" && units.toLowerCase() != "1" && units.toLowerCase() != "counts" && units.toLowerCase().indexOf("seconds since") == -1 && units.toLowerCase() != "bytes"){ validUnits = true } if (variable.toLowerCase().indexOf("sal") > -1){ validUnits = true; } if (validUnits){ validUnitsClass = 'class=validParam' } if (variable.toLowerCase() != "time"){ if ( paramCount < 4 && ( parameterhtml.indexOf("<optgroup label='Derived'></optgroup>") > -1 ) && validUnits && (variable.indexOf('oxygen') > -1 || variable.indexOf('temperature') > -1 || variable.indexOf('velocity') > -1 || variable.indexOf('conductivity') > -1 || variable.indexOf('current') > -1 || variable.indexOf('voltage') > -1 || variable.indexOf('pressure') > -1 || variable.indexOf('ang_rate') > -1 || variable.indexOf('coefficient') > -1 || variable.indexOf('chlorophyll') > -1 || variable.indexOf('par') > -1) ) { parameterhtml+= "<option "+validUnitsClass+" selected pid='"+ parameterId +"'data-params='" + variable + "' data-subtext='"+ units +"' >"+ displayName +"</option>"; paramCount++; } else { parameterhtml+= "<option "+validUnitsClass+" pid='"+ parameterId +"'data-params='" + variable + "' data-subtext='"+ units +"' >"+ displayName +"</option>"; } param_list.push(variable); } } } } parameterhtml += "</optgroup>" self.$el.find('#paramSelection').html(parameterhtml) self.$el.find('#paramSelection .invalidParam').attr('disabled','disabled'); self.$el.find('#paramSelection').selectpicker('refresh'); this.streamingDataView = new HighchartsStreamingDataView({ model: self.model, el: self.$el.find('#streamingDataPlot'), variable: self.getVariableList() }); this.$el.find('#playStream').click(); setTimeout(function (){ $(document).resize() }, 100); }, derender: function() { this.streamingDataView.abort(); this.streamingDataView.remove(); this.streamingDataView.unbind(); this.streamingDataView.chart = null; this.streamingDataView.$el.remove(); this.streamingDataView = null; this.remove(); this.unbind(); if (this.model) this.model.off(); } }); var HighchartsStreamingDataView = Backbone.View.extend({ multiRequest: true, isRendered:false, initialize: function(options) { var self = this; this.title = options && options.title || "Chart"; this.title_style = options && options.title_style || { }; this.subtitle = options && options.subtitle || ""; _.bindAll(this, "onClick",'requestData','abort','updateDateTimes','getUrl','updateVariable','resume'); var dt = moment().utc(); var dt2Str = self.getEndDate(dt,0); var dt1Str = self.getStartDate(dt,300); self.variable = options.variable; self.variable_list = []; _.each(self.variable,function(data_variable,vv){ self.variable_list.push(data_variable['variable']); }); this.ds = new DataSeriesCollection([],{'stream':this.model.get('stream_name'),'ref_des':this.model.get('ref_des'), 'xparameters':['time'],'yparameters':self.variable_list, 'startdate':dt1Str,'enddate':dt2Str}); }, getStartDate:function(dt,rm_seconds){ //start date return dt.subtract(rm_seconds, 'seconds').format("YYYY-MM-DDTHH:mm:ss.000")+"Z" }, getEndDate:function(dt,rm_seconds){ //needs to be first, previous 10 seconds return dt.subtract(rm_seconds, 'seconds').format("YYYY-MM-DDTHH:mm:ss.000")+"Z" }, updateVariable:function(variable){ var self = this; self.variable = variable; self.variable_list = []; _.each(self.variable,function(data_variable,vv){ self.variable_list.push(data_variable['variable']); }); self.ds.yparameters = [self.variable_list]; self.resetAxis = true; }, updateDateTimes:function(){ var self = this; //update datetime using new moment dates var dt = moment().utc(); var dt2Str = self.getEndDate(dt,0); if (self.overrideStDate){ //override start date if data points exceed 0 var dt1Str = self.getStartDate(dt,300); this.ds.startdate = dt1Str; } this.ds.enddate = dt2Str; }, onClick: function(e, point) { //this.trigger('onClick', e, point); }, abort:function(){ //kill the request, if its availble this.multiRequest = false; try{ this.xhr.onreadystatechange = null; this.xhr.abort() }catch(e){ } }, resume:function(){ //kill the request this.multiRequest = true; this.overrideStDate = true; this.requestData(); }, getUrl:function(){ var self = this; self.updateDateTimes(); return this.ds.url(); }, requestData: function() { var self = this; self.xhr = $.ajax({ url: self.getUrl(), cache: false, error: function(XMLHttpRequest, textStatus, errorThrown) { // if (errorThrown!="abort"){ self.$el.parent().parent().parent().find('#pauseStream').click(); self.$el.find('.highcharts-container .highcharts-loading span').text('Error Loading...'); bootbox.dialog({ title: "Error Getting Data From Stream", message: "There was an error obtaining the stream data from uframe", }); } }, success: function(points) { if (self.multiRequest){ if (self.isLoading){ self.chart.hideLoading(); } var point = null; if (self.resetAxis){ for (var i = 0; i < 4; i++) { var series = self.chart.series[i]; self.chart.yAxis[i].update({ labels: {enabled: false}, title: {text: null} }); self.chart.series[i].setData([]); self.chart.series[i].hide(); self.chart.series[i].options.showInLegend = false; self.chart.series[i].legendItem = null; self.chart.legend.destroyItem(self.chart.series[i]); } } self.chart.legend.render(); _.each(self.variable,function(data_variable,vv){ var series = self.chart.series[vv]; var shift = false; var shift = self.chart.series[vv].data.length > 200; if (self.resetAxis){ //reset the axis and some of the contents series.name = data_variable['prettyname']; //self.chart.legend.allItems[vv].update({name:series.name}); series.options.showInLegend = true; self.chart.yAxis[vv].update({ labels: {enabled: true}, title: {text:points['units'][self.variable_list[vv]]} }); series.options.units = points['units'][self.variable_list[vv]]; self.chart.series[vv].show(); self.chart.redraw(); self.chart.legend.renderItem(series); self.chart.legend.render(); } //only override the data if their are points available self.overrideStDate = true; if (points['data'].length > 0){ var dx= null; self.overrideStDate = false; for (var i = 0; i < points['data'].length; i++) { var x = points['data'][i]['time']; var y = points['data'][i][self.variable_list[vv]]; x -= 2208988800; x = x*1000; dx= moment.utc(x); point = [dx._i,y] if (i < points['data'].length-1){ self.chart.series[vv].addPoint(point, false, shift); }else{ self.chart.series[vv].addPoint(point, true, shift); } } //fix start date self.ds.startdate = moment.utc(x).format("YYYY-MM-DDTHH:mm:ss.000")+"Z" } }); if (self.resetAxis){ self.chart.redraw(); self.resetAxis = false; } if (self.multiRequest){ // call it again after (X) seconds setTimeout(self.requestData, 2000); } } }, cache: false }); }, render: function() { var self = this; self.isRendered = true; self.resetAxis = true; self.isLoading = true; var formatter = d3.format(".2f"); var yAxisList = []; var seriesList = []; for (var i = 0; i < 4; i++) { var op = !((i+1) % 2); var gridWidth = 1; if (i>0){ gridWidth = 0; } yAxisList.push({ gridLineWidth:gridWidth, labels: { format: '{value:.2f}', style: { color: Highcharts.getOptions().colors[i] } }, minPadding: 0.2, maxPadding: 0.2, title: { text: null, margin: 80, style: { color: Highcharts.getOptions().colors[i] } }, opposite: op }) seriesList.push({ yAxis: i, name: "unknown", data: [] }); } self.chart = new Highcharts.Chart({ chart: { renderTo: self.el, defaultSeriesType: 'line', events: { load: self.requestData } }, credits: { enabled: false }, loading: { labelStyle: { //color: 'black' }, style: { //backgroundColor: 'lightblue', //opacity: 0.4, }, hideDuration: 500, showDuration: 1000, }, plotOptions: { line: { marker: { enabled: false, } } }, title: { text: self.model.get('display_name') }, subtitle: { text: self.model.get('stream_name') }, legend: { align: 'left' }, exporting: { //Enable exporting images enabled: true, scale: 1, enableImages: true, legend:{ enabled:true }, chartOptions: { chart: { width: 1400, height: 400, events: { load: function () { var chart = this; $.each(chart.series,function(i,series) { series.name = self.chart.series[i].name chart.legend.renderItem(series); }); chart.legend.render(); } } }, } }, xAxis: [{ type: 'datetime', tickPixelInterval: 150, maxZoom: 20 * 1000, title: { text: 'Date (UTC)' } }], tooltip: { useHTML: true, formatter: function() { var x = this.x; var s = ''; s+='<p><b>Time: '+Highcharts.dateFormat('%Y-%m-%d %H:%M:%S UTC', this.x) +'</b></p><p>'; _.each(self.chart.series,function(series) { if (series.visible) { // Assume the data is ordered by time. Find the 1st value that is >= x. var xy = _.find(series.data,function(o){return o.x >= x}); if (xy) { s += '<span style="color: ' + series.color + ';">' + series.name + '</span>' + ': ' + formatter(xy.y)+ '</p>'; } } }); return s; }, shared: true, crosshairs : [true,false] }, yAxis: yAxisList, series: seriesList }); self.chart.showLoading(); } });
FBRTMaka/ooi-ui
ooiui/static/js/views/science/HighChartsStreamingDataView.js
JavaScript
mit
23,076
[assembly: Microsoft.Xrt.Runtime.NativeType("System.Diagnostics.Tracing.*")] namespace Microsoft.Protocols.TestSuites.MS_OXCFXICS { using Microsoft.Modeling; using Microsoft.Protocols.TestSuites.Common; /// <summary> /// Model program. /// </summary> public static class Model { #region Variables /// <summary> /// Record the SHOULD/MAY requirements container. /// </summary> private static MapContainer<int, bool> requirementContainer = new MapContainer<int, bool>(); /// <summary> /// Record the connections data container. /// </summary> private static MapContainer<int, ConnectionData> connections = new MapContainer<int, ConnectionData>(); /// <summary> /// Record the prior operation. /// </summary> private static PriorOperation priorOperation; /// <summary> /// Record whether Message change is partial or not. /// </summary> private static bool messagechangePartail; /// <summary> /// Record the SourceOperation of RopFastTransferDestinationPutBuffer. /// </summary> private static SourceOperation sourOperation; /// <summary> /// Record the prior download operation. /// </summary> private static PriorDownloadOperation priorDownloadOperation; /// <summary> /// Record the prior upload operation. /// </summary> private static PriorOperation priorUploadOperation; /// <summary> /// Record the soft delete message count. /// </summary> private static int softDeleteMessageCount; /// <summary> /// Record the soft delete folder count. /// </summary> private static int softDeleteFolderCount; #endregion /// <summary> /// Gets or sets the priorOperation. /// </summary> public static PriorOperation PriorOperation { get { return priorOperation; } set { priorOperation = value; } } #region Assistant Rop Interfaces /// <summary> /// Determines if the requirement is enabled or not. /// </summary> /// <param name="rsid"> Indicate the requirement ID.</param> /// <param name="enabled"> Indicate the check result whether the requirement is enabled.</param> [Rule(Action = "CheckRequirementEnabled(rsid, out enabled)")] public static void CheckRequirementEnabled(int rsid, out bool enabled) { enabled = Choice.Some<bool>(); requirementContainer.Add(rsid, enabled); } /// <summary> /// This method is used to check whether MAPIHTTP transport is supported by SUT. /// </summary> /// <param name="isSupported">The transport is supported or not.</param> [Rule(Action = "CheckMAPIHTTPTransportSupported(out isSupported)")] public static void CheckMAPIHTTPTransportSupported(out bool isSupported) { isSupported = Choice.Some<bool>(); } /// <summary> /// This method is used to check whether the second system under test is online or not. /// </summary> /// <param name="isSecondSUTOnline"> Indicate the second SUT is online or not.</param> [Rule(Action = "CheckSecondSUTOnline(out isSecondSUTOnline)")] public static void CheckSecondSUTOnline(out bool isSecondSUTOnline) { isSecondSUTOnline = Choice.Some<bool>(); } /// <summary> /// Connect to the server. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="connectionType">The type of connection.</param> [Rule(Action = "Connect(serverId, connectionType)")] public static void Connect(int serverId, ConnectionType connectionType) { // Initialize ConnectionData. ConnectionData newConnection = new ConnectionData { FolderContainer = new Sequence<AbstractFolder>(), AttachmentContainer = new Sequence<AbstractAttachment>(), MessageContainer = new Sequence<AbstractMessage>() }; // Create a new ConnectionData. connections.Add(serverId, newConnection); } /// <summary> /// Disconnect the connection to server. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> [Rule(Action = "Disconnect(serverId)")] public static void Disconnect(int serverId) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Disconnect from server. connections.Remove(serverId); } /// <summary> /// Logon the Server. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="flag">The type of logon.</param> /// <param name="logonHandleIndex">The server object handle index.</param> /// <param name="inboxFolderIdIndex">The inbox folder Id index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "Logon(serverId,flag, out logonHandleIndex,out inboxFolderIdIndex)/result")] public static RopResult Logon(int serverId, LogonFlags flag, out int logonHandleIndex, out int inboxFolderIdIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Initialize the return value. logonHandleIndex = AdapterHelper.GetHandleIndex(); inboxFolderIdIndex = AdapterHelper.GetObjectIdIndex(); ConnectionData changeConnection = connections[serverId]; changeConnection.LogonHandleIndex = logonHandleIndex; changeConnection.LogonFolderType = flag; // Initialize the Container of ConnectionData. changeConnection.FolderContainer = new Sequence<AbstractFolder>(); changeConnection.MessageContainer = new Sequence<AbstractMessage>(); changeConnection.AttachmentContainer = new Sequence<AbstractAttachment>(); changeConnection.DownloadContextContainer = new Sequence<AbstractDownloadInfo>(); changeConnection.UploadContextContainer = new Sequence<AbstractUploadInfo>(); // Create Inbox folder and set value for abstractInboxfolder. AbstractFolder inboxfolder = new AbstractFolder { FolderIdIndex = inboxFolderIdIndex, FolderPermission = PermissionLevels.ReadAny }; // Add inbox folder to FolderContainer. changeConnection.FolderContainer = changeConnection.FolderContainer.Add(inboxfolder); connections[serverId] = changeConnection; RopResult result = RopResult.Success; return result; } /// <summary> /// Open a specific message. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="objHandleIndex">The handle index folder object which the message in. </param> /// <param name="folderIdIndex">The folder id index of which the specific message in.</param> /// <param name="messageIdIndex">The message id index.</param> /// <param name="openMessageHandleIndex">The message handle index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "OpenMessage(serverId, objHandleIndex, folderIdIndex, messageIdIndex,out openMessageHandleIndex)/result")] public static RopResult OpenMessage(int serverId, int objHandleIndex, int folderIdIndex, int messageIdIndex, out int openMessageHandleIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].LogonHandleIndex > 0); Condition.IsTrue(connections[serverId].FolderContainer.Count > 0); Condition.IsTrue(connections[serverId].MessageContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; openMessageHandleIndex = 0; // Get information of ConnectionData. ConnectionData changeConnection = connections[serverId]; // Identify whether the current message is existent or not. AbstractMessage currentMessage = new AbstractMessage(); bool ismessagExist = false; // Record current message. int messageIndex = 0; foreach (AbstractMessage tempMessage in changeConnection.MessageContainer) { if (tempMessage.MessageIdIndex == messageIdIndex) { ismessagExist = true; currentMessage = tempMessage; messageIndex = changeConnection.MessageContainer.IndexOf(tempMessage); } } if (ismessagExist) { // Set value to current folder. currentMessage.MessageHandleIndex = AdapterHelper.GetHandleIndex(); openMessageHandleIndex = currentMessage.MessageHandleIndex; // Update current message. changeConnection.MessageContainer = changeConnection.MessageContainer.Update(messageIndex, currentMessage); connections[serverId] = changeConnection; result = RopResult.Success; } return result; } /// <summary> /// Open specific folder. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="objHandleIndex">The server object handle index.</param> /// <param name="folderIdIndex">The folder id index.</param> /// <param name="inboxFolderHandleIndex">The folder handle index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "OpenFolder(serverId, objHandleIndex, folderIdIndex, out inboxFolderHandleIndex)/result")] public static RopResult OpenFolder(int serverId, int objHandleIndex, int folderIdIndex, out int inboxFolderHandleIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].LogonHandleIndex > 0); Condition.IsTrue(connections[serverId].FolderContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; inboxFolderHandleIndex = 0; // Get information of ConnectionData. ConnectionData changeConnection = connections[serverId]; // Identify whether the CurrentFolder is existent or not. AbstractFolder currentfolder = new AbstractFolder(); bool isFolderExist = false; // Record current folder. int folderIndex = 0; foreach (AbstractFolder tempfolder in changeConnection.FolderContainer) { if (tempfolder.FolderIdIndex == folderIdIndex) { isFolderExist = true; currentfolder = tempfolder; folderIndex = changeConnection.FolderContainer.IndexOf(tempfolder); } } if (isFolderExist) { // Set value to current folder. currentfolder.FolderHandleIndex = AdapterHelper.GetHandleIndex(); inboxFolderHandleIndex = currentfolder.FolderHandleIndex; // Initialize data of part of current folder. currentfolder.SubFolderIds = new Set<int>(); currentfolder.MessageIds = new Set<int>(); currentfolder.FolderProperties = new Set<string>(); // Update current folder. changeConnection.FolderContainer = changeConnection.FolderContainer.Update(folderIndex, currentfolder); connections[serverId] = changeConnection; result = RopResult.Success; } return result; } /// <summary> /// Create a folder and return the folder handle created. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="objHandleIndex">The server object handle index.</param> /// <param name="folderName">The new folder's name.</param> /// <param name="folderIdIndex">The folder id index.</param> /// <param name="folderHandleIndex">The new folder's handle index.</param> /// <returns>Indicate the result of this ROP operation</returns> [Rule(Action = "CreateFolder(serverId, objHandleIndex, folderName, out folderIdIndex, out folderHandleIndex)/result")] public static RopResult CreateFolder(int serverId, int objHandleIndex, string folderName, out int folderIdIndex, out int folderHandleIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].LogonHandleIndex > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; folderIdIndex = 0; folderHandleIndex = 0; // Identify whether the Current Folder is existent or not. ConnectionData changeConnection = connections[serverId]; AbstractFolder parentfolder = new AbstractFolder(); bool isParentFolderExist = false; int parentfolderIndex = 0; // Find Current Folder. foreach (AbstractFolder tempfolder in changeConnection.FolderContainer) { if (tempfolder.FolderHandleIndex == objHandleIndex) { isParentFolderExist = true; parentfolder = tempfolder; parentfolderIndex = changeConnection.FolderContainer.IndexOf(tempfolder); } } if (isParentFolderExist) { // Create a new folder. AbstractFolder currentfolder = new AbstractFolder { FolderHandleIndex = AdapterHelper.GetHandleIndex() }; // Set value for new folder folderHandleIndex = currentfolder.FolderHandleIndex; currentfolder.FolderIdIndex = AdapterHelper.GetObjectIdIndex(); folderIdIndex = currentfolder.FolderIdIndex; currentfolder.ParentFolderHandleIndex = parentfolder.FolderHandleIndex; currentfolder.ParentFolderIdIndex = parentfolder.FolderIdIndex; currentfolder.FolderPermission = PermissionLevels.FolderOwner; // Initialize for new folder. currentfolder.SubFolderIds = new Set<int>(); currentfolder.MessageIds = new Set<int>(); currentfolder.ICSStateContainer = new MapContainer<int, AbstractUpdatedState>(); // Update SubFolderIds of parent folder. parentfolder.SubFolderIds = parentfolder.SubFolderIds.Add(currentfolder.FolderIdIndex); // Update parent folder changeConnection.FolderContainer = changeConnection.FolderContainer.Update(parentfolderIndex, parentfolder); // Add new folder to FolderContainer. changeConnection.FolderContainer = changeConnection.FolderContainer.Add(currentfolder); connections[serverId] = changeConnection; if (folderIdIndex > 0) { // Because only if the folder is right can return a valid folderIdIndex, then the requirement is verified. ModelHelper.CaptureRequirement( 1890, @"[In Identifying Objects and Maintaining Change Numbers] On creation, objects in the mailbox are assigned internal identifiers, commonly known as Folder ID structures ([MS-OXCDATA] section 2.2.1.1) for folders."); } result = RopResult.Success; } return result; } /// <summary> /// Create a message and return the message handle created. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="folderHandleIndex">The folder handle index for creating message.</param> /// <param name="folderIdIndex">The folder Id index.</param> /// <param name="associatedFlag">The message is FAI or not.</param> /// <param name="messageHandleIndex">The created message handle index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "CreateMessage(serverId, folderHandleIndex, folderIdIndex, associatedFlag, out messageHandleIndex)/result")] public static RopResult CreateMessage(int serverId, int folderHandleIndex, int folderIdIndex, bool associatedFlag, out int messageHandleIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].LogonHandleIndex > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; messageHandleIndex = -1; // Identify whether the Current Folder is existent or not. ConnectionData changeConnection = connections[serverId]; AbstractFolder parentfolder = new AbstractFolder(); bool isParentFolderExist = false; int parentfolderIndex = 0; // Find current folder. foreach (AbstractFolder tempfolder in changeConnection.FolderContainer) { if (tempfolder.FolderHandleIndex == folderHandleIndex) { isParentFolderExist = true; parentfolder = tempfolder; parentfolderIndex = changeConnection.FolderContainer.IndexOf(tempfolder); } } if (isParentFolderExist) { // Create a new message object. AbstractMessage currentMessage = new AbstractMessage { IsFAImessage = associatedFlag, IsRead = true, FolderHandleIndex = folderHandleIndex, FolderIdIndex = folderIdIndex, MessageHandleIndex = AdapterHelper.GetHandleIndex(), MessageProperties = new Sequence<string>() }; // Set value for new message. // Initialize message properties. messageHandleIndex = currentMessage.MessageHandleIndex; // Update folder changeConnection.FolderContainer = changeConnection.FolderContainer.Update(parentfolderIndex, parentfolder); // Add new message to MessageContainer. changeConnection.MessageContainer = changeConnection.MessageContainer.Add(currentMessage); connections[serverId] = changeConnection; if (currentMessage.MessageHandleIndex > 0) { // Because only if the folder is right can return a valid message handle index, then the requirement is verified. ModelHelper.CaptureRequirement( 1890001, @"[In Identifying Objects and Maintaining Change Numbers] On creation, objects in the mailbox are assigned internal identifiers, commonly known as Message ID structures ([MS-OXCDATA] section 2.2.1.2) for messages."); } result = RopResult.Success; } return result; } /// <summary> /// Create an attachment on specific message object. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server</param> /// <param name="messageHandleIndex">The message handle</param> /// <param name="attachmentHandleIndex">The attachment handle of created</param> /// <returns>Indicate the result of this ROP operation</returns> [Rule(Action = "CreateAttachment(serverId,messageHandleIndex, out attachmentHandleIndex)/result")] public static RopResult CreateAttachment(int serverId, int messageHandleIndex, out int attachmentHandleIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Initialize the return value. RopResult result = RopResult.InvalidParameter; attachmentHandleIndex = -1; // Identify whether the Current message is existent or not. ConnectionData changeConnection = connections[serverId]; AbstractMessage currentMessage = new AbstractMessage(); bool iscurrentMessageExist = false; int currentMessageIndex = 0; // Find current message foreach (AbstractMessage tempMessage in changeConnection.MessageContainer) { if (tempMessage.MessageHandleIndex == messageHandleIndex) { iscurrentMessageExist = true; currentMessage = tempMessage; currentMessageIndex = changeConnection.MessageContainer.IndexOf(tempMessage); } } if (iscurrentMessageExist) { // Create a new attachment. AbstractAttachment currentAttachment = new AbstractAttachment(); // Set value for new attachment. currentMessage.AttachmentCount++; changeConnection.MessageContainer.Update(currentMessageIndex, currentMessage); currentAttachment.AttachmentHandleIndex = AdapterHelper.GetHandleIndex(); attachmentHandleIndex = currentAttachment.AttachmentHandleIndex; // Add new attachment to attachment container. changeConnection.AttachmentContainer = changeConnection.AttachmentContainer.Add(currentAttachment); connections[serverId] = changeConnection; result = RopResult.Success; } // There is no negative behavior specified in this protocol, so this operation always return true. return result; } /// <summary> /// Save the changes property of message. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="messageHandleIndex">The message handle index.</param> /// <param name="messageIdIndex">The message id index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "SaveChangesMessage(serverId, messageHandleIndex, out messageIdIndex)/result")] public static RopResult SaveChangesMessage(int serverId, int messageHandleIndex, out int messageIdIndex) { // The contraction conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].MessageContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; messageIdIndex = -1; // Identify whether the Current message is existent or not. ConnectionData changeConnection = connections[serverId]; AbstractMessage currentMessage = new AbstractMessage(); bool isMessageExist = false; int messageIndex = 0; // Find current message foreach (AbstractMessage tempMesage in changeConnection.MessageContainer) { if (tempMesage.MessageHandleIndex == messageHandleIndex) { isMessageExist = true; currentMessage = tempMesage; messageIndex = changeConnection.MessageContainer.IndexOf(tempMesage); } } if (isMessageExist) { // Find the parent folder of relate message AbstractFolder parentfolder = new AbstractFolder(); int parentfolderIndex = 0; foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if (tempFolder.FolderHandleIndex == currentMessage.FolderHandleIndex) { parentfolder = tempFolder; parentfolderIndex = changeConnection.FolderContainer.IndexOf(tempFolder); } } // If new message then return a new message id. if (currentMessage.MessageIdIndex == 0) { currentMessage.MessageIdIndex = AdapterHelper.GetObjectIdIndex(); // Because if Create a new messageID then the action which convert GID to a short-term internal identifier and assign it to an imported object execute in MS_OXCFXICSAdapter. So cover this requirement here. ModelHelper.CaptureRequirement(1910, "[In Identifying Objects and Maintaining Change Numbers] Convert the GID structure ([MS-OXCDATA] section 2.2.1.3) to a short-term internal identifier and assign it to an imported object, if the external identifier is a GID value."); } // Set value for the current Message messageIdIndex = currentMessage.MessageIdIndex; parentfolder.MessageIds = parentfolder.MessageIds.Add(messageIdIndex); changeConnection.FolderContainer = changeConnection.FolderContainer.Update(parentfolderIndex, parentfolder); // Assign a new Change number. currentMessage.ChangeNumberIndex = ModelHelper.GetChangeNumberIndex(); // Because of executed import operation before execute RopSaveChangesMessage operation. And assign a new changeNumber. So can cover this requirement here. ModelHelper.CaptureRequirement( 1906, @"[In Identifying Objects and Maintaining Change Numbers]Upon successful import of a new or changed object using ICS upload, the server MUST do the following when receiving the RopSaveChangesMessage ROP:Assign the object a new internal change number (PidTagChangeNumber property (section 2.2.1.2.3))."); // Because of it must execute RopSaveChangesMessage operation after the messaging object each time and assign a new changeNumber. So can cover this requirement Spec here. ModelHelper.CaptureRequirement(1898, "[In Identifying Objects and Maintaining Change Numbers]A new change number is assigned to a messaging object each time it is modified."); currentMessage.ReadStateChangeNumberIndex = 0; // Update current Message into MessageContainer changeConnection.MessageContainer = changeConnection.MessageContainer.Update(messageIndex, currentMessage); connections[serverId] = changeConnection; if (priorOperation == MS_OXCFXICS.PriorOperation.RopCreateMessage && messageIndex > 0) { // When the prior operate is create message and in this ROP return a valid messageIDIndex means this requirement verified. ModelHelper.CaptureRequirement( 1890001, @"[In Identifying Objects and Maintaining Change Numbers] On creation, objects in the mailbox are assigned internal identifiers, commonly known as Message ID structures ([MS-OXCDATA] section 2.2.1.2) for messages."); } result = RopResult.Success; } return result; } /// <summary> /// Commits the changes made to the Attachment object. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="attachmentHandleIndex">The attachment handle</param> /// <returns>Indicate the result of this ROP operation</returns> [Rule(Action = "SaveChangesAttachment(serverId,attachmentHandleIndex)/result")] public static RopResult SaveChangesAttachment(int serverId, int attachmentHandleIndex) { // Contraction condition is the Attachment is created successful Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].AttachmentContainer.Count > 0); // Return Success RopResult result = RopResult.Success; return result; } /// <summary> /// Release the object by handle. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="objHandleIndex">The object handle index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "Release(serverId, objHandleIndex)/result")] public static RopResult Release(int serverId, int objHandleIndex) { // The contraction conditions Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // The operation success. return RopResult.Success; } /// <summary> /// Delete the specific folder. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="folderHandleIndex">The folder handle index.</param> /// <param name="folderIdIndex">The folder id index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "DeleteFolder(serverId, folderHandleIndex, folderIdIndex)/result")] public static RopResult DeleteFolder(int serverId, int folderHandleIndex, int folderIdIndex) { // The contraction conditions Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].LogonHandleIndex > 0); Condition.IsTrue(connections[serverId].FolderContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; ConnectionData changeConnection = connections[serverId]; // Identify whether the Current folder and Parent folder are existent or not. AbstractFolder currentfolder = new AbstractFolder(); AbstractFolder parentfolder = new AbstractFolder(); bool isCurrentFolderExist = false; bool isParentFolderExist = false; // Find parent folder. foreach (AbstractFolder tempfolder in changeConnection.FolderContainer) { if (tempfolder.FolderHandleIndex == folderHandleIndex) { isParentFolderExist = true; parentfolder = tempfolder; } } // Find current folder. foreach (AbstractFolder tempfolder in changeConnection.FolderContainer) { if (tempfolder.FolderIdIndex == folderIdIndex) { isCurrentFolderExist = true; currentfolder = tempfolder; } } if (isParentFolderExist && isCurrentFolderExist) { // Remove current folder from SubFolderIds property of parent folder parentfolder.SubFolderIds = parentfolder.SubFolderIds.Remove(currentfolder.FolderIdIndex); // Remove current folder changeConnection.FolderContainer = changeConnection.FolderContainer.Remove(currentfolder); connections[serverId] = changeConnection; result = RopResult.Success; } return result; } /// <summary> /// Get specific property value. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="handleIndex">Identify from which the property will be gotten.</param> /// <param name="propertyTag">A list of propertyTags.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "GetPropertiesSpecific(serverId, handleIndex, propertyTag)/result")] public static RopResult GetPropertiesSpecific(int serverId, int handleIndex, Sequence<string> propertyTag) { // The contraction conditions Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Initialize the return value. RopResult result = RopResult.InvalidParameter; // Identify whether the Current message is existent or not. ConnectionData changeConnection = connections[serverId]; if (connections[serverId].FolderContainer.Count > 0) { result = RopResult.Success; } else if (connections[serverId].MessageContainer.Count > 0) { AbstractMessage currentMessage = new AbstractMessage(); bool ismessageExist = false; int messageIndex = 0; foreach (AbstractMessage tempMesage in changeConnection.MessageContainer) { if (tempMesage.MessageHandleIndex == handleIndex) { ismessageExist = true; currentMessage = tempMesage; messageIndex = changeConnection.MessageContainer.IndexOf(tempMesage); } } if (ismessageExist) { // Set value for MessageProperties currentMessage.MessageProperties = propertyTag; changeConnection.MessageContainer = changeConnection.MessageContainer.Update(messageIndex, currentMessage); connections[serverId] = changeConnection; result = RopResult.Success; } } return result; } /// <summary> /// Set the specific object's property value. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="handleIndex">Server object handle index.</param> /// <param name="propertyTag">The list of property values.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "SetProperties(serverId, handleIndex, propertyTag)/result")] public static RopResult SetProperties(int serverId, int handleIndex, Sequence<string> propertyTag) { // The construction conditions Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].MessageContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; // Get value of current ConnectionData ConnectionData changeConnection = connections[serverId]; // Identify whether the Current message is existent or not. AbstractMessage currentMessage = new AbstractMessage(); bool ismessageExist = false; int messageIndex = 0; // Find current message. foreach (AbstractMessage tempMesage in changeConnection.MessageContainer) { if (tempMesage.MessageHandleIndex == handleIndex) { ismessageExist = true; currentMessage = tempMesage; messageIndex = changeConnection.MessageContainer.IndexOf(tempMesage); } } if (ismessageExist) { foreach (string propertyName in propertyTag) { // Identify whether the property is existent or not in MessageProperties. if (!currentMessage.MessageProperties.Contains(propertyName)) { // Add property to MessageProperties. currentMessage.MessageProperties = currentMessage.MessageProperties.Add(propertyName); } } changeConnection.MessageContainer = changeConnection.MessageContainer.Update(messageIndex, currentMessage); connections[serverId] = changeConnection; result = RopResult.Success; } return result; } /// <summary> /// Modifies the permissions associated with a folder. /// </summary> /// <param name="serverId">The server id</param> /// <param name="folderHandleIndex">index of folder handle in container</param> /// <param name="permissionLevel">The permission level</param> /// <returns>Indicate the result of this ROP operation</returns> [Rule(Action = "ModifyPermissions(serverId, folderHandleIndex, permissionLevel)/result")] public static RopResult ModifyPermissions(int serverId, int folderHandleIndex, PermissionLevels permissionLevel) { // The contraction conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].FolderContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; ConnectionData changeConnection = connections[serverId]; // Identify whether the Current folder is existent or not. AbstractFolder currentfolder = new AbstractFolder(); bool isCurrentFolderExist = false; int currentfolderIndex = 0; // Find current folder foreach (AbstractFolder tempfolder in changeConnection.FolderContainer) { if (tempfolder.FolderHandleIndex == folderHandleIndex) { isCurrentFolderExist = true; currentfolder = tempfolder; currentfolderIndex = changeConnection.FolderContainer.IndexOf(tempfolder); } } if (isCurrentFolderExist) { // Set folder Permission for CurrentFolder. currentfolder.FolderPermission = permissionLevel; changeConnection.FolderContainer = changeConnection.FolderContainer.Update(currentfolderIndex, currentfolder); connections[serverId] = changeConnection; result = RopResult.Success; } return result; } #endregion #region MS-OXCFXICS operation actions /// <summary> /// Define the scope and parameters of the synchronization download operation. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="folderHandleIndex">The folder object handle.</param> /// <param name="synchronizationType">The type of synchronization requested: contents or hierarchy.</param> /// <param name="option">Defines the parameters of a download operation.</param> /// <param name="synchronizationFlag">Flag structure that defines the parameters of the synchronization operation.</param> /// <param name="synchronizationExtraFlag">Extra Flag structure that defines the parameters of the synchronization operation.</param> /// <param name="property">A list of properties and sub objects to exclude or include.</param> /// <param name="downloadcontextHandleIndex">Synchronization download context handle index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "SynchronizationConfigure(serverId, folderHandleIndex, synchronizationType, option, synchronizationFlag, synchronizationExtraFlag,property, out downloadcontextHandleIndex)/result")] public static RopResult SynchronizationConfigure(int serverId, int folderHandleIndex, SynchronizationTypes synchronizationType, SendOptionAlls option, SynchronizationFlag synchronizationFlag, SynchronizationExtraFlag synchronizationExtraFlag, Sequence<string> property, out int downloadcontextHandleIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].FolderContainer.Count > 0); // Initialize return value. RopResult result = RopResult.Success; downloadcontextHandleIndex = -1; if ((option & SendOptionAlls.Invalid) == SendOptionAlls.Invalid && (requirementContainer.ContainsKey(3463) && requirementContainer[3463])) { result = RopResult.InvalidParameter; return result; } // SynchronizationFlag MUST match the value of the Unicode flag from SendOptions field. if ((synchronizationFlag & SynchronizationFlag.Unicode) == SynchronizationFlag.Unicode) { Condition.IsTrue((option & SendOptionAlls.Unicode) == SendOptionAlls.Unicode); } // When SynchronizationType is 0X04 then Servers return 0x80070057. if (synchronizationType == SynchronizationTypes.InvalidParameter) { if (requirementContainer.ContainsKey(2695) && requirementContainer[2695]) { result = RopResult.NotSupported; } else { result = RopResult.InvalidParameter; ModelHelper.CaptureRequirement(2695, "[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] Servers MUST return 0x80070057 if SynchronizationType is 0x04."); } } else if ((synchronizationFlag & SynchronizationFlag.Reserved) == SynchronizationFlag.Reserved) { // When SynchronizationType is Reserved then Servers MUST fail the ROP request. result = RopResult.RpcFormat; ModelHelper.CaptureRequirement(2180, "[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] The server MUST fail the ROP request if the Reserved flag of the SynchronizationFlags field is set."); } else { // Get ConnectionData value. ConnectionData changeConnection = connections[serverId]; // Identify whether the CurrentFolder is existent or not. bool isCurrentFolderExist = false; // Identify whether the Current Folder is existent or not. foreach (AbstractFolder tempfolder in changeConnection.FolderContainer) { if (tempfolder.FolderHandleIndex == folderHandleIndex) { // Set the value to the variable when the current folder is existent. isCurrentFolderExist = true; } } // The condition of CurrentFolder is existent. if (isCurrentFolderExist) { // Initialize the Download information. AbstractDownloadInfo abstractDownloadInfo = new AbstractDownloadInfo { UpdatedState = new AbstractUpdatedState { CnsetRead = new Set<int>(), CnsetSeen = new Set<int>(), CnsetSeenFAI = new Set<int>(), IdsetGiven = new Set<int>() }, DownloadHandleIndex = AdapterHelper.GetHandleIndex() }; // Get the download Handle for download context. downloadcontextHandleIndex = abstractDownloadInfo.DownloadHandleIndex; ModelHelper.CaptureRequirement(669, "[In RopSynchronizationConfigure ROP Response Buffer]OutputServerObject: This value MUST be the synchronization download context."); // Record the flags. abstractDownloadInfo.Sendoptions = option; abstractDownloadInfo.SynchronizationType = synchronizationType; abstractDownloadInfo.Synchronizationflag = synchronizationFlag; abstractDownloadInfo.SynchronizationExtraflag = synchronizationExtraFlag; // Record the Property. abstractDownloadInfo.Property = property; // Record folder handle of related to the download context. abstractDownloadInfo.RelatedObjectHandleIndex = folderHandleIndex; switch (synchronizationType) { // Record synchronizationType value for condition of Synchronization type is Contents. case SynchronizationTypes.Contents: abstractDownloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.contentsSync; abstractDownloadInfo.ObjectType = ObjectType.Folder; break; // Record synchronizationType value for condition of Synchronization type is Hierarchy. case SynchronizationTypes.Hierarchy: abstractDownloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.hierarchySync; abstractDownloadInfo.ObjectType = ObjectType.Folder; break; default: // Condition ofsynchronizationType is invalid parameter. result = RopResult.InvalidParameter; break; } // Condition of the operation return success. if (result == RopResult.Success) { // Add the new value to DownloadContextContainer. changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Add(abstractDownloadInfo); connections[serverId] = changeConnection; priorDownloadOperation = PriorDownloadOperation.RopSynchronizationConfigure; priorOperation = MS_OXCFXICS.PriorOperation.RopSynchronizationConfigure; ModelHelper.CaptureRequirement( 641, @"[In RopSynchronizationConfigure] The RopSynchronizationConfigure ROP ([MS-OXCROPS] section 2.2.13.1) is used to define the synchronization scope and parameters of the synchronization download operation."); } } } return result; } /// <summary> /// Configures the synchronization upload operation. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="folderHandleIndex">The folder object handle index .</param> /// <param name="synchronizationType">The type of synchronization requested: contents or hierarchy.</param> /// <param name="uploadContextHandleIndex">Synchronization upload context handle index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "SynchronizationOpenCollector(serverId, folderHandleIndex, synchronizationType, out uploadContextHandleIndex)/result")] public static RopResult SynchronizationOpenCollector(int serverId, int folderHandleIndex, SynchronizationTypes synchronizationType, out int uploadContextHandleIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].FolderContainer.Count > 0); // Initialize return value RopResult result = RopResult.InvalidParameter; uploadContextHandleIndex = -1; // Get ConnectionData value. ConnectionData changeConnection = connections[serverId]; AbstractFolder currentfolder = new AbstractFolder(); // Identify whether the CurrentFolder is existent or not. bool isCurrentFolderExist = false; // Identify whether the Current Folder is existent or not. foreach (AbstractFolder tempfolder in changeConnection.FolderContainer) { if (tempfolder.FolderHandleIndex == folderHandleIndex) { // Set the value to the variable when the current folder is existent. isCurrentFolderExist = true; currentfolder = tempfolder; } } if (isCurrentFolderExist) { // Initialize the upload information. AbstractUploadInfo abstractUploadInfo = new AbstractUploadInfo { UploadHandleIndex = AdapterHelper.GetHandleIndex() }; uploadContextHandleIndex = abstractUploadInfo.UploadHandleIndex; ModelHelper.CaptureRequirement(778, "[In RopSynchronizationOpenCollector ROP Response Buffer]OutputServerObject: The value of this field MUST be the synchronization upload context."); abstractUploadInfo.SynchronizationType = synchronizationType; abstractUploadInfo.RelatedObjectHandleIndex = folderHandleIndex; abstractUploadInfo.RelatedObjectIdIndex = currentfolder.FolderIdIndex; // Initialize the updatedState information. abstractUploadInfo.UpdatedState.IdsetGiven = new Set<int>(); abstractUploadInfo.UpdatedState.CnsetRead = new Set<int>(); abstractUploadInfo.UpdatedState.CnsetSeen = new Set<int>(); abstractUploadInfo.UpdatedState.CnsetSeenFAI = new Set<int>(); // Add the new value to UploadContextContainer. changeConnection.UploadContextContainer = changeConnection.UploadContextContainer.Add(abstractUploadInfo); connections[serverId] = changeConnection; // Record RopSynchronizationImportHierarchyChange operation. priorOperation = PriorOperation.RopSynchronizationOpenCollector; result = RopResult.Success; if (uploadContextHandleIndex != -1) { // Because if uploadContextHandleIndex doesn't equal -1 and the ROP return success, so only if this ROP success and return a valid handler this requirement will be verified. ModelHelper.CaptureRequirement( 769, @"[In RopSynchronizationOpenCollector ROP] The RopSynchronizationOpenCollector ROP ([MS-OXCROPS] section 2.2.13.7) configures the synchronization upload operation and returns a handle to a synchronization upload context."); } } return result; } /// <summary> /// Imports deletions of messages or folders into the server replica. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server</param> /// <param name="uploadContextHandleIndex">synchronization upload context handle</param> /// <param name="objIdIndexes">all object id</param> /// <param name="importDeleteFlag">Deletions type</param> /// <returns>Indicate the result of this ROP operation</returns> [Rule(Action = "SynchronizationImportDeletes(serverId,uploadContextHandleIndex,objIdIndexes,importDeleteFlag)/result")] public static RopResult SynchronizationImportDeletes(int serverId, int uploadContextHandleIndex, Sequence<int> objIdIndexes, byte importDeleteFlag) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].FolderContainer.Count > 0); if (requirementContainer.ContainsKey(90205002) && requirementContainer[90205002]) { Condition.IsTrue(((ImportDeleteFlags)importDeleteFlag & ImportDeleteFlags.delete) == ImportDeleteFlags.delete); } // Initialize return value. RopResult result = RopResult.InvalidParameter; // When the ImportDeleteFlags flag is set HardDelete by Exchange 2007 then server return 0x80070057. if (importDeleteFlag == (byte)ImportDeleteFlags.HardDelete) { if (requirementContainer.ContainsKey(2593) && requirementContainer[2593]) { result = RopResult.NotSupported; ModelHelper.CaptureRequirement(2593, "[In Appendix A: Product Behavior] <19> Section 2.2.3.2.4.5.1: The HardDelete flag is not supported by Exchange 2003 or Exchange 2007."); return result; } } // When the ImportDeleteFlags flag is an invalid value (0x10) then server returns 0x80070057. if (importDeleteFlag == 0x10) { if (requirementContainer.ContainsKey(2254001) && requirementContainer[2254001]) { result = RopResult.NotSupported; } else { result = RopResult.InvalidParameter; } return result; } // Get ConnectionData value. ConnectionData changeConnection = connections[serverId]; // Create uploadInfo variable. AbstractUploadInfo uploadInfo = new AbstractUploadInfo(); // Identify whether the Current Upload information is existent or not. bool isCurrentUploadinfoExist = false; // Record the current uploadInfo index. int currentUploadIndex = 0; foreach (AbstractUploadInfo tempUploadInfo in changeConnection.UploadContextContainer) { if (tempUploadInfo.UploadHandleIndex == uploadContextHandleIndex) { // Set the value to the variable when the current upload context is existent. isCurrentUploadinfoExist = true; uploadInfo = tempUploadInfo; currentUploadIndex = changeConnection.UploadContextContainer.IndexOf(tempUploadInfo); } } if (isCurrentUploadinfoExist) { // Set the upload information. uploadInfo.ImportDeleteflags = importDeleteFlag; AbstractFolder currentFolder = new AbstractFolder(); // Record the current Folder Index int currentFolderIndex = 0; foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if (tempFolder.FolderHandleIndex == uploadInfo.RelatedObjectHandleIndex) { // Set the value to the variable when the current Folder is existent. currentFolder = tempFolder; currentFolderIndex = changeConnection.FolderContainer.IndexOf(tempFolder); } } foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if ((tempFolder.ParentFolderIdIndex == currentFolder.FolderIdIndex) && objIdIndexes.Contains(tempFolder.FolderIdIndex)) { // Remove current folder from FolderContainer and parent folder when the parent Folder is existent. changeConnection.FolderContainer = changeConnection.FolderContainer.Remove(tempFolder); currentFolder.SubFolderIds = currentFolder.SubFolderIds.Remove(tempFolder.FolderIdIndex); } if (importDeleteFlag == (byte)ImportDeleteFlags.Hierarchy) { softDeleteFolderCount += 1; } } foreach (AbstractMessage tempMessage in changeConnection.MessageContainer) { if ((tempMessage.FolderIdIndex == currentFolder.FolderIdIndex) && objIdIndexes.Contains(tempMessage.MessageIdIndex)) { // Remove current Message from MessageContainer and current folder when current Message is existent. changeConnection.MessageContainer = changeConnection.MessageContainer.Remove(tempMessage); currentFolder.MessageIds = currentFolder.MessageIds.Remove(tempMessage.MessageIdIndex); if (importDeleteFlag == (byte)ImportDeleteFlags.delete) { softDeleteMessageCount += 1; } } } // Update the FolderContainer. changeConnection.FolderContainer = changeConnection.FolderContainer.Update(currentFolderIndex, currentFolder); // Update the UploadContextContainer. changeConnection.UploadContextContainer = changeConnection.UploadContextContainer.Update(currentUploadIndex, uploadInfo); connections[serverId] = changeConnection; result = RopResult.Success; ModelHelper.CaptureRequirement( 2449, @"[In Uploading Changes Using ICS] Value is Success indicates No error occurred, or a conflict has been resolved."); // Because if the result is success means deletions of messages or folders into the server replica imported ModelHelper.CaptureRequirement( 884, @"[In RopSynchronizationImportDeletes ROP] The RopSynchronizationImportDeletes ROP ([MS-OXCROPS] section 2.2.13.5) imports deletions of messages or folders into the server replica."); return result; } return result; } /// <summary> /// Import new folders, or changes to existing folders, into the server replica. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="uploadContextHandleIndex">Upload context handle.</param> /// <param name="parentFolderHandleIndex">Parent folder handle index.</param> /// <param name="properties">Properties to be set.</param> /// <param name="localFolderIdIndex">Local folder id index</param> /// <param name="folderIdIndex">The folder object id index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "SynchronizationImportHierarchyChange(serverId, uploadContextHandleIndex,parentFolderHandleIndex, properties, localFolderIdIndex, out folderIdIndex)/result")] public static RopResult SynchronizationImportHierarchyChange(int serverId, int uploadContextHandleIndex, int parentFolderHandleIndex, Set<string> properties, int localFolderIdIndex, out int folderIdIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].UploadContextContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; folderIdIndex = -1; if (parentFolderHandleIndex == -1) { result = RopResult.NoParentFolder; ModelHelper.CaptureRequirement( 2450, @"[In Uploading Changes Using ICS] Value is NoParentFolder indicates An attempt is being made to upload a hierarchy change for a folder whose parent folder does not yet exist."); } else { // Get ConnectionData value. ConnectionData changeConnection = connections[serverId]; // Record current Upload Information. AbstractUploadInfo currentUploadInfo = new AbstractUploadInfo(); // Identify current Upload handle. bool isCurrentUploadHandleExist = false; foreach (AbstractUploadInfo tempUploadInfo in changeConnection.UploadContextContainer) { if (tempUploadInfo.UploadHandleIndex == uploadContextHandleIndex) { // Set the value to the variable when the current upload context is existent. isCurrentUploadHandleExist = true; currentUploadInfo = tempUploadInfo; } } if (isCurrentUploadHandleExist) { // Initialize the variable AbstractFolder parentfolder = new AbstractFolder(); bool isParentFolderExist = false; int parentfolderIndex = 0; AbstractFolder currentFolder = new AbstractFolder(); bool isFolderExist = false; int currentFolderIndex = 0; // Research the local folder Id. foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if (tempFolder.FolderIdIndex == localFolderIdIndex) { // Set the value to the current Folder variable when the current folder is existent. isFolderExist = true; currentFolder = tempFolder; currentFolderIndex = changeConnection.FolderContainer.IndexOf(tempFolder); } if (tempFolder.FolderIdIndex == currentUploadInfo.RelatedObjectIdIndex) { // Set the value to the parent folder variable when the current parent folder is existent. isParentFolderExist = true; parentfolder = tempFolder; parentfolderIndex = changeConnection.FolderContainer.IndexOf(tempFolder); } } if (isFolderExist & isParentFolderExist) { foreach (string tempProperty in properties) { if (!currentFolder.FolderProperties.Contains(tempProperty)) { // Add Property for folder currentFolder.FolderProperties = currentFolder.FolderProperties.Add(tempProperty); } } // Get the new change Number currentFolder.ChangeNumberIndex = ModelHelper.GetChangeNumberIndex(); // Update the folder Container changeConnection.FolderContainer = changeConnection.FolderContainer.Update(currentFolderIndex, currentFolder); } else { // Create a new folder AbstractFolder newFolder = new AbstractFolder { FolderIdIndex = AdapterHelper.GetObjectIdIndex() }; // Set new folder Id folderIdIndex = newFolder.FolderIdIndex; // Set value for new folder newFolder.FolderProperties = properties; newFolder.ParentFolderHandleIndex = parentfolder.FolderHandleIndex; newFolder.ParentFolderIdIndex = parentfolder.FolderIdIndex; newFolder.SubFolderIds = new Set<int>(); newFolder.MessageIds = new Set<int>(); // Add the new folder to parent folder parentfolder.SubFolderIds = parentfolder.SubFolderIds.Add(newFolder.FolderIdIndex); newFolder.FolderPermission = PermissionLevels.FolderOwner; newFolder.ChangeNumberIndex = ModelHelper.GetChangeNumberIndex(); ModelHelper.CaptureRequirement(1897, "[In Identifying Objects and Maintaining Change Numbers]When a new object is created, it is assigned a change number."); // Update FolderContainer information changeConnection.FolderContainer = changeConnection.FolderContainer.Add(newFolder); changeConnection.FolderContainer = changeConnection.FolderContainer.Update(parentfolderIndex, parentfolder); } // Return Success connections[serverId] = changeConnection; // Record RopSynchronizationImportHierarchyChange operation. priorUploadOperation = PriorOperation.RopSynchronizationImportHierarchyChange; result = RopResult.Success; ModelHelper.CaptureRequirement( 2449, @"[In Uploading Changes Using ICS] Value is Success indicates No error occurred, or a conflict has been resolved."); // Because if the result is success means the folders or changes are imported. ModelHelper.CaptureRequirement( 816, @"[In RopSynchronizationImportHierarchyChange ROP] The RopSynchronizationImportHierarchyChange ROP ([MS-OXCROPS] section 2.2.13.4) is used to import new folders, or changes to existing folders, into the server replica."); } } return result; } /// <summary> /// Import new folders, or changes with conflict PCL to existing folders, into the server replica. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="uploadContextHandleIndex">Upload context handle.</param> /// <param name="parentFolderHandleIndex">Parent folder handle index.</param> /// <param name="properties">Properties to be set.</param> /// <param name="localFolderIdIndex">Local folder id index</param> /// <param name="folderIdIndex">The folder object id index.</param> /// <param name="conflictType">The conflict type to generate.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "SynchronizationImportHierarchyChangeWithConflict(serverId, uploadContextHandleIndex,parentFolderHandleIndex, properties, localFolderIdIndex, out folderIdIndex, conflictType)/result")] public static RopResult SynchronizationImportHierarchyChangeWithConflict(int serverId, int uploadContextHandleIndex, int parentFolderHandleIndex, Set<string> properties, int localFolderIdIndex, out int folderIdIndex, ConflictTypes conflictType) { return SynchronizationImportHierarchyChange(serverId, uploadContextHandleIndex, parentFolderHandleIndex, properties, localFolderIdIndex, out folderIdIndex); } /// <summary> /// Import new messages or changes to existing messages into the server replica. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="uploadContextHandleIndex">A synchronization upload context handle index.</param> /// <param name="messageIdindex">new client message id</param> /// <param name="importFlag">An 8-bit flag .</param> /// <param name="importMessageHandleIndex">The index of handle that indicate the Message object into which the client will upload the rest of the message changes.</param> /// <returns>Indicate the result of this ROP operation</returns> [Rule(Action = "SynchronizationImportMessageChange(serverId, uploadContextHandleIndex,messageIdindex,importFlag, out importMessageHandleIndex)/result")] public static RopResult SynchronizationImportMessageChange(int serverId, int uploadContextHandleIndex, int messageIdindex, ImportFlag importFlag, out int importMessageHandleIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].UploadContextContainer.Count > 0 && connections[serverId].LogonHandleIndex > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; importMessageHandleIndex = -1; if ((importFlag & ImportFlag.InvalidParameter) == ImportFlag.InvalidParameter && requirementContainer.ContainsKey(3509001) && requirementContainer[3509001]) { result = RopResult.InvalidParameter; ModelHelper.CaptureRequirement( 3509001, @"[In Appendix A: Product Behavior] If unknown flags are set, implementation does fail the operation. &lt;44&gt; Section 3.2.5.9.4.2: Exchange 2010, Exchange 2013, Exchange 2016 and Exchange 2019 fail the ROP [RopSynchronizationImportMessageChange] if unknown bit flags are set."); return result; } else if ((importFlag & ImportFlag.InvalidParameter) == ImportFlag.InvalidParameter && requirementContainer.ContainsKey(350900201) && requirementContainer[350900201]) { result = RopResult.Success; ModelHelper.CaptureRequirement( 350900201, @"[In Appendix A: Product Behavior] If unknown flags are set, implementation does not fail the operation. <44> Section 3.2.5.9.4.2: Exchange 2007 do not fail the ROP [RopSynchronizationImportMessageChange] if unknown bit flags are set."); } // Get ConnectionData value. ConnectionData changeConnection = connections[serverId]; AbstractUploadInfo uploadInfo = new AbstractUploadInfo(); // Identify whether the current Upload information is existent or not. bool isCurrentUploadinfoExist = false; // Record current Upload information. int currentUploadIndex = 0; foreach (AbstractUploadInfo tempUploadInfo in changeConnection.UploadContextContainer) { if (tempUploadInfo.UploadHandleIndex == uploadContextHandleIndex) { // Set the value to the current upload context variable when the current upload context is existent. isCurrentUploadinfoExist = true; uploadInfo = tempUploadInfo; currentUploadIndex = changeConnection.UploadContextContainer.IndexOf(tempUploadInfo); } } if (isCurrentUploadinfoExist) { // Create a new Message AbstractMessage currentMessage = new AbstractMessage(); // Identify whether the current message is existent or not. bool isMessageExist = false; // Record the current Message. int currentMessageIndex = 0; foreach (AbstractMessage tempMessage in changeConnection.MessageContainer) { if (tempMessage.MessageIdIndex == messageIdindex) { // Set the value to the variable when the message is existent. isMessageExist = true; currentMessage = tempMessage; currentMessageIndex = changeConnection.MessageContainer.IndexOf(tempMessage); } } if (isMessageExist) { // Set new change number currentMessage.ChangeNumberIndex = ModelHelper.GetChangeNumberIndex(); ModelHelper.CaptureRequirement(1898, "[In Identifying Objects and Maintaining Change Numbers]A new change number is assigned to a messaging object each time it is modified."); // Update the MessageContainer changeConnection.MessageContainer = changeConnection.MessageContainer.Update(currentMessageIndex, currentMessage); } else { // Set the new message handle currentMessage.MessageHandleIndex = AdapterHelper.GetHandleIndex(); // Set property value of abstract message object currentMessage.FolderHandleIndex = uploadInfo.RelatedObjectHandleIndex; currentMessage.FolderIdIndex = uploadInfo.RelatedObjectIdIndex; currentMessage.MessageProperties = new Sequence<string>(); currentMessage.IsRead = true; if ((importFlag & ImportFlag.Normal) == ImportFlag.Normal) { currentMessage.IsFAImessage = false; } if ((importFlag & ImportFlag.Associated) == ImportFlag.Associated) { currentMessage.IsFAImessage = true; // When the Associated is set and the message being imported is an FAI message this requirement is captured. ModelHelper.CaptureRequirement( 813, @"[In RopSynchronizationImportMessageChange ROP Request Buffer] [ImportFlag,when the name is Associated, the value is 0x10] If this flag is set, the message being imported is an FAI message."); } else { currentMessage.IsFAImessage = false; // When the Associated is not set and the message being imported is a normal message this requirement is captured. ModelHelper.CaptureRequirement( 814, @"[In RopSynchronizationImportMessageChange ROP Request Buffer] [ImportFlag,when the name is Associated, the value is 0x10] If this flag is not set, the message being imported is a normal message."); } // Out the new message handle importMessageHandleIndex = currentMessage.MessageHandleIndex; // Because this is out messageHandle so the OutputServerObject is a Message object. ModelHelper.CaptureRequirement(805, "[In RopSynchronizationImportMessageChange ROP Response Buffer]OutputServerObject: The value of this field MUST be the Message object into which the client will upload the rest of the message changes."); currentMessage.ChangeNumberIndex = ModelHelper.GetChangeNumberIndex(); ModelHelper.CaptureRequirement(1897, "[In Identifying Objects and Maintaining Change Numbers]When a new object is created, it is assigned a change number."); // Add new Message to MessageContainer changeConnection.MessageContainer = changeConnection.MessageContainer.Add(currentMessage); // Record the related FastTransferOperation for Upload Information. uploadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.SynchronizationImportMessageChange; // Update the UploadContextContainer. changeConnection.UploadContextContainer = changeConnection.UploadContextContainer.Update(currentUploadIndex, uploadInfo); connections[serverId] = changeConnection; // Record RopSynchronizationImportMessageChange operation. priorOperation = PriorOperation.RopSynchronizationImportMessageChange; result = RopResult.Success; ModelHelper.CaptureRequirement( 2449, @"[In Uploading Changes Using ICS] Value is Success indicates No error occurred, or a conflict has been resolved."); // Because if the result is success means the messages or changes are imported. ModelHelper.CaptureRequirement( 782, @"[In RopSynchronizationImportMessageChange ROP] The RopSynchronizationImportMessageChange ROP ([MS-OXCROPS] section 2.2.13.2) is used to import new messages or changes to existing messages into the server replica."); } } return result; } /// <summary> /// Imports message read state changes into the server replica. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="uploadContextHandleIndex">Sync handle.</param> /// <param name="messageHandleIndex">Message handle</param> /// <param name="ireadstatus">An array of MessageReadState structures one per each message that's changing its read state.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "SynchronizationImportReadStateChanges(serverId, uploadContextHandleIndex,messageHandleIndex,ireadstatus)/result")] public static RopResult SynchronizationImportReadStateChanges(int serverId, int uploadContextHandleIndex, int messageHandleIndex, bool ireadstatus) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].MessageContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; ConnectionData changeConnection = connections[serverId]; AbstractMessage currentMessage = new AbstractMessage(); AbstractUploadInfo uploadInfo = new AbstractUploadInfo(); // Identify whether the Message is existent or not and record the index. bool isCurrentMessageExist = false; int currentMessageindex = 0; // Identify whether the Upload information is existent or not and record the index. bool isCurrentUploadinfoExist = false; int currentUploadIndex = 0; foreach (AbstractUploadInfo tempUploadInfo in changeConnection.UploadContextContainer) { if (tempUploadInfo.UploadHandleIndex == uploadContextHandleIndex) { // Set the value to the variable when the upload context is existent. isCurrentUploadinfoExist = true; uploadInfo = tempUploadInfo; currentUploadIndex = changeConnection.UploadContextContainer.IndexOf(tempUploadInfo); } } foreach (AbstractMessage tempMessage in changeConnection.MessageContainer) { if (tempMessage.MessageHandleIndex == messageHandleIndex) { // Set the value to the variable when the Message is existent. isCurrentMessageExist = true; currentMessage = tempMessage; currentMessageindex = changeConnection.MessageContainer.IndexOf(tempMessage); } } if (isCurrentMessageExist) { // Find the parent folder of current message AbstractFolder parentfolder = new AbstractFolder(); int parentfolderIndex = 0; foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if (tempFolder.FolderHandleIndex == currentMessage.FolderHandleIndex) { parentfolder = tempFolder; parentfolderIndex = changeConnection.FolderContainer.IndexOf(tempFolder); if (parentfolder.FolderPermission == PermissionLevels.None) { return result = RopResult.AccessDenied; } } } } if (isCurrentUploadinfoExist && isCurrentMessageExist) { // Set the message read status value. if (currentMessage.IsRead != ireadstatus) { currentMessage.IsRead = ireadstatus; // Get read State changeNumber. currentMessage.ReadStateChangeNumberIndex = ModelHelper.GetChangeNumberIndex(); ModelHelper.CaptureRequirement( 2260, @"[In Receiving a RopSynchronizationImportReadStateChanges Request]Upon successful completion of this ROP, the ICS state on the synchronization context MUST be updated by adding the new change number to the MetaTagCnsetRead property (section 2.2.1.1.4)."); } // Record the related Synchronization Operation. uploadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.SynchronizationReadStateChanges; // Update the upload context container and message container. changeConnection.UploadContextContainer = changeConnection.UploadContextContainer.Update(currentUploadIndex, uploadInfo); changeConnection.MessageContainer = changeConnection.MessageContainer.Update(currentMessageindex, currentMessage); connections[serverId] = changeConnection; result = RopResult.Success; ModelHelper.CaptureRequirement( 2449, @"[In Uploading Changes Using ICS] Value is Success indicates No error occurred, or a conflict has been resolved."); // Because if the result is success means message read state changes is imported into the server replica. ModelHelper.CaptureRequirement( 905, @"[In RopSynchronizationImportReadStateChanges ROP] The RopSynchronizationImportReadStateChanges ROP ([MS-OXCROPS] section 2.2.13.3) imports message read state changes into the server replica."); } return result; } /// <summary> /// Imports information about moving a message between two existing folders within the same mailbox. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="synchronizationUploadContextHandleIndex">The index of the synchronization upload context configured for collecting changes to the contents of the message move destination folder.</param> /// <param name="sourceFolderIdIndex">The index of the source folder id in object id container.</param> /// <param name="destinationFolderIdIndex">The index of the destination folder id in object id container.</param> /// <param name="sourceMessageIdIndex">The index of source message id in object id container.</param> /// <param name="sourceFolderHandleIndex">The index of source folder handle in handleContainer.</param> /// <param name="destinationFolderHandleIndex">The index of destination folder handle in handle container.</param> /// <param name="inewerClientChange">If the client has a newer message.</param> /// <param name="iolderversion">If the server have an older version of a message .</param> /// <param name="icnpc">Verify if the change number has been used.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "SynchronizationImportMessageMove(serverId, synchronizationUploadContextHandleIndex,sourceFolderIdIndex,destinationFolderIdIndex,sourceMessageIdIndex,sourceFolderHandleIndex,destinationFolderHandleIndex,inewerClientChange,out iolderversion,out icnpc)/result")] public static RopResult SynchronizationImportMessageMove(int serverId, int synchronizationUploadContextHandleIndex, int sourceFolderIdIndex, int destinationFolderIdIndex, int sourceMessageIdIndex, int sourceFolderHandleIndex, int destinationFolderHandleIndex, bool inewerClientChange, out bool iolderversion, out bool icnpc) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].FolderContainer.Count > 1); // Initialize the return value. RopResult result = RopResult.InvalidParameter; iolderversion = false; icnpc = false; // Get the current ConnectionData value. ConnectionData changeConnection = connections[serverId]; // Identify whether Current Upload information is existent or not. bool isCurrentUploadinfoExist = false; // Record the current Upload information. int currentUploadIndex = 0; AbstractUploadInfo uploadInfo = new AbstractUploadInfo(); foreach (AbstractUploadInfo tempUploadInfo in changeConnection.UploadContextContainer) { if (tempUploadInfo.UploadHandleIndex == synchronizationUploadContextHandleIndex) { // Set the value for current upload information when current upload Information is existent. isCurrentUploadinfoExist = true; uploadInfo = tempUploadInfo; currentUploadIndex = changeConnection.UploadContextContainer.IndexOf(tempUploadInfo); } } // Create variable of relate to source Folder. AbstractFolder sourceFolder = new AbstractFolder(); bool isSourceFolderExist = false; int sourceFolderIndex = 0; // Create variable of relate to destination Folder. AbstractFolder destinationFolder = new AbstractFolder(); bool isdestinationFolderExist = false; int destinationFolderIndex = 0; // Create a new message. AbstractMessage movedMessage = new AbstractMessage(); // Identify whether the Moved Message is existent or not. bool isMovedMessageExist = false; int movedMessageIndex = 0; foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if (tempFolder.FolderIdIndex == sourceFolderIdIndex && tempFolder.FolderHandleIndex == sourceFolderHandleIndex) { // Set the value to the variable when the source folder is existent. isSourceFolderExist = true; sourceFolder = tempFolder; sourceFolderIndex = changeConnection.FolderContainer.IndexOf(tempFolder); } } foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if (tempFolder.FolderIdIndex == destinationFolderIdIndex && tempFolder.FolderHandleIndex == destinationFolderHandleIndex) { // Set the value to the related variable when the destination folder is existent. isdestinationFolderExist = true; destinationFolder = tempFolder; destinationFolderIndex = changeConnection.FolderContainer.IndexOf(tempFolder); } } foreach (AbstractMessage tempMessage in changeConnection.MessageContainer) { if (tempMessage.MessageIdIndex == sourceMessageIdIndex) { // Set the value to the related variable when the source Message is existent. isMovedMessageExist = true; movedMessage = tempMessage; movedMessageIndex = changeConnection.MessageContainer.IndexOf(tempMessage); } } if (isSourceFolderExist && isdestinationFolderExist && isMovedMessageExist && isCurrentUploadinfoExist) { // Set value for the new abstract message property. movedMessage.FolderIdIndex = destinationFolder.FolderIdIndex; movedMessage.FolderHandleIndex = destinationFolder.FolderHandleIndex; // Assigned a new change. movedMessage.ChangeNumberIndex = ModelHelper.GetChangeNumberIndex(); // Assigned a new message id. movedMessage.MessageIdIndex = AdapterHelper.GetObjectIdIndex(); // Update message Container. changeConnection.MessageContainer = changeConnection.MessageContainer.Update(movedMessageIndex, movedMessage); // Remove the current message id from MessageIds of source folder. sourceFolder.MessageIds = sourceFolder.MessageIds.Remove(movedMessage.MessageIdIndex); changeConnection.FolderContainer = changeConnection.FolderContainer.Update(sourceFolderIndex, sourceFolder); // Remove the current message id from MessageIds of destination Folder. destinationFolder.MessageIds = destinationFolder.MessageIds.Add(movedMessage.MessageIdIndex); changeConnection.FolderContainer = changeConnection.FolderContainer.Update(destinationFolderIndex, destinationFolder); // Add information of Upload context uploadInfo.IsnewerClientChange = inewerClientChange; uploadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.SynchronizationImportMessageMove; // Update the upload context container changeConnection.UploadContextContainer = changeConnection.UploadContextContainer.Update(currentUploadIndex, uploadInfo); connections[serverId] = changeConnection; // Identify whether the IsnewerClientChange is true or false. if (uploadInfo.IsnewerClientChange == false) { result = RopResult.Success; ModelHelper.CaptureRequirement( 2449, @"[In Uploading Changes Using ICS] Value is Success indicates No error occurred, or a conflict has been resolved."); // Because if the result is success means the information about moving a message between two existing folders within the same mailbox imported ModelHelper.CaptureRequirement( 839, @"[In RopSynchronizationImportMessageMove ROP] The RopSynchronizationImportMessageMove ROP ([MS-OXCROPS] section 2.2.13.6) imports information about moving a message between two existing folders within the same mailbox."); } else { // Set out put parameter value iolderversion = true; ModelHelper.CaptureRequirement( 875, @"[In RopSynchronizationImportMessageMove ROP Response Buffer] [ Return value (4 bytes):] The following table[In section 2.2.3.2.4.4] contains additional return values[NewerClientChange] , if the ROP succeeded, but the server replica had an older version of a message than the local replica, the return value is 0x00040821."); icnpc = true; ModelHelper.CaptureRequirement( 876, @"[In RopSynchronizationImportMessageMove ROP Response Buffer] [ Return value (4 bytes):] The following table[In section 2.2.3.2.4.4] contains additional return values[NewerClientChange] , if the values of the ChangeNumber and PredecessorChangeList fields, specified in section 2.2.3.2.4.4.1, were not applied to the destination message, the return value is 0x00040821."); ModelHelper.CaptureRequirement( 1892, "[In Identifying Objects and Maintaining Change Numbers]Copying of messaging objects within a mailbox or moving messages between folders of the same mailbox translates into creation of new messaging objects and therefore, new internal identifiers MUST be assigned to new copies."); result = RopResult.NewerClientChange; } // Record RopSynchronizationImportMessageMove operation. priorUploadOperation = PriorOperation.RopSynchronizationImportMessageMove; } return result; } /// <summary> /// Creates a FastTransfer download context for a snapshot of the checkpoint ICS state of the operation identified by the given synchronization download context, or synchronization upload context. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="syncHandleIndex">Synchronization context index.</param> /// <param name="downloadcontextHandleIndex">The index of FastTransfer download context for the ICS state.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "SynchronizationGetTransferState(serverId, syncHandleIndex,out downloadcontextHandleIndex)/result")] public static RopResult SynchronizationGetTransferState(int serverId, int syncHandleIndex, out int downloadcontextHandleIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].UploadContextContainer.Count > 0 || connections[serverId].DownloadContextContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; downloadcontextHandleIndex = -1; // Get the current ConnectionData value. ConnectionData changeConnection = connections[serverId]; AbstractDownloadInfo downloadInfo = new AbstractDownloadInfo(); AbstractUploadInfo uploadInfo = new AbstractUploadInfo(); // Identify whether the Download context or Upload context is existent or not and record the index. bool isCurrentDownloadInfoExist = false; bool isCurrentUploadInfoExist = false; foreach (AbstractDownloadInfo temp in changeConnection.DownloadContextContainer) { if (temp.DownloadHandleIndex == syncHandleIndex) { // Set the value to the related variable when the current Download context is existent. isCurrentDownloadInfoExist = true; downloadInfo = temp; } } if (!isCurrentDownloadInfoExist) { foreach (AbstractUploadInfo tempInfo in changeConnection.UploadContextContainer) { if (tempInfo.UploadHandleIndex == syncHandleIndex) { // Set the value to the related variable when the current upload context is existent. isCurrentUploadInfoExist = true; uploadInfo = tempInfo; } } } if (isCurrentDownloadInfoExist || isCurrentUploadInfoExist) { // Create a new download context. AbstractDownloadInfo newDownloadInfo = new AbstractDownloadInfo { DownloadHandleIndex = AdapterHelper.GetHandleIndex() }; // Out the new downloadHandle. downloadcontextHandleIndex = newDownloadInfo.DownloadHandleIndex; ModelHelper.CaptureRequirement(765, "[In RopSynchronizationGetTransferState ROP Response Buffer]OutputServerObject: The value of this field MUST be the FastTransfer download context for the ICS state."); if (isCurrentDownloadInfoExist) { // Set the new Download context value newDownloadInfo.RelatedObjectHandleIndex = downloadInfo.RelatedObjectHandleIndex; newDownloadInfo.SynchronizationType = downloadInfo.SynchronizationType; newDownloadInfo.UpdatedState = downloadInfo.UpdatedState; priorDownloadOperation = PriorDownloadOperation.RopSynchronizationGetTransferState; } else { // Set the new Upload context value newDownloadInfo.RelatedObjectHandleIndex = uploadInfo.RelatedObjectHandleIndex; newDownloadInfo.SynchronizationType = uploadInfo.SynchronizationType; newDownloadInfo.UpdatedState = uploadInfo.UpdatedState; } // Set the abstractFastTransferStreamType for new Down loadContext value newDownloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.state; newDownloadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.SynchronizationGetTransferState; // Add new download context to DownloadContextContainer. changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Add(newDownloadInfo); connections[serverId] = changeConnection; result = RopResult.Success; // Because context created if the RopSynchronizationGetTransferState execute successful. ModelHelper.CaptureRequirement( 758, @"[In RopSynchronizationGetTransferState ROP] The RopSynchronizationGetTransferState ROP ([MS-OXCROPS] section 2.2.13.8) creates a FastTransfer download context for the checkpoint ICS state of the operation identified by the given synchronization download context or synchronization upload context at the current moment in time."); } return result; } /// <summary> /// Upload of an ICS state property into the synchronization context. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="uploadContextHandleIndex">The synchronization context handle</param> /// <param name="icsPropertyType">Property tags of the ICS state property.</param> /// <param name="isPidTagIdsetGivenInputAsInter32"> identifies Property tags as PtypInteger32.</param> /// <param name="icsStateIndex">The index of the ICS State.</param> /// <returns>The ICS state property is upload to the server successfully or not.</returns> [Rule(Action = "SynchronizationUploadState(serverId, uploadContextHandleIndex, icsPropertyType, isPidTagIdsetGivenInputAsInter32, icsStateIndex)/result")] public static RopResult SynchronizationUploadState(int serverId, int uploadContextHandleIndex, ICSStateProperties icsPropertyType, bool isPidTagIdsetGivenInputAsInter32, int icsStateIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].DownloadContextContainer.Count > 0 || connections[serverId].UploadContextContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; AbstractUploadInfo uploadInfo = new AbstractUploadInfo(); AbstractDownloadInfo downLoadInfo = new AbstractDownloadInfo(); // Get the current ConnectionData value. ConnectionData changeConnection = connections[serverId]; // Identify whether the DownloadContext or UploadContext is existent or not and record the index. bool isCurrentUploadinfoExist = false; int currentUploadIndex = 0; bool isCurrentDownLoadinfoExist = false; int currentDownLoadIndex = 0; foreach (AbstractUploadInfo tempUploadInfo in changeConnection.UploadContextContainer) { if (tempUploadInfo.UploadHandleIndex == uploadContextHandleIndex) { // Set the value to the related variable when the current upload context is existent. isCurrentUploadinfoExist = true; uploadInfo = tempUploadInfo; currentUploadIndex = changeConnection.UploadContextContainer.IndexOf(tempUploadInfo); break; } } if (!isCurrentUploadinfoExist) { foreach (AbstractDownloadInfo tempDownLoadInfo in changeConnection.DownloadContextContainer) { if (tempDownLoadInfo.DownloadHandleIndex == uploadContextHandleIndex) { // Set the value to the related variable when the current Download context is existent. isCurrentDownLoadinfoExist = true; downLoadInfo = tempDownLoadInfo; currentDownLoadIndex = changeConnection.DownloadContextContainer.IndexOf(tempDownLoadInfo); break; } } } if (isCurrentDownLoadinfoExist || isCurrentUploadinfoExist) { if (isCurrentUploadinfoExist) { if (icsStateIndex != 0) { AbstractFolder currentFolder = new AbstractFolder(); foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if (tempFolder.FolderHandleIndex == uploadInfo.RelatedObjectHandleIndex) { // Set the value to the related variable when the current Folder is existent. currentFolder = tempFolder; Condition.IsTrue(currentFolder.ICSStateContainer.ContainsKey(icsStateIndex)); } } // Add ICS State to ICSStateContainer of current folder. AbstractUpdatedState updatedState = currentFolder.ICSStateContainer[icsStateIndex]; switch (icsPropertyType) { case ICSStateProperties.PidTagIdsetGiven: // Set IdsetGiven value uploadInfo.UpdatedState.IdsetGiven = updatedState.IdsetGiven; break; case ICSStateProperties.PidTagCnsetRead: // Set CnsetRead value uploadInfo.UpdatedState.CnsetRead = updatedState.CnsetRead; break; case ICSStateProperties.PidTagCnsetSeen: // Set CnsetSeen value uploadInfo.UpdatedState.CnsetSeen = updatedState.CnsetSeen; break; case ICSStateProperties.PidTagCnsetSeenFAI: // Set CnsetSeenFAI value uploadInfo.UpdatedState.CnsetSeenFAI = updatedState.CnsetSeenFAI; break; default: break; } // Update the UploadContextContainer context. changeConnection.UploadContextContainer = changeConnection.UploadContextContainer.Update(currentUploadIndex, uploadInfo); } } else { if (icsStateIndex != 0) { AbstractFolder currentFolder = new AbstractFolder(); foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if (tempFolder.FolderHandleIndex == downLoadInfo.RelatedObjectHandleIndex) { // Set the value to the related variable when the current Folder is existent. currentFolder = tempFolder; // Identify ICS State whether exist index or not in ICSStateContainer Condition.IsTrue(currentFolder.ICSStateContainer.ContainsKey(icsStateIndex)); } } // Add update state to ICSStateContainer of current folder. AbstractUpdatedState updatedState = currentFolder.ICSStateContainer[icsStateIndex]; switch (icsPropertyType) { case ICSStateProperties.PidTagIdsetGiven: // Set IdsetGiven value. downLoadInfo.UpdatedState.IdsetGiven = updatedState.IdsetGiven; break; case ICSStateProperties.PidTagCnsetRead: // Set CnsetRead value. downLoadInfo.UpdatedState.CnsetRead = updatedState.CnsetRead; break; case ICSStateProperties.PidTagCnsetSeen: // Set CnsetSeen value. downLoadInfo.UpdatedState.CnsetSeen = updatedState.CnsetSeen; break; case ICSStateProperties.PidTagCnsetSeenFAI: // Set CnsetSeenFAI value. downLoadInfo.UpdatedState.CnsetSeenFAI = updatedState.CnsetSeenFAI; break; default: break; } // Update the DownloadContextContainer. changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Update(currentDownLoadIndex, downLoadInfo); } } connections[serverId] = changeConnection; if (isPidTagIdsetGivenInputAsInter32) { // Identify the property tag whether PtypInteger32 is or not. if (requirementContainer.Keys.Contains(2657) && requirementContainer[2657]) { result = RopResult.Success; ModelHelper.CaptureRequirement(2657, "[In Receiving the MetaTagIdsetGiven ICS State Property] Implementation does accept this MetaTagIdsetGiven property when the property tag identifies it as PtypInteger32. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } else { return result; } } result = RopResult.Success; } return result; } /// <summary> /// Allocates a range of internal identifiers for the purpose of assigning them to client-originated objects in a local replica. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="logonHandleIndex">The server object handle index.</param> /// <param name="idcount">An unsigned 32-bit integer specifies the number of IDs to allocate.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "GetLocalReplicaIds(serverId, logonHandleIndex,idcount)/result")] public static RopResult GetLocalReplicaIds(int serverId, int logonHandleIndex, uint idcount) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].LogonHandleIndex > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; // Get the current ConnectionData value. ConnectionData changeConnection = connections[serverId]; if (logonHandleIndex == changeConnection.LogonHandleIndex) { // Set localId Count value. changeConnection.LocalIdCount = idcount; result = RopResult.Success; connections[serverId] = changeConnection; if (idcount > 0) { // Because only if result is success and the idcount larger than 0 indicate a range of internal identifiers (2) for the purpose of assigning them to client-originated objects in a local replica are allocated. ModelHelper.CaptureRequirement( 925, @"[In RopGetLocalReplicaIds ROP] The RopGetLocalReplicaIds ROP ([MS-OXCROPS] section 2.2.13.13) allocates a range of internal identifiers for the purpose of assigning them to client-originated objects in a local replica."); } } return result; } /// <summary> /// Identifies that a set of IDs either belongs to deleted messages in the specified folder or will never be used for any messages in the specified folder. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="folderHandleIndex">A Folder object handle</param> /// <param name="longTermIdRangeIndex">The range of LongTermId.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = "SetLocalReplicaMidsetDeleted(serverId, folderHandleIndex, longTermIdRangeIndex)/result")] public static RopResult SetLocalReplicaMidsetDeleted(int serverId, int folderHandleIndex, Sequence<int> longTermIdRangeIndex) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); Condition.IsTrue(connections[serverId].FolderContainer.Count > 0); // Initialize the return value. RopResult result = RopResult.InvalidParameter; // Get the current ConnectionData value ConnectionData changeConnection = connections[serverId]; // Identify whether the current folder is existent or not and record the index. bool isCurrentFolderExist = false; foreach (AbstractFolder tempfolder in changeConnection.FolderContainer) { if (tempfolder.FolderHandleIndex == folderHandleIndex) { // Set the value to the related variable when the current Folder is existent. isCurrentFolderExist = true; } } if (isCurrentFolderExist == false) { // The server return invalid parameter when current folder is not exist. result = RopResult.InvalidParameter; } else { // The server return Success. result = RopResult.Success; // When the ROP success means server add ranges of IDs supplied through this ROP to the deleted item list. ModelHelper.CaptureRequirement( 2269, @"[In Receiving a RopSetLocalReplicaMidsetDeleted Request] A server MUST add ranges of IDs supplied through this ROP to the deleted item list."); ModelHelper.CaptureRequirement( 940, @"[In RopSetLocalReplicaMidsetDeleted ROP] The RopSetLocalReplicaMidsetDeleted ROP ([MS-OXCROPS] section 2.2.13.12) identifies that a set of IDs either belongs to deleted messages in the specified folder or will never be used for any messages in the specified folder."); } return result; } #endregion #region FastTransfer related actions /// <summary> /// Initializes a FastTransfer operation to download content from a given messaging object and its descendant subObjects. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="objHandleIndex">Folder or message object handle index. </param> /// <param name="handleType">The input handle type</param> /// <param name="level">Variable indicate whether copy the descendant subObjects.</param> /// <param name="copyFlag">Defines parameters of the FastTransfer download operation.</param> /// <param name="option">Defines the parameters of a download operation .</param> /// <param name="propertyTags">Array of properties and subObjects to exclude.</param> /// <param name="downloadContextHandleIndex">The properties handle index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = ("FastTransferSourceCopyTo(serverId,objHandleIndex,handleType,level,copyFlag,option,propertyTags,out downloadContextHandleIndex)/result"))] public static RopResult FastTransferSourceCopyTo(int serverId, int objHandleIndex, InputHandleType handleType, bool level, CopyToCopyFlags copyFlag, SendOptionAlls option, Sequence<string> propertyTags, out int downloadContextHandleIndex) { // The contraction conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Initialize the return value. RopResult result = RopResult.InvalidParameter; // The copyFlag conditions. if (((copyFlag == CopyToCopyFlags.Invalid && (requirementContainer.ContainsKey(3445) && requirementContainer[3445])) || (option == SendOptionAlls.Invalid && (requirementContainer.ContainsKey(3463) && requirementContainer[3463]))) || ((copyFlag & CopyToCopyFlags.Move) == CopyToCopyFlags.Move && (requirementContainer.ContainsKey(3442001) && requirementContainer[3442001])) || ((copyFlag & CopyToCopyFlags.Move) == CopyToCopyFlags.Move && (requirementContainer.ContainsKey(3442003) && requirementContainer[3442003]))) { downloadContextHandleIndex = -1; if ((copyFlag & CopyToCopyFlags.Move) == CopyToCopyFlags.Move) { // CopyToCopyFlags value is Move. if (requirementContainer.ContainsKey(3442001) && requirementContainer[3442001]) { // When the ROP return invalid parameter this requirement verified. ModelHelper.CaptureRequirement( 3442001, @"[In Appendix A: Product Behavior] Implementation does not support. &lt;34&gt; Section 3.2.5.8.1.1: Exchange 2010, Exchange 2013, Exchange 2016 and Exchange 2019 do not support the Move flag for the RopFastTransferSourceCopyTo ROP (section 2.2.3.1.1.1)."); } if (requirementContainer.ContainsKey(3442003) && requirementContainer[3442003]) { result = RopResult.InvalidParameter; // When the ROP return invalid parameter this requirement verified. ModelHelper.CaptureRequirement( 3442003, @"[In Appendix A: Product Behavior] If the server receives the Move flag, implementation does fail the operation with an error code InvalidParameter (0x80070057). &lt;34&gt; Section 3.2.5.8.1.1: The server sets the value of the ReturnValue field to InvalidParameter (0x80070057) if it receives this flag [Move flag].(Microsoft Exchange 2010, Exchange 2013, Exchange 2016 and Exchange 2019 follow this behavior.)"); } } return result; } else { // Create a new download context AbstractDownloadInfo downloadInfo = new AbstractDownloadInfo(); bool isObjExist = false; // Get value of ConnectionData ConnectionData changeConnection = connections[serverId]; connections.Remove(serverId); // Find current message if (handleType == InputHandleType.MessageHandle) { foreach (AbstractMessage temp in changeConnection.MessageContainer) { if (temp.MessageHandleIndex == objHandleIndex) { isObjExist = true; } } Condition.IsTrue(isObjExist); // Set value for new download context. downloadInfo.DownloadHandleIndex = AdapterHelper.GetHandleIndex(); downloadContextHandleIndex = downloadInfo.DownloadHandleIndex; downloadInfo.Sendoptions = option; downloadInfo.Property = propertyTags; downloadInfo.CopyToCopyFlag = copyFlag; downloadInfo.IsLevelTrue = level; // Record FastTransfer Operation. downloadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.FastTransferSourceCopyTo; downloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.MessageContent; downloadInfo.ObjectType = ObjectType.Message; downloadInfo.RelatedObjectHandleIndex = objHandleIndex; priorDownloadOperation = PriorDownloadOperation.RopFastTransferSourceCopyTo; // Add new download context to downloadContext Container. changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Add(downloadInfo); } else if (handleType == InputHandleType.FolderHandle) { // Find current folder. foreach (AbstractFolder temp in changeConnection.FolderContainer) { if (temp.FolderHandleIndex == objHandleIndex) { isObjExist = true; } } Condition.IsTrue(isObjExist); // Set value for new download context. downloadInfo.DownloadHandleIndex = AdapterHelper.GetHandleIndex(); downloadContextHandleIndex = downloadInfo.DownloadHandleIndex; downloadInfo.Sendoptions = option; downloadInfo.Property = propertyTags; downloadInfo.CopyToCopyFlag = copyFlag; // Record FastTransfer Operation downloadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.FastTransferSourceCopyTo; downloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.folderContent; downloadInfo.ObjectType = ObjectType.Folder; downloadInfo.RelatedObjectHandleIndex = objHandleIndex; priorDownloadOperation = PriorDownloadOperation.RopFastTransferSourceCopyTo; // Add new download context to DownloadContextContainer changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Add(downloadInfo); } else { // Find current attachment foreach (AbstractAttachment temp in changeConnection.AttachmentContainer) { if (temp.AttachmentHandleIndex == objHandleIndex) { isObjExist = true; } } Condition.IsTrue(isObjExist); // Set value for new download context. downloadInfo.DownloadHandleIndex = AdapterHelper.GetHandleIndex(); downloadContextHandleIndex = downloadInfo.DownloadHandleIndex; downloadInfo.Sendoptions = option; downloadInfo.Property = propertyTags; downloadInfo.CopyToCopyFlag = copyFlag; // Record FastTransfer Operation downloadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.FastTransferSourceCopyTo; downloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.attachmentContent; downloadInfo.ObjectType = ObjectType.Attachment; downloadInfo.RelatedObjectHandleIndex = objHandleIndex; priorDownloadOperation = PriorDownloadOperation.RopFastTransferSourceCopyTo; // Add new download context to DownloadContextContainer changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Add(downloadInfo); } connections.Add(serverId, changeConnection); result = RopResult.Success; ModelHelper.CaptureRequirement( 361, @"[In RopFastTransferSourceCopyTo ROP] The RopFastTransferSourceCopyTo ROP ([MS-OXCROPS] section 2.2.12.6) initializes a FastTransfer operation to download content from a given messaging object and its descendant subobjects."); if ((copyFlag & CopyToCopyFlags.Move) == CopyToCopyFlags.Move) { if (requirementContainer.ContainsKey(3442002) && requirementContainer[3442002]) { ModelHelper.CaptureRequirement( 3442002, @"[In Appendix A: Product Behavior] Implementation does support Move flag [for the RopFastTransferSourceCopyTo ROP]. (Microsoft Exchange Server 2007 follow this behavior.)"); } if (requirementContainer.ContainsKey(3442004) && requirementContainer[3442004]) { ModelHelper.CaptureRequirement( 3442004, @"[In Appendix A: Product Behavior] If the server receives the Move flag, implementation does not fail the operation.(<34> Section 3.2.5.8.1.1: Microsoft Exchange Server 2007 follows this behavior.)"); } } } return result; } /// <summary> /// Initializes a FastTransfer operation to download content from a given messaging object and its descendant subObjects. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="objHandleIndex">Folder or message object handle index. </param> /// <param name="handleType">Input Handle Type</param> /// <param name="level">Variable indicate whether copy the descendant subObjects.</param> /// <param name="copyFlag">Defines parameters of the FastTransfer download operation.</param> /// <param name="option">Defines the parameters of a download operation .</param> /// <param name="propertyTags">The list of properties and subObjects to exclude.</param> /// <param name="downloadContextHandleIndex">The properties handle index.</param> /// <returns>Indicate the result of this ROP operation</returns> [Rule(Action = ("FastTransferSourceCopyProperties(serverId,objHandleIndex,handleType,level,copyFlag,option,propertyTags,out downloadContextHandleIndex)/result"))] public static RopResult FastTransferSourceCopyProperties(int serverId, int objHandleIndex, InputHandleType handleType, bool level, CopyPropertiesCopyFlags copyFlag, SendOptionAlls option, Sequence<string> propertyTags, out int downloadContextHandleIndex) { // The contraction conditions Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Initialize the return value. RopResult result = RopResult.InvalidParameter; // SendOptionAll value is Invalid parameter if ((option == SendOptionAlls.Invalid && (requirementContainer.ContainsKey(3470) && requirementContainer[3470])) || (copyFlag == CopyPropertiesCopyFlags.Invalid && (requirementContainer.ContainsKey(3466) && requirementContainer[3466]))) { downloadContextHandleIndex = -1; } else if (((copyFlag & CopyPropertiesCopyFlags.Move) == CopyPropertiesCopyFlags.Move) && (requirementContainer.ContainsKey(3466) && requirementContainer[3466])) { // CopyPropertiesCopyFlags value is Move. result = RopResult.NotImplemented; downloadContextHandleIndex = -1; } else { // Create a new download context. AbstractDownloadInfo downloadInfo = new AbstractDownloadInfo(); ConnectionData changeConnection = connections[serverId]; bool isObjExist = false; connections.Remove(serverId); if (handleType == InputHandleType.MessageHandle) { foreach (AbstractMessage temp in changeConnection.MessageContainer) { if (temp.MessageHandleIndex == objHandleIndex) { isObjExist = true; } } Condition.IsTrue(isObjExist); // Set value for new download context. downloadContextHandleIndex = AdapterHelper.GetHandleIndex(); downloadInfo.DownloadHandleIndex = downloadContextHandleIndex; downloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.MessageContent; // Record the FastTransferOperation downloadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.FastTransferSourceCopyProperties; priorDownloadOperation = PriorDownloadOperation.RopFastTransferSourceCopyProperties; // Set value for new download context. downloadInfo.CopyPropertiesCopyFlag = copyFlag; downloadInfo.Property = propertyTags; downloadInfo.Sendoptions = option; downloadInfo.RelatedObjectHandleIndex = objHandleIndex; downloadInfo.ObjectType = ObjectType.Message; downloadInfo.IsLevelTrue = level; // Add new download context to DownloadContextContainer. changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Add(downloadInfo); } else if (handleType == InputHandleType.FolderHandle) { // Find current folder. foreach (AbstractFolder temp in changeConnection.FolderContainer) { if (temp.FolderHandleIndex == objHandleIndex) { isObjExist = true; } } Condition.IsTrue(isObjExist); // Set value for new download context. downloadContextHandleIndex = AdapterHelper.GetHandleIndex(); downloadInfo.DownloadHandleIndex = downloadContextHandleIndex; downloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.folderContent; // Record the FastTransferOperation downloadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.FastTransferSourceCopyProperties; priorDownloadOperation = PriorDownloadOperation.RopFastTransferSourceCopyProperties; // Set value for new download context. downloadInfo.CopyPropertiesCopyFlag = copyFlag; downloadInfo.Property = propertyTags; downloadInfo.Sendoptions = option; downloadInfo.RelatedObjectHandleIndex = objHandleIndex; downloadInfo.ObjectType = ObjectType.Folder; // Add new download context to DownloadContextContainer. changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Add(downloadInfo); } else { // Find the current Attachment foreach (AbstractAttachment temp in changeConnection.AttachmentContainer) { if (temp.AttachmentHandleIndex == objHandleIndex) { isObjExist = true; } } Condition.IsTrue(isObjExist); // Set value for new download context. downloadContextHandleIndex = AdapterHelper.GetHandleIndex(); downloadInfo.DownloadHandleIndex = downloadContextHandleIndex; downloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.attachmentContent; // Record the FastTransferOperation downloadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.FastTransferSourceCopyProperties; priorDownloadOperation = PriorDownloadOperation.RopFastTransferSourceCopyProperties; // Set value for new download context. downloadInfo.CopyPropertiesCopyFlag = copyFlag; downloadInfo.Property = propertyTags; downloadInfo.Sendoptions = option; downloadInfo.ObjectType = ObjectType.Attachment; downloadInfo.RelatedObjectHandleIndex = objHandleIndex; // Add new download context to DownloadContextContainer. changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Add(downloadInfo); } connections.Add(serverId, changeConnection); result = RopResult.Success; // If the server returns success result, it means the RopFastTransferSourceCopyProperties ROP initializes the FastTransfer operation successfully. And then this requirement can be captured. ModelHelper.CaptureRequirement( 431, @"[In RopFastTransferSourceCopyProperties ROP] The RopFastTransferSourceCopyProperties ROP ([MS-OXCROPS] section 2.2.12.7) initializes a FastTransfer operation to download content from a specified messaging object and its descendant sub objects."); } return result; } /// <summary> /// Initializes a FastTransfer operation on a folder for downloading content and descendant subObjects for messages identified by a given set of IDs. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="objHandleIndex">Folder object handle index. </param> /// <param name="copyFlag">Defines parameters of the FastTransfer download operation.</param> /// <param name="option">Defines the parameters of a download operation.</param> /// <param name="messageIds">The list of MIDs the messages should copy.</param> /// <param name="downloadContextHandleIndex">The message handle index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = ("FastTransferSourceCopyMessages(serverId,objHandleIndex,copyFlag,option,messageIds,out downloadContextHandleIndex)/result"))] public static RopResult FastTransferSourceCopyMessages(int serverId, int objHandleIndex, RopFastTransferSourceCopyMessagesCopyFlags copyFlag, SendOptionAlls option, Sequence<int> messageIds, out int downloadContextHandleIndex) { // The contraction conditions Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Initialize the return value. RopResult result = RopResult.InvalidParameter; if (option == SendOptionAlls.Invalid) { if (requirementContainer.ContainsKey(3479) && requirementContainer[3479]) { // SendOption flags value is invalid downloadContextHandleIndex = -1; return result; } } // Modify the logical if ((copyFlag & RopFastTransferSourceCopyMessagesCopyFlags.Unused3) == RopFastTransferSourceCopyMessagesCopyFlags.Unused3) { // CopyFlags is set to Unused3 downloadContextHandleIndex = -1; } else { // Identify whether the current folder is existent or not. ConnectionData changeConnection = connections[serverId]; bool isFolderExist = false; foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if (tempFolder.FolderHandleIndex == objHandleIndex) { isFolderExist = true; } } Condition.IsTrue(isFolderExist); // Set value for new download context. AbstractDownloadInfo downloadInfo = new AbstractDownloadInfo(); downloadContextHandleIndex = AdapterHelper.GetHandleIndex(); downloadInfo.DownloadHandleIndex = downloadContextHandleIndex; connections.Remove(serverId); downloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.MessageList; downloadInfo.CopyMessageCopyFlag = copyFlag; // Record the FastTransferOperation downloadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.FastTransferSourceCopyMessage; priorDownloadOperation = PriorDownloadOperation.RopFastTransferSourceCopyMessage; // Set value for new download context. downloadInfo.Sendoptions = option; downloadInfo.RelatedObjectHandleIndex = objHandleIndex; downloadInfo.ObjectType = ObjectType.Folder; // Add new download context to DownloadContextContainer. changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Add(downloadInfo); connections.Add(serverId, changeConnection); priorOperation = MS_OXCFXICS.PriorOperation.RopFastTransferSourceCopyMessage; result = RopResult.Success; // If the server returns success result, it means the RopFastTransferSourceCopyMessages ROP initializes the FastTransfer operation successfully. And then this requirement can be captured. ModelHelper.CaptureRequirement( 3125, @"[In RopFastTransferSourceCopyMessages ROP] The RopFastTransferSourceCopyMessages ROP ([MS-OXCROPS] section 2.2.12.5) initializes a FastTransfer operation on a folder for downloading content and descendant subobjects of messages identified by a set of MID structures ([MS-OXCDATA] section 2.2.1.2)."); } return result; } /// <summary> /// Initializes a FastTransfer operation to download properties and descendant subObjects for a specified folder. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="folderHandleIndex">Folder object handle index. </param> /// <param name="copyFlag">Defines parameters of the FastTransfer download operation.</param> /// <param name="option">Defines the parameters of a download operation.</param> /// <param name="downloadContextHandleIndex">The folder handle index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = ("FastTransferSourceCopyFolder(serverId,folderHandleIndex,copyFlag,option, out downloadContextHandleIndex)/result"))] public static RopResult FastTransferSourceCopyFolder(int serverId, int folderHandleIndex, CopyFolderCopyFlags copyFlag, SendOptionAlls option, out int downloadContextHandleIndex) { // The contraction conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Initialize the return value. RopResult result = RopResult.InvalidParameter; // Modify the logical if ((option == SendOptionAlls.Invalid && (requirementContainer.ContainsKey(3487) && requirementContainer[3487])) || (copyFlag == CopyFolderCopyFlags.Invalid && (requirementContainer.ContainsKey(3483) && requirementContainer[3483]))) { // SendOption is Invalid parameter and CopyFolderCopyFlags is Invalid parameter. downloadContextHandleIndex = -1; return result; } else if (copyFlag == CopyFolderCopyFlags.Move && (requirementContainer.ContainsKey(526001) && !requirementContainer[526001])) { downloadContextHandleIndex = -1; ModelHelper.CaptureRequirement( 526001, @"[In Appendix A: Product Behavior] [CopyFlags] [When the flag name is Move, value is 0x01] Implementation does set the Move flag on a download operation to indicate the following: The server does not output any objects in a FastTransfer stream that the client does not have permissions to delete. <7> Section 2.2.3.1.1.4.1: In Exchange 2007, the Move bit flag is read by the server."); return result; } else { ConnectionData changeConnection = connections[serverId]; // Identify whether the current folder is existent or not. bool isFolderExist = false; foreach (AbstractFolder tempFolder in changeConnection.FolderContainer) { if (tempFolder.FolderHandleIndex == folderHandleIndex) { isFolderExist = true; } } Condition.IsTrue(isFolderExist); // Create a new download context. AbstractDownloadInfo downloadInfo = new AbstractDownloadInfo(); downloadContextHandleIndex = AdapterHelper.GetHandleIndex(); downloadInfo.DownloadHandleIndex = downloadContextHandleIndex; connections.Remove(serverId); // Record the FastTransferOperation and Stream Type. downloadInfo.AbstractFastTransferStreamType = FastTransferStreamType.TopFolder; downloadInfo.RelatedFastTransferOperation = EnumFastTransferOperation.FastTransferSourceCopyFolder; priorDownloadOperation = PriorDownloadOperation.RopFastTransferSourceCopyFolder; // Set value for new download context. downloadInfo.CopyFolderCopyFlag = copyFlag; downloadInfo.Sendoptions = option; downloadInfo.ObjectType = ObjectType.Folder; downloadInfo.RelatedObjectHandleIndex = folderHandleIndex; // Add new download context to downloadContainer. changeConnection.DownloadContextContainer = changeConnection.DownloadContextContainer.Add(downloadInfo); connections.Add(serverId, changeConnection); result = RopResult.Success; // If the server returns success result, it means the RopFastTransferSourceCopyFolder ROP initializes the FastTransfer operation successfully. And then this requirement can be captured. ModelHelper.CaptureRequirement( 502, @"[In RopFastTransferSourceCopyFolder ROP] The RopFastTransferSourceCopyFolder ROP ([MS-OXCROPS] section 2.2.12.4) initializes a FastTransfer operation to download properties and descendant subobjects for a specified folder."); } return result; } /// <summary> /// Downloads the next portion of a FastTransfer stream. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="downloadHandleIndex">A fastTransfer stream object handle index. </param> /// <param name="bufferSize">Specifies the maximum amount of data to be output in the TransferBuffer.</param> /// <param name="transferBufferIndex">The index of data get from the fastTransfer stream.</param> /// <param name="abstractFastTransferStream">The abstractFastTransferStream.</param> /// <param name="transferDataSmallOrEqualToBufferSize">Variable to not if the transferData is small or equal to bufferSize</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = ("FastTransferSourceGetBuffer(serverId,downloadHandleIndex,bufferSize,out transferBufferIndex,out abstractFastTransferStream ,out transferDataSmallOrEqualToBufferSize)/result"))] public static RopResult FastTransferSourceGetBuffer(int serverId, int downloadHandleIndex, BufferSize bufferSize, out int transferBufferIndex, out AbstractFastTransferStream abstractFastTransferStream, out bool transferDataSmallOrEqualToBufferSize) { // The contractions conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Initialize the return value. RopResult result = RopResult.InvalidParameter; transferBufferIndex = -1; abstractFastTransferStream = new AbstractFastTransferStream(); transferDataSmallOrEqualToBufferSize = false; if (bufferSize == BufferSize.Greater) { result = RopResult.BufferTooSmall; return result; } // Get current ConnectionData value. ConnectionData currentConnection = connections[serverId]; // Create a new currentDownloadContext. AbstractDownloadInfo currentDownloadContext = new AbstractDownloadInfo(); // Identify whether the Download context is existent or not. bool isDownloadHandleExist = false; // Find the current Download Context foreach (AbstractDownloadInfo tempDownloadContext in currentConnection.DownloadContextContainer) { if (tempDownloadContext.DownloadHandleIndex == downloadHandleIndex) { // Set the value to the related variable when the download context is existent. isDownloadHandleExist = true; result = RopResult.Success; currentDownloadContext = tempDownloadContext; int infoIndex = currentConnection.DownloadContextContainer.IndexOf(tempDownloadContext); // Get the Data buffer index transferBufferIndex = AdapterHelper.GetStreamBufferIndex(); currentDownloadContext.DownloadStreamIndex = transferBufferIndex; abstractFastTransferStream.StreamType = currentDownloadContext.AbstractFastTransferStreamType; currentConnection.DownloadContextContainer = currentConnection.DownloadContextContainer.Update(infoIndex, currentDownloadContext); } } // Create new variable relate to current folder. AbstractFolder currentFolder = new AbstractFolder(); int currentFolderIndex = 0; // Identify current whether DownloadHandle is existent or not. if (isDownloadHandleExist) { // If bufferSize is set to a value other than 0xBABE if (bufferSize != BufferSize.Normal) { transferDataSmallOrEqualToBufferSize = true; ModelHelper.CaptureRequirement( 2142, @"[In Receiving a RopFastTransferSourceGetBuffer Request]If the value of BufferSize in the ROP request is set to a value other than 0xBABE, the following semantics apply:The server MUST output, at most, the number of bytes specified by the BufferSize field in the TransferBuffer field even if more data is available."); ModelHelper.CaptureRequirement( 2143, @"[In Receiving a RopFastTransferSourceGetBuffer Request]If the value of BufferSize in the ROP request is set to a value other than 0xBABE, the following semantics apply:The server returns less bytes than the value specified by the BufferSize field, or the server returns the number of bytes specified by the BufferSize field in the TransferBuffer field."); } #region Requirements about RopOperation Response // FolderHandleIndex is the Index of the FastTransfer download context if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyTo) { ModelHelper.CaptureRequirement(384, "[In RopFastTransferSourceCopyTo ROP Response Buffer] OutputServerObject: The value of this field MUST be the FastTransfer download context."); } else if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyProperties) { ModelHelper.CaptureRequirement(455, "[In RopFastTransferSourceCopyProperties ROP Response Buffer] OutputServerObject: The value of this field MUST be the FastTransfer download context. "); } else if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyMessage) { ModelHelper.CaptureRequirement(487, @"[In RopFastTransferSourceCopyMessages ROP Response Buffer]OutputServerObject: The value of this field MUST be the FastTransfer download context."); } else if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyFolder) { ModelHelper.CaptureRequirement(511, @"[In RopFastTransferSourceCopyFolder ROP Response Buffer]OutputServerObject: The value of this field MUST be the FastTransfer download context."); } #endregion // Get the related folder for the download handle in the folder container. foreach (AbstractFolder tempfolder in currentConnection.FolderContainer) { if (tempfolder.FolderHandleIndex == currentDownloadContext.RelatedObjectHandleIndex) { currentFolder = tempfolder; currentFolderIndex = currentConnection.FolderContainer.IndexOf(tempfolder); break; } } // Identify the abstractFastTransferStream type switch (currentDownloadContext.AbstractFastTransferStreamType) { // The hierarchySync element contains the result of the hierarchy synchronization download operation case FastTransferStreamType.hierarchySync: { if (currentDownloadContext.SynchronizationType == SynchronizationTypes.Hierarchy && priorDownloadOperation == PriorDownloadOperation.RopSynchronizationConfigure) { // Because if the synchronizationType in synchronization configure and the stream type return are Hierarchy indicate this requirement verified. ModelHelper.CaptureRequirement( 3322, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopSynchronizationConfigure, ROP request buffer field conditions is The SynchronizationType field is set to Hierarchy (0x02), Root element in the produced FastTransfer stream is hierarchySync."); } // Create a new HierarchySync. abstractFastTransferStream.AbstractHierarchySync = new AbstractHierarchySync { FolderchangeInfo = new AbstractFolderChange(), AbstractDeletion = { IdSetDeleted = new Set<int>() }, FinalICSState = new AbstractState { AbstractICSStateIndex = AdapterHelper.GetICSStateIndex(), IsNewCnsetSeenFAIPropertyChangeNumber = false } }; // Assigned a new final ICS State for HierarchySync. // This isn't New ChangeNumber for CnsetSeenFAIProperty in Initialize. // Because of the SynchronizationType must optioned "Hierarchy" value in RopSynchronizationConfigure operation if FastTransferStreamType is hierarchySync. ModelHelper.CaptureRequirement(1209, "[In state Element] [MetaTagCnsetSeenFAI, Conditional] MetaTagCnsetSeenFAI MUST NOT be present if the SynchronizationType field is set to Hierarchy (0x02), as specified in section 2.2.3.2.1.1.1."); // This isn't New ChangeNumber for CnsetReadProperty in Initialize. abstractFastTransferStream.AbstractHierarchySync.FinalICSState.IsNewCnsetReadPropertyChangeNumber = false; ModelHelper.CaptureRequirement(1211, "[In state Element] [MetaTagCnsetRead,Conditional] MetaTagCnsetRead MUST NOT be present if the SynchronizationType field is set to Hierarchy (0x02)."); // In case of SynchronizationExtraFlag is EID in current DownloadContext. if (((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.Eid) == SynchronizationExtraFlag.Eid) && (currentFolder.SubFolderIds.Count > 0)) { // Because the SynchronizationExtraFlag is EID and the SynchronizationExtraFlag only set Eid. So can cover requirement here. ModelHelper.CaptureRequirement(2730, "[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] Reply is the same whether unknown flags [0x00000010] is set or not."); // In case of SynchronizationExtraFlag is EID in current DownloadContext. if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.Eid) == SynchronizationExtraFlag.Eid) { // The PidTagFolderId must be exist in folder change of HierarchySync. abstractFastTransferStream.AbstractHierarchySync.FolderchangeInfo.IsPidTagFolderIdExist = true; // Because the SynchronizationExtraFlag is EID and the SynchronizationExtraFlag only set Eid. So can cover requirement here. ModelHelper.CaptureRequirement(1095, "[In folderChange Element] [PidTagFolderId, Conditional] PidTagFolderId MUST be present if and only if the Eid flag of the SynchronizationExtraFlags field is set."); ModelHelper.CaptureRequirement( 2191, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagFolderId property (section 2.2.1.2.2) in a folder change header if and only if the Eid flag of the SynchronizationExtraFlags field flag is set."); ModelHelper.CaptureRequirement( 2761, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagMid property (section 2.2.1.2.1) in a message change header if and only if the Eid flag of the SynchronizationExtraFlags field is set."); if (currentDownloadContext.SynchronizationType == SynchronizationTypes.Hierarchy) { ModelHelper.CaptureRequirement( 3500, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagFolderId property in the folder change header if the SynchronizationType field is set to Hierarchy (0x02), as specified in section 2.2.3.2.1.1.1."); } } else { // The PidTagFolderId must be not exist in folder change of HierarchySync. abstractFastTransferStream.AbstractHierarchySync.FolderchangeInfo.IsPidTagFolderIdExist = false; ModelHelper.CaptureRequirement( 716001, @"[In RopSynchronizationConfigure ROP Request Buffer] [SynchronizationExtraFlags, When the flag name is Eid, the value is 0x00000001] The server does not include the PidTagFolderId (section 2.2.1.2.2) property in the folder change header when the Eid flag of the SynchronizationExtraFlag field is not set."); } } else { // The PidTagFolderId must be not exist in folder change of HierarchySync. abstractFastTransferStream.AbstractHierarchySync.FolderchangeInfo.IsPidTagFolderIdExist = false; ModelHelper.CaptureRequirement( 716001, @"[In RopSynchronizationConfigure ROP Request Buffer] [SynchronizationExtraFlags, When the flag name is Eid, the value is 0x00000001] The server does not include the PidTagFolderId (section 2.2.1.2.2) property in the folder change header when the Eid flag of the SynchronizationExtraFlag field is not set."); } // In case of SynchronizationExtraFlag is NoForeignIdentifiers in current DownloadContext. if (((currentDownloadContext.Synchronizationflag & SynchronizationFlag.NoForeignIdentifiers) == SynchronizationFlag.NoForeignIdentifiers) && (currentFolder.SubFolderIds.Count > 0)) { // The PidTagParentFolderId must be exist in folder change of HierarchySync. abstractFastTransferStream.AbstractHierarchySync.FolderchangeInfo.IsPidTagParentFolderIdExist = true; ModelHelper.CaptureRequirement(1097, "[In folderChange Element] [PidTagParentFolderId, Conditional] PidTagParentFolderId MUST be present if the NoForeignIdentifiers flag of the SynchronizationFlags field is set."); // The PidTagParentSourceKey and PidTagSourceKey must be exist in folder change of HierarchySync. abstractFastTransferStream.AbstractHierarchySync.FolderchangeInfo.IsPidTagParentSourceKeyValueZero = false; abstractFastTransferStream.AbstractHierarchySync.FolderchangeInfo.IsPidTagSourceKeyValueZero = false; ModelHelper.CaptureRequirement( 2178001, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the NoForeignIdentifiers flag of the SynchronizationFlags field is set, server will return null values for the PidTagSourceKey property (section 2.2.1.2.5) and PidTagParentSourceKey (section 2.2.1.2.6) properties when producing the FastTransfer stream for folder and message changes."); ModelHelper.CaptureRequirement(2077, "[In Generating the PidTagSourceKey Value] When requested by the client, the server MUST output the PidTagSourceKey property (section 2.2.1.2.5) value if it is persisted."); ModelHelper.CaptureRequirement( 2179001, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the NoForeignIdentifiers flag of the SynchronizationFlags field is not set, server will return not null values for the PidTagSourceKey and PidTagParentSourceKey properties when producing the FastTransfer stream for folder and message changes."); } else { // The PidTagFolderId must be not exist in folder change of HierarchySync. abstractFastTransferStream.AbstractHierarchySync.FolderchangeInfo.IsPidTagParentFolderIdExist = false; } // Sub folder count. int subFolderCount = 0; // Record all descendant folders. Set<int> allDescendantFolders = new Set<int>(); if (currentFolder.SubFolderIds.Count > 0) { // Search the current folder in FolderContainer. foreach (AbstractFolder tempFolder in currentConnection.FolderContainer) { if (currentFolder.FolderIdIndex == tempFolder.ParentFolderIdIndex) { // Set the value to the related variable when the current folder is existent. if (!currentDownloadContext.UpdatedState.IdsetGiven.Contains(tempFolder.FolderIdIndex)) { // Because of identify that It is a folder by (CurrentFolder.FolderIdIndex == tempFolder.ParentFolderIdIndex) and identify that change number is not in PidTagCnsetSeen by (!currentDownloadContext.UpdatedState.CnsetSeen.Contains(tempFolder.changeNumberIndex)). so can cover requirement here. ModelHelper.CaptureRequirement( 2042, @"[In Determining What Differences To Download] For every object in the synchronization scope, servers MUST do the following: Include the following syntactical elements in the FastTransfer stream of the OutputServerObject field of the FastTransfer download ROPs, as specified in section 2.2.3.1.1, if one of the following applies: Include the folderChange element, as specified in section 2.2.4.3.5, if the object specified by the InputServerObject field of the FastTransfer download ROP request is a Folder object And the change number is not included in the value of the MetaTagCnsetSeen property (section 2.2.1.1.2)."); // Add current folder id to IdsetGiven of DownloadContext when the IdsetGiven of updatedState contains the current folder id. currentDownloadContext.UpdatedState.IdsetGiven = currentDownloadContext.UpdatedState.IdsetGiven.Add(tempFolder.FolderIdIndex); // Assign a new change number for CnsetSeenProperty. abstractFastTransferStream.AbstractHierarchySync.FinalICSState.IsNewCnsetSeenPropertyChangeNumber = true; if (priorUploadOperation == PriorOperation.RopSynchronizationImportHierarchyChange) { ModelHelper.CaptureRequirement( 2235, @"[In Receiving a RopSynchronizationImportHierarchyChange Request] Upon successful completion of this ROP, the ICS state on the synchronization context MUST be updated to include a new change number in the MetaTagCnsetSeen property (section 2.2.1.1.2)."); } subFolderCount++; } else { if (!currentDownloadContext.UpdatedState.CnsetSeen.Contains(tempFolder.ChangeNumberIndex)) { // Add current folder id to updatedState.IdsetGiven when the IdsetGiven of updatedState contains the current folder id. currentDownloadContext.UpdatedState.CnsetSeen = currentDownloadContext.UpdatedState.CnsetSeen.Add(tempFolder.ChangeNumberIndex); abstractFastTransferStream.AbstractHierarchySync.FinalICSState.IsNewCnsetSeenPropertyChangeNumber = true; // Because of identify that It is a folder by (CurrentFolder.FolderIdIndex == tempFolder.ParentFolderIdIndex) and identify that change number is not in PidTagCnsetSeen by (!currentDownloadContext.UpdatedState.CnsetSeen.Contains(tempFolder.changeNumberIndex)). so can cover requirement here. ModelHelper.CaptureRequirement( 2042, @"[In Determining What Differences To Download] For every object in the synchronization scope, servers MUST do the following: Include the following syntactical elements in the FastTransfer stream of the OutputServerObject field of the FastTransfer download ROPs, as specified in section 2.2.3.1.1, if one of the following applies: Include the folderChange element, as specified in section 2.2.4.3.5, if the object specified by the InputServerObject field of the FastTransfer download ROP request is a Folder object And the change number is not included in the value of the MetaTagCnsetSeen property (section 2.2.1.1.2)."); if (priorUploadOperation == PriorOperation.RopSynchronizationImportHierarchyChange) { ModelHelper.CaptureRequirement( 2235, @"[In Receiving a RopSynchronizationImportHierarchyChange Request] Upon successful completion of this ROP, the ICS state on the synchronization context MUST be updated to include a new change number in the MetaTagCnsetSeen property (section 2.2.1.1.2)."); } subFolderCount++; } } // In case of current folder's subFolder count greater the 0. if (tempFolder.SubFolderIds.Count > 0) { // Find the second Folder in FolderContainer which was created under current folder. foreach (AbstractFolder secondFolder in currentConnection.FolderContainer) { if (secondFolder.ParentFolderIdIndex == tempFolder.FolderIdIndex) { if (!currentDownloadContext.UpdatedState.IdsetGiven.Contains(secondFolder.FolderIdIndex)) { // Add current folder id to updatedState.IdsetGiven when the IdsetGiven of updatedState contains the current folder id. currentDownloadContext.UpdatedState.IdsetGiven = currentDownloadContext.UpdatedState.IdsetGiven.Add(secondFolder.FolderIdIndex); // Assign a new change number for CnsetSeenPropery. abstractFastTransferStream.AbstractHierarchySync.FinalICSState.IsNewCnsetSeenPropertyChangeNumber = true; if (priorUploadOperation == PriorOperation.RopSynchronizationImportHierarchyChange) { ModelHelper.CaptureRequirement( 2235, @"[In Receiving a RopSynchronizationImportHierarchyChange Request] Upon successful completion of this ROP, the ICS state on the synchronization context MUST be updated to include a new change number in the MetaTagCnsetSeen property (section 2.2.1.1.2)."); } subFolderCount++; } else { if (!currentDownloadContext.UpdatedState.CnsetSeen.Contains(secondFolder.ChangeNumberIndex)) { // Add current folder id to updatedState.CnsetSeen when the CnsetSeen of updatedState contains the current folder id. currentDownloadContext.UpdatedState.CnsetSeen = currentDownloadContext.UpdatedState.CnsetSeen.Add(secondFolder.ChangeNumberIndex); // Assign a new change number for CnsetSeenProperty. abstractFastTransferStream.AbstractHierarchySync.FinalICSState.IsNewCnsetSeenPropertyChangeNumber = true; if (priorUploadOperation == PriorOperation.RopSynchronizationImportHierarchyChange) { ModelHelper.CaptureRequirement( 2235, @"[In Receiving a RopSynchronizationImportHierarchyChange Request] Upon successful completion of this ROP, the ICS state on the synchronization context MUST be updated to include a new change number in the MetaTagCnsetSeen property (section 2.2.1.1.2)."); } subFolderCount++; } } } // Add second Folder to descendant folder. allDescendantFolders = allDescendantFolders.Add(secondFolder.FolderIdIndex); } } // Add second Folder to descendant folder. allDescendantFolders = allDescendantFolders.Add(tempFolder.FolderIdIndex); } } } // Search the Descendant folderId in IdsetGiven. foreach (int folderId in currentDownloadContext.UpdatedState.IdsetGiven) { // Identify whether the last Updated Id is or not in Descendant Folder. if (!allDescendantFolders.Contains(folderId)) { if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.NoDeletions) == SynchronizationFlag.NoDeletions) { if (requirementContainer.ContainsKey(1062) && requirementContainer[1062]) { // Deletions isn't present in deletions. abstractFastTransferStream.AbstractHierarchySync.AbstractDeletion.IsDeletionPresent = false; ModelHelper.CaptureRequirement( 1062, @"[In deletions Element] Implementation does not present deletions element if the NoDeletions flag of the SynchronizationFlag field, as specified in section 2.2.3.2.1.1.1, was set when the synchronization download operation was configured. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } // Deletions isn't present in deletions. abstractFastTransferStream.AbstractHierarchySync.AbstractDeletion.IsDeletionPresent = false; ModelHelper.CaptureRequirement( 2165, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the NoDeletions flag of the SynchronizationFlags field is set, the server MUST NOT download information about item deletions, as specified in section 2.2.4.3.3"); } else { // Deletions is present in deletions. abstractFastTransferStream.AbstractHierarchySync.AbstractDeletion.IsDeletionPresent = true; // PidTagIdsetNoLongerInScope be present in deletions abstractFastTransferStream.AbstractHierarchySync.AbstractDeletion.IsPidTagIdsetNoLongerInScopeExist = false; ModelHelper.CaptureRequirement( 1333, @"[In deletions Element] [The following restrictions exist on the contained propList element, as specified in section 2.2.4.3.20:] MUST adhere to the following restrictions: MetaTagIdsetNoLongerInScope MUST NOT be present if the Hierarchy value of the SynchronizationType field is set, as specified in section 2.2.3.2.1.1.1."); // Are folders that have never been reported as deleted abstractFastTransferStream.AbstractHierarchySync.AbstractDeletion.IsPidTagIdsetExpiredExist = false; ModelHelper.CaptureRequirement( 2046, @"[In Determining What Differences To Download] [For every object in the synchronization scope, servers MUST do the following:] If the NoDeletions flag of the SynchronizationFlags field is not set, include the deletions element, as specified in section 2.2.4.3.3, for objects that either: Have their internal identifiers present in the value of the MetaTagIdsetGiven property (section 2.2.1.1.1) and are missing from the server replica.Are folders that have never been reported as deleted folders. Are folders that have never been reported as deleted folders."); ModelHelper.CaptureRequirement( 1337002, @"[In deletions Element] [The following restrictions exist on the contained propList element, as specified in section 2.2.4.3.20:] MUST adhere to the following restrictions: ] MetaTagIdsetExpired (section 2.2.1.3.3) MUST NOT be present if the Hierarchy value of the SynchronizationType field is set. "); // Because isPidTagIdsetExpiredExist value is false so have their internal identifiers present in PidTagIdsetGiven and isDeletionPresent is true to those are missing from the server replica. So cover requirement here. ModelHelper.CaptureRequirement( 2045, @"[In Determining What Differences To Download] [For every object in the synchronization scope, servers MUST do the following:] If the NoDeletions flag of the SynchronizationFlag field is not set, include the deletions element, as specified in section 2.2.4.3.3, for objects that either: Have their internal identifiers present in the value of the MetaTagIdsetGiven property (section 2.2.1.1.1) and are missing from the server replica.Are folders that have never been reported as deleted folders. Are folders that have never been reported as deleted folders."); // Identify the current ExchangeServer Version. if (requirementContainer.ContainsKey(2652) && requirementContainer[2652]) { // Add folderId to IdSetDeleted of abstractDeletion abstractFastTransferStream.AbstractHierarchySync.AbstractDeletion.IdSetDeleted = abstractFastTransferStream.AbstractHierarchySync.AbstractDeletion.IdSetDeleted.Add(folderId); // Because of execute RopSynchronizationImportHierarchyChange or RopSynchronizationImportMessageChange operation before execute RopSynchronizationImportDeletes operation, record deletions and prevent it restoring them back finished in MS_OXCFXICSAdapter. So cover this requirement here. ModelHelper.CaptureRequirement( 2652, @"[In Receiving a RopSynchronizationImportDeletes Request] Implementation does record deletions of objects that never existed in the server replica, in order to prevent the RopSynchronizationImportHierarchyChange (section 2.2.3.2.4.3) or RopSynchronizationImportMessageChange (section 2.2.3.2.4.2) ROPs from restoring them back. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } // Delete folder id from DownloadContext. currentDownloadContext.UpdatedState.IdsetGiven = currentDownloadContext.UpdatedState.IdsetGiven.Remove(folderId); // If NoDeletions flag is not set and the operation can be executed successfully, the element isDeletionPresent as true will be returned, which means the deletion elements is downloaded, so this requirement can be verified. ModelHelper.CaptureRequirement( 2167, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the NoDeletions flag of the SynchronizationFlags field is not set, the server MUST download information about item deletions, as specified in section 2.2.4.3.3."); } // This is a new changeNumber abstractFastTransferStream.AbstractHierarchySync.FinalICSState.IsNewCnsetSeenPropertyChangeNumber = true; if (priorUploadOperation == PriorOperation.RopSynchronizationImportHierarchyChange) { ModelHelper.CaptureRequirement( 2235, @"[In Receiving a RopSynchronizationImportHierarchyChange Request] Upon successful completion of this ROP, the ICS state on the synchronization context MUST be updated to include a new change number in the MetaTagCnsetSeen property (section 2.2.1.1.2)."); } } } // The lDescendantFolder is existent. if (currentFolder.SubFolderIds == allDescendantFolders) { if (allDescendantFolders.Count > 0) { // Parent folder is existent and PidTagParentSourceKey is not in folder change abstractFastTransferStream.AbstractHierarchySync.FolderchangeInfo.IsPidTagParentSourceKeyValueZero = true; } } else { ModelHelper.CaptureRequirement(1129, "[In hierarchySync Element]The folderChange elements for the parent folders MUST be output before any of their child folders."); abstractFastTransferStream.AbstractHierarchySync.IsParentFolderBeforeChild = true; } // Set value for finalICSState. abstractFastTransferStream.AbstractHierarchySync.FinalICSState.IdSetGiven = currentDownloadContext.UpdatedState.IdsetGiven; abstractFastTransferStream.AbstractHierarchySync.FolderCount = subFolderCount; currentFolder.ICSStateContainer.Add(abstractFastTransferStream.AbstractHierarchySync.FinalICSState.AbstractICSStateIndex, currentDownloadContext.UpdatedState); // Because of the "foreach" Search the Descendant folderId in IdsetGive and the end of "foreach" search. So cover this requirement here. ModelHelper.CaptureRequirement(1128, "[In hierarchySync Element]There MUST be exactly one folderChange element for each descendant folder of the root of the synchronization operation (that is the folder that was passed to the RopSynchronizationConfigure ROP, as specified in section 2.2.3.2.1.1) that is new or has been changed since the last synchronization."); // Update the FolderContainer. currentConnection.FolderContainer = currentConnection.FolderContainer.Update(currentFolderIndex, currentFolder); connections[serverId] = currentConnection; break; } // The state element contains the final ICS state of the synchronization download operation. case FastTransferStreamType.state: { if (priorDownloadOperation == PriorDownloadOperation.RopSynchronizationGetTransferState) { // Because if the isRopSynchronizationGetTransferState called the steam type return by RopFastTransferSourceGetBuffer should be State ModelHelper.CaptureRequirement( 3323, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopSynchronizationGetTransferState, ROP request buffer field conditions is always, Root element in the produced FastTransfer stream is state."); } // Create a new abstractState. abstractFastTransferStream.AbstractState = new AbstractState { AbstractICSStateIndex = AdapterHelper.GetICSStateIndex() }; // Assign a new ICS State Index. // The new IdSetGiven of State value equal to IdsetGiven of current download context. if (requirementContainer.ContainsKey(350400101) && requirementContainer[350400101] && (priorOperation == PriorOperation.RopSynchronizationOpenCollector)) { abstractFastTransferStream.AbstractState.IdSetGiven = new Set<int>(); ModelHelper.CaptureRequirement( 350400101, @"[In Appendix A: Product Behavior] Implementation does use this behavior. <43> Section 3.2.5.9.3.1: In Exchange 2007, the RopSynchronizationGetTransferState ROP (section 2.2.3.2.3.1) returns a checkpoint ICS state that is reflective of the current status."); } else { abstractFastTransferStream.AbstractState.IdSetGiven = currentDownloadContext.UpdatedState.IdsetGiven; } // Add the new stat to ICSStateContainer. currentFolder.ICSStateContainer.Add(abstractFastTransferStream.AbstractState.AbstractICSStateIndex, currentDownloadContext.UpdatedState); currentConnection.FolderContainer = currentConnection.FolderContainer.Update(currentFolderIndex, currentFolder); connections[serverId] = currentConnection; break; } // The messageContent element represents the content of a message. case FastTransferStreamType.contentsSync: { if (currentDownloadContext.SynchronizationType == SynchronizationTypes.Contents && priorDownloadOperation == PriorDownloadOperation.RopSynchronizationConfigure) { // Because if the synchronizationType in synchronization configure and the stream type return are contents indicate this requirement verified. ModelHelper.CaptureRequirement( 3321, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopSynchronizationConfigure, ROP request buffer field conditions is The SynchronizationType field is set to Contents (0x01), Root element in the produced FastTransfer stream is contentsSync."); } // Create a new abstractContentsSync. abstractFastTransferStream.AbstractContentsSync = new AbstractContentsSync { MessageInfo = new Set<AbstractMessageChangeInfo>(), AbstractDeletion = { IdSetDeleted = new Set<int>() }, FinalICSState = new AbstractState { // Assign abstractICSStateIndex. AbstractICSStateIndex = AdapterHelper.GetICSStateIndex() } }; // Create a new finalICSState. if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.Progress) == SynchronizationFlag.Progress) { // The current ContentsSync is include progressTotal. abstractFastTransferStream.AbstractContentsSync.IsprogessTotalPresent = true; ModelHelper.CaptureRequirement(1179, "[In progressTotal Element]This element MUST be present if the Progress flag of the SynchronizationFlags field, as specified in section 2.2.3.2.1.1.1, was set when configuring the synchronization download operation and a server supports progress reporting."); if (requirementContainer.ContainsKey(2675) && requirementContainer[2675]) { // The current ContentsSync is include progressTotal. abstractFastTransferStream.AbstractContentsSync.IsprogessTotalPresent = true; // The current server is exchange. ModelHelper.CaptureRequirement( 2675, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] Implementation does inject the progressTotal element, as specified in section 2.2.4.3.19, into the FastTransfer stream, if the Progress flag of the SynchronizationFlag field is set. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } } else { // The current ContentsSync is not include progressTotal. abstractFastTransferStream.AbstractContentsSync.IsprogessTotalPresent = false; ModelHelper.CaptureRequirement( 2188, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the Progress flag of the SynchronizationFlags field is not set, the server MUST not inject the progressTotal element into the FastTransfer stream."); ModelHelper.CaptureRequirement(1180, "[In progressTotal Element]This element MUST NOT be present if the Progress flag of the SynchronizationFlags field was not set when configuring the synchronization download operation."); } // Search the message ids in IdsetGiven. foreach (int messageId in currentDownloadContext.UpdatedState.IdsetGiven) { if (!currentFolder.MessageIds.Contains(messageId)) { // Assign a new change number for CnsetRead Property. if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.NoDeletions) == SynchronizationFlag.NoDeletions) { // The server MUST NOT download information about item deletions. abstractFastTransferStream.AbstractContentsSync.AbstractDeletion.IsDeletionPresent = false; ModelHelper.CaptureRequirement( 2165, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the NoDeletions flag of the SynchronizationFlags field is set, the server MUST NOT download information about item deletions, as specified in section 2.2.4.3.3"); ModelHelper.CaptureRequirement( 2166, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the NoDeletions flag of the SynchronizationFlags field is set, the server MUST respond as if the IgnoreNoLongerInScope flag was set."); } else if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.IgnoreNoLongerInScope) != SynchronizationFlag.IgnoreNoLongerInScope) { // The server MUST download information about item deletions. abstractFastTransferStream.AbstractContentsSync.AbstractDeletion.IsDeletionPresent = true; ModelHelper.CaptureRequirement( 2167, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the NoDeletions flag of the SynchronizationFlags field is not set, the server MUST download information about item deletions, as specified in section 2.2.4.3.3."); // Identify the current ExchangeServer Version. if (requirementContainer.ContainsKey(2652) && requirementContainer[2652]) { // Add messageId to abstractDeletion of abstractDeletion. abstractFastTransferStream.AbstractContentsSync.AbstractDeletion.IdSetDeleted = abstractFastTransferStream.AbstractContentsSync.AbstractDeletion.IdSetDeleted.Add(messageId); // Because of execute RopSynchronizationImportHierarchyChange or RopSynchronizationImportMessageChange operation before execute RopSynchronizationImportDeletes operation, record deletions and prevent it restoring them back finished in MS_OXCFXICSAdapter. So cover this requirement here. ModelHelper.CaptureRequirement( 2652, @"[In Receiving a RopSynchronizationImportDeletes Request] Implementation does record deletions of objects that never existed in the server replica, in order to prevent the RopSynchronizationImportHierarchyChange (section 2.2.3.2.4.3) or RopSynchronizationImportMessageChange (section 2.2.3.2.4.2) ROPs from restoring them back. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } currentDownloadContext.UpdatedState.IdsetGiven = currentDownloadContext.UpdatedState.IdsetGiven.Remove(messageId); ModelHelper.CaptureRequirement( 2169, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the IgnoreNoLongerInScope flag of the SynchronizationFlags field is not set, the server MUST download information about messages that went out of scope as deletions, as specified in section 2.2.4.3.3."); } if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.IgnoreNoLongerInScope) == SynchronizationFlag.IgnoreNoLongerInScope) { // PidTagIdsetNoLongerInScope MUST NOT be present. abstractFastTransferStream.AbstractContentsSync.AbstractDeletion.IsPidTagIdsetNoLongerInScopeExist = false; ModelHelper.CaptureRequirement(1334, @"[In deletions Element] [The following restrictions exist on the contained propList element, as specified in section 2.2.4.3.20:] MUST adhere to the following restrictions: MetaTagIdsetNoLongerInScope MUST NOT be present if the IgnoreNoLongerInScope flag of the SynchronizationFlags field is set."); ModelHelper.CaptureRequirement( 2168, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the IgnoreNoLongerInScope flag of the SynchronizationFlags field is set, the server MUST NOT download information about messages that went out of scope as deletions, as specified in section 2.2.4.3.3."); } } } #region Set message change contents // Search the current message which match search condition in MessageContainer foreach (AbstractMessage tempMessage in currentConnection.MessageContainer) { if (tempMessage.FolderIdIndex == currentFolder.FolderIdIndex) { // The found message is FAI message. if (tempMessage.IsFAImessage) { if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.FAI) == SynchronizationFlag.FAI) { if (!currentDownloadContext.UpdatedState.IdsetGiven.Contains(tempMessage.MessageIdIndex)) { // Create a new messageChange of contentSync. AbstractMessageChangeInfo newMessageChange = new AbstractMessageChangeInfo { MessageIdIndex = tempMessage.MessageIdIndex, IsMessageChangeFull = true }; // Set the value for new messageChange. // This MessageChangeFull is in new message change. if ((currentDownloadContext.Sendoptions & SendOptionAlls.PartialItem) != SendOptionAlls.PartialItem) { ModelHelper.CaptureRequirement( 1135, @"[In messageChange Element] A server MUST use the messageChangeFull element, instead of the messageChangePartial element, if any of the following are true: The PartialItem flag of the SendOptions field was not set, as specified in section 2.2.3.2.1.1."); } // Because SynchronizationFlag is set FAI and isMessageChangeFull is true so can cover requirement here. ModelHelper.CaptureRequirement(1137, @"[In messageChange Element] [A server MUST use the messageChangeFull element, instead of the messageChangePartial element, if any of the following are true:] The message is an FAI message."); if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.CN) == SynchronizationExtraFlag.CN) { // PidTagChangeNumber must be present . newMessageChange.IsPidTagChangeNumberExist = true; // Because the SynchronizationExtraFlag is CN and the SynchronizationExtraFlag only set CN. So can cover requirement here. ModelHelper.CaptureRequirement(1367, "[In messageChangeHeader Element, PidTagChangeNumber,Conditional]PidTagChangeNumber MUST be present if and only if the CN flag of the SynchronizationExtraFlags field is set."); // Because the SynchronizationExtraFlag is CN and the SynchronizationExtraFlag only set CN. So can cover requirement here. ModelHelper.CaptureRequirement( 2196, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagChangeNumber property (section 2.2.1.2.3) in the message change header if and only if the CN flag of the SynchronizationExtraFlags field is set."); } else { // PidTagChangeNumber must not present . newMessageChange.IsPidTagChangeNumberExist = false; // Because the SynchronizationExtraFlag is not CN and the SynchronizationExtraFlag only don't set CN. So can cover requirement here. ModelHelper.CaptureRequirement( 2197, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST NOT include the PidTagChangeNumber property in the message change header if and only if the CN flag of the SynchronizationExtraFlags field is not set."); } if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.Eid) == SynchronizationExtraFlag.Eid) { // The server MUST include the PidTagMid property in the messageChange. newMessageChange.IsPidTagMidExist = true; // Because the SynchronizationExtraFlag is EID and the SynchronizationExtraFlag only set EID. So can cover requirement here. ModelHelper.CaptureRequirement(1363, "[In messageChangeHeader Element] [PidTagMid,Conditional] PidTagMid MUST be present if and only if the Eid flag of the SynchronizationExtraFlags field is set, as specified in section 2.2.3.2.1.1.1."); } else { // The server don't include the PidTagFolderId property in the messageChange. newMessageChange.IsPidTagMidExist = false; } if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.MessageSize) == SynchronizationExtraFlag.MessageSize) { // The server include the PidTagMessageSize property in the messageChange. newMessageChange.IsPidTagMessageSizeExist = true; // Because the SynchronizationExtraFlag is MessageSize and the SynchronizationExtraFlag only set MessageSize. So can cover requirement here. ModelHelper.CaptureRequirement( 2195, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagMessageSize property (section 2.2.1.6) in the message change header if and only if the MessageSize flag of the SynchronizationExtraFlags field is set."); ModelHelper.CaptureRequirement( 1365, @"[In messageChangeHeader Element] [PidTagMessageSize,Conditional] PidTagMessageSize MUST be present if and only if the MessageSize flag of the SynchronizationExtraFlags field is set."); } if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.Progress) == SynchronizationFlag.Progress) { // The server must include the ProgressPerMessage in the messageChange. newMessageChange.IsProgressPerMessagePresent = true; // Message object that follows is FAI newMessageChange.FollowedFAIMessage = true; // Because the SynchronizationExtraFlag is Progress and the SynchronizationExtraFlag only set Progress. So can cover requirement here. ModelHelper.CaptureRequirement( 1171, @"[In progressPerMessage Element]MUST be present if and only if the progessTotal element, as specified in section 2.2.4.3.18, was output within the same ancestor contentsSync element, as specified in section 2.2.4.3.2."); ModelHelper.CaptureRequirement( 1382, @"[In progressPerMessage Element] [[PtypBoolean] 0x0000000B] [The server returns] TRUE (0x01 or any non-zero value) if the Message object that follows is FAI."); } else { // The server don't include the ProgressPerMessage in the messageChange. newMessageChange.IsProgressPerMessagePresent = false; ModelHelper.CaptureRequirement( 1172, @"[In progressPerMessage Element] [ProgressPerMessage Element] MUST NOT be present if the Progress flag of the SynchronizationFlags field was not set when configuring the synchronization download operation."); } if (tempMessage.MessageProperties.Contains("PidTagBody")) { if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.BestBody) != SynchronizationFlag.BestBody) { // Implementation does only support the message body (2) which is always in the original format if (requirementContainer.ContainsKey(3118002) && requirementContainer[3118002]) { newMessageChange.IsRTFformat = false; ModelHelper.CaptureRequirement( 3118002, @"[In Appendix A: Product Behavior] Implementation does only support the message body which is always in the original format. &lt;3&gt; Section 2.2.3.1.1.1.1: In Exchange 2013, Exchange 2016, and Exchange 2019, the message body is always in the original format."); } if (requirementContainer.ContainsKey(2117002) && requirementContainer[2117002]) { // Identify whether message bodies in the compressed RTF format is or not. newMessageChange.IsRTFformat = true; // Because the BestBody flag of the CopyFlags field is not set before and the prior ROP is RopFastTransferSourceCopyMessages, so this requirement can be captured. ModelHelper.CaptureRequirement( 2117002, @"[In Appendix A: Product Behavior] <36> Section 3.2.5.8.1.3: Implementation does support the BestBody flag. If the BestBody flag of the CopyFlags field is not set, implementation does output message bodies in the compressed RTF (Microsoft Exchange Server 2007 and Exchange Server 2010 follow this behavior.)"); } if (requirementContainer.ContainsKey(3118003) && requirementContainer[3118003]) { // Identify whether message bodies in the compressed RTF format is or not. newMessageChange.IsRTFformat = true; // Because the BestBody flag of the CopyFlags field is not set before and the prior ROP is RopFastTransferSourceCopyMessages, so this requirement can be captured. ModelHelper.CaptureRequirement( 3118003, @"[In Appendix A: Product Behavior] Implementation does support this flag [BestBody flag] [in RopFastTransferSourceCopyTo ROP]. (<3> Section 2.2.3.1.1.1.1: Microsoft Exchange Server 2007 and 2010 follow this behavior.)"); } if (requirementContainer.ContainsKey(499001) && requirementContainer[499001]) { // Identify whether message bodies in the compressed RTF format is or not. newMessageChange.IsRTFformat = false; // Because the BestBody flag of the CopyFlags field is set before and the prior ROP is RopFastTransferSourceCopyMessages, so this requirement can be captured. ModelHelper.CaptureRequirement( 499001, @"[In Appendix A: Product Behavior] Implementation does only support the message body which is always in the original format. &lt;5&gt; Section 2.2.3.1.1.3.1: In Exchange 2013, Exchange 2016, and Exchange 2019, the message body is always in the original format."); } if (requirementContainer.ContainsKey(2182002) && requirementContainer[2182002]) { // Identify whether message bodies in the compressed RTF format is or not. newMessageChange.IsRTFformat = true; // Because the BestBody flag of the CopyFlags field is set before and the prior ROP is RopFastTransferSourceCopyMessages, so this requirement can be captured. ModelHelper.CaptureRequirement( 2182002, @"[In Appendix A: Product Behavior] Implementation does support BestBody flag [in RopSynchronizationConfigure ROP]. (<41> Section 3.2.5.9.1.1: Microsoft Exchange Server 2007 and Exchange Server 2010 follow this behavior.)"); } } } // Add new messagChange to ContentsSync. abstractFastTransferStream.AbstractContentsSync.MessageInfo = abstractFastTransferStream.AbstractContentsSync.MessageInfo.Add(newMessageChange); // Add message id to IdsetGiven of current download context. currentDownloadContext.UpdatedState.IdsetGiven = currentDownloadContext.UpdatedState.IdsetGiven.Add(tempMessage.MessageIdIndex); ModelHelper.CaptureRequirement( 2172, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the FAI flag of the SynchronizationFlags field is set, the server MUST download information about changes to FAI messages, as specified by the folderContents element in section 2.2.4.3.7."); } else if (!currentDownloadContext.UpdatedState.CnsetSeenFAI.Contains(tempMessage.ChangeNumberIndex)) { // The message change number is not in CnsetSeenFAI property. // Create a new message change. AbstractMessageChangeInfo newMessageChange = new AbstractMessageChangeInfo { MessageIdIndex = tempMessage.MessageIdIndex, IsMessageChangeFull = true }; // Set message id for new messageChange // The server don't include messagchangeFull in messageChange. ModelHelper.CaptureRequirement( 1137, @"[In messageChange Element] [A server MUST use the messageChangeFull element, instead of the messageChangePartial element, if any of the following are true:] The message is an FAI message."); if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.CN) == SynchronizationExtraFlag.CN) { // The server MUST include the PidTagChangeNumber property in the message change newMessageChange.IsPidTagChangeNumberExist = true; // Because the SynchronizationExtraFlag is CN and the SynchronizationExtraFlag only set CN. So can cover requirement here. ModelHelper.CaptureRequirement( 2196, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagChangeNumber property (section 2.2.1.2.3) in the message change header if and only if the CN flag of the SynchronizationExtraFlags field is set."); } else { // The server don't include the PidTagChangeNumber property in the message change newMessageChange.IsPidTagChangeNumberExist = false; // Because the SynchronizationExtraFlag is not CN and the SynchronizationExtraFlag not only set CN. So can cover requirement here. ModelHelper.CaptureRequirement( 2197, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST NOT include the PidTagChangeNumber property in the message change header if and only if the CN flag of the SynchronizationExtraFlags field is not set."); } if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.Eid) == SynchronizationExtraFlag.Eid) { // The server MUST include the PidTagFolderId property in the messageChange. newMessageChange.IsPidTagMidExist = true; // Because the SynchronizationExtraFlag is EID and the SynchronizationExtraFlag only set Eid. So can cover requirement here. ModelHelper.CaptureRequirement( 2191, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagFolderId property (section 2.2.1.2.2) in a folder change header if and only if the Eid flag of the SynchronizationExtraFlags field flag is set."); ModelHelper.CaptureRequirement( 2761, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagMid property (section 2.2.1.2.1) in a message change header if and only if the Eid flag of the SynchronizationExtraFlags field is set."); } else { // The server MUST NOT include the PidTagMid property in the messageChange. newMessageChange.IsPidTagMidExist = false; // Because the SynchronizationExtraFlag is Eid and the SynchronizationExtraFlag only set Eid. So can cover requirement here. ModelHelper.CaptureRequirement( 716002, @"[In RopSynchronizationConfigure ROP Request Buffer] [SynchronizationExtraFlags, When the flag name is Eid, the value is 0x00000001] The server does not include the PidTagMid (section 2.2.1.2.1) property in the message change header when the Eid flag of the SynchronizationExtraFlag field is not set."); } if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.MessageSize) == SynchronizationExtraFlag.MessageSize) { ModelHelper.CaptureRequirement( 2195, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagMessageSize property (section 2.2.1.6) in the message change header if and only if the MessageSize flag of the SynchronizationExtraFlags field is set."); // The server MUST include the PidTagMessageSize property in the message change. newMessageChange.IsPidTagMessageSizeExist = true; // Because the SynchronizationExtraFlag is MessageSize and the SynchronizationExtraFlag only set MessageSize. So can cover requirement here. ModelHelper.CaptureRequirement( 1365, @"[In messageChangeHeader Element] [PidTagMessageSize,Conditional] PidTagMessageSize MUST be present if and only if the MessageSize flag of the SynchronizationExtraFlags field is set."); } else { newMessageChange.IsPidTagMessageSizeExist = false; // When the MessageSize flag of the SynchronizationExtraFlag field is not set and the server does not include the PidTagMessageSize property (section 2.2.1.6) in the message change header this requirement captured. ModelHelper.CaptureRequirement( 718001, @"[In RopSynchronizationConfigure ROP Request Buffer] [SynchronizationExtraFlags, When the flag name is MessageSize, the value is 0x00000002] The server does not include the PidTagMessageSize property (section 2.2.1.6) in the message change header if the MessageSize flag of the SynchronizationExtraFlag field is not set."); } if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.Progress) == SynchronizationFlag.Progress) { // The server include ProgressPerMessag in messageChange. newMessageChange.IsProgressPerMessagePresent = true; // The message is a FAl Message. newMessageChange.FollowedFAIMessage = true; // Because the SynchronizationExtraFlag is Progress and the SynchronizationExtraFlag only set Progress. So can cover requirement here. ModelHelper.CaptureRequirement( 1171, @"[In progressPerMessage Element]MUST be present if and only if the progessTotal element, as specified in section 2.2.4.3.18, was output within the same ancestor contentsSync element, as specified in section 2.2.4.3.2."); ModelHelper.CaptureRequirement(1382, "[In progressPerMessage Element] [[PtypBoolean] 0x0000000B] [The server returns] TRUE (0x01 or any non-zero value) if the Message object that follows is FAI."); } else { // The server don't include ProgressPerMessag in messageChange. newMessageChange.IsProgressPerMessagePresent = false; ModelHelper.CaptureRequirement( 1172, @"[In progressPerMessage Element] [ProgressPerMessage Element] MUST NOT be present if the Progress flag of the SynchronizationFlags field was not set when configuring the synchronization download operation."); } if (!messagechangePartail && (requirementContainer.ContainsKey(2172) && !requirementContainer[2172])) { abstractFastTransferStream.AbstractContentsSync.MessageInfo = new Set<AbstractMessageChangeInfo>(); } else { // Add new messagChange to ContentsSync. abstractFastTransferStream.AbstractContentsSync.MessageInfo = abstractFastTransferStream.AbstractContentsSync.MessageInfo.Add(newMessageChange); ModelHelper.CaptureRequirement( 2172, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the FAI flag of the SynchronizationFlags field is set, the server MUST download information about changes to FAI messages, as specified by the folderContents element in section 2.2.4.3.7."); } } } else { // Because SynchronizationFlag FAI flag is not set and no have download context add to abstractFastTransferStream. So can cover this requirement here. ModelHelper.CaptureRequirement( 2173, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the FAI flag of the SynchronizationFlags field is not set, the server MUST NOT download information about changes to FAI messages, as specified by the folderContents element in section 2.2.4.3.7."); } } else { // The found message is Normal message. // SynchronizationFlag is Normal in download context. if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.Normal) == SynchronizationFlag.Normal) { // The message id not in IdsetGiven of download context. if (!currentDownloadContext.UpdatedState.IdsetGiven.Contains(tempMessage.MessageIdIndex)) { // Create a newMessageChange. AbstractMessageChangeInfo newMessageChange = new AbstractMessageChangeInfo { MessageIdIndex = tempMessage.MessageIdIndex, IsMessageChangeFull = true }; // Set message id for newMessageChange. // This messagechangeFull is in newMessageChange. // Because the message object include MId and it is initial ICS state through set sequence. ModelHelper.CaptureRequirement(1136, "[In messageChange Element] [A server MUST use the messageChangeFull element, instead of the messageChangePartial element, if any of the following are true:] The MID structure ([MS-OXCDATA] section 2.2.1.2) of the message to be output is not in the MetaTagIdsetGiven property (section 2.2.1.1.1) from the initial ICS state."); if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.CN) == SynchronizationExtraFlag.CN) { // The server MUST include the PidTagChangeNumber property in the messageChange. newMessageChange.IsPidTagChangeNumberExist = true; // Because the SynchronizationExtraFlag is CN and the SynchronizationExtraFlag only set CN. So can cover requirement here. ModelHelper.CaptureRequirement( 2196, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagChangeNumber property (section 2.2.1.2.3) in the message change header if and only if the CN flag of the SynchronizationExtraFlags field is set."); } else { // The server don't include the PidTagChangeNumber property in the messageChange. newMessageChange.IsPidTagChangeNumberExist = false; // Because the SynchronizationExtraFlag is not CN and the SynchronizationExtraFlag not only set CN. So can cover requirement here. ModelHelper.CaptureRequirement( 2197, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST NOT include the PidTagChangeNumber property in the message change header if and only if the CN flag of the SynchronizationExtraFlags field is not set."); } if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.Eid) == SynchronizationExtraFlag.Eid) { // The server MUST include the PidTagFolderId property in the messageChange. newMessageChange.IsPidTagMidExist = true; // Because the SynchronizationExtraFlag is EID and the SynchronizationExtraFlag only set Eid. So can cover requirement here. ModelHelper.CaptureRequirement( 2191, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagFolderId property (section 2.2.1.2.2) in a folder change header if and only if the Eid flag of the SynchronizationExtraFlags field flag is set."); ModelHelper.CaptureRequirement( 2761, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagMid property (section 2.2.1.2.1) in a message change header if and only if the Eid flag of the SynchronizationExtraFlags field is set."); if (currentDownloadContext.SynchronizationType == SynchronizationTypes.Contents) { ModelHelper.CaptureRequirement( 3501, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagMid property in the message change header if the SynchronizationType field is set Contents (0x01), as specified in section 2.2.3.2.1.1.1."); } } else { // The server don't include the PidTagFolderId property in the messageChange. newMessageChange.IsPidTagMidExist = false; // Because the SynchronizationExtraFlag is Eid and the SynchronizationExtraFlag only set Eid. So can cover requirement here. ModelHelper.CaptureRequirement( 716002, @"[In RopSynchronizationConfigure ROP Request Buffer] [SynchronizationExtraFlags, When the flag name is Eid, the value is 0x00000001] The server does not include the PidTagMid (section 2.2.1.2.1) property in the message change header when the Eid flag of the SynchronizationExtraFlag field is not set."); } if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.MessageSize) == SynchronizationExtraFlag.MessageSize) { ModelHelper.CaptureRequirement( 2195, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagMessageSize property (section 2.2.1.6) in the message change header if and only if the MessageSize flag of the SynchronizationExtraFlags field is set."); // The server MUST include the PidTagMessageSize property in the messageChange. newMessageChange.IsPidTagMessageSizeExist = true; // Because the SynchronizationExtraFlag is MessageSize and the SynchronizationExtraFlag only set MessageSize. So can cover requirement here. ModelHelper.CaptureRequirement( 1365, @"[In messageChangeHeader Element] [PidTagMessageSize,Conditional] PidTagMessageSize MUST be present if and only if the MessageSize flag of the SynchronizationExtraFlags field is set."); } else { newMessageChange.IsPidTagMessageSizeExist = false; ModelHelper.CaptureRequirement( 718001, @"[In RopSynchronizationConfigure ROP Request Buffer] [SynchronizationExtraFlags, When the flag name is MessageSize, the value is 0x00000002] The server does not include the PidTagMessageSize property (section 2.2.1.6) in the message change header if the MessageSize flag of the SynchronizationExtraFlag field is not set."); } if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.Progress) == SynchronizationFlag.Progress) { // The server include the progessTotal in the messageChange. newMessageChange.IsProgressPerMessagePresent = true; // The message object is normal message. newMessageChange.FollowedFAIMessage = false; // Because the SynchronizationExtraFlag is Progress and the SynchronizationExtraFlag only set Progress. So can cover requirement here. ModelHelper.CaptureRequirement( 1171, @"[In progressPerMessage Element]MUST be present if and only if the progessTotal element, as specified in section 2.2.4.3.18, was output within the same ancestor contentsSync element, as specified in section 2.2.4.3.2."); ModelHelper.CaptureRequirement( 1383, @"[In progressPerMessage Element] [[PtypBoolean] 0x0000000B] otherwise[if the Message object that follows is not FAI] ,[the server returns] FALSE (0x00)."); } else { // The server don't include the progessTotal in the messageChange. newMessageChange.IsProgressPerMessagePresent = false; ModelHelper.CaptureRequirement( 1172, @"[In progressPerMessage Element] [ProgressPerMessage Element] MUST NOT be present if the Progress flag of the SynchronizationFlags field was not set when configuring the synchronization download operation."); } // Add new messageChange to ContentsSync. abstractFastTransferStream.AbstractContentsSync.MessageInfo = abstractFastTransferStream.AbstractContentsSync.MessageInfo.Add(newMessageChange); // Add messageId to IdsetGiven of download context. currentDownloadContext.UpdatedState.IdsetGiven = currentDownloadContext.UpdatedState.IdsetGiven.Add(tempMessage.MessageIdIndex); // Because SynchronizationFlag is Normal ModelHelper.CaptureRequirement( 2174, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the Normal flag of the SynchronizationFlags flag is set, the server MUST download information about changes to normal messages, as specified in section 2.2.4.3.11."); } else if (!currentDownloadContext.UpdatedState.CnsetSeen.Contains(tempMessage.ChangeNumberIndex)) { // The message change number is not in CnsetSeenFAI property. // Create a newMessageChange. AbstractMessageChangeInfo newMessageChange = new AbstractMessageChangeInfo { // Set messageId for newMessageChange. MessageIdIndex = tempMessage.MessageIdIndex }; if ((currentDownloadContext.Sendoptions & SendOptionAlls.PartialItem) != SendOptionAlls.PartialItem) { // The server include MessageChangeFull in messageChange. newMessageChange.IsMessageChangeFull = true; ModelHelper.CaptureRequirement( 1135, @"[In messageChange Element]A server MUST use the messageChangeFull element, instead of the messageChangePartial element, if any of the following are true:The PartialItem flag of the SendOptions field was not set, as specified in section 2.2.3.2.1.1."); } else { messagechangePartail = false; // The server include MessageChangePartial in messageChange. newMessageChange.IsMessageChangeFull = false; } if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.CN) == SynchronizationExtraFlag.CN) { // The server include the PidTagChangeNumber property in the messageChange. newMessageChange.IsPidTagChangeNumberExist = true; // Because the SynchronizationExtraFlag is CN and the SynchronizationExtraFlag only set CN. So can cover requirement here. ModelHelper.CaptureRequirement( 2196, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagChangeNumber property (section 2.2.1.2.3) in the message change header if and only if the CN flag of the SynchronizationExtraFlags field is set."); } else { // The server don't include the PidTagChangeNumber property in the messageChange. newMessageChange.IsPidTagChangeNumberExist = false; // Because the SynchronizationExtraFlag is not CN and the SynchronizationExtraFlag not only set CN. So can cover requirement here. ModelHelper.CaptureRequirement( 2197, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST NOT include the PidTagChangeNumber property in the message change header if and only if the CN flag of the SynchronizationExtraFlags field is not set."); } if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.Eid) == SynchronizationExtraFlag.Eid) { // The server include the PidTagMid property in messageChange. newMessageChange.IsPidTagMidExist = true; // Because the SynchronizationExtraFlag is EID and the SynchronizationExtraFlag only set Eid. So can cover requirement here. ModelHelper.CaptureRequirement( 2191, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagFolderId property (section 2.2.1.2.2) in a folder change header if and only if the Eid flag of the SynchronizationExtraFlags field flag is set."); ModelHelper.CaptureRequirement( 2761, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagMid property (section 2.2.1.2.1) in a message change header if and only if the Eid flag of the SynchronizationExtraFlags field is set."); } else { // The server don't include the PidTagMid property in messageChange. newMessageChange.IsPidTagMidExist = false; // Because the SynchronizationExtraFlag is Eid and the SynchronizationExtraFlag only set Eid. So can cover requirement here. ModelHelper.CaptureRequirement( 716002, @"[In RopSynchronizationConfigure ROP Request Buffer] [SynchronizationExtraFlags, When the flag name is Eid, the value is 0x00000001] The server does not include the PidTagMid (section 2.2.1.2.1) property in the message change header when the Eid flag of the SynchronizationExtraFlag field is not set."); } if ((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.MessageSize) == SynchronizationExtraFlag.MessageSize) { // Because the SynchronizationExtraFlag is MessageSize and the SynchronizationExtraFlag only set MessageSize. So can cover requirement here. ModelHelper.CaptureRequirement( 2195, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] The server MUST include the PidTagMessageSize property (section 2.2.1.6) in the message change header if and only if the MessageSize flag of the SynchronizationExtraFlags field is set."); // The server include the PidTagMessageSize property in messageChange. newMessageChange.IsPidTagMessageSizeExist = true; ModelHelper.CaptureRequirement( 1365, @"[In messageChangeHeader Element] [PidTagMessageSize,Conditional] PidTagMessageSize MUST be present if and only if the MessageSize flag of the SynchronizationExtraFlags field is set."); } else { newMessageChange.IsPidTagMessageSizeExist = false; ModelHelper.CaptureRequirement( 718001, @"[In RopSynchronizationConfigure ROP Request Buffer] [SynchronizationExtraFlags, When the flag name is MessageSize, the value is 0x00000002] The server does not include the PidTagMessageSize property (section 2.2.1.6) in the message change header if the MessageSize flag of the SynchronizationExtraFlag field is not set."); } if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.Progress) == SynchronizationFlag.Progress) { // The server include ProgressPerMessage in messageChange. newMessageChange.IsProgressPerMessagePresent = true; // The message object is a normal message. newMessageChange.FollowedFAIMessage = false; // Because the SynchronizationExtraFlag is MessageSize and the SynchronizationExtraFlag only set MessageSize. So can cover requirement here. ModelHelper.CaptureRequirement( 1171, @"[In progressPerMessage Element]MUST be present if and only if the progessTotal element, as specified in section 2.2.4.3.18, was output within the same ancestor contentsSync element, as specified in section 2.2.4.3.2."); ModelHelper.CaptureRequirement( 1383, @"[In progressPerMessage Element] [[PtypBoolean] 0x0000000B] otherwise[if the Message object that follows is not FAI] ,[the server returns] FALSE (0x00)."); } else { // The server don't include ProgressPerMessage in messageChange. newMessageChange.IsProgressPerMessagePresent = false; ModelHelper.CaptureRequirement( 1172, @"[In progressPerMessage Element] [ProgressPerMessage Element] MUST NOT be present if the Progress flag of the SynchronizationFlags field was not set when configuring the synchronization download operation."); } // Add new messageChange to ContentsSync. abstractFastTransferStream.AbstractContentsSync.MessageInfo = abstractFastTransferStream.AbstractContentsSync.MessageInfo.Add(newMessageChange); // Because the MessageChange.followedFAIMessage default expect value is false and it is a normal messages. ModelHelper.CaptureRequirement( 2174, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the Normal flag of the SynchronizationFlags flag is set, the server MUST download information about changes to normal messages, as specified in section 2.2.4.3.11."); } } else { // Because the MessageChange.followedFAIMessage default expect value is false and it is a normal messages. ModelHelper.CaptureRequirement( 2175, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the Normal flag of the SynchronizationFlags field is not set, the server MUST NOT download information about changes to normal messages, as specified in section 2.2.4.3.11."); } } } } #endregion if (((currentDownloadContext.SynchronizationExtraflag & SynchronizationExtraFlag.OrderByDeliveryTime) == SynchronizationExtraFlag.OrderByDeliveryTime) && abstractFastTransferStream.AbstractContentsSync.MessageInfo.Count >= 2) { // The server MUST sort messages by the value of their PidTagMessageDeliveryTime property when generating a sequence of messageChange. abstractFastTransferStream.AbstractContentsSync.IsSortByMessageDeliveryTime = true; ModelHelper.CaptureRequirement( 2198, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] If the OrderByDeliveryTime flag of the SynchronizationExtraFlags field is set, the server MUST sort messages by the value of their PidTagMessageDeliveryTime property ([MS-OXOMSG] section 2.2.3.9) when generating a sequence of messageChange elements for the FastTransfer stream, as specified in section 2.2.4.2."); // The server MUST sort messages by the value of their PidTagLastModificationTime property when generating a sequence of messageChange. abstractFastTransferStream.AbstractContentsSync.IsSortByLastModificationTime = true; ModelHelper.CaptureRequirement( 2199, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationExtraFlags Constraints] If the OrderByDeliveryTime flag of the SynchronizationExtraFlags field is set, the server MUST sort messages by the PidTagLastModificationTime property ([MS-OXPROPS] section 2.764) if the former[PidTagMessageDeliveryTime] is missing, when generating a sequence of messageChange elements for the FastTransfer stream, as specified in section 2.2.4.2."); } // Search the message in MessageContainer. foreach (AbstractMessage tempMessage in currentConnection.MessageContainer) { if (tempMessage.FolderIdIndex == currentFolder.FolderIdIndex) { // Identify whether the readStateChange is or not included in messageContent. if (!currentDownloadContext.UpdatedState.CnsetRead.Contains(tempMessage.ReadStateChangeNumberIndex)) { if (tempMessage.ReadStateChangeNumberIndex != 0) { if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.ReadState) != SynchronizationFlag.ReadState) { // Download information about changes to the read state of messages. abstractFastTransferStream.AbstractContentsSync.IsReadStateChangesExist = false; ModelHelper.CaptureRequirement( 2171, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the ReadState flag of the SynchronizationFlags field is not set, the server MUST NOT download information about changes to the read state of messages, as specified in section 2.2.4.3.22."); // Download information about changes to the read state of messages. if (requirementContainer.ContainsKey(1193) && requirementContainer[1193]) { abstractFastTransferStream.AbstractContentsSync.IsReadStateChangesExist = false; ModelHelper.CaptureRequirement( 1193, @"[In readStateChanges Element] Implementation does not present this element if the ReadState flag of the SynchronizationFlag field was not set when configuring the synchronization download operation. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } } if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.ReadState) == SynchronizationFlag.ReadState) { if (requirementContainer.Keys.Contains(2665) && requirementContainer[2665]) { // Assign a new changeNumber for CnsetReadProperty. abstractFastTransferStream.AbstractContentsSync.FinalICSState.IsNewCnsetReadPropertyChangeNumber = true; // Because identify the read state of a message changes by(currentMessage.IsRead != IReadstatus) and get new change number. So can cover this requirement here. ModelHelper.CaptureRequirement(2665, "[In Tracking Read State Changes] Implementation does assign a new value to the separate change number(the read state change number) on the message, whenever the read state of a message changes on the server. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } abstractFastTransferStream.AbstractContentsSync.IsReadStateChangesExist = true; // Assign a new changeNumber for CnsetReadProperty. abstractFastTransferStream.AbstractContentsSync.FinalICSState.IsNewCnsetReadPropertyChangeNumber = true; ModelHelper.CaptureRequirement( 2087, "[In Tracking Read State Changes] An IDSET structure of change numbers associated with message read state transitions, either from read to unread, or unread to read (as determined by the PidTagMessageFlags property in [MS-OXCMSG] section 2.2.1.6) are included in the MetaTagCnsetRead property (section 2.2.1.1.4), which is part of the ICS state and is never directly set on any objects."); ModelHelper.CaptureRequirement( 3315, "[In readStateChanges Element] This element MUST be present if there are changes to the read state of messages."); } } if (tempMessage.ReadStateChangeNumberIndex == 0) { if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.ReadState) == SynchronizationFlag.ReadState) { // Download information about changes to the read state of messages. abstractFastTransferStream.AbstractContentsSync.IsReadStateChangesExist = false; // Assign a new changeNumber for CnsetReadProperty. abstractFastTransferStream.AbstractContentsSync.FinalICSState.IsNewCnsetReadPropertyChangeNumber = true; ModelHelper.CaptureRequirement( 2170, @"[In Receiving a RopSynchronizationConfigure ROP Request] [SynchronizationType Constraints] If the ReadState flag of the SynchronizationFlags field is set, the server MUST also download information about changes to the read state of messages, as specified in section 2.2.4.3.22."); ModelHelper.CaptureRequirement( 2048, @"[In Determining What Differences To Download] [For every object in the synchronization scope, servers MUST do the following:] If the ReadState flag of the SynchronizationFlags field is set, include the readStateChanges element, as specified in section 2.2.4.3.22, for messages that: Do not have their change numbers for read and unread state in the MetaTagCnsetRead property (section 2.2.1.1.4) And are not FAI messages and have not had change information downloaded for them in this session."); } } } // The message change number is not in CnsetSeenFAI property. if (!currentDownloadContext.UpdatedState.CnsetSeenFAI.Contains(tempMessage.ChangeNumberIndex)) { // The message is FAI message. if (tempMessage.IsFAImessage) { if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.FAI) == SynchronizationFlag.FAI) { ModelHelper.CaptureRequirement( 2044, @"[In Determining What Differences To Download] [For every object in the synchronization scope, servers MUST do the following:] [Include the following syntactical elements in the FastTransfer stream of the OutputServerObject field of the FastTransfer download ROPs, as specified in section 2.2.3.1.1, if one of the following applies:] Include the messageChangeFull element, as specified in section 2.2.4.3.13, if the object specified by the InputServerObject field is an FAI message, meaning the PidTagAssociated property (section 2.2.1.5) is set to TRUE And the FAI flag of the SynchronizationFlag field was set And the change number is not included in the value of the MetaTagCnsetSeenFAI property (section 2.2.1.1.3)."); // Add message changeNumber to CnsetSeenFAI of current download context. currentDownloadContext.UpdatedState.CnsetSeenFAI = currentDownloadContext.UpdatedState.CnsetSeenFAI.Add(tempMessage.ChangeNumberIndex); if (priorUploadOperation == MS_OXCFXICS.PriorOperation.RopSynchronizationImportMessageMove) { // Assign a new changeNumber. abstractFastTransferStream.AbstractContentsSync.FinalICSState.IsNewCnsetSeenFAIPropertyChangeNumber = true; ModelHelper.CaptureRequirement( 2247, @"[In Receiving a RopSynchronizationImportMessageMove Request] Upon successful completion of this ROP, the ICS state on the synchronization context MUST be updated to include change numbers of messages in the destination folder in or MetaTagCnsetSeenFAI (section 2.2.1.1.3) property, when the message is an FAI message."); } // Assign a new changeNumber. abstractFastTransferStream.AbstractContentsSync.FinalICSState.IsNewCnsetSeenFAIPropertyChangeNumber = true; if (requirementContainer.ContainsKey(218300301) && requirementContainer[218300301]) { abstractFastTransferStream.AbstractContentsSync.FinalICSState.IsNewCnsetSeenFAIPropertyChangeNumber = false; } // Because this ROP is called after successful import of a new or changed object using ICS upload and the server represent the imported version in the MetaTagCnsetSeen property for FAI message, this requirement is captured. ModelHelper.CaptureRequirement( 190701, @"[In Identifying Objects and Maintaining Change Numbers] Upon successful import of a new or changed object using ICS upload, the server MUST do the following when receiving RopSaveChangesMessage ROP: This is necessary because the server MUST be able to represent the imported version in the MetaTagCnsetSeenFAI (section 2.2.1.1.3) property for FAI message."); } } else { // SynchronizationFlag is Normal of current Download Context. if ((currentDownloadContext.Synchronizationflag & SynchronizationFlag.Normal) == SynchronizationFlag.Normal) { if (!currentDownloadContext.UpdatedState.CnsetSeen.Contains(tempMessage.ChangeNumberIndex)) { // Add Message changeNumber to CnsetSeen. currentDownloadContext.UpdatedState.CnsetSeen = currentDownloadContext.UpdatedState.CnsetSeen.Add(tempMessage.ChangeNumberIndex); ModelHelper.CaptureRequirement( 2043, @"[In Determining What Differences To Download] [For every object in the synchronization scope, servers MUST do the following:] [Include the following syntactical elements in the FastTransfer stream of the OutputServerObject field of the FastTransfer download ROPs, as specified in section 2.2.3.1.1, if one of the following applies:] Include the messageChange element, as specified in section 2.2.4.3.11, if the object specified by the InputServerObject field is a normal message And the Normal flag of the SynchronizationFlags field was set, as specified in section 2.2.3.2.1.1.1; And the change number is not included in the value of the MetaTagCnsetSeen property."); } else if (abstractFastTransferStream.AbstractContentsSync.FinalICSState.IsNewCnsetReadPropertyChangeNumber) { if (requirementContainer.ContainsKey(2666) && requirementContainer[2666]) { abstractFastTransferStream.AbstractContentsSync.FinalICSState.IsNewCnsetSeenPropertyChangeNumber = false; ModelHelper.CaptureRequirement( 2666, @"[In Tracking Read State Changes] Implementation does not modify the change number of the message unless other changes to a message were made at the same time. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } } // Assign a new changeNumber. abstractFastTransferStream.AbstractContentsSync.FinalICSState.IsNewCnsetSeenPropertyChangeNumber = true; ModelHelper.CaptureRequirement( 2246, @"[In Receiving a RopSynchronizationImportMessageMove Request]Upon successful completion of this ROP, the ICS state on the synchronization context MUST be updated to include change numbers of messages in the destination folder in the MetaTagCnsetSeen (section 2.2.1.1.2) when the message is a normal message."); // Because this ROP is called after successful import of a new or changed object using ICS upload and the server represent the imported version in the MetaTagCnsetSeen property for normal message, this requirement is captured. ModelHelper.CaptureRequirement( 1907, @"[In Identifying Objects and Maintaining Change Numbers] Upon successful import of a new or changed object using ICS upload, the server MUST do the following when receiving RopSaveChangesMessage ROP: This is necessary because the server MUST be able to represent the imported version in the MetaTagCnsetSeen (section 2.2.1.1.2) property for normal message."); } } } } } // Set ContentsSync IdSetGiven value with IdsetGiven value of current download context. abstractFastTransferStream.AbstractContentsSync.FinalICSState.IdSetGiven = currentDownloadContext.UpdatedState.IdsetGiven; // Add ICS State to ICSStateContainer. currentFolder.ICSStateContainer.Add(abstractFastTransferStream.AbstractContentsSync.FinalICSState.AbstractICSStateIndex, currentDownloadContext.UpdatedState); // Update the FolderContainer. currentConnection.FolderContainer = currentConnection.FolderContainer.Update(currentFolderIndex, currentFolder); connections[serverId] = currentConnection; break; } // In case of the FastTransferStreamType of download context include folderContent. case FastTransferStreamType.folderContent: { if (priorDownloadOperation == PriorDownloadOperation.RopFastTransferSourceCopyTo && currentDownloadContext.ObjectType == ObjectType.Folder) { ModelHelper.CaptureRequirement( 3324, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopFastTranserSourceCopyTo, ROP request buffer field conditions is The InputServerObject field is a Folder object<25>, Root element in the produced FastTransfer stream is folderContent."); } if (priorDownloadOperation == PriorDownloadOperation.RopFastTransferSourceCopyProperties && currentDownloadContext.ObjectType == ObjectType.Folder) { ModelHelper.CaptureRequirement( 3325, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopFastTranserSourceCopyProperties, ROP request buffer field conditions is The InputServerObject field is a Folder object<25>, Root element in the produced FastTransfer stream is folderContent."); } if (priorOperation == PriorOperation.RopFastTransferDestinationConfigure && currentDownloadContext.ObjectType == ObjectType.Folder && sourOperation == SourceOperation.CopyProperties) { ModelHelper.CaptureRequirement( 598, @"[In RopFastTransferDestinationConfigure ROP Request Buffer] [SourceOperation] When SourceOperation enumeration value is CopyProperties, if the value of InputServerObject field is a Folder Object, Root element in FastTransfer stream is folderContent element."); } if (priorOperation == PriorOperation.RopFastTransferDestinationConfigure && currentDownloadContext.ObjectType == ObjectType.Folder && sourOperation == SourceOperation.CopyTo) { ModelHelper.CaptureRequirement( 595, @"[In RopFastTransferDestinationConfigure ROP Request Buffer] [SourceOperation] When SourceOperation enumeration value is CopyTo, if the value of the InputServerObject field is a Folder Object, Root element in FastTransfer stream is folderContent element."); } // Initialize the entity variable abstractFastTransferStream.AbstractFolderContent = new AbstractFolderContent { AbsFolderMessage = new AbstractFolderMessage() }; bool isSubFolderExist = false; AbstractFolder subFolder = new AbstractFolder(); // Search the folder container to find if the download folder contains subFolder foreach (AbstractFolder tempSubFolder in currentConnection.FolderContainer) { if (currentFolder.SubFolderIds.Contains(tempSubFolder.FolderIdIndex)) { isSubFolderExist = true; subFolder = tempSubFolder; break; } } // The downLaod folder's subFolder exist if (isSubFolderExist) { if (subFolder.FolderPermission == PermissionLevels.None && (currentDownloadContext.CopyToCopyFlag == CopyToCopyFlags.Move || currentDownloadContext.CopyPropertiesCopyFlag == CopyPropertiesCopyFlags.Move)) { abstractFastTransferStream.AbstractFolderContent.IsNoPermissionObjNotOut = true; if (requirementContainer.ContainsKey(2667) && requirementContainer[2667]) { ModelHelper.CaptureRequirement(2667, @"[In Receiving a RopFastTransferSourceCopyTo ROP Request] Implementation does not output any objects in a FastTransfer stream that the client does not have permissions to delete, if the Move flag of the CopyFlags field is set. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } if (requirementContainer.ContainsKey(2669) && requirementContainer[2669]) { ModelHelper.CaptureRequirement( 2669, @"[In Receiving a RopFastTransferSourceCopyProperties Request] Implementation does not output any objects in a FastTransfer stream that the client does not have permissions to delete, if the Move flag of the CopyFlags field is specified for a download operation. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } } } else if (subFolder.FolderPermission == PermissionLevels.FolderVisible && currentDownloadContext.CopyToCopyFlag == CopyToCopyFlags.Move) { if (requirementContainer.ContainsKey(118201) && requirementContainer[118201]) { abstractFastTransferStream.AbstractFolderContent.IsPidTagEcWarningOut = true; } abstractFastTransferStream.AbstractFolderContent.AbsFolderMessage.MessageList.AbsMessage.AbsMessageContent.IsNoPermissionMessageNotOut = true; } // Search the currentDownloadContext.property to find if the specific property is required download foreach (string propStr in currentDownloadContext.Property) { if (isSubFolderExist && subFolder.FolderPermission != PermissionLevels.None) { // PidTagContainerHierarchy property is required to download if (propStr == "PidTagContainerHierarchy") { // CopyFolder operation will copy subFolder IFF CopySubfolders copyFlag is set if (((currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyFolder && currentDownloadContext.CopyFolderCopyFlag == CopyFolderCopyFlags.CopySubfolders) || currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyProperties) && currentConnection.LogonFolderType != LogonFlags.Ghosted) { if (currentConnection.LogonFolderType != LogonFlags.Ghosted || (requirementContainer.ContainsKey(1113) && requirementContainer[1113] && currentConnection.LogonFolderType == LogonFlags.Ghosted)) { abstractFastTransferStream.AbstractFolderContent.IsSubFolderPrecededByPidTagFXDelProp = true; ModelHelper.CaptureRequirement( 1113, @"[In folderContent Element] Under conditions specified in section 3.2.5.10, the PidTagContainerHierarchy property ([MS-OXPROPS] section 2.645) included in a subFolder element MUST be preceded by a MetaTagFXDelProp meta-property (section 2.2.4.1.5.1)."); } } } else { if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyTo) { if (currentConnection.LogonFolderType != LogonFlags.Ghosted || (requirementContainer.ContainsKey(1113) && requirementContainer[1113] && currentConnection.LogonFolderType == LogonFlags.Ghosted)) { // The FastTransferOperation is FastTransferSourceCopyTo and the properties that not required in the propertyTag is download abstractFastTransferStream.AbstractFolderContent.IsSubFolderPrecededByPidTagFXDelProp = true; ModelHelper.CaptureRequirement( 1113, @"[In folderContent Element] Under conditions specified in section 3.2.5.10, the PidTagContainerHierarchy property ([MS-OXPROPS] section 2.645) included in a subFolder element MUST be preceded by a MetaTagFXDelProp meta-property (section 2.2.4.1.5.1)."); } } } } if (currentConnection.LogonFolderType != LogonFlags.Ghosted) { // PidTagFolderAssociatedContents property is required to download if (propStr == "PidTagFolderAssociatedContents") { if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyProperties) { // The FastTransferOperation is FastTransferSourceCopyProperties and the properties that required in the propertyTag is download abstractFastTransferStream.AbstractFolderContent.AbsFolderMessage.IsFolderMessagesPrecededByPidTagFXDelProp = true; ModelHelper.CaptureRequirement( 2620, @"[In folderMessages Element] Under conditions specified in section 3.2.5.10, when included in the folderMessages element, the PidTagFolderAssociatedContents ([MS-OXPROPS] section 2.699) and PidTagContainerContents ([MS-OXPROPS] section 2.637) properties MUST be preceded by a MetaTagFXDelProp meta-property (section 2.2.4.1.5.1)."); } } else { if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyTo) { // The FastTransferOperation is FastTransferSourceCopyTo and the properties that not required in the propertyTag is download abstractFastTransferStream.AbstractFolderContent.AbsFolderMessage.IsFolderMessagesPrecededByPidTagFXDelProp = true; ModelHelper.CaptureRequirement( 2620, @"[In folderMessages Element] Under conditions specified in section 3.2.5.10, when included in the folderMessages element, the PidTagFolderAssociatedContents ([MS-OXPROPS] section 2.699) and PidTagContainerContents ([MS-OXPROPS] section 2.637) properties MUST be preceded by a MetaTagFXDelProp meta-property (section 2.2.4.1.5.1)."); } } // PidTagContainerContents property is required to download if (propStr == "PidTagContainerContents") { if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyProperties) { // The FastTransferOperation is FastTransferSourceCopyProperties and the properties that required in the propertyTag is download abstractFastTransferStream.AbstractFolderContent.AbsFolderMessage.IsFolderMessagesPrecededByPidTagFXDelProp = true; } } else { if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyTo) { // The FastTransferOperation is FastTransferSourceCopyTo and the properties that not required in the propertyTag is download abstractFastTransferStream.AbstractFolderContent.AbsFolderMessage.IsFolderMessagesPrecededByPidTagFXDelProp = true; } } } } break; } // In case of the FastTransferStreamType of download context include messageContent. case FastTransferStreamType.MessageContent: { if (priorDownloadOperation == PriorDownloadOperation.RopFastTransferSourceCopyTo && currentDownloadContext.ObjectType == ObjectType.Message) { ModelHelper.CaptureRequirement( 3326, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopFastTranserSourceCopyTo, ROP request buffer field conditions is The InputServerObject field is a Message object, Root element in the produced FastTransfer stream is messageContent."); } if (priorDownloadOperation == PriorDownloadOperation.RopFastTransferSourceCopyProperties && currentDownloadContext.ObjectType == ObjectType.Message) { ModelHelper.CaptureRequirement( 3327, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopFastTranserSourceCopyProperties, ROP request buffer field conditions is The InputServerObject field is a Message object, Root element in the produced FastTransfer stream is messageContent."); } if (priorOperation == PriorOperation.RopFastTransferDestinationConfigure && currentDownloadContext.ObjectType == ObjectType.Message && sourOperation == SourceOperation.CopyProperties) { ModelHelper.CaptureRequirement( 596, @"[In RopFastTransferDestinationConfigure ROP Request Buffer] [SourceOperation] When SourceOperation enumeration value is CopyProperties, if the value of the InputServerObject field is a Message object, Root element in FastTransfer stream is messageContent element."); } if (priorOperation == PriorOperation.RopFastTransferDestinationConfigure && currentDownloadContext.ObjectType == ObjectType.Message && sourOperation == SourceOperation.CopyTo) { ModelHelper.CaptureRequirement( 599, @"[In RopFastTransferDestinationConfigure ROP Request Buffer] [SourceOperation] When SourceOperation enumeration value is CopyTo, if the value of the InputServerObject field is a Message object, Root element in FastTransfer stream is messageContent element."); } // Initialize the entity variable abstractFastTransferStream.AbstractMessageContent = new AbstractMessageContent { AbsMessageChildren = new AbstractMessageChildren() }; AbstractFolder messageParentFolder = new AbstractFolder(); // Search the MessagecCntianer to find the downLaodMessage foreach (AbstractMessage cumessage in currentConnection.MessageContainer) { if (cumessage.MessageHandleIndex == currentDownloadContext.RelatedObjectHandleIndex) { foreach (AbstractFolder cufolder in currentConnection.FolderContainer) { if (cufolder.FolderHandleIndex == cumessage.FolderHandleIndex) { messageParentFolder = cufolder; break; } } break; } } if (priorDownloadOperation == PriorDownloadOperation.RopFastTransferSourceCopyTo) { if ((currentDownloadContext.CopyToCopyFlag & CopyToCopyFlags.BestBody) == CopyToCopyFlags.BestBody) { if (requirementContainer.ContainsKey(211501) && requirementContainer[211501]) { abstractFastTransferStream.AbstractMessageContent.IsRTFFormat = false; ModelHelper.CaptureRequirement(211501, @"[In Receiving a RopFastTransferSourceCopyTo ROP Request] Implementation does output the message body, and the body of the Embedded Message object, in their original format, if the BestBody flag of the CopyFlags field is set. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } if (requirementContainer.ContainsKey(3118003) && requirementContainer[3118003]) { abstractFastTransferStream.AbstractMessageContent.IsRTFFormat = false; ModelHelper.CaptureRequirement(3118003, @"[In Appendix A: Product Behavior] Implementation does support this flag [BestBody flag] [in RopFastTransferSourceCopyTo ROP]. (<3> Section 2.2.3.1.1.1.1: Microsoft Exchange Server 2007 and 2010 follow this behavior.)"); } } } #region Verify Requirements about Sendoptions if ((currentDownloadContext.Sendoptions & SendOptionAlls.UseCpid) == SendOptionAlls.UseCpid && connections.Count > 1) { if (currentDownloadContext.Sendoptions == SendOptionAlls.UseCpid) { abstractFastTransferStream.AbstractMessageContent.StringPropertiesInUnicodeCodePage = true; ModelHelper.CaptureRequirement( 3453, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When UseCpid only, if the properties are stored in Unicode on the server, the server MUST return the properties using the Unicode code page (code page property type 0x84B0)."); if (currentDownloadContext.RelatedFastTransferOperation != EnumFastTransferOperation.FastTransferSourceCopyProperties) { if (requirementContainer.ContainsKey(3454) && requirementContainer[3454]) { abstractFastTransferStream.AbstractMessageContent.StringPropertiesInOtherCodePage = true; ModelHelper.CaptureRequirement( 3454, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When UseCpid only, otherwise[the properties are not stored in Unicode on the server] the server MUST send the string using the code page property type of the code page in which the property is stored on the server."); } } ModelHelper.CaptureRequirement( 3452, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When UseCpid only, String properties MUST be output using code page property types, as specified in section 2.2.4.1.1.1."); } else if (currentDownloadContext.Sendoptions == (SendOptionAlls.Unicode | SendOptionAlls.UseCpid)) { abstractFastTransferStream.AbstractMessageContent.StringPropertiesInUnicodeCodePage = true; ModelHelper.CaptureRequirement( 3457, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When UseCpid and Unicode, If string properties are stored in Unicode on the server, the server MUST return the properties using the Unicode code page (code page property type 0x84B0)."); if (currentDownloadContext.RelatedFastTransferOperation != EnumFastTransferOperation.FastTransferSourceCopyProperties) { if (requirementContainer.ContainsKey(3454) && requirementContainer[3454]) { abstractFastTransferStream.AbstractMessageContent.StringPropertiesInOtherCodePage = true; ModelHelper.CaptureRequirement( 3780, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] UseCpid and Unicode: If string properties are not stored in Unicode on the server, the server MUST send the string using the code page property type of the code page in which the property is stored on the server."); } } ModelHelper.CaptureRequirement( 3456, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When UseCpid and Unicode, String properties MUST be output using code page property types, as specified in section 2.2.4.1.1.1. "); } else if (currentDownloadContext.Sendoptions == (SendOptionAlls.UseCpid | SendOptionAlls.ForceUnicode)) { abstractFastTransferStream.AbstractMessageContent.StringPropertiesInUnicodeCodePage = true; ModelHelper.CaptureRequirement( 3782, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] UseCpid and ForceUnicode: String properties MUST be output using the Unicode code page (code page property type 0x84B0)."); } else if (currentDownloadContext.Sendoptions == (SendOptionAlls.UseCpid | SendOptionAlls.ForceUnicode | SendOptionAlls.Unicode)) { abstractFastTransferStream.AbstractMessageContent.StringPropertiesInUnicodeCodePage = true; ModelHelper.CaptureRequirement( 3459, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] WhenUseCpid, Unicode, and ForceUnicode, The combination of the UseCpid and Unicode flags is the ForUpload flag. String properties MUST be output using the Unicode code page (code page property type 0x84B0)."); } } else { if (currentDownloadContext.Sendoptions == SendOptionAlls.ForceUnicode) { // The String properties is saved in the server using unicode format in this test environment ,so the string properties must out in Unicode format abstractFastTransferStream.AbstractMessageContent.StringPropertiesInUnicode = true; ModelHelper.CaptureRequirement( 3451, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When ForceUnicode only, String properties MUST be output in Unicode with a property type of PtypUnicode."); } else if (((currentDownloadContext.Sendoptions & SendOptionAlls.Unicode) != SendOptionAlls.Unicode) && (currentDownloadContext.Sendoptions != (SendOptionAlls.ForceUnicode | SendOptionAlls.Unicode))) { // String properties MUST be output in code page abstractFastTransferStream.AbstractMessageContent.StringPropertiesInUnicode = false; ModelHelper.CaptureRequirement( 3447, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When none of the three flags[Unicode, ForceUnicode, and UseCpid] are set, String properties MUST be output in the code page set on the current connection with a property type of PtypString8 ([MS-OXCDATA] section 2.11.1). "); } else if (currentDownloadContext.Sendoptions == (SendOptionAlls.ForceUnicode | SendOptionAlls.Unicode)) { // String properties MUST be output in Unicode abstractFastTransferStream.AbstractMessageContent.StringPropertiesInUnicode = true; ModelHelper.CaptureRequirement( 3455, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When Unicode and ForceUnicode, String properties MUST be output in Unicode with a property type of PtypUnicode."); } else if (currentDownloadContext.Sendoptions == SendOptionAlls.Unicode) { // The string properties is saved in the server using Unicode format in this test environment ,so the string properties must out in Unicode format abstractFastTransferStream.AbstractMessageContent.StringPropertiesInUnicode = true; ModelHelper.CaptureRequirement( 3448, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When Unicode only, String properties MUST be output either in Unicode with a property type of PtypUnicode ([MS-OXCDATA] section 2.11.1), or in the code page set on the current connection with a property type of PtypString8. "); ModelHelper.CaptureRequirement( 3449, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When Unicode only, if the properties are stored in Unicode on the server, the server MUST return the properties in Unicode. "); ModelHelper.CaptureRequirement( 3450, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When Unicode only, if the properties are not stored in Unicode on the server, the server MUST return the properties in the code page set on the current connection."); } else if (currentDownloadContext.Sendoptions == SendOptionAlls.ForceUnicode) { // The string properties is saved in the server using unicode format in this test environment ,so the string properties must out in Unicode format abstractFastTransferStream.AbstractMessageContent.StringPropertiesInUnicode = true; ModelHelper.CaptureRequirement( 3451, @"[In Receiving a RopFastTransferSourceCopyTo Request] [valid combinations of the Unicode, ForceUnicode, and UseCpid flags of the SendOptions field] When ForceUnicode only, String properties MUST be output in Unicode with a property type of PtypUnicode."); } } #endregion if (!currentDownloadContext.IsLevelTrue) { bool isPidTagMessageAttachmentsExist = false; bool isPidTagMessageRecipientsExist = false; // Search the currentDownloadContext.property to find if the specific property is required to download foreach (string propStr in currentDownloadContext.Property) { if (propStr == "PidTagMessageAttachments") { isPidTagMessageAttachmentsExist = true; } if (propStr == "PidTagMessageRecipients") { isPidTagMessageRecipientsExist = true; } // CopyTo operation's propertyTags specific the properties not to download if (currentDownloadContext.RelatedFastTransferOperation != EnumFastTransferOperation.FastTransferSourceCopyTo) { // The PidTagMessageRecipients property is required to download if (propStr == "PidTagMessageAttachments") { // The PidTagMessageAttachments property is required to download abstractFastTransferStream.AbstractMessageContent.AbsMessageChildren.AttachmentPrecededByPidTagFXDelProp = true; ModelHelper.CaptureRequirement( 3304, @"[In messageChildren Element] Under the conditions specified in section 3.2.5.10 [Effect of Property and Subobject Filters on Download] , the PidTagMessageRecipients ([MS-OXPROPS] section 2.795) property included in a recipient element and the PidTagMessageAttachments ([MS-OXPROPS] section 2.779) property included in an attachment element MUST be preceded by a MetaTagFXDelProp meta-property (section 2.2.4.1.5.1)."); // The AttachmentPrecededByPidTagFXDelProp true means server outputs the MetaTagFXDelProp property before outputting subobjects, such as attachment. ModelHelper.CaptureRequirement( 2276, @"[In Effect of Property and Subobject Filters on Download] Whenever subobject filters have an effect, servers MUST output a MetaTagFXDelProp meta-property (section 2.2.4.1.5.1) immediately before outputting subobjects of a particular type, to differentiate between the cases where a set of subobjects (such as attachments or recipients) was filtered in, but was empty, and where it was filtered out."); ModelHelper.CaptureRequirement( 3464, @"[In Receiving a RopFastTransferSourceCopyProperties Request] If the Level field is set to 0x00, the server MUST copy descendant subobjects by using the property list specified by the PropertyTags field. "); ModelHelper.CaptureRequirement( 3783, @"[In Receiving a RopFastTransferSourceCopyProperties Request] Subobjects are not copied unless listed in the value of the PropertyTags field."); } if (propStr == "PidTagMessageRecipients") { // The PidTagMessageRecipients property is required to download abstractFastTransferStream.AbstractMessageContent.AbsMessageChildren.RecipientPrecededByPidTagFXDelProp = true; ModelHelper.CaptureRequirement( 3304, @"[In messageChildren Element] Under the conditions specified in section 3.2.5.10 [Effect of Property and Subobject Filters on Download] , the PidTagMessageRecipients ([MS-OXPROPS] section 2.795) property included in a recipient element and the PidTagMessageAttachments ([MS-OXPROPS] section 2.779) property included in an attachment element MUST be preceded by a MetaTagFXDelProp meta-property (section 2.2.4.1.5.1)."); // The RecipientPrecededByPidTagFXDelProp true means server outputs the MetaTagFXDelProp property before outputting subobjects, such as recipients. ModelHelper.CaptureRequirement( 2276, @"[In Effect of Property and Subobject Filters on Download] Whenever subobject filters have an effect, servers MUST output a MetaTagFXDelProp meta-property (section 2.2.4.1.5.1) immediately before outputting subobjects of a particular type, to differentiate between the cases where a set of subobjects (such as attachments or recipients) was filtered in, but was empty, and where it was filtered out."); } } else if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyTo) { if (propStr == "PidTagMessageAttachments") { // The PidTagMessageAttachments property is not required to download abstractFastTransferStream.AbstractMessageContent.AbsMessageChildren.AttachmentPrecededByPidTagFXDelProp = false; ModelHelper.CaptureRequirement( 3439, @"[In Receiving a RopFastTransferSourceCopyTo ROP Request] If the Level field is set to 0x00, the server MUST copy descendant subobjects by using the property list specified by the PropertyTags field. "); ModelHelper.CaptureRequirement( 3440, @"[In Receiving a RopFastTransferSourceCopyTo ROP Request] Subobjects are only copied when they are not listed in the value of the PropertyTags field. "); } if (propStr == "PidTagMessageRecipients") { // The PidTagMessageRecipients property is not required to download abstractFastTransferStream.AbstractMessageContent.AbsMessageChildren.RecipientPrecededByPidTagFXDelProp = false; } } } if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyTo && currentConnection.AttachmentContainer.Count > 0) { if (!isPidTagMessageAttachmentsExist) { abstractFastTransferStream.AbstractMessageContent.AbsMessageChildren.AttachmentPrecededByPidTagFXDelProp = true; ModelHelper.CaptureRequirement( 3304, @"[In messageChildren Element] Under the conditions specified in section 3.2.5.10 [Effect of Property and Subobject Filters on Download] , the PidTagMessageRecipients ([MS-OXPROPS] section 2.795) property included in a recipient element and the PidTagMessageAttachments ([MS-OXPROPS] section 2.779) property included in an attachment element MUST be preceded by a MetaTagFXDelProp meta-property (section 2.2.4.1.5.1)."); } } if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyTo) { if (!isPidTagMessageRecipientsExist) { abstractFastTransferStream.AbstractMessageContent.AbsMessageChildren.RecipientPrecededByPidTagFXDelProp = true; // The RecipientPrecededByPidTagFXDelProp true means server outputs the MetaTagFXDelProp property before outputting subobjects, such as recipients. ModelHelper.CaptureRequirement( 2276, @"[In Effect of Property and Subobject Filters on Download] Whenever subobject filters have an effect, servers MUST output a MetaTagFXDelProp meta-property (section 2.2.4.1.5.1) immediately before outputting subobjects of a particular type, to differentiate between the cases where a set of subobjects (such as attachments or recipients) was filtered in, but was empty, and where it was filtered out."); } } } else { abstractFastTransferStream.AbstractMessageContent.AbsMessageChildren.AttachmentPrecededByPidTagFXDelProp = false; abstractFastTransferStream.AbstractMessageContent.AbsMessageChildren.RecipientPrecededByPidTagFXDelProp = false; if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyTo) { ModelHelper.CaptureRequirement( 3441, @"[In Receiving a RopFastTransferSourceCopyTo ROP Request] If the Level field is set to a nonzero value, the server MUST exclude all descendant subobjects from being copied."); } if (currentDownloadContext.RelatedFastTransferOperation == EnumFastTransferOperation.FastTransferSourceCopyProperties) { ModelHelper.CaptureRequirement( 3465, @"[In Receiving a RopFastTransferSourceCopyProperties Request] If the Level field is set to a nonzero value, the server MUST exclude all descendant subobjects from being copied."); } } break; } // In case of the FastTransferStreamType of download context include messageList. case FastTransferStreamType.MessageList: { if (priorDownloadOperation == PriorDownloadOperation.RopFastTransferSourceCopyMessage) { ModelHelper.CaptureRequirement( 3330, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopFastTranserSourceCopyMessages, ROP request buffer field conditions is always, Root element in the produced FastTransfer stream is messageList."); } if (priorOperation == MS_OXCFXICS.PriorOperation.RopFastTransferDestinationConfigure && sourOperation == SourceOperation.CopyMessages) { ModelHelper.CaptureRequirement( 601, @"[In RopFastTransferDestinationConfigure ROP Request Buffer] [SourceOperation] When SourceOperation enumeration value is CopyMessages, Root element in FastTransfer stream is messageList."); } // Initialize the entity variable abstractFastTransferStream.AbstractMessageList = new AbstractMessageList { AbsMessage = new AbsMessage { AbsMessageContent = new AbstractMessageContent() } }; if (priorDownloadOperation == PriorDownloadOperation.RopFastTransferSourceCopyMessage) { if ((currentDownloadContext.CopyMessageCopyFlag & RopFastTransferSourceCopyMessagesCopyFlags.BestBody) == RopFastTransferSourceCopyMessagesCopyFlags.BestBody) { if (requirementContainer.ContainsKey(211601) && requirementContainer[211601]) { abstractFastTransferStream.AbstractMessageContent.IsRTFFormat = false; ModelHelper.CaptureRequirement(211601, @"[In Receiving a RopFastTransferSourceCopyMessages ROP Request] Implementation does output the message body, and the body of the Embedded Message object, in their original format, If the BestBody flag of the CopyFlags field is set. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } if (requirementContainer.ContainsKey(499003) && requirementContainer[499003]) { abstractFastTransferStream.AbstractMessageContent.IsRTFFormat = false; ModelHelper.CaptureRequirement(499003, @"[In Appendix A: Product Behavior] Implementation does support this flag [BestBody flag] [in RopFastTransferSourceCopyMessages ROP]. (<5> Section 2.2.3.1.1.3.1: Microsoft Exchange Server 2007 and Microsoft Exchange Server 2010 follow this behavior.)"); } } } // If the folder permission is set to None. if (currentFolder.FolderPermission == PermissionLevels.None || currentFolder.FolderPermission == PermissionLevels.FolderVisible) { if (currentDownloadContext.CopyMessageCopyFlag == RopFastTransferSourceCopyMessagesCopyFlags.Move) { if (requirementContainer.ContainsKey(2631) && requirementContainer[2631]) { // The server doesn't output any objects in a FastTransfer stream that the client does not have permissions to delete abstractFastTransferStream.AbstractMessageList.AbsMessage.AbsMessageContent.IsNoPermissionMessageNotOut = true; ModelHelper.CaptureRequirement( 2631, @"[In Receiving a RopFastTransferSourceCopyMessages ROP Request] Implementation does not output any objects in a FastTransfer stream that the client does not have permissions to delete, If the Move flag of the CopyFlags field is set for a download operation. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } } if (requirementContainer.ContainsKey(1168) && requirementContainer[1168]) { // The server doesn't have the permissions necessary to access PidTagEcWarning if the folder permission is set to None. abstractFastTransferStream.AbstractMessageList.IsPidTagEcWarningOut = true; ModelHelper.CaptureRequirement( 1168, @"[In messageList Element] Implementation does output MetaTagEcWarning meta-property (section 2.2.4.1.5.2) if a client does not have the permissions necessary to access it, as specified in section 3.2.5.8.1. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } if (requirementContainer.ContainsKey(34381) && requirementContainer[34381]) { // The server doesn't have the permissions necessary to access PidTagEcWarning if the folder permission is set to None. abstractFastTransferStream.AbstractMessageList.IsPidTagEcWarningOut = true; ModelHelper.CaptureRequirement( 34381, @"[In Download] Implementation does output the MetaTagEcWarning meta-property (section 2.2.4.1.5.2) in a FastTransfer stream if a permission check for an object fails, wherever allowed by its syntactical structure, to signal a client about incomplete content. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } } break; } // In case of the FastTransferStreamType of download context include topFolder. case FastTransferStreamType.TopFolder: { if (priorDownloadOperation == PriorDownloadOperation.RopFastTransferSourceCopyFolder) { ModelHelper.CaptureRequirement( 3331, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopFastTranserSourceCopyFolder, ROP request buffer field conditions is always, Root element in the produced FastTransfer stream is topFolder."); } if (priorOperation == MS_OXCFXICS.PriorOperation.RopFastTransferDestinationConfigure && sourOperation == SourceOperation.CopyFolder) { ModelHelper.CaptureRequirement( 602, @"[In RopFastTransferDestinationConfigure ROP Request Buffer] [SourceOperation] When SourceOperation enumeration value is CopyFolder, Root element in FastTransfer stream is topFolder."); } // If the logon folder is Ghosted folder if (currentConnection.LogonFolderType == LogonFlags.Ghosted && requirementContainer.ContainsKey(1111) && requirementContainer[1111]) { // The PidTagNewFXFolder meta-property MUST be output for the Ghosted folder abstractFastTransferStream.AbstractTopFolder.AbsFolderContent.IsPidTagNewFXFolderOut = true; ModelHelper.CaptureRequirement( 1111, @"[In folderContent Element] [If there is a valid replica (1) of the public folder on the server and the folder content has not replicated to the server yet, the folder content is not included in the FastTransfer stream as part of the folderContent element] Implementation does not include any data following the MetaTagNewFXFolder meta-property in the buffer returned by the RopFastTransferSourceGetBuffer ROP (section 2.2.3.1.1.5), although additional data can be included in the FastTransfer stream. (Microsoft Exchange Server 2007 and above follow this behavior.)"); } // Identify whether the subFolder is existent or not. bool isSubFolderExist = false; AbstractFolder subFolder = new AbstractFolder(); // Search the folder container to find if the download folder has subFolder foreach (AbstractFolder tempSubFolder in currentConnection.FolderContainer) { if (currentFolder.SubFolderIds.Contains(tempSubFolder.FolderIdIndex)) { isSubFolderExist = true; subFolder = tempSubFolder; break; } } if (isSubFolderExist) { // Identify folder Permission is available. if (subFolder.FolderPermission != PermissionLevels.None) { if ((currentDownloadContext.CopyFolderCopyFlag & CopyFolderCopyFlags.CopySubfolders) == CopyFolderCopyFlags.CopySubfolders || (currentDownloadContext.CopyFolderCopyFlag & CopyFolderCopyFlags.Move) == CopyFolderCopyFlags.Move) { // The server recursively include the subFolders of the folder specified in the InputServerObject in the scope. abstractFastTransferStream.AbstractTopFolder.SubFolderInScope = true; } if ((currentDownloadContext.CopyFolderCopyFlag & CopyFolderCopyFlags.Move) == CopyFolderCopyFlags.Move && (currentDownloadContext.CopyFolderCopyFlag & CopyFolderCopyFlags.CopySubfolders) != CopyFolderCopyFlags.CopySubfolders) { ModelHelper.CaptureRequirement( 3481, @"[In Receiving a RopFastTransferSourceCopyFolder ROP Request] If the Move flag of the CopyFlags field is set and the CopySubfolders flag is not set, the server MUST recursively include the subfolders of the folder specified in the InputServerObject field in the scope."); } } } break; } // In case of the FastTransferStreamType of download context include messageList. case FastTransferStreamType.attachmentContent: { if (priorDownloadOperation == PriorDownloadOperation.RopFastTransferSourceCopyTo && currentDownloadContext.ObjectType == ObjectType.Attachment) { ModelHelper.CaptureRequirement( 3328, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopFastTranserSourceCopyTo, ROP request buffer field conditions is The InputServerObject field is an Attachment object<26>, Root element in the produced FastTransfer stream is attachmentContent."); } if (priorDownloadOperation == PriorDownloadOperation.RopFastTransferSourceCopyProperties && currentDownloadContext.ObjectType == ObjectType.Attachment) { ModelHelper.CaptureRequirement( 3329, @"[In FastTransfer Streams in ROPs] When ROP that initiates an operation is RopFastTranserSourceCopyProperties, ROP request buffer field conditions is The InputServerObject field is an Attachment object<26>, Root element in the produced FastTransfer stream is attachmentContent."); } if (priorOperation == PriorOperation.RopFastTransferDestinationConfigure && currentConnection.AttachmentContainer.Count > 0 && sourOperation == SourceOperation.CopyTo) { ModelHelper.CaptureRequirement( 597, @"[In RopFastTransferDestinationConfigure ROP Request Buffer] [SourceOperation] When SourceOperation enumeration value is CopyTo, if the value of the InputServerObject field is an Attachment object, Root element in FastTransfer stream is attachmentContent element."); } if (priorOperation == PriorOperation.RopFastTransferDestinationConfigure && currentDownloadContext.ObjectType == ObjectType.Attachment && sourOperation == SourceOperation.CopyProperties) { ModelHelper.CaptureRequirement( 600, @"[In RopFastTransferDestinationConfigure ROP Request Buffer] [SourceOperation] When SourceOperation enumeration value is CopyProperties, if the value of the InputServerObject field is an Attachment object, Root element in FastTransfer stream is attachmentContent element."); } break; } default: break; } } if (result == RopResult.Success) { // If the server returns success result, which means the RopFastTransferSourceGetBuffer ROP downloads the next portion of a FastTransfer stream successfully. Then this requirement can be captured. ModelHelper.CaptureRequirement( 532, @"[In RopFastTransferSourceGetBuffer ROP] The RopFastTransferSourceGetBuffer ROP ([MS-OXCROPS] section 2.2.12.3) downloads the next portion of a FastTransfer stream that is produced by a previously configured download operation."); } return result; } /// <summary> /// Initializes a FastTransfer operation for uploading content encoded in a client-provided FastTransfer stream into a mailbox /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="objHandleIndex">A fast transfer stream object handle index.</param> /// <param name="option">Defines the parameters of a download operation.</param> /// <param name="copyFlag">Defines parameters of the FastTransfer download operation.</param> /// <param name="uploadContextHandleIndex">Configure handle's index.</param> /// <returns>Indicate the result of this ROP operation</returns> [Rule(Action = ("FastTransferDestinationConfigure(serverId,objHandleIndex,option,copyFlag,out uploadContextHandleIndex)/result"))] public static RopResult FastTransferDestinationConfigure(int serverId, int objHandleIndex, SourceOperation option, FastTransferDestinationConfigureCopyFlags copyFlag, out int uploadContextHandleIndex) { // The construction conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Initialize return value. RopResult result = RopResult.InvalidParameter; if (requirementContainer.ContainsKey(3492001)) { if ((copyFlag == FastTransferDestinationConfigureCopyFlags.Invalid) && requirementContainer[3492001] == true) { // FastTransferDestinationConfigureCopyFlags is invalid parameter and exchange server version is not ExchangeServer2007 . uploadContextHandleIndex = -1; ModelHelper.CaptureRequirement( 3492001, @"[In Appendix A: Product Behavior] If unknown flags in the CopyFlags field are set, implementation does fail the operation. <39> Section 3.2.5.8.2.1: Exchange 2010, Exchange 2013 and Exchange 2016 fail the ROP [RopFastTransferDestinationConfigure ROP] if unknown bit flags in the CopyFlags field are set."); return result; } } if (option == SourceOperation.CopyProperties || option == SourceOperation.CopyTo || option == SourceOperation.CopyFolder || option == SourceOperation.CopyMessages) { priorOperation = MS_OXCFXICS.PriorOperation.RopFastTransferDestinationConfigure; } sourOperation = option; // Create a new Upload context. AbstractUploadInfo uploadInfo = new AbstractUploadInfo(); // Set value for upload context. uploadContextHandleIndex = AdapterHelper.GetHandleIndex(); uploadInfo.UploadHandleIndex = uploadContextHandleIndex; ConnectionData changeConnection = connections[serverId]; connections.Remove(serverId); // Add the new Upload context to UploadContextContainer. changeConnection.UploadContextContainer = changeConnection.UploadContextContainer.Add(uploadInfo); connections.Add(serverId, changeConnection); result = RopResult.Success; ModelHelper.CaptureRequirement( 581, @"[In RopFastTransferDestinationConfigure ROP] The RopFastTransferDestinationConfigure ROP ([MS-OXCROPS] section 2.2.12.1) initializes a FastTransfer operation for uploading content encoded in a client-provided FastTransfer stream into a mailbox."); if (requirementContainer.ContainsKey(3492002)) { if ((copyFlag == FastTransferDestinationConfigureCopyFlags.Invalid) && requirementContainer[3492002] == true) { // Exchange 2007 ignore unknown values of the CopyFlags field. ModelHelper.CaptureRequirement( 3492002, @"[In Appendix A: Product Behavior] If unknown flags in the CopyFlags field are set, implementation does not fail the operation. <40> Section 3.2.5.8.2.1: Exchange 2007 ignore unknown values of the CopyFlags field."); return result; } } return result; } /// <summary> /// Uploads the next portion of an input FastTransfer stream for a previously configured FastTransfer upload operation. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="uploadContextHandleIndex">A fastTransfer stream object handle index.</param> /// <param name="transferDataIndex">Transfer data index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = ("FastTransferDestinationPutBuffer(serverId,uploadContextHandleIndex,transferDataIndex)/result"))] public static RopResult FastTransferDestinationPutBuffer(int serverId, int uploadContextHandleIndex, int transferDataIndex) { // The construction conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // serverHandleIndex is Invalid Parameter. if (uploadContextHandleIndex < 0 || transferDataIndex <= 0) { return RopResult.InvalidParameter; } ModelHelper.CaptureRequirement( 614, @"[In RopFastTransferDestinationPutBuffer ROP] The RopFastTransferDestinationPutBuffer ROP ([MS-OXCROPS] section 2.2.12.2) uploads the next portion of an input FastTransfer stream for a previously configured FastTransfer upload operation."); return RopResult.Success; } /// <summary> /// Uploads the next portion of an input FastTransfer stream for a previously configured FastTransfer upload operation. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="uploadContextHandleIndex">A fastTransfer stream object handle index.</param> /// <param name="transferDataIndex">Transfer data index.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = ("FastTransferDestinationPutBufferExtended(serverId,uploadContextHandleIndex,transferDataIndex)/result"))] public static RopResult FastTransferDestinationPutBufferExtended(int serverId, int uploadContextHandleIndex, int transferDataIndex) { // The construction conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // serverHandleIndex is Invalid Parameter. if (uploadContextHandleIndex < 0 || transferDataIndex <= 0) { return RopResult.InvalidParameter; } ModelHelper.CaptureRequirement( 3183001, @"[In RopFastTransferDestinationPutBufferExtended ROP] The RopFastTransferDestinationPutBufferExtended ROP ([MS-OXCROPS] section 2.2.12.3) uploads the next portion of an input FastTransfer stream for a previously configured FastTransfer upload operation."); return RopResult.Success; } /// <summary> /// Tell the server of another server's version. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="serverHandleIndex">Server object handle index in handle container.</param> /// <param name="otherServerId">Another server's id.</param> /// <returns>Indicate the result of this ROP operation.</returns> [Rule(Action = ("TellVersion(serverId,serverHandleIndex,otherServerId)/result"))] public static RopResult TellVersion(int serverId, int serverHandleIndex, int otherServerId) { // The construction conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); if (serverHandleIndex < 0) { // serverHandleIndex is Invalid Parameter. return RopResult.InvalidParameter; } else { ModelHelper.CaptureRequirement( 572, @"[In RopTellVersion ROP] The RopTellVersion ROP ([MS-OXCROPS] section 2.2.12.8) is used to provide the version of one server to another server that is participating in the server-to-client-to-server upload, as specified in section 3.3.4.2.1."); return RopResult.Success; } } /// <summary> /// Tell the server of another server's version. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="folderHandleIndex">Folder Handle index.</param> /// <param name="deleteFlags">The delete flag indicates whether checking delete.</param> /// <param name="rowCount">The row count returned from server.</param> /// <returns>Indicate the result of this rop operation.</returns> [Rule(Action = ("GetContentsTable(serverId,folderHandleIndex,deleteFlags,out rowCount)/result"))] public static RopResult GetContentsTable(int serverId, int folderHandleIndex, DeleteFlags deleteFlags, out int rowCount) { // The construction conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Get current ConnectionData value. ConnectionData currentConnection = connections[serverId]; // Create a new currentDownloadContext. AbstractUploadInfo currentUploadContext = new AbstractUploadInfo(); rowCount = -1; // Find the current Upload Context foreach (AbstractUploadInfo tempUploadContext in currentConnection.UploadContextContainer) { if (tempUploadContext.RelatedFastTransferOperation == EnumFastTransferOperation.SynchronizationImportDeletes) { currentUploadContext = tempUploadContext; } } if (folderHandleIndex < 0) { rowCount = -1; // serverHandleIndex is Invalid Parameter. return RopResult.InvalidParameter; } else { if (deleteFlags == DeleteFlags.Initial) { rowCount = 0; return RopResult.Success; } else if (deleteFlags == DeleteFlags.HardDeleteCheck) { rowCount = 0; } else if (deleteFlags == DeleteFlags.SoftDeleteCheck) { rowCount = softDeleteMessageCount; if (priorOperation == MS_OXCFXICS.PriorOperation.RopSynchronizationImportMessageMove) { rowCount = 1; } } return RopResult.Success; } } /// <summary> /// Tell the server of another server's version. /// </summary> /// <param name="serverId">A 32-bit signed integer represent the Identity of server.</param> /// <param name="folderHandleIndex">Folder Handle index.</param> /// <param name="deleteFlags">The delete flag indicates whether checking delete.</param> /// <param name="rowCount">The row count returned from server.</param> /// <returns>Indicate the result of this rop operation.</returns> [Rule(Action = ("GetHierarchyTable(serverId,folderHandleIndex,deleteFlags,out rowCount)/result"))] public static RopResult GetHierarchyTable(int serverId, int folderHandleIndex, DeleteFlags deleteFlags, out int rowCount) { // The construction conditions. Condition.IsTrue(connections.Count > 0); Condition.IsTrue(connections.Keys.Contains(serverId)); // Get current ConnectionData value. ConnectionData currentConnection = connections[serverId]; // Create a new currentDownloadContext. AbstractUploadInfo currentUploadContext = new AbstractUploadInfo(); // Initialize the rowCount value. rowCount = -1; // Find the current Upload Context foreach (AbstractUploadInfo tempUploadContext in currentConnection.UploadContextContainer) { if (tempUploadContext.RelatedFastTransferOperation == EnumFastTransferOperation.SynchronizationImportDeletes) { currentUploadContext = tempUploadContext; } } if (folderHandleIndex < 0) { rowCount = -1; // serverHandleIndex is Invalid Parameter. return RopResult.InvalidParameter; } else { if (deleteFlags == DeleteFlags.Initial) { rowCount = 0; return RopResult.Success; } else if (deleteFlags == DeleteFlags.HardDeleteCheck) { if (requirementContainer.ContainsKey(90205002) && !requirementContainer[90205002]) { rowCount = -1; } else { rowCount = 0; } } else if (deleteFlags == DeleteFlags.SoftDeleteCheck) { rowCount = softDeleteFolderCount; } return RopResult.Success; } } #endregion #region Others /// <summary> /// Validate if the given two buffer is equal /// </summary> /// <param name="operation">The Enumeration Fast Transfer Operation</param> /// <param name="firstBufferIndex">The first Buffer's index</param> /// <param name="secondBufferIndex">The second buffer's index</param> /// <returns>Returns true only if the two buffers are equal</returns> [Rule(Action = ("AreEqual(operation,firstBufferIndex,secondBufferIndex)/result"))] private static bool AreEqual(EnumFastTransferOperation operation, int firstBufferIndex, int secondBufferIndex) { // Identify whether the firstBuffer and the secondBuffer are equal or not. if (firstBufferIndex <= 0 || secondBufferIndex <= 0) { return false; } bool returnValue = true; return returnValue; } #endregion } }
XinwLi/Interop-TestSuites-1
ExchangeMAPI/Source/MS-OXCFXICS/Model/Model.cs
C#
mit
359,170
/* * homeController.js * Jami Boy Mohammad */ var homeController = angular.module('homeController', []); homeController.controller('homeController', function($scope) { });
jamiboy16/bearded-ninja
public/app/components/home/homeController.js
JavaScript
mit
179
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; using System.Xml; using System.Xml.Linq; using System.IO; using Nuterra; namespace Sylver.PreciseSnapshots { public static class XMLSave { /// <summary> /// Save Techs as XML Files /// </summary> /// <param name="tech">Tech to save</param> /// <param name="path">Path of saving folder</param> public static void SaveTechAsXML(Tank tech,string path) { if (!Directory.Exists(path)) { Console.WriteLine("XMLSave : Specified path \"" + path + "\" doesn't exists !"); return; } XmlWriter saver = XmlWriter.Create(Path.Combine(path, tech.name+".xml"),new XmlWriterSettings { Indent = true }); saver.WriteStartDocument(); saver.WriteStartElement("Tech"); saver.WriteAttributeString("Name", tech.name); saver.WriteStartElement("Blocks"); foreach (var block in tech.blockman.IterateBlocks()) { saver.WriteStartElement("Block"); saver.WriteAttributeString("Type", block.BlockType.ToString()); if(tech.blockman.IsRootBlock(block)) saver.WriteAttributeString("IsRootBlock","true"); saver.WriteStartElement("BlockSpec"); saver.WriteStartElement("OrthoRotation"); saver.WriteString(block.cachedLocalRotation.rot.ToString()); saver.WriteEndElement(); var localPos = new IntVector3(block.cachedLocalPosition); saver.WriteStartElement("IntVector3"); saver.WriteAttributeString("x", localPos.x.ToString()); saver.WriteAttributeString("y", localPos.y.ToString()); saver.WriteAttributeString("z", localPos.z.ToString()); saver.WriteEndElement(); saver.WriteEndElement(); saver.WriteStartElement("Transform"); var pos = block.trans.localPosition; saver.WriteStartElement("Position"); saver.WriteAttributeString("x", pos.x.ToString()); saver.WriteAttributeString("y", pos.y.ToString()); saver.WriteAttributeString("z", pos.z.ToString()); saver.WriteEndElement(); var rotation = block.trans.localRotation.eulerAngles; saver.WriteStartElement("Rotation"); saver.WriteAttributeString("x", rotation.x.ToString()); saver.WriteAttributeString("y", rotation.y.ToString()); saver.WriteAttributeString("z", rotation.z.ToString()); saver.WriteEndElement(); var scale = block.trans.localScale; saver.WriteStartElement("Scale"); saver.WriteAttributeString("x", scale.x.ToString()); saver.WriteAttributeString("y", scale.y.ToString()); saver.WriteAttributeString("z", scale.z.ToString()); saver.WriteEndElement(); saver.WriteEndElement(); saver.WriteEndElement(); } saver.WriteEndElement(); saver.WriteEndDocument(); saver.Close(); } } }
maritaria/terratech-mod
src/Sylver.PreciseSnapshots/XMLSave.cs
C#
mit
3,819
package logviewer; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; /** * * @author Rene Zwanenburg */ public final class LogReader { private LogReader(){} public static ArrayList<Unit> readFile(File f) { ArrayList<Unit> l = new ArrayList<Unit>(); // Temporary unordered unit storage ArrayList<String> lines = new ArrayList<String>(); // Stores unit info lines try{ BufferedReader in = new BufferedReader(new FileReader(f)); String line = null; while((line = in.readLine()) != null){ // while more lines remain... line = line.trim(); // Remove all leading and trailing spaces. if(line.length() == 0 || !line.startsWith("0| [UNIT")) // If line is empty or isn't about units... continue; // Go to next line. lines.add(line); } } catch(Exception e){ System.err.println("Error Reading File:"); e.printStackTrace(); return null; } for(int i = 0; i < lines.size(); i++) // cut off unused first characters lines.set(i, lines.get(i).substring(9)); for(String s : lines){ // adds units to unordered list if(getUnit(getUnitID(s), l) == null) l.add(new Unit(getUnitID(s))); } ArrayList<Unit> units = new ArrayList<Unit>(); // ordered unit storage int maxID = l.size(); // Lowest possible amount of id's is unordered storage size for(int i = 0; i < maxID; i++){ if(getUnit(i, l) == null){ // If id 'i' is not in the list... maxID++; // The highest possible ID increases by one. continue; } units.add(getUnit(i, l)); } for(String s : lines) getUnit(getUnitID(s), units).addMessage(s); // Parsing the line is up to the unit return units; } private static int getUnitID(String line){ return Integer.parseInt(line.split("]")[0]); } private static Unit getUnit(int id, ArrayList<Unit> list){ for(Unit u : list) if(u.getId() == id) return u; return null; } }
166MMX/Dune-II---The-Maker
resources/tools/LogViewer/src/logviewer/LogReader.java
Java
mit
2,290
/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace dragonBones { /** * - The PixiJS texture atlas data. * @version DragonBones 3.0 * @language en_US */ /** * - PixiJS 贴图集数据。 * @version DragonBones 3.0 * @language zh_CN */ export class PixiTextureAtlasData extends TextureAtlasData { public static toString(): string { return "[class dragonBones.PixiTextureAtlasData]"; } private _renderTexture: PIXI.BaseTexture | null = null; // Initial value. protected _onClear(): void { super._onClear(); if (this._renderTexture !== null) { // this._renderTexture.dispose(); } this._renderTexture = null; } /** * @inheritDoc */ public createTexture(): TextureData { return BaseObject.borrowObject(PixiTextureData); } /** * - The PixiJS texture. * @version DragonBones 3.0 * @language en_US */ /** * - PixiJS 贴图。 * @version DragonBones 3.0 * @language zh_CN */ public get renderTexture(): PIXI.BaseTexture | null { return this._renderTexture; } public set renderTexture(value: PIXI.BaseTexture | null) { if (this._renderTexture === value) { return; } this._renderTexture = value; if (this._renderTexture !== null) { for (let k in this.textures) { const textureData = this.textures[k] as PixiTextureData; textureData.renderTexture = new PIXI.Texture( this._renderTexture, new PIXI.Rectangle(textureData.region.x, textureData.region.y, textureData.region.width, textureData.region.height), new PIXI.Rectangle(textureData.region.x, textureData.region.y, textureData.region.width, textureData.region.height), new PIXI.Rectangle(0, 0, textureData.region.width, textureData.region.height), textureData.rotated as any // .d.ts bug ); } } else { for (let k in this.textures) { const textureData = this.textures[k] as PixiTextureData; textureData.renderTexture = null; } } } } /** * @internal */ export class PixiTextureData extends TextureData { public static toString(): string { return "[class dragonBones.PixiTextureData]"; } public renderTexture: PIXI.Texture | null = null; // Initial value. protected _onClear(): void { super._onClear(); if (this.renderTexture !== null) { this.renderTexture.destroy(false); } this.renderTexture = null; } } }
DragonBones/DragonBonesJS
Pixi/5.x/src/dragonBones/pixi/PixiTextureAtlasData.ts
TypeScript
mit
4,172
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.cognitiveservices.vision.computervision.models; import java.util.List; /** * The AnalyzeImageOptionalParameter model. */ public class AnalyzeImageOptionalParameter { /** * A string indicating what visual feature types to return. Multiple values * should be comma-separated. Valid visual feature types include:Categories * - categorizes image content according to a taxonomy defined in * documentation. Tags - tags the image with a detailed list of words * related to the image content. Description - describes the image content * with a complete English sentence. Faces - detects if faces are present. * If present, generate coordinates, gender and age. ImageType - detects if * image is clipart or a line drawing. Color - determines the accent color, * dominant color, and whether an image is black&amp;white.Adult - detects * if the image is pornographic in nature (depicts nudity or a sex act). * Sexually suggestive content is also detected. */ private List<VisualFeatureTypes> visualFeatures; /** * A string indicating which domain-specific details to return. Multiple * values should be comma-separated. Valid visual feature types * include:Celebrities - identifies celebrities if detected in the image. */ private List<Details> details; /** * The desired language for output generation. If this parameter is not * specified, the default value is &amp;quot;en&amp;quot;.Supported * languages:en - English, Default. es - Spanish, ja - Japanese, pt - * Portuguese, zh - Simplified Chinese. Possible values include: 'en', * 'es', 'ja', 'pt', 'zh'. */ private String language; /** * Gets or sets the preferred language for the response. */ private String thisclientacceptLanguage; /** * Get the visualFeatures value. * * @return the visualFeatures value */ public List<VisualFeatureTypes> visualFeatures() { return this.visualFeatures; } /** * Set the visualFeatures value. * * @param visualFeatures the visualFeatures value to set * @return the AnalyzeImageOptionalParameter object itself. */ public AnalyzeImageOptionalParameter withVisualFeatures(List<VisualFeatureTypes> visualFeatures) { this.visualFeatures = visualFeatures; return this; } /** * Get the details value. * * @return the details value */ public List<Details> details() { return this.details; } /** * Set the details value. * * @param details the details value to set * @return the AnalyzeImageOptionalParameter object itself. */ public AnalyzeImageOptionalParameter withDetails(List<Details> details) { this.details = details; return this; } /** * Get the language value. * * @return the language value */ public String language() { return this.language; } /** * Set the language value. * * @param language the language value to set * @return the AnalyzeImageOptionalParameter object itself. */ public AnalyzeImageOptionalParameter withLanguage(String language) { this.language = language; return this; } /** * Get the thisclientacceptLanguage value. * * @return the thisclientacceptLanguage value */ public String thisclientacceptLanguage() { return this.thisclientacceptLanguage; } /** * Set the thisclientacceptLanguage value. * * @param thisclientacceptLanguage the thisclientacceptLanguage value to set * @return the AnalyzeImageOptionalParameter object itself. */ public AnalyzeImageOptionalParameter withThisclientacceptLanguage(String thisclientacceptLanguage) { this.thisclientacceptLanguage = thisclientacceptLanguage; return this; } }
navalev/azure-sdk-for-java
sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageOptionalParameter.java
Java
mit
4,218
<?php return [ 'plugin' => [ 'name' => 'Utenti', 'description' => 'Gestione Utenti Front-End.', 'tab' => 'Utenti', 'access_users' => 'Gestisci Utenti', 'access_groups' => 'Gestisci Gruppi di Utenti', 'access_settings' => 'Gestisci Impostazioni Utenti' ], 'users' => [ 'menu_label' => 'Utenti', 'all_users' => 'Tutti gli utenti', 'new_user' => 'Nuovo Utente', 'list_title' => 'Gestisci Utenti', 'trashed_hint_title' => 'L\'utente ha disabilitato il suo account', 'trashed_hint_desc' => 'Questo utente ha disattivato il suo account and e non vuole più apparire sul sito. Possono riattivarsi in qualsiasi momento effettuando l\'accesso.', 'banned_hint_title' => 'Questo utente è stato bannato', 'banned_hint_desc' => 'Questo utente è stato bannato da un amministratore e non potrà piú effettuare l\'accesso', 'guest_hint_title' => 'Questo è un utente anonimo', 'guest_hint_desc' => 'Questo utente è salvato solo per riferimento e deve registrarsi prima di poter effettuare l\'accesso', 'activate_warning_title' => 'Utente non attivo!', 'activate_warning_desc' => 'Questo utente non è stato attivato e potrebbe non essere in grado di effettuare l\'accesso', 'activate_confirm' => 'Vuoi veramente attivare questo utente?', 'activated_success' => 'Utente Attivato', 'activate_manually' => 'Attiva questo utente manualmente', 'convert_guest_confirm' => 'Convertire questo utente anonimo a un utente registrato?', 'convert_guest_manually' => 'Converti a un utente registrato', 'convert_guest_success' => 'Utente convertito a un account registrato', 'delete_confirm' => 'Vuoi veramente cancellare questo utente?', 'unban_user' => 'Sblocca questo utente', 'unban_confirm' => 'Vuoi veramente sbloccare questo utente?', 'unbanned_success' => 'L\'utente è stato sbloccato', 'return_to_list' => 'Ritorna alla lista utenti', 'update_details' => 'Aggiorna dettagli', 'bulk_actions' => 'Azioni multiple', 'delete_selected' => 'Elimina selezionati', 'delete_selected_confirm' => 'Eliminare gli utenti selezionati?', 'delete_selected_empty' => 'Non ci sono utenti selezionati da cancellare.', 'delete_selected_success' => 'Gli utenti selezionati sono stati cancellati con successo.', 'deactivate_selected' => 'Disabilita selezionati', 'deactivate_selected_confirm' => 'Disattivare gli utenti selezionati?', 'deactivate_selected_empty' => 'Non ci sono utenti selezionati da disattivare.', 'deactivate_selected_success' => 'Utenti selezionati disattivati con successo.', 'restore_selected' => 'Ripristina selezionati', 'restore_selected_confirm' => 'Ripristinare gli utenti selezionati?', 'restore_selected_empty' => 'Non ci sono utenti selezionati da ripristinare.', 'restore_selected_success' => 'Utenti selezionati ripristinati con successo.', 'ban_selected' => 'Blocca selezionati', 'ban_selected_confirm' => 'Bloccare l\'utente selezionato?', 'ban_selected_empty' => 'Non ci sono utenti selezionati da bloccare.', 'ban_selected_success' => 'Utenti selezionati bloccati con successo.', 'unban_selected' => 'Sblocca selezionati', 'unban_selected_confirm' => 'Sbloccare gli utenti selezionati?', 'unban_selected_empty' => 'Non ci sono utenti selezionati da sbloccare.', 'unban_selected_success' => 'Utenti selezionati sbloccati con successo.', ], 'settings' => [ 'users' => 'Utenti', 'menu_label' => 'Impostazioni Utenti', 'menu_description' => 'Gestisci impostazioni degli utenti', 'activation_tab' => 'Attivazione', 'signin_tab' => 'Accesso', 'registration_tab' => 'Registrazione', 'notifications_tab' => 'Notifiche', 'allow_registration' => 'Consenti registrazione utenti', 'allow_registration_comment' => 'Se questo è disabilitato gli utenti possono essere creati solo da un amministratore.', 'activate_mode' => 'Modalità di attivazione', 'activate_mode_comment' => 'Scegli come un utente dovrebbe essere attivato', 'activate_mode_auto' => 'Automaticamente', 'activate_mode_auto_comment' => 'Attivato automaticamente alla registrazione', 'activate_mode_user' => 'Utente', 'activate_mode_user_comment' => 'L\'utente si attiva da solo confermando la sua email', 'activate_mode_admin' => 'Amministratore', 'activate_mode_admin_comment' => 'Solo un amminstratore può attivare un utente.', 'require_activation' => 'Effettuare l\'accesso richiede l\'attivazione.', 'require_activation_comment' => 'Gli utenti devono avere un account attivato per effettuare l\'accesso.', 'block_persistence' => 'Previeni sessioni concorrenti', 'block_persistence_comment' => 'Quando abilitato gli utenti non possono effettuare il log-in da diversi dispositivi contemporaneamente', 'use_throttle' => 'Limita tentativi', 'use_throttle_comment' => 'Ripetuti tentativi errati di accesso porteranno alla sospensione temporanea dell\'utente.', 'login_attribute' => 'Metodo di login', 'login_attribute_comment' => 'Seleziona che attributo gli utenti useranno per effettuare il login.' , ], 'user' => [ 'label' => 'Utente', 'id' => 'ID', 'username' => 'Username', 'name' => 'Nome', 'name_empty' => 'Anonimo', 'surname' => 'Cognome', 'email' => 'Email', 'created_at' => 'Registrato', 'last_seen' => 'Ultimo accesso', 'is_guest' => 'Anonimo', 'joined' => 'Joined', 'is_online' => 'Online adesso', 'is_offline' => 'Al momento non collegato', 'send_invite' => 'Invia invito via mail', 'send_invite_comment' => 'Invia un messaggio di benvenuto contenente le informazioni per l\'accesso', 'create_password' => 'Crea Password', 'create_password_comment' => 'Inserisci una nuova password per l\'accesso.', 'reset_password' => 'Cambia la Password', 'reset_password_comment' => 'Per cambiare la password di questo utente, inserisci una nuova password quí', 'confirm_password' => 'Conferma Password', 'confirm_password_comment' => 'Inserisci nuovamente la password per confermare.', 'groups' => 'Gruppi', 'empty_groups' => 'Non ci sono gruppi di utenti disponibili.', 'avatar' => 'Avatar', 'details' => 'Dettagli', 'account' => 'Account', 'block_mail' => 'Blocca tutte le mail verso questo utente.', 'status_guest' => 'Anonimo', 'status_activated' => 'Attivato', 'status_registered' => 'Registrato', ], 'group' => [ 'label' => 'Gruppo', 'id' => 'ID', 'name' => 'Nome', 'description_field' => 'Descrizione', 'code' => 'Codice', 'code_comment' => 'Inserisci un codice univoco per identificare il gruppo.', 'created_at' => 'Creato', 'users_count' => 'Utenti' ], 'groups' => [ 'menu_label' => 'Gruppi', 'all_groups' => 'Gruppi di Utenti', 'new_group' => 'Nuovo gruppo', 'delete_selected_confirm' => 'Vuoi veramente cancellare i gruppi selezionati?', 'list_title' => 'Gestisci Gruppi', 'delete_confirm' => 'Vuoi veramente cancellare questo gruppo?', 'delete_selected_success' => 'Gruppi selezionati cancellati con successo.', 'delete_selected_empty' => 'Non ci sono gruppi selezionati da cancellare.', 'return_to_list' => 'Torna all\'elenco dei gruppi', 'return_to_users' => 'Torna alla lista utenti', 'create_title' => 'Crea Gruppo di Utenti', 'update_title' => 'Modifica Gruppo di Utenti', 'preview_title' => 'Anteprima Gruppo' ], 'login' => [ 'attribute_email' => 'Email', 'attribute_username' => 'Username' ], 'account' => [ 'account' => 'Account', 'account_desc' => 'Form di gestione account.', 'redirect_to' => 'Reindirizza A', 'redirect_to_desc' => 'Pagina verso cui essere reindirizzati dopo modifica, accesso o registrazione.', 'code_param' => 'Parametro codice di attivazione', 'code_param_desc' => 'Parametro dell\'URL usato per il codice di attivazione', 'invalid_user' => 'Impossibile effettuare il login con le credenziali fornite.', 'invalid_activation_code' => 'Codice di attivazione fornito non valido.', 'invalid_deactivation_pass' => 'La password inserita non è valida.', 'success_activation' => 'Account attivato con successo.', 'success_deactivation' => 'Account disattivato con successo. Ci dispiace vederti andare via!', 'success_saved' => 'Impostazioni salvate con successo!', 'login_first' => 'Devi prima effettuare l\'accesso!', 'already_active' => 'Il tuo account è già stato attivato!', 'activation_email_sent' => 'Una mail di attivazione è stata inviata al tuo indirizzo mail.', 'registration_disabled' => 'La registrazione è al momento disattivata.', 'sign_in' => 'Accedi', 'register' => 'Registra', 'full_name' => 'Nome Completo', 'email' => 'Email', 'password' => 'Password', 'login' => 'Login', 'new_password' => 'Nuova Password', 'new_password_confirm' => 'Conferma Nuova Password' ], 'reset_password' => [ 'reset_password' => 'Ripristina Password', 'reset_password_desc' => 'Form password dimenticata.', 'code_param' => 'Parametro codice di ripristino', 'code_param_desc' => 'Parametro dell\'URL usato per il codice di ripristino' ], 'session' => [ 'session' => 'Sessione', 'session_desc' => 'Aggiungi la sessione utente a una pagina per limitare l\'accesso.', 'security_title' => 'Autorizza solo', 'security_desc' => 'Chi è autorizzato ad accedere alla pagina.', 'all' => 'Tutti', 'users' => 'Utenti', 'guests' => 'Anonimi', 'redirect_title' => 'Reindirizza a', 'redirect_desc' => 'Nome della pagina a cui reindirizzare se l\'accesso è negato.', 'logout' => 'Sei stato scollegato con successo!' ] ];
LukeTowers/oc-queencityhack2k17-site
plugins/rainlab/user/lang/it/lang.php
PHP
mit
10,511
'use strict'; /**@type {{[k: string]: string}} */ let BattleAliases = { // formats "randbats": "[Gen 8] Random Battle", "uber": "[Gen 8] Ubers", "ag": "[Gen 8] Anything Goes", "mono": "[Gen 8] Monotype", "randdubs": "[Gen 8] Random Doubles Battle", "doubles": "[Gen 8] Doubles OU", "dubs": "[Gen 8] Doubles OU", "dou": "[Gen 8] Doubles OU", "duu": "[Gen 8] Doubles UU", "vgc17": "[Gen 7] VGC 2017", "vgc18": "[Gen 7] VGC 2018", "vgc19": "[Gen 7] VGC 2019 Ultra Series", "bss": "[Gen 8] Battle Stadium Singles", "bsd": "[Gen 8] Battle Stadium Doubles", "bsdoubles": "[Gen 8] Battle Stadium Doubles", "2v2": "[Gen 8] 2v2 Doubles", "natdex": "[Gen 8] National Dex", "natdexag": "[Gen 8] National Dex AG", "bh": "[Gen 8] Balanced Hackmons", "mnm": "[Gen 8] Mix and Mega", "aaa": "[Gen 8] Almost Any Ability", "gen7bh": "[Gen 7] Balanced Hackmons", "cc1v1": "[Gen 8] Challenge Cup 1v1", "cc2v2": "[Gen 8] Challenge Cup 2v2", "hc": "[Gen 8] Hackmons Cup", "monorandom": "[Gen 8] Monotype Random Battle", "bf": "[Gen 7] Battle Factory", "bssf": "[Gen 7] BSS Factory", "ssb": "[Gen 7] Super Staff Bros Brawl", "lgrandom": "[Gen 7] Let's Go Random Battle", "gen6bf": "[Gen 6] Battle Factory", "gen7mono": "[Gen 7] Monotype", "gen7ag": "[Gen 7] Anything Goes", "gen7bss": "[Gen 7] Battle Spot Singles", "gen7bsd": "[Gen 7] Battle Spot Doubles", "gen6mono": "[Gen 6] Monotype", "gen6ag": "[Gen 6] Anything Goes", "petmod": "[Gen 7 Pet Mod] Clean Slate: Micro", "cleanslatemicro": "[Gen 7 Pet Mod] Clean Slate: Micro", "csm": "[Gen 7 Pet Mod] Clean Slate: Micro", // mega evos "fabio": "Ampharos-Mega", "maero": "Aerodactyl-Mega", "megabunny": "Lopunny-Mega", "megabro": "Slowbro-Mega", "megacharizard": "Charizard-Mega-Y", "megacharizardx": "Charizard-Mega-X", "megacharizardy": "Charizard-Mega-Y", "megadoom": "Houndoom-Mega", "megadrill": "Beedrill-Mega", "megagard": "Gardevoir-Mega", "megacross": "Heracross-Mega", "megakhan": "Kangaskhan-Mega", "megalop": "Lopunny-Mega", "megaluc": "Lucario-Mega", "megamaw": "Mawile-Mega", "megamedi": "Medicham-Mega", "megamewtwo": "Mewtwo-Mega-Y", "megamewtwox": "Mewtwo-Mega-X", "megamewtwoy": "Mewtwo-Mega-Y", "megasnow": "Abomasnow-Mega", "megashark": "Sharpedo-Mega", "megasaur": "Venusaur-Mega", "mmx": "Mewtwo-Mega-X", "mmy": "Mewtwo-Mega-Y", "zardx": "Charizard-Mega-X", "zardy": "Charizard-Mega-y", // Pokéstar Studios "blackdoor": "Pokestar Black-Door", "brycen": "Brycen-Man", "brycenman": "Pokestar Brycen-Man", "f00": "Pokestar F00", "f002": "Pokestar F002", "giant": "Pokestar Giant", "mt": "Pokestar MT", "mt2": "Pokestar MT2", "majin": "Spirit", "mechatyranitar": "MT", "mechatyranitar2": "MT2", "monica": "Giant", "spirit": "Pokestar Spirit", "transport": "Pokestar Transport", "ufo": "Pokestar UFO", "ufo2": "Pokestar UFO-2", "whitedoor": "Pokestar White-Door", // formes "bugceus": "Arceus-Bug", "darkceus": "Arceus-Dark", "dragonceus": "Arceus-Dragon", "eleceus": "Arceus-Electric", "fairyceus": "Arceus-Fairy", "fightceus": "Arceus-Fighting", "fireceus": "Arceus-Fire", "flyceus": "Arceus-Flying", "ghostceus": "Arceus-Ghost", "grassceus": "Arceus-Grass", "groundceus": "Arceus-Ground", "iceceus": "Arceus-Ice", "poisonceus": "Arceus-Poison", "psyceus": "Arceus-Psychic", "rockceus": "Arceus-Rock", "steelceus": "Arceus-Steel", "waterceus": "Arceus-Water", "arcbug": "Arceus-Bug", "arcdark": "Arceus-Dark", "arcdragon": "Arceus-Dragon", "arcelectric": "Arceus-Electric", "arcfairy": "Arceus-Fairy", "arcfighting": "Arceus-Fighting", "arcfire": "Arceus-Fire", "arcflying": "Arceus-Flying", "arcghost": "Arceus-Ghost", "arcgrass": "Arceus-Grass", "arcground": "Arceus-Ground", "arcice": "Arceus-Ice", "arcpoison": "Arceus-Poison", "arcpsychic": "Arceus-Psychic", "arcrock": "Arceus-Rock", "arcsteel": "Arceus-Steel", "arcwater": "Arceus-Water", "basculinb": "Basculin-Blue-Striped", "basculinblue": "Basculin-Blue-Striped", "basculinbluestripe": "Basculin-Blue-Striped", "castformh": "Castform-Snowy", "castformice": "Castform-Snowy", "castformr": "Castform-Rainy", "castformwater": "Castform-Rainy", "castforms": "Castform-Sunny", "castformfire": "Castform-Sunny", "cherrims": "Cherrim-Sunshine", "cherrimsunny": "Cherrim-Sunshine", "darmanitanz": "Darmanitan-Zen", "darmanitanzenmode": "Darmanitan-Zen", "darmanitanzengalar": "Darmanitan-Galar-Zen", "deoxysnormal": "Deoxys", "deon": "Deoxys", "deoxysa": "Deoxys-Attack", "deoa": "Deoxys-Attack", "deoxysd": "Deoxys-Defense", "deoxysdefence": "Deoxys-Defense", "deod": "Deoxys-Defense", "deoxyss": "Deoxys-Speed", "deos": "Deoxys-Speed", "eiscuen": "Eiscue-Noice", "eternalfloette": "Floette-Eternal", "eternamax": "Eternatus-Eternamax", "girao": "Giratina-Origin", "giratinao": "Giratina-Origin", "gourgeists": "Gourgeist-Small", "gourgeistl": "Gourgeist-Large", "gourgeistxl": "Gourgeist-Super", "gourgeisth": "Gourgeist-Super", "gourgeisthuge": "Gourgeist-Super", "hoopau": "Hoopa-Unbound", "keldeor": "Keldeo-Resolute", "keldeoresolution": "Keldeo-Resolute", "kyuremb": "Kyurem-Black", "kyuremw": "Kyurem-White", "landorust": "Landorus-Therian", "meloettap": "Meloetta-Pirouette", "meloettas": "Meloetta-Pirouette", "meloettastep": "Meloetta-Pirouette", "meowsticfemale": "Meowstic-F", "morpekoh": "Morpeko-Hangry", "pumpkaboohuge": "Pumpkaboo-Super", "rotomc": "Rotom-Mow", "rotomcut": "Rotom-Mow", "rotomf": "Rotom-Frost", "rotomh": "Rotom-Heat", "rotoms": "Rotom-Fan", "rotomspin": "Rotom-Fan", "rotomw": "Rotom-Wash", "shaymins": "Shaymin-Sky", "skymin": "Shaymin-Sky", "thundurust": "Thundurus-Therian", "thundyt": "Thundurus-Therian", "tornadust": "Tornadus-Therian", "tornt": "Tornadus-Therian", "toxtricityl": "Toxtricity-Low-Key", "toxtricitylk": "Toxtricity-Low-Key", "wormadamg": "Wormadam-Sandy", "wormadamground": "Wormadam-Sandy", "wormadamsandycloak": "Wormadam-Sandy", "wormadams": "Wormadam-Trash", "wormadamsteel": "Wormadam-Trash", "wormadamtrashcloak": "Wormadam-Trash", "floettee": "Floette-Eternal", "floetteeternalflower": "Floette-Eternal", "ashgreninja": "Greninja-Ash", "zydog": "Zygarde-10%", "zydoge": "Zygarde-10%", "zygardedog": "Zygarde-10%", "zygarde50": "Zygarde", "zyc": "Zygarde-Complete", "zygarde100": "Zygarde-Complete", "zygardec": "Zygarde-Complete", "zygardefull": "Zygarde-Complete", "zygod": "Zygarde-Complete", "perfectzygarde": "Zygarde-Complete", "oricoriob": "Oricorio", "oricoriobaile": "Oricorio", "oricoriof": "Oricorio", "oricoriofire": "Oricorio", "oricorioe": "Oricorio-Pom-Pom", "oricorioelectric": "Oricorio-Pom-Pom", "oricoriog": "Oricorio-Sensu", "oricorioghost": "Oricorio-Sensu", "oricorios": "Oricorio-Sensu", "oricoriop": "Oricorio-Pa'u", "oricoriopsychic": "Oricorio-Pa'u", "lycanrocmidday": "Lycanroc", "lycanrocday": "Lycanroc", "lycanrocn": "Lycanroc-Midnight", "lycanrocnight": "Lycanroc-Midnight", "lycanrocd": "Lycanroc-Dusk", "ndm": "Necrozma-Dusk-Mane", "ndw": "Necrozma-Dawn-Wings", "necrozmadm": "Necrozma-Dusk-Mane", "necrozmadusk": "Necrozma-Dusk-Mane", "duskmane": "Necrozma-Dusk-Mane", "duskmanenecrozma": "Necrozma-Dusk-Mane", "necrozmadw": "Necrozma-Dawn-Wings", "necrozmadawn": "Necrozma-Dawn-Wings", "dawnwings": "Necrozma-Dawn-Wings", "dawnwingsnecrozma": "Necrozma-Dawn-Wings", "necrozmau": "Necrozma-Ultra", "ultranecrozma": "Necrozma-Ultra", "unecro": "Necrozma-Ultra", "ufop": "Pokestar UFO-2", "ufopsychic": "Pokestar UFO-2", "zacianc": "Zacian-Crowned", "zamazentac": "Zamazenta-Crowned", // base formes "nidoranfemale": "Nidoran-F", "nidoranmale": "Nidoran-M", "wormadamgrass": "Wormadam", "wormadamp": "Wormadam", "wormadamplant": "Wormadam", "wormadamplantcloak": "Wormadam", "cherrimo": "Cherrim", "cherrimovercast": "Cherrim", "giratinaa": "Giratina", "giratinaaltered": "Giratina", "shayminl": "Shaymin", "shayminland": "Shaymin", "basculinr": "Basculin", "basculinred": "Basculin", "basculinredstripe": "Basculin", "basculinredstriped": "Basculin", "darmanitans": "Darmanitan", "darmanitanstandard": "Darmanitan", "darmanitanstandardmode": "Darmanitan", "tornadusi": "Tornadus", "tornadusincarnate": "Tornadus", "tornadusincarnation": "Tornadus", "thundurusi": "Thundurus", "thundurusincarnate": "Thundurus", "thundurusincarnation": "Thundurus", "landorusi": "Landorus", "landorusincarnate": "Landorus", "landorusincarnation": "Landorus", "keldeoo": "Keldeo", "keldeoordinary": "Keldeo", "meloettaa": "Meloetta", "meloettaaria": "Meloetta", "meloettavoice": "Meloetta", "meowsticm": "Meowstic", "meowsticmale": "Meowstic", "aegislashs": "Aegislash", "aegislashshield": "Aegislash", "pumpkabooaverage": "Pumpkaboo", "gourgeistaverage": "Gourgeist", "hoopac": "Hoopa", "hoopaconfined": "Hoopa", "wishiwashisolo": "Wishiwashi", "pokestarufof": "Pokestar UFO", "pokestarufoflying": "Pokestar UFO", "toxtricitya": "Toxtricity", "toxtricityamped": "Toxtricity", "ufof": "Pokestar UFO", "ufoflying": "Pokestar UFO", // event formes "rockruffdusk": "Rockruff", // totem formes "raticatet": "Raticate-Alola-Totem", "totemalolanraticate": "Raticate-Alola-Totem", "totemraticate": "Raticate-Alola-Totem", "totemraticatea": "Raticate-Alola-Totem", "totemraticatealola": "Raticate-Alola-Totem", "marowakt": "Marowak-Alola-Totem", "totemalolanmarowak": "Marowak-Alola-Totem", "totemmarowak": "Marowak-Alola-Totem", "totemmarowaka": "Marowak-Alola-Totem", "totemmarowakalola": "Marowak-Alola-Totem", "gumshoost": "Gumshoos-Totem", "totemgumshoos": "Gumshoos-Totem", "totemvikavolt": "Vikavolt-Totem", "vikavoltt": "Vikavolt-Totem", "ribombeet": "Ribombee-Totem", "totemribombee": "Ribombee-Totem", "araquanidt": "Araquanid-Totem", "totemaraquanid": "Araquanid-Totem", "lurantist": "Lurantis-Totem", "totemlurantis": "Lurantis-Totem", "salazzlet": "Salazzle-Totem", "totemsalazzle": "Salazzle-Totem", "mimikyut": "Mimikyu-Totem", "totemmimikyu": "Mimikyu-Totem", "kommoot": "Kommo-o-Totem", "totemkommoo": "Kommo-o-Totem", // cosmetic formes "alcremierubycream": "Alcremie", "alcremiematcha": "Alcremie", "alcremiemint": "Alcremie", "alcremielemon": "Alcremie", "alcremiesalted": "Alcremie", "alcremierubyswirl": "Alcremie", "alcremiecaramel": "Alcremie", "alcremierainbow": "Alcremie", "burmygrass": "Burmy", "burmyplant": "Burmy", "burmysandy": "Burmy", "burmytrash": "Burmy", "shelloseast": "Shellos", "shelloswest": "Shellos", "gastrodone": "Gastrodon", "gastrodoneast": "Gastrodon", "gastrodoneastsea": "Gastrodon", "gastrodonw": "Gastrodon", "gastrodonwest": "Gastrodon", "gastrodonwestsea": "Gastrodon", "deerlingspring": "Deerling", "deerlingsummer": "Deerling", "deerlingautumn": "Deerling", "deerlingwinter": "Deerling", "sawsbuckspring": "Sawsbuck", "sawsbucksummer": "Sawsbuck", "sawsbuckautumn": "Sawsbuck", "sawsbuckwinter": "Sawsbuck", "vivillonarchipelago": "Vivillon", "vivilloncontinental": "Vivillon", "vivillonelegant": "Vivillon", "vivillongarden": "Vivillon", "vivillonhighplains": "Vivillon", "vivillonicysnow": "Vivillon", "vivillonjungle": "Vivillon", "vivillonmarine": "Vivillon", "vivillonmodern": "Vivillon", "vivillonmonsoon": "Vivillon", "vivillonocean": "Vivillon", "vivillonpolar": "Vivillon", "vivillonriver": "Vivillon", "vivillonsandstorm": "Vivillon", "vivillonsavanna": "Vivillon", "vivillonsun": "Vivillon", "vivillontundra": "Vivillon", "flabb": "Flabebe", "flabebered": "Flabebe", "flabebeblue": "Flabebe", "flabebeorange": "Flabebe", "flabebewhite": "Flabebe", "flabebeyellow": "Flabebe", "flabbred": "Flabebe", "flabbblue": "Flabebe", "flabborange": "Flabebe", "flabbwhite": "Flabebe", "flabbyellow": "Flabebe", "floettered": "Floette", "floetteblue": "Floette", "floetteorange": "Floette", "floettewhite": "Floette", "floetteyellow": "Floette", "florgesred": "Florges", "florgesblue": "Florges", "florgesorange": "Florges", "florgeswhite": "Florges", "florgesyellow": "Florges", "furfroudandy": "Furfrou", "furfroudebutante": "Furfrou", "furfroudiamond": "Furfrou", "furfrouheart": "Furfrou", "furfroukabuki": "Furfrou", "furfroulareine": "Furfrou", "furfroumatron": "Furfrou", "furfroupharaoh": "Furfrou", "furfroustar": "Furfrou", "miniorred": "Minior", "miniororange": "Minior", "minioryellow": "Minior", "miniorgreen": "Minior", "miniorblue": "Minior", "miniorindigo": "Minior", "miniorviolet": "Minior", "pokestargiant2": "Pokestar Giant", "pokestarmonica2": "Pokestar Giant", "pokestarufopropu1": "Pokestar UFO", "pokestarpropu1": "Pokestar UFO", "pokestarpropu2": "Pokestar UFO-2", "pokestarbrycenmanprop": "Pokestar Brycen-Man", "pokestarproph1": "Pokestar Brycen-Man", "pokestarmtprop": "Pokestar MT", "pokestarpropm1": "Pokestar MT", "pokestarmt2prop": "Pokestar MT2", "pokestarpropm2": "Pokestar MT2", "pokestartransportprop": "Pokestar Transport", "pokestarpropt1": "Pokestar Transport", "pokestargiantpropo1": "Pokestar Giant", "pokestarpropo1": "Pokestar Giant", "pokestargiantpropo2": "Pokestar Giant", "pokestarpropo2": "Pokestar Giant", "pokestarhumanoidprop": "Pokestar Humanoid", "pokestarpropc1": "Pokestar Humanoid", "pokestarmonsterprop": "Pokestar Monster", "pokestarpropc2": "Pokestar Monster", "pokestarspiritprop": "Pokestar Spirit", "pokestarpropg1": "Pokestar Spirit", "pokestarblackdoorprop": "Pokestar Black Door", "pokestarpropw1": "Pokestar Black Door", "pokestarwhitedoorprop": "Pokestar White Door", "pokestarpropw2": "Pokestar White Door", "pokestarf00prop": "Pokestar F00", "pokestarpropr1": "Pokestar F00", "pokestarf002prop": "Pokestar F002", "pokestarpropr2": "Pokestar F002", "pokestarblackbeltprop": "Pokestar Black Belt", "pokestarpropk1": "Pokestar Black Belt", "giant2": "Pokestar Giant", "monica2": "Pokestar Giant", "ufopropu1": "Pokestar UFO", "propu1": "Pokestar UFO", "ufopropu2": "Pokestar UFO-2", "propu2": "Pokestar UFO-2", "brycenmanprop": "Pokestar Brycen-Man", "proph1": "Pokestar Brycen-Man", "mtprop": "Pokestar MT", "propm1": "Pokestar MT", "mt2prop": "Pokestar MT2", "propm2": "Pokestar MT2", "transportprop": "Pokestar Transport", "propt1": "Pokestar Transport", "giantpropo1": "Pokestar Giant", "propo1": "Pokestar Giant", "giantpropo2": "Pokestar Giant", "propo2": "Pokestar Giant", "humanoidprop": "Pokestar Humanoid", "propc1": "Pokestar Humanoid", "monsterprop": "Pokestar Monster", "propc2": "Pokestar Monster", "spiritprop": "Pokestar Spirit", "propg1": "Pokestar Spirit", "blackdoorprop": "Pokestar Black Door", "propw1": "Pokestar Black Door", "whitedoorprop": "Pokestar White Door", "propw2": "Pokestar White Door", "f00prop": "Pokestar F00", "propr1": "Pokestar F00", "f002prop": "Pokestar F002", "propr2": "Pokestar F002", "blackbeltprop": "Pokestar Black Belt", "propk1": "Pokestar Black Belt", // abilities "ph": "Poison Heal", "regen": "Regenerator", "stag": "Shadow Tag", // items "assvest": "Assault Vest", "av": "Assault Vest", "balloon": "Air Balloon", "band": "Choice Band", "cb": "Choice Band", "ebelt": "Expert Belt", "fightgem": "Fighting Gem", "flightgem": "Flying Gem", "goggles": "Safety Goggles", "helmet": "Rocky Helmet", "lefties": "Leftovers", "lo": "Life Orb", "lorb": "Life Orb", "sash": "Focus Sash", "scarf": "Choice Scarf", "specs": "Choice Specs", "wp": "Weakness Policy", // pokemon "aboma": "Abomasnow", "aegi": "Aegislash", "aegiblade": "Aegislash-Blade", "aegis": "Aegislash", "aero": "Aerodactyl", "amph": "Ampharos", "arc": "Arceus", "arceusnormal": "Arceus", "ashgren": "Greninja-Ash", "azu": "Azumarill", "bdrill": "Beedrill", "bee": "Beedrill", "birdjesus": "Pidgeot", "bish": "Bisharp", "blace": "Blacephalon", "bliss": "Blissey", "bulu": "Tapu Bulu", "camel": "Camerupt", "cathy": "Trevenant", "chandy": "Chandelure", "chomp": "Garchomp", "clef": "Clefable", "coba": "Cobalion", "cofag": "Cofagrigus", "conk": "Conkeldurr", "cress": "Cresselia", "cube": "Kyurem-Black", "cune": "Suicune", "darm": "Darmanitan", "dnite": "Dragonite", "dogars": "Koffing", "don": "Groudon", "drill": "Excadrill", "driller": "Excadrill", "dug": "Dugtrio", "duggy": "Dugtrio", "ekiller": "Arceus", "esca": "Escavalier", "ferro": "Ferrothorn", "fini": "Tapu Fini", "forry": "Forretress", "fug": "Rayquaza", "gar": "Gengar", "garde": "Gardevoir", "gatr": "Feraligatr", "gene": "Genesect", "gira": "Giratina", "gren": "Greninja", "gross": "Metagross", "gyara": "Gyarados", "hera": "Heracross", "hippo": "Hippowdon", "honch": "Honchkrow", "kanga": "Kangaskhan", "karp": "Magikarp", "kart": "Kartana", "keld": "Keldeo", "klef": "Klefki", "koko": "Tapu Koko", "kou": "Raikou", "krook": "Krookodile", "kyub": "Kyurem-Black", "kyuw": "Kyurem-White", "lando": "Landorus", "landoi": "Landorus", "landot": "Landorus-Therian", "lego": "Nihilego", "lele": "Tapu Lele", "linda": "Fletchinder", "luke": "Lucario", "lurk": "Golurk", "mage": "Magearna", "mamo": "Mamoswine", "mandi": "Mandibuzz", "mence": "Salamence", "milo": "Milotic", "morfentshusbando": "Gengar", "naga": "Naganadel", "nape": "Infernape", "nebby": "Cosmog", "neckboy": "Exeggutor-Alola", "nidok": "Nidoking", "nidoq": "Nidoqueen", "obama": "Abomasnow", "ogre": "Kyogre", "ohmagod": "Plasmanta", "p2": "Porygon2", "pert": "Swampert", "pex": "Toxapex", "phero": "Pheromosa", "pika": "Pikachu", "pory2": "Porygon2", "poryz": "Porygon-Z", "pyuku": "Pyukumuku", "pz": "Porygon-Z", "queen": "Nidoqueen", "rachi": "Jirachi", "rank": "Reuniclus", "ray": "Rayquaza", "reuni": "Reuniclus", "sab": "Sableye", "sable": "Sableye", "scept": "Sceptile", "scoli": "Scolipede", "serp": "Serperior", "shao": "Mienshao", "skarm": "Skarmory", "smogon": "Koffing", "smogonbird": "Talonflame", "snips": "Drapion", "staka": "Stakataka", "steela": "Celesteela", "sui": "Suicune", "swole": "Buzzwole", "talon": "Talonflame", "tang": "Tangrowth", "terra": "Terrakion", "tflame": "Talonflame", "thundy": "Thundurus", "toed": "Politoed", "torn": "Tornadus", "tran": "Heatran", "ttar": "Tyranitar", "venu": "Venusaur", "viriz": "Virizion", "whimsi": "Whimsicott", "xern": "Xerneas", "xurk": "Xurkitree", "ygod": "Yveltal", "zam": "Alakazam", "zard": "Charizard", "zong": "Bronzong", "zor": "Scizor", "zyg": "Zygarde", // ultra beast codenames "ub01": "Nihilego", "ub02a": "Buzzwole", "ub02b": "Pheromosa", "ub03": "Xurkitree", "ub04blade": "Kartana", "ub04blaster": "Celesteela", "ub05": "Guzzlord", "ubburst": "Blacephalon", "ubassembly": "Stakataka", "ubadhesive": "Poipole", // moves "bb": "Brave Bird", "bd": "Belly Drum", "bpass": "Baton Pass", "bp": "Baton Pass", "cc": "Close Combat", "cm": "Calm Mind", "dbond": "Destiny Bond", "dd": "Dragon Dance", "dv": "Dark Void", "eq": "Earthquake", "espeed": "ExtremeSpeed", "eterrain": "Electric Terrain", "faintattack": "Feint Attack", "glowpunch": "Power-up Punch", "gterrain": "Grassy Terrain", "hp": "Hidden Power", "hpbug": "Hidden Power Bug", "hpdark": "Hidden Power Dark", "hpdragon": "Hidden Power Dragon", "hpelectric": "Hidden Power electric", "hpfighting": "Hidden Power Fighting", "hpfire": "Hidden Power Fire", "hpflying": "Hidden Power Flying", "hpghost": "Hidden Power Ghost", "hpgrass": "Hidden Power Grass", "hpground": "Hidden Power Ground", "hpice": "Hidden Power Ice", "hppoison": "Hidden Power Poison", "hppsychic": "Hidden Power Psychic", "hprock": "Hidden Power Rock", "hpsteel": "Hidden Power Steel", "hpwater": "Hidden Power Water", "hjk": "High Jump Kick", "hijumpkick": "High Jump Kick", "mterrain": "Misty Terrain", "np": "Nasty Plot", "pfists": "Plasma Fists", "playaround": "Play Rough", "pterrain": "Psychic Terrain", "pup": "Power-up Punch", "qd": "Quiver Dance", "rocks": "Stealth Rock", "sd": "Swords Dance", "se": "Stone Edge", "spin": "Rapid Spin", "sr": "Stealth Rock", "sub": "Substitute", "tr": "Trick Room", "troom": "Trick Room", "tbolt": "Thunderbolt", "tspikes": "Toxic Spikes", "twave": "Thunder Wave", "vicegrip": "Vise Grip", "web": "Sticky Web", "wow": "Will-O-Wisp", // z-moves "10mv": "10,000,000 Volt Thunderbolt", "10mvt": "10,000,000 Volt Thunderbolt", "clangorous": "Clangorous Soulblaze", "cs": "Clangorous Soulblaze", "ee": "Extreme Evoboost", "extreme": "Extreme Evoboost", "genesis": "Genesis Supernova", "goa": "Guardian of Alola", "gs": "Genesis Supernova", "guardian": "Guardian of Alola", "lets": "Let's Snuggle Forever", "light": "Light That Burns the Sky", "lsf": "Let's Snuggle Forever", "ltbts": "Light That Burns the Sky", "malicious": "Malicious Moonsault", "menacing": "Menacing Moonraze Maelstrom", "mmm": "Menacing Moonraze Maelstrom", "moonsault": "Malicious Moonsault", "oceanic": "Oceanic Operetta", "oo": "Oceanic Operetta", "pp": "Pulverizing Pancake", "pulverizing": "Pulverizing Pancake", "sar": "Sinister Arrow Raid", "searing": "Searing Sunraze Smash", "sinister": "Sinister Arrow Raid", "ss": "Stoked Sparksurfer", "sss": "Searing Sunraze Smash", "sssss": "Soul-Stealing 7-Star Strike", "ss7ss": "Soul-Stealing 7-Star Strike", "soul": "Soul-Stealing 7-Star Strike", "soulstealingsevenstarstrike": "Soul-Stealing 7-Star Strike", "splintered": "Splintered Stormshards", "stoked": "Stoked Sparksurfer", "stormshards": "Splintered Stormshards", "zbug": "Savage Spin-Out", "zclangingscales": "Clangorous Soulblaze", "zdark": "Black Hole Eclipse", "zdarkestlariat": "Malicious Moonsault", "zdawnwingsnecrozma": "Menacing Moonraze Maelstrom", "zdecidueye": "Sinister Arrow Raid", "zdragon": "Devastating Drake", "zduskmanenecrozma": "Searing Sunraze Smash", "zelectric": "Gigavolt Havoc", "zeevee": "Extreme Evoboost", "zevo": "Extreme Evoboost", "zfairy": "Twinkle Tackle", "zflying": "Supersonic Skystrike", "zfighting": "All-Out Pummeling", "zfire": "Inferno Overdrive", "zghost": "Never-Ending Nightmare", "zgigaimpact": "Pulverizing Pancake", "zgrass": "Bloom Doom", "zground": "Tectonic Rage", "zice": "Subzero Slammer", "zincineroar": "Malicious Moonsault", "zkommoo": "Clangorous Soulblaze", "zlastresort": "Extreme Evoboost", "zlunala": "Menacing Moonraze Maelstrom", "zlycanroc": "Splintered Stormshards", "znaturesmadness": "Guardian of Alola", "zmarshadow": "Soul-Stealing 7-Star Strike", "zmew": "Genesis Supernova", "zmimikyu": "Let's Snuggle Forever", "zmoongeistbeam": "Menacing Moonraze Maelstrom", "znecrozma": "Light That Burns the Sky", "znormal": "Breakneck Blitz", "zrock": "Continental Crush", "zphotongeyser": "Light That Burns the Sky", "zpikachu": "Catastropika", "zpikachucap": "10,000,000 Volt Thunderbolt", "zplayrough": "Let's Snuggle Forever", "zpoison": "Acid Downpour", "zprimarina": "Oceanic Operetta", "zpsychic": "Shattered Psyche", "zraichu": "Stoked Sparksurfer", "zsnorlax": "Pulverizing Pancake", "zsolgaleo": "Searing Sunraze Smash", "zsparklingaria": "Oceanic Operetta", "zspectralthief": "Soul-Stealing 7-Star Strike", "zspiritshackle": "Sinister Arrow Raid", "zsunsteelstrike": "Searing Sunraze Smash", "zsteel": "Corkscrew Crash", "zstoneedge": "Splintered Stormshards", "ztapu": "Guardian of Alola", "zthunderbolt": "10,000,000 Volt Thunderbolt", "zultranecrozma": "Light That Burns the Sky", "zvolttackle": "Catastropika", "zwater": "Hydro Vortex", // Max moves "maxbug": "Max Flutterby", "maxdark": "Max Darkness", "maxdragon": "Max Wyrmwind", "maxelectric": "Max Lightning", "maxfairy": "Max Starfall", "maxfighting": "Max Knuckle", "maxfire": "Max Flare", "maxflying": "Max Airstream", "maxghost": "Max Phantasm", "maxgrass": "Max Overgrowth", "maxground": "Max Quake", "maxice": "Max Hailstorm", "maxnormal": "Max Strike", "maxpoison": "Max Ooze", "maxpsychic": "Max Mindstorm", "maxrock": "Max Rockfall", "maxsteel": "Max Steelspike", "maxwater": "Max Geyser", "maxstatus": "Max Guard", "maxprotect": "Max Guard", // Japanese names "fushigidane": "Bulbasaur", "fushigisou": "Ivysaur", "fushigibana": "Venusaur", "hitokage": "Charmander", "rizaado": "Charmeleon", "rizaadon": "Charizard", "zenigame": "Squirtle", "kameeru": "Wartortle", "kamekkusu": "Blastoise", "kyatapii": "Caterpie", "toranseru": "Metapod", "batafurii": "Butterfree", "biidoru": "Weedle", "kokuun": "Kakuna", "supiaa": "Beedrill", "poppo": "Pidgey", "pijon": "Pidgeotto", "pijotto": "Pidgeot", "koratta": "Rattata", "ratta": "Raticate", "onisuzume": "Spearow", "onidoriru": "Fearow", "aabo": "Ekans", "aabokku": "Arbok", "pikachuu": "Pikachu", "raichuu": "Raichu", "sando": "Sandshrew", "sandopan": "Sandslash", "nidoranmesu": "Nidoran-F", "nidoriina": "Nidorina", "nidokuin": "Nidoqueen", "nidoranosu": "Nidoran-M", "nidoriino": "Nidorino", "nidokingu": "Nidoking", "pippi": "Clefairy", "pikushii": "Clefable", "rokon": "Vulpix", "kyuukon": "Ninetales", "purin": "Jigglypuff", "pukurin": "Wigglytuff", "zubatto": "Zubat", "gorubatto": "Golbat", "nazonokusa": "Oddish", "kusaihana": "Gloom", "rafureshia": "Vileplume", "parasu": "Paras", "parasekuto": "Parasect", "konpan": "Venonat", "morufon": "Venomoth", "diguda": "Diglett", "dagutorio": "Dugtrio", "nyaasu": "Meowth", "perushian": "Persian", "kodakku": "Psyduck", "gorudakku": "Golduck", "mankii": "Mankey", "okorizaru": "Primeape", "gaadi": "Growlithe", "uindi": "Arcanine", "nyoromo": "Poliwag", "nyorozo": "Poliwhirl", "nyorobon": "Poliwrath", "keeshy": "Abra", "yungeraa": "Kadabra", "fuudin": "Alakazam", "wanrikii": "Machop", "goorikii": "Machoke", "kairikii": "Machamp", "madatsubomi": "Bellsprout", "utsudon": "Weepinbell", "utsubotto": "Victreebel", "menokurage": "Tentacool", "dokukurage": "Tentacruel", "ishitsubute": "Geodude", "goroon": "Graveler", "goroonya": "Golem", "poniita": "Ponyta", "gyaroppu": "Rapidash", "yadon": "Slowpoke", "yadoran": "Slowbro", "koiru": "Magnemite", "reakoiru": "Magneton", "kamonegi": "Farfetch'd", "doodoo": "Doduo", "doodorio": "Dodrio", "pauwau": "Seel", "jugon": "Dewgong", "betobetaa": "Grimer", "betobeton": "Muk", "sherudaa": "Shellder", "parushen": "Cloyster", "goosu": "Gastly", "goosuto": "Haunter", "gengaa": "Gengar", "iwaaku": "Onix", "suriipu": "Drowzee", "suriipaa": "Hypno", "kurabu": "Krabby", "kinguraa": "Kingler", "biriridama": "Voltorb", "marumain": "Electrode", "tamatama": "Exeggcute", "nasshii": "Exeggutor", "karakara": "Cubone", "garagara": "Marowak", "sawamuraa": "Hitmonlee", "ebiwaraa": "Hitmonchan", "beroringa": "Lickitung", "dogaasu": "Koffing", "matadogasu": "Weezing", "saihoon": "Rhyhorn", "saidon": "Rhydon", "rakkii": "Chansey", "monjara": "Tangela", "garuura": "Kangaskhan", "tattsuu": "Horsea", "shiidora": "Seadra", "tosakinto": "Goldeen", "azumaou": "Seaking", "hitodeman": "Staryu", "sutaamii": "Starmie", "bariyaado": "Mr. Mime", "sutoraiku": "Scyther", "ruujura": "Jynx", "erebuu": "Electabuzz", "buubaa": "Magmar", "kairosu": "Pinsir", "kentarosu": "Tauros", "koikingu": "Magikarp", "gyaradosu": "Gyarados", "rapurasu": "Lapras", "metamon": "Ditto", "iibui": "Eevee", "shawaazu": "Vaporeon", "sandaasu": "Jolteon", "buusutaa": "Flareon", "porigon": "Porygon", "omunaito": "Omanyte", "omusutaa": "Omastar", "kabutopusu": "Kabutops", "putera": "Aerodactyl", "kabigon": "Snorlax", "furiizaa": "Articuno", "sandaa": "Zapdos", "faiyaa": "Moltres", "miniryuu": "Dratini", "hakuryuu": "Dragonair", "kairyuu": "Dragonite", "myuutsuu": "Mewtwo", "myuu": "Mew", "chikoriita": "Chikorita", "beiriifu": "Bayleef", "meganiumu": "Meganium", "hinoarashi": "Cyndaquil", "magumarashi": "Quilava", "bakufuun": "Typhlosion", "waninoko": "Totodile", "arigeitsu": "Croconaw", "oodairu": "Feraligatr", "otachi": "Sentret", "ootachi": "Furret", "hoohoo": "Hoothoot", "yorunozuku": "Noctowl", "rediba": "Ledyba", "redian": "Ledian", "itomaru": "Spinarak", "ariadosu": "Ariados", "kurobatto": "Crobat", "chonchii": "Chinchou", "rantaan": "Lanturn", "pichuu": "Pichu", "py": "Cleffa", "pupurin": "Igglybuff", "togepii": "Togepi", "togechikku": "Togetic", "neitei": "Natu", "neiteio": "Xatu", "meriipu": "Mareep", "mokoko": "Flaaffy", "denryuu": "Ampharos", "kireihana": "Bellossom", "mariru": "Marill", "mariruri": "Azumarill", "usokkii": "Sudowoodo", "nyorotono": "Politoed", "hanekko": "Hoppip", "popokko": "Skiploom", "watakko": "Jumpluff", "eipamu": "Aipom", "himanattsu": "Sunkern", "kimawari": "Sunflora", "yanyanma": "Yanma", "upaa": "Wooper", "nuoo": "Quagsire", "eefi": "Espeon", "burakkii": "Umbreon", "yamikarasu": "Murkrow", "yadokingu": "Slowking", "muuma": "Misdreavus", "annoon": "Unown", "soonansu": "Wobbuffet", "kirinriki": "Girafarig", "kunugidama": "Pineco", "foretosu": "Forretress", "nokotchi": "Dunsparce", "guraigaa": "Gligar", "haganeeru": "Steelix", "buruu": "Snubbull", "guranburu": "Granbull", "hariisen": "Qwilfish", "hassamu": "Scizor", "tsubotsubo": "Shuckle", "herakurosu": "Heracross", "nyuura": "Sneasel", "himeguma": "Teddiursa", "ringuma": "Ursaring", "magumaggu": "Slugma", "magukarugo": "Magcargo", "urimuu": "Swinub", "inomuu": "Piloswine", "saniigo": "Corsola", "teppouo": "Remoraid", "okutan": "Octillery", "deribaado": "Delibird", "mantain": "Mantine", "eaamudo": "Skarmory", "derubiru": "Houndour", "herugaa": "Houndoom", "kingudora": "Kingdra", "gomazou": "Phanpy", "donfan": "Donphan", "porigon2": "Porygon2", "odoshishi": "Stantler", "dooburu": "Smeargle", "barukii": "Tyrogue", "kapoeraa": "Hitmontop", "muchuuru": "Smoochum", "erekiddo": "Elekid", "buby": "Magby", "mirutanku": "Miltank", "hapinasu": "Blissey", "suikun": "Suicune", "yoogirasu": "Larvitar", "sanagirasu": "Pupitar", "bangirasu": "Tyranitar", "rugia": "Lugia", "houou": "Ho-Oh", "sereby": "Celebi", "kimori": "Treecko", "juputoru": "Grovyle", "jukain": "Sceptile", "achamo": "Torchic", "wakashamo": "Combusken", "bashaamo": "Blaziken", "mizugorou": "Mudkip", "numakuroo": "Marshtomp", "raguraaji": "Swampert", "pochiena": "Poochyena", "guraena": "Mightyena", "jiguzaguma": "Zigzagoon", "massuguma": "Linoone", "kemusso": "Wurmple", "karasarisu": "Silcoon", "agehanto": "Beautifly", "mayurudo": "Cascoon", "dokukeiru": "Dustox", "hasuboo": "Lotad", "hasuburero": "Lombre", "runpappa": "Ludicolo", "taneboo": "Seedot", "konohana": "Nuzleaf", "daatengu": "Shiftry", "subame": "Taillow", "oosubame": "Swellow", "kyamome": "Wingull", "perippaa": "Pelipper", "rarutosu": "Ralts", "kiruria": "Kirlia", "saanaito": "Gardevoir", "ametama": "Surskit", "amemoosu": "Masquerain", "kinokoko": "Shroomish", "kinogassa": "Breloom", "namakero": "Slakoth", "yarukimono": "Vigoroth", "kekkingu": "Slaking", "tsuchinin": "Nincada", "tekkanin": "Ninjask", "nukenin": "Shedinja", "gonyonyo": "Whismur", "dogoomu": "Loudred", "bakuongu": "Exploud", "makunoshita": "Makuhita", "hariteyama": "Hariyama", "ruriri": "Azurill", "nozupasu": "Nosepass", "eneko": "Skitty", "enekororo": "Delcatty", "yamirami": "Sableye", "kuchiito": "Mawile", "kokodora": "Aron", "kodora": "Lairon", "bosugodora": "Aggron", "asanan": "Meditite", "chaaremu": "Medicham", "rakurai": "Electrike", "raiboruto": "Manectric", "purasuru": "Plusle", "mainan": "Minun", "barubiito": "Volbeat", "irumiize": "Illumise", "rozeria": "Roselia", "gokurin": "Gulpin", "marunoomu": "Swalot", "kibania": "Carvanha", "samehadaa": "Sharpedo", "hoeruko": "Wailmer", "hoeruoo": "Wailord", "donmeru": "Numel", "bakuuda": "Camerupt", "kootasu": "Torkoal", "banebuu": "Spoink", "buupiggu": "Grumpig", "patchiiru": "Spinda", "nakkuraa": "Trapinch", "biburaaba": "Vibrava", "furaigon": "Flygon", "sabonea": "Cacnea", "nokutasu": "Cacturne", "chirutto": "Swablu", "chirutarisu": "Altaria", "zanguusu": "Zangoose", "habuneeku": "Seviper", "runatoon": "Lunatone", "sorurokku": "Solrock", "dojotchi": "Barboach", "namazun": "Whiscash", "heigani": "Corphish", "shizarigaa": "Crawdaunt", "yajiron": "Baltoy", "nendooru": "Claydol", "ririira": "Lileep", "yureidoru": "Cradily", "anopusu": "Anorith", "aamarudo": "Armaldo", "hinbasu": "Feebas", "mirokarosu": "Milotic", "powarun": "Castform", "kakureon": "Kecleon", "kagebouzu": "Shuppet", "jupetta": "Banette", "yomawaru": "Duskull", "samayooru": "Dusclops", "toropiusu": "Tropius", "chiriin": "Chimecho", "abusoru": "Absol", "soonano": "Wynaut", "yukiwarashi": "Snorunt", "onigoori": "Glalie", "tamazarashi": "Spheal", "todoguraa": "Sealeo", "todozeruga": "Walrein", "paaruru": "Clamperl", "hanteeru": "Huntail", "sakurabisu": "Gorebyss", "jiiransu": "Relicanth", "rabukasu": "Luvdisc", "tatsubei": "Bagon", "komoruu": "Shelgon", "boomanda": "Salamence", "danbaru": "Beldum", "metangu": "Metang", "metagurosu": "Metagross", "rejirokku": "Regirock", "rejiaisu": "Regice", "rejisuchiru": "Registeel", "rateiasu": "Latias", "rateiosu": "Latios", "kaiooga": "Kyogre", "guraadon": "Groudon", "rekkuuza": "Rayquaza", "jiraachi": "Jirachi", "deokishisu": "Deoxys", "naetoru": "Turtwig", "hayashigame": "Grotle", "dodaitosu": "Torterra", "hikozaru": "Chimchar", "moukazaru": "Monferno", "goukazaru": "Infernape", "potchama": "Piplup", "pottaishi": "Prinplup", "enperuto": "Empoleon", "mukkuru": "Starly", "mukubaado": "Staravia", "mukuhooku": "Staraptor", "bippa": "Bidoof", "biidaru": "Bibarel", "korobooshi": "Kricketot", "korotokku": "Kricketune", "korinku": "Shinx", "rukushio": "Luxio", "rentoraa": "Luxray", "subomii": "Budew", "rozureido": "Roserade", "zugaidosu": "Cranidos", "ramuparudo": "Rampardos", "tatetopusu": "Shieldon", "toridepusu": "Bastiodon", "minomutchi": "Burmy", "minomadamu": "Wormadam", "gaameiru": "Mothim", "mitsuhanii": "Combee", "biikuin": "Vespiquen", "buizeru": "Buizel", "furoozeru": "Floatzel", "cherinbo": "Cherubi", "cherimu": "Cherrim", "karanakushi": "Shellos", "toritodon": "Gastrodon", "eteboosu": "Ambipom", "fuwante": "Drifloon", "fuwaraido": "Drifblim", "mimiroru": "Buneary", "mimiroppu": "Lopunny", "muumaaji": "Mismagius", "donkarasu": "Honchkrow", "nyarumaa": "Glameow", "bunyatto": "Purugly", "riishan": "Chingling", "sukanpuu": "Stunky", "sukatanku": "Skuntank", "doomiraa": "Bronzor", "dootakun": "Bronzong", "usohachi": "Bonsly", "manene": "Mime Jr.", "pinpuku": "Happiny", "perappu": "Chatot", "mikaruge": "Spiritomb", "fukamaru": "Gible", "gabaito": "Gabite", "gaburiasu": "Garchomp", "gonbe": "Munchlax", "rioru": "Riolu", "rukario": "Lucario", "hipopotasu": "Hippopotas", "kabarudon": "Hippowdon", "sukorupi": "Skorupi", "dorapion": "Drapion", "guregguru": "Croagunk", "dokuroggu": "Toxicroak", "masukippa": "Carnivine", "keikouo": "Finneon", "neoranto": "Lumineon", "tamanta": "Mantyke", "yukikaburi": "Snover", "yukinooo": "Abomasnow", "manyuura": "Weavile", "jibakoiru": "Magnezone", "beroberuto": "Lickilicky", "dosaidon": "Rhyperior", "mojanbo": "Tangrowth", "erekiburu": "Electivire", "buubaan": "Magmortar", "togekissu": "Togekiss", "megayanma": "Yanmega", "riifia": "Leafeon", "gureishia": "Glaceon", "guraion": "Gliscor", "manmuu": "Mamoswine", "porigonz": "Porygon-Z", "erureido": "Gallade", "dainoozu": "Probopass", "yonowaaru": "Dusknoir", "yukimenoko": "Froslass", "rotomu": "Rotom", "yukushii": "Uxie", "emuritto": "Mesprit", "agunomu": "Azelf", "diaruga": "Dialga", "parukia": "Palkia", "hiidoran": "Heatran", "rejigigasu": "Regigigas", "girateina": "Giratina", "kureseria": "Cresselia", "fione": "Phione", "manafi": "Manaphy", "daakurai": "Darkrai", "sheimi": "Shaymin", "aruseusu": "Arceus", "bikuteini": "Victini", "tsutaaja": "Snivy", "janobii": "Servine", "jarooda": "Serperior", "pokabu": "Tepig", "chaobuu": "Pignite", "enbuoo": "Emboar", "mijumaru": "Oshawott", "futachimaru": "Dewott", "daikenki": "Samurott", "minezumi": "Patrat", "miruhoggu": "Watchog", "yooterii": "Lillipup", "haaderia": "Herdier", "muurando": "Stoutland", "choroneko": "Purrloin", "reparudasu": "Liepard", "yanappu": "Pansage", "yanakkii": "Simisage", "baoppu": "Pansear", "baokkii": "Simisear", "hiyappu": "Panpour", "hiyakkii": "Simipour", "mushaana": "Musharna", "mamepato": "Pidove", "hatooboo": "Tranquill", "kenhorou": "Unfezant", "shimama": "Blitzle", "zeburaika": "Zebstrika", "dangoro": "Roggenrola", "gantoru": "Boldore", "gigaiasu": "Gigalith", "koromori": "Woobat", "kokoromori": "Swoobat", "moguryuu": "Drilbur", "doryuuzu": "Excadrill", "tabunne": "Audino", "dokkoraa": "Timburr", "dotekkotsu": "Gurdurr", "roobushin": "Conkeldurr", "otamaro": "Tympole", "gamagaru": "Palpitoad", "gamageroge": "Seismitoad", "nageki": "Throh", "dageki": "Sawk", "kurumiru": "Sewaddle", "kurumayu": "Swadloon", "hahakomori": "Leavanny", "fushide": "Venipede", "hoiiga": "Whirlipede", "pendoraa": "Scolipede", "monmen": "Cottonee", "erufuun": "Whimsicott", "churine": "Petilil", "doredia": "Lilligant", "basurao": "Basculin", "meguroko": "Sandile", "warubiru": "Krokorok", "warubiaru": "Krookodile", "darumakka": "Darumaka", "hihidaruma": "Darmanitan", "marakatchi": "Maractus", "ishizumai": "Dwebble", "iwaparesu": "Crustle", "zuruggu": "Scraggy", "zuruzukin": "Scrafty", "shinboraa": "Sigilyph", "desumasu": "Yamask", "desukaan": "Cofagrigus", "purotooga": "Tirtouga", "abagoora": "Carracosta", "aaken": "Archen", "aakeosu": "Archeops", "yabukuron": "Trubbish", "dasutodasu": "Garbodor", "zoroa": "Zorua", "zoroaaku": "Zoroark", "chiraamy": "Minccino", "chirachiino": "Cinccino", "gochimu": "Gothita", "gochimiru": "Gothorita", "gochiruzeru": "Gothitelle", "yuniran": "Solosis", "daburan": "Duosion", "rankurusu": "Reuniclus", "koaruhii": "Ducklett", "suwanna": "Swanna", "baniputchi": "Vanillite", "baniritchi": "Vanillish", "baibanira": "Vanilluxe", "shikijika": "Deerling", "mebukijika": "Sawsbuck", "emonga": "Emolga", "kaburumo": "Karrablast", "shubarugo": "Escavalier", "tamagetake": "Foongus", "morobareru": "Amoonguss", "pururiru": "Frillish", "burungeru": "Jellicent", "mamanbou": "Alomomola", "bachuru": "Joltik", "denchura": "Galvantula", "tesshiido": "Ferroseed", "nattorei": "Ferrothorn", "giaru": "Klink", "gigiaru": "Klang", "gigigiaru": "Klinklang", "shibishirasu": "Tynamo", "shibibiiru": "Eelektrik", "shibirudon": "Eelektross", "riguree": "Elgyem", "oobemu": "Beheeyem", "hitomoshi": "Litwick", "ranpuraa": "Lampent", "shandera": "Chandelure", "kibago": "Axew", "onondo": "Fraxure", "ononokusu": "Haxorus", "kumashun": "Cubchoo", "tsunbeaa": "Beartic", "furiijio": "Cryogonal", "chobomaki": "Shelmet", "agirudaa": "Accelgor", "maggyo": "Stunfisk", "kojofuu": "Mienfoo", "kojondo": "Mienshao", "kurimugan": "Druddigon", "gobitto": "Golett", "goruugu": "Golurk", "komatana": "Pawniard", "kirikizan": "Bisharp", "baffuron": "Bouffalant", "washibon": "Rufflet", "uooguru": "Braviary", "baruchai": "Vullaby", "barujiina": "Mandibuzz", "kuitaran": "Heatmor", "aianto": "Durant", "monozu": "Deino", "jiheddo": "Zweilous", "sazandora": "Hydreigon", "meraruba": "Larvesta", "urugamosu": "Volcarona", "kobaruon": "Cobalion", "terakion": "Terrakion", "birijion": "Virizion", "torunerosu": "Tornadus", "borutorosu": "Thundurus", "reshiramu": "Reshiram", "zekuromu": "Zekrom", "randorosu": "Landorus", "kyuremu": "Kyurem", "kerudio": "Keldeo", "meroetta": "Meloetta", "genosekuto": "Genesect", "harimaron": "Chespin", "hariboogu": "Quilladin", "burigaron": "Chesnaught", "fokko": "Fennekin", "teerunaa": "Braixen", "mafokushii": "Delphox", "keromatsu": "Froakie", "gekogashira": "Frogadier", "gekkouga": "Greninja", "gekkougasatoshi": "Greninja-Ash", "satoshigekkouga": "Greninja-Ash", "horubii": "Bunnelby", "horuudo": "Diggersby", "yayakoma": "Fletchling", "hinoyakoma": "Fletchinder", "faiaroo": "Talonflame", "kofukimushi": "Scatterbug", "kofuurai": "Spewpa", "bibiyon": "Vivillon", "shishiko": "Litleo", "kaenjishi": "Pyroar", "furabebe": "Flabébé", "furaette": "Floette", "furaajesu": "Florges", "meeekuru": "Skiddo", "googooto": "Gogoat", "yanchamu": "Pancham", "goronda": "Pangoro", "torimian": "Furfrou", "nyasupaa": "Espurr", "nyaonikusu": "Meowstic", "hitotsuki": "Honedge", "nidangiru": "Doublade", "girugarudo": "Aegislash", "shushupu": "Spritzee", "furefuwan": "Aromatisse", "peroppafu": "Swirlix", "peroriimu": "Slurpuff", "maaiika": "Inkay", "karamanero": "Malamar", "kametete": "Binacle", "gamenodesu": "Barbaracle", "kuzumoo": "Skrelp", "doramidoro": "Dragalge", "udeppou": "Clauncher", "burosutaa": "Clawitzer", "erikiteru": "Helioptile", "erezaado": "Heliolisk", "chigorasu": "Tyrunt", "gachigorasu": "Tyrantrum", "amarusu": "Amaura", "amaruruga": "Aurorus", "ninfia": "Sylveon", "ruchaburu": "Hawlucha", "mereshii": "Carbink", "numera": "Goomy", "numeiru": "Sliggoo", "numerugon": "Goodra", "kureffi": "Klefki", "bokuree": "Phantump", "oorotto": "Trevenant", "baketcha": "Pumpkaboo", "panpujin": "Gourgeist", "kachikooru": "Bergmite", "kurebeesu": "Avalugg", "onbatto": "Noibat", "onbaan": "Noivern", "zeruneasu": "Xerneas", "iberutaru": "Yveltal", "jigarude": "Zygarde", "dianshii": "Diancie", "fuupa": "Hoopa", "borukenion": "Volcanion", "mokuroo": "Rowlet", "fukusuroo": "Dartrix", "junaipaa": "Decidueye", "nyabii": "Litten", "nyahiito": "Torracat", "gaogaen": "Incineroar", "ashimari": "Popplio", "oshamari": "Brionne", "ashireenu": "Primarina", "tsutsukera": "Pikipek", "kerarappa": "Trumbeak", "dodekabashi": "Toucannon", "yanguusu": "Yungoos", "dekaguusu": "Gumshoos", "agojimushi": "Grubbin", "denjimushi": "Charjabug", "kuwaganon": "Vikavolt", "makenkani": "Crabrawler", "kekenkani": "Crabominable", "odoridori": "Oricorio", "aburii": "Cutiefly", "aburibon": "Ribombee", "iwanko": "Rockruff", "rugarugan": "Lycanroc", "yowashi": "Wishiwashi", "hidoide": "Mareanie", "dohidoide": "Toxapex", "dorobanko": "Mudbray", "banbadoro": "Mudsdale", "shizukumo": "Dewpider", "onishizukumo": "Araquanid", "karikiri": "Fomantis", "rarantesu": "Lurantis", "nemashu": "Morelull", "masheedo": "Shiinotic", "yatoumori": "Salandit", "ennyuuto": "Salazzle", "nuikoguma": "Stufful", "kiteruguma": "Bewear", "amakaji": "Bounsweet", "amamaiko": "Steenee", "amaajo": "Tsareena", "kyuwawaa": "Comfey", "yareyuutan": "Oranguru", "nagetsukesaru": "Passimian", "kosokumushi": "Wimpod", "gusokumusha": "Golisopod", "sunabaa": "Sandygast", "shirodesuna": "Palossand", "namakobushi": "Pyukumuku", "taipunuru": "Type: Null", "shiruvuadi": "Silvally", "meteno": "Minior", "nekkoara": "Komala", "bakugamesu": "Turtonator", "mimikkyu": "Mimikyu", "hagigishiri": "Bruxish", "jijiiron": "Drampa", "dadarin": "Dhelmise", "jarako": "Jangmo-o", "jarango": "Hakamo-o", "jararanga": "Kommo-o", "kapukokeko": "Tapu Koko", "kaputetefu": "Tapu Lele", "kapubururu": "Tapu Bulu", "kapurehire": "Tapu Fini", "kosumoggu": "Cosmog", "kosumoumu": "Cosmoem", "sorugareo": "Solgaleo", "runaaara": "Lunala", "utsuroido": "Nihilego", "masshibuun": "Buzzwole", "fierooche": "Pheromosa", "denjumoku": "Xurkitree", "tekkaguya": "Celesteela", "kamitsurugi": "Kartana", "akujikingu": "Guzzlord", "nekurozuma": "Necrozma", "magiana": "Magearna", "maashadoo": "Marshadow", "bebenomu": "Poipole", "aagoyon": "Naganadel", "tsundetsunde": "Stakataka", "zugadoon": "Blacephalon", "merutan": "Meltan", "merumetaru": "Melmetal", }; exports.BattleAliases = BattleAliases;
QuiteQuiet/Pokemon-Showdown
data/aliases.js
JavaScript
mit
43,883
import { moduleForComponent, test } from 'ember-qunit'; import wait from 'ember-test-helpers/wait'; import hbs from 'htmlbars-inline-precompile'; import startMirage from '../../helpers/setup-mirage'; moduleForComponent('data-table', 'Integration | Component | data table', { integration: true, setup: function() { startMirage(this.container); } }); test('it renders', function(assert) { assert.expect(1); this.set('columns', [{label: 'Column'}]); this.render(hbs`{{data-table 'user' columns=columns}}`); return wait().then(() => { assert.ok(this.$('table').length); }); });
quantosobra/ember-data-table-light
tests/integration/components/data-table-test.js
JavaScript
mit
602