repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Mrsananabos/ashveytser
chapter_009/src/main/java/ru/job4j/toDoList/model/dao/HiberStorage.java
2289
package ru.job4j.toDoList.model.dao; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import ru.job4j.toDoList.model.entity.Item; import java.sql.Timestamp; import java.util.Date; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; public class HiberStorage implements Storage { private static final Logger LOGGER = LogManager.getLogger(HiberStorage.class); private static AtomicInteger NEXT_ID = new AtomicInteger(-1); private static final HiberStorage INSTANCE = new HiberStorage(); private final SessionFactory factory; private HiberStorage() { factory = new Configuration().configure().buildSessionFactory(); } public static HiberStorage getInstance() { return INSTANCE; } private <T> T tx(final Function<Session, T> command) { final Session session = factory.openSession(); final Transaction tx = session.beginTransaction(); try { return command.apply(session); } catch (final Exception e) { session.getTransaction().rollback(); throw e; } finally { tx.commit(); session.close(); } } @Override public Item add(Item item) { item.setId(NEXT_ID.getAndIncrement()); item.setCreated(new Timestamp(new Date().getTime())); return tx(session -> { session.save(item); return item; }); } @Override public Item update(Item item) { return tx(session -> { session.update(item); return item; }); } @Override public void delete(Item item) { tx(session -> { session.delete(item); return null; }); } @Override public List findAll() { return tx(session -> session.createQuery("FROM Item i ORDER BY i.id").list()); } @Override public void doneItem(int id) { tx(session -> { Item item = session.get(Item.class, id); item.setDone(true); return null; }); } }
apache-2.0
autermann/smle
src/app/model/swe/SweCategory.ts
604
import { AbstractSimpleComponent } from './AbstractSimpleComponent'; import { AllowedTokens } from './AllowedTokens'; /** * Scalar component used to represent a categorical value as a simple token * identifying a term in a code space */ export class SweCategory extends AbstractSimpleComponent { /** * Value is optional, to enable structure to act as a schema for values * provided using other encodings */ value: string; /** * Name of the dictionary where the possible values for this component are * listed and defined */ codeSpace: string; constraint: AllowedTokens; }
apache-2.0
cilium-team/cilium
daemon/cmd/status.go
25264
// Copyright 2016-2020 Authors of Cilium // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cmd import ( "context" "fmt" "strings" "time" "github.com/cilium/cilium/api/v1/models" . "github.com/cilium/cilium/api/v1/server/restapi/daemon" "github.com/cilium/cilium/pkg/backoff" "github.com/cilium/cilium/pkg/controller" "github.com/cilium/cilium/pkg/datapath" "github.com/cilium/cilium/pkg/k8s" k8smetrics "github.com/cilium/cilium/pkg/k8s/metrics" "github.com/cilium/cilium/pkg/kvstore" "github.com/cilium/cilium/pkg/lock" "github.com/cilium/cilium/pkg/logging/logfields" "github.com/cilium/cilium/pkg/maps/eppolicymap" "github.com/cilium/cilium/pkg/maps/eventsmap" ipcachemap "github.com/cilium/cilium/pkg/maps/ipcache" ipmasqmap "github.com/cilium/cilium/pkg/maps/ipmasq" "github.com/cilium/cilium/pkg/maps/lbmap" "github.com/cilium/cilium/pkg/maps/lxcmap" "github.com/cilium/cilium/pkg/maps/metricsmap" "github.com/cilium/cilium/pkg/maps/signalmap" "github.com/cilium/cilium/pkg/maps/sockmap" tunnelmap "github.com/cilium/cilium/pkg/maps/tunnel" nodeTypes "github.com/cilium/cilium/pkg/node/types" "github.com/cilium/cilium/pkg/option" "github.com/cilium/cilium/pkg/rand" "github.com/cilium/cilium/pkg/status" "github.com/sirupsen/logrus" "github.com/go-openapi/runtime/middleware" "github.com/go-openapi/strfmt" versionapi "k8s.io/apimachinery/pkg/version" ) const ( // k8sVersionCheckInterval is the interval in which the Kubernetes // version is verified even if connectivity is given k8sVersionCheckInterval = 15 * time.Minute // k8sMinimumEventHearbeat is the time interval in which any received // event will be considered proof that the apiserver connectivity is // healthty k8sMinimumEventHearbeat = time.Minute ) var randGen = rand.NewSafeRand(time.Now().UnixNano()) type k8sVersion struct { version string lastVersionCheck time.Time lock lock.Mutex } func (k *k8sVersion) cachedVersion() (string, bool) { k.lock.Lock() defer k.lock.Unlock() if time.Since(k8smetrics.LastInteraction.Time()) > k8sMinimumEventHearbeat { return "", false } if k.version == "" || time.Since(k.lastVersionCheck) > k8sVersionCheckInterval { return "", false } return k.version, true } func (k *k8sVersion) update(version *versionapi.Info) string { k.lock.Lock() defer k.lock.Unlock() k.version = fmt.Sprintf("%s.%s (%s) [%s]", version.Major, version.Minor, version.GitVersion, version.Platform) k.lastVersionCheck = time.Now() return k.version } var k8sVersionCache k8sVersion func (d *Daemon) getK8sStatus() *models.K8sStatus { if !k8s.IsEnabled() { return &models.K8sStatus{State: models.StatusStateDisabled} } version, valid := k8sVersionCache.cachedVersion() if !valid { k8sVersion, err := k8s.Client().Discovery().ServerVersion() if err != nil { return &models.K8sStatus{State: models.StatusStateFailure, Msg: err.Error()} } version = k8sVersionCache.update(k8sVersion) } k8sStatus := &models.K8sStatus{ State: models.StatusStateOk, Msg: version, K8sAPIVersions: d.k8sWatcher.GetAPIGroups(), } return k8sStatus } func (d *Daemon) getMasqueradingStatus() *models.Masquerading { s := &models.Masquerading{ Enabled: option.Config.Masquerade, } if !option.Config.Masquerade { return s } if option.Config.EnableIPv4 { s.SnatExclusionCidr = datapath.RemoteSNATDstAddrExclusionCIDR().String() } if option.Config.EnableBPFMasquerade { s.Mode = models.MasqueradingModeBPF s.IPMasqAgent = option.Config.EnableIPMasqAgent return s } s.Mode = models.MasqueradingModeIptables return s } func (d *Daemon) getBandwidthManagerStatus() *models.BandwidthManager { s := &models.BandwidthManager{ Enabled: option.Config.EnableBandwidthManager, } if !option.Config.EnableBandwidthManager { return s } devices := make([]string, len(option.Config.Devices)) for i, iface := range option.Config.Devices { devices[i] = iface } s.Devices = devices return s } func (d *Daemon) getKubeProxyReplacementStatus() *models.KubeProxyReplacement { if !k8s.IsEnabled() { return &models.KubeProxyReplacement{Mode: models.KubeProxyReplacementModeDisabled} } var mode string switch option.Config.KubeProxyReplacement { case option.KubeProxyReplacementStrict: mode = models.KubeProxyReplacementModeStrict case option.KubeProxyReplacementPartial: mode = models.KubeProxyReplacementModePartial case option.KubeProxyReplacementProbe: mode = models.KubeProxyReplacementModeProbe case option.KubeProxyReplacementDisabled: mode = models.KubeProxyReplacementModeDisabled } devices := make([]string, len(option.Config.Devices)) for i, iface := range option.Config.Devices { devices[i] = iface } features := &models.KubeProxyReplacementFeatures{ NodePort: &models.KubeProxyReplacementFeaturesNodePort{}, HostPort: &models.KubeProxyReplacementFeaturesHostPort{}, ExternalIPs: &models.KubeProxyReplacementFeaturesExternalIPs{}, HostReachableServices: &models.KubeProxyReplacementFeaturesHostReachableServices{}, SessionAffinity: &models.KubeProxyReplacementFeaturesSessionAffinity{}, } if option.Config.EnableNodePort { features.NodePort.Enabled = true features.NodePort.Mode = strings.ToUpper(option.Config.NodePortMode) features.NodePort.Algorithm = models.KubeProxyReplacementFeaturesNodePortAlgorithmRandom if option.Config.NodePortAlg == option.NodePortAlgMaglev { features.NodePort.Algorithm = models.KubeProxyReplacementFeaturesNodePortAlgorithmMaglev features.NodePort.LutSize = int64(option.Config.MaglevTableSize) } if option.Config.NodePortAcceleration == option.NodePortAccelerationGeneric { features.NodePort.Acceleration = models.KubeProxyReplacementFeaturesNodePortAccelerationGeneric } else { features.NodePort.Acceleration = strings.ToTitle(option.Config.NodePortAcceleration) } features.NodePort.PortMin = int64(option.Config.NodePortMin) features.NodePort.PortMax = int64(option.Config.NodePortMax) } if option.Config.EnableHostPort { features.HostPort.Enabled = true } if option.Config.EnableExternalIPs { features.ExternalIPs.Enabled = true } if option.Config.EnableHostServicesTCP { features.HostReachableServices.Enabled = true protocols := []string{} if option.Config.EnableHostServicesTCP { protocols = append(protocols, "TCP") } if option.Config.EnableHostServicesUDP { protocols = append(protocols, "UDP") } features.HostReachableServices.Protocols = protocols } if option.Config.EnableSessionAffinity { features.SessionAffinity.Enabled = true } return &models.KubeProxyReplacement{ Mode: mode, Devices: devices, DirectRoutingDevice: option.Config.DirectRoutingDevice, Features: features, } } func (d *Daemon) getBPFMapStatus() *models.BPFMapStatus { return &models.BPFMapStatus{ DynamicSizeRatio: option.Config.BPFMapsDynamicSizeRatio, Maps: []*models.BPFMapProperties{ { Name: "Non-TCP connection tracking", Size: int64(option.Config.CTMapEntriesGlobalAny), }, { Name: "TCP connection tracking", Size: int64(option.Config.CTMapEntriesGlobalTCP), }, { Name: "Endpoint policy", Size: int64(lxcmap.MaxEntries), }, { Name: "Events", Size: int64(eventsmap.MaxEntries), }, { Name: "IP cache", Size: int64(ipcachemap.MaxEntries), }, { Name: "IP masquerading agent", Size: int64(ipmasqmap.MaxEntries), }, { Name: "IPv4 fragmentation", Size: int64(option.Config.FragmentsMapEntries), }, { Name: "IPv4 service", // cilium_lb4_services_v2 Size: int64(lbmap.MaxEntries), }, { Name: "IPv6 service", // cilium_lb6_services_v2 Size: int64(lbmap.MaxEntries), }, { Name: "IPv4 service backend", // cilium_lb4_backends Size: int64(lbmap.MaxEntries), }, { Name: "IPv6 service backend", // cilium_lb6_backends Size: int64(lbmap.MaxEntries), }, { Name: "IPv4 service reverse NAT", // cilium_lb4_reverse_nat Size: int64(lbmap.MaxEntries), }, { Name: "IPv6 service reverse NAT", // cilium_lb6_reverse_nat Size: int64(lbmap.MaxEntries), }, { Name: "Metrics", Size: int64(metricsmap.MaxEntries), }, { Name: "NAT", Size: int64(option.Config.NATMapEntriesGlobal), }, { Name: "Neighbor table", Size: int64(option.Config.NeighMapEntriesGlobal), }, { Name: "Global policy", Size: int64(option.Config.PolicyMapEntries), }, { Name: "Per endpoint policy", Size: int64(eppolicymap.MaxEntries), }, { Name: "Session affinity", Size: int64(lbmap.MaxEntries), }, { Name: "Signal", Size: int64(signalmap.MaxEntries), }, { Name: "Sockmap", Size: int64(sockmap.MaxEntries), }, { Name: "Sock reverse NAT", Size: int64(option.Config.SockRevNatEntries), }, { Name: "Tunnel", Size: int64(tunnelmap.MaxEntries), }, }, } } type getHealthz struct { daemon *Daemon } func NewGetHealthzHandler(d *Daemon) GetHealthzHandler { return &getHealthz{daemon: d} } func (d *Daemon) getNodeStatus() *models.ClusterStatus { clusterStatus := models.ClusterStatus{ Self: d.nodeDiscovery.LocalNode.Fullname(), } for _, node := range d.nodeDiscovery.Manager.GetNodes() { clusterStatus.Nodes = append(clusterStatus.Nodes, node.GetModel()) } return &clusterStatus } func (h *getHealthz) Handle(params GetHealthzParams) middleware.Responder { brief := params.Brief != nil && *params.Brief sr := h.daemon.getStatus(brief) return NewGetHealthzOK().WithPayload(&sr) } type getNodes struct { d *Daemon // mutex to protect the clients map against concurrent access lock.RWMutex // clients maps a client ID to a clusterNodesClient clients map[int64]*clusterNodesClient } func NewGetClusterNodesHandler(d *Daemon) GetClusterNodesHandler { return &getNodes{ d: d, clients: map[int64]*clusterNodesClient{}, } } // clientGCTimeout is the time for which the clients are kept. After timeout // is reached, clients will be cleaned up. const clientGCTimeout = 15 * time.Minute type clusterNodesClient struct { // mutex to protect the client against concurrent access lock.RWMutex lastSync time.Time *models.ClusterNodeStatus } func (c *clusterNodesClient) NodeAdd(newNode nodeTypes.Node) error { c.Lock() c.NodesAdded = append(c.NodesAdded, newNode.GetModel()) c.Unlock() return nil } func (c *clusterNodesClient) NodeUpdate(oldNode, newNode nodeTypes.Node) error { c.Lock() defer c.Unlock() // If the node is on the added list, just update it for i, added := range c.NodesAdded { if added.Name == newNode.Fullname() { c.NodesAdded[i] = newNode.GetModel() return nil } } // otherwise, add the new node and remove the old one c.NodesAdded = append(c.NodesAdded, newNode.GetModel()) c.NodesRemoved = append(c.NodesRemoved, oldNode.GetModel()) return nil } func (c *clusterNodesClient) NodeDelete(node nodeTypes.Node) error { c.Lock() // If the node was added/updated and removed before the clusterNodesClient // was aware of it then we can safely remove it from the list of added // nodes and not set it in the list of removed nodes. found := -1 for i, added := range c.NodesAdded { if added.Name == node.Fullname() { found = i } } if found != -1 { c.NodesAdded = append(c.NodesAdded[:found], c.NodesAdded[found+1:]...) } else { c.NodesRemoved = append(c.NodesRemoved, node.GetModel()) } c.Unlock() return nil } func (c *clusterNodesClient) NodeValidateImplementation(node nodeTypes.Node) error { // no-op return nil } func (c *clusterNodesClient) NodeConfigurationChanged(config datapath.LocalNodeConfiguration) error { // no-op return nil } func (h *getNodes) cleanupClients() { past := time.Now().Add(-clientGCTimeout) for k, v := range h.clients { if v.lastSync.Before(past) { h.d.nodeDiscovery.Manager.Unsubscribe(v) delete(h.clients, k) } } } func (h *getNodes) Handle(params GetClusterNodesParams) middleware.Responder { var cns *models.ClusterNodeStatus // If ClientID is not set then we send all nodes, otherwise we will store // the client ID in the list of clients and we subscribe this new client // to the list of clients. if params.ClientID == nil { ns := h.d.getNodeStatus() cns = &models.ClusterNodeStatus{ Self: ns.Self, NodesAdded: ns.Nodes, } return NewGetClusterNodesOK().WithPayload(cns) } h.Lock() defer h.Unlock() var clientID int64 c, exists := h.clients[*params.ClientID] if exists { clientID = *params.ClientID } else { clientID = randGen.Int63() // make sure we haven't allocated an existing client ID nor the // randomizer has allocated ID 0, if we have then we will return // clientID 0. _, exists := h.clients[clientID] if exists || clientID == 0 { ns := h.d.getNodeStatus() cns = &models.ClusterNodeStatus{ ClientID: 0, Self: ns.Self, NodesAdded: ns.Nodes, } return NewGetClusterNodesOK().WithPayload(cns) } c = &clusterNodesClient{ lastSync: time.Now(), ClusterNodeStatus: &models.ClusterNodeStatus{ ClientID: clientID, Self: h.d.nodeDiscovery.LocalNode.Fullname(), }, } h.d.nodeDiscovery.Manager.Subscribe(c) // Clean up other clients before adding a new one h.cleanupClients() h.clients[clientID] = c } c.Lock() // Copy the ClusterNodeStatus to the response cns = c.ClusterNodeStatus // Store a new ClusterNodeStatus to reset the list of nodes // added / removed. c.ClusterNodeStatus = &models.ClusterNodeStatus{ ClientID: clientID, Self: h.d.nodeDiscovery.LocalNode.Fullname(), } c.lastSync = time.Now() c.Unlock() return NewGetClusterNodesOK().WithPayload(cns) } // getStatus returns the daemon status. If brief is provided a minimal version // of the StatusResponse is provided. func (d *Daemon) getStatus(brief bool) models.StatusResponse { staleProbes := d.statusCollector.GetStaleProbes() stale := make(map[string]strfmt.DateTime, len(staleProbes)) for probe, startTime := range staleProbes { stale[probe] = strfmt.DateTime(startTime) } d.statusCollectMutex.RLock() defer d.statusCollectMutex.RUnlock() var sr models.StatusResponse if brief { csCopy := new(models.ClusterStatus) if d.statusResponse.Cluster != nil && d.statusResponse.Cluster.CiliumHealth != nil { in, out := &d.statusResponse.Cluster.CiliumHealth, &csCopy.CiliumHealth *out = new(models.Status) **out = **in } var minimalControllers models.ControllerStatuses if d.statusResponse.Controllers != nil { for _, c := range d.statusResponse.Controllers { if c.Status == nil { continue } // With brief, the client should only care if a single controller // is failing and its status so we don't need to continuing // checking for failure messages for the remaining controllers. if c.Status.LastFailureMsg != "" { minimalControllers = append(minimalControllers, c.DeepCopy()) break } } } sr = models.StatusResponse{ Cluster: csCopy, Controllers: minimalControllers, } } else { // d.statusResponse contains references, so we do a deep copy to be able to // safely use sr after the method has returned sr = *d.statusResponse.DeepCopy() } sr.Stale = stale switch { case len(sr.Stale) > 0: sr.Cilium = &models.Status{ State: models.StatusStateWarning, Msg: "Stale status data", } case d.statusResponse.Kvstore != nil && d.statusResponse.Kvstore.State != models.StatusStateOk: sr.Cilium = &models.Status{ State: d.statusResponse.Kvstore.State, Msg: "Kvstore service is not ready", } case d.statusResponse.ContainerRuntime != nil && d.statusResponse.ContainerRuntime.State != models.StatusStateOk: msg := "Container runtime is not ready" if d.statusResponse.ContainerRuntime.State == models.StatusStateDisabled { msg = "Container runtime is disabled" } sr.Cilium = &models.Status{ State: d.statusResponse.ContainerRuntime.State, Msg: msg, } case k8s.IsEnabled() && d.statusResponse.Kubernetes != nil && d.statusResponse.Kubernetes.State != models.StatusStateOk: sr.Cilium = &models.Status{ State: d.statusResponse.Kubernetes.State, Msg: "Kubernetes service is not ready", } default: sr.Cilium = &models.Status{State: models.StatusStateOk, Msg: "OK"} } return sr } func (d *Daemon) startStatusCollector() { probes := []status.Probe{ { Name: "check-locks", Probe: func(ctx context.Context) (interface{}, error) { // Try to acquire a couple of global locks to have the status API fail // in case of a deadlock on these locks option.Config.ConfigPatchMutex.Lock() option.Config.ConfigPatchMutex.Unlock() return nil, nil }, OnStatusUpdate: func(status status.Status) { d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() // FIXME we have no field for the lock status }, }, { Name: "kvstore", Probe: func(ctx context.Context) (interface{}, error) { if option.Config.KVStore == "" { return models.StatusStateDisabled, nil } else { return kvstore.Client().Status() } }, OnStatusUpdate: func(status status.Status) { var msg string state := models.StatusStateOk info, ok := status.Data.(string) switch { case ok && status.Err != nil: state = models.StatusStateFailure msg = fmt.Sprintf("Err: %s - %s", status.Err, info) case status.Err != nil: state = models.StatusStateFailure msg = fmt.Sprintf("Err: %s", status.Err) case ok: msg = fmt.Sprintf("%s", info) } d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() d.statusResponse.Kvstore = &models.Status{ State: state, Msg: msg, } }, }, { Name: "kubernetes", Interval: func(failures int) time.Duration { if failures > 0 { // While failing, we want an initial // quick retry with exponential backoff // to avoid continuous load on the // apiserver return backoff.CalculateDuration(5*time.Second, 2*time.Minute, 2.0, false, failures) } // The base interval is dependant on the // cluster size. One status interval does not // automatically translate to an apiserver // interaction as any regular apiserver // interaction is also used as an indication of // successful connectivity so we can continue // to be fairly aggressive. // // 1 | 7s // 2 | 12s // 4 | 15s // 64 | 42s // 512 | 1m02s // 2048 | 1m15s // 8192 | 1m30s // 16384 | 1m32s return d.nodeDiscovery.Manager.ClusterSizeDependantInterval(10 * time.Second) }, Probe: func(ctx context.Context) (interface{}, error) { return d.getK8sStatus(), nil }, OnStatusUpdate: func(status status.Status) { d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() if status.Err != nil { d.statusResponse.Kubernetes = &models.K8sStatus{ State: models.StatusStateFailure, Msg: status.Err.Error(), } return } if s, ok := status.Data.(*models.K8sStatus); ok { d.statusResponse.Kubernetes = s } }, }, { Name: "ipam", Probe: func(ctx context.Context) (interface{}, error) { return d.DumpIPAM(), nil }, OnStatusUpdate: func(status status.Status) { d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() // IPAMStatus has no way to show errors if status.Err == nil { if s, ok := status.Data.(*models.IPAMStatus); ok { d.statusResponse.Ipam = s } } }, }, { Name: "node-monitor", Probe: func(ctx context.Context) (interface{}, error) { return d.monitorAgent.State(), nil }, OnStatusUpdate: func(status status.Status) { d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() // NodeMonitor has no way to show errors if status.Err == nil { if s, ok := status.Data.(*models.MonitorStatus); ok { d.statusResponse.NodeMonitor = s } } }, }, { Name: "cluster", Probe: func(ctx context.Context) (interface{}, error) { clusterStatus := &models.ClusterStatus{ Self: d.nodeDiscovery.LocalNode.Fullname(), } return clusterStatus, nil }, OnStatusUpdate: func(status status.Status) { d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() // ClusterStatus has no way to report errors if status.Err == nil { if s, ok := status.Data.(*models.ClusterStatus); ok { if d.statusResponse.Cluster != nil { // NB: CiliumHealth is set concurrently by the // "cilium-health" probe, so do not override it s.CiliumHealth = d.statusResponse.Cluster.CiliumHealth } d.statusResponse.Cluster = s } } }, }, { Name: "cilium-health", Probe: func(ctx context.Context) (interface{}, error) { if d.ciliumHealth == nil { return nil, nil } return d.ciliumHealth.GetStatus(), nil }, OnStatusUpdate: func(status status.Status) { if d.ciliumHealth == nil { return } d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() if d.statusResponse.Cluster == nil { d.statusResponse.Cluster = &models.ClusterStatus{} } if status.Err != nil { d.statusResponse.Cluster.CiliumHealth = &models.Status{ State: models.StatusStateFailure, Msg: status.Err.Error(), } return } if s, ok := status.Data.(*models.Status); ok { d.statusResponse.Cluster.CiliumHealth = s } }, }, { Name: "l7-proxy", Probe: func(ctx context.Context) (interface{}, error) { if d.l7Proxy == nil { return nil, nil } return d.l7Proxy.GetStatusModel(), nil }, OnStatusUpdate: func(status status.Status) { d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() // ProxyStatus has no way to report errors if status.Err == nil { if s, ok := status.Data.(*models.ProxyStatus); ok { d.statusResponse.Proxy = s } } }, }, { Name: "controllers", Probe: func(ctx context.Context) (interface{}, error) { return controller.GetGlobalStatus(), nil }, OnStatusUpdate: func(status status.Status) { d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() // ControllerStatuses has no way to report errors if status.Err == nil { if s, ok := status.Data.(models.ControllerStatuses); ok { d.statusResponse.Controllers = s } } }, }, { Name: "clustermesh", Probe: func(ctx context.Context) (interface{}, error) { if d.clustermesh == nil { return nil, nil } return d.clustermesh.Status(), nil }, OnStatusUpdate: func(status status.Status) { d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() if status.Err == nil { if s, ok := status.Data.(*models.ClusterMeshStatus); ok { d.statusResponse.ClusterMesh = s } } }, }, { Name: "hubble", Probe: func(ctx context.Context) (interface{}, error) { return d.getHubbleStatus(ctx), nil }, OnStatusUpdate: func(status status.Status) { d.statusCollectMutex.Lock() defer d.statusCollectMutex.Unlock() if status.Err == nil { if s, ok := status.Data.(*models.HubbleStatus); ok { d.statusResponse.Hubble = s } } }, }, } if k8s.IsEnabled() { // kube-proxy replacement configuration does not change after // initKubeProxyReplacementOptions() has been executed, so it's fine to // statically set the field here. d.statusResponse.KubeProxyReplacement = d.getKubeProxyReplacementStatus() } d.statusResponse.Masquerading = d.getMasqueradingStatus() d.statusResponse.BandwidthManager = d.getBandwidthManagerStatus() d.statusResponse.BpfMaps = d.getBPFMapStatus() d.statusCollector = status.NewCollector(probes, status.Config{}) // Set up a signal handler function which prints out logs related to daemon status. cleaner.cleanupFuncs.Add(func() { // If the KVstore state is not OK, print help for user. if d.statusResponse.Kvstore != nil && d.statusResponse.Kvstore.State != models.StatusStateOk { helpMsg := "cilium-agent depends on the availability of cilium-operator/etcd-cluster. " + "Check if the cilium-operator pod and etcd-cluster are running and do not have any " + "warnings or error messages." log.WithFields(logrus.Fields{ "status": d.statusResponse.Kvstore.Msg, logfields.HelpMessage: helpMsg, }).Error("KVStore state not OK") } }) return }
apache-2.0
warlock-china/wisp
wisp-core/src/main/java/cn/com/warlock/wisp/core/plugin/processor/support/filter/IEntryFilterChain.java
298
package cn.com.warlock.wisp.core.plugin.processor.support.filter; import cn.com.warlock.wisp.core.dto.MysqlEntryWrap; import cn.com.warlock.wisp.core.exception.WispProcessorException; public interface IEntryFilterChain { void doFilter(MysqlEntryWrap entry) throws WispProcessorException; }
apache-2.0
pingcap/tikv
components/tidb_query_datatype/src/codec/data_type/chunked_vec_set.rs
5937
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use super::bit_vec::BitVec; use super::{ChunkRef, ChunkedVec, UnsafeRefInto}; use super::{Set, SetRef}; use crate::impl_chunked_vec_common; use std::sync::Arc; use tikv_util::buffer_vec::BufferVec; /// `ChunkedVecSet` stores set in a compact way. /// /// Inside `ChunkedVecSet`: /// - `data` stores the real set data. /// - `bitmap` indicates if an element at given index is null. /// - `value` is slice for set value bitmap which up to 64 bits. /// /// # Notes /// /// Make sure operating `bitmap` and `value` together to prevent different /// stored representation issue /// /// TODO: add way to set set column data /// TODO: code fot set/enum looks nearly the same, considering refactor them using macro #[derive(Debug, Clone)] pub struct ChunkedVecSet { data: Arc<BufferVec>, bitmap: BitVec, value: Vec<u64>, } impl ChunkedVecSet { #[inline] pub fn get(&self, idx: usize) -> Option<SetRef> { assert!(idx < self.len()); if self.bitmap.get(idx) { Some(SetRef::new(&self.data, self.value[idx])) } else { None } } } impl ChunkedVec<Set> for ChunkedVecSet { impl_chunked_vec_common! { Set } fn with_capacity(capacity: usize) -> Self { Self { data: Arc::new(BufferVec::new()), bitmap: BitVec::with_capacity(capacity), value: Vec::with_capacity(capacity), } } #[inline] fn push_data(&mut self, value: Set) { self.bitmap.push(true); self.value.push(value.value()); } #[inline] fn push_null(&mut self) { self.bitmap.push(false); self.value.push(0); } fn len(&self) -> usize { self.value.len() } fn truncate(&mut self, len: usize) { if len < self.len() { self.bitmap.truncate(len); self.value.truncate(len); } } fn capacity(&self) -> usize { self.bitmap.capacity().max(self.value.capacity()) } fn append(&mut self, other: &mut Self) { self.value.append(&mut other.value); self.bitmap.append(&mut other.bitmap); } fn to_vec(&self) -> Vec<Option<Set>> { let mut x = Vec::with_capacity(self.len()); for i in 0..self.len() { x.push(if self.bitmap.get(i) { Some(Set::new(self.data.clone(), self.value[i])) } else { None }); } x } } impl PartialEq for ChunkedVecSet { fn eq(&self, other: &Self) -> bool { if self.data.len() != other.data.len() { return false; } for idx in 0..self.data.len() { if self.data[idx] != other.data[idx] { return false; } } if !self.bitmap.eq(&other.bitmap) { return false; } if !self.value.eq(&other.value) { return false; } true } } impl<'a> ChunkRef<'a, SetRef<'a>> for &'a ChunkedVecSet { #[inline] fn get_option_ref(self, idx: usize) -> Option<SetRef<'a>> { self.get(idx) } fn get_bit_vec(self) -> &'a BitVec { &self.bitmap } #[inline] fn phantom_data(self) -> Option<SetRef<'a>> { None } } impl Into<ChunkedVecSet> for Vec<Option<Set>> { fn into(self) -> ChunkedVecSet { ChunkedVecSet::from_vec(self) } } impl<'a> UnsafeRefInto<&'static ChunkedVecSet> for &'a ChunkedVecSet { unsafe fn unsafe_into(self) -> &'static ChunkedVecSet { std::mem::transmute(self) } } #[cfg(test)] mod tests { use super::*; fn setup() -> ChunkedVecSet { let mut x: ChunkedVecSet = ChunkedVecSet::with_capacity(0); // FIXME: we need a set_data here, but for now, we set directly let mut buf = BufferVec::new(); buf.push("我好强啊"); buf.push("我强爆啊"); buf.push("我成功了"); x.data = Arc::new(buf); x } #[test] fn test_basics() { let mut x = setup(); x.push(None); x.push(Some(Set::new(x.data.clone(), 2))); x.push(None); x.push(Some(Set::new(x.data.clone(), 1))); x.push(Some(Set::new(x.data.clone(), 3))); assert_eq!(x.get(0), None); assert_eq!(x.get(1), Some(SetRef::new(&x.data, 2))); assert_eq!(x.get(2), None); assert_eq!(x.get(3), Some(SetRef::new(&x.data, 1))); assert_eq!(x.get(4), Some(SetRef::new(&x.data, 3))); assert_eq!(x.len(), 5); assert!(!x.is_empty()); } #[test] fn test_truncate() { let mut x = setup(); x.push(None); x.push(Some(Set::new(x.data.clone(), 2))); x.push(None); x.push(Some(Set::new(x.data.clone(), 1))); x.push(Some(Set::new(x.data.clone(), 3))); x.truncate(100); assert_eq!(x.len(), 5); x.truncate(3); assert_eq!(x.len(), 3); assert_eq!(x.get(0), None); assert_eq!(x.get(1), Some(SetRef::new(&x.data, 2))); assert_eq!(x.get(2), None); x.truncate(1); assert_eq!(x.len(), 1); assert_eq!(x.get(0), None); x.truncate(0); assert_eq!(x.len(), 0); } #[test] fn test_append() { let mut x = setup(); x.push(None); x.push(Some(Set::new(x.data.clone(), 2))); let mut y = setup(); y.push(None); y.push(Some(Set::new(x.data.clone(), 1))); y.push(Some(Set::new(x.data.clone(), 3))); x.append(&mut y); assert_eq!(x.len(), 5); assert!(y.is_empty()); assert_eq!(x.get(0), None); assert_eq!(x.get(1), Some(SetRef::new(&x.data, 2))); assert_eq!(x.get(2), None); assert_eq!(x.get(3), Some(SetRef::new(&x.data, 1))); assert_eq!(x.get(4), Some(SetRef::new(&x.data, 3))); } }
apache-2.0
ryanobjc/hadoop-cloudera
docs/api/org/apache/hadoop/contrib/index/mapred/class-use/IndexUpdateCombiner.html
6306
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_16) on Mon Jun 28 12:45:09 PDT 2010 --> <TITLE> Uses of Class org.apache.hadoop.contrib.index.mapred.IndexUpdateCombiner (Hadoop 0.20.2+320 API) </TITLE> <META NAME="date" CONTENT="2010-06-28"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.contrib.index.mapred.IndexUpdateCombiner (Hadoop 0.20.2+320 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/contrib/index/mapred/IndexUpdateCombiner.html" title="class in org.apache.hadoop.contrib.index.mapred"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/contrib/index/mapred//class-useIndexUpdateCombiner.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="IndexUpdateCombiner.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.contrib.index.mapred.IndexUpdateCombiner</B></H2> </CENTER> No usage of org.apache.hadoop.contrib.index.mapred.IndexUpdateCombiner <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/contrib/index/mapred/IndexUpdateCombiner.html" title="class in org.apache.hadoop.contrib.index.mapred"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/contrib/index/mapred//class-useIndexUpdateCombiner.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="IndexUpdateCombiner.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; 2009 The Apache Software Foundation </BODY> </HTML>
apache-2.0
codenergic/theskeleton
src/main/java/org/codenergic/theskeleton/post/PostRepository.java
1323
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codenergic.theskeleton.post; import org.codenergic.theskeleton.core.data.AuditingEntityRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface PostRepository extends AuditingEntityRepository<PostEntity> { Page<PostEntity> findByPosterId(String posterId, Pageable pageable); Page<PostEntity> findByResponseToId(String postId, Pageable pageable); @Query("from PostEntity p where p.content like %?1% order by p.createdDate desc") Page<PostEntity> findByContentContaining(String title, Pageable pageable); }
apache-2.0
beargiles/cheat-sheet
webservices/Apache-CXF/apache-cxf-wss4j-interceptors/src/main/java/com/coyotesong/demo/cxf/ApacheCxfWss4jApplication.java
1721
/* * Copyright 2016 Bear Giles <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.coyotesong.demo.cxf; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan("com.coyotesong.demo.cxf") public class ApacheCxfWss4jApplication implements ApplicationContextAware { private static ApplicationContext ctx; public void setApplicationContext(ApplicationContext ctx) { this.ctx = ctx; } @SuppressWarnings("unchecked") public static <T> T getBean(String name) { return (T) ctx.getBean(name); } public static void main(String[] args) { SpringApplication.run(ApacheCxfWss4jApplication.class, args); } }
apache-2.0
minwoox/armeria
core/src/test/java/com/linecorp/armeria/server/VirtualHostBuilderTest.java
10501
/* * Copyright 2016 LINE Corporation * * LINE Corporation licenses this file to you 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.server; import static com.linecorp.armeria.common.HttpStatus.OK; import static com.linecorp.armeria.server.RoutingContextTest.virtualHost; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.slf4j.LoggerFactory; import com.linecorp.armeria.common.HttpMethod; import com.linecorp.armeria.common.HttpResponse; import com.linecorp.armeria.common.RequestHeaders; class VirtualHostBuilderTest { private static final VirtualHostBuilder template = Server.builder().virtualHostTemplate; @Test void defaultVirtualHost() { final ServerBuilder sb = Server.builder(); final Server server = sb.defaultVirtualHost() .service("/test", (ctx, req) -> HttpResponse.of(OK)) .and().build(); final VirtualHost virtualHost = server.config().defaultVirtualHost(); assertThat(virtualHost.hostnamePattern()).isEqualTo("*"); assertThat(virtualHost.defaultHostname()).isNotEqualTo("*"); } @Test void withDefaultVirtualHost() { final ServerBuilder sb = Server.builder(); final Server server = sb.withDefaultVirtualHost(builder -> { builder.defaultHostname("foo") .service("/test", (ctx, req) -> HttpResponse.of(OK)); }).build(); final VirtualHost virtualHost = server.config().defaultVirtualHost(); assertThat(virtualHost.hostnamePattern()).isEqualTo("*"); assertThat(virtualHost.defaultHostname()).isEqualTo("foo"); } @Test void defaultVirtualHostSetDefaultHostname() { final ServerBuilder sb = Server.builder(); sb.defaultHostname("foo"); final Server server = sb.defaultVirtualHost() .service("/test", (ctx, req) -> HttpResponse.of(OK)) .and().build(); final VirtualHost virtualHost = server.config().defaultVirtualHost(); assertThat(virtualHost.hostnamePattern()).isEqualTo("*"); assertThat(virtualHost.defaultHostname()).isEqualTo("foo"); } @Test void defaultVirtualHostWithImplicitStyle() { final ServerBuilder sb = Server.builder(); final Server server = sb.service("/test", (ctx, req) -> HttpResponse.of(OK)).build(); final VirtualHost virtualHost = server.config().defaultVirtualHost(); assertThat(virtualHost.hostnamePattern()).isEqualTo("*"); } @Test void virtualHostWithHostnamePattern() { final ServerBuilder sb = Server.builder(); final Server server = sb.virtualHost("*.foo.com") .service("/test", (ctx, req) -> HttpResponse.of(OK)) .and() .build(); final List<VirtualHost> virtualHosts = server.config().virtualHosts(); assertThat(virtualHosts.size()).isEqualTo(2); final VirtualHost virtualHost = virtualHosts.get(0); assertThat(virtualHost.hostnamePattern()).isEqualTo("*.foo.com"); assertThat(virtualHost.defaultHostname()).isEqualTo("foo.com"); final VirtualHost defaultVirtualHost = virtualHosts.get(1); assertThat(defaultVirtualHost).isEqualTo(server.config().defaultVirtualHost()); } @ParameterizedTest @CsvSource({ "foo, foo", "bar, *.bar", "a.baz, *.baz" }) void virtualHostWithDefaultHostnameAndHostnamePattern(String defaultHostname, String hostnamePattern) { final ServerBuilder sb = Server.builder(); final Server server = sb.virtualHost(defaultHostname, hostnamePattern) .service("/test", (ctx, req) -> HttpResponse.of(OK)) .and() .build(); final List<VirtualHost> virtualHosts = server.config().virtualHosts(); assertThat(virtualHosts.size()).isEqualTo(2); final VirtualHost virtualHost = virtualHosts.get(0); assertThat(virtualHost.hostnamePattern()).isEqualTo(hostnamePattern); assertThat(virtualHost.defaultHostname()).isEqualTo(defaultHostname); final VirtualHost defaultVirtualHost = virtualHosts.get(1); assertThat(defaultVirtualHost).isEqualTo(server.config().defaultVirtualHost()); } @Test void withVirtualHost() { final ServerBuilder sb = Server.builder(); final Server server = sb.withVirtualHost(builder -> { builder.defaultHostname("foo") .service("/test", (ctx, req) -> HttpResponse.of(OK)); }).build(); final List<VirtualHost> virtualHosts = server.config().virtualHosts(); assertThat(virtualHosts.size()).isEqualTo(2); final VirtualHost virtualHost = virtualHosts.get(0); assertThat(virtualHost.hostnamePattern()).isEqualTo("*.foo"); assertThat(virtualHost.defaultHostname()).isEqualTo("foo"); } @Test void defaultVirtualHostMixedStyle() { final ServerBuilder sb = Server.builder(); sb.service("/test", (ctx, req) -> HttpResponse.of(OK)) .defaultVirtualHost().service("/test2", (ctx, req) -> HttpResponse.of(OK)); final Server server = sb.build(); final List<ServiceConfig> serviceConfigs = server.config().defaultVirtualHost().serviceConfigs(); assertThat(serviceConfigs.size()).isEqualTo(2); } @Test void virtualHostWithoutPattern() { final VirtualHost h = new VirtualHostBuilder(Server.builder(), false) .defaultHostname("foo.com") .hostnamePattern("foo.com") .build(template); assertThat(h.hostnamePattern()).isEqualTo("foo.com"); assertThat(h.defaultHostname()).isEqualTo("foo.com"); } @Test void virtualHostWithPattern() { final VirtualHost h = new VirtualHostBuilder(Server.builder(), false) .defaultHostname("bar.foo.com") .hostnamePattern("*.foo.com") .build(template); assertThat(h.hostnamePattern()).isEqualTo("*.foo.com"); assertThat(h.defaultHostname()).isEqualTo("bar.foo.com"); } @Test void accessLoggerCustomization() { final VirtualHost h1 = new VirtualHostBuilder(Server.builder(), false) .defaultHostname("bar.foo.com") .hostnamePattern("*.foo.com") .accessLogger(host -> LoggerFactory.getLogger("customize.test")) .build(template); assertThat(h1.accessLogger().getName()).isEqualTo("customize.test"); final VirtualHost h2 = new VirtualHostBuilder(Server.builder(), false) .defaultHostname("bar.foo.com") .hostnamePattern("*.foo.com") .accessLogger(LoggerFactory.getLogger("com.foo.test")) .build(template); assertThat(h2.accessLogger().getName()).isEqualTo("com.foo.test"); } @Test void hostnamePatternCannotBeSetForDefaultBuilder() { final ServerBuilder sb = Server.builder(); assertThatThrownBy(() -> sb.defaultVirtualHost().hostnamePattern("CannotSet")) .isInstanceOf(UnsupportedOperationException.class); } @Test void hostnamePatternCannotBeSetForDefaultBuilder2() { final ServerBuilder sb = Server.builder(); assertThatThrownBy(() -> sb.withDefaultVirtualHost(builder -> builder.hostnamePattern("CannotSet"))) .isInstanceOf(UnsupportedOperationException.class); } @Test void virtualHostWithNull2() { final ServerBuilder sb = Server.builder(); assertThatThrownBy(() -> sb.virtualHost(null, "foo.com")).isInstanceOf(NullPointerException.class); } @Test void virtualHostWithNull3() { final ServerBuilder sb = Server.builder(); assertThatThrownBy(() -> sb.virtualHost(null, null)).isInstanceOf(NullPointerException.class); } @Test void virtualHostWithMismatch() { assertThatThrownBy(() -> { new VirtualHostBuilder(Server.builder(), false) .defaultHostname("bar.com") .hostnamePattern("foo.com") .build(template); }).isInstanceOf(IllegalArgumentException.class); } @Test void virtualHostWithMismatch2() { assertThatThrownBy(() -> { new VirtualHostBuilder(Server.builder(), false) .defaultHostname("bar.com") .hostnamePattern("*.foo.com") .build(template); }).isInstanceOf(IllegalArgumentException.class); } @Test void precedenceOfDuplicateRoute() { final Route routeA = Route.builder().path("/").build(); final Route routeB = Route.builder().path("/").build(); final VirtualHost virtualHost = new VirtualHostBuilder(Server.builder(), true) .service(routeA, (ctx, req) -> HttpResponse.of(OK)) .service(routeB, (ctx, req) -> HttpResponse.of(OK)) .build(template); assertThat(virtualHost.serviceConfigs().size()).isEqualTo(2); final RoutingContext routingContext = new DefaultRoutingContext(virtualHost(), "example.com", RequestHeaders.of(HttpMethod.GET, "/"), "/", null, false); final Routed<ServiceConfig> serviceConfig = virtualHost.findServiceConfig(routingContext); final Route route = serviceConfig.route(); assertThat(route).isSameAs(routeA); } }
apache-2.0
punkhorn/camel-upstream
components/camel-activemq/src/test/java/org/apache/camel/component/activemq/ActiveMQComponentFactoryUserNamePasswordTest.java
2000
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.activemq; import org.apache.camel.test.spring.CamelSpringTestSupport; import org.junit.Test; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ActiveMQComponentFactoryUserNamePasswordTest extends CamelSpringTestSupport { @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/component/activemq/ActiveMQComponentFactoryUserNamePassword.xml"); } @Test public void testActiveMQ() throws Exception { ActiveMQComponent comp = context.getComponent("activemq", ActiveMQComponent.class); assertNotNull(comp); ActiveMQConfiguration config = (ActiveMQConfiguration)comp.getConfiguration(); assertNotNull(config); assertEquals("admin2", config.getUserName()); assertEquals("secret2", config.getPassword()); getMockEndpoint("mock:result").expectedBodiesReceived("Hello World"); template.sendBody("activemq:queue:bar", "Hello World"); assertMockEndpointsSatisfied(); } }
apache-2.0
smspillaz/opshopify
_includes/header.html
365
<header> <div class="header-overlay"> </div> <div class="header-content"> <div class="header-content-inner"> <h1 class="brand-text">{{ site.title }}</h1> <hr> <p>Shopify your op!</p> <a href="#about" class="btn btn-primary btn-xl page-scroll">Find Out More</a> </div> </div> </header>
apache-2.0
Sargul/dbeaver
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/DBPVirtualObject.java
917
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.model; /** * Virtual object. * Object which doesn't exist in database but exist on client side. * Virtual schemas can be created for some drivers (e.g. Phoenix) */ public interface DBPVirtualObject { boolean isVirtual(); }
apache-2.0
pangkailang/TOMS
target-analysis/src/main/resources/static/tocc-toms/common/mod/control/map-tools/resource/css/maptools.css
15314
html,body{ width: 100%; height: 100%; overflow: hidden; } .busmap-container{ width: 100%; height: 100%; position: relative; } .map-tools{ position: absolute; right: 10px; top: 10px; } .analysis-enter{ width: 60px; height: 60px; border-radius: 4px; background: #ff7133; box-shadow: 0px 4px 14px #a8adb2; text-align: center; font-size: 12px; color: #ffffff; cursor: pointer; float: right; } .analysis-enter img{ margin-top: 10px; } .tools-panels{ height: 32px; background: #ffffff; box-shadow: 0px 4px 10px #c2c8ce; margin-right: 10px; padding: 7px 0; color: #666666; font-size: 12px; float: right; } .panels-r-list{ width: 70px; height: 32px; text-align: center; float: left; position: relative; cursor: pointer; } .border-r{ border-right: 1px solid #e1e3e5; } .list-imgs{ width: 18px; height: 18px; background: url(../images/map-tools.png) no-repeat; position: absolute; left: 26px; top: -2px; } .list-imgs-1{ background-position: -66px -3px; } .list-text{ width: 100%; position: absolute; bottom: -4px; left: 0; } .list-imgs-2{ background-position: -87px -3px; } .list-imgs-3{ background-position: -108px -3px; } .panels-l-list{ /*width: 88px;*/ width: 95px; height: 32px; text-align: center; float: left; position: relative; cursor: pointer; } .list-imgs-4{ background-position: -3px -3px; } .panels-l-list .list-text{ width: 95%; } .list-imgs-5{ background-position: -24px -3px; } .list-imgs-6{ background-position: -45px -3px; } .panels-l-list .list-ico{ width: 8px; height: 8px; background: url(../images/select-arrow.png) -5px -5px no-repeat; position: absolute; right: 5px; top: 12px; } .panels-r-list:hover, .panels-l-list:hover, .panels-list-active{ color: #298cef; } .panels-r-list:hover .list-imgs-1, .panels-list-active .list-imgs-1{ background-position: -66px -24px; } .panels-r-list:hover .list-imgs-2, .panels-list-active .list-imgs-2{ background-position: -87px -24px; } .panels-r-list:hover .list-imgs-3, .panels-list-active .list-imgs-3{ background-position: -108px -24px; } .panels-l-list:hover .list-imgs-4, .panels-list-active .list-imgs-4{ background-position: -3px -24px; } .panels-l-list:hover .list-imgs-5, .panels-list-active .list-imgs-5{ background-position: -24px -24px; } .panels-l-list:hover .list-imgs-6, .panels-list-active .list-imgs-6{ background-position: -45px -24px; } .list-drop{ position: absolute; top: 40px; left: 0; width: 100%; text-align: left; line-height: 32px; box-shadow: 0px 4px 10px #c2c8ce; color: #444444; font-size: 13px; background: #ffffff; padding: 10px 0; display: none; } .list-drop-items .drop-checkbox{ cursor: pointer; vertical-align: middle; margin-right: 5px; } .panels-l-list.panels-list-active .list-ico{ background-position: -18px -5px; } .panels-l-list.panels-list-active .list-drop{ display: block; } .map-search{ position: absolute; top: 10px; left: 10px; } .search-panel{ width: 376px; height: 46px; line-height: 45px; background: #ffffff; box-shadow: 0px 4px 10px #c2c8ce; border-radius: 2px; } .search-panel-ico{ display: block; float: right; width: 56px; height: 100%; text-align: center; border-top-right-radius: 2px; border-bottom-right-radius: 2px; background: #298cef; cursor: pointer; } .search-panel-ico .iconfont{ color: #ffffff; font-size: 20px; } .search-panel-inp{ width: 305px; padding-left: 15px; height: 100%; border: 0; color: #444444; font-size: 13px; } @media \0screen { .tools-panels, .search-panel{ border: 1px solid #e1e3e5; } .search-panel-inp{ float: left; line-height: 45px; } } .search-rec,.search-remind{ background: #ffffff; box-shadow: 0px 4px 10px #c2c8ce; position: absolute; top: 47px; left: 0; width: 320px; display: none; } .search-result{ background: #ffffff; box-shadow: 0px 4px 10px #c2c8ce; position: absolute; top: 57px; left: 10px; width: 320px; display: none; bottom: 150px; z-index: 10030; } .search-result.result-fold{ height: 0px; } .search-result.result-fold>#tab{ display: none; } @media \0screen{ .search-rec, .search-result, .search-remind{ border: 1px solid #e1e3e5; } } .search-rec .rec-classes{ overflow: hidden; border-bottom: 1px solid #e1e3e5; padding: 10px 0; } .search-rec .rec-enters{ width: 25%; float: left; text-align: center; color: #444444; font-size: 12px; } .rec-enters-ico{ width: 100%; height: 50px; background-position: center center; background-repeat: no-repeat; } .enters-ico-1{ background-image: url(../images/searchRec-1.png); } .enters-ico-2{ background-image: url(../images/searchRec-2.png); } .enters-ico-3{ background-image: url(../images/searchRec-3.png); } .enters-ico-4{ background-image: url(../images/searchRec-4.png); } .enters-ico-5{ background-image: url(../images/searchRec-5.png); } .enters-ico-6{ background-image: url(../images/searchRec-6.png); } .enters-ico-7{ background-image: url(../images/searchRec-7.png); } .enters-ico-8{ background-image: url(../images/searchRec-8.png); } .rec-enters-text{ padding-bottom: 6px; } .search-rec .rec-history{ padding: 0 15px; } .rec-history .history-items{ height: 31px; line-height: 30px; border-bottom: 1px solid #e1e3e5; color: #666666; font-size: 12px; cursor: pointer; } .history-items .history-items-ico{ margin-right: 8px; position: relative; top: 2px; } .history-items .history-items-remind{ padding-left: 15px; color: #aaaaaa; } .search-rec .rec-clearhis{ height: 36px; line-height: 35px; padding: 0 15px; color: #298cef; font-size: 12px; text-align: right; cursor: pointer; } .search-rec .rec-clearhis:hover{ color: #2782de; } /*重写tab样式start*/ .result-tabs{ position: relative; } .result-tabs-nav.ui-tabs-nav li{ height: 26px; line-height: 27px; border-color: #e1e3e5; color: #666666; font-size: 13px; padding: 0; width: 71px; padding-left: 5px; text-align: left; background: #f5f7fa; margin-right: 2px; } .result-tabs-nav.ui-tabs-nav li .tabs-nav-text{ width: 50px; overflow: hidden; text-overflow:ellipsis; white-space: nowrap; } .result-tabs-content.ui-tabs-content{ border: 0; padding-top: 33px; } .content-panel{ padding: 10px 0 10px 10px; } .result-tabs-nav.ui-tabs-nav li.ui-tabs-active{ height: 27px; background: #ffffff; color: #444444; } .ui-tabs-trigger .ui-tabs-trigger-close{ font-size: 14px; color: #c2c8ce; } .ui-tabs-trigger-close:hover{ color: #e54d4d; } /*重写tab样式end*/ .tabs-nav-btns{ position: absolute; right: 0px; top: 0px; height: 33px; border-left: 1px solid #e1e3e5; line-height: 32px; z-index: 2; } .nav-btns-items{ height: 100%; color: #96a5b3; background: none; border: 0; font-size: 13px; cursor: pointer; } .nav-btns-items:hover{ color: #298cef; } .btns-items-left{ margin-left: 6px; } .btns-items-right{ margin-right: 6px; } .content-panel .ui-scroll{ height: 100%; } .result-items{ width: 288px; margin-bottom: 10px; } .result-items-card{ width: 100%; overflow: hidden; border: 1px solid #71b7fd; background: #f5faff; position: relative; cursor:pointer; } .items-card-title{ display: block; width: 60px; height: 26px; text-align: center; line-height: 25px; background: #C0C0C0; color: #ffffff; font-size: 14px; position: absolute; top: -1px; left: -1px; } .items-card-times{ float: right; padding-top: 4px; } .card-times-detail{ padding-right: 16px; color: #666666; font-size: 13px; font-family: Arial; } .detail-ico{ display: inline-block; width: 16px; height: 16px; margin-right: 6px; vertical-align: text-bottom; } .detail-ico-first{ background: url(../images/result-1.png) 0 0 no-repeat; } .detail-ico-end{ background: url(../images/result-2.png) 0 0 no-repeat; } .items-card-con{ clear: both; color: #298cef; font-size: 13px; font-weight: bold; display: block; padding-top: 14px; padding-left: 8px; } .items-card-subcon{ color: #666666; font-size: 12px; display: block; padding-bottom: 12px; } .subcon-detail{ padding: 0 8px; } .subcon-detail-line{ vertical-align: text-bottom; color: #666666; font-size: 12px; } .result-items-has{ width: 100%; border: 1px solid #e1e3e5; border-top: 0; } .items-station-title, .items-online-title{ line-height: 29px; padding-left: 11px; color: #298cef; font-size: 12px; } .title-icon{ float: left; margin-right: 10px; margin-top: 8px; width: 13px; height: 13px; background: url(../images/result-3.png) 0 0 no-repeat; cursor: pointer; } .result-items-has ul{ padding-left: 17px; display: none; } .items-station-list, .items-online-list{ line-height: 30px; color: #666666; font-size: 12px; cursor: pointer; } .online-num{ padding-right: 10px; } .online-lic{ color: #ffffff; padding: 3px 5px; border-radius: 2px; background: #71b7fd; } .online-monitor{ margin-right: 10px; float: right; margin-top: 7px; } .items-unfold ul{ display: block; } .items-unfold .title-icon{ background-image: url(../images/result-4.png); } .result-items-load{ width: 268px; height: 28px; padding: 0 10px; line-height: 27px; border: 1px solid #e1e3e5; background: #f5f7fa; color: #298cef; font-size: 12px; cursor: pointer; } .items-load-nums{ float: right; } .result-panel-bottom{ width: 320px; height: 25px; background: url(../images/result-5.png) 0 0 no-repeat; position: absolute; bottom: -23px; left: 0px; } .panel-bottom-ico{ width: 8px; height: 8px; background: url(../images/select-arrow.png) -18px -18px no-repeat; position: absolute; bottom: 15px; left: 50%; margin-left: -4px; } .result-fold .result-tabs{ display: none; } .result-fold .panel-bottom-ico{ background-position: -5px -18px; } .result-buses{ width: 296px; padding-left: 4px; padding-bottom: 10px; border-bottom: 1px solid #e1e3e5; } .buses-title{ padding-top: 16px; padding-bottom: 13px; line-height: 20px; color: #444444; font-size: 14px; } .buses-title-text{ padding-right: 10px; cursor: pointer; } .buses-title-char{ color: #298cef; font-size: 12px; line-height: 18px; padding: 1px 5px; border-radius: 2px; border: 1px solid #298cef; } .buses-items{ overflow: hidden; } .buses-items-label{ color: #666666; font-size: 13px; padding-right: 5px; line-height: 24px; float: left; } .buses-items-tag{ width: 48px; height: 22px; line-height: 21px; border-radius: 2px; border: 1px solid #e1e3e5; background: #f5f7fa; color: #298cef; font-size: 13px; text-align: center; float: left; margin-right: 5px; margin-bottom: 10px; cursor: pointer; } .tag-active{ border-color: #71b7fd; background: #f5faff; } .tag-details{ width: 288px; border: 1px solid #71b7fd; background: #f5faff; color: #666666; clear: both; display: none; } .tag-details-close{ text-align: right; } .tag-details-close .iconfont{ color: #c2c8ce; cursor: pointer; font-size: 12px; margin-right: 10px; } .tag-details-close .iconfont:hover{ color: #e54d4d; } .tag-details-title{ color: #298cef; font-size: 13px; font-weight: bold; padding-left: 10px; } .tag-details-times{ line-height: 16px; padding: 5px 0 5px 10px; } .times-text{ font-size: 13px; font-family: Arial; padding-right: 18px; } .tag-details-sub{ font-size: 12px; padding: 0 10px 5px; } .sub-line{ vertical-align: text-bottom; font-size: 12px; padding: 0 10px; } .result-buses:hover{ background: #fafafa; } .tag-details-remind{ color: #aaaaaa; font-size: 13px; clear: both; } .load-buses, .load-lists{ margin-top: 10px; } .result-lists{ cursor: pointer; width: 290px; padding-left: 10px; border-bottom: 1px solid #e1e3e5; } .lists-title{ display: block; color: #444444; font-size: 12px; line-height: 42px; } .lists-subtitle{ display: block; padding-left: 12px; color: #666666; font-size: 12px; padding-bottom: 8px; } .result-lists:hover{ background: #fafafa; } .search-remind-ul{ padding: 10px 0; } .remind-ul-list{ line-height: 32px; color: #444444; font-size: 13px; cursor: pointer; } .remind-ul-list .iconfont{ color: #96a5b3; margin: 0 8px 0 15px; } .remind-ul-list:hover{ background: #fafafa; } .mCSB_scrollTools { width: 6px; opacity: 0; filter: "alpha(opacity=0)"; -ms-filter: "alpha(opacity=0)"; } .mCSB_inside > .mCSB_container { margin-right: 0px; } #analysisBox{ position: absolute; top:0px; left: 0px; bottom: 0px; right: 0px; z-index: 10031; background: #fafafa; } .analysisBox-content>iframe{ border: none; width: 100%; height: 100%; position: absolute; top:0px; left: 0px; bottom: 0px; right: 0px; } .analysisBox-content{ position: absolute; top:50px; left: 0px; bottom: 0px; right: 0px; } .container-title{ height: 49px; border-bottom: 1px solid #e1e3e5; background: #f5f7fa; color: #298cef; font-size: 20px; line-height: 48px; text-align: center; position: relative; } .title-btnClose{ width: 18px; height: 18px; background: url(../images/index.png) -122px -38px no-repeat; cursor: pointer; position: absolute; right: 20px; top: 16px; } .title-btnClose:hover{ background-position: -94px -38px; } .list-drop-items{ position: relative; left: 4px; } /**指标参数样式*/ .floatLayerBox{ position: absolute; top: 80px; right: 80px; width: 222px; z-index: 100031; height: 312px; box-shadow: 0px 4px 10px #c2c8ce; } .floatLayerBox>iframe{ border: none; width: 100%; height: 100%; position: absolute; top:0px; left: 0px; bottom: 0px; right: 0px; } .bus-index{ position: absolute; right: 10px; top: 82px; } .busIndex-enter{ width: 60px; height: 60px; border-radius: 4px; background: #298cef; box-shadow: 0px 4px 14px #a8adb2; text-align: center; font-size: 12px; color: #ffffff; cursor: pointer; position: absolute; /*float: right;*/ right: 0px; top: 70px; } .busIndex-enter img{ margin-top: 10px; }
apache-2.0
p664940448/weixin
www/templates/mylib_myhistorylend.html
618
<ion-header-bar align-title="center" class="bar-positive"> <a class="button button-clear icon ion-chevron-left" ui-sref="tab.mylib"></a> <h2 class="title"> 借阅历史 </h2> </ion-header-bar> <ion-content> <ion-list> <ion-item class="item-avatar" ng-repeat="book in bookList" ng-click="bookDetils(book.bookId)"> <img ng-src="{{book.pic}}"> <h2 ng-bind="book.bookName"></h2> <p class="rj-list-p" ng-bind="book.author+'&nbsp;&nbsp;'+book.publisher"></p> <span class="rj-push-right" ng-bind="'借阅:'+book.lendDate"></span> </ion-item> </ion-list> </ion-content>
apache-2.0
zerosum0x0/koadic
data/stager/js/stage.js
1812
try { if (Koadic.JOBKEY != "stage") { if (Koadic.isHTA()) { //HKCU\SOFTWARE\Microsoft\Internet Explorer\Style\MaxScriptStatements = 0xFFFFFFFF var path = "SOFTWARE\\Microsoft\\Internet Explorer\\Styles"; var key = "MaxScriptStatements"; Koadic.registry.write(Koadic.registry.HKCU, path, key, 0xFFFFFFFF, Koadic.registry.DWORD); } Koadic.work.report(Koadic.user.info()); try { Koadic.work.fork(""); } catch (e) { Koadic.work.error(e) } Koadic.exit(); } else { if (Koadic.isHTA()) DoWorkTimeout(); else DoWorkLoop(); } } catch (e) { // todo: critical error reporting Koadic.work.error(e); } function DoWork() { var epoch = new Date().getTime(); var expire = parseInt(Koadic.EXPIRE); if (epoch > expire) { return false; } try { var work = Koadic.work.get(); // 201 = x64 or x86 // 202 = force x86 if (work.status == 501 || work.status == 502) { if (work.responseText.length > 0) { var jobkey = work.responseText; Koadic.work.fork(jobkey, work.status == 502); } } else // if (work.status == 500) // kill code { return false; } } catch (e) { return false; } return true; } function DoWorkLoop() { while (DoWork()) ; Koadic.exit(); } function DoWorkTimeout() { for (var i = 0; i < 10; ++i) { if (!DoWork()) { Koadic.exit(); return; } } //window.setTimeout(DoWorkTimeoutCallback, 0); Koadic.work.fork(""); Koadic.exit(); }
apache-2.0
profitbricks/profitbricks-sdk-go
lan.go
6599
package profitbricks import ( "context" "github.com/ionos-cloud/sdk-go/v5" "net/http" ) // Lan object type Lan struct { ID string `json:"id,omitempty"` PBType string `json:"type,omitempty"` Href string `json:"href,omitempty"` Metadata *Metadata `json:"metadata,omitempty"` Properties LanProperties `json:"properties,omitempty"` Entities *LanEntities `json:"entities,omitempty"` Response string `json:"Response,omitempty"` Headers *http.Header `json:"headers,omitempty"` StatusCode int `json:"statuscode,omitempty"` } // LanProperties object type LanProperties struct { Name string `json:"name,omitempty"` Public bool `json:"public,omitempty"` IPFailover *[]IPFailover `json:"ipFailover,omitempty"` PCC string `json:"pcc,omitempty"` } // LanEntities object type LanEntities struct { Nics *LanNics `json:"nics,omitempty"` } // IPFailover object type IPFailover struct { NicUUID string `json:"nicUuid,omitempty"` IP string `json:"ip,omitempty"` } // LanNics object type LanNics struct { ID string `json:"id,omitempty"` PBType string `json:"type,omitempty"` Href string `json:"href,omitempty"` Items []Nic `json:"items,omitempty"` } // Lans object type Lans struct { ID string `json:"id,omitempty"` PBType string `json:"type,omitempty"` Href string `json:"href,omitempty"` Items []Lan `json:"items,omitempty"` Response string `json:"Response,omitempty"` Headers *http.Header `json:"headers,omitempty"` StatusCode int `json:"statuscode,omitempty"` } // ListLans returns a Collection for lans in the Datacenter func (c *Client) ListLans(dcid string) (*Lans, error) { ctx, cancel := c.GetContext() if cancel != nil { defer cancel() } rsp, apiResponse, err := c.CoreSdk.LanApi.DatacentersLansGet(ctx, dcid).Execute() ret := Lans{} if errConvert := convertToCompat(&rsp, &ret); errConvert != nil { return nil, errConvert } fillInResponse(&ret, apiResponse) return &ret, err /* url := lansPath(dcid) ret := &Lans{} err := c.Get(url, ret, http.StatusOK) return ret, err */ } // CreateLan creates a lan in the datacenter // from a jason []byte and returns a Instance struct func (c *Client) CreateLan(dcid string, request Lan) (*Lan, error) { input := ionoscloud.LanPost{} if errConvert := convertToCore(&request, &input); errConvert != nil { return nil, errConvert } ctx, cancel := c.GetContext() if cancel != nil { defer cancel() } rsp, apiResponse, err := c.CoreSdk.LanApi.DatacentersLansPost(ctx, dcid).Lan(input).Execute() ret := Lan{} if errConvert := convertToCompat(&rsp, &ret); errConvert != nil { return nil, errConvert } fillInResponse(&ret, apiResponse) return &ret, err /* url := lansPath(dcid) ret := &Lan{} err := c.Post(url, request, ret, http.StatusAccepted) return ret, err */ } // CreateLanAndWait creates a lan, waits for the request to finish and returns a refreshed lan // Note that an error does not necessarily means that the resource has not been created. // If err & res are not nil, a resource with res.ID exists, but an error occurred either while waiting for // the request or when refreshing the resource. func (c *Client) CreateLanAndWait(ctx context.Context, dcid string, request Lan) (res *Lan, err error) { res, err = c.CreateLan(dcid, request) if err != nil { return } if err = c.WaitTillProvisionedOrCanceled(ctx, res.Headers.Get("location")); err != nil { return } var lan *Lan if lan, err = c.GetLan(dcid, res.ID); err != nil { return } else { return lan, err } } // GetLan pulls data for the lan where id = lanid returns an Instance struct func (c *Client) GetLan(dcid, lanid string) (*Lan, error) { ctx, cancel := c.GetContext() if cancel != nil { defer cancel() } rsp, apiResponse, err := c.CoreSdk.LanApi.DatacentersLansFindById(ctx, dcid, lanid).Execute() ret := Lan{} if errConvert := convertToCompat(&rsp, &ret); errConvert != nil { return nil, errConvert } fillInResponse(&ret, apiResponse) return &ret, err /* url := lanPath(dcid, lanid) ret := &Lan{} err := c.Get(url, ret, http.StatusOK) return ret, err */ } // UpdateLan does a partial update to a lan using json from []byte json returns a Instance struct func (c *Client) UpdateLan(dcid string, lanid string, obj LanProperties) (*Lan, error) { input := ionoscloud.LanProperties{} if errConvert := convertToCore(&obj, &input); errConvert != nil { return nil, errConvert } ctx, cancel := c.GetContext() if cancel != nil { defer cancel() } rsp, apiResponse, err := c.CoreSdk.LanApi.DatacentersLansPatch(ctx, dcid, lanid).Lan(input).Execute() ret := Lan{} if errConvert := convertToCompat(&rsp, &ret); errConvert != nil { return nil, errConvert } fillInResponse(&ret, apiResponse) return &ret, err /* url := lanPath(dcid, lanid) ret := &Lan{} err := c.Patch(url, obj, ret, http.StatusAccepted) return ret, err */ } // UpdateLanAndWait creates a lan, waits for the request to finish and returns a refreshed lan // Note that an error does not necessarily means that the resource has not been updated. // If err & res are not nil, a resource with res.ID exists, but an error occurred either while waiting for // the request or when refreshing the resource. func (c *Client) UpdateLanAndWait(ctx context.Context, dcid, lanid string, props LanProperties) (res *Lan, err error) { res, err = c.UpdateLan(dcid, lanid, props) if err != nil { return } if err = c.WaitTillProvisionedOrCanceled(ctx, res.Headers.Get("location")); err != nil { return } var lan *Lan if lan, err = c.GetLan(dcid, res.ID); err != nil { return } else { return lan, err } } // DeleteLan deletes a lan where id == lanid func (c *Client) DeleteLan(dcid, lanid string) (*http.Header, error) { ctx, cancel := c.GetContext() if cancel != nil { defer cancel() } _, apiResponse, err := c.CoreSdk.LanApi.DatacentersLansDelete(ctx, dcid, lanid).Execute() if apiResponse != nil { return &apiResponse.Header, err } else { return nil, err } /* url := lanPath(dcid, lanid) ret := &http.Header{} err := c.Delete(url, ret, http.StatusAccepted) return ret, err */ } // DeleteLanAndWait deletes given lan and waits for the request to finish func (c *Client) DeleteLanAndWait(ctx context.Context, dcid, lanid string) error { rsp, err := c.DeleteLan(dcid, lanid) if err != nil { return err } return c.WaitTillProvisionedOrCanceled(ctx, rsp.Get("location")) }
apache-2.0
Lartza/rabbitmq-website
site/mqtt.md
11251
<!-- Copyright (C) 2007-2015 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the 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. --> # RabbitMQ MQTT Adapter NOSYNTAX RabbitMQ supports MQTT as of 3.0 (currently targeting version 3.1.1 of the spec). ## <a id="smf"/> Supported MQTT 3.1.1 features * QoS0 and QoS1 publish & consume * Last Will and Testament (LWT) * TLS/SSL * Session stickiness * Retained messages with pluggable storage backends MQTT clients can interoperate with other protocols. All the functionality in the [management UI](/management.html) and several other clients can be used with MQTT, although there may be some limitations or the need to tweak the defaults. ## <a id="ifb"/>Enabling the Plugin The MQTT adapter is included in the RabbitMQ distribution. To enable it, use [rabbitmq-plugins](/man/rabbitmq-plugins.1.man.html): rabbitmq-plugins enable rabbitmq_mqtt After the plugin has been enabled, RabbitMQ needs restarting. ## <a id="overview"/> How it Works RabbitMQ MQTT plugin targets MQTT 3.1.1 and supports a broad range of MQTT clients. It also makes it possible for MQTT clients to interoperate with [AMQP 0-9-1, AMQP 1.0, and STOMP](https://www.rabbitmq.com/protocols.html) clients. There is also support for multi-tenancy. The plugin builds on top of RabbitMQ core protocol's entities: exchanges and queues. Messages published to MQTT topics use a topic exchange (`amq.topic` by default) internally. Subscribers consume from RabbitMQ queues bound to the topic exchange. This both enables interoperability with other protocols and makes it possible to use the [Management plugin](/management.html) to inspect queue sizes, message rates, and so on. ### <a id="durability"/> Subscription Durability MQTT 3.1 assumes two primary usage scenarios: * Transient clients that use transient (non-persistent) messages * Stateful clients that use durable subscriptions (non-clean sessions, QoS1) This section briefly covers how these scenarios map to RabbitMQ queue durability and persistence features. Transient (QoS0) subscription use non-durable, auto-delete queues that will be deleted when the client disconnects. Durable (QoS1) subscriptions use durable queues. Whether the queues are auto-deleted is controlled by the client's clean session flag. Clients with clean sessions use auto-deleted queues, others use non-auto-deleted ones. For transient (QoS0) publishes, the plugin will publish messages as transient (non-persistent). Naturally, for durable (QoS1) publishes, persistent messages will be used internally. Queues created for MQTT subscribers will have names starting with `mqtt-subscription-`, one per subscription QoS level. The queues will have [queue TTL](/ttl.html) depending on MQTT plugin configuration. ## <a id="config"/> Plugin Configuration Here is a sample configuration that sets every MQTT option: [{rabbit, [{tcp_listeners, [5672]}]}, {rabbitmq_mqtt, [{default_user, <<"guest">>}, {default_pass, <<"guest">>}, {allow_anonymous, true}, {vhost, <<"/">>}, {exchange, <<"amq.topic">>}, {subscription_ttl, 1800000}, {prefetch, 10}, {ssl_listeners, []}, %% Default MQTT with TLS port is 8883 %% {ssl_listeners, [8883]} {tcp_listeners, [1883]}, {tcp_listen_options, [binary, {packet, raw}, {reuseaddr, true}, {backlog, 128}, {nodelay, true}]}]} ]. ### <a id="authentication"/> Authentication The `default_user` and `default_pass` options are used to authenticate the adapter in case MQTT clients provide no login credentials. If the `allow_anonymous` option is set to `false` then clients MUST provide credentials. The presence of client-supplied credentials over the network overrides the `allow_anonymous` option. Colons may not appear in usernames. The `vhost` option controls which RabbitMQ vhost the adapter connects to. The `vhost` configuration is only consulted if no vhost is provided during connection establishment. You can optionally specify a vhost while connecting, by prepending the vhost to the username and separating with a colon. For example, connecting with /:guest is equivalent to the default vhost and username. mqtt-vhost:mqtt-username means connecting to the vhost `mqtt-host` with username `mqtt-username`. ### Host and Port The `tcp_listeners` and `tcp_listen_options` options are interpreted in the same way as the corresponding options in the `rabbit` section, as explained in the [broker configuration documentation](http://www.rabbitmq.com/configure.html). ### TLS/SSL The `ssl_listeners` option in the `rabbitmq_mqtt` config section controls the endpoint (if any) that the adapter accepts SSL connections on. The default MQTT SSL port is 8883. If this option is non-empty then the `rabbit` section of the configuration file must contain an `ssl_options` entry: [{rabbit, [ {ssl_options, [{cacertfile, "/path/to/tls/ca/cacert.pem"}, {certfile, "/path/to/tls/server/cert.pem"}, {keyfile, "/path/to/tls/server/key.pem"}, {verify, verify_peer}, {fail_if_no_peer_cert, true}]} ]}, {rabbitmq_mqtt, [ {ssl_listeners, [8883]} {tcp_listeners, [1883]} ]} ]. See the [SSL configuration guide](http://www.rabbitmq.com/ssl.html) for details. ### <a id="cta.ssl"/>Authentication with SSL client certificates The MQTT adapter can authenticate SSL-based connections by extracting a name from the client's SSL certificate, without using a password. For safety the server must be configured with the SSL options `fail_if_no_peer_cert` set to `true` and `verify` set to `verify_peer`, to force all SSL clients to have a verifiable client certificate. To switch this feature on, set `ssl_cert_login` to `true` for the `rabbitmq_mqtt` application. For example: [ {rabbitmq_mqtt, [{ssl_cert_login, true}]} ]. By default this will set the username to an RFC4514-ish string form of the certificate's subject's Distinguished Name, similar to that produced by OpenSSL's "-nameopt RFC2253" option. To use the Common Name instead, add: {rabbit, [{ssl_cert_login_from, common_name}]} to your configuration. Note that: * The authenticated user must exist in the configured authentication / authorisation backend(s). * Clients must **not** supply username and password. ### <a id="stickiness"/> Session Stickiness (Clean and Non-clean Sessions) The `subscription_ttl` option controls the lifetime of non-clean sessions. This option is interpreted in the same way as the [queue TTL](http://www.rabbitmq.com/ttl.html#queue-ttl) parameter, so the value `1800000` means 30 minutes. The `prefetch` option controls the maximum number of unacknowledged messages that will be delivered. This option is interpreted in the same way as the [AMQP 0-9-1 prefetch-count](http://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.qos.prefetch-count) field, so a value of `0` means "no limit". ### Custom Exchanges The `exchange` option determines which exchange messages from MQTT clients are published to. If a non-default exchange is chosen then it must be created before clients publish any messages. The exchange is expected to be a topic exchange. ## <a id="retained"/> Retained Messages and Stores The plugin supports retained messages. Message store implementation is pluggable and the plugin ships with two implementation out of the box: * ETS-based (in memory), implemented in the <code>rabbit_mqtt_retained_msg_store_ets</code> module * DETS-based (on disk), implemented in the <code>rabbit_mqtt_retained_msg_store_dets</code> Both implementations have limitations and trade-offs. With the first one, maximum number of messages that can be retained is limited by RAM. With the second one, there is a limit of 2 GB per vhost. Both are node-local (messages retained on one broker node are not replicated to other nodes in the cluster). To configure the store, use <code>rabbitmq_mqtt.retained_message_store</code> configuration key: [{rabbitmq_mqtt, [{default_user, <<"guest">>}, {default_pass, <<"guest">>}, {allow_anonymous, true}, {vhost, <<"/">>}, {exchange, <<"amq.topic">>}, {subscription_ttl, 1800000}, {prefetch, 10}, %% use DETS (disk-based) store for retained messages {retained_message_store, rabbit_mqtt_retained_msg_store_dets}, %% only used by DETS store {retained_message_store_dets_sync_interval, 2000}, {ssl_listeners, []}, {tcp_listeners, [1883]}]} ]. The value must be a module that implements the store: * <code>rabbit_mqtt_retained_msg_store_ets</code> for RAM-based * <code>rabbit_mqtt_retained_msg_store_dets</code> for disk-based These implementations are suitable for development but sometimes won't be for production needs. MQTT 3.1 specification does not define consistency or replication requirements for retained message stores, therefore RabbitMQ allows for custom ones to meet the consistency and availability needs of a particular environment. For example, stores based on [Riak](http://basho.com/riak/) and [Cassandra](http://cassandra.apache.org/) would be suitable for most production environments as those data stores provide [tunable consistency](http://docs.basho.com/riak/latest/dev/advanced/replication-properties/). Message stores must implement the <code>rabbit_mqtt_retained_msg_store</code> behaviour. ## <a id="limitations"/> Limitations ### Overlapping Subscriptions Overlapping subscriptions from the same client (e.g. `/sports/football/epl/#` and `/sports/football/#`) can result in duplicate messages being delivered. Applications need to account for this. ### Retained Message Stores See Retained Messages above. Different retained message stores have different benefits, trade-offs, and limitations.
apache-2.0
JoyIfBam5/aws-sdk-cpp
aws-cpp-sdk-email/include/aws/email/SESRequest.h
1683
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/email/SES_EXPORTS.h> #include <aws/core/AmazonSerializableWebServiceRequest.h> #include <aws/core/utils/UnreferencedParam.h> #include <aws/core/http/HttpRequest.h> namespace Aws { namespace SES { class AWS_SES_API SESRequest : public Aws::AmazonSerializableWebServiceRequest { public: virtual ~SESRequest () {} virtual Aws::String SerializePayload() const override = 0; void AddParametersToRequest(Aws::Http::HttpRequest& httpRequest) const { AWS_UNREFERENCED_PARAM(httpRequest); } inline Aws::Http::HeaderValueCollection GetHeaders() const override { auto headers = GetRequestSpecificHeaders(); if(headers.size() == 0 || (headers.size() > 0 && headers.count(Aws::Http::CONTENT_TYPE_HEADER) == 0)) { headers.insert(Aws::Http::HeaderValuePair(Aws::Http::CONTENT_TYPE_HEADER, Aws::FORM_CONTENT_TYPE )); } return headers; } protected: virtual Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const { return Aws::Http::HeaderValueCollection(); } }; } // namespace SES } // namespace Aws
apache-2.0
iwangkang/spring
spring-framework-example/spring-messaging-example/src/main/java/me/wangkang/spring/messaging/App.java
191
package me.wangkang.spring.messaging; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
apache-2.0
wildfly-swarm/wildfly-swarm-javadocs
2017.7.0/apidocs/org/wildfly/swarm/jaxrs/package-summary.html
6453
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112) on Thu Jul 06 10:54:03 MST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.jaxrs (Public javadocs 2017.7.0 API)</title> <meta name="date" content="2017-07-06"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.wildfly.swarm.jaxrs (Public javadocs 2017.7.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.7.0</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/wildfly/swarm/javafx/detect/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../org/wildfly/swarm/jaxrs/btm/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/wildfly/swarm/jaxrs/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;org.wildfly.swarm.jaxrs</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation"> <caption><span>Interface Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Interface</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/wildfly/swarm/jaxrs/JAXRSArchive.html" title="interface in org.wildfly.swarm.jaxrs">JAXRSArchive</a></td> <td class="colLast"> <div class="block">An archive supporting easy usage of JAX-RS applications.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../org/wildfly/swarm/jaxrs/JAXRSMessages.html" title="interface in org.wildfly.swarm.jaxrs">JAXRSMessages</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../org/wildfly/swarm/jaxrs/JAXRSFraction.html" title="class in org.wildfly.swarm.jaxrs">JAXRSFraction</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../org/wildfly/swarm/jaxrs/JAXRSMessages_$logger.html" title="class in org.wildfly.swarm.jaxrs">JAXRSMessages_$logger</a></td> <td class="colLast"> <div class="block">Warning this class consists of generated code.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.7.0</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/wildfly/swarm/javafx/detect/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../org/wildfly/swarm/jaxrs/btm/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/wildfly/swarm/jaxrs/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
apache-2.0
yauritux/venice-legacy
Venice/Venice-Service/src/main/java/com/gdn/venice/facade/VenOrderItemHistorySessionEJBBean.java
19139
package com.gdn.venice.facade; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import javax.ejb.EJBException; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContextType; import javax.persistence.Query; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.log4j.Logger; import com.gdn.venice.facade.callback.SessionCallback; import com.gdn.venice.facade.finder.FinderReturn; import com.gdn.venice.persistence.VenOrderItemHistory; import com.djarum.raf.utilities.JPQLAdvancedQueryCriteria; import com.djarum.raf.utilities.JPQLQueryStringBuilder; import com.djarum.raf.utilities.Log4jLoggerFactory; /** * Session Bean implementation class VenOrderItemHistorySessionEJBBean * * <p> * <b>author:</b> <a href="mailto:[email protected]">David Forden</a> * <p> * <b>version:</b> 1.0 * <p> * <b>since:</b> 2011 * */ @Stateless(mappedName = "VenOrderItemHistorySessionEJBBean") public class VenOrderItemHistorySessionEJBBean implements VenOrderItemHistorySessionEJBRemote, VenOrderItemHistorySessionEJBLocal { /* * Implements an IOC model for pre/post callbacks to persist, merge, and * remove operations. The onPrePersist, onPostPersist, onPreMerge, * onPostMerge, onPreRemove and OnPostRemove operations must be implemented * by the callback class. */ private String _sessionCallbackClassName = null; // A reference to the callback object that has been instantiated private SessionCallback _callback = null; protected static Logger _log = null; // The configuration file to use private String _configFile = System.getenv("VENICE_HOME") + "/conf/module-config.xml"; //The binding array used when binding variables into a JPQL query private Object[] bindingArray = null; @PersistenceContext(unitName = "GDN-Venice-Persistence", type = PersistenceContextType.TRANSACTION) protected EntityManager em; /** * Default constructor. */ public VenOrderItemHistorySessionEJBBean() { super(); Log4jLoggerFactory loggerFactory = new Log4jLoggerFactory(); _log = loggerFactory .getLog4JLogger("com.gdn.venice.facade.VenOrderItemHistorySessionEJBBean"); // If the configuration is successful then instantiate the callback if (this.configure()) this.instantiateTriggerCallback(); } /** * Reads the venice configuration file and configures the EJB's * triggerCallbackClassName */ private Boolean configure() { _log.debug("Venice Configuration File:" + _configFile); try { XMLConfiguration config = new XMLConfiguration(_configFile); /* * Get the index entry for the adapter configuration from the * configuration file - there will be multiple adapter * configurations */ @SuppressWarnings({ "rawtypes" }) List callbacks = config .getList("sessionBeanConfig.callback.[@name]"); Integer beanConfigIndex = new Integer(Integer.MAX_VALUE); @SuppressWarnings("rawtypes") Iterator i = callbacks.iterator(); while (i.hasNext()) { String beanName = (String) i.next(); if (this.getClass().getSimpleName().equals(beanName)) { beanConfigIndex = callbacks.indexOf(beanName); _log.debug("Bean configuration for " + beanName + " found at " + beanConfigIndex); } } this._sessionCallbackClassName = config .getString("sessionBeanConfig.callback(" + beanConfigIndex + ").[@class]"); _log.debug("Loaded configuration for _sessionCallbackClassName:" + _sessionCallbackClassName); } catch (ConfigurationException e) { _log.error("A ConfigurationException occured when processing the configuration file" + e.getMessage()); e.printStackTrace(); return Boolean.FALSE; } return Boolean.TRUE; } /** * Instantiates the trigger callback handler class * * @return */ Boolean instantiateTriggerCallback() { if (_sessionCallbackClassName != null && !_sessionCallbackClassName.isEmpty()) try { Class<?> c = Class.forName(_sessionCallbackClassName); _callback = (SessionCallback) c.newInstance(); } catch (ClassNotFoundException e) { _log.error("A ClassNotFoundException occured when trying to instantiate:" + this._sessionCallbackClassName); e.printStackTrace(); return Boolean.FALSE; } catch (InstantiationException e) { _log.error("A InstantiationException occured when trying to instantiate:" + this._sessionCallbackClassName); e.printStackTrace(); return Boolean.FALSE; } catch (IllegalAccessException e) { _log.error("A IllegalAccessException occured when trying to instantiate:" + this._sessionCallbackClassName); e.printStackTrace(); return Boolean.FALSE; } return Boolean.TRUE; } /* * (non-Javadoc) * * @see * com.gdn.venice.facade.VenOrderItemHistorySessionEJBRemote#queryByRange(java.lang * .String, int, int) */ @Override @SuppressWarnings({ "unchecked" }) public List<VenOrderItemHistory> queryByRange(String jpqlStmt, int firstResult, int maxResults) { Long startTime = System.currentTimeMillis(); _log.debug("queryByRange()"); Query query = null; try { query = em.createQuery(jpqlStmt); if(this.bindingArray != null){ for(int i = 0; i < bindingArray.length; ++i){ if(bindingArray[i] != null){ query.setParameter(i+1, bindingArray[i]); } } } } catch (Exception e) { _log.error("An exception occured when calling em.createQuery():" + e.getMessage()); throw new EJBException(e); } try { if (firstResult > 0) { query = query.setFirstResult(firstResult); } if (maxResults > 0) { query = query.setMaxResults(maxResults); } } catch (Exception e) { _log.error("An exception occured when accessing the result set of a query:" + e.getMessage()); throw new EJBException(e); } List<VenOrderItemHistory> returnList = (List<VenOrderItemHistory>)query.getResultList(); this.bindingArray = null; Long endTime = System.currentTimeMillis(); Long duration = startTime - endTime; _log.debug("queryByRange() duration:" + duration + "ms"); return returnList; } /* * (non-Javadoc) * * @see * com.gdn.venice.facade.VenOrderItemHistorySessionEJBRemote#persistVenOrderItemHistory(com * .gdn.venice.persistence.VenOrderItemHistory) */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public VenOrderItemHistory persistVenOrderItemHistory(VenOrderItemHistory venOrderItemHistory) { Long startTime = System.currentTimeMillis(); _log.debug("persistVenOrderItemHistory()"); // Call the onPrePersist() callback and throw an exception if it fails if (this._callback != null) { if (!this._callback.onPrePersist(venOrderItemHistory)) { _log.error("An onPrePersist callback operation failed for:" + this._sessionCallbackClassName); throw new EJBException( "An onPrePersist callback operation failed for:" + this._sessionCallbackClassName); } } VenOrderItemHistory existingVenOrderItemHistory = null; if (venOrderItemHistory != null && venOrderItemHistory.getOrderItemHistoryId() != null) { _log.debug("persistVenOrderItemHistory:em.find()"); try { existingVenOrderItemHistory = em.find(VenOrderItemHistory.class, venOrderItemHistory.getOrderItemHistoryId()); } catch (Exception e) { _log.error("An exception occured when calling em.find():" + e.getMessage()); throw new EJBException(e); } } if (existingVenOrderItemHistory == null) { _log.debug("persistVenOrderItemHistory:em.persist()"); try { em.persist(venOrderItemHistory); } catch (Exception e) { _log.error("An exception occured when calling em.persist():" + e.getMessage()); throw new EJBException(e); } _log.debug("persistVenOrderItemHistory:em.flush()"); try { em.flush(); em.clear(); } catch (Exception e) { _log.error("An exception occured when calling em.flush():" + e.getMessage()); throw new EJBException(e); } // Call the onPostPersist() callback and throw an exception if it fails if (this._callback != null) { if (!this._callback.onPostPersist(venOrderItemHistory)) { _log.error("An onPostPersist callback operation failed for:" + this._sessionCallbackClassName); throw new EJBException( "An onPostPersist callback operation failed for:" + this._sessionCallbackClassName); } } Long endTime = System.currentTimeMillis(); Long duration = startTime - endTime; _log.debug("persistVenOrderItemHistory() duration:" + duration + "ms"); return venOrderItemHistory; } else { throw new EJBException("VenOrderItemHistory exists!. VenOrderItemHistory = " + venOrderItemHistory.getOrderItemHistoryId()); } } /* * (non-Javadoc) * * @see * com.gdn.venice.facade.VenOrderItemHistorySessionEJBRemote#persistVenOrderItemHistoryList * (java.util.List) */ @Override @SuppressWarnings("rawtypes") @TransactionAttribute(TransactionAttributeType.REQUIRED) public ArrayList<VenOrderItemHistory> persistVenOrderItemHistoryList( List<VenOrderItemHistory> venOrderItemHistoryList) { _log.debug("persistVenOrderItemHistoryList()"); Iterator i = venOrderItemHistoryList.iterator(); while (i.hasNext()) { this.persistVenOrderItemHistory((VenOrderItemHistory) i.next()); } return (ArrayList<VenOrderItemHistory>)venOrderItemHistoryList; } /* * (non-Javadoc) * * @see * com.gdn.venice.facade.VenOrderItemHistorySessionEJBRemote#mergeVenOrderItemHistory(com. * gdn.venice.persistence.VenOrderItemHistory) */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public VenOrderItemHistory mergeVenOrderItemHistory(VenOrderItemHistory venOrderItemHistory) { Long startTime = System.currentTimeMillis(); _log.debug("mergeVenOrderItemHistory()"); // Call the onPreMerge() callback and throw an exception if it fails if (this._callback != null) { if (!this._callback.onPreMerge(venOrderItemHistory)) { _log.error("An onPreMerge callback operation failed for:" + this._sessionCallbackClassName); throw new EJBException( "An onPreMerge callback operation failed for:" + this._sessionCallbackClassName); } } VenOrderItemHistory existing = null; if (venOrderItemHistory.getOrderItemHistoryId() != null){ _log.debug("mergeVenOrderItemHistory:em.find()"); existing = em.find(VenOrderItemHistory.class, venOrderItemHistory.getOrderItemHistoryId()); } if (existing == null) { return this.persistVenOrderItemHistory(venOrderItemHistory); } else { _log.debug("mergeVenOrderItemHistory:em.merge()"); try { em.merge(venOrderItemHistory); } catch (Exception e) { _log.error("An exception occured when calling em.merge():" + e.getMessage()); throw new EJBException(e); } _log.debug("mergeVenOrderItemHistory:em.flush()"); try { em.flush(); em.clear(); } catch (Exception e) { _log.error("An exception occured when calling em.flush():" + e.getMessage()); throw new EJBException(e); } VenOrderItemHistory newobject = em.find(VenOrderItemHistory.class, venOrderItemHistory.getOrderItemHistoryId()); _log.debug("mergeVenOrderItemHistory():em.refresh"); try { em.refresh(newobject); } catch (Exception e) { _log.error("An exception occured when calling em.refresh():" + e.getMessage()); throw new EJBException(e); } // Call the onPostMerge() callback and throw an exception if it fails if (this._callback != null) { if (!this._callback.onPostMerge(newobject)) { _log.error("An onPostMerge callback operation failed for:" + this._sessionCallbackClassName); throw new EJBException( "An onPostMerge callback operation failed for:" + this._sessionCallbackClassName); } } Long endTime = System.currentTimeMillis(); Long duration = startTime - endTime; _log.debug("mergeVenOrderItemHistory() duration:" + duration + "ms"); return newobject; } } /* * (non-Javadoc) * * @see * com.gdn.venice.facade.VenOrderItemHistorySessionEJBRemote#mergeVenOrderItemHistoryList( * java.util.List) */ @Override @SuppressWarnings("rawtypes") @TransactionAttribute(TransactionAttributeType.REQUIRED) public ArrayList<VenOrderItemHistory> mergeVenOrderItemHistoryList( List<VenOrderItemHistory> venOrderItemHistoryList) { _log.debug("mergeVenOrderItemHistoryList()"); Iterator i = venOrderItemHistoryList.iterator(); while (i.hasNext()) { this.mergeVenOrderItemHistory((VenOrderItemHistory) i.next()); } return (ArrayList<VenOrderItemHistory>)venOrderItemHistoryList; } /* * (non-Javadoc) * * @see * com.gdn.venice.facade.VenOrderItemHistorySessionEJBRemote#removeVenOrderItemHistory(com. * gdn.venice.persistence.VenOrderItemHistory) */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void removeVenOrderItemHistory(VenOrderItemHistory venOrderItemHistory) { Long startTime = System.currentTimeMillis(); _log.debug("removeVenOrderItemHistory()"); // Call the onPreRemove() callback and throw an exception if it fails if (this._callback != null) { if (!this._callback.onPreRemove(venOrderItemHistory)) { _log.error("An onPreRemove callback operation failed for:" + this._sessionCallbackClassName); throw new EJBException( "An onPreRemove callback operation failed for:" + this._sessionCallbackClassName); } } _log.debug("removeVenOrderItemHistory:em.find()"); venOrderItemHistory = em.find(VenOrderItemHistory.class, venOrderItemHistory.getOrderItemHistoryId()); try { _log.debug("removeVenOrderItemHistory:em.remove()"); em.remove(venOrderItemHistory); } catch (Exception e) { _log.error("An exception occured when calling em.remove():" + e.getMessage()); throw new EJBException(e); } // Call the onPostRemove() callback and throw an exception if it fails if (this._callback != null) { if (!this._callback.onPostRemove(venOrderItemHistory)) { _log.error("An onPostRemove callback operation failed for:" + this._sessionCallbackClassName); throw new EJBException( "An onPostRemove callback operation failed for:" + this._sessionCallbackClassName); } } _log.debug("removeVenOrderItemHistory:em.flush()"); em.flush(); em.clear(); Long endTime = System.currentTimeMillis(); Long duration = startTime - endTime; _log.debug("removeVenOrderItemHistory() duration:" + duration + "ms"); } /* * (non-Javadoc) * * @see * com.gdn.venice.facade.VenOrderItemHistorySessionEJBRemote#removeVenOrderItemHistoryList( * java.util.List) */ @Override @SuppressWarnings("rawtypes") @TransactionAttribute(TransactionAttributeType.REQUIRED) public void removeVenOrderItemHistoryList(List<VenOrderItemHistory> venOrderItemHistoryList) { _log.debug("removeVenOrderItemHistoryList()"); Iterator i = venOrderItemHistoryList.iterator(); while (i.hasNext()) { this.removeVenOrderItemHistory((VenOrderItemHistory) i.next()); } } /* * (non-Javadoc) * * @see * com.gdn.venice.facade.VenOrderItemHistorySessionEJBRemote#findByVenOrderItemHistoryLike( * com.gdn.venice.persistence.VenOrderItemHistory, int, int) */ @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public List<VenOrderItemHistory> findByVenOrderItemHistoryLike(VenOrderItemHistory venOrderItemHistory, JPQLAdvancedQueryCriteria criteria, int firstResult, int maxResults) { Long startTime = System.currentTimeMillis(); _log.debug("findByVenOrderItemHistoryLike()"); JPQLQueryStringBuilder qb = new JPQLQueryStringBuilder(venOrderItemHistory); HashMap complexTypeBindings = new HashMap(); String stmt = qb.buildQueryString(complexTypeBindings, criteria); if(criteria != null){ /* * Get the binding array from the query builder and make * it available to the queryByRange method */ this.bindingArray = qb.getBindingArray(); for(int i = 0; i < qb.getBindingArray().length; i++){ System.out.println("Bindings:" + i + ":" + qb.getBindingArray()[i]); } List<VenOrderItemHistory> venOrderItemHistoryList = this.queryByRange(stmt, firstResult, maxResults); Long endTime = System.currentTimeMillis(); Long duration = startTime - endTime; _log.debug("findByVenOrderItemHistoryLike() duration:" + duration + "ms"); return venOrderItemHistoryList; }else{ String errMsg = "A query has been initiated with null criteria."; _log.error(errMsg); throw new EJBException(errMsg); } } /* * (non-Javadoc) * * @see * com.gdn.venice.facade.VenOrderItemHistorySessionEJBRemote#findByVenOrderItemHistoryLikeFR( * com.gdn.venice.persistence.VenOrderItemHistory, int, int) */ @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public FinderReturn findByVenOrderItemHistoryLikeFR(VenOrderItemHistory venOrderItemHistory, JPQLAdvancedQueryCriteria criteria, int firstResult, int maxResults) { Long startTime = System.currentTimeMillis(); _log.debug("findByVenOrderItemHistoryLikeFR()"); JPQLQueryStringBuilder qb = new JPQLQueryStringBuilder(venOrderItemHistory); HashMap complexTypeBindings = new HashMap(); String stmt = qb.buildQueryString(complexTypeBindings, criteria); if(criteria != null){ /* * Get the binding array from the query builder and make * it available to the queryByRange method */ this.bindingArray = qb.getBindingArray(); for(int i = 0; i < qb.getBindingArray().length; i++){ System.out.println("Bindings:" + i + ":" + qb.getBindingArray()[i]); } //Set the finder return object with the count of the total query rows FinderReturn fr = new FinderReturn(); String countStmt = "select count(o) " + stmt.substring(stmt.indexOf("from")); Query query = null; try { query = em.createQuery(countStmt); if(this.bindingArray != null){ for(int i = 0; i < bindingArray.length; ++i){ if(bindingArray[i] != null){ query.setParameter(i+1, bindingArray[i]); } } } Long totalRows = (Long)query.getSingleResult(); fr.setNumQueryRows(totalRows); } catch (Exception e) { _log.error("An exception occured when calling em.createQuery():" + e.getMessage()); throw new EJBException(e); } //Set the finder return object with the query list fr.setResultList(this.queryByRange(stmt, firstResult, maxResults)); Long endTime = System.currentTimeMillis(); Long duration = startTime - endTime; _log.debug("findByVenOrderItemHistoryLike() duration:" + duration + "ms"); return fr; }else{ String errMsg = "A query has been initiated with null criteria."; _log.error(errMsg); throw new EJBException(errMsg); } } }
apache-2.0
hiwhitley/CodingEveryDay
src/com/hiwhitley/chapter01/Pet.java
248
package com.hiwhitley.chapter01; /** * Created by hiwhitley on 2016/10/27. */ public class Pet { private String type; public Pet(String type) { this.type = type; } public String getType() { return type; } }
apache-2.0
blackducksoftware/ohcount4j
src/main/java/com/blackducksoftware/ohcount4j/Language.java
16986
/* * Copyright 2016 Black Duck Software, 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. */ package com.blackducksoftware.ohcount4j; import java.util.ArrayList; import java.util.List; import com.blackducksoftware.ohcount4j.scan.ActionScriptScanner; import com.blackducksoftware.ohcount4j.scan.AdaScanner; import com.blackducksoftware.ohcount4j.scan.AssemblyScanner; import com.blackducksoftware.ohcount4j.scan.AugeasScanner; import com.blackducksoftware.ohcount4j.scan.AutoconfScanner; import com.blackducksoftware.ohcount4j.scan.AutomakeScanner; import com.blackducksoftware.ohcount4j.scan.AwkScanner; import com.blackducksoftware.ohcount4j.scan.BatScanner; import com.blackducksoftware.ohcount4j.scan.BfkScanner; import com.blackducksoftware.ohcount4j.scan.BfkppScanner; import com.blackducksoftware.ohcount4j.scan.BinaryScanner; import com.blackducksoftware.ohcount4j.scan.BlitzMaxScanner; import com.blackducksoftware.ohcount4j.scan.BooScanner; import com.blackducksoftware.ohcount4j.scan.CMakeScanner; import com.blackducksoftware.ohcount4j.scan.CStyleScanner; import com.blackducksoftware.ohcount4j.scan.ClearSilverTemplateScanner; import com.blackducksoftware.ohcount4j.scan.ClojureScanner; import com.blackducksoftware.ohcount4j.scan.CobolScanner; import com.blackducksoftware.ohcount4j.scan.CoffeeScriptScanner; import com.blackducksoftware.ohcount4j.scan.ColdFusionScanner; import com.blackducksoftware.ohcount4j.scan.CoqScanner; import com.blackducksoftware.ohcount4j.scan.DScanner; import com.blackducksoftware.ohcount4j.scan.DclScanner; import com.blackducksoftware.ohcount4j.scan.EiffelScanner; import com.blackducksoftware.ohcount4j.scan.ElixirScanner; import com.blackducksoftware.ohcount4j.scan.ErlangScanner; import com.blackducksoftware.ohcount4j.scan.FSharpScanner; import com.blackducksoftware.ohcount4j.scan.FactorScanner; import com.blackducksoftware.ohcount4j.scan.ForthScanner; import com.blackducksoftware.ohcount4j.scan.FortranFixedScanner; import com.blackducksoftware.ohcount4j.scan.FortranFreeScanner; import com.blackducksoftware.ohcount4j.scan.GenericCodeScanner; import com.blackducksoftware.ohcount4j.scan.HTMLScanner; import com.blackducksoftware.ohcount4j.scan.HamlScanner; import com.blackducksoftware.ohcount4j.scan.HaskellScanner; import com.blackducksoftware.ohcount4j.scan.IdlPvwaveScanner; import com.blackducksoftware.ohcount4j.scan.JspScanner; import com.blackducksoftware.ohcount4j.scan.LispScanner; import com.blackducksoftware.ohcount4j.scan.LogtalkScanner; import com.blackducksoftware.ohcount4j.scan.LuaScanner; import com.blackducksoftware.ohcount4j.scan.MakeScanner; import com.blackducksoftware.ohcount4j.scan.MathematicaScanner; import com.blackducksoftware.ohcount4j.scan.MatlabScanner; import com.blackducksoftware.ohcount4j.scan.MetapostWithTexScanner; import com.blackducksoftware.ohcount4j.scan.MetafontScanner; import com.blackducksoftware.ohcount4j.scan.ModulaScanner; import com.blackducksoftware.ohcount4j.scan.OCamlScanner; import com.blackducksoftware.ohcount4j.scan.PascalScanner; import com.blackducksoftware.ohcount4j.scan.PerlScanner; import com.blackducksoftware.ohcount4j.scan.PhpScanner; import com.blackducksoftware.ohcount4j.scan.PrologScanner; import com.blackducksoftware.ohcount4j.scan.PythonScanner; import com.blackducksoftware.ohcount4j.scan.RebolScanner; import com.blackducksoftware.ohcount4j.scan.RexxScanner; import com.blackducksoftware.ohcount4j.scan.RubyScanner; import com.blackducksoftware.ohcount4j.scan.Scanner; import com.blackducksoftware.ohcount4j.scan.SchemeScanner; import com.blackducksoftware.ohcount4j.scan.ShellScanner; import com.blackducksoftware.ohcount4j.scan.SmalltalkScanner; import com.blackducksoftware.ohcount4j.scan.SqlScanner; import com.blackducksoftware.ohcount4j.scan.TclScanner; import com.blackducksoftware.ohcount4j.scan.TexScanner; import com.blackducksoftware.ohcount4j.scan.VimScriptScanner; import com.blackducksoftware.ohcount4j.scan.VisualBasicScanner; import com.blackducksoftware.ohcount4j.scan.XmlScanner; public enum Language implements LanguageCategory { /* * All languages must be defined here. * * Each language must declare three mandatory properties: * * - The language's official display name (niceName) * - The category of the language, one of BUILD, LOGIC, MARKUP, UNKNOWN * - A Scanner subclass capable of parsing this language */ ACTIONSCRIPT("ActionScript", LOGIC, ActionScriptScanner.class), ADA("Ada", LOGIC, AdaScanner.class), ASPX_CSHARP("ASP.NET (C#)", LOGIC, GenericCodeScanner.class), // TODO. ASPX_VB("ASP.NET (VB)", LOGIC, GenericCodeScanner.class), // TODO. ASSEMBLY("Assembly", LOGIC, AssemblyScanner.class), AUGEAS("Augeas", LOGIC, AugeasScanner.class), AUTOCONF("Autoconf", BUILD, AutoconfScanner.class), AUTOMAKE("Automake", BUILD, AutomakeScanner.class), AWK("Awk", LOGIC, AwkScanner.class), BAT("Windows Batch", LOGIC, BatScanner.class), BFPP("Brainfuck++", LOGIC, BfkppScanner.class), BINARY("Binary", LOGIC, BinaryScanner.class), BLITZMAX("BlitzMax", LOGIC, BlitzMaxScanner.class), BOO("Boo", LOGIC, BooScanner.class), BRAINFUCK("Brainfuck", LOGIC, BfkScanner.class), C("C", LOGIC, CStyleScanner.class), CHAISCRIPT("ChaiScript", LOGIC, CStyleScanner.class), CLASSIC_BASIC("Classic BASIC", LOGIC, GenericCodeScanner.class), // TODO. CLEARSILVER("ClearSilver", LOGIC, ClearSilverTemplateScanner.class), CLOJURE("Clojure", LOGIC, ClojureScanner.class), COBOL("COBOL", LOGIC, CobolScanner.class), COFFEESCRIPT("CoffeeScript", LOGIC, CoffeeScriptScanner.class), COLDFUSION("ColdFusion", MARKUP, ColdFusionScanner.class), CPP("C++", LOGIC, CStyleScanner.class), CMake("CMake", BUILD, CMakeScanner.class), CSHARP("C#", LOGIC, CStyleScanner.class), COQ("Coq", LOGIC, CoqScanner.class), CSS("CSS", MARKUP, CStyleScanner.class), CUDA("CUDA", LOGIC, CStyleScanner.class), D("D", LOGIC, DScanner.class), DYLAN("Dylan", LOGIC, CStyleScanner.class), DCL("DCL", LOGIC, DclScanner.class), EBUILD("Ebuild", BUILD, ShellScanner.class), EC("eC", LOGIC, CStyleScanner.class), ECMASCRIPT("ECMAScript", LOGIC, CStyleScanner.class), EIFFEL("Eiffel", LOGIC, EiffelScanner.class), ELIXIR("Elixir", LOGIC, ElixirScanner.class), EMACSLISP("Emacs Lisp", LOGIC, LispScanner.class), ERLANG("Erlang", LOGIC, ErlangScanner.class), FACTOR("Factor", LOGIC, FactorScanner.class), EXHERES("Exheres", LOGIC, ShellScanner.class), FORTH("Forth", LOGIC, ForthScanner.class), FORTRANFIXED("Fortran (Fixed-Format)", LOGIC, FortranFixedScanner.class), FORTRANFREE("Fortran (Free-Format)", LOGIC, FortranFreeScanner.class), FSHARP("F#", LOGIC, FSharpScanner.class), GENIE("Genie", LOGIC, CStyleScanner.class), GLSL("OpenGL Shading Language", LOGIC, CStyleScanner.class), GOLANG("Go", LOGIC, CStyleScanner.class), GROOVY("Groovy", LOGIC, CStyleScanner.class), HAML("Haml", MARKUP, HamlScanner.class), HAXE("HaXe", LOGIC, CStyleScanner.class), HTML("HTML", MARKUP, HTMLScanner.class), HASKELL("Haskell", LOGIC, HaskellScanner.class), IDL_PVWAVE("IDL/PV-WAVE/GDL", LOGIC, IdlPvwaveScanner.class), JAM("Jam", BUILD, ShellScanner.class), JAVA("Java", LOGIC, CStyleScanner.class), JAVASCRIPT("JavaScript", LOGIC, CStyleScanner.class), JSP("JSP", LOGIC, JspScanner.class), KOTLIN("Kotlin", LOGIC, CStyleScanner.class), LIMBO("Limbo", LOGIC, CStyleScanner.class), LISP("Lisp", LOGIC, LispScanner.class), LOGTALK("Logtalk", LOGIC, LogtalkScanner.class), LUA("Lua", LOGIC, LuaScanner.class), MAKE("Make", BUILD, MakeScanner.class), MATHEMATICA("Mathematica", LOGIC, MathematicaScanner.class), MATLAB("Matlab", LOGIC, MatlabScanner.class), METAPOST("MetaPost", MARKUP, MetapostWithTexScanner.class), METAFONT("MetaFont", MARKUP, MetafontScanner.class), MODULA2("Modula 2", LOGIC, ModulaScanner.class), MODULA3("Modula 3", LOGIC, ModulaScanner.class), OBJECTIVE_C("Objective-C", LOGIC, CStyleScanner.class), OCAML("OCaml", LOGIC, OCamlScanner.class), OCTAVE("Octave", LOGIC, MatlabScanner.class), // TODO. Octave also supports # comments PASCAL("Pascal", LOGIC, PascalScanner.class), PERL("Perl", LOGIC, PerlScanner.class), PHP("Php", LOGIC, PhpScanner.class), PUPPET("Puppet", LOGIC, GenericCodeScanner.class), // TODO. PROLOG("Prolog", LOGIC, PrologScanner.class), PYTHON("Python", LOGIC, PythonScanner.class), R("R", LOGIC, GenericCodeScanner.class), // TODO. REBOL("REBOL", LOGIC, RebolScanner.class), REXX("Rexx", LOGIC, RexxScanner.class), RUBY("Ruby", LOGIC, RubyScanner.class), SCALA("Scala", LOGIC, CStyleScanner.class), SWIFT("Swift", LOGIC, CStyleScanner.class), SCHEME("Scheme", LOGIC, SchemeScanner.class), SHELL("Shell", LOGIC, ShellScanner.class), SMALLTALK("Smalltalk", LOGIC, SmalltalkScanner.class), SQL("SQL", LOGIC, SqlScanner.class), STRUCTURED_BASIC("Structured Basic", LOGIC, VisualBasicScanner.class), TCL("Tcl", LOGIC, TclScanner.class), TEX("TeX/LaTeX", MARKUP, TexScanner.class), UNKNOWN("Unknown", CATEGORY_UNKNOWN, GenericCodeScanner.class), VB("VisualBasic", LOGIC, VisualBasicScanner.class), VBSCRIPT("VBScript", LOGIC, VisualBasicScanner.class), VIMSCRIPT("Vimscript", LOGIC, VimScriptScanner.class), XML("XML", MARKUP, XmlScanner.class), XMLSCHEMA("XML Schema", MARKUP, XmlScanner.class), XSLT("XSL Transformation", MARKUP, XmlScanner.class); /* * Optional properties of languages are declared here. * * At a minimum, a language should define one or more file * extensions or filenames associated with the language. * * You may also declare additional names (beyond the uname * and niceName) by which the language might be known. * These aliases can be matched against things like Emacs * mode headers or shebang directives. */ static { ACTIONSCRIPT.extension("as"); ADA.extensions("ada", "adb"); ASPX_CSHARP.extension("aspx"); ASPX_VB.extension("aspx"); ASSEMBLY.extensions("as8", "asm", "asx", "S", "z80"); AUGEAS.extensions("aug"); AUTOCONF.extensions("autoconf", "ac", "m4"); // m4 (unix macro processor) AUTOMAKE.extensions("am"); AWK.extension("awk"); BAT.extension("bat"); BFPP.extensions("bfpp"); BINARY.extensions("inc", "st"); BLITZMAX.extension("bmx"); BOO.extension("boo"); BRAINFUCK.extension("bf"); C.extensions("c", "h"); CHAISCRIPT.extension("chai"); CLASSIC_BASIC.extensions("b", "bas"); CLEARSILVER.extension("cs"); CLOJURE.extensions("clj", "cljs", "cljc"); CMake.extensions("cmake").filename("CMakeLists.txt"); COBOL.extension("cbl"); COFFEESCRIPT.extension("coffee"); COLDFUSION.extensions("cfc", "cfm"); CPP.extensions("C", "c++", "cc", "cpp", "cxx", "H", "h", "h++", "hh", "hpp", "hxx"); COQ.extension("v"); CSHARP.aliases("C#", "cs").extension("cs"); CSS.extension("css"); CUDA.extensions("cu", "cuh"); D.extension("d"); DYLAN.extension("dylan"); DCL.extension("com"); EBUILD.extensions("ebuild", "kdebuild-1", "eclass"); EC.extensions("ec", "eh"); ECMASCRIPT.extension("es"); EIFFEL.extension("e"); ELIXIR.extensions("ex", "exs"); EMACSLISP.extension("el"); ERLANG.extension("erl"); EXHERES.extensions("exheres-0", "exheres-1", "exlib"); FACTOR.extension("factor"); FORTH.extensions("fr", "4th"); FORTRANFIXED.extensions("i", "f", "f03", "f08", "f77", "f90", "f95", "for", "fpp", "ftn"); FORTRANFREE.extensions("i90", "f", "f03", "f08", "f77", "f90", "f95", "for", "fpp", "ftn"); FSHARP.extension("fs"); GENIE.extension("gs"); GLSL.extensions("frag", "glsl", "vert"); GOLANG.extensions("go"); GROOVY.extension("groovy"); HAML.extension("haml"); HAXE.extension("hx"); HTML.extensions("htm", "html"); HASKELL.extensions("hs", "lhs"); JAM.filenames("Jamfile", "Jamrules"); JAVA.extension("java"); JAVASCRIPT.alias("js").extension("js"); JSP.extension("jsp"); KOTLIN.extensions("kt", "kts"); LIMBO.extensions("b", "m"); LOGTALK.extension("lgt"); LUA.extension("lua"); MAKE.filename("Makefile").extensions("mk", "pro"); MATHEMATICA.extensions("nb", "nbs"); METAPOST.extension("mp"); METAFONT.extensions("mf"); MODULA2.extensions("mod", "m2"); MODULA3.extensions("m3", "i3"); OBJECTIVE_C.extensions("m", "h"); OCAML.extensions("ml", "mli"); OCTAVE.extensions("m", "octave"); PASCAL.extensions("pas", "pp"); PERL.extensions("pl", "pm"); PHP.extensions("inc", "php", "phtml", "php4", "php3", "php5", "phps"); IDL_PVWAVE.extension("pro"); PROLOG.extension("pl"); PUPPET.extension("pp"); PYTHON.extension("py"); R.extension("r"); REBOL.extensions("r", "r3", "reb", "rebol"); REXX.extensions("cmd", "exec", "rexx"); RUBY.alias("jruby").extensions("rb", "ru").filenames("Rakefile", "Gemfile"); SCALA.extensions("scala", "sc"); SWIFT.extensions("swift"); SCHEME.extensions("scm", "ss"); SHELL.extensions("bash", "sh"); SMALLTALK.extension("st"); SQL.extension("sql"); STRUCTURED_BASIC.extensions("b", "bas", "bi"); TCL.extension("tcl"); TEX.extension("tex"); VB.extensions("bas", "frm", "frx", "vb", "vba"); VBSCRIPT.extensions("vbs", "vbe"); VIMSCRIPT.extension("vim").aliases("Vim Script", "VimL"); XML.extensions("asx", "csproj", "xml", "mxml"); XMLSCHEMA.extension("xsd"); XSLT.extensions("xsl", "xslt"); } private final String niceName; private final String category; private final Class<? extends Scanner> scannerClass; private final List<String> extensions; private final List<String> filenames; private final List<String> aliases; Language(String niceName, String category, Class<? extends Scanner> scannerClass) { this.niceName = niceName; this.category = category; this.scannerClass = scannerClass; extensions = new ArrayList<String>(); filenames = new ArrayList<String>(); aliases = new ArrayList<String>(); } public String uname() { return toString().toLowerCase(); } public String niceName() { return niceName; } public String category() { return category; } public Class<? extends Scanner> scannerClass() { return scannerClass; } public Scanner makeScanner() { try { Scanner scanner = scannerClass.newInstance(); scanner.setDefaultLanguage(this); return scanner; } catch (InstantiationException e) { throw new OhcountException(e); } catch (IllegalAccessException e) { throw new OhcountException(e); } } private Language extension(String ext) { extensions.add(ext); return this; } private Language extensions(String... exts) { for (String ext : exts) { extension(ext); } return this; } public List<String> getExtensions() { return new ArrayList<String>(extensions); } private Language filename(String filename) { filenames.add(filename); return this; } private Language filenames(String... filenames) { for (String filename : filenames) { filename(filename); } return this; } public List<String> getFilenames() { return new ArrayList<String>(filenames); } private Language alias(String alias) { aliases.add(alias); return this; } private Language aliases(String... aliases) { for (String alias : aliases) { alias(alias); } return this; } public List<String> getAliases() { return new ArrayList<String>(aliases); } }
apache-2.0
hroyrh/svt
logging_metrics_performance/enterprise_logging/test/manage_pods.sh
3905
#!/usr/bin/env bash # # Simple utility that uses ssh to check, run or kill the logger script # on every node of the cluster. # Automatically obtains the cluster nodes and writes them to a hostsfile. # NOTE: Runs in sequence not in paralell. # # # EXAMPLES: # # Runs 3 busybox containers per each node. # export TIMES=3; export MODE=1; ./manage_pods.sh -r 128 # # # Runs 5 standalone logger.sh processes logging forever # export TIMES=5; export MODE=2; ./manage_pods.sh -r 128 # # Both the above methods should log output to be picked up by the fluentd pods. # # # # Check for running pods. # export MODE=1; ./manage_pods.sh -c 1 # # # Run 5 pods in every node. # The argument to '-r' is the log line length. # This is the only arg that takes a value different than 1 # # export TIMES=5; export MODE=1; ./manage_pods.sh -r 250 # # Kill pods in every node. # export MODE=1; ./manage_pods.sh -k 1 # # Check pods. # export MODE=1; ./manage_pods.sh -c 1 # set -o pipefail if [[ `id -u` -ne 0 ]] then echo -e "Please run as root/sudo.\n" echo -e "Terminated." exit 1 fi SCRIPTNAME=$(basename ${0%.*}) SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" WORKDIR=$SCRIPTDIR HOSTSFILE=$WORKDIR/hostlist.txt declare -a NODELIST function cp_logger() { for host in ${NODELIST[@]} do scp $WORKDIR/logger.sh $host: done } function run_logger() { for host in ${NODELIST[@]} do echo -e "\n\n[+] Line length ${x}: $host" ssh -f $host "/root/logger.sh -r 60 -l ${x} -t ${TIMES} -m ${MODE}" done } function check_pods() { for host in ${NODELIST[@]} do ssh $host "echo $host; docker ps | grep busybox; echo" done } function kill_pods() { for host in ${NODELIST[@]} do echo -e "\n$host" ssh $host "docker kill \$(docker ps | grep busybox | awk '{print \$1}' ;echo)" done } function check_logger() { for host in ${NODELIST[@]} do echo -e "\n$host" ssh $host "ps -ef | grep [l]ogger.sh" done } function kill_logger() { for host in ${NODELIST[@]} do echo -e "\n$host" ssh $host "pkill -f logger.sh" done } function read_hosts() { hf=${1} while read line; do NODELIST+=($line); done < $hf } # MAIN if [[ -f $HOSTSFILE ]] then echo -e "Hosts file exists.\n" read_hosts $HOSTSFILE else echo "First run:" echo "Creating $HOSTSFILE ..." oc get nodes | awk '{print $1}' | grep -v 'NAME' > $HOSTSFILE [[ $? -eq 0 ]] && echo -e "Done.\n" || (echo 'Fatal: "oc get nodes failed."' ; exit 1) read_hosts $HOSTSFILE echo "Copying logger.sh to cluster nodes." cp_logger echo "Done." fi # for process mode if [[ ${MODE} -eq 2 ]]; then while getopts ":s:r:c:k:q:" option; do case "${option}" in s) x=${OPTARG} && [[ $x -eq 1 ]] && cp_logger ;; r) x=${OPTARG} if [[ $x -ne 0 ]]; then while [ ${TIMES} -ne 0 ] do run_logger $x ((TIMES--)) done fi ;; c) x=${OPTARG} && [[ $x -eq 1 ]] && check_logger ;; k) x=${OPTARG} && [[ $x -eq 1 ]] && kill_logger ;; q) x=${OPTARG} && [[ $x -eq 1 ]] && kill_logger ;; '*') echo -e "Invalid option / usage: ${option}\nExiting." exit 1 ;; esac done shift $((OPTIND-1)) fi # container mode if [[ ${MODE} -eq 1 ]]; then while getopts ":s:r:c:k:q:" option; do case "${option}" in s) x=${OPTARG} && [[ $x -eq 1 ]] && cp_logger ;; r) x=${OPTARG} && [[ $x -ne 0 ]] && run_logger $x ;; c) x=${OPTARG} && [[ $x -eq 1 ]] && check_pods ;; k) x=${OPTARG} && [[ $x -eq 1 ]] && kill_pods ;; q) x=${OPTARG} && [[ $x -eq 1 ]] && kill_logger ;; '*') echo -e "Invalid option / usage: ${option}\nExiting." exit 1 ;; esac done shift $((OPTIND-1)) fi echo -e "\nDone." exit 0
apache-2.0
Appleseed/learn
README.md
168
# Learn Appleseed Read the Docs (RTD) repository for Appleseed Framework documentation. ![Appleseed Framework 2017](assets/SM.RD.Appleseed.Framework.Diagram.2017.png)
apache-2.0
RobertSzarejko/WebSecurityForBackendDev
web-security-demo/src/main/java/pl/itdonat/demo/wsfbd/encryption/CryptoController.java
1419
package pl.itdonat.demo.wsfbd.encryption; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import pl.itdonat.demo.wsfbd.encryption.encode.EncodeData; import pl.itdonat.demo.wsfbd.encryption.encode.EncodeService; import java.util.List; /** * Created by r.szarejko on 2017-03-22. */ @Controller @RequestMapping("/crypto") public class CryptoController { private final EncodeService encodeService; public CryptoController(EncodeService encodeService) { this.encodeService = encodeService; } @GetMapping public String get(Model model){ model.addAttribute("plainText", ""); return "crypto"; } @PostMapping public String post(Model model, @RequestParam String plainText){ List<EncodeData> encodeData = encodeService.prepareEncodedValueByAlgorithmMap(plainText); model.addAttribute("valueList", encodeData); model.addAttribute("plainText", plainText); return "crypto"; } @PostMapping("/broke") @ResponseBody public String postBroke(@RequestParam String hash, @RequestParam Algorithm algorithm){ String bruteForce = encodeService.bruteForce(hash, algorithm); return bruteForce; } @GetMapping("/broke1") @ResponseBody public String postBroke(Model model){ return "7654321"; } }
apache-2.0
dldinternet/chefrepo-builder
README.md
59
chefrepo-builder ================ Chef Repo CI/CD builder
apache-2.0
asakusafw/asakusafw
operator/core/src/main/java/com/asakusafw/operator/Constants.java
8005
/** * Copyright 2011-2021 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.operator; import java.text.MessageFormat; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import javax.annotation.Generated; import javax.lang.model.SourceVersion; import com.asakusafw.operator.description.AnnotationDescription; import com.asakusafw.operator.description.ClassDescription; import com.asakusafw.operator.description.Descriptions; import com.asakusafw.operator.description.ValueDescription; /** * Available constant values in this project. * @since 0.9.0 * @version 0.9.1 */ public final class Constants { private static final String BASE = "com.asakusafw.vocabulary."; //$NON-NLS-1$ private static ClassDescription classOf(String name) { return new ClassDescription(BASE + name); } /** * {@code OperatorHelper} annotation type name. */ public static final ClassDescription TYPE_ANNOTATION_HELPER = classOf("operator.OperatorHelper"); //$NON-NLS-1$ /** * {@code In} type name. */ public static final ClassDescription TYPE_IN = classOf("flow.In"); //$NON-NLS-1$ /** * {@code Out} type name. */ public static final ClassDescription TYPE_OUT = classOf("flow.Out"); //$NON-NLS-1$ /** * {@code Source} type name. */ public static final ClassDescription TYPE_SOURCE = classOf("flow.Source"); //$NON-NLS-1$ /** * {@code View} type name. * @since 0.9.1 */ public static final ClassDescription TYPE_VIEW = new ClassDescription("com.asakusafw.runtime.core.View"); //$NON-NLS-1$ /** * {@code GroupView} type name. * @since 0.9.1 */ public static final ClassDescription TYPE_GROUP_VIEW = new ClassDescription("com.asakusafw.runtime.core.GroupView"); //$NON-NLS-1$ /** * {@code Result} type name. */ public static final ClassDescription TYPE_RESULT = new ClassDescription("com.asakusafw.runtime.core.Result"); //$NON-NLS-1$ /** * {@code Key} type name. */ public static final ClassDescription TYPE_KEY = classOf("model.Key"); //$NON-NLS-1$ /** * {@code Joined} type name. */ public static final ClassDescription TYPE_JOINED = classOf("model.Joined"); //$NON-NLS-1$ /** * {@code Summarized} type name. */ public static final ClassDescription TYPE_SUMMARIZED = classOf("model.Summarized"); //$NON-NLS-1$ /** * {@code FlowPart} annotation type name. */ public static final ClassDescription TYPE_FLOW_PART = classOf("flow.FlowPart"); //$NON-NLS-1$ /** * {@code FlowDescription} type name. */ public static final ClassDescription TYPE_FLOW_DESCRIPTION = classOf("flow.FlowDescription"); //$NON-NLS-1$ /** * {@code Import} type name. */ public static final ClassDescription TYPE_IMPORT = classOf("flow.Import"); //$NON-NLS-1$ /** * {@code Export} type name. */ public static final ClassDescription TYPE_EXPORT = classOf("flow.Export"); //$NON-NLS-1$ /** * {@code ImporterDescription} type name. */ public static final ClassDescription TYPE_IMPORTER_DESC = classOf("external.ImporterDescription"); //$NON-NLS-1$ /** * {@code ExporterDescription} type name. */ public static final ClassDescription TYPE_EXPORTER_DESC = classOf("external.ExporterDescription"); //$NON-NLS-1$ /** * {@code FlowElementBuilder} type name. */ public static final ClassDescription TYPE_ELEMENT_BUILDER = classOf("flow.builder.FlowElementBuilder"); //$NON-NLS-1$ /** * singleton name of flow-part factory method. */ public static final String NAME_FLOW_PART_FACTORY_METHOD = "create"; //$NON-NLS-1$ /** * Simple name pattern for operator implementation class (0: simple name of operator class). */ private static final String PATTERN_IMPLEMENTATION_CLASS = "{0}Impl"; //$NON-NLS-1$ /** * Simple name pattern for operator factory class (0: simple name of operator/flow-part class). */ private static final String PATTERN_FACTORY_CLASS = "{0}Factory"; //$NON-NLS-1$ /** * Simple name pattern for built-in operator annotation class (0: simple name). */ private static final String PATTERN_BUILTIN_OPERATOR_ANNOTATION_CLASS = BASE + "operator.{0}"; //$NON-NLS-1$ /** * The generator ID. */ public static final String GENERATOR_ID = "com.asakusafw.operator"; //$NON-NLS-1$ /** * The generator name. */ public static final String GENERATOR_NAME = "Asakusa Operator DSL Compiler"; //$NON-NLS-1$ /** * The generator version. */ public static final String GENERATOR_VERSION = "3.0.0"; //$NON-NLS-1$ /** * Returns the implementation class name of target class with the specified name. * @param simpleName the simple class name of the operator annotation * @return qualified name * @throws IllegalArgumentException if some parameters were {@code null} */ public static ClassDescription getBuiltinOperatorClass(String simpleName) { Objects.requireNonNull(simpleName, "simpleName must not be null"); //$NON-NLS-1$ return new ClassDescription(MessageFormat.format(PATTERN_BUILTIN_OPERATOR_ANNOTATION_CLASS, simpleName)); } /** * Returns the implementation class name of target class with the specified name. * @param originalName the original class name * @return related implementation class name * @throws IllegalArgumentException if some parameters were {@code null} */ public static ClassDescription getImplementationClass(CharSequence originalName) { Objects.requireNonNull(originalName, "originalName must not be null"); //$NON-NLS-1$ return new ClassDescription(MessageFormat.format(PATTERN_IMPLEMENTATION_CLASS, originalName)); } /** * Returns the factory class name of target class with the specified name. * @param originalName the original class name * @return related factory class name * @throws IllegalArgumentException if some parameters were {@code null} */ public static ClassDescription getFactoryClass(CharSequence originalName) { Objects.requireNonNull(originalName, "originalName must not be null"); //$NON-NLS-1$ return new ClassDescription(MessageFormat.format(PATTERN_FACTORY_CLASS, originalName)); } /** * Returns the current supported source version. * @return the supported version */ public static SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } /** * Returns {@link Generated} annotation. * @return the annotation */ public static AnnotationDescription getGenetedAnnotation() { Map<String, ValueDescription> elements = new LinkedHashMap<>(); elements.put("value", Descriptions.valueOf(new String[] { //$NON-NLS-1$ GENERATOR_ID })); elements.put("comments", //$NON-NLS-1$ Descriptions.valueOf(MessageFormat.format( "generated by {0} {1}", //$NON-NLS-1$ GENERATOR_NAME, GENERATOR_VERSION))); return new AnnotationDescription(Descriptions.classOf(Generated.class), elements); } private Constants() { return; } }
apache-2.0
centreon/centreon-plugins
network/audiocodes/snmp/mode/memory.pm
3052
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::audiocodes::snmp::mode::memory; use base qw(centreon::plugins::templates::counter); use strict; use warnings; sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0, message_separator => ' - ' }, ]; $self->{maps_counters}->{global} = [ { label => 'voip', nlabel => 'memory.voip.utilization.percentage', set => { key_values => [ { name => 'voip' } ], output_template => 'Memory VoIp Usage : %.2f %%', perfdatas => [ { label => 'used_voip', value => 'voip', template => '%.2f', min => 0, max => 100, unit => '%' }, ], } }, { label => 'data', nlabel => 'memory.data.utilization.percentage', set => { key_values => [ { name => 'data' } ], output_template => 'Memory Data Usage : %.2f %%', perfdatas => [ { label => 'used_data', value => 'data', template => '%.2f', min => 0, max => 100, unit => '%' }, ], } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { }); return $self; } sub manage_selection { my ($self, %options) = @_; my $oid_acSysStateVoIpMemoryUtilization = '.1.3.6.1.4.1.5003.9.10.10.2.5.11.0'; my $oid_acSysStateDataMemoryUtilization = '.1.3.6.1.4.1.5003.9.10.10.2.5.9.0'; my $snmp_result = $options{snmp}->get_leef(oids => [ $oid_acSysStateVoIpMemoryUtilization, $oid_acSysStateDataMemoryUtilization ], nothing_quit => 1); $self->{global} = { data => $snmp_result->{$oid_acSysStateDataMemoryUtilization}, voip => $snmp_result->{$oid_acSysStateVoIpMemoryUtilization} }; } 1; __END__ =head1 MODE Check memory usages. =over 8 =item B<--filter-counters> Only display some counters (regexp can be used). Example: --filter-counters='^voip$' =item B<--warning-*> Threshold warning. Can be: 'voip', 'data'. =item B<--critical-*> Threshold critical. Can be: 'voip', 'data'. =back =cut
apache-2.0
imclab/liz
client/dev.html
3141
<!doctype html> <html> <head> <title>Liz - easy scheduling</title> <link rel="shortcut icon" href="favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="/node_modules/bootflat/bootflat/css/bootflat.min.css"> <link rel="stylesheet" href="/node_modules/selectize/dist/css/selectize.bootstrap3.css"> <link rel="stylesheet" href="app.css"> <script src="/node_modules/es5-shim/es5-shim.min.js"></script> <script src="/node_modules/es6-shim/es6-shim.min.js"></script> <script src="/node_modules/lodash/dist/lodash.min.js"></script> <script src="/node_modules/jquery/dist/jquery.min.js"></script> <script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script> <!--<script src="/node_modules/bootflat/bootflat/js/icheck.min.js"></script>--> <!--<script src="/node_modules/bootflat/bootflat/js/jquery.fs.selecter.min.js"></script>--> <!--<script src="/node_modules/bootflat/bootflat/js/jquery.fs.stepper.min.js"></script>--> <script src="/node_modules/moment/min/moment.min.js"></script> <script src="/node_modules/promise-js/promise.js"></script> <script src="/node_modules/uuid-v4.js/uuid-v4.min.js"></script> <script src="/node_modules/juration/juration.js"></script> <script src="/node_modules/react/dist/react.js"></script> <script src="/node_modules/react/dist/JSXTransformer.js"></script> <script src="/assets/react-checkbox-group/react-checkbox-group.jsx" type="text/jsx"></script> <!--<script src="assets/react-radiogroup/react-radiogroup.jsx" type="text/jsx"></script>--> <script src="/node_modules/selectize/dist/js/standalone/selectize.js"></script> <script src="assets/selectize/Selectize.jsx" type="text/jsx"></script> <script src="/shared/intervals.js"></script> <script src="util/queryparams.js"></script> <script src="util/hash.js"></script> <script src="util/ajax.js"></script> <script src="util/util.js"></script> <script type="text/jsx" src="components/Calendar.jsx"></script> <script type="text/jsx" src="components/CalendarList.jsx"></script> <script type="text/jsx" src="components/EventList.jsx"></script> <script type="text/jsx" src="components/EventScheduler.jsx"></script> <script type="text/jsx" src="components/Menu.jsx"></script> <script type="text/jsx" src="components/TimeslotList.jsx"></script> <script type="text/jsx" src="components/Profile.jsx"></script> <script type="text/jsx" src="components/EventGenerator.jsx"></script> <script type="text/jsx" src="pages/App.jsx"></script> <script type="text/jsx" src="pages/HomePage.jsx"></script> <script type="text/jsx" src="pages/CalendarPage.jsx"></script> <script type="text/jsx" src="pages/SettingsPage.jsx"></script> <script type="text/jsx" src="app.jsx"></script> </head> <body> <div id="page"> <a id="header" href="dev.html"> <img src="img/calendar-icon.png" width="48" height="48" style="vertical-align: middle;"> Liz </a> <div id="app"></div> <div id="errors"></div> </div> </body> </html>
apache-2.0
fungku/netsuite-php
src/Classes/FairValuePriceSearchBasic.php
2206
<?php /** * This file is part of the SevenShores/NetSuite library * AND originally from the NetSuite PHP Toolkit. * * New content: * @package ryanwinchester/netsuite-php * @copyright Copyright (c) Ryan Winchester * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 * @link https://github.com/ryanwinchester/netsuite-php * * Original content: * @copyright Copyright (c) NetSuite Inc. * @license https://raw.githubusercontent.com/ryanwinchester/netsuite-php/master/original/NetSuite%20Application%20Developer%20License%20Agreement.txt * @link http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml * * generated: 2019-06-12 10:27:00 AM PDT */ namespace NetSuite\Classes; class FairValuePriceSearchBasic extends SearchRecordBasic { public $currency; public $endDate; public $externalId; public $externalIdString; public $fairValue; public $fairValueFormula; public $fairValueRangePolicy; public $highValue; public $highValuePercent; public $internalId; public $internalIdNumber; public $isVsoePrice; public $item; public $itemRevenueCategory; public $lowValue; public $lowValuePercent; public $startDate; public $unitsType; static $paramtypesmap = array( "currency" => "SearchMultiSelectField", "endDate" => "SearchDateField", "externalId" => "SearchMultiSelectField", "externalIdString" => "SearchStringField", "fairValue" => "SearchDoubleField", "fairValueFormula" => "SearchMultiSelectField", "fairValueRangePolicy" => "SearchEnumMultiSelectField", "highValue" => "SearchDoubleField", "highValuePercent" => "SearchDoubleField", "internalId" => "SearchMultiSelectField", "internalIdNumber" => "SearchLongField", "isVsoePrice" => "SearchBooleanField", "item" => "SearchMultiSelectField", "itemRevenueCategory" => "SearchMultiSelectField", "lowValue" => "SearchDoubleField", "lowValuePercent" => "SearchDoubleField", "startDate" => "SearchDateField", "unitsType" => "SearchMultiSelectField", ); }
apache-2.0
ulpian/Suuta
build/iphone/Classes/TiViewController.h
2485
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2011 by testio, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. * * WARNING: This is generated code. Modify at your own risk and without support. */ #import "TiViewProxy.h" /** The protocol for view controllers. */ @protocol TiUIViewController @required /** Returns the child view controller, if any. @return The child view controller. */ - (UIViewController *)childViewController; /** Tells the view controller that its view will appear. Called when the view is about to made visible. @param animated The animation flag. */ - (void)viewWillAppear:(BOOL)animated; /** Tells the view controller that its view did appear. Called when the view has been fully transitioned onto the screen. @param animated The animation flag. */ - (void)viewDidAppear:(BOOL)animated; /** Tells the view controller that its view will disappear. Called when the view is dismissed, covered or otherwise hidden. @param animated The animation flag. */ - (void)viewWillDisappear:(BOOL)animated; /** Tells the view controller that its view did disappear. Called after the view was dismissed, covered or otherwise hidden. @param animated The animation flag. */ - (void)viewDidDisappear:(BOOL)animated; @optional /** Tells the view controller that its view will be rotated to interface orientation. @param toInterfaceOrientation The target interface orientation. @param duration The duration of the rotation animation. */ - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration; /** Tells the view controller to ignore rotation to specified orientation. @param orientation The orientation to ignore. */ -(void)ignoringRotationToOrientation:(UIInterfaceOrientation)orientation; @end /** The base class for testio view controllers. */ @interface TiViewController : UIViewController { TiViewProxy<TiUIViewController> *proxy; } /** Initialize the view controller with the provided view proxy. @param window The view proxy associated with the view controller. @return A new view controller. */ -(id)initWithViewProxy:(TiViewProxy<TiUIViewController>*)window; /** Provides access to view proxy associated with the view controller. */ @property(nonatomic,readwrite,assign) TiViewProxy<TiUIViewController> *proxy; @end
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Inula ciliaris/Erigeron myosotis humile/README.md
187
# Erigeron myosotis var. humile Sch.Bip VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Camphorina/Camphorina cinnamomum/README.md
177
# Camphorina cinnamomum Farw. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
metatron-app/metatron-discovery
discovery-server/src/main/java/app/metatron/discovery/common/ResultSetSerializer.java
6631
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.metatron.discovery.common; import com.facebook.presto.jdbc.PrestoArray; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; /** * Created by kyungtaak on 2016. 10. 11.. */ public class ResultSetSerializer extends JsonSerializer<ResultSet> { public static class ResultSetSerializerException extends JsonProcessingException { private static final long serialVersionUID = -914957626413580734L; public ResultSetSerializerException(Throwable cause) { super(cause); } } @Override public Class<ResultSet> handledType() { return ResultSet.class; } @Override public void serialize(ResultSet rs, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { try { ResultSetMetaData rsmd = rs.getMetaData(); int numColumns = rsmd.getColumnCount(); String[] columnNames = new String[numColumns]; int[] columnTypes = new int[numColumns]; for (int i = 0; i < columnNames.length; i++) { columnNames[i] = rsmd.getColumnLabel(i + 1); columnTypes[i] = rsmd.getColumnType(i + 1); } jgen.writeStartArray(); while (rs.next()) { boolean b; long l; double d; jgen.writeStartObject(); for (int i = 0; i < columnNames.length; i++) { jgen.writeFieldName(columnNames[i]); switch (columnTypes[i]) { case Types.INTEGER: l = rs.getInt(i + 1); if (rs.wasNull()) { jgen.writeNull(); } else { jgen.writeNumber(l); } break; case Types.BIGINT: l = rs.getLong(i + 1); if (rs.wasNull()) { jgen.writeNull(); } else { jgen.writeNumber(l); } break; case Types.DECIMAL: case Types.NUMERIC: jgen.writeNumber(rs.getBigDecimal(i + 1)); break; case Types.FLOAT: case Types.REAL: case Types.DOUBLE: d = rs.getDouble(i + 1); if (rs.wasNull()) { jgen.writeNull(); } else { jgen.writeNumber(d); } break; case Types.NVARCHAR: case Types.VARCHAR: case Types.LONGNVARCHAR: case Types.LONGVARCHAR: jgen.writeString(rs.getString(i + 1)); break; case Types.BOOLEAN: case Types.BIT: b = rs.getBoolean(i + 1); if (rs.wasNull()) { jgen.writeNull(); } else { jgen.writeBoolean(b); } break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: jgen.writeBinary(rs.getBytes(i + 1)); break; case Types.TINYINT: case Types.SMALLINT: l = rs.getShort(i + 1); if (rs.wasNull()) { jgen.writeNull(); } else { jgen.writeNumber(l); } break; case Types.DATE: Date date = rs.getDate(i + 1); if(date == null) { jgen.writeNull(); } else { provider.defaultSerializeDateValue(rs.getDate(i + 1), jgen); } break; case Types.TIME: case Types.TIME_WITH_TIMEZONE: Time time = rs.getTime(i + 1); if(time == null) { jgen.writeNull(); } else { provider.defaultSerializeDateValue(rs.getTime(i + 1), jgen); } break; case Types.TIMESTAMP: case Types.TIMESTAMP_WITH_TIMEZONE: Timestamp ts = rs.getTimestamp(i + 1); if(ts == null) { jgen.writeNull(); } else { provider.defaultSerializeDateValue(rs.getTimestamp(i + 1), jgen); } break; case Types.BLOB: Blob blob = rs.getBlob(i); provider.defaultSerializeValue(blob.getBinaryStream(), jgen); blob.free(); break; case Types.CLOB: Clob clob = rs.getClob(i); provider.defaultSerializeValue(clob.getCharacterStream(), jgen); clob.free(); break; case Types.ARRAY: if(rs.getObject(i + 1) instanceof PrestoArray) { provider.defaultSerializeValue(((PrestoArray) rs.getObject(i + 1)).getArray(), jgen); } else { provider.defaultSerializeValue(rs.getArray(i + 1), jgen); } break; case Types.STRUCT: throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type STRUCT"); case Types.DISTINCT: throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type DISTINCT"); case Types.REF: throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type REF"); case Types.JAVA_OBJECT: default: provider.defaultSerializeValue(rs.getObject(i + 1), jgen); break; } } jgen.writeEndObject(); } jgen.writeEndArray(); } catch (SQLException e) { throw new ResultSetSerializerException(e); } } }
apache-2.0
YAFNET/YAFNET
yafsrc/YetAnotherForum.NET/Controls/EditUsersInfo.ascx.designer.cs
14587
//------------------------------------------------------------------------------ // <automatisch generiert> // Dieser Code wurde von einem Tool generiert. // // Änderungen an dieser Datei können fehlerhaftes Verhalten verursachen und gehen verloren, wenn // der Code neu generiert wird. // </automatisch generiert> //------------------------------------------------------------------------------ namespace YAF.Controls { public partial class EditUsersInfo { /// <summary> /// LocalizedLabel1-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.LocalizedLabel LocalizedLabel1; /// <summary> /// HelpLabel1-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel1; /// <summary> /// Name-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Name; /// <summary> /// HelpLabel2-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel2; /// <summary> /// DisplayName-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.TextBox DisplayName; /// <summary> /// HelpLabel3-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel3; /// <summary> /// Email-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Email; /// <summary> /// HelpLabel4-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel4; /// <summary> /// RankID-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList RankID; /// <summary> /// IsHostAdminRow-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder IsHostAdminRow; /// <summary> /// HelpLabel15-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel15; /// <summary> /// Moderated-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox Moderated; /// <summary> /// HelpLabel5-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel5; /// <summary> /// IsHostAdminX-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox IsHostAdminX; /// <summary> /// IsCaptchaExcludedRow-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder IsCaptchaExcludedRow; /// <summary> /// HelpLabel6-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel6; /// <summary> /// IsCaptchaExcluded-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox IsCaptchaExcluded; /// <summary> /// IsExcludedFromActiveUsersRow-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder IsExcludedFromActiveUsersRow; /// <summary> /// HelpLabel7-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel7; /// <summary> /// IsExcludedFromActiveUsers-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox IsExcludedFromActiveUsers; /// <summary> /// HelpLabel8-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel8; /// <summary> /// IsApproved-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox IsApproved; /// <summary> /// ApproveHolder-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder ApproveHolder; /// <summary> /// ApproveUser-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.ThemeButton ApproveUser; /// <summary> /// DisabledHolder-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder DisabledHolder; /// <summary> /// HelpLabel16-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel16; /// <summary> /// UnDisableUser-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox UnDisableUser; /// <summary> /// IsGuestRow-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder IsGuestRow; /// <summary> /// HelpLabel9-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel9; /// <summary> /// IsGuestX-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox IsGuestX; /// <summary> /// HelpLabel10-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel10; /// <summary> /// Joined-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.TextBox Joined; /// <summary> /// HelpLabel11-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel11; /// <summary> /// LastVisit-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.TextBox LastVisit; /// <summary> /// HelpLabel12-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel12; /// <summary> /// IsFacebookUser-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox IsFacebookUser; /// <summary> /// HelpLabel13-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel13; /// <summary> /// IsTwitterUser-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox IsTwitterUser; /// <summary> /// HelpLabel14-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.HelpLabel HelpLabel14; /// <summary> /// IsGoogleUser-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::System.Web.UI.WebControls.CheckBox IsGoogleUser; /// <summary> /// Save-Steuerelement. /// </summary> /// <remarks> /// Automatisch generiertes Feld. /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben. /// </remarks> protected global::YAF.Web.Controls.ThemeButton Save; } }
apache-2.0
dcos/dcos-ui
src/js/components/modals/FullScreenModalHeaderActions.tsx
1285
import { Trans } from "@lingui/macro"; import classNames from "classnames/dedupe"; import * as React from "react"; type Action = { className?: string; clickHandler?: (e?: any) => void; disabled?: boolean; label?: string; node?: React.ReactNode; }; class FullScreenModalHeaderActions extends React.Component<{ actions: Action[]; className?: string; type: "primary" | "secondary"; }> { getActions() { const { actions } = this.props; if (!actions || actions.length === 0) { return null; } return actions.map( ({ className, clickHandler, label, node, disabled }, index) => { if (node) { return node; } const classes = classNames("button flush-top", className); return ( <button className={classes} disabled={disabled} key={index} onClick={clickHandler} > <Trans id={label} /> </button> ); } ); } render() { const classes = classNames( `modal-full-screen-actions modal-full-screen-actions-${this.props.type} flush-vertical`, this.props.className ); return <div className={classes}>{this.getActions()}</div>; } } export default FullScreenModalHeaderActions;
apache-2.0
mineral-ui/mineral-ui
packages/mineral-ui-icons/src/IconExposurePlus1.js
553
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconExposurePlus1(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M10 7H8v4H4v2h4v4h2v-4h4v-2h-4V7zm10 11h-2V7.38L15 8.4V6.7L19.7 5h.3v13z"/> </g> </Icon> ); } IconExposurePlus1.displayName = 'IconExposurePlus1'; IconExposurePlus1.category = 'image';
apache-2.0
resin-io-library/base-images
balena-base-images/node/apalis-imx6q/ubuntu/bionic/17.6.0/build/Dockerfile
2757
# AUTOGENERATED FILE FROM balenalib/apalis-imx6q-ubuntu:bionic-build ENV NODE_VERSION 17.6.0 ENV YARN_VERSION 1.22.4 RUN for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "31786cf6387c85a34f1eb85be5838facaad40f50f61030557e42a4af4bb31294 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu bionic \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v17.6.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
apache-2.0
madhanhere/android-utils
README.md
436
# android-utils A simple android library for validate EditText, check internet connection and show Toast. Features: * To check internet connection. * Validation for empty EditText boxes. * Validation for mobile number. * Validate EditText values against user defined patterns (e.g mobile number patterns). * Validate length of EditText values. * Validation for special characters in EditText values. * To show Toast messages.
apache-2.0
Pokevian/caroolive-app
app/src/main/java/com/pokevian/app/smartfleet/service/floatinghead/TtsHandler.java
4562
/* * Copyright (c) 2015. Pokevian Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pokevian.app.smartfleet.service.floatinghead; import android.content.Context; import android.os.Build; import android.speech.tts.TextToSpeech; import android.speech.tts.UtteranceProgressListener; import org.apache.log4j.Logger; import java.util.HashMap; import java.util.Locale; /** * Created by dg.kim on 2015-04-13. */ public class TtsHandler { private static final String TAG = "TtsHandler"; private TextToSpeech mTts; private final Callbacks mCallbacks; public TtsHandler(Context context, Callbacks callbacks) { mTts = new TextToSpeech(context, new TtsInitListener()); mCallbacks = callbacks; } public void shutdown() { if (mTts != null) { mTts.stop(); mTts.shutdown(); mTts = null; } } public boolean speak(CharSequence text) { if (mTts != null) { String utteranceId = String.valueOf(Math.random()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId); } else { HashMap<String, String> params = new HashMap<>(); params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId); mTts.speak(text.toString(), TextToSpeech.QUEUE_FLUSH, params); } mCallbacks.onTtsStart(utteranceId); return true; } else { return false; } } public void stopSpeak() { if (mTts != null && mTts.isSpeaking()) { mTts.stop(); } } private void setUtteranceListener() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { mTts.setOnUtteranceProgressListener(new UtteranceProgressListener() { @Override public void onStart(String utteranceId) { Logger.getLogger(TAG).info("tts start"); } @Override public void onDone(String utteranceId) { Logger.getLogger(TAG).info("tts done"); mCallbacks.onTtsDone(utteranceId); } @Override public void onError(String utteranceId) { Logger.getLogger(TAG).info("tts error"); mCallbacks.onTtsDone(utteranceId); } }); } else { mTts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() { @Override public void onUtteranceCompleted(String utteranceId) { Logger.getLogger(TAG).info("tts done"); mCallbacks.onTtsDone(utteranceId); } }); } } private class TtsInitListener implements TextToSpeech.OnInitListener { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = mTts.setLanguage(Locale.getDefault()); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Logger.getLogger(TAG).warn(Locale.getDefault() + " is not supported!"); mTts.shutdown(); mTts = null; mCallbacks.onTtsInit(false); } else { Logger.getLogger(TAG).warn(Locale.getDefault() + "TTS initialized"); setUtteranceListener(); mCallbacks.onTtsInit(true); } } else { Logger.getLogger(TAG).warn(Locale.getDefault() + "failed to initialize TTS"); } } } public interface Callbacks { void onTtsInit(boolean result); void onTtsStart(String utteranceId); void onTtsDone(String utteranceId); } }
apache-2.0
riganti/infrastructure
src/Infrastructure/Tests/Riganti.Utils.Infrastructure.EntityFramework.Tests/Repository/EntityFrameworkRepositoryTests.cs
10020
using System.Data.Entity; using System.Linq; using Moq; using Riganti.Utils.Infrastructure.Core; using Xunit; namespace Riganti.Utils.Infrastructure.EntityFramework.Tests.Repository { public class EntityFrameworkRepositoryTests { private static readonly EpisodeEntity[] episodesSeriesOne = { new EpisodeEntity {Id = 1, Series = 1, Title = "Open Government"}, new EpisodeEntity {Id = 2, Series = 1, Title = "The Official Visit"}, new EpisodeEntity {Id = 3, Series = 1, Title = "The Economy Drive"}, new EpisodeEntity {Id = 4, Series = 1, Title = "Big Brother"}, new EpisodeEntity {Id = 5, Series = 1, Title = "The Writing on the Wall"}, new EpisodeEntity {Id = 6, Series = 1, Title = "The Right to Know"}, new EpisodeEntity {Id = 7, Series = 1, Title = "Jobs for the Boys"} }; private static readonly QuoteEntity[] quotes = { new QuoteEntity {Id = 1, Text = " It is not for a humble mortal such as I to speculate on the complex and elevated deliberations of the mighty."}, }; private readonly Mock<YesMinisterDbContext> dbContextMock; private readonly EntityFrameworkRepository<EpisodeEntity, int> episodeRepositorySUT; private readonly EntityFrameworkRepository<QuoteEntity, int> quoteRepositorySUT; private readonly Mock<IDbSet<EpisodeEntity>> episodesDbSetMock; private readonly Mock<IDbSet<QuoteEntity>> quotesDbSetMock; public EntityFrameworkRepositoryTests() { var dbContextMockFactory = new DbContextMockFactory(); dbContextMock = dbContextMockFactory.CreateDbContextMock<YesMinisterDbContext>(); episodesDbSetMock = dbContextMock.SetupDbSet<YesMinisterDbContext, EpisodeEntity, int>(episodesSeriesOne, context => context.Episodes); quotesDbSetMock = dbContextMock.SetupDbSet<YesMinisterDbContext, QuoteEntity, int>(quotes, context => context.Quotes); episodeRepositorySUT = CreateEntityFrameworkRepository<EpisodeEntity>(); quoteRepositorySUT = CreateEntityFrameworkRepository<QuoteEntity>(); } [Fact] public void InitializeNew_ReturnsNotNullItem() { var newEpisode = episodeRepositorySUT.InitializeNew(); Assert.NotNull(newEpisode); } [Fact] public void Insert_OneItem_CallDbSetAddMethod() { var newEpisode = new EpisodeEntity { Id = 10, Title = "Inserted item" }; episodeRepositorySUT.Insert(newEpisode); episodesDbSetMock.Verify(set => set.Add(newEpisode), Times.Once); } [Fact] public void Insert_MultipleItems_NewItemShouldBeInDbSetLocal() { var newEpisode1 = new EpisodeEntity { Id = 10, Title = "Inserted item 1" }; var newEpisode2 = new EpisodeEntity { Id = 11, Title = "Inserted item 2" }; var newEpisode3 = new EpisodeEntity { Id = 12, Title = "Inserted item 3" }; var newEpisodes = new[] { newEpisode1, newEpisode2, newEpisode3 }; episodeRepositorySUT.Insert(newEpisodes); Assert.Contains(newEpisode1, episodesDbSetMock.Object.Local); Assert.Contains(newEpisode2, episodesDbSetMock.Object.Local); Assert.Contains(newEpisode3, episodesDbSetMock.Object.Local); } [Fact] public void Delete_OneItem_SetEntityStateToModified() { var deletedEpisode = episodesSeriesOne[1]; episodeRepositorySUT.Delete(deletedEpisode); Assert.DoesNotContain(deletedEpisode, episodesDbSetMock.Object.Local); } [Fact] public void Delete_MultipleItems_SetEntityStateToModified() { var deletedEpisode1 = episodesSeriesOne[1]; var deletedEpisode2 = episodesSeriesOne[2]; var deletedEpisode3 = episodesSeriesOne[3]; var deletedEpisodes = new[] { deletedEpisode1, deletedEpisode2, deletedEpisode3 }; episodeRepositorySUT.Delete(deletedEpisodes); Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local); Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local); Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local); } [Fact] public void DeleteById_OneItem_ShouldDeleteItemFromDbSetLocal() { var deletedEpisode = episodesSeriesOne[1]; episodeRepositorySUT.Delete(deletedEpisode.Id); Assert.DoesNotContain(deletedEpisode, episodesDbSetMock.Object.Local); } [Fact] public void DeleteById_OneItem_ShouldCallRemove() { var deletedEpisode = episodesSeriesOne[1]; episodeRepositorySUT.Delete(deletedEpisode.Id); episodesDbSetMock.Verify(set => set.Remove(It.Is<EpisodeEntity>(entity => entity.Id == deletedEpisode.Id)), Times.Once); } [Fact] public void DeleteById_MultipleItems_SetEntityStateToModified() { var deletedEpisode1 = episodesSeriesOne[1]; var deletedEpisode2 = episodesSeriesOne[2]; var deletedEpisode3 = episodesSeriesOne[3]; var deletedEpisodesIds = new[] { deletedEpisode1.Id, deletedEpisode2.Id, deletedEpisode3.Id }; episodeRepositorySUT.Delete(deletedEpisodesIds); Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local); Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local); Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local); } [Fact] public void SoftDelete_OneItem_SetDeletedDate() { var deletedQuote = quotes[0]; quoteRepositorySUT.Delete(deletedQuote); var quoteById = quoteRepositorySUT.GetById(deletedQuote.Id); Assert.NotNull(quoteById.DeletedDate); } [Fact] public void SoftDelete_MultipleItems_SetEntityStateToModified() { var deletedEpisode1 = episodesSeriesOne[1]; var deletedEpisode2 = episodesSeriesOne[2]; var deletedEpisode3 = episodesSeriesOne[3]; var deletedEpisodes = new[] { deletedEpisode1, deletedEpisode2, deletedEpisode3 }; episodeRepositorySUT.Delete(deletedEpisodes); Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local); Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local); Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local); } [Fact] public void SoftDeleteById_OneItem_ShouldDeleteItemFromDbSetLocal() { var deletedEpisode = episodesSeriesOne[1]; episodeRepositorySUT.Delete(deletedEpisode.Id); Assert.DoesNotContain(deletedEpisode, episodesDbSetMock.Object.Local); } [Fact] public void SoftDeleteById_OneItem_ShouldCallRemove() { var deletedEpisode = episodesSeriesOne[1]; episodeRepositorySUT.Delete(deletedEpisode.Id); episodesDbSetMock.Verify(set => set.Remove(It.Is<EpisodeEntity>(entity => entity.Id == deletedEpisode.Id)), Times.Once); } [Fact] public void SoftDeleteById_MultipleItems_SetEntityStateToModified() { var deletedEpisode1 = episodesSeriesOne[1]; var deletedEpisode2 = episodesSeriesOne[2]; var deletedEpisode3 = episodesSeriesOne[3]; var deletedEpisodesIds = new[] { deletedEpisode1.Id, deletedEpisode2.Id, deletedEpisode3.Id }; episodeRepositorySUT.Delete(deletedEpisodesIds); Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local); Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local); Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local); } [Fact] public void GetById_OneItem_ReturnsCorrectItem() { var id = 1; var expectedEpisode = episodesSeriesOne.Single(e => e.Id == id); var episode = episodeRepositorySUT.GetById(id); Assert.Equal(expectedEpisode, episode); } [Fact] public void GetByIds_MultipleItems_ReturnsCorrectItem() { var id1 = 1; var id2 = 2; var id3 = 3; var expectedEpisode1 = episodesSeriesOne.Single(e => e.Id == id1); var expectedEpisode2 = episodesSeriesOne.Single(e => e.Id == id2); var expectedEpisode3 = episodesSeriesOne.Single(e => e.Id == id3); var episodes = episodeRepositorySUT.GetByIds(new[] { 1, 2, 3 }); Assert.Contains(expectedEpisode1, episodes); Assert.Contains(expectedEpisode2, episodes); Assert.Contains(expectedEpisode3, episodes); } private EntityFrameworkRepository<TEntity, int> CreateEntityFrameworkRepository<TEntity>() where TEntity : class, IEntity<int>, new() { var unitOfWorkRegistryStub = new ThreadLocalUnitOfWorkRegistry(); var unitOfWorkProvider = new EntityFrameworkUnitOfWorkProvider(unitOfWorkRegistryStub, CreateYesMinisterDbContext); IDateTimeProvider dateTimeProvider = new UtcDateTimeProvider(); var unitOfWork = new EntityFrameworkUnitOfWork(unitOfWorkProvider, CreateYesMinisterDbContext, DbContextOptions.ReuseParentContext); unitOfWorkRegistryStub.RegisterUnitOfWork(unitOfWork); return new EntityFrameworkRepository<TEntity, int>(unitOfWorkProvider, dateTimeProvider); } private YesMinisterDbContext CreateYesMinisterDbContext() { return dbContextMock.Object; } } }
apache-2.0
addieljuarez/TallerUAM
Resources/app.js
789
Ti.UI.setBackgroundColor('#fff'); var inicio = Ti.UI.createWindow({ backgroundColor:'#fff' }); var titulo = Ti.UI.createLabel({ text:'UAM', width:'300dp', height:'50dp', left:'10dp', top:'100dp', font:{fontSize:30, fontFamily:'Helvetica Neue'}, textAlign:'center', }); inicio.add(titulo); var data = [{title:'Ingresar'},{title:'Registrarse'}]; var opciones = Ti.UI.createTableView({ width:'300dp', height:'100dp', top:'180dp', left:'10dp', data:data, color:'#000' }); inicio.add(opciones); opciones.addEventListener('click', function(e){ if(e.index==0){ var vIng = Ti.UI.createWindow({ url:'/ui/ingresar' }); vIng.open({modal:true}); } else{ alert('Registrar' +e.index); Ti.API.info('Estoy en la opcion registrarse'+ e.index); } }); inicio.open();
apache-2.0
chirino/proton
proton-j/proton-api/src/main/java/org/apache/qpid/proton/amqp/transport/ErrorCondition.java
1885
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.qpid.proton.amqp.transport; import java.util.Map; import org.apache.qpid.proton.amqp.Symbol; public final class ErrorCondition { private Symbol _condition; private String _description; private Map _info; public Symbol getCondition() { return _condition; } public void setCondition(Symbol condition) { if( condition == null ) { throw new NullPointerException("the condition field is mandatory"); } _condition = condition; } public String getDescription() { return _description; } public void setDescription(String description) { _description = description; } public Map getInfo() { return _info; } public void setInfo(Map info) { _info = info; } @Override public String toString() { return "Error{" + "_condition=" + _condition + ", _description='" + _description + '\'' + ", _info=" + _info + '}'; } }
apache-2.0
Gitpiece/ssm
ssm-db-support/src/main/java/com/icfcc/db/orderhelper/OrderByHelper.java
3806
package com.icfcc.db.orderhelper; import com.icfcc.db.orderhelper.sqlsource.*; import org.apache.ibatis.builder.StaticSqlSource; import org.apache.ibatis.builder.annotation.ProviderSqlSource; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.SystemMetaObject; import org.apache.ibatis.scripting.defaults.RawSqlSource; import org.apache.ibatis.scripting.xmltags.DynamicSqlSource; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.Properties; /** * 排序辅助类 * * @author liuzh * @since 2015-06-26 */ @SuppressWarnings({"rawtypes", "unchecked"}) @Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})) public class OrderByHelper implements Interceptor { private static final ThreadLocal<String> ORDER_BY = new ThreadLocal<String>(); public static String getOrderBy() { String orderBy = ORDER_BY.get(); if (orderBy == null || orderBy.length() == 0) { return null; } return orderBy; } /** * 增加排序 * * @param orderBy */ public static void orderBy(String orderBy) { ORDER_BY.set(orderBy); } /** * 清除本地变量 */ public static void clear() { ORDER_BY.remove(); } /** * 是否已经处理过 * * @param ms * @return */ public static boolean hasOrderBy(MappedStatement ms) { if (ms.getSqlSource() instanceof OrderBySqlSource) { return true; } return false; } /** * 不支持注解形式(ProviderSqlSource)的增加order by * * @param invocation * @throws Throwable */ public static void processIntercept(Invocation invocation) throws Throwable { final Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; if (!hasOrderBy(ms)) { MetaObject msObject = SystemMetaObject.forObject(ms); //判断是否自带order by,自带的情况下作为默认排序 SqlSource sqlSource = ms.getSqlSource(); if (sqlSource instanceof StaticSqlSource) { msObject.setValue("sqlSource", new OrderByStaticSqlSource((StaticSqlSource) sqlSource)); } else if (sqlSource instanceof RawSqlSource) { msObject.setValue("sqlSource", new OrderByRawSqlSource((RawSqlSource) sqlSource)); } else if (sqlSource instanceof ProviderSqlSource) { msObject.setValue("sqlSource", new OrderByProviderSqlSource((ProviderSqlSource) sqlSource)); } else if (sqlSource instanceof DynamicSqlSource) { msObject.setValue("sqlSource", new OrderByDynamicSqlSource((DynamicSqlSource) sqlSource)); } else { throw new RuntimeException("无法处理该类型[" + sqlSource.getClass() + "]的SqlSource"); } } } @Override public Object intercept(Invocation invocation) throws Throwable { try { if (getOrderBy() != null) { processIntercept(invocation); } return invocation.proceed(); } finally { clear(); } } @Override public Object plugin(Object target) { if (target instanceof Executor) { return Plugin.wrap(target, this); } else { return target; } } @Override public void setProperties(Properties properties) { } }
apache-2.0
Tr1aL/utils
src/main/java/ru/tr1al/dao/DAO.java
127
package ru.tr1al.dao; import ru.tr1al.model.Model; public interface DAO<T extends Model> { Class<T> getEntityClass(); }
apache-2.0
tiagofalcao/GoNotebook
manager/test/benchmark.go
423
package test import ( "bufio" "os" "testing" ) import manager "github.com/tiagofalcao/GoNotebook/manager" func Benchmark(b *testing.B, input string, caseTask manager.Task) { i, err := os.Open(input) if err != nil { b.Errorf("Can't open %s", input) } var o NilWriter b.ResetTimer() for x := 0; x < b.N; x++ { manager.NewManagerIO(caseTask, bufio.NewReader(i), o) } i.Close() }
apache-2.0
cowthan/AyoWeibo
sample/back/src/com/example/views/V_ViewSwitcher.java
1766
package com.example.views; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.ViewSwitcher; import android.widget.ViewSwitcher.ViewFactory; public class V_ViewSwitcher extends GhostActivity { private ViewSwitcher switcher; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.uistudy_view_switcher); switcher = this.findViewSwitcher(R.id.viewSwitcher); //===给swticher设置View工厂,当调用switcher.getNextView()时,就是返回 factory.makeView()创建的View //===这里给一个TextView,让swticher切换多个TextView switcher.setFactory(new ViewFactory() { @Override public View makeView() { return new TextView(V_ViewSwitcher.this); } }); } private int count = 0; //====消息响应:下一个 public void next(View v){ count++; switcher.setInAnimation(this, R.anim.slide_in_right); //切换组件:显示过程的动画 switcher.setOutAnimation(this, R.anim.slide_out_left); //切换组件:隐藏过程的动画 TextView textView = (TextView) switcher.getNextView(); textView.setText("This is "+count+"!!!"); textView.setTextSize(22); textView.setTextColor(0xffff0000); switcher.showNext(); } //====消息响应:上一个 public void prev(View v){ count--; switcher.setInAnimation(this, R.anim.slide_in_left); //切换组件:显示过程的动画 switcher.setOutAnimation(this, R.anim.slide_out_right); //切换组件:隐藏过程的动画 TextView textView = (TextView) switcher.getNextView(); textView.setText("This is "+count+"!!!"); textView.setTextSize(22); textView.setTextColor(0xffff0000); switcher.showPrevious(); } }
apache-2.0
knowit/Knowit.EPiModules.ImageScaling
sample/Properties/AssemblyInfo.cs
1410
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Knowit.EPiModules.ImageScaling.Sample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Knowit.EPiModules.ImageScaling.Sample")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4afc5705-c5ba-4f1d-97e2-81020c83c492")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
VHAINNOVATIONS/Telepathology
Source/Java/CacheAPI/main/src/java/gov/va/med/imaging/storage/cache/Group.java
2459
package gov.va.med.imaging.storage.cache; import java.util.Iterator; import java.util.regex.Pattern; import gov.va.med.imaging.storage.cache.events.GroupLifecycleListener; import gov.va.med.imaging.storage.cache.exceptions.CacheException; /** * * i.e. A Group may contain other Group instances, which contain other Group instances, * which eventually contain Instance. * */ public interface Group extends MutableNamedObject, GroupAndInstanceAncestor, GroupSet, InstanceSet { // A group name must be 1 to 64 chars, start with a letter and contain letters, numbers, dashes and underscores public static Pattern NamePattern = Pattern.compile( "[a-zA-Z][a-zA-Z0-9-_]{0,63}" ); /** * Return some human readable identifier for this group. * This must be unique within the parent group, not necessarily across all groups. * @return */ @Override public String getName(); public java.util.Date getLastAccessed() throws CacheException; public long getSize() throws CacheException; // =========================================================================== // Methods that recursively walk down the Region/Group/Instance graph are // defined in GroupAndInstanceAncestor // =========================================================================== // =========================================================================== // Methods operating on the child Group of this Group are defined in GroupSet // =========================================================================== // ===================================================================================== // Methods operating on child Instance are defined in InstanceSet // ===================================================================================== // ===================================================================================== // Eviction Methods // ===================================================================================== public int evaluateAndEvictChildGroups(EvictionJudge<Group> judge) throws CacheException; // ====================================================================================================== // Listener Management // ====================================================================================================== public abstract void registerListener(GroupLifecycleListener listener); public abstract void unregisterListener(GroupLifecycleListener listener); }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-retail/v2/1.31.0/com/google/api/services/retail/v2/model/GoogleCloudRetailV2Product.java
62165
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.retail.v2.model; /** * Product captures all metadata information of items to be recommended or searched. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Retail API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudRetailV2Product extends com.google.api.client.json.GenericJson { /** * Highly encouraged. Extra product attributes to be included. For example, for products, this * could include the store name, vendor, style, color, etc. These are very strong signals for * recommendation model, thus we highly recommend providing the attributes here. Features that can * take on one of a limited number of possible values. Two types of features can be set are: * Textual features. some examples would be the brand/maker of a product, or country of a * customer. Numerical features. Some examples would be the height/weight of a product, or age of * a customer. For example: `{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": * {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }`. This field needs to pass all * below criteria, otherwise an INVALID_ARGUMENT error is returned: * Max entries count: 200. * * The key must be a UTF-8 encoded string with a length limit of 128 characters. * For indexable * attribute, the key must match the pattern: `a-zA-Z0-9*`. For example, `key0LikeThis` or * `KEY_1_LIKE_THIS`. * For text attributes, at most 400 values are allowed. Empty values are not * allowed. Each value must be a non-empty UTF-8 encoded string with a length limit of 256 * characters. * For number attributes, at most 400 values are allowed. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, GoogleCloudRetailV2CustomAttribute> attributes; static { // hack to force ProGuard to consider GoogleCloudRetailV2CustomAttribute used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudRetailV2CustomAttribute.class); } /** * The target group associated with a given audience (e.g. male, veterans, car owners, musicians, * etc.) of the product. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2Audience audience; /** * The online availability of the Product. Default to Availability.IN_STOCK. Corresponding * properties: Google Merchant Center property * [availability](https://support.google.com/merchants/answer/6324448). Schema.org property * [Offer.availability](https://schema.org/availability). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String availability; /** * The available quantity of the item. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer availableQuantity; /** * The timestamp when this Product becomes available for SearchService.Search. * The value may be {@code null}. */ @com.google.api.client.util.Key private String availableTime; /** * The brands of the product. A maximum of 30 brands are allowed. Each brand must be a UTF-8 * encoded string with a length limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is * returned. Corresponding properties: Google Merchant Center property * [brand](https://support.google.com/merchants/answer/6324351). Schema.org property * [Product.brand](https://schema.org/brand). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> brands; /** * Product categories. This field is repeated for supporting one product belonging to several * parallel categories. Strongly recommended using the full path for better search / * recommendation quality. To represent full path of category, use '>' sign to separate different * hierarchies. If '>' is part of the category name, please replace it with other character(s). * For example, if a shoes product belongs to both ["Shoes & Accessories" -> "Shoes"] and ["Sports * & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be represented as: "categories": [ * "Shoes & Accessories > Shoes", "Sports & Fitness > Athletic Clothing > Shoes" ] Must be set for * Type.PRIMARY Product otherwise an INVALID_ARGUMENT error is returned. At most 250 values are * allowed per Product. Empty values are not allowed. Each value must be a UTF-8 encoded string * with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is returned. * Corresponding properties: Google Merchant Center property google_product_category. Schema.org * property [Product.category] (https://schema.org/category). [mc_google_product_category]: * https://support.google.com/merchants/answer/6324436 * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> categories; /** * The id of the collection members when type is Type.COLLECTION. Non-existent product ids are * allowed. The type of the members must be either Type.PRIMARY or Type.VARIANT otherwise and * INVALID_ARGUMENT error is thrown. Should not set it for other types. A maximum of 1000 values * are allowed. Otherwise, an INVALID_ARGUMENT error is return. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> collectionMemberIds; /** * The color of the product. Corresponding properties: Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org property * [Product.color](https://schema.org/color). * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2ColorInfo colorInfo; /** * The condition of the product. Strongly encouraged to use the standard values: "new", * "refurbished", "used". A maximum of 1 value is allowed per Product. Each value must be a UTF-8 * encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is * returned. Corresponding properties: Google Merchant Center property * [condition](https://support.google.com/merchants/answer/6324469). Schema.org property * [Offer.itemCondition](https://schema.org/itemCondition). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> conditions; /** * Product description. This field must be a UTF-8 encoded string with a length limit of 5,000 * characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google * Merchant Center property [description](https://support.google.com/merchants/answer/6324468). * Schema.org property [Product.description](https://schema.org/description). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String description; /** * The timestamp when this product becomes unavailable for SearchService.Search. If it is set, the * Product is not available for SearchService.Search after expire_time. However, the product can * still be retrieved by ProductService.GetProduct and ProductService.ListProducts. expire_time * must be later than available_time and publish_time, otherwise an INVALID_ARGUMENT error is * thrown. Corresponding properties: Google Merchant Center property * [expiration_date](https://support.google.com/merchants/answer/6324499). * The value may be {@code null}. */ @com.google.api.client.util.Key private String expireTime; /** * Fulfillment information, such as the store IDs for in-store pickup or region IDs for different * shipping methods. All the elements must have distinct FulfillmentInfo.type. Otherwise, an * INVALID_ARGUMENT error is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudRetailV2FulfillmentInfo> fulfillmentInfo; static { // hack to force ProGuard to consider GoogleCloudRetailV2FulfillmentInfo used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudRetailV2FulfillmentInfo.class); } /** * The Global Trade Item Number (GTIN) of the product. This field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. This * field must be a Unigram. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding * properties: Google Merchant Center property * [gtin](https://support.google.com/merchants/answer/6324461). Schema.org property * [Product.isbn](https://schema.org/isbn), [Product.gtin8](https://schema.org/gtin8), * [Product.gtin12](https://schema.org/gtin12), [Product.gtin13](https://schema.org/gtin13), or * [Product.gtin14](https://schema.org/gtin14). If the value is not a valid GTIN, an * INVALID_ARGUMENT error is returned. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String gtin; /** * Immutable. Product identifier, which is the final component of name. For example, this field is * "id_1", if name is * `projects/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1`. * This field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant Center property * [id](https://support.google.com/merchants/answer/6324405). Schema.org property * [Product.sku](https://schema.org/sku). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String id; /** * Product images for the product.Highly recommended to put the main image to the first. A maximum * of 300 images are allowed. Corresponding properties: Google Merchant Center property * [image_link](https://support.google.com/merchants/answer/6324350). Schema.org property * [Product.image](https://schema.org/image). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudRetailV2Image> images; static { // hack to force ProGuard to consider GoogleCloudRetailV2Image used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudRetailV2Image.class); } /** * Language of the title/description and other string attributes. Use language tags defined by * [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt). For product prediction, this field is * ignored and the model automatically detects the text language. The Product can include text in * different languages, but duplicating Products to provide text in multiple languages can result * in degraded model performance. For product search this field is in use. It defaults to "en-US" * if unset. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String languageCode; /** * The material of the product. For example, "leather", "wooden". A maximum of 20 values are * allowed. Each value must be a UTF-8 encoded string with a length limit of 200 characters. * Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant * Center property [material](https://support.google.com/merchants/answer/6324410). Schema.org * property [Product.material](https://schema.org/material). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> materials; /** * Immutable. Full resource name of the product, such as `projects/locations/global/catalogs/defau * lt_catalog/branches/default_branch/products/product_id`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * The pattern or graphic print of the product. For example, "striped", "polka dot", "paisley". A * maximum of 20 values are allowed per Product. Each value must be a UTF-8 encoded string with a * length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding * properties: Google Merchant Center property * [pattern](https://support.google.com/merchants/answer/6324483). Schema.org property * [Product.pattern](https://schema.org/pattern). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> patterns; /** * Product price and cost information. Corresponding properties: Google Merchant Center property * [price](https://support.google.com/merchants/answer/6324371). * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2PriceInfo priceInfo; /** * Variant group identifier. Must be an id, with the same parent branch with this product. * Otherwise, an error is thrown. For Type.PRIMARY Products, this field can only be empty or set * to the same value as id. For VARIANT Products, this field cannot be empty. A maximum of 2,000 * products are allowed to share the same Type.PRIMARY Product. Otherwise, an INVALID_ARGUMENT * error is returned. Corresponding properties: Google Merchant Center property * [item_group_id](https://support.google.com/merchants/answer/6324507). Schema.org property * [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String primaryProductId; /** * The promotions applied to the product. A maximum of 10 values are allowed per Product. Only * Promotion.promotion_id will be used, other fields will be ignored if set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudRetailV2Promotion> promotions; /** * The timestamp when the product is published by the retailer for the first time, which indicates * the freshness of the products. Note that this field is different from available_time, given it * purely describes product freshness regardless of when it is available on search and * recommendation. * The value may be {@code null}. */ @com.google.api.client.util.Key private String publishTime; /** * The rating of this product. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudRetailV2Rating rating; /** * Indicates which fields in the Products are returned in SearchResponse. Supported fields for all * types: * audience * availability * brands * color_info * conditions * gtin * materials * name * * patterns * price_info * rating * sizes * title * uri Supported fields only for Type.PRIMARY and * Type.COLLECTION: * categories * description * images Supported fields only for Type.VARIANT: * * Only the first image in images To mark attributes as retrievable, include paths of the form * "attributes.key" where "key" is the key of a custom attribute, as specified in attributes. For * Type.PRIMARY and Type.COLLECTION, the following fields are always returned in SearchResponse by * default: * name For Type.VARIANT, the following fields are always returned in by default: * * name * color_info Maximum number of paths is 30. Otherwise, an INVALID_ARGUMENT error is * returned. Note: Returning more fields in SearchResponse may increase response payload size and * serving latency. * The value may be {@code null}. */ @com.google.api.client.util.Key private String retrievableFields; /** * The size of the product. To represent different size systems or size types, consider using this * format: [[[size_system:]size_type:]size_value]. For example, in "US:MENS:M", "US" represents * size system; "MENS" represents size type; "M" represents size value. In "GIRLS:27", size system * is empty; "GIRLS" represents size type; "27" represents size value. In "32 inches", both size * system and size type are empty, while size value is "32 inches". A maximum of 20 values are * allowed per Product. Each value must be a UTF-8 encoded string with a length limit of 128 * characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google * Merchant Center property [size](https://support.google.com/merchants/answer/6324492), * [size_type](https://support.google.com/merchants/answer/6324497), and * [size_system](https://support.google.com/merchants/answer/6324502). Schema.org property * [Product.size](https://schema.org/size). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> sizes; /** * Custom tags associated with the product. At most 250 values are allowed per Product. This value * must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an * INVALID_ARGUMENT error is returned. This tag can be used for filtering recommendation results * by passing the tag as part of the PredictRequest.filter. Corresponding properties: Google * Merchant Center property * [custom_label_0–4](https://support.google.com/merchants/answer/6324473). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> tags; /** * Required. Product title. This field must be a UTF-8 encoded string with a length limit of 1,000 * characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google * Merchant Center property [title](https://support.google.com/merchants/answer/6324415). * Schema.org property [Product.name](https://schema.org/name). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String title; /** * Input only. The TTL (time to live) of the product. If it is set, it must be a non-negative * value, and expire_time is set as current timestamp plus ttl. The derived expire_time is * returned in the output and ttl is left blank when retrieving the Product. If it is set, the * product is not available for SearchService.Search after current timestamp plus ttl. However, * the product can still be retrieved by ProductService.GetProduct and * ProductService.ListProducts. * The value may be {@code null}. */ @com.google.api.client.util.Key private String ttl; /** * Immutable. The type of the product. Default to * Catalog.product_level_config.ingestion_product_type if unset. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String type; /** * Canonical URL directly linking to the product detail page. It is strongly recommended to * provide a valid uri for the product, otherwise the service performance could be significantly * degraded. This field must be a UTF-8 encoded string with a length limit of 5,000 characters. * Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant * Center property [link](https://support.google.com/merchants/answer/6324416). Schema.org * property [Offer.url](https://schema.org/url). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String uri; /** * Output only. Product variants grouped together on primary product which share similar product * attributes. It's automatically grouped by primary_product_id for all the product variants. Only * populated for Type.PRIMARY Products. Note: This field is OUTPUT_ONLY for * ProductService.GetProduct. Do not set this field in API requests. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudRetailV2Product> variants; /** * Highly encouraged. Extra product attributes to be included. For example, for products, this * could include the store name, vendor, style, color, etc. These are very strong signals for * recommendation model, thus we highly recommend providing the attributes here. Features that can * take on one of a limited number of possible values. Two types of features can be set are: * Textual features. some examples would be the brand/maker of a product, or country of a * customer. Numerical features. Some examples would be the height/weight of a product, or age of * a customer. For example: `{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": * {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }`. This field needs to pass all * below criteria, otherwise an INVALID_ARGUMENT error is returned: * Max entries count: 200. * * The key must be a UTF-8 encoded string with a length limit of 128 characters. * For indexable * attribute, the key must match the pattern: `a-zA-Z0-9*`. For example, `key0LikeThis` or * `KEY_1_LIKE_THIS`. * For text attributes, at most 400 values are allowed. Empty values are not * allowed. Each value must be a non-empty UTF-8 encoded string with a length limit of 256 * characters. * For number attributes, at most 400 values are allowed. * @return value or {@code null} for none */ public java.util.Map<String, GoogleCloudRetailV2CustomAttribute> getAttributes() { return attributes; } /** * Highly encouraged. Extra product attributes to be included. For example, for products, this * could include the store name, vendor, style, color, etc. These are very strong signals for * recommendation model, thus we highly recommend providing the attributes here. Features that can * take on one of a limited number of possible values. Two types of features can be set are: * Textual features. some examples would be the brand/maker of a product, or country of a * customer. Numerical features. Some examples would be the height/weight of a product, or age of * a customer. For example: `{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm": * {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }`. This field needs to pass all * below criteria, otherwise an INVALID_ARGUMENT error is returned: * Max entries count: 200. * * The key must be a UTF-8 encoded string with a length limit of 128 characters. * For indexable * attribute, the key must match the pattern: `a-zA-Z0-9*`. For example, `key0LikeThis` or * `KEY_1_LIKE_THIS`. * For text attributes, at most 400 values are allowed. Empty values are not * allowed. Each value must be a non-empty UTF-8 encoded string with a length limit of 256 * characters. * For number attributes, at most 400 values are allowed. * @param attributes attributes or {@code null} for none */ public GoogleCloudRetailV2Product setAttributes(java.util.Map<String, GoogleCloudRetailV2CustomAttribute> attributes) { this.attributes = attributes; return this; } /** * The target group associated with a given audience (e.g. male, veterans, car owners, musicians, * etc.) of the product. * @return value or {@code null} for none */ public GoogleCloudRetailV2Audience getAudience() { return audience; } /** * The target group associated with a given audience (e.g. male, veterans, car owners, musicians, * etc.) of the product. * @param audience audience or {@code null} for none */ public GoogleCloudRetailV2Product setAudience(GoogleCloudRetailV2Audience audience) { this.audience = audience; return this; } /** * The online availability of the Product. Default to Availability.IN_STOCK. Corresponding * properties: Google Merchant Center property * [availability](https://support.google.com/merchants/answer/6324448). Schema.org property * [Offer.availability](https://schema.org/availability). * @return value or {@code null} for none */ public java.lang.String getAvailability() { return availability; } /** * The online availability of the Product. Default to Availability.IN_STOCK. Corresponding * properties: Google Merchant Center property * [availability](https://support.google.com/merchants/answer/6324448). Schema.org property * [Offer.availability](https://schema.org/availability). * @param availability availability or {@code null} for none */ public GoogleCloudRetailV2Product setAvailability(java.lang.String availability) { this.availability = availability; return this; } /** * The available quantity of the item. * @return value or {@code null} for none */ public java.lang.Integer getAvailableQuantity() { return availableQuantity; } /** * The available quantity of the item. * @param availableQuantity availableQuantity or {@code null} for none */ public GoogleCloudRetailV2Product setAvailableQuantity(java.lang.Integer availableQuantity) { this.availableQuantity = availableQuantity; return this; } /** * The timestamp when this Product becomes available for SearchService.Search. * @return value or {@code null} for none */ public String getAvailableTime() { return availableTime; } /** * The timestamp when this Product becomes available for SearchService.Search. * @param availableTime availableTime or {@code null} for none */ public GoogleCloudRetailV2Product setAvailableTime(String availableTime) { this.availableTime = availableTime; return this; } /** * The brands of the product. A maximum of 30 brands are allowed. Each brand must be a UTF-8 * encoded string with a length limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is * returned. Corresponding properties: Google Merchant Center property * [brand](https://support.google.com/merchants/answer/6324351). Schema.org property * [Product.brand](https://schema.org/brand). * @return value or {@code null} for none */ public java.util.List<java.lang.String> getBrands() { return brands; } /** * The brands of the product. A maximum of 30 brands are allowed. Each brand must be a UTF-8 * encoded string with a length limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is * returned. Corresponding properties: Google Merchant Center property * [brand](https://support.google.com/merchants/answer/6324351). Schema.org property * [Product.brand](https://schema.org/brand). * @param brands brands or {@code null} for none */ public GoogleCloudRetailV2Product setBrands(java.util.List<java.lang.String> brands) { this.brands = brands; return this; } /** * Product categories. This field is repeated for supporting one product belonging to several * parallel categories. Strongly recommended using the full path for better search / * recommendation quality. To represent full path of category, use '>' sign to separate different * hierarchies. If '>' is part of the category name, please replace it with other character(s). * For example, if a shoes product belongs to both ["Shoes & Accessories" -> "Shoes"] and ["Sports * & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be represented as: "categories": [ * "Shoes & Accessories > Shoes", "Sports & Fitness > Athletic Clothing > Shoes" ] Must be set for * Type.PRIMARY Product otherwise an INVALID_ARGUMENT error is returned. At most 250 values are * allowed per Product. Empty values are not allowed. Each value must be a UTF-8 encoded string * with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is returned. * Corresponding properties: Google Merchant Center property google_product_category. Schema.org * property [Product.category] (https://schema.org/category). [mc_google_product_category]: * https://support.google.com/merchants/answer/6324436 * @return value or {@code null} for none */ public java.util.List<java.lang.String> getCategories() { return categories; } /** * Product categories. This field is repeated for supporting one product belonging to several * parallel categories. Strongly recommended using the full path for better search / * recommendation quality. To represent full path of category, use '>' sign to separate different * hierarchies. If '>' is part of the category name, please replace it with other character(s). * For example, if a shoes product belongs to both ["Shoes & Accessories" -> "Shoes"] and ["Sports * & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be represented as: "categories": [ * "Shoes & Accessories > Shoes", "Sports & Fitness > Athletic Clothing > Shoes" ] Must be set for * Type.PRIMARY Product otherwise an INVALID_ARGUMENT error is returned. At most 250 values are * allowed per Product. Empty values are not allowed. Each value must be a UTF-8 encoded string * with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is returned. * Corresponding properties: Google Merchant Center property google_product_category. Schema.org * property [Product.category] (https://schema.org/category). [mc_google_product_category]: * https://support.google.com/merchants/answer/6324436 * @param categories categories or {@code null} for none */ public GoogleCloudRetailV2Product setCategories(java.util.List<java.lang.String> categories) { this.categories = categories; return this; } /** * The id of the collection members when type is Type.COLLECTION. Non-existent product ids are * allowed. The type of the members must be either Type.PRIMARY or Type.VARIANT otherwise and * INVALID_ARGUMENT error is thrown. Should not set it for other types. A maximum of 1000 values * are allowed. Otherwise, an INVALID_ARGUMENT error is return. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getCollectionMemberIds() { return collectionMemberIds; } /** * The id of the collection members when type is Type.COLLECTION. Non-existent product ids are * allowed. The type of the members must be either Type.PRIMARY or Type.VARIANT otherwise and * INVALID_ARGUMENT error is thrown. Should not set it for other types. A maximum of 1000 values * are allowed. Otherwise, an INVALID_ARGUMENT error is return. * @param collectionMemberIds collectionMemberIds or {@code null} for none */ public GoogleCloudRetailV2Product setCollectionMemberIds(java.util.List<java.lang.String> collectionMemberIds) { this.collectionMemberIds = collectionMemberIds; return this; } /** * The color of the product. Corresponding properties: Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org property * [Product.color](https://schema.org/color). * @return value or {@code null} for none */ public GoogleCloudRetailV2ColorInfo getColorInfo() { return colorInfo; } /** * The color of the product. Corresponding properties: Google Merchant Center property * [color](https://support.google.com/merchants/answer/6324487). Schema.org property * [Product.color](https://schema.org/color). * @param colorInfo colorInfo or {@code null} for none */ public GoogleCloudRetailV2Product setColorInfo(GoogleCloudRetailV2ColorInfo colorInfo) { this.colorInfo = colorInfo; return this; } /** * The condition of the product. Strongly encouraged to use the standard values: "new", * "refurbished", "used". A maximum of 1 value is allowed per Product. Each value must be a UTF-8 * encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is * returned. Corresponding properties: Google Merchant Center property * [condition](https://support.google.com/merchants/answer/6324469). Schema.org property * [Offer.itemCondition](https://schema.org/itemCondition). * @return value or {@code null} for none */ public java.util.List<java.lang.String> getConditions() { return conditions; } /** * The condition of the product. Strongly encouraged to use the standard values: "new", * "refurbished", "used". A maximum of 1 value is allowed per Product. Each value must be a UTF-8 * encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is * returned. Corresponding properties: Google Merchant Center property * [condition](https://support.google.com/merchants/answer/6324469). Schema.org property * [Offer.itemCondition](https://schema.org/itemCondition). * @param conditions conditions or {@code null} for none */ public GoogleCloudRetailV2Product setConditions(java.util.List<java.lang.String> conditions) { this.conditions = conditions; return this; } /** * Product description. This field must be a UTF-8 encoded string with a length limit of 5,000 * characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google * Merchant Center property [description](https://support.google.com/merchants/answer/6324468). * Schema.org property [Product.description](https://schema.org/description). * @return value or {@code null} for none */ public java.lang.String getDescription() { return description; } /** * Product description. This field must be a UTF-8 encoded string with a length limit of 5,000 * characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google * Merchant Center property [description](https://support.google.com/merchants/answer/6324468). * Schema.org property [Product.description](https://schema.org/description). * @param description description or {@code null} for none */ public GoogleCloudRetailV2Product setDescription(java.lang.String description) { this.description = description; return this; } /** * The timestamp when this product becomes unavailable for SearchService.Search. If it is set, the * Product is not available for SearchService.Search after expire_time. However, the product can * still be retrieved by ProductService.GetProduct and ProductService.ListProducts. expire_time * must be later than available_time and publish_time, otherwise an INVALID_ARGUMENT error is * thrown. Corresponding properties: Google Merchant Center property * [expiration_date](https://support.google.com/merchants/answer/6324499). * @return value or {@code null} for none */ public String getExpireTime() { return expireTime; } /** * The timestamp when this product becomes unavailable for SearchService.Search. If it is set, the * Product is not available for SearchService.Search after expire_time. However, the product can * still be retrieved by ProductService.GetProduct and ProductService.ListProducts. expire_time * must be later than available_time and publish_time, otherwise an INVALID_ARGUMENT error is * thrown. Corresponding properties: Google Merchant Center property * [expiration_date](https://support.google.com/merchants/answer/6324499). * @param expireTime expireTime or {@code null} for none */ public GoogleCloudRetailV2Product setExpireTime(String expireTime) { this.expireTime = expireTime; return this; } /** * Fulfillment information, such as the store IDs for in-store pickup or region IDs for different * shipping methods. All the elements must have distinct FulfillmentInfo.type. Otherwise, an * INVALID_ARGUMENT error is returned. * @return value or {@code null} for none */ public java.util.List<GoogleCloudRetailV2FulfillmentInfo> getFulfillmentInfo() { return fulfillmentInfo; } /** * Fulfillment information, such as the store IDs for in-store pickup or region IDs for different * shipping methods. All the elements must have distinct FulfillmentInfo.type. Otherwise, an * INVALID_ARGUMENT error is returned. * @param fulfillmentInfo fulfillmentInfo or {@code null} for none */ public GoogleCloudRetailV2Product setFulfillmentInfo(java.util.List<GoogleCloudRetailV2FulfillmentInfo> fulfillmentInfo) { this.fulfillmentInfo = fulfillmentInfo; return this; } /** * The Global Trade Item Number (GTIN) of the product. This field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. This * field must be a Unigram. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding * properties: Google Merchant Center property * [gtin](https://support.google.com/merchants/answer/6324461). Schema.org property * [Product.isbn](https://schema.org/isbn), [Product.gtin8](https://schema.org/gtin8), * [Product.gtin12](https://schema.org/gtin12), [Product.gtin13](https://schema.org/gtin13), or * [Product.gtin14](https://schema.org/gtin14). If the value is not a valid GTIN, an * INVALID_ARGUMENT error is returned. * @return value or {@code null} for none */ public java.lang.String getGtin() { return gtin; } /** * The Global Trade Item Number (GTIN) of the product. This field must be a UTF-8 encoded string * with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. This * field must be a Unigram. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding * properties: Google Merchant Center property * [gtin](https://support.google.com/merchants/answer/6324461). Schema.org property * [Product.isbn](https://schema.org/isbn), [Product.gtin8](https://schema.org/gtin8), * [Product.gtin12](https://schema.org/gtin12), [Product.gtin13](https://schema.org/gtin13), or * [Product.gtin14](https://schema.org/gtin14). If the value is not a valid GTIN, an * INVALID_ARGUMENT error is returned. * @param gtin gtin or {@code null} for none */ public GoogleCloudRetailV2Product setGtin(java.lang.String gtin) { this.gtin = gtin; return this; } /** * Immutable. Product identifier, which is the final component of name. For example, this field is * "id_1", if name is * `projects/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1`. * This field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant Center property * [id](https://support.google.com/merchants/answer/6324405). Schema.org property * [Product.sku](https://schema.org/sku). * @return value or {@code null} for none */ public java.lang.String getId() { return id; } /** * Immutable. Product identifier, which is the final component of name. For example, this field is * "id_1", if name is * `projects/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1`. * This field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an * INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant Center property * [id](https://support.google.com/merchants/answer/6324405). Schema.org property * [Product.sku](https://schema.org/sku). * @param id id or {@code null} for none */ public GoogleCloudRetailV2Product setId(java.lang.String id) { this.id = id; return this; } /** * Product images for the product.Highly recommended to put the main image to the first. A maximum * of 300 images are allowed. Corresponding properties: Google Merchant Center property * [image_link](https://support.google.com/merchants/answer/6324350). Schema.org property * [Product.image](https://schema.org/image). * @return value or {@code null} for none */ public java.util.List<GoogleCloudRetailV2Image> getImages() { return images; } /** * Product images for the product.Highly recommended to put the main image to the first. A maximum * of 300 images are allowed. Corresponding properties: Google Merchant Center property * [image_link](https://support.google.com/merchants/answer/6324350). Schema.org property * [Product.image](https://schema.org/image). * @param images images or {@code null} for none */ public GoogleCloudRetailV2Product setImages(java.util.List<GoogleCloudRetailV2Image> images) { this.images = images; return this; } /** * Language of the title/description and other string attributes. Use language tags defined by * [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt). For product prediction, this field is * ignored and the model automatically detects the text language. The Product can include text in * different languages, but duplicating Products to provide text in multiple languages can result * in degraded model performance. For product search this field is in use. It defaults to "en-US" * if unset. * @return value or {@code null} for none */ public java.lang.String getLanguageCode() { return languageCode; } /** * Language of the title/description and other string attributes. Use language tags defined by * [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt). For product prediction, this field is * ignored and the model automatically detects the text language. The Product can include text in * different languages, but duplicating Products to provide text in multiple languages can result * in degraded model performance. For product search this field is in use. It defaults to "en-US" * if unset. * @param languageCode languageCode or {@code null} for none */ public GoogleCloudRetailV2Product setLanguageCode(java.lang.String languageCode) { this.languageCode = languageCode; return this; } /** * The material of the product. For example, "leather", "wooden". A maximum of 20 values are * allowed. Each value must be a UTF-8 encoded string with a length limit of 200 characters. * Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant * Center property [material](https://support.google.com/merchants/answer/6324410). Schema.org * property [Product.material](https://schema.org/material). * @return value or {@code null} for none */ public java.util.List<java.lang.String> getMaterials() { return materials; } /** * The material of the product. For example, "leather", "wooden". A maximum of 20 values are * allowed. Each value must be a UTF-8 encoded string with a length limit of 200 characters. * Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant * Center property [material](https://support.google.com/merchants/answer/6324410). Schema.org * property [Product.material](https://schema.org/material). * @param materials materials or {@code null} for none */ public GoogleCloudRetailV2Product setMaterials(java.util.List<java.lang.String> materials) { this.materials = materials; return this; } /** * Immutable. Full resource name of the product, such as `projects/locations/global/catalogs/defau * lt_catalog/branches/default_branch/products/product_id`. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Immutable. Full resource name of the product, such as `projects/locations/global/catalogs/defau * lt_catalog/branches/default_branch/products/product_id`. * @param name name or {@code null} for none */ public GoogleCloudRetailV2Product setName(java.lang.String name) { this.name = name; return this; } /** * The pattern or graphic print of the product. For example, "striped", "polka dot", "paisley". A * maximum of 20 values are allowed per Product. Each value must be a UTF-8 encoded string with a * length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding * properties: Google Merchant Center property * [pattern](https://support.google.com/merchants/answer/6324483). Schema.org property * [Product.pattern](https://schema.org/pattern). * @return value or {@code null} for none */ public java.util.List<java.lang.String> getPatterns() { return patterns; } /** * The pattern or graphic print of the product. For example, "striped", "polka dot", "paisley". A * maximum of 20 values are allowed per Product. Each value must be a UTF-8 encoded string with a * length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding * properties: Google Merchant Center property * [pattern](https://support.google.com/merchants/answer/6324483). Schema.org property * [Product.pattern](https://schema.org/pattern). * @param patterns patterns or {@code null} for none */ public GoogleCloudRetailV2Product setPatterns(java.util.List<java.lang.String> patterns) { this.patterns = patterns; return this; } /** * Product price and cost information. Corresponding properties: Google Merchant Center property * [price](https://support.google.com/merchants/answer/6324371). * @return value or {@code null} for none */ public GoogleCloudRetailV2PriceInfo getPriceInfo() { return priceInfo; } /** * Product price and cost information. Corresponding properties: Google Merchant Center property * [price](https://support.google.com/merchants/answer/6324371). * @param priceInfo priceInfo or {@code null} for none */ public GoogleCloudRetailV2Product setPriceInfo(GoogleCloudRetailV2PriceInfo priceInfo) { this.priceInfo = priceInfo; return this; } /** * Variant group identifier. Must be an id, with the same parent branch with this product. * Otherwise, an error is thrown. For Type.PRIMARY Products, this field can only be empty or set * to the same value as id. For VARIANT Products, this field cannot be empty. A maximum of 2,000 * products are allowed to share the same Type.PRIMARY Product. Otherwise, an INVALID_ARGUMENT * error is returned. Corresponding properties: Google Merchant Center property * [item_group_id](https://support.google.com/merchants/answer/6324507). Schema.org property * [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID). * @return value or {@code null} for none */ public java.lang.String getPrimaryProductId() { return primaryProductId; } /** * Variant group identifier. Must be an id, with the same parent branch with this product. * Otherwise, an error is thrown. For Type.PRIMARY Products, this field can only be empty or set * to the same value as id. For VARIANT Products, this field cannot be empty. A maximum of 2,000 * products are allowed to share the same Type.PRIMARY Product. Otherwise, an INVALID_ARGUMENT * error is returned. Corresponding properties: Google Merchant Center property * [item_group_id](https://support.google.com/merchants/answer/6324507). Schema.org property * [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID). * @param primaryProductId primaryProductId or {@code null} for none */ public GoogleCloudRetailV2Product setPrimaryProductId(java.lang.String primaryProductId) { this.primaryProductId = primaryProductId; return this; } /** * The promotions applied to the product. A maximum of 10 values are allowed per Product. Only * Promotion.promotion_id will be used, other fields will be ignored if set. * @return value or {@code null} for none */ public java.util.List<GoogleCloudRetailV2Promotion> getPromotions() { return promotions; } /** * The promotions applied to the product. A maximum of 10 values are allowed per Product. Only * Promotion.promotion_id will be used, other fields will be ignored if set. * @param promotions promotions or {@code null} for none */ public GoogleCloudRetailV2Product setPromotions(java.util.List<GoogleCloudRetailV2Promotion> promotions) { this.promotions = promotions; return this; } /** * The timestamp when the product is published by the retailer for the first time, which indicates * the freshness of the products. Note that this field is different from available_time, given it * purely describes product freshness regardless of when it is available on search and * recommendation. * @return value or {@code null} for none */ public String getPublishTime() { return publishTime; } /** * The timestamp when the product is published by the retailer for the first time, which indicates * the freshness of the products. Note that this field is different from available_time, given it * purely describes product freshness regardless of when it is available on search and * recommendation. * @param publishTime publishTime or {@code null} for none */ public GoogleCloudRetailV2Product setPublishTime(String publishTime) { this.publishTime = publishTime; return this; } /** * The rating of this product. * @return value or {@code null} for none */ public GoogleCloudRetailV2Rating getRating() { return rating; } /** * The rating of this product. * @param rating rating or {@code null} for none */ public GoogleCloudRetailV2Product setRating(GoogleCloudRetailV2Rating rating) { this.rating = rating; return this; } /** * Indicates which fields in the Products are returned in SearchResponse. Supported fields for all * types: * audience * availability * brands * color_info * conditions * gtin * materials * name * * patterns * price_info * rating * sizes * title * uri Supported fields only for Type.PRIMARY and * Type.COLLECTION: * categories * description * images Supported fields only for Type.VARIANT: * * Only the first image in images To mark attributes as retrievable, include paths of the form * "attributes.key" where "key" is the key of a custom attribute, as specified in attributes. For * Type.PRIMARY and Type.COLLECTION, the following fields are always returned in SearchResponse by * default: * name For Type.VARIANT, the following fields are always returned in by default: * * name * color_info Maximum number of paths is 30. Otherwise, an INVALID_ARGUMENT error is * returned. Note: Returning more fields in SearchResponse may increase response payload size and * serving latency. * @return value or {@code null} for none */ public String getRetrievableFields() { return retrievableFields; } /** * Indicates which fields in the Products are returned in SearchResponse. Supported fields for all * types: * audience * availability * brands * color_info * conditions * gtin * materials * name * * patterns * price_info * rating * sizes * title * uri Supported fields only for Type.PRIMARY and * Type.COLLECTION: * categories * description * images Supported fields only for Type.VARIANT: * * Only the first image in images To mark attributes as retrievable, include paths of the form * "attributes.key" where "key" is the key of a custom attribute, as specified in attributes. For * Type.PRIMARY and Type.COLLECTION, the following fields are always returned in SearchResponse by * default: * name For Type.VARIANT, the following fields are always returned in by default: * * name * color_info Maximum number of paths is 30. Otherwise, an INVALID_ARGUMENT error is * returned. Note: Returning more fields in SearchResponse may increase response payload size and * serving latency. * @param retrievableFields retrievableFields or {@code null} for none */ public GoogleCloudRetailV2Product setRetrievableFields(String retrievableFields) { this.retrievableFields = retrievableFields; return this; } /** * The size of the product. To represent different size systems or size types, consider using this * format: [[[size_system:]size_type:]size_value]. For example, in "US:MENS:M", "US" represents * size system; "MENS" represents size type; "M" represents size value. In "GIRLS:27", size system * is empty; "GIRLS" represents size type; "27" represents size value. In "32 inches", both size * system and size type are empty, while size value is "32 inches". A maximum of 20 values are * allowed per Product. Each value must be a UTF-8 encoded string with a length limit of 128 * characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google * Merchant Center property [size](https://support.google.com/merchants/answer/6324492), * [size_type](https://support.google.com/merchants/answer/6324497), and * [size_system](https://support.google.com/merchants/answer/6324502). Schema.org property * [Product.size](https://schema.org/size). * @return value or {@code null} for none */ public java.util.List<java.lang.String> getSizes() { return sizes; } /** * The size of the product. To represent different size systems or size types, consider using this * format: [[[size_system:]size_type:]size_value]. For example, in "US:MENS:M", "US" represents * size system; "MENS" represents size type; "M" represents size value. In "GIRLS:27", size system * is empty; "GIRLS" represents size type; "27" represents size value. In "32 inches", both size * system and size type are empty, while size value is "32 inches". A maximum of 20 values are * allowed per Product. Each value must be a UTF-8 encoded string with a length limit of 128 * characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google * Merchant Center property [size](https://support.google.com/merchants/answer/6324492), * [size_type](https://support.google.com/merchants/answer/6324497), and * [size_system](https://support.google.com/merchants/answer/6324502). Schema.org property * [Product.size](https://schema.org/size). * @param sizes sizes or {@code null} for none */ public GoogleCloudRetailV2Product setSizes(java.util.List<java.lang.String> sizes) { this.sizes = sizes; return this; } /** * Custom tags associated with the product. At most 250 values are allowed per Product. This value * must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an * INVALID_ARGUMENT error is returned. This tag can be used for filtering recommendation results * by passing the tag as part of the PredictRequest.filter. Corresponding properties: Google * Merchant Center property * [custom_label_0–4](https://support.google.com/merchants/answer/6324473). * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTags() { return tags; } /** * Custom tags associated with the product. At most 250 values are allowed per Product. This value * must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an * INVALID_ARGUMENT error is returned. This tag can be used for filtering recommendation results * by passing the tag as part of the PredictRequest.filter. Corresponding properties: Google * Merchant Center property * [custom_label_0–4](https://support.google.com/merchants/answer/6324473). * @param tags tags or {@code null} for none */ public GoogleCloudRetailV2Product setTags(java.util.List<java.lang.String> tags) { this.tags = tags; return this; } /** * Required. Product title. This field must be a UTF-8 encoded string with a length limit of 1,000 * characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google * Merchant Center property [title](https://support.google.com/merchants/answer/6324415). * Schema.org property [Product.name](https://schema.org/name). * @return value or {@code null} for none */ public java.lang.String getTitle() { return title; } /** * Required. Product title. This field must be a UTF-8 encoded string with a length limit of 1,000 * characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google * Merchant Center property [title](https://support.google.com/merchants/answer/6324415). * Schema.org property [Product.name](https://schema.org/name). * @param title title or {@code null} for none */ public GoogleCloudRetailV2Product setTitle(java.lang.String title) { this.title = title; return this; } /** * Input only. The TTL (time to live) of the product. If it is set, it must be a non-negative * value, and expire_time is set as current timestamp plus ttl. The derived expire_time is * returned in the output and ttl is left blank when retrieving the Product. If it is set, the * product is not available for SearchService.Search after current timestamp plus ttl. However, * the product can still be retrieved by ProductService.GetProduct and * ProductService.ListProducts. * @return value or {@code null} for none */ public String getTtl() { return ttl; } /** * Input only. The TTL (time to live) of the product. If it is set, it must be a non-negative * value, and expire_time is set as current timestamp plus ttl. The derived expire_time is * returned in the output and ttl is left blank when retrieving the Product. If it is set, the * product is not available for SearchService.Search after current timestamp plus ttl. However, * the product can still be retrieved by ProductService.GetProduct and * ProductService.ListProducts. * @param ttl ttl or {@code null} for none */ public GoogleCloudRetailV2Product setTtl(String ttl) { this.ttl = ttl; return this; } /** * Immutable. The type of the product. Default to * Catalog.product_level_config.ingestion_product_type if unset. * @return value or {@code null} for none */ public java.lang.String getType() { return type; } /** * Immutable. The type of the product. Default to * Catalog.product_level_config.ingestion_product_type if unset. * @param type type or {@code null} for none */ public GoogleCloudRetailV2Product setType(java.lang.String type) { this.type = type; return this; } /** * Canonical URL directly linking to the product detail page. It is strongly recommended to * provide a valid uri for the product, otherwise the service performance could be significantly * degraded. This field must be a UTF-8 encoded string with a length limit of 5,000 characters. * Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant * Center property [link](https://support.google.com/merchants/answer/6324416). Schema.org * property [Offer.url](https://schema.org/url). * @return value or {@code null} for none */ public java.lang.String getUri() { return uri; } /** * Canonical URL directly linking to the product detail page. It is strongly recommended to * provide a valid uri for the product, otherwise the service performance could be significantly * degraded. This field must be a UTF-8 encoded string with a length limit of 5,000 characters. * Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant * Center property [link](https://support.google.com/merchants/answer/6324416). Schema.org * property [Offer.url](https://schema.org/url). * @param uri uri or {@code null} for none */ public GoogleCloudRetailV2Product setUri(java.lang.String uri) { this.uri = uri; return this; } /** * Output only. Product variants grouped together on primary product which share similar product * attributes. It's automatically grouped by primary_product_id for all the product variants. Only * populated for Type.PRIMARY Products. Note: This field is OUTPUT_ONLY for * ProductService.GetProduct. Do not set this field in API requests. * @return value or {@code null} for none */ public java.util.List<GoogleCloudRetailV2Product> getVariants() { return variants; } /** * Output only. Product variants grouped together on primary product which share similar product * attributes. It's automatically grouped by primary_product_id for all the product variants. Only * populated for Type.PRIMARY Products. Note: This field is OUTPUT_ONLY for * ProductService.GetProduct. Do not set this field in API requests. * @param variants variants or {@code null} for none */ public GoogleCloudRetailV2Product setVariants(java.util.List<GoogleCloudRetailV2Product> variants) { this.variants = variants; return this; } @Override public GoogleCloudRetailV2Product set(String fieldName, Object value) { return (GoogleCloudRetailV2Product) super.set(fieldName, value); } @Override public GoogleCloudRetailV2Product clone() { return (GoogleCloudRetailV2Product) super.clone(); } }
apache-2.0
SrinivasReddy987/Lookswoow
app/controllers/search.js
2071
var httpManager = require("httpManager"); Alloy.Globals.isSearch = true; if (OS_ANDROID) { $.search.windowSoftInputMode = Ti.UI.Android.SOFT_INPUT_ADJUST_PAN; } var dataTitles = [ { name : "Find Us", view : "findUs" }, { name : "Deals", view : "deals" }, { name : "Testimonials", view : "testmonials" }, { name : "Loyalty", view : "loyalty" }, { name : "Be Social", view : "beSocial" }, { name : "Before & After", view : "beforeAfter" }, { name : "About Us", view : "aboutUs" }, { name : "Services for dermatology", view : "services" }, { name : "Services for dental", view : "services" }, ]; var data =[]; for (var i=0; i < dataTitles.length; i++) { var row = Titanium.UI.createTableViewRow({ title:dataTitles[i].name, color:'black', height:50, id : i, }); data.push(row); } var search = Titanium.UI.createSearchBar({ barColor : '#DA308A', showCancel : true, height : 43, top : 0, }); search.addEventListener('cancel', function() { search.blur(); }); var listView = Ti.UI.createListView({ searchView : search, caseInsensitiveSearch : true, backgroundColor:'white', top :"60", bottom :"60", }); var listSection = Ti.UI.createListSection( ); var data = []; for (var i = 0; i < dataTitles.length; i++) { data.push({ properties : { title : dataTitles[i].name, searchableText :dataTitles[i].name, color :"black", height : "40", } }); } listSection.setItems(data); listView.sections = [listSection]; listView.addEventListener('itemclick', function(e){ Alloy.createController(dataTitles[e.itemIndex].view).getView(); }); $.search.add(listView); function logoutClicked (e) { httpManager.userLogout(function(response) { if(response.success == 1) { Alloy.createController('login').getView(); $.search .close(); } }); } Ti.App.addEventListener('android:back', function() { $.search.exitOnClose = true; var myActivity = Ti.Android.currentActivity(); myActivity.finish(); }); Alloy.Globals.closeSearchWindow = function(){ $.search .close(); }; $.search.open();
apache-2.0
lugavin/ssh
ssh-sys-core/src/test/java/com/ssh/sys/core/validation/ValidationTest.java
2560
package com.ssh.sys.core.validation; import com.ssh.common.util.Constant; import com.ssh.sys.api.dto.UserDTO; import com.ssh.sys.api.dto.extension.PermissionExtDTO; import com.ssh.sys.api.service.PermissionService; import com.ssh.sys.api.service.UserService; import org.junit.Assert; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.support.AopUtils; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; import java.util.List; @ActiveProfiles(Constant.ENV_DEV) @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:spring-validation.xml", "classpath:spring-core-context.xml", "classpath:sys-core-context.xml" }) //@TransactionConfiguration(transactionManager = "transactionManager") @Transactional(transactionManager = "transactionManager") @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ValidationTest { private static final Logger LOGGER = LoggerFactory.getLogger(ValidationTest.class); @Inject private UserService userService; @Inject private PermissionService permissionService; @Before public void setUp() throws Exception { Assert.assertNotNull(userService); // 注意: 引进和不引进spring-validation.xml配置文件一下结果的区别 LOGGER.info("isAopProxy => {}", AopUtils.isAopProxy(userService)); LOGGER.info("isJdkDynamicProxy => {}", AopUtils.isJdkDynamicProxy(userService)); LOGGER.info("isCglibProxy => {}", AopUtils.isCglibProxy(userService)); } @Test @Rollback public void test1Save() throws Exception { UserDTO dto = new UserDTO(); dto.setCode("King"); dto.setName("King"); dto.setPass("King"); userService.add(dto); } @Test public void test2GetList() throws Exception { List<UserDTO> list = userService.getList(new UserDTO()); LOGGER.info("list => {}", list); } @Test public void test3GetById() throws Exception { PermissionExtDTO dto = permissionService.getById(11L); LOGGER.info("=== {} ===", dto); } }
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Yushania/Yushania alpina/ Syn. Sinarundinaria alpina/README.md
209
# Sinarundinaria alpina (K.Schum.) C.S.Chao & Renvoize SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
chat-sdk/chat-sdk-android
firestream/src/main/java/firestream/chat/chat/AbstractChat.java
15606
package firestream.chat.chat; import androidx.annotation.Nullable; import org.pmw.tinylog.Logger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; import firestream.chat.events.ListData; import firestream.chat.filter.Filter; import firestream.chat.firebase.service.Path; import firestream.chat.interfaces.IAbstractChat; import firestream.chat.message.Sendable; import firestream.chat.message.TypingState; import firestream.chat.namespace.Fire; import firestream.chat.types.SendableType; import firestream.chat.types.TypingStateType; import firestream.chat.util.TypingMap; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.ObservableSource; import io.reactivex.Single; import io.reactivex.SingleSource; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.functions.Predicate; import sdk.guru.common.DisposableMap; import sdk.guru.common.Event; import sdk.guru.common.EventType; import sdk.guru.common.Optional; import sdk.guru.common.RX; /** * This class handles common elements of a conversation bit it 1-to-1 or group. * Mainly sending and receiving messages. */ public abstract class AbstractChat implements IAbstractChat { /** * Store the disposables so we can dispose of all of them when the user logs out */ protected DisposableMap dm = new DisposableMap(); /** * Event events */ protected Events events = new Events(); /** * A list of all sendables received */ protected List<Sendable> sendables = new ArrayList<>(); protected TypingMap typingMap = new TypingMap(); /** * Start listening to the current message reference and retrieve all messages * @return a events of message results */ protected Observable<Event<Sendable>> messagesOn() { return messagesOn(null); } /** * Start listening to the current message reference and pass the messages to the events * @param newerThan only listen for messages after this date * @return a events of message results */ protected Observable<Event<Sendable>> messagesOn(Date newerThan) { return Fire.internal().getFirebaseService().core.messagesOn(messagesPath(), newerThan).doOnNext(event -> { Sendable sendable = event.get(); Sendable previous = getSendable(sendable.getId()); if (event.isAdded()) { sendables.add(sendable); } if (previous != null) { if (event.isModified()) { sendable.copyTo(previous); } if (event.isRemoved()) { sendables.remove(previous); } } getSendableEvents().getSendables().accept(event); }).doOnError(throwable -> { events.publishThrowable().accept(throwable); }).observeOn(RX.main()); } /** * Get a updateBatch of messages once * @param fromDate get messages from this date * @param toDate get messages until this date * @param limit limit the maximum number of messages * @return a events of message results */ protected Single<List<Sendable>> loadMoreMessages(@Nullable Date fromDate, @Nullable Date toDate, @Nullable Integer limit, boolean desc) { return Fire.stream().getFirebaseService().core .loadMoreMessages(messagesPath(), fromDate, toDate, limit) .map(sendables -> { Collections.sort(sendables, (s1, s2) -> { if (desc) { return s2.getDate().compareTo(s1.getDate()); } else { return s1.getDate().compareTo(s2.getDate()); } }); return sendables; }) .observeOn(RX.main()); } public Single<List<Sendable>> loadMoreMessages(Date fromDate, Date toDate, boolean desc) { return loadMoreMessages(fromDate, toDate, null, desc); } public Single<List<Sendable>> loadMoreMessagesFrom(Date fromDate, Integer limit, boolean desc) { return loadMoreMessages(fromDate, null, limit, desc); } public Single<List<Sendable>> loadMoreMessagesTo(Date toDate, Integer limit, boolean desc) { return loadMoreMessages(null, toDate, limit, desc); } public Single<List<Sendable>> loadMoreMessagesBefore(final Date toDate, Integer limit, boolean desc) { return Single.defer(() -> { Date before = toDate == null ? null : new Date(toDate.getTime() - 1); return loadMoreMessagesTo(before, limit, desc); }); } /** * Listen for changes in the value of a list reference * @param path to listen to * @return events of list events */ protected Observable<Event<ListData>> listChangeOn(Path path) { return Fire.stream().getFirebaseService().core .listChangeOn(path) .observeOn(RX.main()); } public Completable send(Path messagesPath, Sendable sendable) { return send(messagesPath, sendable, null); } /** * Send a message to a messages ref * @param messagesPath * @param sendable item to be sent * @param newId the ID of the new message * @return single containing message id */ public Completable send(Path messagesPath, Sendable sendable, @Nullable Consumer<String> newId) { return Fire.stream().getFirebaseService().core .send(messagesPath, sendable, newId) .observeOn(RX.main()); } /** * Delete a sendable from our queue * @param messagesPath * @return completion */ protected Completable deleteSendable (Path messagesPath) { return Fire.stream().getFirebaseService().core .deleteSendable(messagesPath) .observeOn(RX.main()); } /** * Remove a user from a reference * @param path for users * @param user to remove * @return completion */ protected Completable removeUser(Path path, User user) { return removeUsers(path, user); } /** * Remove users from a reference * @param path for users * @param users to remove * @return completion */ protected Completable removeUsers(Path path, User... users) { return removeUsers(path, Arrays.asList(users)); } /** * Remove users from a reference * @param path for users * @param users to remove * @return completion */ protected Completable removeUsers(Path path, List<? extends User> users) { return Fire.stream().getFirebaseService().core .removeUsers(path, users) .observeOn(RX.main()); } /** * Add a user to a reference * @param path for users * @param dataProvider a callback to extract the data to add from the user * this allows us to use one method to write to multiple different places * @param user to add * @return completion */ protected Completable addUser(Path path, User.DataProvider dataProvider, User user) { return addUsers(path, dataProvider, user); } /** * Add users to a reference * @param path for users * @param dataProvider a callback to extract the data to add from the user * this allows us to use one method to write to multiple different places * @param users to add * @return completion */ public Completable addUsers(Path path, User.DataProvider dataProvider, User... users) { return addUsers(path, dataProvider, Arrays.asList(users)); } /** * Add users to a reference * @param path * @param dataProvider a callback to extract the data to add from the user * this allows us to use one method to write to multiple different places * @param users to add * @return completion */ public Completable addUsers(Path path, User.DataProvider dataProvider, List<? extends User> users) { return Fire.stream().getFirebaseService().core .addUsers(path, dataProvider, users) .observeOn(RX.main()); } /** * Updates a user for a reference * @param path for users * @param dataProvider a callback to extract the data to add from the user * this allows us to use one method to write to multiple different places * @param user to update * @return completion */ public Completable updateUser(Path path, User.DataProvider dataProvider, User user) { return updateUsers(path, dataProvider, user); } /** * Update users for a reference * @param path for users * @param dataProvider a callback to extract the data to add from the user * this allows us to use one method to write to multiple different places * @param users to update * @return completion */ public Completable updateUsers(Path path, User.DataProvider dataProvider, User... users) { return updateUsers(path, dataProvider, Arrays.asList(users)); } /** * Update users for a reference * @param path for users * @param dataProvider a callback to extract the data to add from the user * this allows us to use one method to write to multiple different places * @param users to update * @return completion */ public Completable updateUsers(Path path, User.DataProvider dataProvider, List<? extends User> users) { return Fire.stream().getFirebaseService().core .updateUsers(path, dataProvider, users) .observeOn(RX.main()); } @Override public void connect() throws Exception { dm.add(Single.defer((Callable<SingleSource<Optional<Sendable>>>) () -> { // If we are deleting the messages on receipt then we want to get all new messages if (Fire.stream().getConfig().deleteMessagesOnReceipt) { return Single.just(Optional.empty()); } else { return Fire.stream().getFirebaseService().core.lastMessage(messagesPath()); } }).flatMapObservable((Function<Optional<Sendable>, ObservableSource<Event<Sendable>>>) optional -> { Date date = null; if (!optional.isEmpty()) { if (Fire.stream().getConfig().emitEventForLastMessage) { passMessageResultToStream(new Event<>(optional.get(), EventType.Added)); } date = optional.get().getDate(); } return messagesOn(date); }).subscribe(this::passMessageResultToStream, this)); } @Override public void disconnect () { dm.dispose(); } /** * Convenience method to cast sendables and send them to the correct events * @param event sendable event */ protected void passMessageResultToStream(Event<Sendable> event) { Sendable sendable = event.get(); // if (Fire.stream().isBlocked(new User(sendable.getFrom()))) { // return; // } debug("Sendable: " + sendable.getType() + " " + sendable.getId() + ", date: " + sendable.getDate().getTime()); // In general, we are mostly interested when messages are added if (sendable.isType(SendableType.message())) { events.getMessages().accept(event.to(sendable.toMessage())); } if (sendable.isType(SendableType.deliveryReceipt())) { events.getDeliveryReceipts().accept(event.to(sendable.toDeliveryReceipt())); } if (sendable.isType(SendableType.typingState())) { TypingState typingState = sendable.toTypingState(); if (event.isAdded()) { typingState.setBodyType(TypingStateType.typing()); } if (event.isRemoved()) { typingState.setBodyType(TypingStateType.none()); } events.getTypingStates().accept(new Event<>(typingState, EventType.Modified)); } if (sendable.isType(SendableType.invitation())) { events.getInvitations().accept(event.to(sendable.toInvitation())); } if (sendable.isType(SendableType.presence())) { events.getPresences().accept(event.to(sendable.toPresence())); } } @Override public List<Sendable> getSendables() { return sendables; } @Override public List<Sendable> getSendables(SendableType type) { List<Sendable> sendables = new ArrayList<>(); for (Sendable s: sendables) { if (s.isType(type)) { sendables.add(s); } } return sendables; } // public DeliveryReceipt getDeliveryReceiptsForMessage(String messageId, DeliveryReceiptType type) { // List<DeliveryReceipt> receipts = getSendables(DeliveryReceipt.class); // for (DeliveryReceipt receipt: receipts) { // try { // if (receipt.getMessageId().equals(messageId) && receipt.getDeliveryReceiptType() == type) { // return receipt; // } // } catch (Exception ignored) {} // } // return null; // } public <T extends Sendable> List<T> getSendables(Class<T> clazz) { return new Sendable.Converter<T>(clazz).convert(getSendables()); } @Override public Sendable getSendable(String id) { for (Sendable s: sendables) { if (s.getId().equals(id)) { return s; } } return null; } /** * returns the events object which exposes the different sendable streams * @return events */ public Events getSendableEvents() { return events; } /** * Overridable messages reference * @return Firestore messages reference */ protected abstract Path messagesPath(); @Override public DisposableMap getDisposableMap() { return dm; } @Override public void manage(Disposable disposable) { getDisposableMap().add(disposable); } public abstract Completable markRead(Sendable message); public abstract Completable markReceived(Sendable message); public void debug(String text) { if (Fire.stream().getConfig().debugEnabled) { Logger.debug(text); } } protected Predicate<Event<? extends Sendable>> deliveryReceiptFilter() { return Filter.and(new ArrayList<Predicate<Event<? extends Sendable>>>() {{ add(Fire.internal().getMarkReceivedFilter()); add(Filter.notFromMe()); add(Filter.byEventType(EventType.Added)); }}); } @Override public void onSubscribe(Disposable d) { dm.add(d); } @Override public void onComplete() { } @Override public void onError(Throwable e) { events.publishThrowable().accept(e); } /** * Error handler method so we can redirect all errors to the error events * @param throwable - the events error */ @Override public void accept(Throwable throwable) { onError(throwable); } }
apache-2.0
petermr/norma
src/main/java/org/xmlcml/norma/biblio/RISEntry.java
3184
package org.xmlcml.norma.biblio; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.xmlcml.graphics.html.HtmlDiv; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class RISEntry { public static final Logger LOG = Logger.getLogger(RISEntry.class); static { LOG.setLevel(Level.DEBUG); } private static final String AB = "AB"; private static final String ER = "ER"; public static final String TY = "TY"; public final static String START_DASH_SPACE = "^[A-Z][A-Z][A-Z ][A-Z ]\\- .*"; // PMID breaks the rules, this covers it public final static String DASH_SPACE = "- "; // PMID breaks the rules, this covers it public static final String PMID = "PMID"; private String type; private StringBuilder currentValue; private Multimap<String, StringBuilder> valuesByField = ArrayListMultimap.create(); private boolean canAdd; private List<String> fieldList; String abstractx; public RISEntry() { canAdd = true; fieldList = new ArrayList<String>(); } public String getType() { return type; } public String addLine(String line) { if (!canAdd) { System.err.println("Cannot add line: "+line); } String field = null; if (line.matches(START_DASH_SPACE)) { String[] ss = line.split(DASH_SPACE); field = ss[0].trim(); recordUnknownFields(field); if (!fieldList.contains(field)) { fieldList.add(field); } if (ss.length == 1) { currentValue = null; if (field.equals(ER)) { canAdd = false; } } else { currentValue = new StringBuilder(ss[1].trim()); valuesByField.put(field, currentValue); } } else { String v = line.trim(); if (canAdd) { if (currentValue != null) { currentValue.append(" "+v); } else { System.err.println("Cannot add "+line); } } else { System.err.println("Cannot add: "+line); } } return field; } private void recordUnknownFields(String field) { if (!RISParser.FIELD_MAP.containsKey(field)) { if (!RISParser.UNKNOWN_KEYS.contains(field)) { RISParser.addUnknownKey(field); LOG.trace("Unknown Key: "+field); } } } public HtmlDiv createAbstractHtml() { List<StringBuilder> abstracts = new ArrayList<StringBuilder>(valuesByField.get(AB)); HtmlDiv abstractDiv = null; if (abstracts.size() == 1) { abstractx = abstracts.get(0).toString(); BiblioAbstractAnalyzer abstractAnalyzer = new BiblioAbstractAnalyzer(); abstractDiv = abstractAnalyzer.createAndAnalyzeSections(abstractx); } return abstractDiv; } public String toString() { StringBuilder sb = new StringBuilder(); for (String key : fieldList) { sb.append(key+": "); List<StringBuilder> values = new ArrayList<StringBuilder>(valuesByField.get(key)); if (values.size() == 1) { sb.append(values.get(0).toString()+"\n"); } else { sb.append("\n"); for (StringBuilder sb0 : values) { sb.append(" "+sb0.toString()+"\n"); } } } return sb.toString(); } public String getAbstractString() { if (abstractx == null) { createAbstractHtml(); } return abstractx; } }
apache-2.0
naver/arcus-hubble
view/partials/tabs/load_overview.html
315
<h6>load (overview)</h6> <div ng-model="selectedTab" chartgroup> <div class="chart span5" data-chart-type="multi_line" data-chart-group="load" data-chart-title="load" data-chart-legend="shortterm,midterm,longterm" data-chart-key="load/load.rrd/shortterm,load/load.rrd/midterm,load/load.rrd/longterm"></div> </div>
apache-2.0
uli-heller/uli-jbake
content/blog/2015/016-derby-command-line-editing.md
1174
title=Derby: Editierbare Kommandozeile date=2015-07-06 type=post tags=derby status=published ~~~~~~ Derby: Editierbare Kommandozeile ================================ Ich benutze häufig den Kommandozeilen-Modus "IJ" von Derby. Damit kann ich schnell mal eine SQL-Abfrage losschicken, ohne dass ich lange auf den Start warten muß - wie bspq. bei SqlDeveloper. Problem: Zumindest unter Linux rächt sich jeder Vertipper. Man kann die Kommandos schlecht editieren und auch die "vorigen" Befehle nicht mittels Pfeil-hoch "zurückholen". Abhilfe gibt's mit [jline](http://jline.sourceforge.net/): * Herunterladen von [hier](http://mvnrepository.com/artifact/jline/jline/1.0) (Version 2.x funktioniert nicht) * Ablegen in einem Verzeichnis * Erstellen des Start-Skriptes "ij.sh" Hier noch das Start-Skript "ij.sh": ``` #!/bin/sh D="$(dirname "$0")" DD="$(cd "${D}"; pwd)" JLINE_JAR="$(ls "${D}/"jline*jar|sort|tail -1)" DERBY_HOME=$(ls -d /opt/db-derby*|sort|tail -1) exec java -classpath "${JLINE_JAR}:${DERBY_HOME}/lib/*" jline.ConsoleRunner org.apache.derby.tools.ij "$@" ``` Quelle: [db-derby/CommandHistoryInIj](http://wiki.apache.org/db-derby/CommandHistoryInIj)
apache-2.0
aws/aws-sdk-cpp
aws-cpp-sdk-mwaa/include/aws/mwaa/model/PublishMetricsRequest.h
6400
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/mwaa/MWAA_EXPORTS.h> #include <aws/mwaa/MWAARequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/mwaa/model/MetricDatum.h> #include <utility> namespace Aws { namespace MWAA { namespace Model { /** */ class AWS_MWAA_API PublishMetricsRequest : public MWAARequest { public: PublishMetricsRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "PublishMetrics"; } Aws::String SerializePayload() const override; /** * <p> <b>Internal only</b>. The name of the environment.</p> */ inline const Aws::String& GetEnvironmentName() const{ return m_environmentName; } /** * <p> <b>Internal only</b>. The name of the environment.</p> */ inline bool EnvironmentNameHasBeenSet() const { return m_environmentNameHasBeenSet; } /** * <p> <b>Internal only</b>. The name of the environment.</p> */ inline void SetEnvironmentName(const Aws::String& value) { m_environmentNameHasBeenSet = true; m_environmentName = value; } /** * <p> <b>Internal only</b>. The name of the environment.</p> */ inline void SetEnvironmentName(Aws::String&& value) { m_environmentNameHasBeenSet = true; m_environmentName = std::move(value); } /** * <p> <b>Internal only</b>. The name of the environment.</p> */ inline void SetEnvironmentName(const char* value) { m_environmentNameHasBeenSet = true; m_environmentName.assign(value); } /** * <p> <b>Internal only</b>. The name of the environment.</p> */ inline PublishMetricsRequest& WithEnvironmentName(const Aws::String& value) { SetEnvironmentName(value); return *this;} /** * <p> <b>Internal only</b>. The name of the environment.</p> */ inline PublishMetricsRequest& WithEnvironmentName(Aws::String&& value) { SetEnvironmentName(std::move(value)); return *this;} /** * <p> <b>Internal only</b>. The name of the environment.</p> */ inline PublishMetricsRequest& WithEnvironmentName(const char* value) { SetEnvironmentName(value); return *this;} /** * <p> <b>Internal only</b>. Publishes metrics to Amazon CloudWatch. To learn more * about the metrics published to Amazon CloudWatch, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/cw-metrics.html">Amazon * MWAA performance metrics in Amazon CloudWatch</a>.</p> */ inline const Aws::Vector<MetricDatum>& GetMetricData() const{ return m_metricData; } /** * <p> <b>Internal only</b>. Publishes metrics to Amazon CloudWatch. To learn more * about the metrics published to Amazon CloudWatch, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/cw-metrics.html">Amazon * MWAA performance metrics in Amazon CloudWatch</a>.</p> */ inline bool MetricDataHasBeenSet() const { return m_metricDataHasBeenSet; } /** * <p> <b>Internal only</b>. Publishes metrics to Amazon CloudWatch. To learn more * about the metrics published to Amazon CloudWatch, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/cw-metrics.html">Amazon * MWAA performance metrics in Amazon CloudWatch</a>.</p> */ inline void SetMetricData(const Aws::Vector<MetricDatum>& value) { m_metricDataHasBeenSet = true; m_metricData = value; } /** * <p> <b>Internal only</b>. Publishes metrics to Amazon CloudWatch. To learn more * about the metrics published to Amazon CloudWatch, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/cw-metrics.html">Amazon * MWAA performance metrics in Amazon CloudWatch</a>.</p> */ inline void SetMetricData(Aws::Vector<MetricDatum>&& value) { m_metricDataHasBeenSet = true; m_metricData = std::move(value); } /** * <p> <b>Internal only</b>. Publishes metrics to Amazon CloudWatch. To learn more * about the metrics published to Amazon CloudWatch, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/cw-metrics.html">Amazon * MWAA performance metrics in Amazon CloudWatch</a>.</p> */ inline PublishMetricsRequest& WithMetricData(const Aws::Vector<MetricDatum>& value) { SetMetricData(value); return *this;} /** * <p> <b>Internal only</b>. Publishes metrics to Amazon CloudWatch. To learn more * about the metrics published to Amazon CloudWatch, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/cw-metrics.html">Amazon * MWAA performance metrics in Amazon CloudWatch</a>.</p> */ inline PublishMetricsRequest& WithMetricData(Aws::Vector<MetricDatum>&& value) { SetMetricData(std::move(value)); return *this;} /** * <p> <b>Internal only</b>. Publishes metrics to Amazon CloudWatch. To learn more * about the metrics published to Amazon CloudWatch, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/cw-metrics.html">Amazon * MWAA performance metrics in Amazon CloudWatch</a>.</p> */ inline PublishMetricsRequest& AddMetricData(const MetricDatum& value) { m_metricDataHasBeenSet = true; m_metricData.push_back(value); return *this; } /** * <p> <b>Internal only</b>. Publishes metrics to Amazon CloudWatch. To learn more * about the metrics published to Amazon CloudWatch, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/cw-metrics.html">Amazon * MWAA performance metrics in Amazon CloudWatch</a>.</p> */ inline PublishMetricsRequest& AddMetricData(MetricDatum&& value) { m_metricDataHasBeenSet = true; m_metricData.push_back(std::move(value)); return *this; } private: Aws::String m_environmentName; bool m_environmentNameHasBeenSet; Aws::Vector<MetricDatum> m_metricData; bool m_metricDataHasBeenSet; }; } // namespace Model } // namespace MWAA } // namespace Aws
apache-2.0
adbrucker/SecureBPMN
designer/src/org.activiti.designer.model/src/main/java/org/eclipse/bpmn2/impl/DataStoreReferenceImpl.java
13233
/** * <copyright> * * Copyright (c) 2010 SAP AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation * * </copyright> */ package org.eclipse.bpmn2.impl; import java.util.Collection; import java.util.List; import org.eclipse.bpmn2.Bpmn2Package; import org.eclipse.bpmn2.DataState; import org.eclipse.bpmn2.DataStore; import org.eclipse.bpmn2.DataStoreReference; import org.eclipse.bpmn2.ItemAwareElement; import org.eclipse.bpmn2.ItemDefinition; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList; import org.eclipse.emf.ecore.util.InternalEList; import org.eclipse.securebpmn2.ItemAwareElementAction; import org.eclipse.securebpmn2.Securebpmn2Package; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Data Store Reference</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getDataState <em>Data State</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getItemSubjectRef <em>Item Subject Ref</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getItemAwareElementActions <em>Item Aware Element Actions</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getDataStoreRef <em>Data Store Ref</em>}</li> * </ul> * </p> * * @generated */ public class DataStoreReferenceImpl extends FlowElementImpl implements DataStoreReference { /** * The cached value of the '{@link #getDataState() <em>Data State</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDataState() * @generated * @ordered */ protected DataState dataState; /** * The cached value of the '{@link #getItemSubjectRef() <em>Item Subject Ref</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getItemSubjectRef() * @generated * @ordered */ protected ItemDefinition itemSubjectRef; /** * The cached value of the '{@link #getItemAwareElementActions() <em>Item Aware Element Actions</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getItemAwareElementActions() * @generated * @ordered */ protected EList<ItemAwareElementAction> itemAwareElementActions; /** * The cached value of the '{@link #getDataStoreRef() <em>Data Store Ref</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDataStoreRef() * @generated * @ordered */ protected DataStore dataStoreRef; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DataStoreReferenceImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Bpmn2Package.Literals.DATA_STORE_REFERENCE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataState getDataState() { return dataState; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetDataState(DataState newDataState, NotificationChain msgs) { DataState oldDataState = dataState; dataState = newDataState; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE, oldDataState, newDataState); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDataState(DataState newDataState) { if (newDataState != dataState) { NotificationChain msgs = null; if (dataState != null) msgs = ((InternalEObject) dataState) .eInverseRemove( this, EOPPOSITE_FEATURE_BASE - Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE, null, msgs); if (newDataState != null) msgs = ((InternalEObject) newDataState) .eInverseAdd( this, EOPPOSITE_FEATURE_BASE - Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE, null, msgs); msgs = basicSetDataState(newDataState, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE, newDataState, newDataState)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ItemDefinition getItemSubjectRef() { if (itemSubjectRef != null && itemSubjectRef.eIsProxy()) { InternalEObject oldItemSubjectRef = (InternalEObject) itemSubjectRef; itemSubjectRef = (ItemDefinition) eResolveProxy(oldItemSubjectRef); if (itemSubjectRef != oldItemSubjectRef) { if (eNotificationRequired()) eNotify(new ENotificationImpl( this, Notification.RESOLVE, Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF, oldItemSubjectRef, itemSubjectRef)); } } return itemSubjectRef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ItemDefinition basicGetItemSubjectRef() { return itemSubjectRef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setItemSubjectRef(ItemDefinition newItemSubjectRef) { ItemDefinition oldItemSubjectRef = itemSubjectRef; itemSubjectRef = newItemSubjectRef; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF, oldItemSubjectRef, itemSubjectRef)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public List<ItemAwareElementAction> getItemAwareElementActions() { if (itemAwareElementActions == null) { itemAwareElementActions = new EObjectContainmentWithInverseEList<ItemAwareElementAction>( ItemAwareElementAction.class, this, Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS, Securebpmn2Package.ITEM_AWARE_ELEMENT_ACTION__ITEM_AWARE_ELEMENT); } return itemAwareElementActions; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataStore getDataStoreRef() { if (dataStoreRef != null && dataStoreRef.eIsProxy()) { InternalEObject oldDataStoreRef = (InternalEObject) dataStoreRef; dataStoreRef = (DataStore) eResolveProxy(oldDataStoreRef); if (dataStoreRef != oldDataStoreRef) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF, oldDataStoreRef, dataStoreRef)); } } return dataStoreRef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DataStore basicGetDataStoreRef() { return dataStoreRef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDataStoreRef(DataStore newDataStoreRef) { DataStore oldDataStoreRef = dataStoreRef; dataStoreRef = newDataStoreRef; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF, oldDataStoreRef, dataStoreRef)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS: return ((InternalEList<InternalEObject>) (InternalEList<?>) getItemAwareElementActions()) .basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE: return basicSetDataState(null, msgs); case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS: return ((InternalEList<?>) getItemAwareElementActions()) .basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE: return getDataState(); case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF: if (resolve) return getItemSubjectRef(); return basicGetItemSubjectRef(); case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS: return getItemAwareElementActions(); case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF: if (resolve) return getDataStoreRef(); return basicGetDataStoreRef(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE: setDataState((DataState) newValue); return; case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF: setItemSubjectRef((ItemDefinition) newValue); return; case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS: getItemAwareElementActions().clear(); getItemAwareElementActions().addAll( (Collection<? extends ItemAwareElementAction>) newValue); return; case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF: setDataStoreRef((DataStore) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE: setDataState((DataState) null); return; case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF: setItemSubjectRef((ItemDefinition) null); return; case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS: getItemAwareElementActions().clear(); return; case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF: setDataStoreRef((DataStore) null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE: return dataState != null; case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF: return itemSubjectRef != null; case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS: return itemAwareElementActions != null && !itemAwareElementActions.isEmpty(); case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF: return dataStoreRef != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) { if (baseClass == ItemAwareElement.class) { switch (derivedFeatureID) { case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE: return Bpmn2Package.ITEM_AWARE_ELEMENT__DATA_STATE; case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF: return Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_SUBJECT_REF; case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS: return Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_AWARE_ELEMENT_ACTIONS; default: return -1; } } return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) { if (baseClass == ItemAwareElement.class) { switch (baseFeatureID) { case Bpmn2Package.ITEM_AWARE_ELEMENT__DATA_STATE: return Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE; case Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_SUBJECT_REF: return Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF; case Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_AWARE_ELEMENT_ACTIONS: return Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS; default: return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass); } } //DataStoreReferenceImpl
apache-2.0
y-todorov/Inventory
Inventory.MVC/Scripts/Kendo/cultures/kendo.culture.de-LI.js
2637
/* * Kendo UI v2014.3.1119 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["de-LI"] = { name: "de-LI", numberFormat: { pattern: ["-n"], decimals: 2, ",": "'", ".": ".", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": "'", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$-n","$ n"], decimals: 2, ",": "'", ".": ".", groupSize: [3], symbol: "CHF" } }, calendars: { standard: { days: { names: ["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"], namesAbbr: ["So","Mo","Di","Mi","Do","Fr","Sa"], namesShort: ["So","Mo","Di","Mi","Do","Fr","Sa"] }, months: { names: ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember",""], namesAbbr: ["Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez",""] }, AM: [""], PM: [""], patterns: { d: "dd.MM.yyyy", D: "dddd, d. MMMM yyyy", F: "dddd, d. MMMM yyyy HH:mm:ss", g: "dd.MM.yyyy HH:mm", G: "dd.MM.yyyy HH:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": ".", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
apache-2.0
KirillOsenkov/SourceBrowser
src/HtmlGenerator/Pass1-Generation/TypeScriptSupport.cs
26413
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Microsoft.SourceBrowser.Common; using Newtonsoft.Json; namespace Microsoft.SourceBrowser.HtmlGenerator { public class TypeScriptSupport { private static readonly HashSet<string> alreadyProcessed = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private Dictionary<string, List<Reference>> references; private List<string> declarations; public Dictionary<string, List<Tuple<string, long>>> SymbolIDToListOfLocationsMap { get; private set; } public void Generate(IEnumerable<string> typeScriptFiles, string solutionDestinationFolder) { if (typeScriptFiles == null || !typeScriptFiles.Any()) { return; } var projectDestinationFolder = Path.Combine(solutionDestinationFolder, Constants.TypeScriptFiles).MustBeAbsolute(); declarations = new List<string>(); references = new Dictionary<string, List<Reference>>(StringComparer.OrdinalIgnoreCase); SymbolIDToListOfLocationsMap = new Dictionary<string, List<Tuple<string, long>>>(); var list = new List<string>(); string libFile = null; foreach (var file in typeScriptFiles) { if (!alreadyProcessed.Contains(file)) { if (libFile == null && string.Equals(Path.GetFileName(file), "lib.d.ts", StringComparison.OrdinalIgnoreCase)) { libFile = file; } else { list.Add(file); } } } if (libFile == null) { libFile = Path.Combine(Common.Paths.BaseAppFolder, "TypeScriptSupport", "lib.d.ts"); } try { GenerateCore(list, libFile); } catch (Exception ex) { Log.Exception(ex, "Error when generating TypeScript files"); return; } ProjectGenerator.GenerateReferencesDataFilesToAssembly( Paths.SolutionDestinationFolder, Constants.TypeScriptFiles, references); declarations.Sort(); Serialization.WriteDeclaredSymbols( projectDestinationFolder, declarations); ProjectGenerator.GenerateSymbolIDToListOfDeclarationLocationsMap( projectDestinationFolder, SymbolIDToListOfLocationsMap); } private void GenerateCore(IEnumerable<string> fileNames, string libFile) { var output = Path.Combine(Common.Paths.BaseAppFolder, "output"); if (Directory.Exists(output)) { Directory.Delete(output, recursive: true); } var json = JsonConvert.SerializeObject(new { fileNames, libFile, outputFolder = output }); var argumentsJson = Path.Combine(Common.Paths.BaseAppFolder, "TypeScriptAnalyzerArguments.json"); File.WriteAllText(argumentsJson, json); var analyzerJs = Path.Combine(Common.Paths.BaseAppFolder, @"TypeScriptSupport\analyzer.js"); var arguments = string.Format("\"{0}\" {1}", analyzerJs, argumentsJson); ProcessLaunchService.ProcessRunResult result; try { using (Disposable.Timing("Calling Node.js to process TypeScript")) { result = new ProcessLaunchService().RunAndRedirectOutput("node", arguments); } } catch (Win32Exception) { Log.Write("Warning: Node.js is required to generate TypeScript files. Skipping generation. Download Node.js from https://nodejs.org.", ConsoleColor.Yellow); Log.Exception("Node.js is not installed."); return; } using (Disposable.Timing("Generating TypeScript files")) { foreach (var file in Directory.GetFiles(output)) { if (Path.GetFileNameWithoutExtension(file) == "ok") { continue; } if (Path.GetFileNameWithoutExtension(file) == "error") { var errorContent = File.ReadAllText(file); Log.Exception(DateTime.Now.ToString() + " " + errorContent); return; } var text = File.ReadAllText(file); AnalyzedFile analysis = JsonConvert.DeserializeObject<AnalyzedFile>(text); EnsureFileGeneratedAndGetUrl(analysis); } } } public void EnsureFileGeneratedAndGetUrl(AnalyzedFile analysis) { string localFileSystemPath = analysis.fileName; localFileSystemPath = Path.GetFullPath(localFileSystemPath); string destinationFilePath = GetDestinationFilePath(localFileSystemPath); if (!File.Exists(destinationFilePath)) { Generate(localFileSystemPath, destinationFilePath, analysis.syntacticClassifications, analysis.semanticClassifications); } } public static string GetDestinationFilePath(string sourceFilePath) { var url = sourceFilePath + ".html"; url = url.Replace(":", ""); url = url.Replace(" ", ""); url = url.Replace(@"\bin\", @"\bin_\"); if (url.StartsWith(@"\\", StringComparison.Ordinal)) { url = url.Substring(2); } url = Constants.TypeScriptFiles + @"\" + url; url = Path.Combine(Paths.SolutionDestinationFolder, url); return url; } private void Generate( string sourceFilePath, string destinationHtmlFilePath, ClassifiedRange[] syntacticRanges, ClassifiedRange[] semanticRanges) { Log.Write(destinationHtmlFilePath); var sb = new StringBuilder(); var lines = File.ReadAllLines(sourceFilePath); var text = File.ReadAllText(sourceFilePath); var lineCount = lines.Length; var lineLengths = TextUtilities.GetLineLengths(text); var ranges = PrepareRanges(syntacticRanges, semanticRanges, text); var relativePathToRoot = Paths.CalculateRelativePathToRoot(destinationHtmlFilePath, Paths.SolutionDestinationFolder); var prefix = Markup.GetDocumentPrefix(Path.GetFileName(sourceFilePath), relativePathToRoot, lineCount, "ix"); sb.Append(prefix); var displayName = GetDisplayName(destinationHtmlFilePath); const string assemblyName = "TypeScriptFiles"; var url = "/#" + assemblyName + "/" + displayName.Replace('\\', '/'); displayName = @"\\" + displayName; Markup.WriteLinkPanel(s => sb.AppendLine(s), fileLink: (displayName, url)); // pass a value larger than 0 to generate line numbers statically at HTML generation time var table = Markup.GetTablePrefix(); sb.AppendLine(table); var localSymbolIdMap = new Dictionary<string, int>(); foreach (var range in ranges) { range.lineNumber = TextUtilities.GetLineNumber(range.start, lineLengths); var line = TextUtilities.GetLineFromPosition(range.start, text); range.column = range.start - line.Item1; range.lineText = text.Substring(line.Item1, line.Item2); GenerateRange(sb, range, destinationHtmlFilePath, localSymbolIdMap); } var suffix = Markup.GetDocumentSuffix(); sb.AppendLine(suffix); var folder = Path.GetDirectoryName(destinationHtmlFilePath); Directory.CreateDirectory(folder); File.WriteAllText(destinationHtmlFilePath, sb.ToString()); } public static ClassifiedRange[] PrepareRanges( ClassifiedRange[] syntacticRanges, ClassifiedRange[] semanticRanges, string text) { foreach (var range in semanticRanges) { range.IsSemantic = true; } var rangesSortedByStart = syntacticRanges .Concat(semanticRanges) .Where(r => r.length > 0) .OrderBy(r => r.start) .ToArray(); var midpoints = rangesSortedByStart .Select(r => r.start) .Concat( rangesSortedByStart .Select(r => r.end)) .Distinct() .OrderBy(n => n) .ToArray(); var ranges = RemoveIntersectingRanges( text, rangesSortedByStart, midpoints); ranges = RemoveOverlappingRanges( text, ranges); ranges = RangeUtilities.FillGaps( text, ranges, r => r.start, r => r.length, (s, l, t) => new ClassifiedRange(t, s, l)); foreach (var range in ranges) { if (range.text == null) { range.text = text.Substring(range.start, range.length); } } return ranges; } public static ClassifiedRange[] RemoveOverlappingRanges(string text, ClassifiedRange[] ranges) { var output = new List<ClassifiedRange>(ranges.Length); for (int i = 0; i < ranges.Length; i++) { ClassifiedRange best = ranges[i]; while (i < ranges.Length - 1 && ranges[i].start == ranges[i + 1].start) { best = ChooseBetterRange(best, ranges[i + 1]); i++; } output.Add(best); } return output.ToArray(); } private static ClassifiedRange ChooseBetterRange(ClassifiedRange left, ClassifiedRange right) { if (left == null) { return right; } if (right == null) { return left; } if (left.IsSemantic != right.IsSemantic) { if (left.IsSemantic) { right.classification = left.classification; return right; } else { left.classification = right.classification; return left; } } ClassifiedRange victim = left; ClassifiedRange winner = right; if (left.classification == "comment") { victim = left; winner = right; } if (right.classification == "comment") { victim = right; winner = left; } if (winner.hyperlinks == null && victim.hyperlinks != null) { winner.hyperlinks = victim.hyperlinks; } if (winner.classification == "text") { winner.classification = victim.classification; } return winner; } public static ClassifiedRange[] RemoveIntersectingRanges( string text, ClassifiedRange[] rangesSortedByStart, int[] midpoints) { var result = new List<ClassifiedRange>(); int currentEndpoint = 0; int currentRangeIndex = 0; for (; currentEndpoint < midpoints.Length && currentRangeIndex < rangesSortedByStart.Length;) { while ( currentRangeIndex < rangesSortedByStart.Length && rangesSortedByStart[currentRangeIndex].start == midpoints[currentEndpoint]) { var currentRange = rangesSortedByStart[currentRangeIndex]; if (currentRange.end == midpoints[currentEndpoint + 1]) { result.Add(currentRange); } else { int endpoint = currentEndpoint; do { result.Add( new ClassifiedRange( text, midpoints[endpoint], midpoints[endpoint + 1] - midpoints[endpoint], currentRange)); endpoint++; } while (endpoint < midpoints.Length && midpoints[endpoint] < currentRange.end); } currentRangeIndex++; } currentEndpoint++; } return result.ToArray(); } private void GenerateRange( StringBuilder sb, ClassifiedRange range, string destinationFilePath, Dictionary<string, int> localSymbolIdMap) { var html = range.text; html = Markup.HtmlEscape(html); var localRelativePath = destinationFilePath.Substring( Path.Combine( Paths.SolutionDestinationFolder, Constants.TypeScriptFiles).Length + 1); localRelativePath = localRelativePath.Substring(0, localRelativePath.Length - ".html".Length); string classAttributeValue = GetSpanClass(range.classification); HtmlElementInfo hyperlinkInfo = GenerateLinks(range, destinationFilePath, localSymbolIdMap); if (hyperlinkInfo == null) { if (classAttributeValue == null) { sb.Append(html); return; } if (classAttributeValue == "k") { sb.Append("<b>").Append(html).Append("</b>"); return; } } var elementName = "span"; if (hyperlinkInfo != null) { elementName = hyperlinkInfo.Name; } sb.Append("<").Append(elementName); bool overridingClassAttributeSpecified = false; if (hyperlinkInfo != null) { foreach (var attribute in hyperlinkInfo.Attributes) { const string typeScriptFilesR = "/TypeScriptFiles/R/"; if (attribute.Key == "href" && attribute.Value.StartsWith(typeScriptFilesR, StringComparison.Ordinal)) { var streamPosition = sb.Length + 7 + typeScriptFilesR.Length; // exact offset into <a href="HERE ProjectGenerator.AddDeclaredSymbolToRedirectMap( SymbolIDToListOfLocationsMap, attribute.Value.Substring(typeScriptFilesR.Length, 16), localRelativePath, streamPosition); } AddAttribute(sb, attribute.Key, attribute.Value); if (attribute.Key == "class") { overridingClassAttributeSpecified = true; } } } if (!overridingClassAttributeSpecified) { AddAttribute(sb, "class", classAttributeValue); } sb.Append('>'); sb.Append(html); sb.Append("</").Append(elementName).Append(">"); } private void AddAttribute(StringBuilder sb, string name, string value) { if (value != null) { sb.Append(" ").Append(name).Append("=\"").Append(value).Append("\""); } } private int GetLocalId(string symbolId, Dictionary<string, int> localSymbolIdMap) { int localId = 0; if (!localSymbolIdMap.TryGetValue(symbolId, out localId)) { localId = localSymbolIdMap.Count; localSymbolIdMap.Add(symbolId, localId); } return localId; } private HtmlElementInfo GenerateLinks(ClassifiedRange range, string destinationHtmlFilePath, Dictionary<string, int> localSymbolIdMap) { HtmlElementInfo result = null; var localRelativePath = destinationHtmlFilePath.Substring( Path.Combine( Paths.SolutionDestinationFolder, Constants.TypeScriptFiles).Length); if (!string.IsNullOrEmpty(range.definitionSymbolId)) { var definitionSymbolId = SymbolIdService.GetId(range.definitionSymbolId); if (range.IsSymbolLocalOnly()) { var localId = GetLocalId(definitionSymbolId, localSymbolIdMap); result = new HtmlElementInfo { Name = "span", Attributes = { { "id", "r" + localId + " rd" }, { "class", "r" + localId + " r" } } }; return result; } result = new HtmlElementInfo { Name = "a", Attributes = { { "id", definitionSymbolId }, { "href", "/TypeScriptFiles/" + Constants.ReferencesFileName + "/" + definitionSymbolId + ".html" }, { "target", "n" } } }; var searchString = range.searchString; if (!string.IsNullOrEmpty(searchString) && searchString.Length > 2) { lock (declarations) { searchString = searchString.StripQuotes(); if (IsWellFormed(searchString)) { var declaration = string.Join(";", searchString, // symbol name definitionSymbolId, // 8-byte symbol ID range.definitionKind, // kind (e.g. "class") Markup.EscapeSemicolons(range.fullName), // symbol full name and signature GetGlyph(range.definitionKind) // glyph number ); declarations.Add(declaration); } } } } if (range.hyperlinks == null || range.hyperlinks.Length == 0) { return result; } var hyperlink = range.hyperlinks[0]; var symbolId = SymbolIdService.GetId(hyperlink.symbolId); if (range.IsSymbolLocalOnly() || localSymbolIdMap.ContainsKey(symbolId)) { var localId = GetLocalId(symbolId, localSymbolIdMap); result = new HtmlElementInfo { Name = "span", Attributes = { { "class", "r" + localId + " r" } } }; return result; } var hyperlinkDestinationFile = Path.GetFullPath(hyperlink.sourceFile); hyperlinkDestinationFile = GetDestinationFilePath(hyperlinkDestinationFile); string href = ""; if (!string.Equals(hyperlinkDestinationFile, destinationHtmlFilePath, StringComparison.OrdinalIgnoreCase)) { href = Paths.MakeRelativeToFile(hyperlinkDestinationFile, destinationHtmlFilePath); href = href.Replace('\\', '/'); } href = href + "#" + symbolId; if (result == null) { result = new HtmlElementInfo { Name = "a", Attributes = { { "href", href }, { "target", "s" }, } }; } else if (!result.Attributes.ContainsKey("href")) { result.Attributes.Add("href", href); result.Attributes.Add("target", "s"); } lock (this.references) { var lineNumber = range.lineNumber + 1; var linkToReference = ".." + localRelativePath + "#" + lineNumber.ToString(); var start = range.column; var end = range.column + range.text.Length; var lineText = Markup.HtmlEscape(range.lineText, ref start, ref end); var reference = new Reference { FromAssemblyId = Constants.TypeScriptFiles, ToAssemblyId = Constants.TypeScriptFiles, FromLocalPath = localRelativePath.Substring(0, localRelativePath.Length - ".html".Length).Replace('\\', '/'), Kind = ReferenceKind.Reference, ToSymbolId = symbolId, ToSymbolName = range.text, ReferenceLineNumber = lineNumber, ReferenceLineText = lineText, ReferenceColumnStart = start, ReferenceColumnEnd = end, Url = linkToReference.Replace('\\', '/') }; if (!references.TryGetValue(symbolId, out List<Reference> bucket)) { bucket = new List<Reference>(); references.Add(symbolId, bucket); } bucket.Add(reference); } return result; } private bool IsWellFormed(string searchString) { return searchString.Length > 2 && !searchString.Contains(";") && !searchString.Contains("\n"); } private string GetGlyph(string definitionKind) { switch (definitionKind) { case "variable": return "42"; case "function": return "72"; case "parameter": return "42"; case "interface": return "48"; case "property": return "102"; case "method": return "72"; case "type parameter": return "114"; case "module": return "150"; case "class": return "0"; case "constructor": return "72"; case "enum": return "18"; case "enum member": return "24"; case "import": return "6"; case "get accessor": return "72"; case "set accessor": return "72"; default: return "195"; } } private string GetSpanClass(string classification) { if (classification == "keyword") { return "k"; } else if (classification == "comment") { return "c"; } else if (classification == "string") { return "s"; } else if (classification == "class name") { return "t"; } else if (classification == "enum name") { return "t"; } else if (classification == "interface name" || classification == "type alias name") { return "t"; } else if (classification == "type parameter name") { return "t"; } else if (classification == "module name") { return "t"; } return null; } private string GetDisplayName(string destinationHtmlFilePath) { var result = Path.GetFileNameWithoutExtension(destinationHtmlFilePath); var lengthOfPrefixToTrim = Paths.SolutionDestinationFolder.Length + Constants.TypeScriptFiles.Length + 2; result = destinationHtmlFilePath.Substring(lengthOfPrefixToTrim, destinationHtmlFilePath.Length - lengthOfPrefixToTrim - 5); // strip ".html" return result; } } }
apache-2.0
credentials/irma_future_id
addons/abc/irma_configuration/README.md
1428
# IRMA Configuration files This repository contains all the configuration files for the irma project. It describes all the issuer and verifies and declares which credentials are issued respectively verified by these parties. In the normal branch private keys of the issuers are not included. Therefore it is **highly recommended** to use the *demo* branch when developping. This branch has a seperate set of keys and does include a private key for every issuer. ## Directory structure Stores configuration files per issuer/relying party. Typical directory structure: Organization +-- Issues | +-- CredetialName | +--- description.xml | +--- id.txt | +--- structure.xml +-- Verifies | +-- VerifySpecName | +--- description.xml | +--- specification.xml +-- private | +-- isk.xml (not present in master branch) +-- description.xml +-- baseURL.txt +-- gp.xml +-- ipk.xml +-- logo.png +-- sp.xml Finally, there is the special directory _android_ that contains a list of issuers and verifiers. ## Some notes on adding a new organization 1. Make sure you add a description for your organization, and a logo.png file. 2. Generate key material and put the public files into the tree (more information on this later) 3. For every credential this organization issues, make sure you use a unique id. 4. Remember to add your verifier/issuer to the appropriate lists in the android directory.
apache-2.0
mamandal/fleetchaincd
chaincode/marbles_chaincode.go
32592
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "errors" "fmt" "strconv" "encoding/json" "time" "strings" "github.com/hyperledger/fabric/core/chaincode/shim" ) // SimpleChaincode example simple Chaincode implementation type SimpleChaincode struct { } var marbleIndexStr = "_marbleindex" var driverIndexStr = "_driverindex" //name for the key/value that will store a list of all known marbles var openTradesStr = "_opentrades" //name for the key/value that will store all open trades type Marble struct{ Name string `json:"name"` //the fieldtags are needed to keep case from bouncing around Color string `json:"color"` Size int `json:"size"` User string `json:"user"` } type Driver struct{ FirstName string `json:"firstname"` //the fieldtags are needed to keep case from bouncing around LastName string `json:"lastname"` Email string `json:"email"` Mobile string `json:"mobile"` Password string `json:"password"` Street string `json:"street"` City string `json:"city"` State string `json:"state"` Zip string `json:"zip"` Status string `json:"status"` } type Description struct{ Color string `json:"color"` Size int `json:"size"` } type AnOpenTrade struct{ User string `json:"user"` //user who created the open trade order Timestamp int64 `json:"timestamp"` //utc timestamp of creation Want Description `json:"want"` //description of desired marble Willing []Description `json:"willing"` //array of marbles willing to trade away } type AllTrades struct{ OpenTrades []AnOpenTrade `json:"open_trades"` } type Adminlogin struct{ Userid string `json:"userid"` //User login for system Admin Password string `json:"password"` } // ============================================================================================================================ // Main // ============================================================================================================================ func main() { err := shim.Start(new(SimpleChaincode)) if err != nil { fmt.Printf("Error starting Simple chaincode: %s", err) } } // ============================================================================================================================ // Init - reset all the things // ============================================================================================================================ func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) { var Aval int var err error //Changes for the Hertz Blockchain if len(args) != 2 { return nil, errors.New("Incorrect number of arguments. Expecting 1") } //Write the User Id "mail Id" arg[0] and password arg[1] userid := args[0] //argument for UserID password := args[1] //argument for password str := `{"userid": "` + userid+ `", "password": "` + password + `"}` err = stub.PutState(userid, []byte(str)) //Put the userid and password in blockchain if err != nil { return nil, err } //End of Changes for the Hertz Blockchain} // Initialize the chaincode Aval, err = strconv.Atoi(args[0]) if err != nil { return nil, errors.New("Expecting integer value for asset holding") } // Write the state to the ledger err = stub.PutState("abc", []byte(strconv.Itoa(Aval))) //making a test var "abc", I find it handy to read/write to it right away to test the network if err != nil { return nil, err } var empty []string jsonAsBytes, _ := json.Marshal(empty) //marshal an emtpy array of strings to clear the index err = stub.PutState(marbleIndexStr, jsonAsBytes) if err != nil { return nil, err } //var empty []string //jsonAsBytes, _ := json.Marshal(empty) //marshal an emtpy array of strings to clear the index err = stub.PutState(driverIndexStr, jsonAsBytes) if err != nil { return nil, err } var trades AllTrades jsonAsBytes, _ = json.Marshal(trades) //clear the open trade struct err = stub.PutState(openTradesStr, jsonAsBytes) if err != nil { return nil, err } return nil, nil } // ============================================================================================================================ // Run - Our entry point for Invocations - [LEGACY] obc-peer 4/25/2016 // ============================================================================================================================ func (t *SimpleChaincode) Run(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) { fmt.Println("run is running " + function) return t.Invoke(stub, function, args) } // ============================================================================================================================ // Invoke - Our entry point for Invocations // ============================================================================================================================ func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) { fmt.Println("invoke is running " + function) // Handle different functions if function == "init" { //initialize the chaincode state, used as reset return t.Init(stub, "init", args) } else if function == "delete" { //deletes an entity from its state res, err := t.Delete(stub, args) cleanTrades(stub) //lets make sure all open trades are still valid return res, err } else if function == "write" { //writes a value to the chaincode state return t.Write(stub, args) } else if function == "init_marble" { //create a new marble return t.init_marble(stub, args) } else if function == "signup_driver" { //create a new marble return t.signup_driver(stub, args) } else if function == "set_user" { //change owner of a marble res, err := t.set_user(stub, args) cleanTrades(stub) //lets make sure all open trades are still valid return res, err }else if function == "set_status" { //change owner of a marble res, err := t.set_status(stub, args) cleanTrades(stub) //lets make sure all open trades are still valid return res, err } else if function == "open_trade" { //create a new trade order return t.open_trade(stub, args) } else if function == "perform_trade" { //forfill an open trade order res, err := t.perform_trade(stub, args) cleanTrades(stub) //lets clean just in case return res, err } else if function == "remove_trade" { //cancel an open trade order return t.remove_trade(stub, args) } fmt.Println("invoke did not find func: " + function) //error return nil, errors.New("Received unknown function invocation") } // ============================================================================================================================ // Query - Our entry point for Queries // ============================================================================================================================ func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) { fmt.Println("query is running " + function) // Handle different functions if function == "read" { //read a variable return t.read(stub, args) } else if function == "read_sysadmin" { //Read system admin User id and password return t.read_sysadmin(stub, args) } fmt.Println("query did not find func: " + function) //error return nil, errors.New("Received unknown function query") } // ============================================================================================================================ // Read - read a variable from chaincode state // ============================================================================================================================ func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { var name, jsonResp string var err error if len(args) != 1 { return nil, errors.New("Incorrect number of arguments. Expecting name of the var to query") } name = args[0] valAsbytes, err := stub.GetState(name) //get the var from chaincode state if err != nil { jsonResp = "{\"Error\":\"Failed to get state for " + name + "\"}" return nil, errors.New(jsonResp) } return valAsbytes, nil //send it onward } //============================================================= // Read - query function to read key/value pair (System Admin read User id and Password) //=============================================================================================================================== func (t *SimpleChaincode) read_sysadmin(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { var err error if len(args) != 1 { return nil, errors.New("Incorrect number of arguments. Expecting name of the key to query") } userid := args[0] PassAsbytes, err := stub.GetState(userid) if err != nil { jsonResp := "{\"Error\":\"Failed to get state for " + userid + "\"}" return nil, errors.New(jsonResp) } res := Adminlogin{} json.Unmarshal(PassAsbytes,&res) if res.Userid == userid{ fmt.Println("Userid Password Matched: " +res.Userid + res.Password) }else { fmt.Println("Wrong ID Password: " +res.Userid + res.Password) } return PassAsbytes, nil } // ============================================================================================================================ // Delete - remove a key/value pair from state // ============================================================================================================================ func (t *SimpleChaincode) Delete(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { if len(args) != 1 { return nil, errors.New("Incorrect number of arguments. Expecting 1") } name := args[0] err := stub.DelState(name) //remove the key from chaincode state if err != nil { return nil, errors.New("Failed to delete state") } //get the marble index marblesAsBytes, err := stub.GetState(marbleIndexStr) if err != nil { return nil, errors.New("Failed to get marble index") } var marbleIndex []string json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse() //remove marble from index for i,val := range marbleIndex{ fmt.Println(strconv.Itoa(i) + " - looking at " + val + " for " + name) if val == name{ //find the correct marble fmt.Println("found marble") marbleIndex = append(marbleIndex[:i], marbleIndex[i+1:]...) //remove it for x:= range marbleIndex{ //debug prints... fmt.Println(string(x) + " - " + marbleIndex[x]) } break } } jsonAsBytes, _ := json.Marshal(marbleIndex) //save new index err = stub.PutState(marbleIndexStr, jsonAsBytes) return nil, nil } // ============================================================================================================================ // Write - write variable into chaincode state // ============================================================================================================================ func (t *SimpleChaincode) Write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { var name, value string // Entities var err error fmt.Println("running write()") if len(args) != 2 { return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the variable and value to set") } name = args[0] //rename for funsies value = args[1] err = stub.PutState(name, []byte(value)) //write the variable into the chaincode state if err != nil { return nil, err } return nil, nil } // ============================================================================================================================ // Init Marble - create a new marble, store into chaincode state // ============================================================================================================================ func (t *SimpleChaincode) init_marble(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { var err error // 0 1 2 3 // "asdf", "blue", "35", "bob" if len(args) != 4 { return nil, errors.New("Incorrect number of arguments. Expecting 4") } fmt.Println("-Amit C code-Init_marble driver") //input sanitation fmt.Println("- start init marble") if len(args[0]) <= 0 { return nil, errors.New("1st argument must be a non-empty string") } if len(args[1]) <= 0 { return nil, errors.New("2nd argument must be a non-empty string") } if len(args[2]) <= 0 { return nil, errors.New("3rd argument must be a non-empty string") } if len(args[3]) <= 0 { return nil, errors.New("4th argument must be a non-empty string") } name := args[0] color := strings.ToLower(args[1]) user := strings.ToLower(args[3]) size, err := strconv.Atoi(args[2]) if err != nil { return nil, errors.New("3rd argument must be a numeric string") } //check if marble already exists marbleAsBytes, err := stub.GetState(name) if err != nil { return nil, errors.New("Failed to get marble name") } res := Marble{} json.Unmarshal(marbleAsBytes, &res) if res.Name == name{ fmt.Println("This marble arleady exists: " + name) fmt.Println(res); return nil, errors.New("This marble arleady exists") //all stop a marble by this name exists } //build the marble json string manually str := `{"name": "` + name + `", "color": "` + color + `", "size": ` + strconv.Itoa(size) + `, "user": "` + user + `"}` err = stub.PutState(name, []byte(str)) //store marble with id as key if err != nil { return nil, err } //get the marble index marblesAsBytes, err := stub.GetState(marbleIndexStr) if err != nil { return nil, errors.New("Failed to get marble index") } var marbleIndex []string json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse() //append marbleIndex = append(marbleIndex, name) //add marble name to index list fmt.Println("! marble index: ", marbleIndex) jsonAsBytes, _ := json.Marshal(marbleIndex) err = stub.PutState(marbleIndexStr, jsonAsBytes) //store name of marble fmt.Println("- end init marble") return nil, nil } // ============================================================================================================================ // Init Marble - create a new marble, store into chaincode state // ============================================================================================================================ func (t *SimpleChaincode) signup_driver(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { var err error // 0 1 2 3 // "Mainak", "Mandal", "[email protected]", "password" if len(args) != 9 { return nil, errors.New("Incorrect number of arguments. Expecting 4") } //input sanitation fmt.Println("- start signup driver") fmt.Println("-Amit C code-signup driver") if len(args[0]) <= 0 { return nil, errors.New("1st argument must be a non-empty string") } if len(args[1]) <= 0 { return nil, errors.New("2nd argument must be a non-empty string") } if len(args[2]) <= 0 { return nil, errors.New("3rd argument must be a non-empty string") } if len(args[3]) <= 0 { return nil, errors.New("4th argument must be a non-empty string") } if len(args[4]) <= 0 { return nil, errors.New("5th argument must be a non-empty string") } if len(args[5]) <= 0 { return nil, errors.New("6th argument must be a non-empty string") } if len(args[6]) <= 0 { return nil, errors.New("7th argument must be a non-empty string") } if len(args[7]) <= 0 { return nil, errors.New("8th argument must be a non-empty string") } if len(args[8]) <= 0 { return nil, errors.New("9th argument must be a non-empty string") } firstname := args[0] lastname := strings.ToLower(args[1]) email := strings.ToLower(args[2]) mobile := strings.ToLower(args[3]) password := strings.ToLower(args[4]) street := strings.ToLower(args[5]) city := strings.ToLower(args[6]) state := strings.ToLower(args[7]) zip := strings.ToLower(args[8]) status := "P" //if err != nil { //return nil, errors.New("3rd argument must be a numeric string") //} //check if marble already exists driverAsBytes, err := stub.GetState(email) if err != nil { return nil, errors.New("Failed to get driver name") } res := Driver{} json.Unmarshal(driverAsBytes, &res) if res.Email == email{ fmt.Println("This marble arleady exists: " + email) fmt.Println(res); return nil, errors.New("This driver arleady exists") //all stop a marble by this name exists } //build the marble json string manually str := `{"firstname": "` + firstname + `", "lastname": "` + lastname + `", "email": "` + email + `", "mobile": "` + mobile + `", "password": "` + password + `","street": "` + street + `","city": "` + city + `","state": "` + state + `","zip": "` + zip + `","status": "` + status + `"}` err = stub.PutState(email, []byte(str)) //store marble with id as key if err != nil { return nil, err } //get the driver index driversAsBytes, err := stub.GetState(driverIndexStr) if err != nil { return nil, errors.New("Failed to get driver index") } var driverIndex []string json.Unmarshal(driversAsBytes, &driverIndex) //un stringify it aka JSON.parse() //append driverIndex = append(driverIndex, email) //add marble name to index list fmt.Println("! driver index: ", driverIndex) jsonAsBytes, _ := json.Marshal(driverIndex) err = stub.PutState(driverIndexStr, jsonAsBytes) //store name of marble fmt.Println("- end signup driver") return nil, nil } // ============================================================================================================================ // Set User Permission on Marble // ============================================================================================================================ func (t *SimpleChaincode) set_user(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { var err error // 0 1 // "name", "bob" if len(args) < 2 { return nil, errors.New("Incorrect number of arguments. Expecting 2") } fmt.Println("- start set user") fmt.Println(args[0] + " - " + args[1]) marbleAsBytes, err := stub.GetState(args[0]) if err != nil { return nil, errors.New("Failed to get thing") } res := Marble{} json.Unmarshal(marbleAsBytes, &res) //un stringify it aka JSON.parse() res.User = args[1] //change the user jsonAsBytes, _ := json.Marshal(res) err = stub.PutState(args[0], jsonAsBytes) //rewrite the marble with id as key if err != nil { return nil, err } fmt.Println("- end set user") return nil, nil } // ============================================================================================================================ // Set User Permission on Marble // ============================================================================================================================ func (t *SimpleChaincode) set_status(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { var err error // 0 1 // "email", "status" if len(args) < 10 { return nil, errors.New("Incorrect number of arguments. Expecting 2") } fmt.Println("- start set user") fmt.Println(args[0] + " - " + args[1]) driverAsBytes, err := stub.GetState(args[0]) if err != nil { return nil, errors.New("Failed to get driver name") } res := Driver{} json.Unmarshal(driverAsBytes, &res) res.FirstName = args[1] //change the user res.LastName = args[2] res.Mobile = args[3] res.Password = args[4] res.Street = args[5] res.City = args[6] res.State = args[7] res.Zip = args[8] res.Status = args[9] jsonAsBytes, _ := json.Marshal(res) err = stub.PutState(args[0], jsonAsBytes) //rewrite the user status with email-id as key if err != nil { return nil, err } fmt.Println("- end set user") return nil, nil } // ============================================================================================================================ // Open Trade - create an open trade for a marble you want with marbles you have // ============================================================================================================================ func (t *SimpleChaincode) open_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { var err error var will_size int var trade_away Description // 0 1 2 3 4 5 6 //["bob", "blue", "16", "red", "16"] *"blue", "35* if len(args) < 5 { return nil, errors.New("Incorrect number of arguments. Expecting like 5?") } if len(args)%2 == 0{ return nil, errors.New("Incorrect number of arguments. Expecting an odd number") } size1, err := strconv.Atoi(args[2]) if err != nil { return nil, errors.New("3rd argument must be a numeric string") } open := AnOpenTrade{} open.User = args[0] open.Timestamp = makeTimestamp() //use timestamp as an ID open.Want.Color = args[1] open.Want.Size = size1 fmt.Println("- start open trade") jsonAsBytes, _ := json.Marshal(open) err = stub.PutState("_debug1", jsonAsBytes) for i:=3; i < len(args); i++ { //create and append each willing trade will_size, err = strconv.Atoi(args[i + 1]) if err != nil { msg := "is not a numeric string " + args[i + 1] fmt.Println(msg) return nil, errors.New(msg) } trade_away = Description{} trade_away.Color = args[i] trade_away.Size = will_size fmt.Println("! created trade_away: " + args[i]) jsonAsBytes, _ = json.Marshal(trade_away) err = stub.PutState("_debug2", jsonAsBytes) open.Willing = append(open.Willing, trade_away) fmt.Println("! appended willing to open") i++; } //get the open trade struct tradesAsBytes, err := stub.GetState(openTradesStr) if err != nil { return nil, errors.New("Failed to get opentrades") } var trades AllTrades json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse() trades.OpenTrades = append(trades.OpenTrades, open); //append to open trades fmt.Println("! appended open to trades") jsonAsBytes, _ = json.Marshal(trades) err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders if err != nil { return nil, err } fmt.Println("- end open trade") return nil, nil } // ============================================================================================================================ // Perform Trade - close an open trade and move ownership // ============================================================================================================================ func (t *SimpleChaincode) perform_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { var err error // 0 1 2 3 4 5 //[data.id, data.closer.user, data.closer.name, data.opener.user, data.opener.color, data.opener.size] if len(args) < 6 { return nil, errors.New("Incorrect number of arguments. Expecting 6") } fmt.Println("- start close trade") timestamp, err := strconv.ParseInt(args[0], 10, 64) if err != nil { return nil, errors.New("1st argument must be a numeric string") } size, err := strconv.Atoi(args[5]) if err != nil { return nil, errors.New("6th argument must be a numeric string") } //get the open trade struct tradesAsBytes, err := stub.GetState(openTradesStr) if err != nil { return nil, errors.New("Failed to get opentrades") } var trades AllTrades json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse() for i := range trades.OpenTrades{ //look for the trade fmt.Println("looking at " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10) + " for " + strconv.FormatInt(timestamp, 10)) if trades.OpenTrades[i].Timestamp == timestamp{ fmt.Println("found the trade"); marbleAsBytes, err := stub.GetState(args[2]) if err != nil { return nil, errors.New("Failed to get thing") } closersMarble := Marble{} json.Unmarshal(marbleAsBytes, &closersMarble) //un stringify it aka JSON.parse() //verify if marble meets trade requirements if closersMarble.Color != trades.OpenTrades[i].Want.Color || closersMarble.Size != trades.OpenTrades[i].Want.Size { msg := "marble in input does not meet trade requriements" fmt.Println(msg) return nil, errors.New(msg) } marble, e := findMarble4Trade(stub, trades.OpenTrades[i].User, args[4], size) //find a marble that is suitable from opener if(e == nil){ fmt.Println("! no errors, proceeding") t.set_user(stub, []string{args[2], trades.OpenTrades[i].User}) //change owner of selected marble, closer -> opener t.set_user(stub, []string{marble.Name, args[1]}) //change owner of selected marble, opener -> closer trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove trade jsonAsBytes, _ := json.Marshal(trades) err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders if err != nil { return nil, err } } } } fmt.Println("- end close trade") return nil, nil } // ============================================================================================================================ // findMarble4Trade - look for a matching marble that this user owns and return it // ============================================================================================================================ func findMarble4Trade(stub shim.ChaincodeStubInterface, user string, color string, size int )(m Marble, err error){ var fail Marble; fmt.Println("- start find marble 4 trade") fmt.Println("looking for " + user + ", " + color + ", " + strconv.Itoa(size)); //get the marble index marblesAsBytes, err := stub.GetState(marbleIndexStr) if err != nil { return fail, errors.New("Failed to get marble index") } var marbleIndex []string json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse() for i:= range marbleIndex{ //iter through all the marbles //fmt.Println("looking @ marble name: " + marbleIndex[i]); marbleAsBytes, err := stub.GetState(marbleIndex[i]) //grab this marble if err != nil { return fail, errors.New("Failed to get marble") } res := Marble{} json.Unmarshal(marbleAsBytes, &res) //un stringify it aka JSON.parse() //fmt.Println("looking @ " + res.User + ", " + res.Color + ", " + strconv.Itoa(res.Size)); //check for user && color && size if strings.ToLower(res.User) == strings.ToLower(user) && strings.ToLower(res.Color) == strings.ToLower(color) && res.Size == size{ fmt.Println("found a marble: " + res.Name) fmt.Println("! end find marble 4 trade") return res, nil } } fmt.Println("- end find marble 4 trade - error") return fail, errors.New("Did not find marble to use in this trade") } // ============================================================================================================================ // Make Timestamp - create a timestamp in ms // ============================================================================================================================ func makeTimestamp() int64 { return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond)) } // ============================================================================================================================ // Remove Open Trade - close an open trade // ============================================================================================================================ func (t *SimpleChaincode) remove_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) { var err error // 0 //[data.id] if len(args) < 1 { return nil, errors.New("Incorrect number of arguments. Expecting 1") } fmt.Println("- start remove trade") timestamp, err := strconv.ParseInt(args[0], 10, 64) if err != nil { return nil, errors.New("1st argument must be a numeric string") } //get the open trade struct tradesAsBytes, err := stub.GetState(openTradesStr) if err != nil { return nil, errors.New("Failed to get opentrades") } var trades AllTrades json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse() for i := range trades.OpenTrades{ //look for the trade //fmt.Println("looking at " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10) + " for " + strconv.FormatInt(timestamp, 10)) if trades.OpenTrades[i].Timestamp == timestamp{ fmt.Println("found the trade"); trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove this trade jsonAsBytes, _ := json.Marshal(trades) err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders if err != nil { return nil, err } break } } fmt.Println("- end remove trade") return nil, nil } // ============================================================================================================================ // Clean Up Open Trades - make sure open trades are still possible, remove choices that are no longer possible, remove trades that have no valid choices // ============================================================================================================================ func cleanTrades(stub shim.ChaincodeStubInterface)(err error){ var didWork = false fmt.Println("- start clean trades") //get the open trade struct tradesAsBytes, err := stub.GetState(openTradesStr) if err != nil { return errors.New("Failed to get opentrades") } var trades AllTrades json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse() fmt.Println("# trades " + strconv.Itoa(len(trades.OpenTrades))) for i:=0; i<len(trades.OpenTrades); { //iter over all the known open trades fmt.Println(strconv.Itoa(i) + ": looking at trade " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10)) fmt.Println("# options " + strconv.Itoa(len(trades.OpenTrades[i].Willing))) for x:=0; x<len(trades.OpenTrades[i].Willing); { //find a marble that is suitable fmt.Println("! on next option " + strconv.Itoa(i) + ":" + strconv.Itoa(x)) _, e := findMarble4Trade(stub, trades.OpenTrades[i].User, trades.OpenTrades[i].Willing[x].Color, trades.OpenTrades[i].Willing[x].Size) if(e != nil){ fmt.Println("! errors with this option, removing option") didWork = true trades.OpenTrades[i].Willing = append(trades.OpenTrades[i].Willing[:x], trades.OpenTrades[i].Willing[x+1:]...) //remove this option x--; }else{ fmt.Println("! this option is fine") } x++ fmt.Println("! x:" + strconv.Itoa(x)) if x >= len(trades.OpenTrades[i].Willing) { //things might have shifted, recalcuate break } } if len(trades.OpenTrades[i].Willing) == 0 { fmt.Println("! no more options for this trade, removing trade") didWork = true trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove this trade i--; } i++ fmt.Println("! i:" + strconv.Itoa(i)) if i >= len(trades.OpenTrades) { //things might have shifted, recalcuate break } } if(didWork){ fmt.Println("! saving open trade changes") jsonAsBytes, _ := json.Marshal(trades) err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders if err != nil { return err } }else{ fmt.Println("! all open trades are fine") } fmt.Println("- end clean trades") return nil }
apache-2.0
XElementDev/SDM
code/Startup/ManagementLogic.Implementation/AbstractProgramLogic.cs
661
using XElement.DotNet.System.Environment.Startup; namespace XElement.SDM.ManagementLogic { #region not unit-tested internal abstract class AbstractProgramLogic : IProgramLogic { protected AbstractProgramLogic( IProgramInfo programInfo ) { this._programInfo = programInfo; } public abstract void /*IProgramLogic.*/DelayStartup(); public void /*IProgramLogic.*/Do() { this.DelayStartup(); } public abstract void /*IProgramLogic.*/PromoteStartup(); public void /*IProgramLogic.*/Undo() { this.PromoteStartup(); } protected IProgramInfo _programInfo; } #endregion }
apache-2.0
directonlijn/app
app/resources/views/emails/hippiemarkt-aalsmeer-factuur.blade.php
34222
<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <!-- NAME: 1 COLUMN --> <!--[if gte mso 15]> <xml> <o:OfficeDocumentSettings> <o:AllowPNG/> <o:PixelsPerInch>96</o:PixelsPerInch> </o:OfficeDocumentSettings> </xml> <![endif]--> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Factuur</title> <style type="text/css"> p{ margin:10px 0; padding:0; } table{ border-collapse:collapse; } h1,h2,h3,h4,h5,h6{ display:block; margin:0; padding:0; } img,a img{ border:0; height:auto; outline:none; text-decoration:none; } body,#bodyTable,#bodyCell{ height:100%; margin:0; padding:0; width:100%; } #outlook a{ padding:0; } img{ -ms-interpolation-mode:bicubic; } table{ mso-table-lspace:0pt; mso-table-rspace:0pt; } .ReadMsgBody{ width:100%; } .ExternalClass{ width:100%; } p,a,li,td,blockquote{ mso-line-height-rule:exactly; } a[href^=tel],a[href^=sms]{ color:inherit; cursor:default; text-decoration:none; } p,a,li,td,body,table,blockquote{ -ms-text-size-adjust:100%; -webkit-text-size-adjust:100%; } .ExternalClass,.ExternalClass p,.ExternalClass td,.ExternalClass div,.ExternalClass span,.ExternalClass font{ line-height:100%; } a[x-apple-data-detectors]{ color:inherit !important; text-decoration:none !important; font-size:inherit !important; font-family:inherit !important; font-weight:inherit !important; line-height:inherit !important; } #bodyCell{ padding:10px; } .templateContainer{ max-width:600px !important; } a.mcnButton{ display:block; } .mcnImage{ vertical-align:bottom; } .mcnTextContent{ word-break:break-word; } .mcnTextContent img{ height:auto !important; } .mcnDividerBlock{ table-layout:fixed !important; } body,#bodyTable{ background-color:#FAFAFA; } #bodyCell{ border-top:0; } .templateContainer{ border:0; } h1{ color:#202020; font-family:Helvetica; font-size:26px; font-style:normal; font-weight:bold; line-height:125%; letter-spacing:normal; text-align:left; } h2{ color:#202020; font-family:Helvetica; font-size:22px; font-style:normal; font-weight:bold; line-height:125%; letter-spacing:normal; text-align:left; } h3{ color:#202020; font-family:Helvetica; font-size:20px; font-style:normal; font-weight:bold; line-height:125%; letter-spacing:normal; text-align:left; } h4{ color:#202020; font-family:Helvetica; font-size:18px; font-style:normal; font-weight:bold; line-height:125%; letter-spacing:normal; text-align:left; } #templatePreheader{ background-color:#FAFAFA; background-image:none; background-repeat:no-repeat; background-position:center; background-size:cover; border-top:0; border-bottom:0; padding-top:9px; padding-bottom:9px; } #templatePreheader .mcnTextContent,#templatePreheader .mcnTextContent p{ color:#656565; font-family:Helvetica; font-size:12px; line-height:150%; text-align:left; } #templatePreheader .mcnTextContent a,#templatePreheader .mcnTextContent p a{ color:#656565; font-weight:normal; text-decoration:underline; } #templateHeader{ background-color:#FFFFFF; background-image:none; background-repeat:no-repeat; background-position:center; background-size:cover; border-top:0; border-bottom:0; padding-top:9px; padding-bottom:0; } #templateHeader .mcnTextContent,#templateHeader .mcnTextContent p{ color:#202020; font-family:Helvetica; font-size:16px; line-height:150%; text-align:left; } #templateHeader .mcnTextContent a,#templateHeader .mcnTextContent p a{ color:#2BAADF; font-weight:normal; text-decoration:underline; } #templateBody{ background-color:#FFFFFF; background-image:none; background-repeat:no-repeat; background-position:center; background-size:cover; border-top:0; border-bottom:2px solid #EAEAEA; padding-top:0; padding-bottom:9px; } #templateBody .mcnTextContent,#templateBody .mcnTextContent p{ color:#202020; font-family:Helvetica; font-size:16px; line-height:150%; text-align:left; } #templateBody .mcnTextContent a,#templateBody .mcnTextContent p a{ color:#2BAADF; font-weight:normal; text-decoration:underline; } #templateFooter{ background-color:#FAFAFA; background-image:none; background-repeat:no-repeat; background-position:center; background-size:cover; border-top:0; border-bottom:0; padding-top:9px; padding-bottom:9px; } #templateFooter .mcnTextContent,#templateFooter .mcnTextContent p{ color:#656565; font-family:Helvetica; font-size:12px; line-height:150%; text-align:center; } #templateFooter .mcnTextContent a,#templateFooter .mcnTextContent p a{ color:#656565; font-weight:normal; text-decoration:underline; } @media only screen and (min-width:768px){ .templateContainer{ width:600px !important; } } @media only screen and (max-width: 480px){ body,table,td,p,a,li,blockquote{ -webkit-text-size-adjust:none !important; } } @media only screen and (max-width: 480px){ body{ width:100% !important; min-width:100% !important; } } @media only screen and (max-width: 480px){ #bodyCell{ padding-top:10px !important; } } @media only screen and (max-width: 480px){ .mcnImage{ width:100% !important; } } @media only screen and (max-width: 480px){ .mcnCartContainer,.mcnCaptionTopContent,.mcnRecContentContainer,.mcnCaptionBottomContent,.mcnTextContentContainer,.mcnBoxedTextContentContainer,.mcnImageGroupContentContainer,.mcnCaptionLeftTextContentContainer,.mcnCaptionRightTextContentContainer,.mcnCaptionLeftImageContentContainer,.mcnCaptionRightImageContentContainer,.mcnImageCardLeftTextContentContainer,.mcnImageCardRightTextContentContainer{ max-width:100% !important; width:100% !important; } } @media only screen and (max-width: 480px){ .mcnBoxedTextContentContainer{ min-width:100% !important; } } @media only screen and (max-width: 480px){ .mcnImageGroupContent{ padding:9px !important; } } @media only screen and (max-width: 480px){ .mcnCaptionLeftContentOuter .mcnTextContent,.mcnCaptionRightContentOuter .mcnTextContent{ padding-top:9px !important; } } @media only screen and (max-width: 480px){ .mcnImageCardTopImageContent,.mcnCaptionBlockInner .mcnCaptionTopContent:last-child .mcnTextContent{ padding-top:18px !important; } } @media only screen and (max-width: 480px){ .mcnImageCardBottomImageContent{ padding-bottom:9px !important; } } @media only screen and (max-width: 480px){ .mcnImageGroupBlockInner{ padding-top:0 !important; padding-bottom:0 !important; } } @media only screen and (max-width: 480px){ .mcnImageGroupBlockOuter{ padding-top:9px !important; padding-bottom:9px !important; } } @media only screen and (max-width: 480px){ .mcnTextContent,.mcnBoxedTextContentColumn{ padding-right:18px !important; padding-left:18px !important; } } @media only screen and (max-width: 480px){ .mcnImageCardLeftImageContent,.mcnImageCardRightImageContent{ padding-right:18px !important; padding-bottom:0 !important; padding-left:18px !important; } } @media only screen and (max-width: 480px){ .mcpreview-image-uploader{ display:none !important; width:100% !important; } } @media only screen and (max-width: 480px){ h1{ font-size:22px !important; line-height:125% !important; } } @media only screen and (max-width: 480px){ h2{ font-size:20px !important; line-height:125% !important; } } @media only screen and (max-width: 480px){ h3{ font-size:18px !important; line-height:125% !important; } } @media only screen and (max-width: 480px){ h4{ font-size:16px !important; line-height:150% !important; } } @media only screen and (max-width: 480px){ .mcnBoxedTextContentContainer .mcnTextContent,.mcnBoxedTextContentContainer .mcnTextContent p{ font-size:14px !important; line-height:150% !important; } } @media only screen and (max-width: 480px){ #templatePreheader{ display:block !important; } } @media only screen and (max-width: 480px){ #templatePreheader .mcnTextContent,#templatePreheader .mcnTextContent p{ font-size:14px !important; line-height:150% !important; } } @media only screen and (max-width: 480px){ #templateHeader .mcnTextContent,#templateHeader .mcnTextContent p{ font-size:16px !important; line-height:150% !important; } } @media only screen and (max-width: 480px){ #templateBody .mcnTextContent,#templateBody .mcnTextContent p{ font-size:16px !important; line-height:150% !important; } } @media only screen and (max-width: 480px){ #templateFooter .mcnTextContent,#templateFooter .mcnTextContent p{ font-size:14px !important; line-height:150% !important; } }</style></head> <body style="height: 100%;margin: 0;padding: 0;width: 100%;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FAFAFA;"> <center> <table align="center" border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" id="bodyTable" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;height: 100%;margin: 0;padding: 0;width: 100%;background-color: #FAFAFA;"> <tr> <td align="center" valign="top" id="bodyCell" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;height: 100%;margin: 0;padding: 10px;width: 100%;border-top: 0;"> <!-- BEGIN TEMPLATE // --> <!--[if gte mso 9]> <table align="center" border="0" cellspacing="0" cellpadding="0" width="600" style="width:600px;"> <tr> <td align="center" valign="top" width="600" style="width:600px;"> <![endif]--> <table border="0" cellpadding="0" cellspacing="0" width="100%" class="templateContainer" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;border: 0;max-width: 600px !important;"> <tr> <td valign="top" id="templatePreheader" style="background:#FAFAFA none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FAFAFA;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 0;padding-top: 9px;padding-bottom: 9px;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnTextBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody class="mcnTextBlockOuter"> <tr> <td valign="top" class="mcnTextBlockInner" style="padding-top: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <!--[if mso]> <table align="left" border="0" cellspacing="0" cellpadding="0" width="100%" style="width:100%;"> <tr> <![endif]--> <!--[if mso]> <td valign="top" width="390" style="width:390px;"> <![endif]--> <table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 390px;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer"> <tbody><tr> <td valign="top" class="mcnTextContent" style="padding-top: 0;padding-left: 18px;padding-bottom: 9px;padding-right: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #656565;font-family: Helvetica;font-size: 12px;line-height: 150%;text-align: left;"> Factuur Hippiemarkt Aalsmeer </td> </tr> </tbody></table> <!--[if mso]> </td> <![endif]--> <!--[if mso]> <td valign="top" width="210" style="width:210px;"> <![endif]--> <table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 210px;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer"> <tbody><tr> <td valign="top" class="mcnTextContent" style="padding-top: 0;padding-left: 18px;padding-bottom: 9px;padding-right: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #656565;font-family: Helvetica;font-size: 12px;line-height: 150%;text-align: left;"> <a href="http://app.directevents.nl/mail/view/hippiemarkt-aalsmeer-factuur" target="_blank" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;color: #656565;font-weight: normal;text-decoration: underline;">Mail niet leesbaar of graag in uw browser openen? Klik hier.</a> </td> </tr> </tbody></table> <!--[if mso]> </td> <![endif]--> <!--[if mso]> </tr> </table> <![endif]--> </td> </tr> </tbody> </table></td> </tr> <tr> <td valign="top" id="templateHeader" style="background:#FFFFFF none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FFFFFF;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 0;padding-top: 9px;padding-bottom: 0;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnImageBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody class="mcnImageBlockOuter"> <tr> <td valign="top" style="padding: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnImageBlockInner"> <table align="left" width="100%" border="0" cellpadding="0" cellspacing="0" class="mcnImageContentContainer" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td class="mcnImageContent" valign="top" style="padding-right: 9px;padding-left: 9px;padding-top: 0;padding-bottom: 0;text-align: center;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <img align="center" alt="" src="http://app.directevents.nl/assets/img/hippiemarkt-aalsmeer/mail-header.png" width="564" style="max-width: 799px;padding-bottom: 0;display: inline !important;vertical-align: bottom;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" class="mcnImage"> </td> </tr> </tbody></table> </td> </tr> </tbody> </table></td> </tr> <tr> <td valign="top" id="templateBody" style="background:#FFFFFF none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FFFFFF;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 2px solid #EAEAEA;padding-top: 0;padding-bottom: 9px;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnTextBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody class="mcnTextBlockOuter"> <tr> <td valign="top" class="mcnTextBlockInner" style="padding-top: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <!--[if mso]> <table align="left" border="0" cellspacing="0" cellpadding="0" width="100%" style="width:100%;"> <tr> <![endif]--> <!--[if mso]> <td valign="top" width="600" style="width:600px;"> <![endif]--> <table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 100%;min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer"> <tbody><tr> <td valign="top" class="mcnTextContent" style="padding-top: 0;padding-right: 18px;padding-bottom: 9px;padding-left: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #202020;font-family: Helvetica;font-size: 16px;line-height: 150%;text-align: left;"> <h1 style="display: block;margin: 0;padding: 0;color: #202020;font-family: Helvetica;font-size: 26px;font-style: normal;font-weight: bold;line-height: 125%;letter-spacing: normal;text-align: left;">Factuur Hippiemarkt Aalsmeer</h1> <p style="margin: 10px 0;padding: 0;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;color: #202020;font-family: Helvetica;font-size: 16px;line-height: 150%;text-align: left;">Beste Standhouder,<br>  <br> Bedankt voor uw inschrijving voor De Hippiemarkt Aalsmeer op vrijdag 27 juli.<br>  <br> Wij zijn enorm druk met alle voorbereidingen om de markt tot een succes te laten verlopen. In de bijlage sturen wij de algemene voorwaarden (met onder andere opbouw en afbouw tijden) en de factuur.<br>  <br> Pas na ontvangst van uw betaling is uw inschrijving definitief.<br>  <br> Tot vrijdag 27 juli op het surfeiland te Aalsmeer,<br>  <br> Contact informatie:<br> [email protected]<br>  </p> </td> </tr> </tbody></table> <!--[if mso]> </td> <![endif]--> <!--[if mso]> </tr> </table> <![endif]--> </td> </tr> </tbody> </table></td> </tr> <tr> <td valign="top" id="templateFooter" style="background:#FAFAFA none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FAFAFA;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 0;padding-top: 9px;padding-bottom: 9px;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnImageBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody class="mcnImageBlockOuter"> <tr> <td valign="top" style="padding: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnImageBlockInner"> <table align="left" width="100%" border="0" cellpadding="0" cellspacing="0" class="mcnImageContentContainer" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td class="mcnImageContent" valign="top" style="padding-right: 9px;padding-left: 9px;padding-top: 0;padding-bottom: 0;text-align: center;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <img align="center" alt="" src="https://gallery.mailchimp.com/042b4e4809d32ad5aa6147613/images/0bbee562-e766-4dda-83ca-4474a23a419b.png" width="564" style="max-width: 975px;padding-bottom: 0;display: inline !important;vertical-align: bottom;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" class="mcnImage"> </td> </tr> </tbody></table> </td> </tr> </tbody> </table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody class="mcnFollowBlockOuter"> <tr> <td align="center" valign="top" style="padding: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowBlockInner"> <table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowContentContainer" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td align="center" style="padding-left: 9px;padding-right: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <table border="0" cellpadding="0" cellspacing="0" width="100%" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowContent"> <tbody><tr> <td align="center" valign="top" style="padding-top: 9px;padding-right: 9px;padding-left: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <table align="center" border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td align="center" valign="top" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <!--[if mso]> <table align="center" border="0" cellspacing="0" cellpadding="0"> <tr> <![endif]--> <!--[if mso]> <td align="center" valign="top"> <![endif]--> <table align="left" border="0" cellpadding="0" cellspacing="0" style="display: inline;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td valign="top" style="padding-right: 10px;padding-bottom: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowContentItemContainer"> <table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowContentItem" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td align="left" valign="middle" style="padding-top: 5px;padding-right: 10px;padding-bottom: 5px;padding-left: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <table align="left" border="0" cellpadding="0" cellspacing="0" width="" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td align="center" valign="middle" width="24" class="mcnFollowIconContent" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <a href="https://www.facebook.com/events/434974326975583/" target="_blank" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"><img src="https://cdn-images.mailchimp.com/icons/social-block-v2/color-facebook-48.png" style="display: block;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" height="24" width="24" class=""></a> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </td> </tr> </tbody></table> <!--[if mso]> </td> <![endif]--> <!--[if mso]> <td align="center" valign="top"> <![endif]--> <table align="left" border="0" cellpadding="0" cellspacing="0" style="display: inline;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td valign="top" style="padding-right: 0;padding-bottom: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowContentItemContainer"> <table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowContentItem" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td align="left" valign="middle" style="padding-top: 5px;padding-right: 10px;padding-bottom: 5px;padding-left: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <table align="left" border="0" cellpadding="0" cellspacing="0" width="" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td align="center" valign="middle" width="24" class="mcnFollowIconContent" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <a href="http://www.hippiemarktaalsmeer.nl/" target="_blank" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"><img src="https://cdn-images.mailchimp.com/icons/social-block-v2/color-link-48.png" style="display: block;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" height="24" width="24" class=""></a> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </td> </tr> </tbody></table> <!--[if mso]> </td> <![endif]--> <!--[if mso]> </tr> </table> <![endif]--> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </td> </tr> </tbody></table> </td> </tr> </tbody> </table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnDividerBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;table-layout: fixed !important;"> <tbody class="mcnDividerBlockOuter"> <tr> <td class="mcnDividerBlockInner" style="min-width: 100%;padding: 10px 18px 25px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <table class="mcnDividerContent" border="0" cellpadding="0" cellspacing="0" width="100%" style="min-width: 100%;border-top-width: 2px;border-top-style: solid;border-top-color: #EEEEEE;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody><tr> <td style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <span></span> </td> </tr> </tbody></table> <!-- <td class="mcnDividerBlockInner" style="padding: 18px;"> <hr class="mcnDividerContent" style="border-bottom-color:none; border-left-color:none; border-right-color:none; border-bottom-width:0; border-left-width:0; border-right-width:0; margin-top:0; margin-right:0; margin-bottom:0; margin-left:0;" /> --> </td> </tr> </tbody> </table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnTextBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <tbody class="mcnTextBlockOuter"> <tr> <td valign="top" class="mcnTextBlockInner" style="padding-top: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"> <!--[if mso]> <table align="left" border="0" cellspacing="0" cellpadding="0" width="100%" style="width:100%;"> <tr> <![endif]--> <!--[if mso]> <td valign="top" width="600" style="width:600px;"> <![endif]--> <table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 100%;min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer"> <tbody><tr> <td valign="top" class="mcnTextContent" style="padding-top: 0;padding-right: 18px;padding-bottom: 9px;padding-left: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #656565;font-family: Helvetica;font-size: 12px;line-height: 150%;text-align: center;"> <em>Copyright © 2017 Direct Events, All rights reserved.</em><br> <br> [email protected]<br></td> </tr> </tbody></table> <!--[if mso]> </td> <![endif]--> <!--[if mso]> </tr> </table> <![endif]--> </td> </tr> </tbody> </table></td> </tr> </table> <!--[if gte mso 9]> </td> </tr> </table> <![endif]--> <!-- // END TEMPLATE --> </td> </tr> </table> </center> <center> <style type="text/css"> @media only screen and (max-width: 480px){ table#canspamBar td{font-size:14px !important;} table#canspamBar td a{display:block !important; margin-top:10px !important;} } </style> </center></body> </html>
apache-2.0
goxhaj/gastronomee
src/main/webapp/app/dashboard/menu/menu-delete-dialog.controller.js
694
(function() { 'use strict'; angular .module('gastronomeeApp') .controller('MenuDeleteController',MenuDeleteController); MenuDeleteController.$inject = ['$uibModalInstance', 'entity', 'Menu']; function MenuDeleteController($uibModalInstance, entity, Menu) { var vm = this; vm.menu = entity; vm.clear = clear; vm.confirmDelete = confirmDelete; function clear () { $uibModalInstance.dismiss('cancel'); } function confirmDelete (id) { Menu.delete({id: id}, function () { $uibModalInstance.close(true); }); } } })();
apache-2.0
google/gapid
gapic/src/main/com/google/gapid/perfetto/models/Track.java
11222
/* * Copyright (C) 2019 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. */ package com.google.gapid.perfetto.models; import static com.google.gapid.util.MoreFutures.logFailure; import static com.google.gapid.util.MoreFutures.transform; import static com.google.gapid.util.MoreFutures.transformAsync; import static com.google.gapid.util.Scheduler.EXECUTOR; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import com.google.common.cache.Cache; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.gapid.perfetto.TimeSpan; import com.google.gapid.util.Caches; import java.util.List; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.logging.Logger; // Note on multi-threading issues here: // Because of how the window tables work, the below computeData(..) calls have to be serialized // by track. That is, data for different requests can not be fetched in parallel. Thus, the calls // to computeData(..) are funneled through the getDataLock semaphore. Care needs to be taken not to // block the executor threads indefinitely, as otherwise a deadlock could occur, due to the results // of the query futures no longer being able to be executed. Thus, the semaphore is try-acquired // with a short timeout, followed by a slightly longer wait, before retrying. /** * A {@link Track} is responsible for loading the data to be shown in the UI. */ public abstract class Track<D extends Track.Data> { private static final Logger LOG = Logger.getLogger(Track.class.getName()); public static final long QUANTIZE_CUT_OFF = 2000; private static final long REQUEST_DELAY_MS = 50; private static final long ACQUIRE_TIMEOUT_MS = 5; private static final long ACQUIRE_RETRY_MS = 10; private static final long PAGE_SIZE = 3600; private static DataCache cache = new DataCache(); private final String trackId; private D data; private ListenableFuture<?> scheduledFuture; // Set to null on any thread, set to non-null only on the UI thread. private final AtomicReference<ScheduledRequest<D>> scheduledRequest = new AtomicReference<ScheduledRequest<D>>(null); private final Semaphore getDataLock = new Semaphore(1); private boolean initialized; // guarded by getDataLock public Track(String trackId) { this.trackId = trackId.replace("-", "_"); } public String getId() { return trackId; } // on UI Thread public D getData(DataRequest req, OnUiThread<D> onUiThread) { if (checkScheduledRequest(req, onUiThread) && (data == null || !data.request.satisfies(req))) { schedule(req.pageAlign(), onUiThread); } return data; } // on UI Thread. returns true, if a new request may be scheduled. private boolean checkScheduledRequest(DataRequest req, OnUiThread<D> callback) { ScheduledRequest<D> scheduled = scheduledRequest.get(); if (scheduled == null) { return true; } else if (scheduled.satisfies(req)) { scheduled.addCallback(callback); return false; } scheduledFuture.cancel(true); scheduledFuture = null; scheduledRequest.set(null); return true; } // on UI Thread private void schedule(DataRequest request, OnUiThread<D> onUiThread) { D newData = cache.getIfPresent(this, request); if (newData != null) { data = newData; return; } ScheduledRequest<D> scheduled = new ScheduledRequest<D>(request, onUiThread); scheduledRequest.set(scheduled); scheduledFuture = EXECUTOR.schedule( () -> query(scheduled), REQUEST_DELAY_MS, MILLISECONDS); } // *not* on UI Thread private void query(ScheduledRequest<D> scheduled) { try { if (!getDataLock.tryAcquire(ACQUIRE_TIMEOUT_MS, MILLISECONDS)) { logFailure(LOG, EXECUTOR.schedule( () -> query(scheduled), ACQUIRE_RETRY_MS, MILLISECONDS)); return; } } catch (InterruptedException e) { // We were cancelled while waiting on the lock. scheduledRequest.compareAndSet(scheduled, null); return; } if (scheduledRequest.get() != scheduled) { getDataLock.release(); return; } try { ListenableFuture<D> future = transformAsync(setup(), $ -> computeData(scheduled.request)); scheduled.scheduleCallbacks(future, newData -> update(scheduled, newData)); // Always unlock when the future completes/fails/is cancelled. future.addListener(getDataLock::release, EXECUTOR); } catch (RuntimeException e) { getDataLock.release(); throw e; } } // on UI Thread private void update(ScheduledRequest<D> scheduled, D newData) { cache.put(this, scheduled.request, newData); if (scheduledRequest.compareAndSet(scheduled, null)) { data = newData; scheduledFuture = null; } } private ListenableFuture<?> setup() { if (initialized) { return Futures.immediateFuture(null); } return transform(initialize(), $ -> initialized = true); } protected abstract ListenableFuture<?> initialize(); protected abstract ListenableFuture<D> computeData(DataRequest req); protected String tableName(String prefix) { return prefix + "_" + trackId; } public static interface OnUiThread<T> { /** * Runs the consumer with the result of the given future on the UI thread. */ public void onUiThread(ListenableFuture<T> future, Consumer<T> callback); public void repaint(); } public static class Data { public final DataRequest request; public Data(DataRequest request) { this.request = request; } } public static class DataRequest { public final TimeSpan range; public final long resolution; public DataRequest(TimeSpan range, long resolution) { this.range = range; this.resolution = resolution; } public DataRequest pageAlign() { return new DataRequest(range.align(PAGE_SIZE * resolution), resolution); } public boolean satisfies(DataRequest other) { return resolution == other.resolution && range.contains(other.range); } @Override public String toString() { return "Request{start: " + range.start + ", end: " + range.end + ", res: " + resolution + "}"; } } public static class Window { private static final long RESOLUTION_QUANTIZE_CUTOFF = MICROSECONDS.toNanos(80); private static final String UPDATE_SQL = "update %s set " + "window_start = %d, window_dur = %d, quantum = %d where rowid = 0"; public final long start; public final long end; public final boolean quantized; public final long bucketSize; private Window(long start, long end, boolean quantized, long bucketSize) { this.start = start; this.end = end; this.quantized = quantized; this.bucketSize = bucketSize; } public static Window compute(DataRequest request) { return new Window(request.range.start, request.range.end, false, 0); } public static Window compute(DataRequest request, int bucketSizePx) { if (request.resolution >= RESOLUTION_QUANTIZE_CUTOFF) { return quantized(request, bucketSizePx); } else { return compute(request); } } public static Window quantized(DataRequest request, int bucketSizePx) { long quantum = request.resolution * bucketSizePx; long start = (request.range.start / quantum) * quantum; return new Window(start, request.range.end, true, quantum); } public int getNumberOfBuckets() { return (int)((end - start + bucketSize - 1) / bucketSize); } public ListenableFuture<?> update(QueryEngine qe, String name) { return qe.query(String.format( UPDATE_SQL, name, start, Math.max(1, end - start), bucketSize)); } @Override public String toString() { return "window{start: " + start + ", end: " + end + (quantized ? ", " + getNumberOfBuckets() : "") + "}"; } } public abstract static class WithQueryEngine<D extends Track.Data> extends Track<D> { protected final QueryEngine qe; public WithQueryEngine(QueryEngine qe, String trackId) { super(trackId); this.qe = qe; } } private static class ScheduledRequest<D extends Track.Data> { public final DataRequest request; private final List<OnUiThread<D>> callbacks; public ScheduledRequest(DataRequest request, OnUiThread<D> callback) { this.request = request; this.callbacks = Lists.newArrayList(callback); } public boolean satisfies(DataRequest req) { return request.satisfies(req); } // Only on UI thread. public void addCallback(OnUiThread<D> callback) { callbacks.add(callback); } // Not on UI thread. public void scheduleCallbacks(ListenableFuture<D> future, Consumer<D> update) { // callbacks.get(0) is safe since we only ever append to the list. callbacks.get(0).onUiThread(future, data -> { update.accept(data); for (OnUiThread<D> callback : callbacks) { callback.repaint(); } }); } } private static class DataCache { private final Cache<Key, Object> dataCache = Caches.softCache(); public DataCache() { } @SuppressWarnings("unchecked") public <D extends Track.Data> D getIfPresent(Track<D> track, DataRequest req) { return (D)dataCache.getIfPresent(new Key(track, req)); } public <D extends Track.Data> void put(Track<D> track, DataRequest req, D data) { dataCache.put(new Key(track, req), data); } private static class Key { private final Track<?> track; private final long resolution; private final long start; private final long end; private final int h; public Key(Track<?> track, DataRequest req) { this.track = track; this.resolution = req.resolution; this.start = req.range.start; this.end = req.range.end; this.h = ((track.hashCode() * 31 + Long.hashCode(resolution)) * 31 + Long.hashCode(start)) + Long.hashCode(end); } @Override public int hashCode() { return h; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof Key)) { return false; } Key o = (Key)obj; return track == o.track && resolution == o.resolution && start == o.start && end == o.end; } } } }
apache-2.0
IoSL-INav/android
app/src/main/java/de/tu_berlin/indoornavigation/GroupsActivity.java
979
package de.tu_berlin.indoornavigation; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import de.tu_berlin.indoornavigation.entities.Group; public class GroupsActivity extends AppCompatActivity implements GroupFragment.OnListFragmentInteractionListener { private static final String TAG = GroupsActivity.class.toString(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_groups); } /** * Open view showing users of the group. * * @param group */ public void onListFragmentInteraction(Group group) { Log.d(TAG, group.getName()); Intent intent = new Intent(this, UsersActivity.class); intent.putExtra("members", group.getMembers()); intent.putExtra("groupId", group.getId()); startActivity(intent); } }
apache-2.0
zachal/MultiROM_PORT-toroplus
README.md
80
MultiROM_PORT-toroplus ====================== MultiROM toroplus port by zachal
apache-2.0
HuangLS/neo4j
advanced/management/src/main/java/org/neo4j/management/LockManager.java
1871
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.management; import java.util.List; import org.neo4j.jmx.Description; import org.neo4j.jmx.ManagementInterface; import org.neo4j.kernel.info.LockInfo; @ManagementInterface( name = LockManager.NAME ) @Description( "Information about the Neo4j lock status" ) public interface LockManager { final String NAME = "Locking"; @Description( "The number of lock sequences that would have lead to a deadlock situation that " + "Neo4j has detected and averted (by throwing DeadlockDetectedException)." ) long getNumberOfAvertedDeadlocks(); @Description( "Information about all locks held by Neo4j" ) List<LockInfo> getLocks(); @Description( "Information about contended locks (locks where at least one thread is waiting) held by Neo4j. " + "The parameter is used to get locks where threads have waited for at least the specified number " + "of milliseconds, a value of 0 retrieves all contended locks." ) List<LockInfo> getContendedLocks( long minWaitTime ); }
apache-2.0
SmartI18N/SmartI18N
smarti18n/smarti18n-messages/src/main/java/org/smarti18n/messages/users/Users2Endpoint.java
1926
package org.smarti18n.messages.users; import org.smarti18n.api.v2.UsersApi; import org.smarti18n.exceptions.UserExistException; import org.smarti18n.exceptions.UserUnknownException; import org.smarti18n.models.User; import org.smarti18n.models.UserCreateDTO; import org.smarti18n.models.UserSimplified; import org.smarti18n.models.UserUpdateDTO; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class Users2Endpoint implements UsersApi { private final UserService userService; public Users2Endpoint(UserService userService) { this.userService = userService; } @Override @GetMapping(PATH_USERS_FIND_ALL) public List<User> findAll() { return userService.findAll(); } @Override @GetMapping(PATH_USERS_FIND_ONE) public User findOne( @PathVariable("mail") String mail) throws UserUnknownException { return userService.findOne(mail); } @Override @GetMapping(PATH_USERS_FIND_ONE_SIMPLIFIED) public UserSimplified findOneSimplified( @PathVariable("mail") String mail) { return userService.findOneSimplified(mail); } @Override @PostMapping(PATH_USERS_CREATE) public User create(@RequestBody UserCreateDTO dto) throws UserExistException { return userService.register(dto); } @Override @PutMapping(PATH_USERS_UPDATE) public User update( @PathVariable("mail") String mail, @RequestBody UserUpdateDTO dto) throws UserUnknownException { return userService.update(mail, dto); } }
apache-2.0
kit-data-manager/base
DataOrganization/src/test/java/edu/kit/dama/mdm/dataorganization/test/TestUtil.java
6221
/** * Copyright (C) 2014 Karlsruhe Institute of Technology * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package edu.kit.dama.mdm.dataorganization.test; import edu.kit.dama.commons.types.DigitalObjectId; import edu.kit.dama.mdm.dataorganization.entity.core.IAttribute; import edu.kit.dama.mdm.dataorganization.entity.core.ICollectionNode; import edu.kit.dama.mdm.dataorganization.entity.core.IFileTree; import edu.kit.dama.mdm.dataorganization.impl.jpa.Attribute; import edu.kit.dama.mdm.dataorganization.impl.jpa.CollectionNode; import edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizationNode; import edu.kit.dama.mdm.dataorganization.impl.jpa.FileTree; import edu.kit.dama.mdm.dataorganization.impl.jpa.persistence.PersistenceFacade; import java.util.List; import java.util.UUID; import javax.persistence.EntityManager; /** * * @author pasic */ public class TestUtil { static void clearDB() { EntityManager em = PersistenceFacade.getInstance(). getEntityManagerFactory().createEntityManager(); em.getTransaction().begin(); List<DataOrganizationNode> nodes = em.createQuery( "SELECT m FROM DataOrganizationNode m", DataOrganizationNode.class).getResultList(); for (DataOrganizationNode node : nodes) { em.remove(node); } em.flush(); em.getTransaction().commit(); em.close(); } public static IFileTree createBasicTestTree() { IFileTree tree = new edu.kit.dama.mdm.dataorganization.entity.impl.client.FileTree(); DigitalObjectId digitalObjectID = new DigitalObjectId("Dummy " + UUID.randomUUID().toString()); tree.setDigitalObjectId(digitalObjectID); ICollectionNode cnp; ICollectionNode cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); cnc.setName("child 1"); cnp = tree.getRootNode(); tree.getRootNode().setName("root"); cnp.addChild(cnc); cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); IAttribute attr = new edu.kit.dama.mdm.dataorganization.entity.impl.client.Attribute(); attr.setKey("dummy"); attr.setValue("attribute"); cnc.addAttribute(attr); cnc.setName("child 2"); cnp.addChild(cnc); cnp = cnc; cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); cnc.setName("cnc 2.1"); cnp.addChild(cnc); cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); cnc.setName("cnc 2.2"); cnp.addChild(cnc); ICollectionNode cnp22 = cnc; cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); cnc.setName("cnc 2.3"); cnp.addChild(cnc); cnp = cnc; cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); cnc.setName("cnc 2.3.1"); cnp.addChild(cnc); cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); cnc.setName("cnc 2.3.2"); cnp.addChild(cnc); cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); cnc.setName("cnc 2.3.3"); cnp.addChild(cnc); cnp = cnp22; cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); cnc.setName("cnc 2.2.1"); cnp.addChild(cnc); cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); cnc.setName("cnc 2.2.2"); cnp.addChild(cnc); cnc = new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode(); cnc.setName("cnc 2.2.3"); cnp.addChild(cnc); tree.setViewName("default"); return tree; } public static FileTree createBasicJPATestTree() { FileTree tree = new FileTree(); DigitalObjectId digitalObjectID = new DigitalObjectId("Dummy"); tree.setDigitalObjectId(digitalObjectID); CollectionNode cnp; CollectionNode cnc = new CollectionNode(); tree.setName("root"); cnc.setName("child 1"); cnp = (CollectionNode) tree; cnp.addChild(cnc); cnc = new CollectionNode(); Attribute attr = new Attribute(); attr.setKey("dummy"); attr.setValue("attribute"); cnc.addAttribute(attr); cnc.setName("child 2"); cnp.addChild(cnc); cnp = cnc; cnc = new CollectionNode(); cnc.setName("cnc 2.1"); cnp.addChild(cnc); cnc = new CollectionNode(); cnc.setName("cnc 2.2"); cnp.addChild(cnc); CollectionNode cnp22 = cnc; cnc = new CollectionNode(); cnc.setName("cnc 2.3"); cnp.addChild(cnc); cnp = cnc; cnc = new CollectionNode(); cnc.setName("cnc 2.3.1"); cnp.addChild(cnc); cnc = new CollectionNode(); cnc.setName("cnc 2.3.2"); cnp.addChild(cnc); cnc = new CollectionNode(); cnc.setName("cnc 2.3.3"); cnp.addChild(cnc); cnp = cnp22; cnc = new CollectionNode(); cnc.setName("cnc 2.2.1"); cnp.addChild(cnc); cnc = new CollectionNode(); cnc.setName("cnc 2.2.2"); cnp.addChild(cnc); cnc = new CollectionNode(); cnc.setName("cnc 2.2.3"); cnp.addChild(cnc); return tree; } }
apache-2.0
phvu/tweetviz
README.md
328
# tweetviz Tweet visualization Basically you will need to install Theano (and CUDA if you want to use GPUs), then go: pip install -r requirements.txt ./setup.sh Install and start `couchdb` on your system. Then update the configuration parameters in `conf.py`, and start the server with: ./run_server.sh
apache-2.0
siracoj/ProPain
ProPain/src/Wait.js
1384
var WaitState = function(game){this.game = game}; WaitState.prototype.preload = function(){ }; WaitState.prototype.create = function(){ this.background = this.game.add.sprite(0,0,'fence'); this.title = this.add.sprite(400,200, 'waitforplay'); this.title.anchor.setTo(0.5, 0.5); this.waitBar = this.game.add.tileSprite(0,500,800,29,'tankbar'); this.waitBar.autoScroll(-200,0); this.menubutton = this.game.add.button(400,350,'menubutton',this.menuClick, this); this.menubutton.anchor.setTo(0.5,0.5); this.searching = this.game.add.audio('searching'); this.searching.play(); try{ socket.emit("new player", {gameRequest: this.game.gameRequest, character: this.game.character, x: game.width/2 , y: game.height-100}); console.log("Player sent"); }catch(err){ console.log("PLayer could not be sent"); console.log(err.message); } }; WaitState.prototype.update = function(){ if(otherPlayerReady){ this.searching.stop(); this.game.state.start("GameState"); }else if(noGames){ this.title.destroy() this.title = this.add.sprite(400,200,'nogames'); this.title.anchor.setTo(0.5, 0.5); } }; WaitState.prototype.menuClick = function(){ //this.game.state.start("MenuState",true,false); window.location.replace(window.location.pathname); };
apache-2.0
bozimmerman/CoffeeMud
com/planet_ink/coffee_mud/Locales/Woods.java
4316
package com.planet_ink.coffee_mud.Locales; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2001-2022 Bo Zimmerman 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. */ public class Woods extends StdRoom { @Override public String ID() { return "Woods"; } public Woods() { super(); name="the woods"; basePhyStats.setWeight(3); recoverPhyStats(); } @Override public int domainType() { return Room.DOMAIN_OUTDOORS_WOODS; } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { if((msg.amITarget(this)||(msg.targetMinor()==CMMsg.TYP_ADVANCE)||(msg.targetMinor()==CMMsg.TYP_RETREAT)) &&(!msg.source().isMonster()) &&(CMLib.dice().rollPercentage()==1) &&(CMLib.dice().rollPercentage()==1) &&(isInhabitant(msg.source())) &&(!CMSecurity.isDisabled(CMSecurity.DisFlag.AUTODISEASE))) { final Ability A=CMClass.getAbility("Disease_PoisonIvy"); if((A!=null) &&(msg.source().fetchEffect(A.ID())==null) &&(!CMSecurity.isAbilityDisabled(A.ID()))) A.invoke(msg.source(),msg.source(),true,0); } super.executeMsg(myHost,msg); } public static final Integer[] resourceList={ Integer.valueOf(RawMaterial.RESOURCE_WOOD), Integer.valueOf(RawMaterial.RESOURCE_PINE), Integer.valueOf(RawMaterial.RESOURCE_OAK), Integer.valueOf(RawMaterial.RESOURCE_MAPLE), Integer.valueOf(RawMaterial.RESOURCE_REDWOOD), Integer.valueOf(RawMaterial.RESOURCE_SAP), Integer.valueOf(RawMaterial.RESOURCE_YEW), Integer.valueOf(RawMaterial.RESOURCE_HICKORY), Integer.valueOf(RawMaterial.RESOURCE_TEAK), Integer.valueOf(RawMaterial.RESOURCE_CEDAR), Integer.valueOf(RawMaterial.RESOURCE_ELM), Integer.valueOf(RawMaterial.RESOURCE_CHERRYWOOD), Integer.valueOf(RawMaterial.RESOURCE_BEECHWOOD), Integer.valueOf(RawMaterial.RESOURCE_WILLOW), Integer.valueOf(RawMaterial.RESOURCE_SYCAMORE), Integer.valueOf(RawMaterial.RESOURCE_SPRUCE), Integer.valueOf(RawMaterial.RESOURCE_FLOWERS), Integer.valueOf(RawMaterial.RESOURCE_FRUIT), Integer.valueOf(RawMaterial.RESOURCE_APPLES), Integer.valueOf(RawMaterial.RESOURCE_BERRIES), Integer.valueOf(RawMaterial.RESOURCE_PEACHES), Integer.valueOf(RawMaterial.RESOURCE_CHERRIES), Integer.valueOf(RawMaterial.RESOURCE_ORANGES), Integer.valueOf(RawMaterial.RESOURCE_LEMONS), Integer.valueOf(RawMaterial.RESOURCE_FUR), Integer.valueOf(RawMaterial.RESOURCE_NUTS), Integer.valueOf(RawMaterial.RESOURCE_HERBS), Integer.valueOf(RawMaterial.RESOURCE_DIRT), Integer.valueOf(RawMaterial.RESOURCE_HONEY), Integer.valueOf(RawMaterial.RESOURCE_VINE), Integer.valueOf(RawMaterial.RESOURCE_HIDE), Integer.valueOf(RawMaterial.RESOURCE_FEATHERS), Integer.valueOf(RawMaterial.RESOURCE_LEATHER)}; public static final List<Integer> roomResources=new Vector<Integer>(Arrays.asList(resourceList)); @Override public List<Integer> resourceChoices() { return Woods.roomResources; } }
apache-2.0
marska/wundercal
src/Wundercal/Services/Dto/WunderlistList.cs
145
namespace Wundercal.Services.Dto { public class WunderlistList { public int Id { get; set; } public string Title { get; set; } } }
apache-2.0
consulo/consulo
modules/base/lang-api/src/main/java/com/intellij/codeInsight/actions/SimpleCodeInsightAction.java
1052
/* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.actions; import com.intellij.codeInsight.CodeInsightActionHandler; import javax.annotation.Nonnull; /** * @author Dmitry Avdeev */ public abstract class SimpleCodeInsightAction extends CodeInsightAction implements CodeInsightActionHandler { @Nonnull @Override protected CodeInsightActionHandler getHandler() { return this; } @Override public boolean startInWriteAction() { return true; } }
apache-2.0
instacart/Snacks
docs/colors.md
983
Available colors: ```jsx import { colors } from 'ic-snacks' const wrapperStyles = { display: 'flex', flexDirection: 'row', flexWrap: 'wrap', margin: 0, padding: '15px', background: `repeating-linear-gradient( 45deg, ${colors.WHITE}, ${colors.WHITE} 10px, ${colors.GRAY_88} 10px, ${colors.GRAY_88} 20px )`, } const colorWrapStyles = { flex: 1, height: '220px', flexBasis: '220px', boxSizing: 'border-box', textAlign: 'center', listStyle: 'none', } const colorSwatchStyles = { height: '150px' } const colorsSwatches = Object.keys(colors).map(name => { return ( <li style={colorWrapStyles}> <div style={Object.assign({}, colorSwatchStyles, { backgroundColor: colors[name] } )} ></div> <p style={{ fontWeight: '600', marginBottom: 0 }}>{name}</p> <p style={{ fontSize: '12px', margin: 0 }}>{colors[name]}</p> </li> ) }) ; <ul style={wrapperStyles}> { colorsSwatches } </ul> ```
apache-2.0
olacabs/fabric
fabric-components/kafka-writer/src/main/java/com/olacabs/fabric/processors/kafkawriter/KafkaWriter.java
9285
/* * Copyright 2016 ANI Technologies Pvt. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.olacabs.fabric.processors.kafkawriter; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.olacabs.fabric.compute.ProcessingContext; import com.olacabs.fabric.compute.processor.InitializationException; import com.olacabs.fabric.compute.processor.ProcessingException; import com.olacabs.fabric.compute.processor.StreamingProcessor; import com.olacabs.fabric.compute.util.ComponentPropertyReader; import com.olacabs.fabric.model.common.ComponentMetadata; import com.olacabs.fabric.model.event.Event; import com.olacabs.fabric.model.event.EventSet; import com.olacabs.fabric.model.processor.Processor; import com.olacabs.fabric.model.processor.ProcessorType; import kafka.javaapi.producer.Producer; import kafka.producer.DefaultPartitioner; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import lombok.Getter; import lombok.Setter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Properties; /** * TODO Javadoc. */ @Processor( namespace = "global", name = "kafka-writer", version = "2.0", description = "A processor that write data into kafka", cpu = 0.1, memory = 1, processorType = ProcessorType.EVENT_DRIVEN, requiredProperties = { "brokerList", "ingestionPoolSize", "kafkaKeyJsonPath" }, optionalProperties = { "isTopicOnJsonPath", "topic", "topicJsonPath", "ignoreError", "kafkaSerializerClass", "ackCount" }) public class KafkaWriter extends StreamingProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(KafkaWriter.class.getSimpleName()); private static final boolean DEFAULT_IGNORE_SERIALIZATION_ERROR = false; private static final boolean DEFAULT_TOPIC_ON_JSON_PATH = false; private static final String DEFAULT_SERIALIZER_CLASS = "kafka.serializer.StringEncoder"; private static final String DEFAULT_KAFKA_KEY_JSON_PATH = "/metadata/partitionKey/value"; private static final int DEFAULT_ACK_COUNT = 1; private static final int DEFAULT_BATCH_SIZE = 10; private static final String ACK_COUNT = "-1"; private String kafkaKeyJsonPath; private boolean ignoreError; private ObjectMapper mapper; @Getter @Setter private String kafkaTopic; @Getter @Setter private String kafkaTopicJsonPath; @Getter @Setter private int ingestionPoolSize; @Getter @Setter private Producer<String, String> producer; @Getter @Setter private boolean isTopicOnJsonPath = false; @Override protected EventSet consume(ProcessingContext processingContext, EventSet eventSet) throws ProcessingException { final List<KeyedMessage<String, String>> messages = Lists.newArrayList(); try { eventSet.getEvents().forEach(event -> { KeyedMessage<String, String> convertedMessage = null; try { convertedMessage = convertEvent(event); } catch (ProcessingException e) { LOGGER.error("Error converting byte stream to event: ", e); throw new RuntimeException(e); } if (null != convertedMessage) { messages.add(convertedMessage); } }); } catch (final Exception e) { LOGGER.error("Error converting byte stream to event: ", e); throw new ProcessingException(e); } Lists.partition(messages, ingestionPoolSize).forEach(messageList -> getProducer().send(messageList)); return eventSet; } /** * convert the event into Kafka keyed messages. * * @param event to convert * @return KeyedMessage */ protected KeyedMessage<String, String> convertEvent(Event event) throws ProcessingException { JsonNode eventData = event.getJsonNode(); if (null == eventData) { if (event.getData() instanceof byte[]) { try { eventData = mapper.readTree((byte[]) event.getData()); } catch (IOException e) { LOGGER.error("Error converting byte stream to event: ", e); if (!ignoreError) { LOGGER.error("Error converting byte stream to event"); throw new ProcessingException("Error converting byte stream to event", e); } return null; } } else { if (!ignoreError) { LOGGER.error("Error converting byte stream to event: Event is not byte stream"); throw new ProcessingException("Error converting byte stream to event: Event is not byte stream"); } return null; } } final String kafkaKey = kafkaKeyJsonPath != null ? eventData.at(kafkaKeyJsonPath).asText().replace("\"", "") : eventData.at(DEFAULT_KAFKA_KEY_JSON_PATH).asText().replace("\"", ""); final String topic = isTopicOnJsonPath() ? eventData.at(getKafkaTopicJsonPath()).toString().replace("\"", "") : getKafkaTopic().replace("\"", ""); return new KeyedMessage<>(topic, kafkaKey, eventData.toString()); } @Override public void initialize(String instanceId, Properties globalProperties, Properties properties, ComponentMetadata componentMetadata) throws InitializationException { final String kafkaBrokerList = ComponentPropertyReader .readString(properties, globalProperties, "brokerList", instanceId, componentMetadata); isTopicOnJsonPath = ComponentPropertyReader .readBoolean(properties, globalProperties, "isTopicOnJsonPath", instanceId, componentMetadata, DEFAULT_TOPIC_ON_JSON_PATH); if (!isTopicOnJsonPath) { kafkaTopic = ComponentPropertyReader .readString(properties, globalProperties, "topic", instanceId, componentMetadata); if (kafkaTopic == null) { LOGGER.error("Kafka topic in properties not found"); throw new RuntimeException("Kafka topic in properties not found"); } setKafkaTopic(kafkaTopic); } else { kafkaTopicJsonPath = ComponentPropertyReader .readString(properties, globalProperties, "topicJsonPath", instanceId, componentMetadata); if (kafkaTopicJsonPath == null) { LOGGER.error("Kafka topic json path not found"); throw new RuntimeException("Kafka topic json path not found"); } setKafkaTopicJsonPath(kafkaTopicJsonPath); } kafkaKeyJsonPath = ComponentPropertyReader .readString(properties, globalProperties, "kafkaKeyJsonPath", instanceId, componentMetadata, DEFAULT_KAFKA_KEY_JSON_PATH); final String kafkaSerializerClass = ComponentPropertyReader .readString(properties, globalProperties, "kafkaSerializerClass", instanceId, componentMetadata, DEFAULT_SERIALIZER_CLASS); ingestionPoolSize = ComponentPropertyReader .readInteger(properties, globalProperties, "ingestionPoolSize", instanceId, componentMetadata, DEFAULT_BATCH_SIZE); final Integer ackCount = ComponentPropertyReader .readInteger(properties, globalProperties, "ackCount", instanceId, componentMetadata, DEFAULT_ACK_COUNT); ignoreError = ComponentPropertyReader .readBoolean(properties, globalProperties, "ignoreError", instanceId, componentMetadata, DEFAULT_IGNORE_SERIALIZATION_ERROR); final Properties props = new Properties(); props.put("metadata.broker.list", kafkaBrokerList); props.put("serializer.class", kafkaSerializerClass); props.put("partitioner.class", DefaultPartitioner.class.getName()); props.put("request.required.acks", ACK_COUNT); props.put("min.isr", Integer.toString(ackCount)); producer = new Producer<>(new ProducerConfig(props)); mapper = new ObjectMapper(); LOGGER.info("Initialized kafka writer..."); } @Override public void destroy() { producer.close(); LOGGER.info("Closed kafka writer..."); } }
apache-2.0
YogiAi/ColorTalk_Android
app/src/main/java/navyblue/top/colortalk/ui/activities/AppIntroActivity.java
990
package navyblue.top.colortalk.ui.activities; import android.os.Bundle; import android.support.v4.app.Fragment; import com.github.paolorotolo.appintro.AppIntro2; import navyblue.top.colortalk.R; import navyblue.top.colortalk.ui.fragments.SampleSlide; /** * Created by CIR on 16/6/4. */ public class AppIntroActivity extends AppIntro2 { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setFlowAnimation(); addSlide(SampleSlide.newInstance(R.layout.intro)); addSlide(SampleSlide.newInstance(R.layout.intro_2)); addSlide(SampleSlide.newInstance(R.layout.intro3)); addSlide(SampleSlide.newInstance(R.layout.intro4)); addSlide(SampleSlide.newInstance(R.layout.intro5)); } @Override public void onDonePressed(Fragment currentFragment) { finish(); } @Override public void onSkipPressed(Fragment currentFragment) { finish(); } }
apache-2.0
mdanielwork/intellij-community
plugins/java-i18n/src/com/intellij/codeInspection/i18n/JavaI18nUtil.java
16944
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.codeInspection.i18n; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.template.macro.MacroUtil; import com.intellij.lang.properties.*; import com.intellij.lang.properties.ResourceBundle; import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.lang.properties.psi.PropertyCreationHandler; import com.intellij.lang.properties.references.I18nUtil; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.scope.util.PsiScopesUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ArrayUtil; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.uast.*; import java.text.MessageFormat; import java.util.*; /** * @author max */ public class JavaI18nUtil extends I18nUtil { public static final PropertyCreationHandler DEFAULT_PROPERTY_CREATION_HANDLER = (project, propertiesFiles, key, value, parameters) -> createProperty(project, propertiesFiles, key, value, true); private JavaI18nUtil() { } @Nullable public static TextRange getSelectedRange(Editor editor, final PsiFile psiFile) { if (editor == null) return null; String selectedText = editor.getSelectionModel().getSelectedText(); if (selectedText != null) { return new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd()); } PsiElement psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset()); if (psiElement == null || psiElement instanceof PsiWhiteSpace) return null; return psiElement.getTextRange(); } public static boolean mustBePropertyKey(@NotNull PsiExpression expression, @Nullable Ref<? super PsiAnnotationMemberValue> resourceBundleRef) { PsiElement parent = expression.getParent(); if (parent instanceof PsiVariable) { final PsiAnnotation annotation = AnnotationUtil.findAnnotation((PsiVariable)parent, AnnotationUtil.PROPERTY_KEY); if (annotation != null) { processAnnotationAttributes(resourceBundleRef, annotation); return true; } } return isPassedToAnnotatedParam(expression, AnnotationUtil.PROPERTY_KEY, resourceBundleRef, null); } public static boolean mustBePropertyKey(@NotNull ULiteralExpression expression, @Nullable Ref<? super UExpression> resourceBundleRef) { final UElement parent = expression.getUastParent(); if (parent instanceof UVariable) { UAnnotation annotation = ((UVariable)parent).findAnnotation(AnnotationUtil.PROPERTY_KEY); if (annotation != null) { processAnnotationAttributes(resourceBundleRef, annotation); return true; } } UCallExpression callExpression = UastUtils.getUCallExpression(expression); if (callExpression == null) return false; PsiMethod psiMethod = callExpression.resolve(); if (psiMethod == null) return false; PsiParameter parameter = UastUtils.getParameterForArgument(callExpression, expression); if (parameter == null) return false; int paramIndex = ArrayUtil.indexOf(psiMethod.getParameterList().getParameters(), parameter); if (paramIndex == -1) return false; return isMethodParameterAnnotatedWith(psiMethod, paramIndex, null, AnnotationUtil.PROPERTY_KEY, null, null); } static boolean isPassedToAnnotatedParam(@NotNull PsiExpression expression, final String annFqn, @Nullable Ref<? super PsiAnnotationMemberValue> resourceBundleRef, @Nullable final Set<? super PsiModifierListOwner> nonNlsTargets) { expression = getTopLevelExpression(expression); final PsiElement parent = expression.getParent(); if (!(parent instanceof PsiExpressionList)) return false; int idx = -1; final PsiExpression[] args = ((PsiExpressionList)parent).getExpressions(); for (int i = 0; i < args.length; i++) { PsiExpression arg = args[i]; if (PsiTreeUtil.isAncestor(arg, expression, false)) { idx = i; break; } } if (idx == -1) return false; PsiElement grParent = parent.getParent(); if (grParent instanceof PsiAnonymousClass) { grParent = grParent.getParent(); } if (grParent instanceof PsiCall) { PsiMethod method = ((PsiCall)grParent).resolveMethod(); return method != null && isMethodParameterAnnotatedWith(method, idx, null, annFqn, resourceBundleRef, nonNlsTargets); } return false; } @NotNull static PsiExpression getTopLevelExpression(@NotNull PsiExpression expression) { while (expression.getParent() instanceof PsiExpression) { final PsiExpression parent = (PsiExpression)expression.getParent(); if (parent instanceof PsiConditionalExpression && ((PsiConditionalExpression)parent).getCondition() == expression) { break; } expression = parent; if (expression instanceof PsiAssignmentExpression) break; } return expression; } static boolean isMethodParameterAnnotatedWith(final PsiMethod method, final int idx, @Nullable Collection<? super PsiMethod> processed, final String annFqn, @Nullable Ref<? super PsiAnnotationMemberValue> resourceBundleRef, @Nullable final Set<? super PsiModifierListOwner> nonNlsTargets) { if (processed != null) { if (processed.contains(method)) return false; } else { processed = new THashSet<>(); } processed.add(method); final PsiParameter[] params = method.getParameterList().getParameters(); PsiParameter param; if (idx >= params.length) { if (params.length == 0) { return false; } PsiParameter lastParam = params[params.length - 1]; if (lastParam.isVarArgs()) { param = lastParam; } else { return false; } } else { param = params[idx]; } final PsiAnnotation annotation = AnnotationUtil.findAnnotation(param, annFqn); if (annotation != null) { processAnnotationAttributes(resourceBundleRef, annotation); return true; } if (nonNlsTargets != null) { nonNlsTargets.add(param); } final PsiMethod[] superMethods = method.findSuperMethods(); for (PsiMethod superMethod : superMethods) { if (isMethodParameterAnnotatedWith(superMethod, idx, processed, annFqn, resourceBundleRef, null)) return true; } return false; } private static void processAnnotationAttributes(@Nullable Ref<? super PsiAnnotationMemberValue> resourceBundleRef, @NotNull PsiAnnotation annotation) { if (resourceBundleRef != null) { final PsiAnnotationParameterList parameterList = annotation.getParameterList(); final PsiNameValuePair[] attributes = parameterList.getAttributes(); for (PsiNameValuePair attribute : attributes) { final String name = attribute.getName(); if (AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER.equals(name)) { resourceBundleRef.set(attribute.getValue()); } } } } private static void processAnnotationAttributes(@Nullable Ref<? super UExpression> resourceBundleRef, @NotNull UAnnotation annotation) { if (resourceBundleRef != null) { for (UNamedExpression attribute : annotation.getAttributeValues()) { final String name = attribute.getName(); if (AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER.equals(name)) { resourceBundleRef.set(attribute.getExpression()); } } } } static boolean isValidPropertyReference(@NotNull Project project, @NotNull PsiExpression expression, @NotNull String key, @NotNull Ref<? super String> outResourceBundle) { Ref<PsiAnnotationMemberValue> resourceBundleRef = Ref.create(); if (mustBePropertyKey(expression, resourceBundleRef)) { final Object resourceBundleName = resourceBundleRef.get(); if (!(resourceBundleName instanceof PsiExpression)) { return false; } PsiExpression expr = (PsiExpression)resourceBundleName; final PsiConstantEvaluationHelper constantEvaluationHelper = JavaPsiFacade.getInstance(project).getConstantEvaluationHelper(); Object value = constantEvaluationHelper.computeConstantExpression(expr); if (value == null) { if (expr instanceof PsiReferenceExpression) { final PsiElement resolve = ((PsiReferenceExpression)expr).resolve(); if (resolve instanceof PsiField && ((PsiField)resolve).hasModifierProperty(PsiModifier.FINAL)) { value = constantEvaluationHelper.computeConstantExpression(((PsiField)resolve).getInitializer()); if (value == null) { return false; } } } if (value == null) { final ResourceBundle resourceBundle = resolveResourceBundleByKey(key, project); if (resourceBundle == null) { return false; } final PropertiesFile defaultPropertiesFile = resourceBundle.getDefaultPropertiesFile(); final String bundleName = BundleNameEvaluator.DEFAULT.evaluateBundleName(defaultPropertiesFile.getContainingFile()); if (bundleName == null) { return false; } value = bundleName; } } String bundleName = value.toString(); outResourceBundle.set(bundleName); return isPropertyRef(expression, key, bundleName); } return true; } @Nullable private static ResourceBundle resolveResourceBundleByKey(@NotNull final String key, @NotNull final Project project) { final Ref<ResourceBundle> bundleRef = Ref.create(); final boolean r = PropertiesReferenceManager.getInstance(project).processAllPropertiesFiles((baseName, propertiesFile) -> { if (propertiesFile.findPropertyByKey(key) != null) { if (bundleRef.get() == null) { bundleRef.set(propertiesFile.getResourceBundle()); } else { return bundleRef.get().equals(propertiesFile.getResourceBundle()); } } return true; }); return r ? bundleRef.get() : null; } static boolean isPropertyRef(final PsiExpression expression, final String key, final String resourceBundleName) { if (resourceBundleName == null) { return !PropertiesImplUtil.findPropertiesByKey(expression.getProject(), key).isEmpty(); } else { final List<PropertiesFile> propertiesFiles = propertiesFilesByBundleName(resourceBundleName, expression); boolean containedInPropertiesFile = false; for (PropertiesFile propertiesFile : propertiesFiles) { containedInPropertiesFile |= propertiesFile.findPropertyByKey(key) != null; } return containedInPropertiesFile; } } public static Set<String> suggestExpressionOfType(final PsiClassType type, final PsiLiteralExpression context) { PsiVariable[] variables = MacroUtil.getVariablesVisibleAt(context, ""); Set<String> result = new LinkedHashSet<>(); for (PsiVariable var : variables) { PsiType varType = var.getType(); PsiIdentifier identifier = var.getNameIdentifier(); if ((type == null || type.isAssignableFrom(varType)) && identifier != null) { result.add(identifier.getText()); } } PsiExpression[] expressions = MacroUtil.getStandardExpressionsOfType(context, type); for (PsiExpression expression : expressions) { result.add(expression.getText()); } if (type != null) { addAvailableMethodsOfType(type, context, result); } return result; } private static void addAvailableMethodsOfType(final PsiClassType type, final PsiLiteralExpression context, final Collection<? super String> result) { PsiScopesUtil.treeWalkUp((element, state) -> { if (element instanceof PsiMethod) { PsiMethod method = (PsiMethod)element; PsiType returnType = method.getReturnType(); if (returnType != null && TypeConversionUtil.isAssignable(type, returnType) && method.getParameterList().isEmpty()) { result.add(method.getName() + "()"); } } return true; }, context, null); } /** * Returns number of different message format parameters in property value * * <i>Class {0} info: Class {0} extends class {1} and implements interface {2}</i> * number of parameters is 3. * * @return number of parameters from single property or 0 for wrong format */ public static int getPropertyValuePlaceholdersCount(@NotNull final String propertyValue) { try { return new MessageFormat(propertyValue).getFormatsByArgumentIndex().length; } catch (final IllegalArgumentException e) { return 0; } } /** * Returns number of different parameters in i18n message. For example, for string * * <i>Class {0} info: Class {0} extends class {1} and implements interface {2}</i> in one translation of property * <i>Class {0} info: Class {0} extends class {1} </i> in other translation of property * <p> * number of parameters is 3. * * @param expression i18n literal * @return number of parameters */ public static int getPropertyValueParamsMaxCount(@NotNull final UExpression expression) { final SortedSet<Integer> paramsCount = getPropertyValueParamsCount(expression, null); if (paramsCount.isEmpty()) { return -1; } return paramsCount.last(); } @NotNull static SortedSet<Integer> getPropertyValueParamsCount(@NotNull final PsiExpression expression, @Nullable final String resourceBundleName) { UExpression uExpression = UastContextKt.toUElement(expression, UExpression.class); if (uExpression == null) return new TreeSet<>(); return getPropertyValueParamsCount(uExpression, resourceBundleName); } @NotNull private static SortedSet<Integer> getPropertyValueParamsCount(@NotNull final UExpression expression, @Nullable final String resourceBundleName) { final ULiteralExpression literalExpression; if (expression instanceof ULiteralExpression) { literalExpression = (ULiteralExpression)expression; } else if (expression instanceof UReferenceExpression) { final PsiElement resolved = ((UReferenceExpression)expression).resolve(); final PsiField field = resolved == null ? null : (PsiField)resolved; literalExpression = field != null && field.hasModifierProperty(PsiModifier.FINAL) && field.getInitializer() instanceof PsiLiteralExpression ? UastContextKt.toUElement(field.getInitializer(), ULiteralExpression.class) : null; } else { literalExpression = null; } final TreeSet<Integer> paramsCount = new TreeSet<>(); if (literalExpression == null) { return paramsCount; } for (PsiReference reference : UastLiteralUtils.getInjectedReferences(literalExpression)) { if (reference instanceof PsiPolyVariantReference) { for (ResolveResult result : ((PsiPolyVariantReference)reference).multiResolve(false)) { if (result.isValidResult() && result.getElement() instanceof IProperty) { try { final IProperty property = (IProperty)result.getElement(); if (resourceBundleName != null) { final PsiFile file = property.getPropertiesFile().getContainingFile(); if (!resourceBundleName.equals(BundleNameEvaluator.DEFAULT.evaluateBundleName(file))) { continue; } } final String propertyValue = property.getValue(); if (propertyValue == null) { continue; } paramsCount.add(getPropertyValuePlaceholdersCount(propertyValue)); } catch (IllegalArgumentException ignored) { } } } } } return paramsCount; } }
apache-2.0
qinjiannet/screen-chess-qq
src/entity/chess/General.java
1727
package entity.chess; import java.util.ArrayList; import entity.Board; import entity.Coordinate; //Author 在线疯狂 //Homepage http://bookshadow.com public class General extends Chess { public final static int VALUE = 100000; private final static int deltaX[] = { 1, 0, -1, 0 }; private final static int deltaY[] = { 0, 1, 0, -1 }; public General() { super.setCode(Chess.GENERAL); } @Override public ArrayList<Coordinate> getPossibleLocations(Board chessBoard) { Chess[][] board = chessBoard.getBoard(); ArrayList<Coordinate> al = new ArrayList<Coordinate>(); Coordinate sourceCoo = getCoordinate(); for (int i = 0; i < deltaX.length; i++) { int x = sourceCoo.getX() + deltaX[i]; int y = sourceCoo.getY() + deltaY[i]; if (!isValid(x, y)) { continue; } if (board[x][y] != null && (board[x][y].getColor() == getColor())) { continue; } al.add(new Coordinate(x, y)); } Coordinate enemyGeneralCoo = generalMeet(board); if (enemyGeneralCoo != null) al.add(enemyGeneralCoo); return al; } @Override public boolean isValid(int x, int y) { return ((x <= 2 && x >= 0) || (x >= 7 && x <= 9)) && (y >= 3 && y <= 5); } public Coordinate generalMeet(Chess board[][]) { char color = getColor(); Chess opponentGeneral = Board.findGeneral(board, Chess.oppositeColor(color)); if (opponentGeneral == null) return null; int sy = getCoordinate().getY(); int oy = opponentGeneral.getCoordinate().getY(); if (sy == oy) { if (Board.countChess(board, getCoordinate(), opponentGeneral.getCoordinate()) == 2) { return opponentGeneral.getCoordinate(); } } return null; } @Override public int getValue(Board chessBoard) { return VALUE; } }
apache-2.0
GoogleForCreators/web-stories-wp
packages/story-editor/src/components/floatingMenu/menus/image.js
1257
/* * Copyright 2021 Google LLC * * 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 * * https://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. */ /** * External dependencies */ import { memo } from '@googleforcreators/react'; /** * Internal dependencies */ import { SwapMedia, LayerOpacity, FlipHorizontal, FlipVertical, BorderWidthAndColor, More, Separator, Dismiss, } from '../elements'; const FloatingImageMenu = memo(function FloatingImageMenu() { return ( <> <SwapMedia /> <Separator /> <LayerOpacity /> <Separator /> <FlipHorizontal /> <FlipVertical /> <Separator /> <BorderWidthAndColor /> <Separator /> <More /> <Separator /> <Dismiss /> </> ); }); export default FloatingImageMenu;
apache-2.0
blademainer/common_utils
common_helper/src/main/java/com/xiongyingqi/captcha/filter/ConfigurableFilterFactory.java
1181
/* * Copyright (c) 2009 Piotr Piastucki * * This file is part of Patchca CAPTCHA library. * * Patchca is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Patchca 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Patchca. If not, see <http://www.gnu.org/licenses/>. */ package com.xiongyingqi.captcha.filter; import java.awt.image.BufferedImageOp; import java.util.List; public class ConfigurableFilterFactory extends AbstractFilterFactory { private List<BufferedImageOp> filters; @Override public List<BufferedImageOp> getFilters() { return filters; } public void setFilters(List<BufferedImageOp> filters) { this.filters = filters; } }
apache-2.0
wildfly-swarm/wildfly-swarm-javadocs
2017.12.1/apidocs/org/wildfly/swarm/cdi/jaxrsapi/deployment/package-tree.html
5445
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Wed Dec 13 10:32:39 MST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.cdi.jaxrsapi.deployment Class Hierarchy (BOM: * : All 2017.12.1 API)</title> <meta name="date" content="2017-12-13"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.wildfly.swarm.cdi.jaxrsapi.deployment Class Hierarchy (BOM: * : All 2017.12.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.12.1</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/wildfly/swarm/cdi/jaxrsapi/package-tree.html">Prev</a></li> <li><a href="../../../../../../org/wildfly/swarm/cli/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/cdi/jaxrsapi/deployment/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package org.wildfly.swarm.cdi.jaxrsapi.deployment</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">org.wildfly.swarm.cdi.jaxrsapi.deployment.<a href="../../../../../../org/wildfly/swarm/cdi/jaxrsapi/deployment/ProxyBuilder.html" title="class in org.wildfly.swarm.cdi.jaxrsapi.deployment"><span class="typeNameLink">ProxyBuilder</span></a>&lt;T&gt;</li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2017.12.1</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/wildfly/swarm/cdi/jaxrsapi/package-tree.html">Prev</a></li> <li><a href="../../../../../../org/wildfly/swarm/cli/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/cdi/jaxrsapi/deployment/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
apache-2.0
aws/aws-sdk-cpp
aws-cpp-sdk-kafkaconnect/include/aws/kafkaconnect/model/ConnectorSummary.h
25883
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/kafkaconnect/KafkaConnect_EXPORTS.h> #include <aws/kafkaconnect/model/CapacityDescription.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/kafkaconnect/model/ConnectorState.h> #include <aws/core/utils/DateTime.h> #include <aws/kafkaconnect/model/KafkaClusterDescription.h> #include <aws/kafkaconnect/model/KafkaClusterClientAuthenticationDescription.h> #include <aws/kafkaconnect/model/KafkaClusterEncryptionInTransitDescription.h> #include <aws/kafkaconnect/model/LogDeliveryDescription.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/kafkaconnect/model/WorkerConfigurationDescription.h> #include <aws/kafkaconnect/model/PluginDescription.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace KafkaConnect { namespace Model { /** * <p>Summary of a connector.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/kafkaconnect-2021-09-14/ConnectorSummary">AWS * API Reference</a></p> */ class AWS_KAFKACONNECT_API ConnectorSummary { public: ConnectorSummary(); ConnectorSummary(Aws::Utils::Json::JsonView jsonValue); ConnectorSummary& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The connector's compute capacity settings.</p> */ inline const CapacityDescription& GetCapacity() const{ return m_capacity; } /** * <p>The connector's compute capacity settings.</p> */ inline bool CapacityHasBeenSet() const { return m_capacityHasBeenSet; } /** * <p>The connector's compute capacity settings.</p> */ inline void SetCapacity(const CapacityDescription& value) { m_capacityHasBeenSet = true; m_capacity = value; } /** * <p>The connector's compute capacity settings.</p> */ inline void SetCapacity(CapacityDescription&& value) { m_capacityHasBeenSet = true; m_capacity = std::move(value); } /** * <p>The connector's compute capacity settings.</p> */ inline ConnectorSummary& WithCapacity(const CapacityDescription& value) { SetCapacity(value); return *this;} /** * <p>The connector's compute capacity settings.</p> */ inline ConnectorSummary& WithCapacity(CapacityDescription&& value) { SetCapacity(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the connector.</p> */ inline const Aws::String& GetConnectorArn() const{ return m_connectorArn; } /** * <p>The Amazon Resource Name (ARN) of the connector.</p> */ inline bool ConnectorArnHasBeenSet() const { return m_connectorArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the connector.</p> */ inline void SetConnectorArn(const Aws::String& value) { m_connectorArnHasBeenSet = true; m_connectorArn = value; } /** * <p>The Amazon Resource Name (ARN) of the connector.</p> */ inline void SetConnectorArn(Aws::String&& value) { m_connectorArnHasBeenSet = true; m_connectorArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the connector.</p> */ inline void SetConnectorArn(const char* value) { m_connectorArnHasBeenSet = true; m_connectorArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the connector.</p> */ inline ConnectorSummary& WithConnectorArn(const Aws::String& value) { SetConnectorArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the connector.</p> */ inline ConnectorSummary& WithConnectorArn(Aws::String&& value) { SetConnectorArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the connector.</p> */ inline ConnectorSummary& WithConnectorArn(const char* value) { SetConnectorArn(value); return *this;} /** * <p>The description of the connector.</p> */ inline const Aws::String& GetConnectorDescription() const{ return m_connectorDescription; } /** * <p>The description of the connector.</p> */ inline bool ConnectorDescriptionHasBeenSet() const { return m_connectorDescriptionHasBeenSet; } /** * <p>The description of the connector.</p> */ inline void SetConnectorDescription(const Aws::String& value) { m_connectorDescriptionHasBeenSet = true; m_connectorDescription = value; } /** * <p>The description of the connector.</p> */ inline void SetConnectorDescription(Aws::String&& value) { m_connectorDescriptionHasBeenSet = true; m_connectorDescription = std::move(value); } /** * <p>The description of the connector.</p> */ inline void SetConnectorDescription(const char* value) { m_connectorDescriptionHasBeenSet = true; m_connectorDescription.assign(value); } /** * <p>The description of the connector.</p> */ inline ConnectorSummary& WithConnectorDescription(const Aws::String& value) { SetConnectorDescription(value); return *this;} /** * <p>The description of the connector.</p> */ inline ConnectorSummary& WithConnectorDescription(Aws::String&& value) { SetConnectorDescription(std::move(value)); return *this;} /** * <p>The description of the connector.</p> */ inline ConnectorSummary& WithConnectorDescription(const char* value) { SetConnectorDescription(value); return *this;} /** * <p>The name of the connector.</p> */ inline const Aws::String& GetConnectorName() const{ return m_connectorName; } /** * <p>The name of the connector.</p> */ inline bool ConnectorNameHasBeenSet() const { return m_connectorNameHasBeenSet; } /** * <p>The name of the connector.</p> */ inline void SetConnectorName(const Aws::String& value) { m_connectorNameHasBeenSet = true; m_connectorName = value; } /** * <p>The name of the connector.</p> */ inline void SetConnectorName(Aws::String&& value) { m_connectorNameHasBeenSet = true; m_connectorName = std::move(value); } /** * <p>The name of the connector.</p> */ inline void SetConnectorName(const char* value) { m_connectorNameHasBeenSet = true; m_connectorName.assign(value); } /** * <p>The name of the connector.</p> */ inline ConnectorSummary& WithConnectorName(const Aws::String& value) { SetConnectorName(value); return *this;} /** * <p>The name of the connector.</p> */ inline ConnectorSummary& WithConnectorName(Aws::String&& value) { SetConnectorName(std::move(value)); return *this;} /** * <p>The name of the connector.</p> */ inline ConnectorSummary& WithConnectorName(const char* value) { SetConnectorName(value); return *this;} /** * <p>The state of the connector.</p> */ inline const ConnectorState& GetConnectorState() const{ return m_connectorState; } /** * <p>The state of the connector.</p> */ inline bool ConnectorStateHasBeenSet() const { return m_connectorStateHasBeenSet; } /** * <p>The state of the connector.</p> */ inline void SetConnectorState(const ConnectorState& value) { m_connectorStateHasBeenSet = true; m_connectorState = value; } /** * <p>The state of the connector.</p> */ inline void SetConnectorState(ConnectorState&& value) { m_connectorStateHasBeenSet = true; m_connectorState = std::move(value); } /** * <p>The state of the connector.</p> */ inline ConnectorSummary& WithConnectorState(const ConnectorState& value) { SetConnectorState(value); return *this;} /** * <p>The state of the connector.</p> */ inline ConnectorSummary& WithConnectorState(ConnectorState&& value) { SetConnectorState(std::move(value)); return *this;} /** * <p>The time that the connector was created.</p> */ inline const Aws::Utils::DateTime& GetCreationTime() const{ return m_creationTime; } /** * <p>The time that the connector was created.</p> */ inline bool CreationTimeHasBeenSet() const { return m_creationTimeHasBeenSet; } /** * <p>The time that the connector was created.</p> */ inline void SetCreationTime(const Aws::Utils::DateTime& value) { m_creationTimeHasBeenSet = true; m_creationTime = value; } /** * <p>The time that the connector was created.</p> */ inline void SetCreationTime(Aws::Utils::DateTime&& value) { m_creationTimeHasBeenSet = true; m_creationTime = std::move(value); } /** * <p>The time that the connector was created.</p> */ inline ConnectorSummary& WithCreationTime(const Aws::Utils::DateTime& value) { SetCreationTime(value); return *this;} /** * <p>The time that the connector was created.</p> */ inline ConnectorSummary& WithCreationTime(Aws::Utils::DateTime&& value) { SetCreationTime(std::move(value)); return *this;} /** * <p>The current version of the connector.</p> */ inline const Aws::String& GetCurrentVersion() const{ return m_currentVersion; } /** * <p>The current version of the connector.</p> */ inline bool CurrentVersionHasBeenSet() const { return m_currentVersionHasBeenSet; } /** * <p>The current version of the connector.</p> */ inline void SetCurrentVersion(const Aws::String& value) { m_currentVersionHasBeenSet = true; m_currentVersion = value; } /** * <p>The current version of the connector.</p> */ inline void SetCurrentVersion(Aws::String&& value) { m_currentVersionHasBeenSet = true; m_currentVersion = std::move(value); } /** * <p>The current version of the connector.</p> */ inline void SetCurrentVersion(const char* value) { m_currentVersionHasBeenSet = true; m_currentVersion.assign(value); } /** * <p>The current version of the connector.</p> */ inline ConnectorSummary& WithCurrentVersion(const Aws::String& value) { SetCurrentVersion(value); return *this;} /** * <p>The current version of the connector.</p> */ inline ConnectorSummary& WithCurrentVersion(Aws::String&& value) { SetCurrentVersion(std::move(value)); return *this;} /** * <p>The current version of the connector.</p> */ inline ConnectorSummary& WithCurrentVersion(const char* value) { SetCurrentVersion(value); return *this;} /** * <p>The details of the Apache Kafka cluster to which the connector is * connected.</p> */ inline const KafkaClusterDescription& GetKafkaCluster() const{ return m_kafkaCluster; } /** * <p>The details of the Apache Kafka cluster to which the connector is * connected.</p> */ inline bool KafkaClusterHasBeenSet() const { return m_kafkaClusterHasBeenSet; } /** * <p>The details of the Apache Kafka cluster to which the connector is * connected.</p> */ inline void SetKafkaCluster(const KafkaClusterDescription& value) { m_kafkaClusterHasBeenSet = true; m_kafkaCluster = value; } /** * <p>The details of the Apache Kafka cluster to which the connector is * connected.</p> */ inline void SetKafkaCluster(KafkaClusterDescription&& value) { m_kafkaClusterHasBeenSet = true; m_kafkaCluster = std::move(value); } /** * <p>The details of the Apache Kafka cluster to which the connector is * connected.</p> */ inline ConnectorSummary& WithKafkaCluster(const KafkaClusterDescription& value) { SetKafkaCluster(value); return *this;} /** * <p>The details of the Apache Kafka cluster to which the connector is * connected.</p> */ inline ConnectorSummary& WithKafkaCluster(KafkaClusterDescription&& value) { SetKafkaCluster(std::move(value)); return *this;} /** * <p>The type of client authentication used to connect to the Apache Kafka * cluster. The value is NONE when no client authentication is used.</p> */ inline const KafkaClusterClientAuthenticationDescription& GetKafkaClusterClientAuthentication() const{ return m_kafkaClusterClientAuthentication; } /** * <p>The type of client authentication used to connect to the Apache Kafka * cluster. The value is NONE when no client authentication is used.</p> */ inline bool KafkaClusterClientAuthenticationHasBeenSet() const { return m_kafkaClusterClientAuthenticationHasBeenSet; } /** * <p>The type of client authentication used to connect to the Apache Kafka * cluster. The value is NONE when no client authentication is used.</p> */ inline void SetKafkaClusterClientAuthentication(const KafkaClusterClientAuthenticationDescription& value) { m_kafkaClusterClientAuthenticationHasBeenSet = true; m_kafkaClusterClientAuthentication = value; } /** * <p>The type of client authentication used to connect to the Apache Kafka * cluster. The value is NONE when no client authentication is used.</p> */ inline void SetKafkaClusterClientAuthentication(KafkaClusterClientAuthenticationDescription&& value) { m_kafkaClusterClientAuthenticationHasBeenSet = true; m_kafkaClusterClientAuthentication = std::move(value); } /** * <p>The type of client authentication used to connect to the Apache Kafka * cluster. The value is NONE when no client authentication is used.</p> */ inline ConnectorSummary& WithKafkaClusterClientAuthentication(const KafkaClusterClientAuthenticationDescription& value) { SetKafkaClusterClientAuthentication(value); return *this;} /** * <p>The type of client authentication used to connect to the Apache Kafka * cluster. The value is NONE when no client authentication is used.</p> */ inline ConnectorSummary& WithKafkaClusterClientAuthentication(KafkaClusterClientAuthenticationDescription&& value) { SetKafkaClusterClientAuthentication(std::move(value)); return *this;} /** * <p>Details of encryption in transit to the Apache Kafka cluster.</p> */ inline const KafkaClusterEncryptionInTransitDescription& GetKafkaClusterEncryptionInTransit() const{ return m_kafkaClusterEncryptionInTransit; } /** * <p>Details of encryption in transit to the Apache Kafka cluster.</p> */ inline bool KafkaClusterEncryptionInTransitHasBeenSet() const { return m_kafkaClusterEncryptionInTransitHasBeenSet; } /** * <p>Details of encryption in transit to the Apache Kafka cluster.</p> */ inline void SetKafkaClusterEncryptionInTransit(const KafkaClusterEncryptionInTransitDescription& value) { m_kafkaClusterEncryptionInTransitHasBeenSet = true; m_kafkaClusterEncryptionInTransit = value; } /** * <p>Details of encryption in transit to the Apache Kafka cluster.</p> */ inline void SetKafkaClusterEncryptionInTransit(KafkaClusterEncryptionInTransitDescription&& value) { m_kafkaClusterEncryptionInTransitHasBeenSet = true; m_kafkaClusterEncryptionInTransit = std::move(value); } /** * <p>Details of encryption in transit to the Apache Kafka cluster.</p> */ inline ConnectorSummary& WithKafkaClusterEncryptionInTransit(const KafkaClusterEncryptionInTransitDescription& value) { SetKafkaClusterEncryptionInTransit(value); return *this;} /** * <p>Details of encryption in transit to the Apache Kafka cluster.</p> */ inline ConnectorSummary& WithKafkaClusterEncryptionInTransit(KafkaClusterEncryptionInTransitDescription&& value) { SetKafkaClusterEncryptionInTransit(std::move(value)); return *this;} /** * <p>The version of Kafka Connect. It has to be compatible with both the Apache * Kafka cluster's version and the plugins.</p> */ inline const Aws::String& GetKafkaConnectVersion() const{ return m_kafkaConnectVersion; } /** * <p>The version of Kafka Connect. It has to be compatible with both the Apache * Kafka cluster's version and the plugins.</p> */ inline bool KafkaConnectVersionHasBeenSet() const { return m_kafkaConnectVersionHasBeenSet; } /** * <p>The version of Kafka Connect. It has to be compatible with both the Apache * Kafka cluster's version and the plugins.</p> */ inline void SetKafkaConnectVersion(const Aws::String& value) { m_kafkaConnectVersionHasBeenSet = true; m_kafkaConnectVersion = value; } /** * <p>The version of Kafka Connect. It has to be compatible with both the Apache * Kafka cluster's version and the plugins.</p> */ inline void SetKafkaConnectVersion(Aws::String&& value) { m_kafkaConnectVersionHasBeenSet = true; m_kafkaConnectVersion = std::move(value); } /** * <p>The version of Kafka Connect. It has to be compatible with both the Apache * Kafka cluster's version and the plugins.</p> */ inline void SetKafkaConnectVersion(const char* value) { m_kafkaConnectVersionHasBeenSet = true; m_kafkaConnectVersion.assign(value); } /** * <p>The version of Kafka Connect. It has to be compatible with both the Apache * Kafka cluster's version and the plugins.</p> */ inline ConnectorSummary& WithKafkaConnectVersion(const Aws::String& value) { SetKafkaConnectVersion(value); return *this;} /** * <p>The version of Kafka Connect. It has to be compatible with both the Apache * Kafka cluster's version and the plugins.</p> */ inline ConnectorSummary& WithKafkaConnectVersion(Aws::String&& value) { SetKafkaConnectVersion(std::move(value)); return *this;} /** * <p>The version of Kafka Connect. It has to be compatible with both the Apache * Kafka cluster's version and the plugins.</p> */ inline ConnectorSummary& WithKafkaConnectVersion(const char* value) { SetKafkaConnectVersion(value); return *this;} /** * <p>The settings for delivering connector logs to Amazon CloudWatch Logs.</p> */ inline const LogDeliveryDescription& GetLogDelivery() const{ return m_logDelivery; } /** * <p>The settings for delivering connector logs to Amazon CloudWatch Logs.</p> */ inline bool LogDeliveryHasBeenSet() const { return m_logDeliveryHasBeenSet; } /** * <p>The settings for delivering connector logs to Amazon CloudWatch Logs.</p> */ inline void SetLogDelivery(const LogDeliveryDescription& value) { m_logDeliveryHasBeenSet = true; m_logDelivery = value; } /** * <p>The settings for delivering connector logs to Amazon CloudWatch Logs.</p> */ inline void SetLogDelivery(LogDeliveryDescription&& value) { m_logDeliveryHasBeenSet = true; m_logDelivery = std::move(value); } /** * <p>The settings for delivering connector logs to Amazon CloudWatch Logs.</p> */ inline ConnectorSummary& WithLogDelivery(const LogDeliveryDescription& value) { SetLogDelivery(value); return *this;} /** * <p>The settings for delivering connector logs to Amazon CloudWatch Logs.</p> */ inline ConnectorSummary& WithLogDelivery(LogDeliveryDescription&& value) { SetLogDelivery(std::move(value)); return *this;} /** * <p>Specifies which plugins were used for this connector.</p> */ inline const Aws::Vector<PluginDescription>& GetPlugins() const{ return m_plugins; } /** * <p>Specifies which plugins were used for this connector.</p> */ inline bool PluginsHasBeenSet() const { return m_pluginsHasBeenSet; } /** * <p>Specifies which plugins were used for this connector.</p> */ inline void SetPlugins(const Aws::Vector<PluginDescription>& value) { m_pluginsHasBeenSet = true; m_plugins = value; } /** * <p>Specifies which plugins were used for this connector.</p> */ inline void SetPlugins(Aws::Vector<PluginDescription>&& value) { m_pluginsHasBeenSet = true; m_plugins = std::move(value); } /** * <p>Specifies which plugins were used for this connector.</p> */ inline ConnectorSummary& WithPlugins(const Aws::Vector<PluginDescription>& value) { SetPlugins(value); return *this;} /** * <p>Specifies which plugins were used for this connector.</p> */ inline ConnectorSummary& WithPlugins(Aws::Vector<PluginDescription>&& value) { SetPlugins(std::move(value)); return *this;} /** * <p>Specifies which plugins were used for this connector.</p> */ inline ConnectorSummary& AddPlugins(const PluginDescription& value) { m_pluginsHasBeenSet = true; m_plugins.push_back(value); return *this; } /** * <p>Specifies which plugins were used for this connector.</p> */ inline ConnectorSummary& AddPlugins(PluginDescription&& value) { m_pluginsHasBeenSet = true; m_plugins.push_back(std::move(value)); return *this; } /** * <p>The Amazon Resource Name (ARN) of the IAM role used by the connector to * access Amazon Web Services resources.</p> */ inline const Aws::String& GetServiceExecutionRoleArn() const{ return m_serviceExecutionRoleArn; } /** * <p>The Amazon Resource Name (ARN) of the IAM role used by the connector to * access Amazon Web Services resources.</p> */ inline bool ServiceExecutionRoleArnHasBeenSet() const { return m_serviceExecutionRoleArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the IAM role used by the connector to * access Amazon Web Services resources.</p> */ inline void SetServiceExecutionRoleArn(const Aws::String& value) { m_serviceExecutionRoleArnHasBeenSet = true; m_serviceExecutionRoleArn = value; } /** * <p>The Amazon Resource Name (ARN) of the IAM role used by the connector to * access Amazon Web Services resources.</p> */ inline void SetServiceExecutionRoleArn(Aws::String&& value) { m_serviceExecutionRoleArnHasBeenSet = true; m_serviceExecutionRoleArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the IAM role used by the connector to * access Amazon Web Services resources.</p> */ inline void SetServiceExecutionRoleArn(const char* value) { m_serviceExecutionRoleArnHasBeenSet = true; m_serviceExecutionRoleArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the IAM role used by the connector to * access Amazon Web Services resources.</p> */ inline ConnectorSummary& WithServiceExecutionRoleArn(const Aws::String& value) { SetServiceExecutionRoleArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the IAM role used by the connector to * access Amazon Web Services resources.</p> */ inline ConnectorSummary& WithServiceExecutionRoleArn(Aws::String&& value) { SetServiceExecutionRoleArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the IAM role used by the connector to * access Amazon Web Services resources.</p> */ inline ConnectorSummary& WithServiceExecutionRoleArn(const char* value) { SetServiceExecutionRoleArn(value); return *this;} /** * <p>The worker configurations that are in use with the connector.</p> */ inline const WorkerConfigurationDescription& GetWorkerConfiguration() const{ return m_workerConfiguration; } /** * <p>The worker configurations that are in use with the connector.</p> */ inline bool WorkerConfigurationHasBeenSet() const { return m_workerConfigurationHasBeenSet; } /** * <p>The worker configurations that are in use with the connector.</p> */ inline void SetWorkerConfiguration(const WorkerConfigurationDescription& value) { m_workerConfigurationHasBeenSet = true; m_workerConfiguration = value; } /** * <p>The worker configurations that are in use with the connector.</p> */ inline void SetWorkerConfiguration(WorkerConfigurationDescription&& value) { m_workerConfigurationHasBeenSet = true; m_workerConfiguration = std::move(value); } /** * <p>The worker configurations that are in use with the connector.</p> */ inline ConnectorSummary& WithWorkerConfiguration(const WorkerConfigurationDescription& value) { SetWorkerConfiguration(value); return *this;} /** * <p>The worker configurations that are in use with the connector.</p> */ inline ConnectorSummary& WithWorkerConfiguration(WorkerConfigurationDescription&& value) { SetWorkerConfiguration(std::move(value)); return *this;} private: CapacityDescription m_capacity; bool m_capacityHasBeenSet; Aws::String m_connectorArn; bool m_connectorArnHasBeenSet; Aws::String m_connectorDescription; bool m_connectorDescriptionHasBeenSet; Aws::String m_connectorName; bool m_connectorNameHasBeenSet; ConnectorState m_connectorState; bool m_connectorStateHasBeenSet; Aws::Utils::DateTime m_creationTime; bool m_creationTimeHasBeenSet; Aws::String m_currentVersion; bool m_currentVersionHasBeenSet; KafkaClusterDescription m_kafkaCluster; bool m_kafkaClusterHasBeenSet; KafkaClusterClientAuthenticationDescription m_kafkaClusterClientAuthentication; bool m_kafkaClusterClientAuthenticationHasBeenSet; KafkaClusterEncryptionInTransitDescription m_kafkaClusterEncryptionInTransit; bool m_kafkaClusterEncryptionInTransitHasBeenSet; Aws::String m_kafkaConnectVersion; bool m_kafkaConnectVersionHasBeenSet; LogDeliveryDescription m_logDelivery; bool m_logDeliveryHasBeenSet; Aws::Vector<PluginDescription> m_plugins; bool m_pluginsHasBeenSet; Aws::String m_serviceExecutionRoleArn; bool m_serviceExecutionRoleArnHasBeenSet; WorkerConfigurationDescription m_workerConfiguration; bool m_workerConfigurationHasBeenSet; }; } // namespace Model } // namespace KafkaConnect } // namespace Aws
apache-2.0
NotFound403/WePay
src/main/java/cn/felord/wepay/ali/sdk/api/request/KoubeiRetailShopitemUploadRequest.java
4790
package cn.felord.wepay.ali.sdk.api.request; import java.util.Map; import cn.felord.wepay.ali.sdk.api.AlipayRequest; import cn.felord.wepay.ali.sdk.api.internal.util.AlipayHashMap; import cn.felord.wepay.ali.sdk.api.response.KoubeiRetailShopitemUploadResponse; import cn.felord.wepay.ali.sdk.api.AlipayObject; /** * ALIPAY API: koubei.retail.shopitem.upload request * * @author auto create * @version $Id: $Id */ public class KoubeiRetailShopitemUploadRequest implements AlipayRequest<KoubeiRetailShopitemUploadResponse> { private AlipayHashMap udfParams; // add user-defined text parameters private String apiVersion="1.0"; /** * isv 回传的门店商品信息上传接口 */ private String bizContent; /** * <p>Setter for the field <code>bizContent</code>.</p> * * @param bizContent a {@link java.lang.String} object. */ public void setBizContent(String bizContent) { this.bizContent = bizContent; } /** * <p>Getter for the field <code>bizContent</code>.</p> * * @return a {@link java.lang.String} object. */ public String getBizContent() { return this.bizContent; } private String terminalType; private String terminalInfo; private String prodCode; private String notifyUrl; private String returnUrl; private boolean needEncrypt=false; private AlipayObject bizModel=null; /** * <p>Getter for the field <code>notifyUrl</code>.</p> * * @return a {@link java.lang.String} object. */ public String getNotifyUrl() { return this.notifyUrl; } /** {@inheritDoc} */ public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } /** * <p>Getter for the field <code>returnUrl</code>.</p> * * @return a {@link java.lang.String} object. */ public String getReturnUrl() { return this.returnUrl; } /** {@inheritDoc} */ public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } /** * <p>Getter for the field <code>apiVersion</code>.</p> * * @return a {@link java.lang.String} object. */ public String getApiVersion() { return this.apiVersion; } /** {@inheritDoc} */ public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } /** {@inheritDoc} */ public void setTerminalType(String terminalType){ this.terminalType=terminalType; } /** * <p>Getter for the field <code>terminalType</code>.</p> * * @return a {@link java.lang.String} object. */ public String getTerminalType(){ return this.terminalType; } /** {@inheritDoc} */ public void setTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } /** * <p>Getter for the field <code>terminalInfo</code>.</p> * * @return a {@link java.lang.String} object. */ public String getTerminalInfo(){ return this.terminalInfo; } /** {@inheritDoc} */ public void setProdCode(String prodCode) { this.prodCode=prodCode; } /** * <p>Getter for the field <code>prodCode</code>.</p> * * @return a {@link java.lang.String} object. */ public String getProdCode() { return this.prodCode; } /** * <p>getApiMethodName.</p> * * @return a {@link java.lang.String} object. */ public String getApiMethodName() { return "koubei.retail.shopitem.upload"; } /** * <p>getTextParams.</p> * * @return a {@link java.util.Map} object. */ public Map<String, String> getTextParams() { AlipayHashMap txtParams = new AlipayHashMap(); txtParams.put("biz_content", this.bizContent); if(udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } /** * <p>putOtherTextParam.</p> * * @param key a {@link java.lang.String} object. * @param value a {@link java.lang.String} object. */ public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new AlipayHashMap(); } this.udfParams.put(key, value); } /** * <p>getResponseClass.</p> * * @return a {@link java.lang.Class} object. */ public Class<KoubeiRetailShopitemUploadResponse> getResponseClass() { return KoubeiRetailShopitemUploadResponse.class; } /** * <p>isNeedEncrypt.</p> * * @return a boolean. */ public boolean isNeedEncrypt() { return this.needEncrypt; } /** {@inheritDoc} */ public void setNeedEncrypt(boolean needEncrypt) { this.needEncrypt=needEncrypt; } /** * <p>Getter for the field <code>bizModel</code>.</p> * * @return a {@link cn.felord.wepay.ali.sdk.api.AlipayObject} object. */ public AlipayObject getBizModel() { return this.bizModel; } /** {@inheritDoc} */ public void setBizModel(AlipayObject bizModel) { this.bizModel=bizModel; } }
apache-2.0
mcanthony/slayer
README.md
5417
# Slayer [![Build Status](https://secure.travis-ci.org/bbcrd/slayer.png?branch=master)](http://travis-ci.org/bbcrd/slayer.js) > JavaScript time series spike detection for Node.js; like the Octave [findpeaks](http://www.mathworks.co.uk/help/signal/ref/findpeaks.html) function. Time series are often displayed as bar, line or area charts. A _peak_ or _spike_ in a time series is a the highest value before the trend start to decrease. In reality you do not need all the spikes. You only need **the highest spike amongst them**. _Slayer_ helps to identify these local peaks easily. [![](chart.png?raw=1)](http://blogs.sas.com/content/iml/2013/08/28/finite-diff-estimate-maxi/) # Install <table> <thead> <tr> <th>npm</th> <th>bower</th> <th>old school</th> </tr> </thead> <tbody> <tr> <td><code>npm install --save slayer</code></td> <td>-</td> <td><a href="https://github.com/bbcrd/slayer/archive/master.zip">download zip file</a></td> </tr> </tbody> </table> # Usage _Slayer_ exposes a fluent JavaScript API and requires as little configuration as possible. The following examples illustrates common use cases. ## Flat array peak detection ```js var slayer = require('slayer'); var arrayData = [0, 0, 0, 12, 0, …]; slayer().fromArray(arrayData, function(err, spikes){ console.log(spikes); // [ { x: 4, y: 12 }, { x: 12, y: 25 } ] }); ``` ## Object based peak detection ```js var slayer = require('slayer'); var arrayData = […, { date: '…', value: 12 }, …]; slayer() .y(function(item){ return item.value; }) .fromArray(arrayData, function(err, spikes){ console.log(spikes); // [ { x: 4, y: 12 }, { x: 12, y: 25 } ] }); ``` ## Streaming detection Not yet implemented. ```js var slayer = slayer().pipe(process.stdin); slayer.on('peak', function onSpike(spike){ console.log(spike); // { x: 4, y: 12 } }); slayer.on('end', function(){ console.log('Processing done!'); }); ``` # API Access the _Slayer_ API by requiring the CommonJS module: ```js var slayer = require('slayer'); ``` A _spike_ object is an object composed of two keys: - `x`: the index value within the time series array; - `y`: the spike value within the time series array. ## `slayer(config)` The `slayer()` factory returns a new chainable instance of _Slayer_. The optional `config` object enables you to adjust its behaviour according to your needs: - `minPeakDistance` (_Integer_): size of the values overlooked window. _Default is `30`_; - `minPeakHeight` (_Number_): discard any value below that threshold. _Default is `0`_. Returns a `slayer` chainable object. ## `.y(fn)` Data accessor applied to each series item and used to determine spike values. It will return this value as the `y` value of a spike object. ```js slayer() .y(function(item){ return item.value; // considering item looks like `{ value: 12 }` }) .fromArray(arrayData, function(err, spikes){ console.log(spikes); // { x: 4, y: 12 } }); ``` Returns a mutated `slayer` chainable object. ## `.x(fn)` Index accessor applied to each series item. It will return this value as the `x` value of a spike object. ```js slayer() .x(function(item, i){ return item.date; // considering item looks like `{ date: '2014-04-12T17:31:40.000Z', value: 12 }` }) .fromArray(arrayData, function(err, spikes){ console.log(spikes); // { x: '2014-04-12T17:31:40.000Z', y: 12 } }); ``` Returns a mutated `slayer` chainable object. ## `.transform(fn)` Transforms the spike object before returning it as part of the found spike collections. It is useful if you want to add extra data to the returned spike object. ```js slayer() .transform(function(xyItem, originalItem, i){ xyItem.id = originalItem.id; return xyItem; }) .fromArray(arrayData, function(err, spikes){ console.log(spikes); // { x: 4, y: 12, id: '21232f297a57a5a743894a0e4a801fc3' } }); ``` Returns a mutated `slayer` chainable object. ## `.fromArray(data, onComplete)` Processes an array of data and calls an `onComplete` callback with an `error` and `spikes` parameters. ```js slayer() .fromArray(arrayData, function(err, spikes){ if (err){ console.error(err); return; } console.log(spikes); // { x: 4, y: 12, id: '21232f297a57a5a743894a0e4a801fc3' } }); ``` Returns `undefined`. # Contributing and testing If you wish to contribute the project with code but you fear to break something, no worries as [TravisCI](https://travis-ci.org/bbcrd/slayer) takes care of this for each Pull Request. Nobody will blame your code. And feel free to ask _before_ making a pull request. We will try to provide you guidance for code design etc. If you want to run the tests locally, simply run: ```bash npm test ``` # Licence > Copyright 2014 British Broadcasting Corporation > > 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.
apache-2.0
skyjia/elasticsearch-rtf
plugins/marvel/_site/sense/app/kb/api_0_90/nodes.js
169
define([],function(){return function(n){n.addEndpointDescription("_nodes/hot_threads",{methods:["GET"],patterns:["_nodes/hot_threads","_nodes/{nodes}/hot_threads"]})}});
apache-2.0
cockroachlabs/roachprod
vendor/github.com/nlopes/slack/websocket_managed_conn_test.go
1918
package slack_test import ( "testing" slacktest "github.com/lusis/slack-test" "github.com/nlopes/slack" "github.com/stretchr/testify/assert" ) const ( testMessage = "test message" testToken = "TEST_TOKEN" ) func TestRTMSingleConnect(t *testing.T) { // Set up the test server. testServer := slacktest.NewTestServer() go testServer.Start() // Setup and start the RTM. slack.SLACK_API = testServer.GetAPIURL() api := slack.New(testToken) rtm := api.NewRTM() go rtm.ManageConnection() // Observe incoming messages. done := make(chan struct{}) connectingReceived := false connectedReceived := false testMessageReceived := false go func() { for msg := range rtm.IncomingEvents { switch ev := msg.Data.(type) { case *slack.ConnectingEvent: if connectingReceived { t.Error("Received multiple connecting events.") t.Fail() } connectingReceived = true case *slack.ConnectedEvent: if connectedReceived { t.Error("Received multiple connected events.") t.Fail() } connectedReceived = true case *slack.MessageEvent: if ev.Text == testMessage { testMessageReceived = true rtm.Disconnect() done <- struct{}{} return } t.Logf("Discarding message with content %+v", ev) default: t.Logf("Discarded event of type '%s' with content '%#v'", msg.Type, ev) } } }() // Send a message and sleep for some time to make sure the message can be processed client-side. testServer.SendDirectMessageToBot(testMessage) <-done testServer.Stop() // Verify that all expected events have been received by the RTM client. assert.True(t, connectingReceived, "Should have received a connecting event from the RTM instance.") assert.True(t, connectedReceived, "Should have received a connected event from the RTM instance.") assert.True(t, testMessageReceived, "Should have received a test message from the server.") }
apache-2.0
mission-peace/interview
C++/Graph Algorithms/Breadth First Search.cpp
843
#include<iostream> #include<vector> #include<list> #include<queue> using namespace std; void breadth_first_search(vector<list<int>> graph,int src){ vector<bool>visited(graph.size(),false); queue<int>Q; Q.push(src); visited[src] = true; while(!Q.empty()){ int vertex = Q.front(); Q.pop(); cout << vertex << " "; for(list<int>::iterator itr = graph[vertex].begin();itr!=graph[vertex].end();itr++){ if(!visited[*itr]) Q.push(*itr); visited[*itr] = true; } } } int main(){ vector<list<int>> graph; int v,e,src,des; cin >> v >> e; graph.resize(v); while(e--){ cin >> src >> des; graph[src].push_back(des); graph[des].push_back(src); } cin >> src; breadth_first_search(graph,src); return 0; }
apache-2.0
ONLYOFFICE/CommunityServer
web/studio/ASC.Web.Studio/ThirdParty/plugin/easybib/bibliography.js
9168
function Bibliography() { this.searchOptions = { source: 0, value: '', style: '' }; this.bibliography = []; this.bibliographyText = []; this.localStorageKey = "Bibliography"; }; Bibliography.prototype.showBookSearchResult = function (results) { for (key in results) { var title = results[key].display.title; var description = ""; var contributors = results[key].data.contributors; contributors.forEach(function (contributors_item) { if (description != "") { description += ", " + contributors_item.first + " " + contributors_item.last; } else { description += contributors_item.first + " " + contributors_item.last; } }); if (results[key].display.publisher) { description += " - " + results[key].display.publisher; } if (results[key].display.year) { description += " - " + results[key].display.year; } createSearchItem(title, description, key); } }; Bibliography.prototype.showJournalSearchResult = function(results) { results.forEach(function(results_item, i) { var title = results_item.data.journal.title; var description = results_item.data.pubjournal.title; createSearchItem(title, description, i); }); }; Bibliography.prototype.showWebSiteSearchResult = function (results) { var urlSearchResult; results.forEach(function(results_item, i) { try { urlSearchResult = new URL(results_item.display.displayurl).hostname; } catch(error) { urlSearchResult = results_item.display.displayurl; } createSearchItem(results_item.display.title + "(" + results_item.display.displayurl + ")", results_item.display.summary, i); }); }; Bibliography.prototype.createCitations = function (id, data) { var biblist = this; $.ajax({ url: '/api/2.0/files/easybib-citation', type: "POST", data: { citationData: JSON.stringify(data) }, success: function(answer) { if (answer.response.success) { try { var citation = JSON.parse(answer.response.citation); if (citation.status === 'ok') { biblist.bibliographyText.push({ id: id, data: citation.data }); createBibItem(id, citation.data); } } catch(e) { console.log(e.message); } } }, }); }; Bibliography.prototype.updateCitations = function (id, data) { var biblist = this; $.ajax({ url: '/api/2.0/files/easybib-citation', type: "POST", data: { citationData: JSON.stringify(data) }, success: function (answer) { if (answer.response.success) { try { var citation = JSON.parse(answer.response.citation); if (citation.status === 'ok') { if (biblist.bibliographyText.length > 0) { biblist.bibliographyText.forEach(function (item) { if (item.id == id) { item.data = citation.data; } }); } createBibItem(id, citation.data); } } catch (e) { console.log(e.message); } } }, }); }; Bibliography.prototype.getCitation = function (id, foundData, bibliographyStorage, fileId) { var biblist = this; var source = foundData.results[id]; var data; switch (this.searchOptions.source) { case 0: data = { style: $('#styles option:selected').val() ? $('#styles option:selected').val() : "3d-research", pubtype: source.data.pubtype, pubnonperiodical: source.data.pubnonperiodical, contributors: source.data.contributors, other: source.data.other, source: source.data.source }; break; case 1: data = { style: $('#styles option:selected').val() ? $('#styles option:selected').val() : "3d-research", pubtype: source.data.pubtype, pubjournal: source.data.pubjournal, publication_type: source.data.publication_type, contributors: source.data.contributors, other: source.data.other, source: source.data.source }; break; case 2: source.data.pubonline.url = source.display.displayurl; data = { style: $('#styles option:selected').val() ? $('#styles option:selected').val() : "3d-research", autocite: source.display.displayurl, pubtype: source.data.pubtype, pubonline: source.data.pubonline, other: source.data.other, website: source.data.website, source: source.data.source }; break; default: break; }; $.ajax({ url: '/api/2.0/files/easybib-citation', type: "POST", data: { citationData: JSON.stringify(data) }, success: function (answer) { if (answer.response.success && answer.response.citations != "error") { var citation = JSON.parse(answer.response.citation); if (citation.status === 'ok') { saveCitation.call(biblist, citation, data, bibliographyStorage, fileId); } else if (citation.status === 'error') { alert("ERROR. " + citation.msg); } } return true; }, error: function(err) { console.log(err); } }); }; Bibliography.prototype.fillListStyles = function (styles, bibliographyStyle) { var selectStyles = $('#styles'); for (var style in styles) { var value = styles[style]; selectStyles[0].options[selectStyles[0].options.length] = new Option(value, style); } $("#styles :first").remove(); selectStyles.attr('disabled', false); if (bibliographyStyle) { $("#styles option[value=" + bibliographyStyle + "]").attr('selected', 'true'); } }; function escapeHtml(str) { if (str) return $('<div />').text(str).html(); else return null; }; function createSearchItem(title, description, id) { var searchResult = $("#search_result"); $("#search_result").show(); $(".result-container .search-title").show(); $(".result-container .bibliography-title").hide(); $("#bib").hide(); searchResult.show(); var item = "<div class=\"search-item\" id=" + escapeHtml(id) + ">" + "<div class = \"citation\">" + "<h4 style=\"overflow-x: hidden;margin:0\">" + escapeHtml(title) + "</h4>" + "<p style=\";margin:0\">" + escapeHtml(description) + "</p>" + "</div>" + "<div class=\"add-button-container\">" + "<div class=\"add-button\" onclick=\"addItem(this)\"></div>" + "</div>" + "</div>"; $('#titleContent').text('Your Search Results'); searchResult.append(item); }; function createBibItem(id, data) { var item = "<div class=\"bibliography-part\">" + "<div class=\"bibliography-part-data\">" + escapeHtml(data) + "</div>" + "<div class=\"del-button-container\">" + "<div onclick=\"delBibliographyPart(this)\" id=bibliography-path_" + escapeHtml(id) + " class=\"del-bibliography-part\"></div>" + "</div>" + "</br>"; $('#bib').append(item); }; function saveCitation(citation, data, bibliographyStorage, fileId) { var id, bibliographyItem; if (this.bibliography.length > 0) { id = this.bibliography[this.bibliography.length - 1].id + 1; } else { id = 1; } bibliographyItem = { id: id, data: data }; this.bibliography.push(bibliographyItem); this.bibliographyText.push({ id: id, data: citation.data }); $("#search_result").empty(); $("#search_result").hide(); $(".result-container .search-title").hide(); $(".result-container .bibliography-title").show(); $("#bib").show(); createBibItem(id, citation.data); if (!localStorageManager.isAvailable || fileId == null) { return null; } else { if (bibliographyStorage) { bibliographyStorage[fileId] = this.bibliography; localStorageManager.setItem(this.localStorageKey, bibliographyStorage); } else { bibliographyStorage = {}; bibliographyStorage[fileId] = this.bibliography; localStorageManager.setItem(this.localStorageKey, bibliographyStorage); } } };
apache-2.0
caojieliang/crud-core
src/main/java/com/landian/crud/core/dao/ProxyDaoSupport.java
20038
package com.landian.crud.core.dao; import com.landian.commons.page.PageListSupport; import com.landian.commons.page.PageRequest; import com.landian.crud.core.builder.SelectBuilder; import com.landian.crud.core.builder.SqlBuilder; import com.landian.crud.core.builder.impl.*; import com.landian.crud.core.context.ResultMapContext; import com.landian.crud.core.context.SystemContextFactory; import com.landian.crud.core.context.impl.HashMapResultContext; import com.landian.crud.core.converter.ResultContextConverter; import com.landian.crud.core.converter.ResultContextConverterFactory; import com.landian.crud.core.converter.impl.JavaBeanConverter; import com.landian.crud.core.provider.ProviderHelper; import com.landian.crud.core.result.SingleValue; import com.landian.crud.core.result.StatisticMap; import com.landian.crud.core.result.StatisticMapBuilder; import com.landian.crud.core.sql.DeleteSQLBuilder; import com.landian.crud.core.sql.InsertSQLBuilder; import com.landian.crud.core.sql.PageSqlAdapter; import com.landian.crud.core.sql.UpdateSQLBuilder; import com.landian.sql.jpa.annotation.IdTypePolicy; import com.landian.sql.jpa.context.BeanContext; import com.landian.sql.jpa.context.ResultMapConfig; import com.landian.sql.jpa.context.ResultMappingVirtual; import com.landian.sql.jpa.criterion.Criterion; import com.landian.sql.jpa.criterion.CriterionAppender; import com.landian.sql.jpa.criterion.FieldAppender; import com.landian.sql.jpa.criterion.Restrictions; import com.landian.sql.jpa.log.JieLoggerProxy; import com.landian.sql.jpa.order.Order; import com.landian.sql.jpa.order.OrderAppender; import com.landian.sql.jpa.sql.SelectUnitAppender; import com.landian.sql.jpa.sql.SelectUnitRestrictions; import com.landian.sql.jpa.sql.UpdateUnitAppender; import com.landian.sql.jpa.utils.ConvertUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.lang.reflect.Method; import java.math.BigDecimal; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * ProxyDaoSupport * @author cao.jl * to be continute * * 毫无疑问,SpringData才是大神版的进化封装 */ @Repository public class ProxyDaoSupport<T> { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(ProxyDaoSupport.class); private static final Logger infoSQLLogger = Logger.getLogger("infoSQL"); @Autowired private ProxyDao proxyDao; private void proxyInfo(Object object){ if(null != infoSQLLogger){ infoSQLLogger.info(object); } } /** * 指定ID业务Bean是否存在 * @param beanId * @param beanContext * @return */ public boolean isExist(long beanId,BeanContext beanContext) { String beanIdColumn = this.getBeanIdColumn(beanContext); CommonSelectSQLBuilder builder = CommonSelectSQLBuilder.getInstance(beanContext.getTableName(), SelectUnitRestrictions.column(beanIdColumn), Restrictions.eq(beanIdColumn, beanId), Order.asc(beanIdColumn)); HashMapResultContext hashMapResultContext = this.doFind(builder.SQL()); if(hashMapResultContext.getResultCount() > 0){ return true; } return false; } public int doInsert(String sql){ return proxyDao.doInsert(sql); } /** * 插入对像bean * @param bean * @param beanContext */ public int insertWithId(Object bean,BeanContext beanContext){ String sql = InsertSQLBuilder.insertWithIdSQL(bean, beanContext); return proxyDao.doInsertWidthId(sql); } /** * 插入对像bean * @param bean * @param beanContext */ public void insert(Object bean,BeanContext beanContext){ String sql = InsertSQLBuilder.insertSQL(bean, beanContext); Object idObject = proxyDao.doInsertAndReturnId(sql); //回填ID refillId(bean, beanContext, idObject); } /** * 回填业务Bean ID */ private void refillId(Object bean, BeanContext beanContext,Object idObject){ try { String idFieldName = beanContext.getIdFieldName(); String setMethodName = ProviderHelper.toSetMethodName(idFieldName); Method idSetMethod = null; SingleValue idSingleValue = SingleValue.newInstance(idObject); Object fixIdObject = null; if(IdTypePolicy.INTEGER == beanContext.getIdType()){ fixIdObject = idSingleValue.integerValue(); idSetMethod = bean.getClass().getDeclaredMethod(setMethodName,Integer.class); }else if(IdTypePolicy.LONG == beanContext.getIdType()){ fixIdObject = idSingleValue.longValue(); idSetMethod = bean.getClass().getDeclaredMethod(setMethodName,Long.class); }else if(IdTypePolicy.BIGDECIMAL == beanContext.getIdType()){ fixIdObject = idSingleValue.bigDecimalValue(); idSetMethod = bean.getClass().getDeclaredMethod(setMethodName,BigDecimal.class); } if(null == idSetMethod){ String msg = MessageFormat.format("ID回填策略未实现,目标对像[{0}],目标类型[{1}]",bean,idObject); logger.warn(msg); }else{ idSetMethod.invoke(bean,new Object[]{fixIdObject}); } }catch (Exception e) { String errorMsg = "回填业务Bean ID异常!"; JieLoggerProxy.error(logger, errorMsg); JieLoggerProxy.error(logger, e); throw new RuntimeException(errorMsg); } } /** * 更新对像非空属性值 * @param bean * @param beanContext */ public int updateNotNull(Object bean, BeanContext beanContext) { String sql = UpdateSQLBuilder.updateNotNull(bean, beanContext); return proxyDao.doUpdate(sql); } /** * 更新字段 * @param updateUnitAppender 更新单元追加器 * @param criterionAppender 条件追加器 * @param beanContext * @return * @throws Exception */ public int update(UpdateUnitAppender updateUnitAppender, CriterionAppender criterionAppender, BeanContext beanContext){ String sql = UpdateSqlBuilder.getInstance(beanContext.getTableName(), updateUnitAppender, criterionAppender).SQL(); return proxyDao.doUpdate(sql); } /** * 更新对像非空属性值 * @param sql */ public int doUpdate(String sql) { return proxyDao.doUpdate(sql); } /** * 查询统计 * 由于经常需要根据ID(某属性作为key),统计某属性总计(某属性总计作为Value) * @param sql * @param resultMapConfig * @return */ public StatisticMap queryAsStatisticMap(String sql,ResultMapConfig resultMapConfig) { HashMapResultContext hashMapResultContext = doFind(sql); return StatisticMapBuilder.buildStatisticMap(resultMapConfig, hashMapResultContext); } /** * 根据SQL查询,返回结果集 * @param sql */ public HashMapResultContext doFind(String sql){ proxyInfo(sql); List<Map<String, Object>> resultContext = proxyDao.doFind(sql); HashMapResultContext hashMapResultContext = new HashMapResultContext(resultContext); return hashMapResultContext; } /** * 根据SQL查询,返回结果集 * @param sql */ public List doFind(String sql,Class clazz){ proxyInfo(clazz); proxyInfo(sql); //转换器 ResultContextConverter converter = JavaBeanConverter.newInstance(clazz); //适配调用 return this.doFind(sql, converter); } /** * @param sql * @param converter 结果集转换器 */ public List<T> doFindPage(String sql, int start, int pageSize, ResultContextConverter converter){ PageSqlAdapter pageSqlAdapter = SystemContextFactory.getPageSqlAdapter(); String pageSQL = pageSqlAdapter.wrapSQL(sql,start,pageSize); //结果集 List<Map<String, Object>> resultList = proxyDao.doFind(pageSQL); //处理结果集 List<T> beanList = new ArrayList<T>(); if(CollectionUtils.isNotEmpty(resultList)){ for(Map<String, Object> dataMap : resultList){ @SuppressWarnings("unchecked") T bean = (T) converter.convert(dataMap); beanList.add(bean); } } return beanList; } /** * @param sql * @param converter 结果集转换器 */ public List<T> doFind(String sql, ResultContextConverter converter){ //结果集 HashMapResultContext hashMapResultContext = this.doFind(sql); //处理结果集 List<T> beanList = new ArrayList<T>(); List<Map<String, Object>> resultList = hashMapResultContext.getResultObject(); if(CollectionUtils.isNotEmpty(resultList)){ for(Map<String, Object> dataMap : resultList){ @SuppressWarnings("unchecked") T bean = (T) converter.convert(dataMap); beanList.add(bean); } } return beanList; } /** * 根据ID查询对像 * @param beanId * @param beanContext */ public T queryById(int beanId, BeanContext beanContext){ Integer id = beanId; return this.queryById(id.longValue(), beanContext); } /** * 根据ID查询对像 * @param beanId * @param beanContext */ public T queryById(long beanId,BeanContext beanContext){ List<Long> ids = new ArrayList<Long>(); ids.add(beanId); List<T> list = this.queryByIds(ids,beanContext); if(!CollectionUtils.isEmpty(list)){ return list.get(0); } return null; } /** * 根据ID列表,查询对像集 * @param beanContext * @param ids */ public List<T> queryByIds(BeanContext beanContext,List<Integer> ids){ if(CollectionUtils.isEmpty(ids)){ return Collections.EMPTY_LIST; } return queryByIds(ConvertUtils.Int2long(ids),beanContext); } /** * 根据ID列表,查询对像集 * @param ids * @param beanContext */ public List<T> queryByIds(List<Long> ids,BeanContext beanContext){ if(CollectionUtils.isEmpty(ids)){ return Collections.EMPTY_LIST; } CriterionAppender criterionAppender = CriterionAppender.newInstance(); String column = beanContext.getIdFieldName(); criterionAppender.add(Restrictions.in(column, ids,0l)); List<T> beanList = queryBean(beanContext,criterionAppender); return beanList; } /** * 此方法非元数据表,谨慎使用 * 查询Bean全部对像 * @param beanContext */ public List<T> queryBeanAll(BeanContext beanContext) { return queryBean(beanContext,null,null); } /** * 查询Bean * @param beanContext * @param criterionAppender */ public List<T> queryBean(BeanContext beanContext,CriterionAppender criterionAppender) { return queryBean(beanContext,criterionAppender,null); } /** * 查询Bean * @param beanContext * @param proxyOrderAppender */ public List<T> queryBean(BeanContext beanContext,OrderAppender proxyOrderAppender) { return queryBean(beanContext,null,proxyOrderAppender); } /** * 查询bean * @param beanContext * @param criterionAppender * @param proxyOrderAppender */ public List<T> queryBean(BeanContext beanContext,CriterionAppender criterionAppender, OrderAppender proxyOrderAppender) { String tableName = beanContext.getTableName(); //选择器 Class<T> beanClass = beanContext.getBeanClass(); SelectBuilder selectBuilder = SelectBuilderFactory.builder(beanClass); SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanClass, selectBuilder, criterionAppender, proxyOrderAppender); //转换器 ResultContextConverter resultContextConverter = ResultContextConverterFactory.build(beanContext.getBeanClass()); //数据集 List<T> beanList = queryBean(sqlBuilder,resultContextConverter); return beanList; } /** * 查询bean * @param beanContext * @param criterionAppender * @param proxyOrderAppender */ public List<T> queryBeanField(BeanContext beanContext,FieldAppender fieldAppender, CriterionAppender criterionAppender, OrderAppender proxyOrderAppender) { String tableName = beanContext.getTableName(); //选择器 SelectBuilder selectBuilder = new FieldAppenderSelectBuilder(fieldAppender,beanContext.getBeanClass()); SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanContext.getBeanClass(), selectBuilder, criterionAppender, proxyOrderAppender); //转换器 ResultContextConverter resultContextConverter = ResultContextConverterFactory.build(beanContext.getBeanClass()); //数据集 List<T> beanList = queryBean(sqlBuilder, resultContextConverter); return beanList; } /** * 查询对像信息 * @param tableName * @param clazz * @param selectUnitAppender * @param criterionAppender * @param proxyOrderAppender * @return */ public HashMapResultContext queryBeanInfo(String tableName, Class clazz,SelectUnitAppender selectUnitAppender, CriterionAppender criterionAppender, OrderAppender proxyOrderAppender) { //选择器 SelectBuilder selectBuilder = SelectBuilderFactory.builder(selectUnitAppender); //SQL构建器 SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, clazz, selectBuilder, criterionAppender, proxyOrderAppender); //结果集 String sql = sqlBuilder.SQL(); HashMapResultContext hashMapResultContext = this.doFind(sql); return hashMapResultContext; } /** * 决定不重载此方法基于以下理由 * 1.分页查询大部份情况需要追加条件和排序 * 2.参数已经没有更好重构感觉,个人感觉不能再少了, * 重载会令方法组数量变多 * 3.criterionAppender proxyOrderAppender 入参可为null, * 里面的SqlBuilder已作了相应处理, * @param beanContext * @param criterionAppender * @param proxyOrderAppender * @param pageRequest * @return */ public PageListSupport<T> queryBeanPage(BeanContext beanContext, CriterionAppender criterionAppender,OrderAppender proxyOrderAppender,PageRequest pageRequest) { String tableName = beanContext.getTableName(); //选择器 SelectBuilder selectBuilder = SelectBuilderFactory.builder(beanContext.getBeanClass()); //加强条件追加器 if(null == criterionAppender){ criterionAppender = CriterionAppender.newInstance(); } //SQL建造器 SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanContext.getBeanClass(), selectBuilder, criterionAppender, proxyOrderAppender); //转换器 ResultContextConverter resultContextConverter = ResultContextConverterFactory.build(beanContext.getBeanClass()); //分页查询 int start = getPageStart(pageRequest); int size = pageRequest.getPageSize(); List<T> beanList = doFindPage(sqlBuilder.SQL(), start, size, resultContextConverter); //封装PageListSupport PageListSupport<T> pageListSupport = new PageListSupport<T>(); //总数查询 Long count = 0l; if(!CollectionUtils.isEmpty(beanList)){ HashMapResultContext hashMapResultContext = this.doFind(sqlBuilder.SQLCount()); Object countObj = hashMapResultContext.singleResult(); if(null != countObj){ SingleValue singleValue = SingleValue.newInstance(countObj); count = singleValue.longValue(); } } pageListSupport.setList(beanList); pageListSupport.setCount(count); pageListSupport.setPageIndex(pageRequest.getPageIndex()); pageListSupport.setPageSize(pageRequest.getPageSize()); return pageListSupport; } /** * 查询Bean * @param sqlBuilder * @param resultContextConverter */ public List<T> queryBean(SqlBuilder sqlBuilder,ResultContextConverter resultContextConverter) { return doFind(sqlBuilder.SQL(), resultContextConverter); } /** * 得到业务Bean的id字段 * @param beanContext * @return */ public String getBeanIdColumn(BeanContext beanContext){ String idFieldName = beanContext.getIdFieldName(); Map<String, ResultMappingVirtual> resultMappingMap = ResultMapContext.getResultMappingMap(beanContext.getBeanClass()); String columnName = resultMappingMap.get(idFieldName).getColumn(); return columnName; } /** * author jie * date 15/08/21 * 根据业务BeanID删除业务Bean * @param beanId * @param beanContext * @return */ public int deleteById(long beanId, BeanContext beanContext) { Criterion criterion = buildIdCriterion(beanId, beanContext); String sql = DeleteSQLBuilder.buildDeleteSQL(beanContext.getTableName(), criterion); return doDelete(sql); } /** * 构建ID条件 * @param id * @param beanContext * @return */ public Criterion buildIdCriterion(long id, BeanContext beanContext){ String beanIdColumn = getBeanIdColumn(beanContext); return Restrictions.eq(beanIdColumn,id); } /** * 构建ID条件 * @param ids * @param beanContext * @return */ public Criterion buildIdCriterion(List<Long> ids, BeanContext beanContext){ String beanIdColumn = getBeanIdColumn(beanContext); return Restrictions.in(beanIdColumn,ids,0l); } /** * 根据ID批量删除 * @param ids * @param beanContext * @return */ public int deleteByIdLong(List<Long> ids,BeanContext beanContext) { if(CollectionUtils.isEmpty(ids)){ return 0; } Criterion criterion = buildIdCriterion(ids, beanContext); String sql = DeleteSQLBuilder.buildDeleteSQL(beanContext.getTableName(), criterion); return doDelete(sql); } public int doDelete(String sql){ return proxyDao.doDelete(sql); } /** * 得到构建的查询SQL * @param beanContext * @param criterionAppender * @param proxyOrderAppender * @return */ public String getQuerySQL(BeanContext beanContext, CriterionAppender criterionAppender, OrderAppender proxyOrderAppender) { //选择器 SelectBuilder selectBuilder = SelectBuilderFactory.builder(beanContext.getBeanClass()); //SQL建造器 String tableName = beanContext.getTableName(); SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanContext.getBeanClass(), selectBuilder, criterionAppender, proxyOrderAppender); return sqlBuilder.SQL(); } private int getPageStart(PageRequest pageRequest) { return pageRequest.getPageIndex() * pageRequest.getPageSize(); //起始分页位置 } /** * 根据SQL查询,返回结果集第一个对像 * @param sql */ public Object queryAsValueFirst(String sql,Class clazz){ List list = this.doFind(sql, clazz); if(CollectionUtils.isEmpty(list)){ return null; } return list.get(0); } /** * 根据SQL查询,返回单值列表结果 * @param sql */ public List queryAsValueList(String sql){ List list = Collections.EMPTY_LIST; HashMapResultContext hashMapResultContext = doFind(sql); if(hashMapResultContext.getResultCount() > 0){ list = hashMapResultContext.singleList(); } return list; } /** * 查询为SingleValue * @param sql * @return */ public SingleValue queryAsSingleValue(String sql) { HashMapResultContext hashMapResultContext = this.doFind(sql); Object object = hashMapResultContext.singleResult(); SingleValue singleValue = SingleValue.newInstance(object); return singleValue; } /** * 查询为SingleValueInt * @param sql * @return */ public int queryAsSingleValueInt(String sql) { SingleValue singleValue = queryAsSingleValue(sql); return singleValue.integerValue(); } /** * 查询为SingleValueLong * @param sql * @return */ public long queryAsSingleValueLong(String sql) { SingleValue singleValue = queryAsSingleValue(sql); return singleValue.longValue(); } /** * 查询为Long值列表 * @param sql * @return */ public List<Long> queryAsLongValue(String sql) { return proxyDao.queryAsLongValue(sql); } /** * 查询为Long值列表 * @param sql * @param start 开始位置 * @param size 查询大小 * @return */ public List<Long> queryAsLongValue(String sql, int start, int size) { PageSqlAdapter pageSqlAdapter = SystemContextFactory.getPageSqlAdapter(); String sqlQ = pageSqlAdapter.wrapSQL(sql, start, size); return proxyDao.queryAsLongValue(sqlQ); } /** * 查询为Integer值列表 * @param sql * @return */ public List<Integer> queryAsIntValue(String sql) { return proxyDao.queryAsIntValue(sql); } /** * 查询为Integer值列表 * @param sql * @param start 开始位置 * @param size 查询大小 * @return */ public List<Integer> queryAsIntValue(String sql, int start, int size) { PageSqlAdapter pageSqlAdapter = SystemContextFactory.getPageSqlAdapter(); String sqlQ = pageSqlAdapter.wrapSQL(sql, start, size); return proxyDao.queryAsIntValue(sqlQ); } }
apache-2.0
tomtrije/huozhu
server/huozhu/java/src/main/java/site/huozhu/home/controller/form/PagenationForm.java
483
package site.huozhu.home.controller.form; /** * ${DESCRIPTION} * * @author chuanxue.mcx * @date 2017/09/06 */ public class PagenationForm { private int page = 1; private int pageSize = 20; public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } }
apache-2.0
JUG-Ostfalen/JUG-Ostfalen.github.io
_posts/2013/2013-05-04-amazon-fur-code.html
3107
--- layout: post title: Amazon für Code... date: 2013-05-04 23:02:48.000000000 +02:00 categories: article tags: - Veranstaltungen - code recommenders - eclipse status: publish type: post published: true meta: _edit_last: '3' author: uwe --- <p>Der Satz blieb mir als erstes im Gedächtnis. Wenn wir etwas aus diesem Abend mitnehmen sollten dann die Botschaft, dass Code Recommenders die Amazon-Variante für Code-Schreiber ist. Mit letzterem verdienten die meisten der Anwesenden ihre Brötchen, also ein interessanter Einstieg.</p> <p><a href="{{site.baseurl}}/assets/wp/2013/05/coderec1.jpg"><img class="size-thumbnail wp-image-1129" alt="Marcel Bruch im Haus der Wissenschaft" src="{{site.baseurl}}/assets/wp/coderec1-150x150.jpg" width="150" height="150" /></a> Marcel Bruch im Haus der Wissenschaft</p> <p>Das Problem: Womit verbringen wir beim Programmieren die Zeit?  Es sind eine Vielzahl von Dingen, von E-Mails über  das Lesen von Dokumentation, das Suchen nach APIs die Analyse von Code usw.  In jedem größeren Projekt 'frisst' die Einarbeitung neuer Mitarbeiter einen nicht unerheblichen Teil des Budgets und wenn man Pech hat, verlässt der Neue gleich wieder das Team.  Wie kann man diese Zeiten verkürzen, die Arbeit auf das Wesentliche konzentrieren?</p> <p>Hier kommt Code Recommenders ins Spiel. Eigentlich nur ein paar Plugins, die jedoch ihre Hausaufgaben gemacht haben.  Die Analyse existierender Code-Repos (u.a. Eclipse Kepler) liefert Statistiken zur Verwendung der API.  Mit diesen Daten versehen, kann zum einen die Auswahl der angezeigten Methoden und die Wahrscheinlichkeit, eine falsche Funktion einzusetzen, drastisch reduziert werden.</p> <p><a href="{{site.baseurl}}/assets/wp/2013/05/coderec2.jpg"><img class="size-thumbnail wp-image-1128" alt="...auf einen Blick" src="{{site.baseurl}}/assets/wp/coderec2-150x150.jpg" width="150" height="150" /></a> ...auf einen Blick</p> <p>Aus meiner Sicht stößt das die Tür in eine völlig neue Dimension der Wizards auf.  Spannend auch die Rückkopplung auf die API-Entwickler, die, mit diesen Analysen ausgestattet,  Optimierungen an ihren APIs vornehmen  und damit die Nutzung weiter erleichtern können.  Pattern-Analyse drängt sich einem ebenfalls auf, Automatisierung des Entwicklungsprozess.  Marcel Bruch zeigte abschließen, an welchen Themen derzeit geforscht wird  und ich kann nur hoffen, dass wir die Resultate, u.a. auch des Google Summer of Code, bald in den IDEs wiederfinden werden. Eine weitere gute Botschaft, auch Netbeans und Intellij werden mittelfristig über diese Helferlein verfügen.  Ich kann mir gut vorstellen, dass wir in Zukunft noch einmal zu diesem Thema zusammenkommen werden.</p> <p><span style="text-decoration: underline;">Links</span>:</p> <ul> <li><a href="https://docs.google.com/file/d/0B9Gf8BD0WA1SUlYzT05pdmpZLTg/edit" target="_blank">Präsentation</a></li> <li><a href="http://code-recommenders.blogspot.de/" target="_blank"><span style="line-height: 13px;">Blog Seite des Code Recommenders Projekts</span></a></li> </ul> <pre>(Anmeldungen: 46 / Teilnehmer 23)</pre>
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Verbesina santanderensis/README.md
182
# Verbesina santanderensis S.Díaz SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
revapi/revapi
revapi-java/src/main/java/org/revapi/java/checks/annotations/Removed.java
1860
/* * Copyright 2014-2021 Lukas Krejci * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.revapi.java.checks.annotations; import java.util.Collections; import java.util.EnumSet; import java.util.List; import org.revapi.Difference; import org.revapi.java.spi.CheckBase; import org.revapi.java.spi.Code; import org.revapi.java.spi.JavaAnnotationElement; import org.revapi.java.spi.Util; /** * @author Lukas Krejci * * @since 0.1 */ public final class Removed extends CheckBase { @Override protected List<Difference> doVisitAnnotation(JavaAnnotationElement oldAnnotation, JavaAnnotationElement newAnnotation) { if (oldAnnotation != null && newAnnotation == null && isAccessible(oldAnnotation.getParent())) { return Collections.singletonList(createDifference(Code.ANNOTATION_REMOVED, Code.attachmentsFor(oldAnnotation.getParent(), null, "annotationType", Util.toHumanReadableString(oldAnnotation.getAnnotation().getAnnotationType()), "annotation", Util.toHumanReadableString(oldAnnotation.getAnnotation())))); } return null; } @Override public EnumSet<Type> getInterest() { return EnumSet.of(Type.ANNOTATION); } }
apache-2.0
aws/aws-sdk-cpp
aws-cpp-sdk-apprunner/include/aws/apprunner/model/VpcConnector.h
17964
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/apprunner/AppRunner_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/apprunner/model/VpcConnectorStatus.h> #include <aws/core/utils/DateTime.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace AppRunner { namespace Model { /** * <p>Describes an App Runner VPC connector resource. A VPC connector describes the * Amazon Virtual Private Cloud (Amazon VPC) that an App Runner service is * associated with, and the subnets and security group that are used.</p> * <p>Multiple revisions of a connector might have the same <code>Name</code> and * different <code>Revision</code> values.</p> <p>At this time, App Runner * supports only one revision per name.</p> <p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/apprunner-2020-05-15/VpcConnector">AWS * API Reference</a></p> */ class AWS_APPRUNNER_API VpcConnector { public: VpcConnector(); VpcConnector(Aws::Utils::Json::JsonView jsonValue); VpcConnector& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The customer-provided VPC connector name.</p> */ inline const Aws::String& GetVpcConnectorName() const{ return m_vpcConnectorName; } /** * <p>The customer-provided VPC connector name.</p> */ inline bool VpcConnectorNameHasBeenSet() const { return m_vpcConnectorNameHasBeenSet; } /** * <p>The customer-provided VPC connector name.</p> */ inline void SetVpcConnectorName(const Aws::String& value) { m_vpcConnectorNameHasBeenSet = true; m_vpcConnectorName = value; } /** * <p>The customer-provided VPC connector name.</p> */ inline void SetVpcConnectorName(Aws::String&& value) { m_vpcConnectorNameHasBeenSet = true; m_vpcConnectorName = std::move(value); } /** * <p>The customer-provided VPC connector name.</p> */ inline void SetVpcConnectorName(const char* value) { m_vpcConnectorNameHasBeenSet = true; m_vpcConnectorName.assign(value); } /** * <p>The customer-provided VPC connector name.</p> */ inline VpcConnector& WithVpcConnectorName(const Aws::String& value) { SetVpcConnectorName(value); return *this;} /** * <p>The customer-provided VPC connector name.</p> */ inline VpcConnector& WithVpcConnectorName(Aws::String&& value) { SetVpcConnectorName(std::move(value)); return *this;} /** * <p>The customer-provided VPC connector name.</p> */ inline VpcConnector& WithVpcConnectorName(const char* value) { SetVpcConnectorName(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of this VPC connector.</p> */ inline const Aws::String& GetVpcConnectorArn() const{ return m_vpcConnectorArn; } /** * <p>The Amazon Resource Name (ARN) of this VPC connector.</p> */ inline bool VpcConnectorArnHasBeenSet() const { return m_vpcConnectorArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of this VPC connector.</p> */ inline void SetVpcConnectorArn(const Aws::String& value) { m_vpcConnectorArnHasBeenSet = true; m_vpcConnectorArn = value; } /** * <p>The Amazon Resource Name (ARN) of this VPC connector.</p> */ inline void SetVpcConnectorArn(Aws::String&& value) { m_vpcConnectorArnHasBeenSet = true; m_vpcConnectorArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of this VPC connector.</p> */ inline void SetVpcConnectorArn(const char* value) { m_vpcConnectorArnHasBeenSet = true; m_vpcConnectorArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of this VPC connector.</p> */ inline VpcConnector& WithVpcConnectorArn(const Aws::String& value) { SetVpcConnectorArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of this VPC connector.</p> */ inline VpcConnector& WithVpcConnectorArn(Aws::String&& value) { SetVpcConnectorArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of this VPC connector.</p> */ inline VpcConnector& WithVpcConnectorArn(const char* value) { SetVpcConnectorArn(value); return *this;} /** * <p>The revision of this VPC connector. It's unique among all the active * connectors (<code>"Status": "ACTIVE"</code>) that share the same * <code>Name</code>.</p> <p>At this time, App Runner supports only one * revision per name.</p> */ inline int GetVpcConnectorRevision() const{ return m_vpcConnectorRevision; } /** * <p>The revision of this VPC connector. It's unique among all the active * connectors (<code>"Status": "ACTIVE"</code>) that share the same * <code>Name</code>.</p> <p>At this time, App Runner supports only one * revision per name.</p> */ inline bool VpcConnectorRevisionHasBeenSet() const { return m_vpcConnectorRevisionHasBeenSet; } /** * <p>The revision of this VPC connector. It's unique among all the active * connectors (<code>"Status": "ACTIVE"</code>) that share the same * <code>Name</code>.</p> <p>At this time, App Runner supports only one * revision per name.</p> */ inline void SetVpcConnectorRevision(int value) { m_vpcConnectorRevisionHasBeenSet = true; m_vpcConnectorRevision = value; } /** * <p>The revision of this VPC connector. It's unique among all the active * connectors (<code>"Status": "ACTIVE"</code>) that share the same * <code>Name</code>.</p> <p>At this time, App Runner supports only one * revision per name.</p> */ inline VpcConnector& WithVpcConnectorRevision(int value) { SetVpcConnectorRevision(value); return *this;} /** * <p>A list of IDs of subnets that App Runner uses for your service. All IDs are * of subnets of a single Amazon VPC.</p> */ inline const Aws::Vector<Aws::String>& GetSubnets() const{ return m_subnets; } /** * <p>A list of IDs of subnets that App Runner uses for your service. All IDs are * of subnets of a single Amazon VPC.</p> */ inline bool SubnetsHasBeenSet() const { return m_subnetsHasBeenSet; } /** * <p>A list of IDs of subnets that App Runner uses for your service. All IDs are * of subnets of a single Amazon VPC.</p> */ inline void SetSubnets(const Aws::Vector<Aws::String>& value) { m_subnetsHasBeenSet = true; m_subnets = value; } /** * <p>A list of IDs of subnets that App Runner uses for your service. All IDs are * of subnets of a single Amazon VPC.</p> */ inline void SetSubnets(Aws::Vector<Aws::String>&& value) { m_subnetsHasBeenSet = true; m_subnets = std::move(value); } /** * <p>A list of IDs of subnets that App Runner uses for your service. All IDs are * of subnets of a single Amazon VPC.</p> */ inline VpcConnector& WithSubnets(const Aws::Vector<Aws::String>& value) { SetSubnets(value); return *this;} /** * <p>A list of IDs of subnets that App Runner uses for your service. All IDs are * of subnets of a single Amazon VPC.</p> */ inline VpcConnector& WithSubnets(Aws::Vector<Aws::String>&& value) { SetSubnets(std::move(value)); return *this;} /** * <p>A list of IDs of subnets that App Runner uses for your service. All IDs are * of subnets of a single Amazon VPC.</p> */ inline VpcConnector& AddSubnets(const Aws::String& value) { m_subnetsHasBeenSet = true; m_subnets.push_back(value); return *this; } /** * <p>A list of IDs of subnets that App Runner uses for your service. All IDs are * of subnets of a single Amazon VPC.</p> */ inline VpcConnector& AddSubnets(Aws::String&& value) { m_subnetsHasBeenSet = true; m_subnets.push_back(std::move(value)); return *this; } /** * <p>A list of IDs of subnets that App Runner uses for your service. All IDs are * of subnets of a single Amazon VPC.</p> */ inline VpcConnector& AddSubnets(const char* value) { m_subnetsHasBeenSet = true; m_subnets.push_back(value); return *this; } /** * <p>A list of IDs of security groups that App Runner uses for access to Amazon * Web Services resources under the specified subnets. If not specified, App Runner * uses the default security group of the Amazon VPC. The default security group * allows all outbound traffic.</p> */ inline const Aws::Vector<Aws::String>& GetSecurityGroups() const{ return m_securityGroups; } /** * <p>A list of IDs of security groups that App Runner uses for access to Amazon * Web Services resources under the specified subnets. If not specified, App Runner * uses the default security group of the Amazon VPC. The default security group * allows all outbound traffic.</p> */ inline bool SecurityGroupsHasBeenSet() const { return m_securityGroupsHasBeenSet; } /** * <p>A list of IDs of security groups that App Runner uses for access to Amazon * Web Services resources under the specified subnets. If not specified, App Runner * uses the default security group of the Amazon VPC. The default security group * allows all outbound traffic.</p> */ inline void SetSecurityGroups(const Aws::Vector<Aws::String>& value) { m_securityGroupsHasBeenSet = true; m_securityGroups = value; } /** * <p>A list of IDs of security groups that App Runner uses for access to Amazon * Web Services resources under the specified subnets. If not specified, App Runner * uses the default security group of the Amazon VPC. The default security group * allows all outbound traffic.</p> */ inline void SetSecurityGroups(Aws::Vector<Aws::String>&& value) { m_securityGroupsHasBeenSet = true; m_securityGroups = std::move(value); } /** * <p>A list of IDs of security groups that App Runner uses for access to Amazon * Web Services resources under the specified subnets. If not specified, App Runner * uses the default security group of the Amazon VPC. The default security group * allows all outbound traffic.</p> */ inline VpcConnector& WithSecurityGroups(const Aws::Vector<Aws::String>& value) { SetSecurityGroups(value); return *this;} /** * <p>A list of IDs of security groups that App Runner uses for access to Amazon * Web Services resources under the specified subnets. If not specified, App Runner * uses the default security group of the Amazon VPC. The default security group * allows all outbound traffic.</p> */ inline VpcConnector& WithSecurityGroups(Aws::Vector<Aws::String>&& value) { SetSecurityGroups(std::move(value)); return *this;} /** * <p>A list of IDs of security groups that App Runner uses for access to Amazon * Web Services resources under the specified subnets. If not specified, App Runner * uses the default security group of the Amazon VPC. The default security group * allows all outbound traffic.</p> */ inline VpcConnector& AddSecurityGroups(const Aws::String& value) { m_securityGroupsHasBeenSet = true; m_securityGroups.push_back(value); return *this; } /** * <p>A list of IDs of security groups that App Runner uses for access to Amazon * Web Services resources under the specified subnets. If not specified, App Runner * uses the default security group of the Amazon VPC. The default security group * allows all outbound traffic.</p> */ inline VpcConnector& AddSecurityGroups(Aws::String&& value) { m_securityGroupsHasBeenSet = true; m_securityGroups.push_back(std::move(value)); return *this; } /** * <p>A list of IDs of security groups that App Runner uses for access to Amazon * Web Services resources under the specified subnets. If not specified, App Runner * uses the default security group of the Amazon VPC. The default security group * allows all outbound traffic.</p> */ inline VpcConnector& AddSecurityGroups(const char* value) { m_securityGroupsHasBeenSet = true; m_securityGroups.push_back(value); return *this; } /** * <p>The current state of the VPC connector. If the status of a connector revision * is <code>INACTIVE</code>, it was deleted and can't be used. Inactive connector * revisions are permanently removed some time after they are deleted.</p> */ inline const VpcConnectorStatus& GetStatus() const{ return m_status; } /** * <p>The current state of the VPC connector. If the status of a connector revision * is <code>INACTIVE</code>, it was deleted and can't be used. Inactive connector * revisions are permanently removed some time after they are deleted.</p> */ inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; } /** * <p>The current state of the VPC connector. If the status of a connector revision * is <code>INACTIVE</code>, it was deleted and can't be used. Inactive connector * revisions are permanently removed some time after they are deleted.</p> */ inline void SetStatus(const VpcConnectorStatus& value) { m_statusHasBeenSet = true; m_status = value; } /** * <p>The current state of the VPC connector. If the status of a connector revision * is <code>INACTIVE</code>, it was deleted and can't be used. Inactive connector * revisions are permanently removed some time after they are deleted.</p> */ inline void SetStatus(VpcConnectorStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); } /** * <p>The current state of the VPC connector. If the status of a connector revision * is <code>INACTIVE</code>, it was deleted and can't be used. Inactive connector * revisions are permanently removed some time after they are deleted.</p> */ inline VpcConnector& WithStatus(const VpcConnectorStatus& value) { SetStatus(value); return *this;} /** * <p>The current state of the VPC connector. If the status of a connector revision * is <code>INACTIVE</code>, it was deleted and can't be used. Inactive connector * revisions are permanently removed some time after they are deleted.</p> */ inline VpcConnector& WithStatus(VpcConnectorStatus&& value) { SetStatus(std::move(value)); return *this;} /** * <p>The time when the VPC connector was created. It's in Unix time stamp * format.</p> */ inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; } /** * <p>The time when the VPC connector was created. It's in Unix time stamp * format.</p> */ inline bool CreatedAtHasBeenSet() const { return m_createdAtHasBeenSet; } /** * <p>The time when the VPC connector was created. It's in Unix time stamp * format.</p> */ inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; } /** * <p>The time when the VPC connector was created. It's in Unix time stamp * format.</p> */ inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); } /** * <p>The time when the VPC connector was created. It's in Unix time stamp * format.</p> */ inline VpcConnector& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;} /** * <p>The time when the VPC connector was created. It's in Unix time stamp * format.</p> */ inline VpcConnector& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;} /** * <p>The time when the VPC connector was deleted. It's in Unix time stamp * format.</p> */ inline const Aws::Utils::DateTime& GetDeletedAt() const{ return m_deletedAt; } /** * <p>The time when the VPC connector was deleted. It's in Unix time stamp * format.</p> */ inline bool DeletedAtHasBeenSet() const { return m_deletedAtHasBeenSet; } /** * <p>The time when the VPC connector was deleted. It's in Unix time stamp * format.</p> */ inline void SetDeletedAt(const Aws::Utils::DateTime& value) { m_deletedAtHasBeenSet = true; m_deletedAt = value; } /** * <p>The time when the VPC connector was deleted. It's in Unix time stamp * format.</p> */ inline void SetDeletedAt(Aws::Utils::DateTime&& value) { m_deletedAtHasBeenSet = true; m_deletedAt = std::move(value); } /** * <p>The time when the VPC connector was deleted. It's in Unix time stamp * format.</p> */ inline VpcConnector& WithDeletedAt(const Aws::Utils::DateTime& value) { SetDeletedAt(value); return *this;} /** * <p>The time when the VPC connector was deleted. It's in Unix time stamp * format.</p> */ inline VpcConnector& WithDeletedAt(Aws::Utils::DateTime&& value) { SetDeletedAt(std::move(value)); return *this;} private: Aws::String m_vpcConnectorName; bool m_vpcConnectorNameHasBeenSet; Aws::String m_vpcConnectorArn; bool m_vpcConnectorArnHasBeenSet; int m_vpcConnectorRevision; bool m_vpcConnectorRevisionHasBeenSet; Aws::Vector<Aws::String> m_subnets; bool m_subnetsHasBeenSet; Aws::Vector<Aws::String> m_securityGroups; bool m_securityGroupsHasBeenSet; VpcConnectorStatus m_status; bool m_statusHasBeenSet; Aws::Utils::DateTime m_createdAt; bool m_createdAtHasBeenSet; Aws::Utils::DateTime m_deletedAt; bool m_deletedAtHasBeenSet; }; } // namespace Model } // namespace AppRunner } // namespace Aws
apache-2.0
thatcoderguy/Secure-Password-Repository
Secure Password Repository/ViewModels/CategoryViewModels.cs
1022
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Secure_Password_Repository.ViewModels { public class CategoryEdit { public Int32? CategoryId { get; set; } [Required] public string CategoryName { get; set; } } public class CategoryAdd : CategoryEdit { public Int32? Category_ParentID { get; set; } } public class CategoryDelete { public Int32? CategoryId { get; set; } } public class CategoryItem : CategoryEdit { [Required] public Int32 Category_ParentID { get; set; } public virtual ICollection<CategoryItem> SubCategories { get; set; } public virtual ICollection<PasswordItem> Passwords { get; set; } } public class CategoryDisplayItem { public CategoryItem categoryListItem { get; set; } public CategoryAdd categoryAddItem { get; set; } public PasswordAdd passwordAddItem { get; set; } } }
apache-2.0