repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
jwuttke/daquiri-qpx
source/core/util/color_bash.h
#pragma once #include <string> #include <sstream> enum BashColor { NONE = 0, BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE }; enum BashSpecial { RESET = 0, BRIGHT, DIM, UNDER, BLINK, REVERSE, HIDDEN }; inline std::string col(BashColor foreground = NONE, BashColor background = NONE, BashSpecial special = RESET) { std::stringstream s; #ifdef NOCOLORBASH return s.str(); #endif s << "\033["; if (!foreground && !background && !special) s << "0"; // reset colors if no params if (special) { s << special << "m"; if (foreground || background) s << "\033["; } if (foreground) { s << 29 + foreground; if (background) s << ";"; } if (background) s << 39 + background; s << "m"; return s.str(); }
JouniVatanen/NLP-and-Deep-Learning
src/unsupervised_class3/vae_tf.py
<filename>src/unsupervised_class3/vae_tf.py # https://deeplearningcourses.com/c/deep-learning-gans-and-variational-autoencoders # https://www.udemy.com/deep-learning-gans-and-variational-autoencoders from __future__ import print_function, division from builtins import range, input # Note: you may need to update your version of future # sudo pip install -U future import util import numpy as np import tensorflow as tf import matplotlib.pyplot as plt st = None try: st = tf.contrib.bayesflow.stochastic_tensor except: # doesn't exist in later versions of TF # we will use the reparameterization trick instead # watch the later lecture on the reparameterization trick # to learn about it. pass Normal = tf.contrib.distributions.Normal Bernoulli = tf.contrib.distributions.Bernoulli class DenseLayer(object): def __init__(self, M1, M2, f=tf.nn.relu): # self.M1 = M1 # self.M2 = M2 self.W = tf.Variable(tf.random_normal(shape=(M1, M2)) * 2 / np.sqrt(M1)) self.b = tf.Variable(np.zeros(M2).astype(np.float32)) self.f = f def forward(self, X): return self.f(tf.matmul(X, self.W) + self.b) class VariationalAutoencoder: def __init__(self, D, hidden_layer_sizes): # hidden_layer_sizes specifies the size of every layer # in the encoder # up to the final hidden layer Z # the decoder will have the reverse shape # represents a batch of training data self.X = tf.placeholder(tf.float32, shape=(None, D)) # encoder self.encoder_layers = [] M_in = D for M_out in hidden_layer_sizes[:-1]: h = DenseLayer(M_in, M_out) self.encoder_layers.append(h) M_in = M_out # for convenience, we'll refer to the final encoder size as M # also the input to the decoder size M = hidden_layer_sizes[-1] # the encoder's final layer output is unbounded # so there is no activation function # we also need 2 times as many units as specified by M_out # since there needs to be M_out means + M_out variances h = DenseLayer(M_in, 2 * M, f=lambda x: x) self.encoder_layers.append(h) # get the mean and variance / std dev of Z. # note that the variance must be > 0 # we can get a sigma (standard dev) > 0 from an unbounded variable by # passing it through the softplus function. # add a small amount for smoothing. current_layer_value = self.X for layer in self.encoder_layers: current_layer_value = layer.forward(current_layer_value) self.means = current_layer_value[:, :M] self.stddev = tf.nn.softplus(current_layer_value[:, M:]) + 1e-6 # get a sample of Z # we need to use a stochastic tensor # in order for the errors to be backpropagated past this point if st is None: # doesn't exist in later versions of Tensorflow # we'll use the same trick we use in Theano standard_normal = Normal( loc=np.zeros(M, dtype=np.float32), scale=np.ones(M, dtype=np.float32) ) e = standard_normal.sample(tf.shape(self.means)[0]) self.Z = e * self.stddev + self.means # note: this also works because Tensorflow # now does the "magic" for you # n = Normal( # loc=self.means, # scale=self.stddev, # ) # self.Z = n.sample() else: with st.value_type(st.SampleValue()): self.Z = st.StochasticTensor(Normal(loc=self.means, scale=self.stddev)) # to get back Q(Z), the distribution of Z # we will later use self.Z.distribution # decoder self.decoder_layers = [] M_in = M for M_out in reversed(hidden_layer_sizes[:-1]): h = DenseLayer(M_in, M_out) self.decoder_layers.append(h) M_in = M_out # the decoder's final layer should technically go through a sigmoid # so that the final output is a binary probability (e.g. Bernoulli) # but Bernoulli accepts logits (pre-sigmoid) so we will take those # so no activation function is needed at the final layer h = DenseLayer(M_in, D, f=lambda x: x) self.decoder_layers.append(h) # get the logits current_layer_value = self.Z for layer in self.decoder_layers: current_layer_value = layer.forward(current_layer_value) logits = current_layer_value posterior_predictive_logits = logits # save for later # get the output self.X_hat_distribution = Bernoulli(logits=logits) # take samples from X_hat # we will call this the posterior predictive sample self.posterior_predictive = self.X_hat_distribution.sample() self.posterior_predictive_probs = tf.nn.sigmoid(logits) # take sample from a Z ~ N(0, 1) # and put it through the decoder # we will call this the prior predictive sample standard_normal = Normal( loc=np.zeros(M, dtype=np.float32), scale=np.ones(M, dtype=np.float32) ) Z_std = standard_normal.sample(1) current_layer_value = Z_std for layer in self.decoder_layers: current_layer_value = layer.forward(current_layer_value) logits = current_layer_value prior_predictive_dist = Bernoulli(logits=logits) self.prior_predictive = prior_predictive_dist.sample() self.prior_predictive_probs = tf.nn.sigmoid(logits) # prior predictive from input # only used for generating visualization self.Z_input = tf.placeholder(tf.float32, shape=(None, M)) current_layer_value = self.Z_input for layer in self.decoder_layers: current_layer_value = layer.forward(current_layer_value) logits = current_layer_value self.prior_predictive_from_input_probs = tf.nn.sigmoid(logits) # now build the cost if st is None: kl = -tf.log(self.stddev) + 0.5*(self.stddev**2 + self.means**2) - 0.5 kl = tf.reduce_sum(kl, axis=1) else: kl = tf.reduce_sum( tf.contrib.distributions.kl_divergence( self.Z.distribution, standard_normal ), 1 ) expected_log_likelihood = tf.reduce_sum( self.X_hat_distribution.log_prob(self.X), 1 ) # equivalent # expected_log_likelihood = -tf.nn.sigmoid_cross_entropy_with_logits( # labels=self.X, # logits=posterior_predictive_logits # ) # expected_log_likelihood = tf.reduce_sum(expected_log_likelihood, 1) self.elbo = tf.reduce_sum(expected_log_likelihood - kl) self.train_op = tf.train.RMSPropOptimizer(learning_rate=0.001).minimize(-self.elbo) # set up session and variables for later self.init_op = tf.global_variables_initializer() self.sess = tf.InteractiveSession() self.sess.run(self.init_op) def fit(self, X, epochs=30, batch_sz=64): costs = [] n_batches = len(X) // batch_sz print("n_batches:", n_batches) for i in range(epochs): print("epoch:", i) np.random.shuffle(X) for j in range(n_batches): batch = X[j*batch_sz:(j+1)*batch_sz] _, c, = self.sess.run((self.train_op, self.elbo), feed_dict={self.X: batch}) c /= batch_sz # just debugging costs.append(c) if j % 100 == 0: print("iter: %d, cost: %.3f" % (j, c)) plt.plot(costs) plt.show() def transform(self, X): return self.sess.run( self.means, feed_dict={self.X: X} ) def prior_predictive_with_input(self, Z): return self.sess.run( self.prior_predictive_from_input_probs, feed_dict={self.Z_input: Z} ) def posterior_predictive_sample(self, X): # returns a sample from p(x_new | X) return self.sess.run(self.posterior_predictive, feed_dict={self.X: X}) def prior_predictive_sample_with_probs(self): # returns a sample from p(x_new | z), z ~ N(0, 1) return self.sess.run((self.prior_predictive, self.prior_predictive_probs)) def main(): X, Y = util.get_mnist() # convert X to binary variable X = (X > 0.5).astype(np.float32) vae = VariationalAutoencoder(784, [200, 100]) vae.fit(X) # plot reconstruction done = False while not done: i = np.random.choice(len(X)) x = X[i] im = vae.posterior_predictive_sample([x]).reshape(28, 28) plt.subplot(1,2,1) plt.imshow(x.reshape(28, 28), cmap='gray') plt.title("Original") plt.subplot(1,2,2) plt.imshow(im, cmap='gray') plt.title("Sampled") plt.show() ans = input("Generate another?") if ans and ans[0] in ('n' or 'N'): done = True # plot output from random samples in latent space done = False while not done: im, probs = vae.prior_predictive_sample_with_probs() im = im.reshape(28, 28) probs = probs.reshape(28, 28) plt.subplot(1,2,1) plt.imshow(im, cmap='gray') plt.title("Prior predictive sample") plt.subplot(1,2,2) plt.imshow(probs, cmap='gray') plt.title("Prior predictive probs") plt.show() ans = input("Generate another?") if ans and ans[0] in ('n' or 'N'): done = True if __name__ == '__main__': main()
caufieldjh/ensmallen_graph
bindings/python/ensmallen_graph/datasets/__init__.py
<gh_stars>0 """Module with datasets."""
valitydev/fraudbusters-mg-connector
src/main/java/dev/vality/fraudbusters/mg/connector/domain/MgEventWrapper.java
package dev.vality.fraudbusters.mg.connector.domain; import dev.vality.damsel.payment_processing.InvoiceChange; import dev.vality.machinegun.eventsink.MachineEvent; import lombok.Builder; import lombok.Data; @Data @Builder public class MgEventWrapper { private InvoiceChange change; private MachineEvent event; }
Abdelsalam-Abbas/rook_fork
pkg/ceph/mds/filesystem.go
/* Copyright 2016 The Rook Authors. 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. 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 mds import ( "fmt" "path" "strconv" "strings" etcd "github.com/coreos/etcd/client" ctx "golang.org/x/net/context" "github.com/rook/rook/pkg/ceph/client" "github.com/rook/rook/pkg/ceph/mon" "github.com/rook/rook/pkg/clusterd" "github.com/rook/rook/pkg/util" ) const ( defaultFileSystemName = "rookfs" defaultPoolName = "fspool" poolKeyName = "pool" idKeyName = "id" dataPoolSuffix = "-data" metadataPoolSuffix = "-metadata" mdsKeyName = "mds" FileSystemKey = "fs" ) // A castle file system (an instance of CephFS) type FileSystem struct { context *clusterd.Context ID string `json:"id"` Pool string `json:"pool"` } type mdsInfo struct { nodeID string mdsID string fileSystem string } // Create a new file service struct func NewFS(context *clusterd.Context, id, pool string) *FileSystem { if pool == "" { pool = id } return &FileSystem{ ID: id, Pool: pool, context: context, } } func (f *FileSystem) CreateFilesystem(cluster *mon.ClusterInfo) error { logger.Infof("Creating file system %s", f.ID) _, err := client.GetFilesystem(f.context, cluster.Name, f.ID) if err == nil { logger.Infof("file system %s already exists", f.ID) return nil } dataPool := f.Pool + dataPoolSuffix metadataPool := f.Pool + metadataPoolSuffix // Create the metadata and data pools pool := client.CephStoragePoolDetails{Name: dataPool} _, err = client.CreatePool(f.context, cluster.Name, pool) if err != nil { return fmt.Errorf("failed to create data pool '%s': %+v", dataPool, err) } pool = client.CephStoragePoolDetails{Name: metadataPool} _, err = client.CreatePool(f.context, cluster.Name, pool) if err != nil { return fmt.Errorf("failed to create metadata pool '%s': %+v", metadataPool, err) } // create the file system if err := client.CreateFilesystem(f.context, cluster.Name, f.ID, metadataPool, dataPool); err != nil { return err } logger.Infof("created file system %s on data pool %s and metadata pool %s", f.ID, dataPool, metadataPool) return nil } // Create the file system in ceph func (f *FileSystem) enable(cluster *mon.ClusterInfo) error { // start MDS instances in the cluster mdsCount := 1 err := f.startMDSUnitInstances(mdsCount) if err != nil { return fmt.Errorf("Failed to start MDS. err=%v", err) } err = f.markApplied() if err != nil { return fmt.Errorf("failed to mark file system applied. %+v", err) } logger.Infof("Created file system %s", f.ID) return nil } // Remove the file system in ceph func (f *FileSystem) disable(cluster *mon.ClusterInfo) error { logger.Infof("Removing file system %s", f.ID) // mark the cephFS instance as cluster_down before removing if err := client.MarkFilesystemAsDown(f.context, cluster.Name, f.ID); err != nil { return err } // mark each MDS associated with the file system to "failed" fsDetails, err := client.GetFilesystem(f.context, cluster.Name, f.ID) if err != nil { return err } for _, mdsInfo := range fsDetails.MDSMap.Info { if err := client.FailMDS(f.context, cluster.Name, mdsInfo.GID); err != nil { return err } } // Stop MDS if err := f.stopMDSUnitInstances(); err != nil { return fmt.Errorf("failed to stop mds instances. %+v", err) } // Permanently remove the file system if err := client.RemoveFilesystem(f.context, cluster.Name, f.ID); err != nil { return err } err = f.markUnapplied() if err != nil { return fmt.Errorf("failed to mark file system unapplied. %+v", err) } logger.Infof("Removed file system %s", f.ID) return nil } // Add the file system to the desired state. func (f *FileSystem) AddToDesiredState() error { return f.storeSettings(false) } // Remove the file system from the desired state. func (f *FileSystem) DeleteFromDesiredState() error { // remove the file system from desired state _, err := f.context.EtcdClient.Delete(ctx.Background(), getFileKey(f.ID, false), &etcd.DeleteOptions{Dir: true, Recursive: true}) if err != nil && !util.IsEtcdKeyNotFound(err) { return fmt.Errorf("failed to delete file system %s from desired state. %+v", f.ID, err) } // remove the mds from desired state idMap, _, _, err := f.loadMDS(f.ID, false) if err != nil { return fmt.Errorf("failed to load desired MDS for removal. %+v", err) } for _, mds := range idMap { // TODO: remove the mds for this file system from desired state if err := f.removeMDSState(mds, false); err != nil { return fmt.Errorf("failed to remove mds from desired state. %+v", err) } } return err } func (f *FileSystem) removeMDSState(fs *mdsInfo, applied bool) error { key := path.Join(getMDSDesiredNodesKey(applied), fs.nodeID) _, err := f.context.EtcdClient.Delete(ctx.Background(), key, &etcd.DeleteOptions{Dir: true, Recursive: true}) if err != nil { return fmt.Errorf("failed to delete mds %s from desired state. %+v", fs.mdsID, err) } return nil } // Persist the file system config to the applied key func (f *FileSystem) markApplied() error { return f.storeSettings(true) } // Remove the file system from the applied key func (f *FileSystem) markUnapplied() error { _, err := f.context.EtcdClient.Delete(ctx.Background(), getFileKey(f.ID, true), &etcd.DeleteOptions{Dir: true, Recursive: true}) return err } func getFileRootKey(applied bool) string { return path.Join(mon.CephKey, FileSystemKey, getAppliedStr(applied)) } func getFileKey(name string, applied bool) string { return path.Join(mon.CephKey, FileSystemKey, getAppliedStr(applied), name) } func getAppliedStr(applied bool) string { if applied { return clusterd.AppliedKey } return clusterd.DesiredKey } func (f *FileSystem) storeSettings(applied bool) error { key := path.Join(getFileKey(f.ID, applied), poolKeyName) _, err := f.context.EtcdClient.Set(ctx.Background(), key, f.Pool, nil) return err } func (f *FileSystem) startMDSUnitInstances(count int) error { desiredMDS, err := f.getDesiredMDSIDs(count) if err != nil { return fmt.Errorf("failed to get desired mds instances. %+v", err) } var nodeIDs []string for _, mds := range desiredMDS { nodeIDs = append(nodeIDs, mds.nodeID) } // trigger the mds to start on each node logger.Infof("Triggering mds on nodes: %+v", nodeIDs) err = clusterd.TriggerAgentsAndWaitForCompletion(f.context.EtcdClient, nodeIDs, mdsAgentName, len(desiredMDS)) if err != nil { return fmt.Errorf("failed to deploy mds agents. %+v", err) } // set the mds as applied for _, mds := range desiredMDS { if err := f.storeMDSState(mds, true); err != nil { return fmt.Errorf("failed to set mds agent as applied. %+v", err) } } return nil } func (f *FileSystem) stopMDSUnitInstances() error { appliedMDS, _, _, err := f.loadMDS(f.ID, true) if err != nil { return fmt.Errorf("failed to get desired mds instances. %+v", err) } var nodeIDs []string for _, mds := range appliedMDS { nodeIDs = append(nodeIDs, mds.nodeID) } // trigger the monitors to start on each node logger.Infof("Triggering removal of mds on nodes: %+v", nodeIDs) err = clusterd.TriggerAgentsAndWaitForCompletion(f.context.EtcdClient, nodeIDs, mdsAgentName, len(nodeIDs)) if err != nil { return fmt.Errorf("failed to deploy mds agents. %+v", err) } // remove the mds from applied for _, mds := range appliedMDS { if err := f.removeMDSState(mds, true); err != nil { return fmt.Errorf("failed to set mds agent as applied. %+v", err) } } return nil } func (f *FileSystem) getDesiredMDSIDs(count int) (map[string]*mdsInfo, error) { idMap, nodes, nextID, err := f.loadMDS("", false) if err != nil { return nil, fmt.Errorf("failed to load desired MDS IDs. %+v", err) } // Assign MDS to nodes if not already assigned for nodeID := range f.context.Inventory.Nodes { // we have enough mds instances if len(idMap) >= count { break } // cannot use the same node for more than one mds if nodes.Contains(nodeID) { continue } // assign this node an MDS ID mds := &mdsInfo{ nodeID: nodeID, mdsID: strconv.Itoa(nextID), fileSystem: f.ID, } idMap[mds.mdsID] = mds nextID++ if err := f.storeMDSState(mds, false); err != nil { return nil, err } } if len(idMap) < count { return nil, fmt.Errorf("not enough nodes for mds services. required=%d, actual=%d", count, len(idMap)) } return idMap, nil } func (f *FileSystem) storeMDSState(info *mdsInfo, applied bool) error { // store the mds in desired state if _, err := f.context.EtcdClient.Set(ctx.Background(), getMDSIDKey(info.nodeID, applied), info.mdsID, nil); err != nil { return fmt.Errorf("failed to set desired mds %s. %+v", info.mdsID, err) } if _, err := f.context.EtcdClient.Set(ctx.Background(), getMDSFileSystemKey(info.nodeID, applied), f.ID, nil); err != nil { return fmt.Errorf("failed to set desired mds file system %s. %+v", f.ID, err) } return nil } // Load where the MDS services are intended to be running, on which nodes and for which file systems func (f *FileSystem) loadMDS(fileSystemFilter string, applied bool) (map[string]*mdsInfo, *util.Set, int, error) { idToNodeMap := make(map[string]*mdsInfo) nextID := 1 nodes := util.NewSet() key := getMDSDesiredNodesKey(applied) result, err := f.context.EtcdClient.Get(ctx.Background(), key, &etcd.GetOptions{Recursive: true}) if err != nil { if util.IsEtcdKeyNotFound(err) { return idToNodeMap, nodes, nextID, nil } return nil, nil, -1, err } // load the desired IDs that have already been generated previously for _, nodeKey := range result.Node.Nodes { info := &mdsInfo{ nodeID: util.GetLeafKeyPath(nodeKey.Key), } mdsID := -1 for _, setting := range nodeKey.Nodes { if strings.HasSuffix(setting.Key, "/id") { var err error info.mdsID = setting.Value mdsID, err = strconv.Atoi(setting.Value) if err != nil { return nil, nil, -1, fmt.Errorf("bad mds id %s. %+v", setting.Value, err) } } else if strings.HasSuffix(setting.Key, "/filesystem") { info.fileSystem = setting.Value } } // if the file system name matches, or a specific file system name was not requested, add it to the result if f.ID == fileSystemFilter || fileSystemFilter == "" { idToNodeMap[info.mdsID] = info nodes.Add(info.nodeID) } if mdsID >= nextID { nextID = mdsID + 1 } } return idToNodeMap, nodes, nextID, nil }
othmaan/codesandbox-clien
src/sandbox/actions/index.js
<gh_stars>0 // @flow // All actions of the editor are defined here. The sandbox can send messages // like `source.files.rename` which the editor will see as an action to rename // a module. This will allow plugins to alter project content in the future import * as notifications from './notifications'; import * as editor from './/editor'; import * as module from './source/module'; import * as dependencies from './source/dependencies'; import sendMessage from '../utils/send-message'; const actions = { notifications, editor, source: { module, dependencies, }, }; export const dispatch = sendMessage; export default actions;
lhzheng880828/VOIPCall
doc/libjitisi/sources/org/jitsi/impl/neomedia/jmfext/media/renderer/video/JAWTRenderer.java
<filename>doc/libjitisi/sources/org/jitsi/impl/neomedia/jmfext/media/renderer/video/JAWTRenderer.java package org.jitsi.impl.neomedia.jmfext.media.renderer.video; import com.lti.utils.UnsignedUtils; import java.lang.reflect.InvocationTargetException; import javax.media.Buffer; import javax.media.Format; import javax.media.ResourceUnavailableException; import javax.media.format.RGBFormat; import javax.media.format.VideoFormat; import javax.media.format.YUVFormat; import javax.media.renderer.VideoRenderer; import org.jitsi.android.util.java.awt.Component; import org.jitsi.android.util.java.awt.Dimension; import org.jitsi.android.util.java.awt.Graphics; import org.jitsi.android.util.java.awt.Rectangle; import org.jitsi.android.util.javax.swing.SwingUtilities; import org.jitsi.impl.neomedia.jmfext.media.renderer.AbstractRenderer; import org.jitsi.util.Logger; import org.jitsi.util.OSUtils; import org.jitsi.util.swing.VideoLayout; public class JAWTRenderer extends AbstractRenderer<VideoFormat> implements VideoRenderer { private static final int DEFAULT_COMPONENT_HEIGHT_OR_WIDTH = 16; private static final String PLUGIN_NAME = "JAWT Renderer"; private static final Format[] SUPPORTED_INPUT_FORMATS; private static final Logger logger = Logger.getLogger(JAWTRenderer.class); private Component component; private long handle = 0; private int height = 0; private final Runnable reflectInputFormatOnComponentInEventDispatchThread = new Runnable() { public void run() { JAWTRenderer.this.reflectInputFormatOnComponentInEventDispatchThread(); } }; private int width = 0; private static native void close(long j, Component component); private static native long open(Component component) throws ResourceUnavailableException; static native boolean paint(long j, Component component, Graphics graphics, int i); static native boolean process(long j, Component component, int[] iArr, int i, int i2, int i3, int i4); private static native String sysctlbyname(String str); static { Format[] formatArr = new Format[1]; RGBFormat yUVFormat = OSUtils.IS_LINUX ? new YUVFormat(null, -1, Format.intArray, -1.0f, 2, -1, -1, -1, -1, -1) : OSUtils.IS_ANDROID ? new RGBFormat(null, -1, Format.intArray, -1.0f, 32, UnsignedUtils.MAX_UBYTE, 65280, 16711680) : new RGBFormat(null, -1, Format.intArray, -1.0f, 32, 16711680, 65280, UnsignedUtils.MAX_UBYTE); formatArr[0] = yUVFormat; SUPPORTED_INPUT_FORMATS = formatArr; System.loadLibrary("jnawtrenderer"); } public synchronized void close() { if (this.handle != 0) { close(this.handle, this.component); this.handle = 0; } } public Rectangle getBounds() { return null; } public synchronized Component getComponent() { if (this.component == null) { StringBuilder componentClassName = new StringBuilder(); componentClassName.append("org.jitsi.impl.neomedia.jmfext.media.renderer.video.JAWTRenderer"); if (OSUtils.IS_ANDROID) { componentClassName.append("Android"); } componentClassName.append("VideoComponent"); Throwable reflectiveOperationException = null; try { this.component = (Component) Class.forName(componentClassName.toString()).getConstructor(new Class[]{JAWTRenderer.class}).newInstance(new Object[]{this}); } catch (ClassNotFoundException cnfe) { reflectiveOperationException = cnfe; } catch (IllegalAccessException iae) { reflectiveOperationException = iae; } catch (InstantiationException ie) { reflectiveOperationException = ie; } catch (InvocationTargetException ite) { reflectiveOperationException = ite; } catch (NoSuchMethodException nsme) { reflectiveOperationException = nsme; } if (reflectiveOperationException != null) { throw new RuntimeException(reflectiveOperationException); } this.component.setSize(16, 16); reflectInputFormatOnComponentInEventDispatchThread(); } return this.component; } public long getHandle() { return this.handle; } public Object getHandleLock() { return this; } public String getName() { return PLUGIN_NAME; } public Format[] getSupportedInputFormats() { return (Format[]) SUPPORTED_INPUT_FORMATS.clone(); } public void open() throws ResourceUnavailableException { boolean addNotify; Component component; synchronized (this) { if (this.handle == 0) { addNotify = (this.component == null || this.component.getParent() == null) ? false : true; component = getComponent(); this.handle = open(component); if (this.handle == 0) { throw new ResourceUnavailableException("Failed to open the native JAWTRenderer."); } } addNotify = false; component = null; } if (addNotify) { SwingUtilities.invokeLater(new Runnable() { public void run() { component.addNotify(); } }); } } public synchronized int process(Buffer buffer) { int i; if (buffer.isDiscard()) { i = 0; } else { int bufferLength = buffer.getLength(); if (bufferLength == 0) { i = 0; } else { Format format = buffer.getFormat(); if (format != null && format != this.inputFormat && !format.equals(this.inputFormat) && setInputFormat(format) == null) { i = 1; } else if (this.handle == 0) { i = 1; } else { Dimension size = null; if (format != null) { size = ((VideoFormat) format).getSize(); } if (size == null) { size = ((VideoFormat) this.inputFormat).getSize(); if (size == null) { i = 1; } } if (size.width >= 4 && size.height >= 4) { Component component = getComponent(); if (process(this.handle, component, (int[]) buffer.getData(), buffer.getOffset(), bufferLength, size.width, size.height)) { component.repaint(); } } i = 0; } } } return i; } private void reflectInputFormatOnComponent() { if (SwingUtilities.isEventDispatchThread()) { reflectInputFormatOnComponentInEventDispatchThread(); } else { SwingUtilities.invokeLater(this.reflectInputFormatOnComponentInEventDispatchThread); } } /* access modifiers changed from: private */ public void reflectInputFormatOnComponentInEventDispatchThread() { if (this.component != null && this.width > 0 && this.height > 0) { Dimension prefSize = this.component.getPreferredSize(); if (prefSize == null || prefSize.width < 1 || prefSize.height < 1 || !VideoLayout.areAspectRatiosEqual(prefSize, this.width, this.height) || prefSize.width < this.width || prefSize.height < this.height) { this.component.setPreferredSize(new Dimension(this.width, this.height)); } if (this.component.isPreferredSizeSet() && this.component.getParent() == null) { Dimension size = this.component.getSize(); prefSize = this.component.getPreferredSize(); if (size.width < 1 || size.height < 1 || !VideoLayout.areAspectRatiosEqual(size, prefSize.width, prefSize.height)) { this.component.setSize(prefSize.width, prefSize.height); } } } } public void setBounds(Rectangle bounds) { } public boolean setComponent(Component component) { return false; } public synchronized Format setInputFormat(Format format) { Format newInputFormat; Format oldInputFormat = this.inputFormat; newInputFormat = super.setInputFormat(format); if (oldInputFormat != this.inputFormat) { if (logger.isDebugEnabled()) { logger.debug(getClass().getName() + " 0x" + Integer.toHexString(hashCode()) + " set to input in " + this.inputFormat); } Dimension size = ((VideoFormat) this.inputFormat).getSize(); if (size == null) { this.height = 0; this.width = 0; } else { this.width = size.width; this.height = size.height; } reflectInputFormatOnComponent(); } return newInputFormat; } public void start() { } public void stop() { } }
tobiaserich/oneglance
client/src/components/DarkFilter.js
import styled from "@emotion/styled"; const DarkFilter = styled.div` height: 100%; width: 100%; position: absolute; border-radius: 10px; background: #0000004d; `; export default DarkFilter;
hmcts/div-orchestration-service
src/main/java/uk/gov/hmcts/reform/divorce/orchestration/tasks/servicejourney/BailiffServiceDueDateSetterTask.java
<filename>src/main/java/uk/gov/hmcts/reform/divorce/orchestration/tasks/servicejourney/BailiffServiceDueDateSetterTask.java package uk.gov.hmcts.reform.divorce.orchestration.tasks.servicejourney; import lombok.extern.slf4j.Slf4j; import uk.gov.hmcts.reform.divorce.orchestration.framework.workflow.task.TaskContext; import uk.gov.hmcts.reform.divorce.orchestration.framework.workflow.task.TaskException; import uk.gov.hmcts.reform.divorce.orchestration.tasks.DueDateSetterTask; import uk.gov.hmcts.reform.divorce.utils.DateUtils; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Map; import static uk.gov.hmcts.reform.divorce.orchestration.service.bulk.print.dataextractor.DatesDataExtractor.getCertificateOfServiceDateUnformatted; import static uk.gov.hmcts.reform.divorce.orchestration.tasks.util.TaskUtils.getCaseId; @Slf4j public abstract class BailiffServiceDueDateSetterTask extends DueDateSetterTask { private final Integer dueDateOffset; protected BailiffServiceDueDateSetterTask(int dueDateOffset) { this.dueDateOffset = dueDateOffset; } @Override public Map<String, Object> execute(TaskContext context, Map<String, Object> caseData) throws TaskException { final String caseId = getCaseId(context); final String fieldName = getFieldName(); final String formattedDateValue = getCertificateOfServiceFormattedDate(caseData); log.info("CaseID: {} setting up date {} for field {}", caseId, formattedDateValue, fieldName); caseData.put(fieldName, formattedDateValue); return caseData; } @Override protected Integer getDueDateOffsetInDays() { return dueDateOffset; } protected String getCertificateOfServiceFormattedDate(Map<String, Object> caseData) { String date = getCertificateOfServiceDateUnformatted(caseData); LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern(DateUtils.Formats.CCD_DATE)); return DateUtils.formatDateFromLocalDate(localDate.plus(getDueDateOffsetInDays(), ChronoUnit.DAYS)); } }
Koronen/stringer
spec/repositories/feed_repository_spec.rb
<reponame>Koronen/stringer<filename>spec/repositories/feed_repository_spec.rb require "spec_helper" require "support/active_record" app_require "repositories/feed_repository" describe FeedRepository do describe ".update_last_fetched" do let(:timestamp) { Time.now } it "saves the last_fetched timestamp" do feed = Feed.new FeedRepository.update_last_fetched(feed, timestamp) expect(feed.last_fetched).to eq timestamp end let(:weird_timestamp) { Time.parse("Mon, 01 Jan 0001 00:00:00 +0100") } it "rejects weird timestamps" do feed = Feed.new(last_fetched: timestamp) FeedRepository.update_last_fetched(feed, weird_timestamp) expect(feed.last_fetched).to eq timestamp end it "doesn't update if timestamp is nil (feed does not report last modified)" do feed = Feed.new(last_fetched: timestamp) FeedRepository.update_last_fetched(feed, nil) expect(feed.last_fetched).to eq timestamp end it "doesn't update if timestamp is older than the current value" do feed = Feed.new(last_fetched: timestamp) one_week_ago = timestamp - 1.week FeedRepository.update_last_fetched(feed, one_week_ago) expect(feed.last_fetched).to eq timestamp end end describe ".update_feed" do it "saves the name and url" do feed = Feed.new FeedRepository.update_feed(feed, "Test Feed", "example.com/feed") expect(feed.name).to eq "Test Feed" expect(feed.url).to eq "example.com/feed" end end describe "fetch" do let(:feed) { Feed.new(id: 1) } it "finds by id" do expect(Feed).to receive(:find).with(feed.id).and_return(feed) FeedRepository.fetch(feed.id) end it "returns found feed" do allow(Feed).to receive(:find).with(feed.id).and_return(feed) result = FeedRepository.fetch(feed.id) expect(result).to eq feed end end end
kevinkda/UnivCourse_Java
Undergraduate Courses/Front-end/Course Design/CourseDesign_201912/Project/JavaScriptCourseDesign/Project/Whac-A-Mole/test1/js/resources/images.js
/** * 图像资源列表 */ function getImageRes() { return [{ id : 'hammer', src : 'images/hammer.png' },{ id:"bg_hole", src:"images/bg_canvas.png" },{ id:"bg_holeHide", src:"images/bg_hole.png" },{ id:"mouse", src:"images/mouse.png" },{ id:"help", src:"images/help.png" },{ id:"star", src:"images/star.png" },{ id:"icon", src:"images/icon.png" },{ id:"time_roller", src:"images/time_roller.png" }]; }
Jakegogo/concurrent
concur/src-dbcache/dbcache/test/SubEntity.java
package dbcache.test; import javax.persistence.Transient; import java.util.HashSet; import java.util.Set; /** * Created by Administrator on 2015/1/18. */ //@javax.persistence.Entity //@Table(name = "subEntity") public class SubEntity extends Entity { private String subName; @Transient private Set<Integer> stranges = new HashSet<Integer>(); public Set<Integer> getStranges() { return stranges; } public void setStranges(Set<Integer> stranges) { this.stranges = stranges; } public String getSubName() { return subName; } public void setSubName(String subName) { this.subName = subName; } }
dyorgio/radiance
substance/src/main/java/org/pushingpixels/substance/internal/utils/PairwiseButtonBackgroundDelegate.java
<gh_stars>0 /* * Copyright (c) 2005-2019 <NAME>. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * o Neither the name of Substance <NAME> nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.pushingpixels.substance.internal.utils; import org.pushingpixels.neon.NeonCortex; import org.pushingpixels.substance.api.*; import org.pushingpixels.substance.api.SubstanceSlices.*; import org.pushingpixels.substance.api.colorscheme.SubstanceColorScheme; import org.pushingpixels.substance.api.painter.border.SubstanceBorderPainter; import org.pushingpixels.substance.api.painter.fill.*; import org.pushingpixels.substance.api.shaper.*; import org.pushingpixels.substance.internal.SubstanceSynapse; import org.pushingpixels.substance.internal.animation.*; import javax.swing.*; import java.awt.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.util.*; /** * Delegate class for painting backgrounds of buttons in <b>Substance </b> look and feel. This class * is <b>for internal use only</b>. * * @author <NAME> */ public class PairwiseButtonBackgroundDelegate { /** * Cache for background images for pairwise backgrounds. Each time * {@link #getPairwiseFullAlphaBackground(AbstractButton, SubstanceFillPainter, SubstanceButtonShaper, int, int, SubstanceColorScheme, SubstanceColorScheme, boolean, boolean)} * is called, it checks <code>this</code> map to see if it already contains such background. * If so, the background from the map is returned. */ private static LazyResettableHashMap<BufferedImage> pairwiseBackgrounds = new LazyResettableHashMap<>( "PairwiseButtonBackgroundDelegate"); /** * Paints background image for the specified button in button pair (such as scrollbar arrows, * for example). * * @param g Graphics context. * @param button Button. * @param width Button width. * @param height Button height. * @param toIgnoreOpenSides If <code>true</code>, the open side setting (controlled by the * {@link SubstanceSynapse#BUTTON_OPEN_SIDE} is ignored. */ static void updatePairwiseBackground(Graphics g, AbstractButton button, int width, int height, boolean toIgnoreOpenSides) { if (SubstanceCoreUtilities.isButtonNeverPainted(button)) { return; } SubstanceButtonShaper shaper = SubstanceCoreUtilities.getButtonShaper(button); TransitionAwareUI transitionAwareUI = (TransitionAwareUI) button.getUI(); StateTransitionTracker stateTransitionTracker = transitionAwareUI.getTransitionTracker(); StateTransitionTracker.ModelStateInfo modelStateInfo = stateTransitionTracker .getModelStateInfo(); ComponentState currState = modelStateInfo.getCurrModelState(); SubstanceColorScheme baseFillScheme = SubstanceColorSchemeUtilities.getColorScheme(button, currState); SubstanceColorScheme baseBorderScheme = SubstanceColorSchemeUtilities.getColorScheme(button, ColorSchemeAssociationKind.BORDER, currState); SubstanceFillPainter fillPainter = SubstanceCoreUtilities.isSpinnerButton(button) ? MatteFillPainter.INSTANCE : SubstanceImageCreator.SimplisticSoftBorderReverseFillPainter.INSTANCE; Set<Side> openSides = toIgnoreOpenSides ? EnumSet.noneOf(Side.class) : SubstanceCoreUtilities.getSides(button, SubstanceSynapse.BUTTON_OPEN_SIDE); boolean needsRotation = (openSides != null) && (openSides.contains(Side.BOTTOM) || openSides.contains(Side.TOP)); BufferedImage baseLayer = getPairwiseFullAlphaBackground(button, fillPainter, shaper, width, height, baseFillScheme, baseBorderScheme, toIgnoreOpenSides, needsRotation); BufferedImage fullOpacity = null; Map<ComponentState, StateTransitionTracker.StateContributionInfo> activeStates = modelStateInfo.getStateContributionMap(); if (currState.isDisabled() || (activeStates.size() == 1)) { fullOpacity = baseLayer; } else { fullOpacity = SubstanceCoreUtilities.getBlankUnscaledImage(baseLayer); Graphics2D g2fullOpacity = fullOpacity.createGraphics(); // draw the base layer g2fullOpacity.drawImage(baseLayer, 0, 0, baseLayer.getWidth(), baseLayer.getHeight(), null); for (Map.Entry<ComponentState, StateTransitionTracker.StateContributionInfo> activeEntry : activeStates.entrySet()) { ComponentState activeState = activeEntry.getKey(); if (activeState == currState) { continue; } float contribution = activeEntry.getValue().getContribution(); if (contribution == 0.0f) { continue; } SubstanceColorScheme fillScheme = SubstanceColorSchemeUtilities .getColorScheme(button, activeState); SubstanceColorScheme borderScheme = SubstanceColorSchemeUtilities .getColorScheme(button, ColorSchemeAssociationKind.BORDER, activeState); BufferedImage layer = getPairwiseFullAlphaBackground(button, fillPainter, shaper, width, height, fillScheme, borderScheme, toIgnoreOpenSides, needsRotation); g2fullOpacity.setComposite(AlphaComposite.SrcOver.derive(contribution)); g2fullOpacity.drawImage(layer, 0, 0, layer.getWidth(), layer.getHeight(), null); } g2fullOpacity.dispose(); } boolean isFlat = SubstanceCoreUtilities.hasFlatAppearance(button); boolean isSpecial = isFlat || !button.isEnabled(); float extraAlpha = 1.0f; if (isSpecial) { if (isFlat) { // Special handling of flat buttons extraAlpha = 0.0f; for (Map.Entry<ComponentState, StateTransitionTracker.StateContributionInfo> activeEntry : activeStates.entrySet()) { ComponentState activeState = activeEntry.getKey(); if (activeState.isDisabled()) { continue; } if (activeState == ComponentState.ENABLED) { continue; } extraAlpha += activeEntry.getValue().getContribution(); } } else { if (!button.isEnabled()) { extraAlpha = SubstanceColorSchemeUtilities.getAlpha(button, currState); } } } if (extraAlpha > 0.0f) { Graphics2D graphics = (Graphics2D) g.create(); graphics.setComposite(WidgetUtilities.getAlphaComposite(button, extraAlpha, g)); NeonCortex.drawImage(graphics, fullOpacity, 0, 0); graphics.dispose(); } } /** * Retrieves background image for the specified button in button pair (such as scrollbar arrows, * for example). * * @param button Button. * @param fillPainter Gradient painter. * @param width Button width. * @param height Button height. * @param colorScheme The fill color scheme. * @param borderScheme The border color scheme. * @param toIgnoreOpenSides If <code>true</code>, the open side setting (controlled by the * {@link SubstanceSynapse#BUTTON_OPEN_SIDE} is ignored. * @return Button background image. */ private static BufferedImage getPairwiseFullAlphaBackground(AbstractButton button, SubstanceFillPainter fillPainter, SubstanceButtonShaper shaper, int width, int height, SubstanceColorScheme colorScheme, SubstanceColorScheme borderScheme, boolean toIgnoreOpenSides, boolean needsRotation) { if (SubstanceCoreUtilities.isButtonNeverPainted(button)) { return null; } Set<Side> openSides = toIgnoreOpenSides ? EnumSet.noneOf(Side.class) : SubstanceCoreUtilities.getSides(button, SubstanceSynapse.BUTTON_OPEN_SIDE); Set<Side> straightSides = SubstanceCoreUtilities.getSides(button, SubstanceSynapse.BUTTON_STRAIGHT_SIDE); boolean isBorderPainted = button.isBorderPainted(); boolean isContentAreaFilled = button.isContentAreaFilled(); float radius = 0.0f; if (SubstanceCoreUtilities.isSpinnerButton(button) && shaper instanceof RectangularButtonShaper) { radius = ((RectangularButtonShaper) shaper).getCornerRadius(button, 0.0f); } HashMapKey key = SubstanceCoreUtilities.getHashKey(width, height, straightSides, openSides, colorScheme.getDisplayName(), borderScheme.getDisplayName(), button.getClass().getName(), fillPainter.getDisplayName(), shaper.getDisplayName(), isBorderPainted, isContentAreaFilled, radius); // System.out.println("\tKey " + key); BufferedImage finalBackground = pairwiseBackgrounds.get(key); if (finalBackground == null) { // System.out.println("\tNot found"); int deltaLeft = (openSides != null) && openSides.contains(Side.LEFT) ? 3 : 0; int deltaRight = (openSides != null) && openSides.contains(Side.RIGHT) ? 3 : 0; int deltaTop = (openSides != null) && openSides.contains(Side.TOP) ? 3 : 0; int deltaBottom = (openSides != null) && openSides.contains(Side.BOTTOM) ? 3 : 0; GeneralPath contour = null; SubstanceBorderPainter borderPainter = SubstanceCoreUtilities.getBorderPainter(button); float borderDelta = SubstanceSizeUtils.getBorderStrokeWidth() / 2.0f; finalBackground = SubstanceCoreUtilities.getBlankImage(width, height); Graphics2D finalGraphics = (Graphics2D) finalBackground.getGraphics(); finalGraphics.translate(-deltaLeft, -deltaTop); if (needsRotation) { // rotate by 90% for better visuals contour = SubstanceOutlineUtilities.getBaseOutline(height + deltaTop + deltaBottom, width + deltaLeft + deltaRight, radius, null, borderDelta); int translateY = finalBackground.getHeight(); if (SubstanceCoreUtilities.isScrollButton(button)) { if ((openSides != null) && openSides.contains(SubstanceSlices.Side.BOTTOM)) { translateY += 4; } } AffineTransform at = AffineTransform.getTranslateInstance(0, translateY); at.rotate(-Math.PI / 2); double scaleFactor = NeonCortex.getScaleFactor(); finalGraphics.scale(1, 1); finalGraphics.setTransform(at); finalGraphics.scale(scaleFactor, scaleFactor); if (isContentAreaFilled) { fillPainter.paintContourBackground(finalGraphics, button, height + deltaTop + deltaBottom, width + deltaLeft + deltaRight, contour, false, colorScheme, true); } if (isBorderPainted) { borderPainter.paintBorder(finalGraphics, button, height + deltaTop + deltaBottom, width + deltaLeft + deltaRight, contour, null, borderScheme); } } else { contour = SubstanceOutlineUtilities.getBaseOutline(width + deltaLeft + deltaRight, height + deltaTop + deltaBottom, radius, straightSides, borderDelta); if (SubstanceCoreUtilities.isScrollButton(button)) { if ((openSides != null) && openSides.contains(SubstanceSlices.Side.LEFT)) finalGraphics.translate(1, 0); } if (isContentAreaFilled) { fillPainter.paintContourBackground(finalGraphics, button, width + deltaLeft + deltaRight, height + deltaTop + deltaBottom, contour, false, colorScheme, true); } if (isBorderPainted) { borderPainter.paintBorder(finalGraphics, button, width + deltaLeft + deltaRight, height + deltaTop + deltaBottom, contour, null, borderScheme); } } pairwiseBackgrounds.put(key, finalBackground); } return finalBackground; } }
wenfeifei/miniblink49
third_party/WebKit/Source/core/animation/animatable/AnimatableLengthBoxAndBool.cpp
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/animation/animatable/AnimatableLengthBoxAndBool.h" #include "core/animation/animatable/AnimatableLength.h" #include "core/animation/animatable/AnimatableLengthBox.h" namespace blink { static bool sidesHaveSameUnits(const AnimatableValue* sideA, const AnimatableValue* sideB) { if (!sideA->isLength() || !sideB->isLength()) return false; return toAnimatableLength(sideA)->hasSameUnits(toAnimatableLength(sideB)); } // This is only used by *-image-slice properties which cannot interpolate between numbers and percentages. // Numbers are internally represented by pixels on the ComputedStyle so we must manually type check both sides. bool AnimatableLengthBoxAndBool::usesDefaultInterpolationWith(const AnimatableValue* value) const { const AnimatableLengthBoxAndBool* lengthBoxAndBool = toAnimatableLengthBoxAndBool(value); if (lengthBoxAndBool->flag() != flag()) return true; if (!box()->isLengthBox() || !lengthBoxAndBool->box()->isLengthBox()) return AnimatableValue::usesDefaultInterpolation(box(), lengthBoxAndBool->box()); const AnimatableLengthBox* boxA = toAnimatableLengthBox(box()); const AnimatableLengthBox* boxB = toAnimatableLengthBox(lengthBoxAndBool->box()); return !sidesHaveSameUnits(boxA->left(), boxB->left()) || !sidesHaveSameUnits(boxA->right(), boxB->right()) || !sidesHaveSameUnits(boxA->top(), boxB->top()) || !sidesHaveSameUnits(boxA->bottom(), boxB->bottom()); } PassRefPtrWillBeRawPtr<AnimatableValue> AnimatableLengthBoxAndBool::interpolateTo(const AnimatableValue* value, double fraction) const { const AnimatableLengthBoxAndBool* lengthBoxAndBool = toAnimatableLengthBoxAndBool(value); if (usesDefaultInterpolationWith(lengthBoxAndBool)) return defaultInterpolateTo(this, value, fraction); return AnimatableLengthBoxAndBool::create( AnimatableValue::interpolate(box(), lengthBoxAndBool->box(), fraction), flag()); } bool AnimatableLengthBoxAndBool::equalTo(const AnimatableValue* value) const { const AnimatableLengthBoxAndBool* lengthBox = toAnimatableLengthBoxAndBool(value); return box()->equals(lengthBox->box()) && flag() == lengthBox->flag(); } DEFINE_TRACE(AnimatableLengthBoxAndBool) { visitor->trace(m_box); AnimatableValue::trace(visitor); } }
dekieras/GLEANKernel
GLEANKernel/GLEANLib/Framework Classes/testheader.cpp
#include "Human_subprocessor.h"
opensingular/singular-apps
requirement/requirement-module/src/test/java/org/opensingular/requirement/module/service/ModuleServiceMock.java
<reponame>opensingular/singular-apps /* * * * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * * * 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.opensingular.requirement.module.service; import org.opensingular.flow.persistence.entity.Actor; import org.opensingular.requirement.module.box.BoxItemDataMap; import org.opensingular.requirement.module.box.action.ActionRequest; import org.opensingular.requirement.module.box.action.ActionResponse; import org.opensingular.requirement.module.connector.DefaultModuleService; import org.opensingular.requirement.module.service.dto.BoxItemAction; import org.opensingular.requirement.module.service.dto.ItemActionConfirmation; import org.springframework.context.annotation.Primary; import javax.inject.Named; import java.util.Collections; import java.util.List; import java.util.Map; @Primary @Named public class ModuleServiceMock extends DefaultModuleService { @Override public List<Actor> findEligibleUsers(BoxItemDataMap rowItemData, ItemActionConfirmation confirmAction) { Actor actor = new Actor(1, "USUARIO.TESTE", "<NAME>", "<EMAIL>"); return Collections.singletonList(actor); } @Override public ActionResponse executeAction(BoxItemAction itemAction, Map<String, String> params, ActionRequest actionRequest) { ActionResponse response = new ActionResponse("Sucesso", true); return ActionResponse.class.cast(response); } }
trivassi/VendooEpicodus
app/src/main/java/co/vendoo/vendooepicodus/util/ItemTouchHelperViewHolder.java
package co.vendoo.vendooepicodus.util; /** * Created by T on 12/20/16. */ public interface ItemTouchHelperViewHolder { void onItemSelected(); void onItemClear(); }
guilhermepe/SOLLUS
sollus3/src/main/java/com/guiper/repository/PortaRepository.java
package com.guiper.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.guiper.entities.Porta; /** * * @author guiper */ public interface PortaRepository extends CrudRepository<Porta, Integer>{ List<Porta> findByNome(String nome); List<Porta> findByEquipamentoId(Long equipamentoId); }
ImaginaryNumb3r/Hephaestus-Collections
src/collections/iteration/MatchSink.java
package collections.iteration; import java.util.function.Predicate; /** * @author Patrick * @since 19.01.2018 */ abstract class MatchSink<T, X extends Exception> extends TerminationSink<T, X> { protected final IterationPredicate<T, X> _predicate; protected long _index; public MatchSink(IteratorEx<T, X> aggregator, IterationPredicate<T, X> predicate) { super(aggregator); _predicate = predicate; } public MatchSink(IteratorEx<T, X> aggregator, Predicate<T> predicate) { this(aggregator, (value, index) -> predicate.test(value)); } /** * The common abstract method to test for the matchings. * Implemented for "allMatch" and "anyMatch". */ public abstract boolean doesMatch() throws Exception; //<editor-fold desc="Match All"> public static final class MatchAllSink<T, X extends Exception> extends MatchSink<T, X> { //<editor-fold desc="Constructors"> public MatchAllSink(IteratorEx<T, X> aggregator, IterationPredicate<T, X> predicate) { super(aggregator, predicate); } public MatchAllSink(IteratorEx<T, X> aggregator, Predicate<T> predicate) { super(aggregator, predicate); } //</editor-fold> public boolean doesMatch() throws X { boolean allMatch = true; while (_source.hasNext() && allMatch){ T current = _source.next(); allMatch = _predicate.test(current, _index); ++_index; } return allMatch; } } //</editor-fold> //<editor-fold desc="Match Any"> public static final class MatchAnySink<T, X extends Exception> extends MatchSink<T, X> { //<editor-fold desc="Constructors"> public MatchAnySink(IteratorEx<T, X> aggregator, IterationPredicate<T, X> predicate) { super(aggregator, predicate); } public MatchAnySink(IteratorEx<T, X> aggregator, Predicate<T> predicate) { super(aggregator, predicate); } //</editor-fold> public boolean doesMatch() throws X { boolean anyMatch = false; while (_source.hasNext() && !anyMatch){ T current = _source.next(); anyMatch = _predicate.test(current, _index); ++_index; } return anyMatch; } } //</editor-fold> }
dtsimpson2/amf
build.sbt
import org.scalajs.core.tools.linker.ModuleKind import sbt.Keys.{libraryDependencies, resolvers} import sbtcrossproject.CrossPlugin.autoImport.crossProject import sbtsonar.SonarPlugin.autoImport.sonarProperties import scala.language.postfixOps import scala.sys.process._ import Versions.versions val ivyLocal = Resolver.file("ivy", file(Path.userHome.absolutePath + "/.ivy2/local"))(Resolver.ivyStylePatterns) name := "amf" version in ThisBuild := versions("amf.webapi") publish := {} jsEnv := new org.scalajs.jsenv.nodejs.NodeJSEnv() lazy val sonarUrl = sys.env.getOrElse("SONAR_SERVER_URL", "Not found url.") lazy val sonarToken = sys.env.getOrElse("SONAR_SERVER_TOKEN", "Not found token.") lazy val branch = sys.env.getOrElse("BRANCH_NAME", "develop") sonarProperties ++= Map( "sonar.login" -> sonarToken, "sonar.projectKey" -> "mulesoft.amf", "sonar.projectName" -> "AMF", "sonar.projectVersion" -> versions("amf.webapi"), "sonar.sourceEncoding" -> "UTF-8", "sonar.github.repository" -> "mulesoft/amf", "sonar.branch.name" -> branch, "sonar.scala.coverage.reportPaths" -> "amf-client/jvm/target/scala-2.12/scoverage-report/scoverage.xml,amf-webapi/jvm/target/scala-2.12/scoverage-report/scoverage.xml,amf-validation/jvm/target/scala-2.12/scoverage-report/scoverage.xml", "sonar.sources" -> "amf-client/shared/src/main/scala,amf-webapi/shared/src/main/scala,amf-validation/shared/src/main/scala", "sonar.tests" -> "amf-client/shared/src/test/scala" ) val settings = Common.settings ++ Common.publish ++ Seq( organization := "com.github.amlorg", resolvers ++= List(ivyLocal, Common.releases, Common.snapshots, Resolver.mavenLocal), resolvers += "jitpack" at "https://jitpack.io", credentials ++= Common.credentials(), aggregate in assembly := false, libraryDependencies ++= Seq( "org.scalatest" %%% "scalatest" % "3.0.5" % Test, "com.github.scopt" %%% "scopt" % "3.7.0" ) ) lazy val workspaceDirectory: File = sys.props.get("sbt.mulesoft") match { case Some(x) => file(x) case _ => Path.userHome / "mulesoft" } val amfAmlVersion = versions("amf.aml") lazy val amfAmlJVMRef = ProjectRef(workspaceDirectory / "amf-aml", "amlJVM") lazy val amfAmlJSRef = ProjectRef(workspaceDirectory / "amf-aml", "amlJS") lazy val amfAmlLibJVM = "com.github.amlorg" %% "amf-aml" % amfAmlVersion lazy val amfAmlLibJS = "com.github.amlorg" %% "amf-aml_sjs0.6" % amfAmlVersion lazy val defaultProfilesGenerationTask = TaskKey[Unit]( "defaultValidationProfilesGeneration", "Generates the validation dialect documents for the standard profiles") /** ********************************************** * AMF-WebAPI * ********************************************* */ lazy val webapi = crossProject(JSPlatform, JVMPlatform) .settings(Seq( name := "amf-webapi" )) .in(file("./amf-webapi")) .settings(settings) .jvmSettings( libraryDependencies += "org.scala-js" %% "scalajs-stubs" % scalaJSVersion % "provided", libraryDependencies += "org.scala-lang.modules" % "scala-java8-compat_2.12" % "0.8.0", libraryDependencies += "org.json4s" %% "json4s-native" % "3.5.4", libraryDependencies += "com.github.everit-org.json-schema" % "org.everit.json.schema" % "1.9.2", artifactPath in (Compile, packageDoc) := baseDirectory.value / "target" / "artifact" / "amf-webapi-javadoc.jar", mappings in (Compile, packageBin) += file("amf-webapi.versions") -> "amf-webapi.versions" ) .jsSettings( libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.9.2", scalaJSModuleKind := ModuleKind.CommonJSModule, artifactPath in (Compile, fullOptJS) := baseDirectory.value / "target" / "artifact" / "amf-webapi-module.js", scalacOptions += "-P:scalajs:suppressExportDeprecations" ).disablePlugins(SonarPlugin) lazy val webapiJVM = webapi.jvm.in(file("./amf-webapi/jvm")).sourceDependency(amfAmlJVMRef, amfAmlLibJVM) lazy val webapiJS = webapi.js.in(file("./amf-webapi/js")).sourceDependency(amfAmlJSRef, amfAmlLibJS).disablePlugins(SonarPlugin) /** ********************************************** * AMF-Validation * ********************************************* */ lazy val validation = crossProject(JSPlatform, JVMPlatform) .settings(Seq( name := "amf-validation" )) .in(file("./amf-validation")) .settings(settings) .jvmSettings( libraryDependencies += "org.scala-js" %% "scalajs-stubs" % scalaJSVersion % "provided", libraryDependencies += "org.scala-lang.modules" % "scala-java8-compat_2.12" % "0.8.0", libraryDependencies += "org.json4s" %% "json4s-native" % "3.5.4", libraryDependencies += "org.topbraid" % "shacl" % "1.3.0", libraryDependencies += "org.slf4j" % "slf4j-simple" % "1.7.12", libraryDependencies += "org.apache.commons" % "commons-compress" % "1.19", libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.9.8", artifactPath in (Compile, packageDoc) := baseDirectory.value / "target" / "artifact" / "amf-validation-javadoc.jar" ) .jsSettings( libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.9.2", scalaJSModuleKind := ModuleKind.CommonJSModule, artifactPath in (Compile, fullOptJS) := baseDirectory.value / "target" / "artifact" / "amf-validation-module.js" ).disablePlugins(SonarPlugin) lazy val validationJVM = validation.jvm.in(file("./amf-validation/jvm")).sourceDependency(amfAmlJVMRef, amfAmlLibJVM) lazy val validationJS = validation.js.in(file("./amf-validation/js")).sourceDependency(amfAmlJSRef, amfAmlLibJS).disablePlugins(SonarPlugin) /** ********************************************** * AMF Client * ********************************************* */ lazy val client = crossProject(JSPlatform, JVMPlatform) .settings(name := "amf-client") .settings(fullRunTask(defaultProfilesGenerationTask, Compile, "amf.tasks.validations.ValidationProfileExporter")) .dependsOn( webapi, validation) .in(file("./amf-client")) .settings(settings) .jvmSettings( libraryDependencies += "org.scala-js" %% "scalajs-stubs" % scalaJSVersion % "provided", libraryDependencies += "org.reflections" % "reflections" % "0.9.11", libraryDependencies += "org.scala-lang.modules" % "scala-java8-compat_2.12" % "0.8.0", libraryDependencies += "org.json4s" %% "json4s-native" % "3.5.4", libraryDependencies += "org.topbraid" % "shacl" % "1.3.0", libraryDependencies += "org.apache.commons" % "commons-compress" % "1.18", libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.9.8", mainClass in Compile := Some("amf.Main"), packageOptions in (Compile, packageBin) += Package.ManifestAttributes("Automatic-Module-Name" → "org.mule.amf"), mappings in (Compile, packageBin) += file("amf-webapi.versions") -> "amf-webapi.versions", aggregate in assembly := true, test in assembly := {}, mainClass in assembly := Some("amf.Main"), assemblyOutputPath in assembly := file(s"./amf-${version.value}.jar"), assemblyMergeStrategy in assembly := { case x if x.toString.contains("commons/logging") => MergeStrategy.discard case x if x.toString.endsWith("JS_DEPENDENCIES") => MergeStrategy.discard case PathList(ps @ _*) if ps.last endsWith "JS_DEPENDENCIES" => MergeStrategy.discard case x => val oldStrategy = (assemblyMergeStrategy in assembly).value oldStrategy(x) } ) .jsSettings( jsDependencies += ProvidedJS / "shacl.js", jsDependencies += ProvidedJS / "ajv.min.js", libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.9.2", scalaJSModuleKind := ModuleKind.CommonJSModule, artifactPath in (Compile, fullOptJS) := baseDirectory.value / "target" / "artifact" / "amf-client-module.js" ).disablePlugins(SonarPlugin) lazy val clientJVM = client.jvm.in(file("./amf-client/jvm")).sourceDependency(amfAmlJVMRef, amfAmlLibJVM) lazy val clientJS = client.js.in(file("./amf-client/js")).sourceDependency(amfAmlJSRef, amfAmlLibJS).disablePlugins(SonarPlugin) /** ********************************************** * AMF Tools ********************************************** */ //lazy val tools = crossProject(JVMPlatform) // .settings(Seq( // name := "amf-tools", // fullRunTask(defaultProfilesGenerationTask, Compile, "amf.tasks.validations.ValidationProfileExporter"))) // .dependsOn(core, webapi, vocabularies, validation, client % "compile->compile;test->test") // .in(file("./amf-tools")) // .settings(settings) // .jvmSettings( // mainClass in Compile := Some("amf.VocabularyExporter"), // mainClass in assembly := Some("amf.VocabularyExporter"), // assemblyOutputPath in assembly := file(s"./amf-${version.value}.jar") // ) // //lazy val toolsJVM = tools.jvm.in(file("./amf-tools/jvm")) // Tasks val buildJS = TaskKey[Unit]("buildJS", "Build npm module") buildJS := { val _ = (fullOptJS in Compile in clientJS).value "./amf-client/js/build-scripts/buildjs.sh" ! } addCommandAlias( "buildCommandLine", "; clean; clientJVM/assembly" ) /** ********************************************** * AMF Runner ********************************************** */ lazy val amfRunner = project .in(file("./amf-runner")) .dependsOn(clientJVM) .settings(settings) .disablePlugins(SonarPlugin)
rageyboiii/test-boy
cogs/music.py
<reponame>rageyboiii/test-boy import asyncio import datetime import json import math import os import re from typing import List, Literal, Optional, Union import async_timeout import nextcord as discord import validators import wavelink from nextcord.ext import commands, menus from numpy import random from functions import MessageColors, MyContext, checks, config, embed, exceptions URL_REG = re.compile(r'https?://(?:www\.)?.+') def can_play(): async def predicate(ctx: MyContext) -> bool: # connect_perms = ["connect", "speak"] # missing = [] # if ctx.author.voice is None or ctx.author.voice.channel is None: # raise NoChannelProvided() # for perm, value in ctx.author.voice.channel.permissions_for(ctx.me): # if value is False and perm.lower() in connect_perms: # missing.append(perm) # if len(missing) > 0: # raise commands.BotMissingPermissions(missing) # return True player: Player = ctx.bot.wavelink.get_player(ctx.guild.id, cls=Player, ctx=ctx) if player.ctx and player.ctx.channel != ctx.channel: raise IncorrectChannelError(f"You must be in `{player.ctx.channel}` for this session.") if ctx.command.name == "connect" and not player.ctx: return True elif ctx.cog.is_privileged(ctx): return True if not player.channel_id: raise IncorrectChannelError("Failed to load the channel to play music.") channel = ctx.bot.get_channel(player.channel_id) if not channel: raise IncorrectChannelError("Failed to load the channel to play music.") if player.is_connected: if ctx.author not in channel.members: raise IncorrectChannelError(f"You must be in `{channel}` to use voice commands.") return True return commands.check(predicate) class NoChannelProvided(exceptions.Base): def __init__(self, message="You must be in a voice channel or provide one to connect to."): super().__init__(message=message) class IncorrectChannelError(exceptions.Base): def __init__(self, message="You must be in the same voice channel as the bot."): super().__init__(message=message) class NoCustomSoundsFound(exceptions.Base): def __init__(self, message="There are no custom sounds for this server (yet)"): super().__init__(message=message) class VoiceConnectionError(exceptions.Base): def __init__(self, message="An error occured while connecting to a voice channel."): super().__init__(message=message) class Track(wavelink.Track): __slots__ = ("requester", "thumbnail",) def __init__(self, *args, **kwargs): super().__init__(*args) self.requester = kwargs.get("requester") self.thumbnail = kwargs.get("thumbnail") class Player(wavelink.Player): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ctx: Optional[MyContext] = kwargs.get("ctx", None) self.dj: Optional[discord.Member] = self.ctx.author if self.ctx else None self.current_title = None self.queue = asyncio.Queue() self.waiting = False self.pause_votes = set() self.resume_votes = set() self.skip_votes = set() self.shuffle_votes = set() self.stop_votes = set() async def connect(self, channel: Union[discord.VoiceChannel, discord.StageChannel], self_deaf: bool = True, *, ctx: MyContext = None) -> Union[discord.VoiceChannel, discord.StageChannel]: if not self.ctx: self.ctx = ctx self.dj = ctx.author guild = self.bot.get_guild(self.guild_id) if not guild: raise wavelink.errors.InvalidIDProvided(f'No guild found for id <{self.guild_id}>') self.channel_id = channel.id await self._get_shard_socket(guild.shard_id).voice_state(self.guild_id, str(channel.id), self_deaf=self_deaf) return channel async def disconnect(self, *, force: bool = False): guild = self.bot.get_guild(self.guild_id) if not guild and force is True: self.channel_id = None return if not guild: raise wavelink.errors.InvalidIDProvided(f'No guild found for id <{self.guild_id}>') self.channel_id = None await self._get_shard_socket(guild.shard_id).voice_state(self.guild_id, None) async def do_next(self): if self.is_playing or self.waiting: return self.pause_votes.clear() self.resume_votes.clear() self.skip_votes.clear() self.shuffle_votes.clear() self.stop_votes.clear() try: self.waiting = True with async_timeout.timeout(60): track = await self.queue.get() except asyncio.TimeoutError: # No music has been played for 5 minutes, cleanup and disconnect... return await self.teardown() channel = self.bot.get_channel(self.channel_id) if channel and channel.type == discord.ChannelType.stage_voice and not channel.instance: await channel.create_instance(topic=track.title, reason="Music time!") elif channel and channel.type == discord.ChannelType.stage_voice and channel.instance is not None and self.current_title and channel.instance.topic == self.current_title: await channel.instance.edit(topic=track.title, reason="Next track!") self.current_title = track.title await self.play(track) self.waiting = False await self.ctx.reply(embed=self.build_embed()) def build_embed(self) -> Optional[discord.Embed]: track = self.current if not track: return channel = self.bot.get_channel(self.channel_id) qsize = self.queue.qsize() try: duration = str(datetime.timedelta(milliseconds=int(track.length))) except OverflowError: duration = "??:??:??" return embed( title=f"Now playing: **{track.title}**", thumbnail=track.thumbnail, url=track.uri, fieldstitle=["Duration", "Queue Length", "Volume", "Requested By", "DJ", "Channel"], fieldsval=[duration, str(qsize), f"**`{self.volume}%`**", f"{track.requester.mention}", f"{self.dj.mention if self.dj else None}", f"{channel.mention if channel else None}"], color=MessageColors.MUSIC) async def teardown(self): try: await self.destroy() except KeyError: pass NUMTOEMOTES = { 0: "0️⃣", 1: "1️⃣", 2: "2️⃣", 3: "3️⃣", 4: "4️⃣", 5: "5️⃣", 6: "6️⃣", 7: "7️⃣", 8: "8️⃣", 9: "9️⃣", 10: "🔟", } class PaginatorSource(menus.ListPageSource): def __init__(self, entries: List[str], *, per_page: int = 10): super().__init__(entries, per_page=per_page) async def format_page(self, menu: menus.MenuPages, page: List[str]) -> discord.Embed: return embed( title="Coming up...", description='\n'.join(f'{NUMTOEMOTES[index]} - {title}' for index, title in enumerate(page, 1)), color=MessageColors.MUSIC) def is_paginating(self) -> bool: return True class QueueMenu(menus.ButtonMenuPages): def __init__(self, source, *, title="Commands", description=""): super().__init__(source=source, timeout=30.0) self._source = source self.current_page = 0 self.ctx = None self.message = None async def start(self, ctx, *, channel: discord.TextChannel = None, wait=False) -> None: await self._source._prepare_once() self.ctx = ctx self.message = await self.send_initial_message(ctx, ctx.channel) async def send_initial_message(self, ctx: "MyContext", channel: discord.TextChannel): page = await self._source.get_page(0) kwargs = await self._get_kwargs_from_page(page) return await ctx.send(**kwargs) async def _get_kwargs_from_page(self, page): value = await super()._get_kwargs_from_page(page) if "view" not in value: value.update({"view": self}) return value async def interaction_check(self, interaction: discord.Interaction) -> bool: if interaction.user and interaction.user == self.ctx.author: return True else: await interaction.response.send_message('This help menu is not for you.', ephemeral=True) return False def stop(self): try: self.ctx.bot.loop.create_task(self.message.delete()) except discord.NotFound: pass super().stop() async def on_timeout(self) -> None: self.stop() class Music(commands.Cog, wavelink.WavelinkMixin): """Listen to your favourite music and audio clips with Friday's music commands""" def __init__(self, bot): self.bot = bot if not hasattr(self.bot, "wavelink"): self.bot.wavelink = wavelink.Client(bot=bot, session=bot.session) bot.loop.create_task(self.start_nodes()) async def start_nodes(self): await self.bot.wait_until_ready() nodes = { "MAIN": { "host": os.environ.get("LAVALINKUSHOST"), "port": os.environ.get("LAVALINKUSPORT"), "rest_uri": f"http://{os.environ.get('LAVALINKUSHOST')}:{os.environ.get('LAVALINKUSPORT')}/", "password": <PASSWORD>("<PASSWORD>"), "identifier": "MAIN", "region": "us_central", }, } if self.bot.wavelink.nodes: previous: List[wavelink.Node] = self.bot.wavelink.nodes.copy() for node in previous.values(): if not node.is_available: await node.destroy() for n in nodes.values(): try: await self.bot.wavelink.initiate_node(**n) except wavelink.errors.NodeOccupied: pass def cog_check(self, ctx: MyContext) -> bool: if not ctx.guild: raise commands.NoPrivateMessage() return True async def cog_command_error(self, ctx: MyContext, error: Exception): if isinstance(error, (IncorrectChannelError, NoChannelProvided, NoCustomSoundsFound, VoiceConnectionError)): return await ctx.send(embed=embed(title=error, color=MessageColors.ERROR)) elif isinstance(error, commands.BadLiteralArgument): return await ctx.send(embed=embed(title=f"`{error.param.name}` must be one of `{', '.join(error.literals)}.`", color=MessageColors.ERROR)) elif isinstance(error, (exceptions.RequiredTier, exceptions.NotSupporter, exceptions.NotInSupportServer)): return await ctx.send(embed=embed(title=error, color=MessageColors.ERROR)) else: print(f"Error in {ctx.command.qualified_name}: {type(error).__name__}: {error}") @wavelink.WavelinkMixin.listener() async def on_node_ready(self, node: wavelink.Node): print(f"Node {node.identifier} is ready!") @wavelink.WavelinkMixin.listener('on_track_stuck') @wavelink.WavelinkMixin.listener('on_track_end') @wavelink.WavelinkMixin.listener('on_track_exception') async def on_player_stop(self, node: wavelink.Node, payload): await payload.player.do_next() @commands.Cog.listener() async def on_voice_state_update(self, member: discord.Member, before: discord.VoiceState, after: discord.VoiceState): # TODO: when moved to another voice channel, Friday will some times just stop playing music until !pause and !resume are executed if member == self.bot.user: if before.channel != after.channel and after.channel is not None and after.channel.type == discord.ChannelType.stage_voice: await member.edit(suppress=False) # TODO: Check if node has been made yet # if not player: player: Player = self.bot.wavelink.get_player(member.guild.id, cls=Player) if member.bot: return if not player.channel_id or not player.ctx: player.node.players.pop(member.guild.id) return channel = self.bot.get_channel(int(player.channel_id)) if member == player.dj and after.channel is None: for m in channel.members: if m.bot: continue else: player.dj = m return elif after.channel == channel and player.dj not in channel.members: player.dj = member def required(self, ctx: MyContext): player: Player = self.bot.wavelink.get_player(ctx.guild.id, cls=Player, ctx=ctx) channel = self.bot.get_channel(player.channel_id) required = math.ceil((len(channel.members) - 1) / 2.5) if ctx.command.name == "stop": if len(channel.members) == 3: required = 2 return required def is_privileged(self, ctx: MyContext): player: Player = self.bot.wavelink.get_player(ctx.guild.id, cls=Player, ctx=ctx) return player.dj == ctx.author or ctx.author.guild_permissions.kick_members async def join(self, ctx: MyContext, channel: Union[discord.VoiceChannel, discord.StageChannel] = None) -> Optional[Union[discord.VoiceChannel, discord.StageChannel]]: player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if player.is_connected: return channel = getattr(ctx.author.voice, 'channel', channel) if channel is None else channel if channel is None: raise NoChannelProvided return await player.connect(channel, ctx=ctx) @commands.command(name="connect", aliases=["join"], help="Join a voice channel") @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) @can_play() async def connect(self, ctx: MyContext, *, channel: Optional[Union[discord.VoiceChannel, discord.StageChannel]] = None): """Connect to a voice channel.""" ch = await self.join(ctx, channel) if ch: return await ctx.send(f"{ch.mention}", embed=embed(title="Connected to voice channel", color=MessageColors.MUSIC)) return await ctx.send(embed=embed(title="Failed to connect to voice channel.", color=MessageColors.ERROR)) @commands.command(name="play", aliases=["p", "add"], extras={"examples": ["https://youtu.be/dQw4w9WgXcQ"]}, usage="<url/title>", help="Follow this command with the title of a song to search for it or just paste the Youtube/SoundCloud url if the search gives and undesirable result") @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) @can_play() async def play(self, ctx: MyContext, *, query: str): """Play or queue a song with the given query.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) await ctx.trigger_typing() if not player.is_connected: await self.join(ctx) query = query.strip('<>') if not URL_REG.match(query): query = f'ytsearch:{query}' tracks = await self.bot.wavelink.get_tracks(query) if not tracks: return await ctx.send(embed=embed(title='No songs were found with that query. Please try again.', color=MessageColors.ERROR)) if isinstance(tracks, wavelink.TrackPlaylist): for track in tracks.tracks: track = Track(track.id, track.info, thumbnail=track.thumb, requester=ctx.author) await player.queue.put(track) if player.is_playing or player.is_paused: await ctx.send(embed=embed( title=f"Added the playlist {tracks.data['playlistInfo']['name']}", description=f" with {len(tracks.tracks)} songs to the queue.", color=MessageColors.MUSIC)) else: track = Track(tracks[0].id, tracks[0].info, thumbnail=tracks[0].thumb, requester=ctx.author) await player.queue.put(track) if player.is_playing or player.is_paused: await ctx.send(embed=embed(title=f"Added **{track.title}** to the Queue", color=MessageColors.MUSIC)) if not player.is_playing: await player.do_next() @commands.command(name="pause") @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) @can_play() async def pause(self, ctx: MyContext): """Pause the currently playing song.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if player.is_paused or not player.is_connected: return await ctx.send(embed=embed(title='Nothing is playing right now', color=MessageColors.ERROR)) if self.is_privileged(ctx): await ctx.send(embed=embed(title='An admin or DJ has paused the player.', color=MessageColors.MUSIC)) player.pause_votes.clear() return await player.set_pause(True) required = self.required(ctx) player.pause_votes.add(ctx.author) if len(player.pause_votes) >= required: await ctx.send(embed=embed(title='Vote to pause passed. Pausing player.', color=MessageColors.MUSIC)) player.pause_votes.clear() await player.set_pause(True) else: await ctx.send(embed=embed(title=f'{ctx.author} has voted to pause the player.', color=MessageColors.MUSIC)) @commands.command(name="resume") @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) @can_play() async def resume(self, ctx: MyContext): """Resume a currently paused player.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if not player.is_paused or not player.is_connected: return await ctx.send(embed=embed(title='Nothing is playing right now', color=MessageColors.ERROR)) if self.is_privileged(ctx): await ctx.send(embed=embed(title='An admin or DJ has resumed the player.', color=MessageColors.MUSIC)) player.resume_votes.clear() return await player.set_pause(False) required = self.required(ctx) player.resume_votes.add(ctx.author) if len(player.resume_votes) >= required: await ctx.send(embed=embed(title='Vote to resume passed. Resuming player.', color=MessageColors.MUSIC)) player.resume_votes.clear() await player.set_pause(False) else: await ctx.send(embed=embed(title=f'{ctx.author.mention} has voted to resume the player.', color=MessageColors.MUSIC)) @commands.command(name="skip", help="Skips the current song") @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) @can_play() async def skip(self, ctx: MyContext): """Skip the currently playing song.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if not player.is_connected: return await ctx.send(embed=embed(title='Nothing is playing right now', color=MessageColors.ERROR)) if self.is_privileged(ctx): await ctx.send(embed=embed(title='An admin or DJ has skipped the song.', color=MessageColors.MUSIC)) player.skip_votes.clear() return await player.stop() if ctx.author == player.current.requester: await ctx.send(embed=embed(title='The song requester has skipped the song.', color=MessageColors.MUSIC)) player.skip_votes.clear() return await player.stop() required = self.required(ctx) player.skip_votes.add(ctx.author) if len(player.skip_votes) >= required: await ctx.send(embed=embed(title='Vote to skip passed. Skipping song.', color=MessageColors.MUSIC)) player.skip_votes.clear() await player.stop() else: await ctx.send(embed=embed(title=f'{ctx.author} has voted to skip the song.', color=MessageColors.MUSIC)) @commands.command(name="stop", aliases=["disconnect"], help="Stops the currently playing music") @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) # @can_play() async def stop(self, ctx: MyContext): """Stop the player and clear all internal states.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if not player.is_connected: return await ctx.send(embed=embed(title='Nothing is playing right now', color=MessageColors.ERROR)) if self.is_privileged(ctx): await ctx.send(embed=embed(title='An admin or DJ has stopped the player.', color=MessageColors.MUSIC)) return await player.teardown() required = self.required(ctx) player.stop_votes.add(ctx.author) if len(player.stop_votes) >= required: await ctx.send(embed=embed(title='Vote to stop passed. Stopping the player.', color=MessageColors.MUSIC)) await player.teardown() else: await ctx.send(embed=embed(title=f'{ctx.author} has voted to stop the player.', color=MessageColors.MUSIC)) @commands.command(name="volume", aliases=['v', 'vol']) @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) @can_play() async def volume(self, ctx: MyContext, *, vol: int): """Change the players volume, between 1 and 100.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if not player.is_connected: return await ctx.send(embed=embed(title='Nothing is playing right now', color=MessageColors.ERROR)) if not self.is_privileged(ctx): return await ctx.send(embed=embed(title='Only the DJ or admins may change the volume.', color=MessageColors.MUSIC)) if not 0 < vol <= 100: return await ctx.send(embed=embed(title='Please enter a value between 1 and 100.', color=MessageColors.MUSIC)) await player.set_volume(vol) await ctx.send(embed=embed(title=f'Set the volume to **{vol}**%')) @commands.command(name="shuffle", aliases=['mix']) @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) @can_play() async def shuffle(self, ctx: MyContext): """Shuffle the players queue.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if not player.is_connected: return await ctx.send(embed=embed(title='Nothing is playing right now', color=MessageColors.ERROR)) if player.queue.qsize() < 3: return await ctx.send(embed=embed(title='Add more songs to the queue before shuffling.', color=MessageColors.MUSIC)) if self.is_privileged(ctx): await ctx.send(embed=embed(title='An admin or DJ has shuffled the playlist.', color=MessageColors.MUSIC)) player.shuffle_votes.clear() return random.shuffle(player.queue._queue) required = self.required(ctx) player.shuffle_votes.add(ctx.author) if len(player.shuffle_votes) >= required: await ctx.send(embed=embed(title='Vote to shuffle passed. Shuffling the playlist.', color=MessageColors.MUSIC)) player.shuffle_votes.clear() random.shuffle(player.queue._queue) else: await ctx.send(embed=embed(title=f'{ctx.author.mention} has voted to shuffle the playlist.', color=MessageColors.MUSIC)) @commands.command(name="equalizer", aliases=['eq']) @checks.is_min_tier(list(config.premium_tiers)[1]) @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) @can_play() async def equalizer(self, ctx: MyContext, *, equalizer: Literal["flat", "boost", "metal", "piano"]): """Change the players equalizer.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if not player.is_connected: return await ctx.send(embed=embed(title='Nothing is playing right now', color=MessageColors.ERROR)) if not self.is_privileged(ctx): return await ctx.send(embed=embed(title='Only the DJ or admins may change the equalizer.', color=MessageColors.ERROR)) eqs = {'flat': wavelink.Equalizer.flat(), 'boost': wavelink.Equalizer.boost(), 'metal': wavelink.Equalizer.metal(), 'piano': wavelink.Equalizer.piano()} eq = eqs.get(equalizer.lower(), None) if not eq: joined = "\n".join(eqs.keys()) return await ctx.send(embed=embed(title=f'Invalid EQ provided. Valid EQs:\n\n{joined}', color=MessageColors.ERROR)) await ctx.send(embed=embed(title=f'Successfully changed equalizer to {equalizer}', color=MessageColors.MUSIC)) await player.set_eq(eq) @commands.command(name="queue", aliases=['que'], help="shows the song queue") @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.channel, wait=True) @can_play() async def queue(self, ctx: MyContext): """Display the players queued songs.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if not player.is_connected: return await ctx.send(embed=embed(title='Nothing is playing right now', color=MessageColors.ERROR)) if player.queue.qsize() == 0: return await ctx.send(embed=embed(title='There are no more songs in the queue.', color=MessageColors.ERROR)) entries = [track.title for track in player.queue._queue] pages = PaginatorSource(entries=entries) paginator = QueueMenu(source=pages) await paginator.start(ctx) @commands.command(name="nowplaying", aliases=['np', 'now_playing', 'current']) @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.channel, wait=True) @can_play() async def nowplaying(self, ctx: MyContext): """Update the player controller.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if not player.is_connected: return await ctx.send(embed=embed(title='Nothing is playing right now', color=MessageColors.ERROR)) await ctx.send(embed=player.build_embed()) @commands.command(name="swap_dj", aliases=['swap'], help="Swap who has control over the music. (Admins always have control)") @commands.guild_only() @commands.max_concurrency(1, commands.BucketType.guild, wait=True) @can_play() async def swap_dj(self, ctx: MyContext, *, member: discord.Member = None): """Swap the current DJ to another member in the voice channel.""" player: Player = self.bot.wavelink.get_player(guild_id=ctx.guild.id, cls=Player, ctx=ctx) if not player.is_connected: return await ctx.send(embed=embed(title='Nothing is playing right now', color=MessageColors.ERROR)) if not self.is_privileged(ctx): return await ctx.send(embed=embed(title='Only admins and the DJ may use this command.', color=MessageColors.ERROR)) members = self.bot.get_channel(int(player.channel_id)).members if member and member not in members: return await ctx.send(embed=embed(title=f'{member} is not currently in voice, so can not be a DJ.')) if member and member == player.dj: return await ctx.send(embed=embed(title='Cannot swap DJ to the current DJ... :)')) if len(members) <= 2: return await ctx.send(embed=embed(title='No more members to swap to.', color=MessageColors.MUSIC)) if member: player.dj = member return await ctx.send(embed=embed(title=f'{member.mention} is now the DJ.', color=MessageColors.MUSIC)) for m in members: if m == player.dj or m.bot: continue else: player.dj = m return await ctx.send(embed=embed(title=f'{member.mention} is now the DJ.', color=MessageColors.MUSIC)) @commands.group(name="custom", aliases=["c"], invoke_without_command=True, case_insensitive=True, help="Play sounds/songs without looking for the url everytime") @commands.guild_only() # @commands.cooldown(1,4, commands.BucketType.channel) @can_play() @commands.max_concurrency(1, commands.BucketType.channel, wait=True) async def custom(self, ctx, name: str = None): if name is None: return await ctx.invoke(self.custom_list) try: async with ctx.typing(): sounds = await self.bot.db.query("SELECT customSounds FROM servers WHERE id=$1 LIMIT 1", str(ctx.guild.id)) sounds = [json.loads(x) for x in sounds] except Exception: await ctx.reply(embed=embed(title=f"The custom sound `{name}` has not been set, please add it with `{ctx.prefix}custom|c add <name> <url>`", color=MessageColors.ERROR)) else: i = next((index for (index, d) in enumerate(sounds) if d["name"] == name), None) if sounds is not None and i is not None: sound = sounds[i] await ctx.invoke(self.bot.get_command("play"), query=sound["url"]) else: await ctx.reply(embed=embed(title=f"The sound `{name}` has not been added, please check the `custom list` command", color=MessageColors.ERROR)) @custom.command(name="add") @commands.guild_only() @commands.has_guild_permissions(manage_channels=True) async def custom_add(self, ctx, name: str, url: str): url = url.strip("<>") valid = validators.url(url) if valid is not True: await ctx.reply(embed=embed(title=f"Failed to recognize the url `{url}`", color=MessageColors.ERROR)) return if name in ["add", "change", "replace", "list", "remove", "del"]: await ctx.reply(embed=embed(title=f"`{name}`is not an acceptable name for a command as it is a sub-command of custom", color=MessageColors.ERROR)) return async with ctx.typing(): name: str = "".join(name.split(" ")).lower() sounds: list = (await self.bot.db.query("SELECT customSounds FROM servers WHERE id=$1 LIMIT 1", str(ctx.guild.id))) if sounds == "" or sounds is None: sounds = [] if name in [json.loads(x)["name"] for x in sounds]: return await ctx.reply(embed=embed(title=f"`{name}` was already added, please choose another", color=MessageColors.ERROR)) sounds.append(json.dumps({"name": name, "url": url})) await self.bot.db.query("UPDATE servers SET customSounds=$1::json[] WHERE id=$2::text", sounds, str(ctx.guild.id)) await ctx.reply(embed=embed(title=f"I will now play `{url}` for the command `{ctx.prefix}{ctx.command.parent} {name}`")) @custom.command(name="list") @commands.guild_only() async def custom_list(self, ctx): async with ctx.typing(): sounds = await self.bot.db.query("SELECT customSounds FROM servers WHERE id=$1 LIMIT 1", str(ctx.guild.id)) if sounds is None: raise NoCustomSoundsFound("There are no custom sounds for this server (yet)") sounds = [json.loads(x) for x in sounds] result = "" for sound in sounds: result += f"```{sound['name']} -> {sound['url']}```" if result == "": result = "There are no custom sounds for this server (yet)" await ctx.reply(embed=embed(title="The list of custom sounds", description=result)) @custom.command(name="change", aliases=["replace"]) @commands.guild_only() @commands.has_guild_permissions(manage_channels=True) async def custom_change(self, ctx, name: str, url: str): try: async with ctx.typing(): name = "".join(name.split(" ")).lower() sounds = await self.bot.db.query("SELECT customSounds FROM servers WHERE id=$1 LIMIT 1", str(ctx.guild.id)) sounds = json.loads(sounds) old = sounds[name] sounds[name] = url await self.bot.db.query("UPDATE servers SET customSounds=$1 WHERE id=$2", json.dumps(sounds), str(ctx.guild.id)) except KeyError: await ctx.reply(embed=embed(title=f"Could not find the custom command `{name}`", color=MessageColors.ERROR)) else: await ctx.reply(embed=embed(title=f"Changed `{name}` from `{old}` to `{url}`")) @custom.command(name="remove", aliases=["del"]) @commands.guild_only() @commands.has_guild_permissions(manage_channels=True) async def custom_del(self, ctx, name: str): try: async with ctx.typing(): name = "".join(name.split(" ")).lower() sounds = await self.bot.db.query("SELECT customSounds FROM servers WHERE id=$1 LIMIT 1", str(ctx.guild.id)) sounds = [json.loads(x) for x in sounds] sounds.pop(next((index for (index, d) in enumerate(sounds) if d["name"] == name), None)) await self.bot.db.query("UPDATE servers SET customSounds=$1::json[] WHERE id=$2", [json.dumps(x) for x in sounds], str(ctx.guild.id)) except KeyError: await ctx.reply(embed=embed(title=f"Could not find the custom command `{name}`", color=MessageColors.ERROR)) else: await ctx.reply(embed=embed(title=f"Removed the custom sound `{name}`")) @custom.command(name="clear") @commands.guild_only() @commands.has_guild_permissions(manage_channels=True) async def custom_clear(self, ctx): async with ctx.typing(): await self.bot.db.query("UPDATE servers SET customsounds=array[]::json[] WHERE id=$1", str(ctx.guild.id)) await ctx.send(embed=embed(title="Cleared this servers custom commands")) def setup(bot): bot.add_cog(Music(bot))
baiheinet/scalable-form-platform
packages/scalable-form-antd-mobile/src/i18n/ko-kr.js
module.exports = { "xform.client.xform-antd-mobile.dateRange.xformDefaultEndDatePlaceholder": "끝 Date", "xform.client.xform-antd-mobile.dateRange.xformDefaultStartDatePlaceholder": "Start date", "xform.client.xform-antd-mobile.index.xformDefaultSubmitButtonLabel": "!! 만족해주신다니", "xform.client.xform-antd-mobile.index.xformUploaderErrorStatusCheckMessage": "Pictures/만이 파세요 upload 고민 많이하다가 please re-upload 또 후!! 만족해주신다니", "xform.client.xform-antd-mobile.index.xformUploaderExampleLink": "샘플 사진", "xform.client.xform-antd-mobile.index.xformUploaderUploadingStatusCheckMessage": "Pictures/만이 파세요 upload 에 Please 후!! 만족해주신다니" };
Nightwish-cn/my_leetcode
code/381.cpp
#include <bits/stdc++.h> #define INF 2000000000 using namespace std; typedef long long ll; int read(){ int f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();} while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar(); return f * x; } struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool isLeaf(TreeNode* root) { return root->left == NULL && root->right == NULL; } struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class RandomizedCollection { public: /** Initialize your data structure here. */ vector<int> vec; unordered_map<int, unordered_set<int>> mp; int siz; RandomizedCollection() { siz = 0; } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ bool insert(int val) { bool flag = mp.count(val) ? false: true; //if (!flag) mp.insert(make_pair(val, unordered_set<int>())); if (!flag) flag = mp[val].empty(); vec.push_back(val); mp[val].insert(siz); ++siz; return flag; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ bool remove(int val) { if (!mp.count(val)) return false; if (mp[val].empty()) return false; if (vec.back() == val){ mp[val].erase(siz - 1), vec.pop_back(), --siz; return true; } int id = *(mp[val].begin()); if (id != siz - 1) { mp[vec.back()].erase(siz - 1); mp[vec.back()].insert(id); vec[id] = vec.back(); } mp[val].erase(id), vec.pop_back(), --siz; return true; } /** Get a random element from the collection. */ int getRandom() { int id = rand() % siz; return vec[id]; } }; /** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection* obj = new RandomizedCollection(); * bool param_1 = obj->insert(val); * bool param_2 = obj->remove(val); * int param_3 = obj->getRandom(); */ void init(){ } void solve(){ // sol.convert(); } int main(){ init(); solve(); return 0; }
jokade/scalanative-gtk
tepl/src/main/scala/tepl/TeplTabGroup.scala
// Copyright (c) 2018. Distributed under the MIT License (see included LICENSE file). package tepl import glib.GList import scalanative.native._ import cobj._ /** * Interface for a group of [[TeplTab]]s. * * @see [[https://developer.gnome.org/tepl/stable/TeplTabGroup.html]] */ @CObj trait TeplTabGroup extends CObjWrapper { /** * Gets the list of tabs contained in this group. * If this group contains children that are not [[TeplTab]]s, those will not be present * in the returned list, i.e. it is not guaranteed that the index of a TeplTab * in the returned GList has the same child index in the group container. */ @inline final def getTabs(): GList = extern /** * Like [[getTabs]] but returns [[TeplView]]s. */ @inline final def getViews(): GList = extern /** * Like [[getTabs]] but returns [[TeplBuffer]]s. */ @inline final def getBuffers(): GList = extern /** * Returns the currently displayed tab in this group. */ @nullable @inline final def getActiveTab(): TeplTab = extern /** * Sets the active tab for this group. * * @param tab TeplTab to be made active (must be part of this group!) */ @inline final def setActiveTab(tab: TeplTab): Unit = extern /** * Returns the currently active TeplView, or null */ @nullable @inline final def getActiveView(): TeplView = extern // @inline final def getActiveBuffer(): Tepl }
migijs/m
tests/diffadd7/test.js
<filename>tests/diffadd7/test.js var path = require('path'); var fs = require('fs'); module.exports = { 'init empty': function(browser) { browser .url('file://' + path.join(__dirname, 'index.html')) .waitForElementVisible('body', 1000) .assert.containsText('#test p[ref="1"]', '2') .assert.containsText('#test p[ref="2"]', '1<span migi-uid="1">0</span>') }, 't2dd': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '3') .assert.containsText('#test p[ref="2"]', '<span migi-uid="7">1</span><span migi-uid="8">2</span><span migi-uid="1">0</span>') }, 't2dd_restore': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '2') .assert.containsText('#test p[ref="2"]', '1<span migi-uid="1">0</span>') }, 't2dt': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '3') .assert.containsText('#test p[ref="2"]', '<span migi-uid="11">1</span>2<span migi-uid="1">0</span>') }, 't2dt_restore': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '2') .assert.containsText('#test p[ref="2"]', '1<span migi-uid="1">0</span>') }, 't2ddt': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '4') .assert.containsText('#test p[ref="2"]', '<span migi-uid="14">1</span><span migi-uid="15">2</span>3<span migi-uid="1">0</span>') }, 't2ddt_restore': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '2') .assert.containsText('#test p[ref="2"]', '1<span migi-uid="1">0</span>') }, 't2ddtd': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '5') .assert.containsText('#test p[ref="2"]', '<span migi-uid="18">1</span><span migi-uid="19">2</span>3<span migi-uid="20">4</span><span migi-uid="1">0</span>') }, 't2ddtd_restore': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '2') .assert.containsText('#test p[ref="2"]', '1<span migi-uid="1">0</span>') }, 't2ddtdt': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '6') .assert.containsText('#test p[ref="2"]', '<span migi-uid="23">1</span><span migi-uid="24">2</span>3<span migi-uid="25">4</span>5<span migi-uid="1">0</span>') }, 't2ddtdt_restore': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '2') .assert.containsText('#test p[ref="2"]', '1<span migi-uid="1">0</span>') }, 't2dtd': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '4') .assert.containsText('#test p[ref="2"]', '<span migi-uid="28">1</span>2<span migi-uid="29">3</span><span migi-uid="1">0</span>') }, 't2dtd_restore': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '2') .assert.containsText('#test p[ref="2"]', '1<span migi-uid="1">0</span>') }, 't2dtdd': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '5') .assert.containsText('#test p[ref="2"]', '<span migi-uid="32">1</span>2<span migi-uid="33">3</span><span migi-uid="34">4</span><span migi-uid="1">0</span>') }, 't2dtdd_restore': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '2') .assert.containsText('#test p[ref="2"]', '1<span migi-uid="1">0</span>') }, 't2dtdt': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '5') .assert.containsText('#test p[ref="2"]', '<span migi-uid="37">1</span>2<span migi-uid="38">3</span>4<span migi-uid="1">0</span>') }, 't2dtdt_restore': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '2') .assert.containsText('#test p[ref="2"]', '1<span migi-uid="1">0</span>') }, 't2dtdtd': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '6') .assert.containsText('#test p[ref="2"]', '<span migi-uid="41">1</span>2<span migi-uid="42">3</span>4<span migi-uid="43">5</span><span migi-uid="1">0</span>') }, 't2dtdtd_restore': function(browser) { browser .click('#test strong') .assert.containsText('#test p[ref="1"]', '2') .assert.containsText('#test p[ref="2"]', '1<span migi-uid="1">0</span>') .end() }, };
michel-pi/xenforo-documentation
docs/2-1-0/d4/dec/class_x_f_1_1_entity_1_1_oembed.js
var class_x_f_1_1_entity_1_1_oembed = [ [ "_preSave", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#afe23830269d783eebc97de635fdebd10", null ], [ "getAbstractedJsonPath", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#ab8c66950699114e49781427e38968c59", null ], [ "getUrl", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#accd14bda49a1044b4d8dd93f020f11ee", null ], [ "isFailure", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#aca7c2d13862869a3538adf2d6a8fc4f5", null ], [ "isFailureRefreshRequired", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#a734d8fe6c29d0ab869e968736dc1185e", null ], [ "isRefreshRequired", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#a07d6a92ecaf46eb37e186f0c0daaf80f", null ], [ "isValid", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#a7b37efab7473a1effc29f8be2421f6e3", null ], [ "prune", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#ae16076fa15eca0d8f497bde4e80ec667", null ], [ "setAsFailure", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#a24231218a2dc2a8d3d5cf395cb5ff245", null ], [ "$failure", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#a16c694fa4a01e9dc157063bd274c327a", null ], [ "FAILURE", "d4/dec/class_x_f_1_1_entity_1_1_oembed.html#ac1386528d90fa568f7226a4e51e6d986", null ] ];
iedadata/PetDB
ROOT/petdb/wrapper/AbbreviationsWrapper.java
<gh_stars>0 package petdb.wrapper; import java.util.*; import petdb.data.*; import petdb.query.*; import petdb.criteria.*; public class AbbreviationsWrapper extends Wrapper { static ControlQuery[] queries = new ControlQuery[8]; static boolean status = false; public static int Alteration = 0; public static int RockType = 1; public static int Crystal = 2; public static int Material = 3; public static int Mineral = 4; public static int Method = 5; public static int Navigation = 6; public static int SamplingTech = 7; //public static int RimCore = "5"; static private AbbreviationsWrapper aw_instance; public static AbbreviationsWrapper getAbbreviationsWrapper() { if (aw_instance ==null) aw_instance = new AbbreviationsWrapper(); return aw_instance; } protected AbbreviationsWrapper() { controlLists = new Vector(); queries[Alteration] = new AlterationCtlQuery(); queries[RockType] = new RockTypeCtlQuery(); queries[Crystal] = new CrystalCtlQuery(); queries[Material] = new MaterialCtlQuery(); queries[Mineral] = new MineralCtlQuery(); queries[Method] = new MethodCtlQuery(); queries[Navigation] = new NavigationCtlQuery(); queries[SamplingTech] = new RockMethodCtlQuery(); int t = populate(); } protected int populate() { synchronized(controlLists) { for (int i=0; i<queries.length; i++) controlLists.add( ((ControlQuery)queries[i]).getDataSet()); return 1; } } }
wittech/libqimuikit-ios
QIMUIKit/Application/ViewController/Friend/QIMFriendTitleListCell.h
<reponame>wittech/libqimuikit-ios // // QIMFriendTitleListCell.h // qunarChatIphone // // Created by admin on 15/11/17. // // #import "QIMCommonUIFramework.h" @interface QIMFriendTitleListCell : UITableViewCell @property (nonatomic, strong) NSString *title; @property (nonatomic, strong) NSString *desc; @property (nonatomic, assign, getter=isExpanded) BOOL expanded; + (CGFloat)getCellHeight; - (void) refresh; @end
prantlf/requirejs-esm
src/transform.js
import { resolvePath as originalResolvePath } from './resolve-path' // import { parse } from 'acorn' import { parseModule } from 'meriyah' import { generate } from 'astring' import { SourceMapGenerator } from 'source-map' import convert from '@prantlf/convert-source-map' import { transformAst } from './transformer' export default function transform(text, file, { // Allow using a different plugin alias than `esm` in the source code. pluginName = 'esm', // Method to update paths of module dependencies, to prefix JavaScript module // name with `esm!`, above all. resolvePath = originalResolvePath, // ecmaVersion = 2020, sourceMap } = {}) { // const ast = parse(text, { ecmaVersion, sourceType: 'module', locations: true }) let ast = parseModule(text, { next: true, loc: true }) const options = { sourceFileName: file, pluginName, resolvePath, originalResolvePath } const { updated } = transformAst(ast, options) let code, map if (updated) { if (sourceMap === true) { sourceMap = { inline: true, content: true } } const mapGenerator = sourceMap ? new SourceMapGenerator({ file }) : undefined code = generate(ast, { sourceMap: mapGenerator }) if (sourceMap) { if (sourceMap.content) { mapGenerator.setSourceContent(file, text) } if (sourceMap.inline) { code += convert.fromObject(mapGenerator.toJSON()).toComment() } else { map = mapGenerator.toJSON() } } } else { code = text } return { code, map, updated } }
Tobisaninfo/rewrite
api-tests/src/test/java/org/ocpsoft/rewrite/config/RelocatingConfigurationProvider3.java
<reponame>Tobisaninfo/rewrite package org.ocpsoft.rewrite.config; import org.ocpsoft.rewrite.servlet.config.Path; import org.ocpsoft.rewrite.servlet.config.SendStatus; /** * @author <a href="mailto:<EMAIL>"><NAME>, III</a> * */ public class RelocatingConfigurationProvider3 implements ConfigurationProvider<Object> { @Override public int priority() { return 10; } @Override public boolean handles(final Object payload) { return true; } @Override public Configuration getConfiguration(final Object context) { return ConfigurationBuilder.begin() .addRule() .when(Path.matches("/priority")) .perform(SendStatus.code(203)) .addRule() .when(Path.matches("/priority2")) .perform(SendStatus.code(203)) .addRule() .when(Path.matches("/priority3")) .perform(SendStatus.code(203)) .addRule() .when(Path.matches("/priority4")) .perform(SendStatus.code(203)) .withPriority(-1) ; } }
FIT-Mobility/dimo-tool-suite
server-converter-model/src/main/java/de/fraunhofer/fit/ips/model/template/helper/InnerNode.java
<reponame>FIT-Mobility/dimo-tool-suite<gh_stars>1-10 package de.fraunhofer.fit.ips.model.template.helper; import de.fraunhofer.fit.ips.model.template.MultilingualPlaintext; import java.util.List; /** * @author <NAME> <<EMAIL>> */ public interface InnerNode extends StructureBase { List<StructureBase> getChildren(); MultilingualPlaintext getHeadingTitle(); }
yeoman/yeoman-app
spec/components/prompts/input-spec.js
<reponame>yeoman/yeoman-app<gh_stars>1000+ import createComponent from '../../helpers/createComponent.js'; import InputPrompt from '../../../src/renderer/components/prompts/input.jsx'; describe('InputPrompt', function () { let tree; let renderOutput; let labelComponent; let inputComponent; beforeEach(function () { tree = createComponent(InputPrompt, { defaultAnswer: 'Sushi', type: 'input', name: 'food', color: '#dd002a', message: 'What is your favourite food' }); renderOutput = tree.getRenderOutput(); labelComponent = renderOutput.props.children[0]; inputComponent = renderOutput.props.children[1]; }); describe('label', function () { it('pass options to the component', function () { expect(labelComponent.props.message).toBe('What is your favourite food'); expect(labelComponent.props.color).toBe('#dd002a'); }); }); describe('input', function () { it('pass options to the component', function () { expect(inputComponent.props.type).toBe('input'); expect(inputComponent.props.name).toBe('food'); expect(inputComponent.props.value).toBe('Sushi'); }); }); });
johngreyland262/Stealth
src/explore/ExploreDestination.hpp
<reponame>johngreyland262/Stealth // Copyright (c) 2019 2020 The Stealth Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef _EXPLOREDESTINATION_H_ #define _EXPLOREDESTINATION_H_ 1 #include "serialize.h" #include "json/json_spirit_utils.h" class ExploreDestination { public: std::vector<std::string> addresses; int required; int64_t amount; std::string type; void SetNull(); ExploreDestination(); ExploreDestination(const std::vector<std::string>& addressesIn, const int requiredIn, const int64_t& amountIn, const std::string& typeIn); void AsJSON(json_spirit::Object& objRet) const; IMPLEMENT_SERIALIZE ( READWRITE(addresses); READWRITE(required); READWRITE(amount); READWRITE(type); ) }; #endif /* _EXPLOREDESTINATION_H_ */
josemafe7/IA-BusquedaLocal
aima-core/src/main/java/aima/core/search/uninformed/DepthFirstSearch.java
package aima.core.search.uninformed; import java.util.List; import aima.core.agent.Action; import aima.core.search.framework.Metrics; import aima.core.search.framework.Node; import aima.core.search.framework.NodeExpander; import aima.core.search.framework.QueueFactory; import aima.core.search.framework.SearchForActions; import aima.core.search.framework.SearchForStates; import aima.core.search.framework.SearchUtils; import aima.core.search.framework.problem.Problem; import aima.core.search.framework.qsearch.QueueSearch; /** * Artificial Intelligence A Modern Approach (3rd Edition): page 85.<br> * <br> * Depth-first search always expands the deepest node in the current frontier of * the search tree. <br> * <br> * <b>Note:</b> Supports TreeSearch, GraphSearch, and BidirectionalSearch. Just * provide an instance of the desired QueueSearch implementation to the * constructor! * * @author <NAME> * @author <NAME> * */ public class DepthFirstSearch implements SearchForActions, SearchForStates { QueueSearch implementation; public DepthFirstSearch(QueueSearch impl) { implementation = impl; } @Override public List<Action> findActions(Problem p) { implementation.getNodeExpander().useParentLinks(true); Node node = implementation.findNode(p, QueueFactory.<Node>createLifoQueue()); return node == null ? SearchUtils.failure() : SearchUtils.getSequenceOfActions(node); } @Override public Object findState(Problem p) { implementation.getNodeExpander().useParentLinks(false); Node node = implementation.findNode(p, QueueFactory.<Node>createLifoQueue()); return node == null ? null : node.getState(); } @Override public NodeExpander getNodeExpander() { return implementation.getNodeExpander(); } @Override public Metrics getMetrics() { return implementation.getMetrics(); } }
strassek/chromiumos-platform2
cryptohome/proxy/cryptohome_proxy.cc
<filename>cryptohome/proxy/cryptohome_proxy.cc // Copyright 2019 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <base/command_line.h> #include <base/logging.h> #include <brillo/syslog_logging.h> #include "cryptohome/proxy/dbus_service.h" int main(int argc, char** argv) { // Initialize command line configuration early, as logging will require // command line to be initialized base::CommandLine::Init(argc, argv); base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); int flags = brillo::kLogToSyslog; if (cl->HasSwitch("log_to_stderr")) { flags |= brillo::kLogToStderr; } brillo::InitLog(flags); cryptohome::CryptohomeProxyDaemon proxy_daemon; return proxy_daemon.Run(); }
GeorgiMateev/twitter-user-gender-classification
src/main/java/edu/fmi/genderclassify/weka/features/BaseFeaturesFactory.java
<reponame>GeorgiMateev/twitter-user-gender-classification package edu.fmi.genderclassify.weka.features; import edu.fmi.genderclassify.dataimport.Fields; import edu.fmi.genderclassify.utils.Conversion; import weka.core.Attribute; import java.util.*; /** * A factory for creating Attribute instances for the input (base) features */ @SuppressWarnings("unused") public class BaseFeaturesFactory { private Map<String, Set<Object>> dataDomain; public BaseFeaturesFactory(Map<String, Set<Object>> dataDomain) { this.dataDomain = dataDomain; } public Attribute getUserId() { return getNumericAttribute(Fields.USER_ID); } public Attribute getGolden() { return getNominalAttribute(Fields.GOLDEN); } public Attribute getUnitState() { return getNominalAttribute(Fields.UNIT_STATE); } public Attribute getTrustedJudgements() { return getNumericAttribute(Fields.TRUSTED_JUDGEMENTS); } public Attribute getLastJudgementTime() { return getStringAttribute(Fields.LAST_JUDGEMENT_TIME); } public Attribute getGender() { return getNominalAttribute(Fields.GENDER); } public Attribute getGenderConfidence() { return getNumericAttribute(Fields.GENDER_CONFIDENCE); } public Attribute getProfileExists() { return getNominalAttribute(Fields.PROFILE_EXISTS); } public Attribute getProfileExistsConfidence() { return getNumericAttribute(Fields.PROFILE_EXISTS_CONFIDENCE); } public Attribute getProfileCreationDate() { return getStringAttribute(Fields.PROFILE_CREATION_DATE); } public Attribute getDescription() { return getStringAttribute(Fields.PROFILE_DESCRIPTION); } public Attribute getFavoritesNumber() { return getNumericAttribute(Fields.FAVORITES_NUMBER); } public Attribute getGenderGold() { return getNominalAttribute(Fields.GENDER_GOLDEN); } public Attribute getLinkColor() { return getNominalColorAttribute(Fields.LINK_COLOR); } public Attribute getUserName() { return getStringAttribute(Fields.USERNAME); } public Attribute getProfileYnGolden() { return getNominalAttribute(Fields.PROFILE_YN_VALUE_GOLDEN); } public Attribute getProfileImageLink() { return getStringAttribute(Fields.PROFILE_IMAGE_LINK); } public Attribute getRetweetsCount() { return getNumericAttribute(Fields.RETWEET_COUNT); } public Attribute getSidebarColor() { return getNominalColorAttribute(Fields.SIDEBAR_COLOR); } public Attribute getText() { return getStringAttribute(Fields.TWEET_TEXT); } public Attribute getTweetsCount() { return getNumericAttribute(Fields.TWEETS_COUNT); } public Attribute getTweetCreationDate() { return getStringAttribute(Fields.TWEET_CREATION_DATE); } public Attribute getTweetId() { return getStringAttribute(Fields.TWEET_ID); } public Attribute getTweetLocation() { return getStringAttribute(Fields.TWEET_LOCATION); } public Attribute getUserTimezone() { return getStringAttribute(Fields.USER_TIMEZONE); } private Attribute getNominalAttribute(Fields field) { Set<String> values = new HashSet<>(); for(Object obj: dataDomain.get(field.name())) values.add(Conversion.getValueAsStr(obj)); return new Attribute(field.name(), new ArrayList<>(values)); } private Attribute getNominalColorAttribute(Fields field) { Set<String> values = new HashSet<>(); for(Object obj: dataDomain.get(field.name())) values.add(Conversion.getHexColorAsNominal(obj.toString())); return new Attribute(field.name(), new ArrayList<>(values)); } private Attribute getNumericAttribute(Fields field) { return new Attribute(field.name()); } private Attribute getStringAttribute(Fields field) { return new Attribute(field.name(), true); } }
Scrappers-glitch/SS-Editor
src/main/java/com/ss/editor/ui/component/editor/state/EditorState.java
package com.ss.editor.ui.component.editor.state; import java.io.Serializable; /** * The interface for implementing a state container of Editor. * * @author JavaSaBr */ public interface EditorState extends Serializable { /** * Sets change handler. * * @param handle the change handler. */ void setChangeHandler(final Runnable handle); }
lxh888/openshop
client/web-admin/src/page/admin/adminUserEdit.js
av({ id: 'page-admin-adminUserEdit', include: ["src/common/content.js"], extend: ["common-content"], 'export': { template: "src/page/admin/adminUserEdit.html" }, 'import': function (e) { this.template(e.template); }, main: function () { this.data.admin_user_id = (function () { try { return av.router().anchor.query.id; } catch (e) { return ''; } }()); var config = {}; config.user_id = this.data.admin_user_id; // if( !this.data.agent_user_id ){ // return av.router(av.router().url, '#/').request(); // } this.data.request.data = ['ADMINUSERGET', [config]]; this.data.request.admin_option = ["ADMINOPTION", [{ sort: ["sort_asc", "update_time_asc"] }]]; }, event: { error: function (error) { console.log('error 跳转', error); return av.router(av.router().url, '#/agent-userList/').request(); }, loadEnd: function(){ //加载完成,说明有数据了,将值赋 if( this.data.data ){ this.data.selectAdminOption=this.data.data.admin_id; } }, }, data: { request: {}, data: null, admin_user_id: '', selectAdminOption: '', eventSelectAdminOptionChange:function(ele,e){ this.selectAdminOption=$(ele).val(); console.log(this.selectAdminOption); }, //按回车键时提交 keyupFunction: function () { this.eventSubmit(); }, submitLock: false, eventSubmit: function () { var _this = this; if (_this.submitLock) { return false; } else { _this.submitLock = true; } var form_input = {}; if(_this.applicationCheckEmshop() && _this.selectAdminOption=='area_agent') { form_input={admin_user_json:{}} } form_input.user_id = _this.admin_user_id; form_input.admin_id = $.trim($('[name="admin_id"]').val()); form_input.admin_user_info = $.trim($('[name="admin_user_info"]').val()); form_input.admin_user_sort = $.trim($('[name="admin_user_sort"]').val()); form_input.admin_user_state = $('[name="admin_user_state"]').is(':checked')? 0 : 1; if(_this.applicationCheckEmshop() && _this.selectAdminOption=='area_agent') { form_input.admin_user_json.show_region_order = $('[name="show_region_order"]').is(':checked')? 1 : 0; } try { if (form_input.user_id == '') throw "用户ID异常"; } catch (err) { layer.msg(err, { icon: 5, time: 2000 }); return _this.submitLock = false; } //console.log(form_input); //提交数据 this.submit({ method: "submit", request: ["ADMINUSEREDIT", [form_input]], error: function () { _this.submitLock = false; }, success: function () { _this.submitLock = false; //刷新页面 av().render("refresh").run(); } }); } } });
zaikio/keyline-gem
lib/keyline/resources/production/order.rb
module Keyline::Production class Order include Jeweler::Resource attributes :reference, :custom_references, :custom_ofer_text, :due_at, :confirmed_at, :state singleton_associations :customer end end
AbyteofteA/MiteVox
engine/CodeSafety/src/ensureValue.h
<reponame>AbyteofteA/MiteVox #ifndef ENSUREVALUE_H #define ENSUREVALUE_H namespace safety { /// <summary> /// Ensures that the value is within the inclusive range of [rangeStart, rangeEnd]. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <param name="rangeStart"></param> /// <param name="rangeEnd"></param> /// <returns></returns> template <typename T> T ensureRange(T value, T rangeStart, T rangeEnd) { if (value < rangeStart) { value = rangeStart; } else if (value > rangeEnd) { value = rangeEnd; } return value; } /// <summary> /// Ensures that the value is at least minimumValue. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <param name="minimumValue"></param> /// <returns></returns> template <typename T> T ensureMinimum(T value, T minimumValue) { if (value < minimumValue) { value = minimumValue; } return value; } /// <summary> /// Ensures that the value doesn't exceed maximumValue. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <param name="maximumValue"></param> /// <returns></returns> template <typename T> T ensureMaximum(T value, T maximumValue) { if (value > maximumValue) { value = maximumValue; } return value; } template <typename T> T ensureOddDown(T value) { if (value % 2 == 0) { value = value - 1; } return value; } template <typename T> T ensureOddUp(T value) { if (value % 2 == 0) { value = value + 1; } return value; } template <typename T> T ensureEvenDown(T value) { if (value % 2 == 1) { value = value - 1; } return value; } template <typename T> T ensureEvenUp(T value) { if (value % 2 == 1) { value = value + 1; } return value; } } #endif
houzeyu2683/KMLT
BMSMT/network/v1/__model__.py
## ## Packages. import torch, torchvision import torch.nn as nn ## ## The [model] class. class model(torch.nn.Module): def __init__(self): super(model, self).__init__() pass self.layer = nn.Sequential( torchvision.models.resnet18(pretrained=True), nn.Linear(1000, 24) ) pass def forward(self, feature): score = self.layer(feature) pass output = score return(output) def load(self, path): weight = torch.load(path, map_location='cpu') self.load_state_dict(weight) pass
jdsjlzx/365browser
app/src/main/java/org/chromium/chrome/browser/preferences/SearchEngineAdapter.java
<reponame>jdsjlzx/365browser // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.preferences; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.LayoutInflater; import android.view.View; import android.view.View.AccessibilityDelegate; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.BaseAdapter; import android.widget.RadioButton; import android.widget.TextView; import org.chromium.chrome.R; import org.chromium.chrome.browser.preferences.website.ContentSetting; import org.chromium.chrome.browser.preferences.website.GeolocationInfo; import org.chromium.chrome.browser.preferences.website.SingleWebsitePreferences; import org.chromium.chrome.browser.preferences.website.WebsitePreferenceBridge; import org.chromium.chrome.browser.search_engines.TemplateUrlService; import org.chromium.chrome.browser.search_engines.TemplateUrlService.LoadListener; import org.chromium.chrome.browser.search_engines.TemplateUrlService.TemplateUrl; import org.chromium.ui.text.SpanApplier; import org.chromium.ui.text.SpanApplier.SpanInfo; import java.util.List; /** * A custom adapter for listing search engines. */ public class SearchEngineAdapter extends BaseAdapter implements LoadListener, OnClickListener { /** * A callback for reporting progress to the owner. */ public interface SelectSearchEngineCallback { /** * Called when the search engine data has loaded and we've determined the currently active * one. * @param name Provides the name of it (with a simplified URL in parenthesis). */ void currentSearchEngineDetermined(String name); /** * Called when the dialog should be dismissed. */ void onDismissDialog(); } // The current context. private Context mContext; // The layout inflater to use for the custom views. private LayoutInflater mLayoutInflater; // The callback to use for notifying caller of progress. private SelectSearchEngineCallback mCallback; // The list of available search engines. private List<TemplateUrl> mSearchEngines; // The position (index into mSearchEngines) of the currently selected search engine. Can be -1 // if current search engine is managed and set to something other than the pre-populated values. private int mSelectedSearchEnginePosition = -1; /** * Construct a SearchEngineAdapter. * @param context The current context. * @param callback The callback to use to communicate back. */ public SearchEngineAdapter(Context context, SelectSearchEngineCallback callback) { mContext = context; mLayoutInflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); mCallback = callback; initEntries(); } // Used for testing. String getValueForTesting() { return Integer.toString(mSelectedSearchEnginePosition); } void setValueForTesting(String value) { searchEngineSelected(Integer.parseInt(value)); } /** * Initialize the search engine list. */ private void initEntries() { TemplateUrlService templateUrlService = TemplateUrlService.getInstance(); if (!templateUrlService.isLoaded()) { templateUrlService.registerLoadListener(this); templateUrlService.load(); return; // Flow continues in onTemplateUrlServiceLoaded below. } // Fetch all the search engine info and the currently active one. mSearchEngines = templateUrlService.getLocalizedSearchEngines(); int searchEngineIndex = templateUrlService.getDefaultSearchEngineIndex(); // Convert the TemplateUrl index into an index into mSearchEngines. mSelectedSearchEnginePosition = -1; for (int i = 0; i < mSearchEngines.size(); ++i) { if (mSearchEngines.get(i).getIndex() == searchEngineIndex) { mSelectedSearchEnginePosition = i; } } // Report back what is selected. String name = ""; if (mSelectedSearchEnginePosition > -1) { TemplateUrl templateUrl = mSearchEngines.get(mSelectedSearchEnginePosition); name = getSearchEngineNameAndDomain(mContext.getResources(), templateUrl); } mCallback.currentSearchEngineDetermined(name); } private int toIndex(int position) { return mSearchEngines.get(position).getIndex(); } /** * @return The name of the search engine followed by the domain, e.g. "Google (google.co.uk)". */ private static String getSearchEngineNameAndDomain(Resources res, TemplateUrl searchEngine) { String title = searchEngine.getShortName(); if (!searchEngine.getKeyword().isEmpty()) { title = res.getString(R.string.search_engine_name_and_domain, title, searchEngine.getKeyword()); } return title; } // BaseAdapter: @Override public int getCount() { return mSearchEngines.size(); } @Override public Object getItem(int pos) { TemplateUrl templateUrl = mSearchEngines.get(pos); return getSearchEngineNameAndDomain(mContext.getResources(), templateUrl); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (convertView == null) { view = mLayoutInflater.inflate(R.layout.search_engine, null); } view.setOnClickListener(this); view.setTag(position); // TODO(finnur): There's a tinting bug in the AppCompat lib (see http://crbug.com/474695), // which causes the first radiobox to always appear selected, even if it is not. It is being // addressed, but in the meantime we should use the native RadioButton instead. RadioButton radioButton = (RadioButton) view.findViewById(R.id.radiobutton); // On Lollipop this removes the redundant animation ring on selection but on older versions // it would cause the radio button to disappear. // TODO(finnur): Remove the encompassing if statement once we go back to using the AppCompat // control. final boolean selected = position == mSelectedSearchEnginePosition; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { radioButton.setBackgroundResource(0); } radioButton.setChecked(selected); TextView description = (TextView) view.findViewById(R.id.description); TemplateUrl templateUrl = mSearchEngines.get(position); Resources resources = mContext.getResources(); description.setText(getSearchEngineNameAndDomain(resources, templateUrl)); // To improve the explore-by-touch experience, the radio button is hidden from accessibility // and instead, "checked" or "not checked" is read along with the search engine's name, e.g. // "google.com checked" or "google.com not checked". radioButton.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); description.setAccessibilityDelegate(new AccessibilityDelegate() { @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); event.setChecked(selected); } @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(host, info); info.setCheckable(true); info.setChecked(selected); } }); TextView link = (TextView) view.findViewById(R.id.link); link.setVisibility(selected ? View.VISIBLE : View.GONE); if (selected) { ForegroundColorSpan linkSpan = new ForegroundColorSpan( resources.getColor(R.color.pref_accent_color)); if (LocationSettings.getInstance().isSystemLocationSettingEnabled()) { String message = mContext.getString( locationEnabled(position, true) ? R.string.search_engine_location_allowed : R.string.search_engine_location_blocked); SpannableString messageWithLink = new SpannableString(message); messageWithLink.setSpan(linkSpan, 0, messageWithLink.length(), 0); link.setText(messageWithLink); } else { link.setText(SpanApplier.applySpans( mContext.getString(R.string.android_location_off), new SpanInfo("<link>", "</link>", linkSpan))); } link.setOnClickListener(this); } return view; } // TemplateUrlService.LoadListener @Override public void onTemplateUrlServiceLoaded() { TemplateUrlService.getInstance().unregisterLoadListener(this); initEntries(); } // OnClickListener: @Override public void onClick(View view) { if (view.getTag() == null) { onLocationLinkClicked(); } else { searchEngineSelected((int) view.getTag()); } } private void searchEngineSelected(int position) { // First clean up any automatically added permissions (if any) for the previously selected // search engine. SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); if (sharedPreferences.getBoolean(PrefServiceBridge.LOCATION_AUTO_ALLOWED, false)) { if (locationEnabled(mSelectedSearchEnginePosition, false)) { String url = TemplateUrlService.getInstance().getSearchEngineUrlFromTemplateUrl( toIndex(mSelectedSearchEnginePosition)); WebsitePreferenceBridge.nativeSetGeolocationSettingForOrigin( url, url, ContentSetting.DEFAULT.toInt(), false); } sharedPreferences.edit().remove(PrefServiceBridge.LOCATION_AUTO_ALLOWED).apply(); } // Record the change in search engine. mSelectedSearchEnginePosition = position; TemplateUrlService.getInstance().setSearchEngine(toIndex(mSelectedSearchEnginePosition)); // Report the change back. TemplateUrl templateUrl = mSearchEngines.get(mSelectedSearchEnginePosition); mCallback.currentSearchEngineDetermined(getSearchEngineNameAndDomain( mContext.getResources(), templateUrl)); notifyDataSetChanged(); } private void onLocationLinkClicked() { if (!LocationSettings.getInstance().isSystemLocationSettingEnabled()) { mContext.startActivity( LocationSettings.getInstance().getSystemLocationSettingsIntent()); } else { Intent settingsIntent = PreferencesLauncher.createIntentForSettingsPage( mContext, SingleWebsitePreferences.class.getName()); String url = TemplateUrlService.getInstance().getSearchEngineUrlFromTemplateUrl( toIndex(mSelectedSearchEnginePosition)); Bundle fragmentArgs = SingleWebsitePreferences.createFragmentArgsForSite(url); fragmentArgs.putBoolean(SingleWebsitePreferences.EXTRA_LOCATION, locationEnabled(mSelectedSearchEnginePosition, true)); settingsIntent.putExtra(Preferences.EXTRA_SHOW_FRAGMENT_ARGUMENTS, fragmentArgs); mContext.startActivity(settingsIntent); } mCallback.onDismissDialog(); } private boolean locationEnabled(int position, boolean checkGeoHeader) { if (position == -1) return false; String url = TemplateUrlService.getInstance().getSearchEngineUrlFromTemplateUrl( toIndex(position)); GeolocationInfo locationSettings = new GeolocationInfo(url, null, false); ContentSetting locationPermission = locationSettings.getContentSetting(); // Handle the case where the geoHeader being sent when no permission has been specified. if (locationPermission == ContentSetting.ASK && checkGeoHeader) { return PrefServiceBridge.isGeoHeaderEnabledForUrl(mContext, url, false); } return locationPermission == ContentSetting.ALLOW; } }
iotechn/unimall-App-H5
unimall-data/src/main/java/com/iotechn/unimall/data/mapper/AddressMapper.java
<filename>unimall-data/src/main/java/com/iotechn/unimall/data/mapper/AddressMapper.java package com.iotechn.unimall.data.mapper; import com.dobbinsoft.fw.support.mapper.IMapper; import com.iotechn.unimall.data.domain.AddressDO; /* @author kbq @date 2019/7/4 - 22:09 */ public interface AddressMapper extends IMapper<AddressDO> { }
marazmarci/belatheblob
core/src/hu/marazmarci/belatheblob/gui/HUD.java
package hu.marazmarci.belatheblob.gui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.TextureData; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import hu.marazmarci.belatheblob.main.GameMain; import hu.marazmarci.belatheblob.main.GameMain.GameVariant; import hu.marazmarci.belatheblob.states.levels.Level1; import static hu.marazmarci.belatheblob.main.GameMain.time; import static hu.marazmarci.belatheblob.states.levels.Level1.frame; import static hu.marazmarci.belatheblob.states.levels.Level1.player; public class HUD { //private TextureRegion container; private TextureRegion[] font, blocks; private TextureRegion crystal, heart, heart_empty; private Pixmap smallObject; private int smallObjectWidth, smallObjectHeight; private Texture bigObject, overlay; private int android; private long nextTileDraw = 0; //private Sound pop; float bigObjX, bigObjY; public HUD() { android = 0; //GameMain.android ? 40 : 0; //pop = GameMain.res.getSound("slimejump1"); Texture tex = GameMain.res.getTexture("hud"); heart = new TextureRegion(GameMain.res.getTexture("heart")); heart_empty = new TextureRegion(GameMain.res.getTexture("heart_empty")); overlay = new Texture(GameMain.WIDTH, GameMain.HEIGHT, Format.RGBA4444); TextureData smallObjTex = null; if (GameMain.gameVariant == GameVariant.ANNA) { smallObjTex = heart.getTexture().getTextureData(); bigObject = GameMain.res.getTexture("ztepowerbank"); } else if (GameMain.gameVariant == GameVariant.LIVIA) { smallObjTex = GameMain.res.getTexture("mushroom").getTextureData(); bigObject = GameMain.res.getTexture("grandma"); } else if (GameMain.gameVariant == GameVariant.MAG) { smallObjTex = GameMain.res.getTexture("beer").getTextureData(); bigObject = GameMain.res.getTexture("kozel"); } else { //GameVariant.DEFAULT smallObjTex = GameMain.res.getTexture("beer").getTextureData(); bigObject = GameMain.res.getTexture("kozel"); } bigObjX = GameMain.WIDTH/2f-bigObject.getWidth()/2f; bigObjY = GameMain.HEIGHT/2f-bigObject.getHeight()/2f; if (!smallObjTex.isPrepared()) smallObjTex.prepare(); smallObject = smallObjTex.consumePixmap(); smallObjectWidth = smallObject.getWidth(); smallObjectHeight = smallObject.getHeight(); smallObjTex.disposePixmap(); //TODO ????? blocks = new TextureRegion[3]; for(int i = 0; i < blocks.length; i++) { blocks[i] = new TextureRegion(tex, 32 + i * 16, 0, 16, 16); } crystal = new TextureRegion(tex, 80, 0, 16, 16); font = new TextureRegion[13]; for(int i = 0; i < 6; i++) { font[i] = new TextureRegion(tex, 32 + i * 9, 16, 9, 9); } for(int i = 0; i < 5; i++) { font[i + 6] = new TextureRegion(tex, 32 + i * 9, 25, 9, 9); } font[11] = new TextureRegion(tex, 32 + (6) * 9, 16, 9, 9); font[12] = new TextureRegion(tex, 32 + (5) * 9, 25, 9, 9); } public void render(SpriteBatch sb, ShapeRenderer sr) { sb.begin(); // draw container ////spriteBatch.draw(container, 32, 200); // draw blocks /*short bits = player.getBody().getFixtureList().first().getFilterData().maskBits; if((bits & B2DVars.BIT_RED_BLOCK) != 0) { spriteBatch.draw(blocks[0], 40, 208); } else if((bits & B2DVars.BIT_GREEN_BLOCK) != 0) { spriteBatch.draw(blocks[1], 40, 208); } else if((bits & B2DVars.BIT_BLUE_BLOCK) != 0) { spriteBatch.draw(blocks[2], 40, 208); }*/ // draw crystal sb.draw(crystal, 7, 280+android); // draw crystal amount drawString(sb, player.getScore() + " / " + player.getMaxScore() + " - " + (Level1.collected==0?"":Level1.collected+""), 28, 283+android); //if(Level1.collected != 0) drawString(spriteBatch, Level1.collected+"", 10, 266+android); drawString(sb, ((float)(int)(time*10)/10)+"", 336, 302+android); //drawString(spriteBatch, "HP: " + player.HP, 0, 300); for (int i=0; i<player.HP; i++) { sb.draw(heart, 8 + i*16, 300+android); } for (int i = player.HP; i<20; i++) { sb.draw(heart_empty, 8 + i*16, 300+android); } //if (Level1.debug) { drawString(sb, GameMain.FPS+"", 615, 305+android); sb.end(); //Level1.gameOver = true; //TODO remove //Level1.gameOverType = false; if (GameMain.gameOver) { Gdx.gl.glEnable(GL20.GL_BLEND); Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); sr.begin(ShapeType.Filled); if (GameMain.gameOverType) { //HALÁL sr.setColor(1f, 0, 0, 0.5f); sr.rect(0, 0, GameMain.WIDTH, GameMain.HEIGHT); } else { //WIN //TODO ANNA->TÖLTÕ, MAG->SÖR, LÍVIACUCC, PUBLIC CUCC, TheVR cucc??? if (frame>nextTileDraw) { nextTileDraw = frame+Level1.random.nextInt(20)+10; //pop.play(); //Pixmap.setBlending(Pixmap.Blending.SourceOver); overlay.draw(smallObject, Level1.random.nextInt(GameMain.WIDTH/smallObjectWidth+1)*smallObjectWidth, (Level1.random.nextInt(GameMain.HEIGHT/smallObjectHeight+2)-2)*smallObjectHeight); //TODO random } sr.setColor(0, 1f, 0, 0.5f); sr.rect(0, 0, GameMain.WIDTH, GameMain.HEIGHT); } sr.end(); if (!GameMain.gameOverType) { sb.begin(); sb.draw(overlay, 0, 0); sb.draw(bigObject, bigObjX, bigObjY); sb.end(); } Gdx.gl.glDisable(GL20.GL_BLEND); } } private void drawString(SpriteBatch sb, String s, float x, float y) { for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c == '/') c = 10; //. -> 11 : -> 12 else if(c == '.') c = 11; else if(c == ':') c = 12; else if(c >= '0' && c <= '9') c -= '0'; else continue; sb.draw(font[c], x + i * 9, y); } } }
ging/ackuaria
common/mdb/eventsRegistry.js
<filename>common/mdb/eventsRegistry.js var db = require('./dataBase').db; var getEvent = exports.getEvent = function(id, callback) { "use strict"; db.events.findOne({ _id: db.ObjectId(id) }, function(err, event) { if (event === undefined) { console.log('Event ', id, ' not found'); } if (callback !== undefined) { callback(event); } }); }; var hasEvent = exports.hasEvent = function(id, callback) { "use strict"; getEvent(id, function(event) { if (event === undefined) { callback(false); } else { callback(true); } }); }; exports.addEvent = function(event, callback) { "use strict"; db.events.save(event, function(error, saved) { if (error) console.log('MongoDB: Error adding event: ', error); if (callback !== undefined) { callback(saved); } }); }; /* * Removes a determined room from the data base. */ var removeEvent = exports.removeEvent = function(id, callback) { "use strict"; hasEvent(id, function(hasEvent) { if (hasEvent) { db.events.remove({ _id: db.ObjectId(id) }, function(error, removed) { if (error) console.log('MongoDB: Error removing event: ', error); callback("yes"); }); } }); }; exports.removeEventsByRoom = function(roomId, callback) { db.events.find({ room: roomId }).toArray(function(err, events) { if (err || !events) { console.log("There are no events for room " + roomId); } else { for (var i in events) { removeEvent(events[i]._id, function(removed) { console.log(removed); }); } callback("Removed all events in room " + roomId); } }) }; exports.getEvents = function(callback) { db.events.find({}).toArray(function(err, events) { if (err) { console.log("Error: " + err); } else { callback(events); } }); }; exports.getEventsOfRoom = function(roomId, callback) { db.events.find({ room: roomId }).toArray(function(err, events) { if (err || !events) { console.log("There are no events for room " + roomId); } else { callback(events); } }) }; exports.getEventsOfUser = function(userId, callback) { db.events.find({ user: userId }).toArray(function(err, events) { if (err || !events) { console.log("There are no events for user " + userId); } else { callback(events); } }) }; exports.getEventsOfType = function(type, callback) { db.events.find({ type: type }).toArray(function(err, events) { if (err || !events) { console.log("There are no events of type " + type); } else { callback(events); } }) }; exports.getEventsByDate = function(timestampInit, timestampFinal, callback) { if (timestampInit && timestampFinal) { db.events.find({ timestamp: { $gt: timestampInit, $lt: timestampFinal } }).toArray(function(err, events) { if (err || !events) { console.log("There are no events on this date "); } else { callback(events); } }) } else if (timestampInit && !timestampFinal) { db.events.find({ timestamp: { $gt: timestampInit } }).toArray(function(err, events) { if (err || !events) { console.log("There are no events on this date"); } else { callback(events); } }) } else if (timestampFinal && !timestampinit) { db.events.find({ timestamp: { $lt: timestampFinal } }).toArray(function(err, events) { if (err || !events) { console.log("There are no events on this date"); } else { callback(events); } }) } }; exports.getEventsByDateAndType = function(timestampInit, timestampFinal, type, callback) { if (timestampInit && timestampFinal) { db.events.find({ timestamp: { $gt: timestampInit, $lt: timestampFinal }, type: type }).toArray(function(err, events) { if (err || !events) { console.log("There are no events on this date "); } else { callback(events); } }) } else if (timestampInit && !timestampFinal) { db.events.find({ timestamp: { $gt: timestampInit } }).toArray(function(err, events) { if (err || !events) { console.log("There are no events on this date"); } else { callback(events); } }) } else if (timestampFinal && !timestampinit) { db.events.find({ timestamp: { $lt: timestampFinal } }).toArray(function(err, events) { if (err || !events) { console.log("There are no events on this date"); } else { callback(events); } }) } }; exports.removeAllEvents = function() { db.events.remove(); //callback("All events removed succesfully"); };
jmolloy/pedigree
src/system/kernel/debugger/commands/LocksCommand.cc
<reponame>jmolloy/pedigree /* * Copyright (c) 2008 <NAME>, <NAME>, <NAME> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "LocksCommand.h" #include <utilities/utility.h> #include <processor/Processor.h> #include <linker/KernelElf.h> #include <utilities/demangle.h> #include <processor/Processor.h> #include <Backtrace.h> LocksCommand g_LocksCommand; extern Spinlock g_MallocLock; // This is global because we need to rely on it before the constructor is called. static bool g_bReady = false; LocksCommand::LocksCommand() : DebuggerCommand(), m_bAcquiring(false) { memset(m_pDescriptors, 0, sizeof(LockDescriptor)*MAX_DESCRIPTORS); } LocksCommand::~LocksCommand() { } void LocksCommand::autocomplete(const HugeStaticString &input, HugeStaticString &output) { } bool LocksCommand::execute(const HugeStaticString &input, HugeStaticString &output, InterruptState &state, DebuggerIO *pScreen) { // If we see just "locks", no parameters were matched. uintptr_t address = 0; if (input != "locks") { // Is it an address? address = input.intValue(); if (address == 0) { // No, try a symbol name. // TODO. output = "Not a valid address: `"; output += input; output += "'.\n"; return true; } } for (int i = 0; i < MAX_DESCRIPTORS; i++) { LockDescriptor *pD = &m_pDescriptors[i]; if (pD->used == false) continue; if (address && address != reinterpret_cast<uintptr_t>(pD->pLock)) continue; output += "Lock at "; output.append(reinterpret_cast<uintptr_t>(pD->pLock), 16); output += ":\n"; for (size_t i = 0; i < pD->n; i++) { uintptr_t symStart = 0; const char *pSym = KernelElf::instance().globalLookupSymbol(pD->ra[i], &symStart); if (pSym == 0) { output += " - "; output.append(pD->ra[i], 16); } else { LargeStaticString sym(pSym); output += " - ["; output.append(symStart, 16); output += "] "; static symbol_t symbol; demangle(sym, &symbol); output += static_cast<const char*>(symbol.name); } output += "\n"; } } if (address) { Spinlock *pLock = reinterpret_cast<Spinlock*>(address); output += "Lock state:\n"; output += " m_bInterrupts: "; output += pLock->m_bInterrupts; output += "\n m_Atom:"; output += (pLock->m_Atom) ? "Unlocked" : "Locked"; output += "\n m_Ra: "; output.append(pLock->m_Ra, 16); output += "\n m_bAvoidTracking: "; output += pLock->m_bAvoidTracking; output += "\n m_Magic: "; output.append(pLock->m_Magic, 16); output += "\n"; } return true; } void LocksCommand::setReady() { g_bReady = true; } bool g_bMallocLockAcquired = false; void LocksCommand::lockAcquired(Spinlock *pLock) { if (!g_bReady || m_bAcquiring) return; m_bAcquiring = true; // Get a backtrace. Backtrace bt; bt.performBpBacktrace(0, 0); LockDescriptor *pD = 0; for (int i = 0; i < MAX_DESCRIPTORS; i++) { if (m_pDescriptors[i].used == false) { pD = &m_pDescriptors[i]; break; } } if (pD) { pD->used = true; pD->pLock = pLock; memcpy(&pD->ra, bt.m_pReturnAddresses, NUM_BT_FRAMES*sizeof(uintptr_t)); pD->n = bt.m_nStackFrames; } m_bAcquiring = false; } void LocksCommand::lockReleased(Spinlock *pLock) { if (!g_bReady || m_bAcquiring) return; m_bAcquiring = true; for (int i = 0; i < MAX_DESCRIPTORS; i++) { if (m_pDescriptors[i].used == true && m_pDescriptors[i].pLock == pLock) { m_pDescriptors[i].used = false; } } m_bAcquiring = false; }
hanhlinux/skalibs
src/libstddjb/tai_unpack.c
<reponame>hanhlinux/skalibs<filename>src/libstddjb/tai_unpack.c /* ISC license. */ #include <skalibs/uint64.h> #include <skalibs/tai.h> void tai_unpack (char const *s, tai *t) { uint64_unpack_big(s, &t->x) ; }
cybergarage/CyberX3D4CC
include/cybergarage/x3d/Parser.h
/****************************************************************** * * CyberX3D for C++ * * Copyright (C) <NAME> 1996-2007 * * File: Parser.h * ******************************************************************/ #ifndef _CX3D_PARSER_H_ #define _CX3D_PARSER_H_ #include <cybergarage/x3d/CyberX3DConfig.h> #include <cybergarage/x3d/Scene.h> #include <cybergarage/x3d/ParserNode.h> #include <cybergarage/x3d/ParserResult.h> #include <cybergarage/x3d/PROTO.h> #include <cybergarage/x3d/DEF.h> #include <cybergarage/x3d/StringUtil.h> #include <cybergarage/x3d/LinkedListNode.h> namespace CyberX3D { const int DEFAULT_LEX_LINE_BUFFER_SIZE = 64*1024; class Parser : public Scene, public ParserResult, public LinkedListNode<Parser> { LinkedList<ParserNode> mParserNodeList; LinkedList<DEF> mDEFList; LinkedList<PROTO> mPROTOList; String mDefName; bool mbParsering; public: Parser(); virtual ~Parser(); /////////////////////////////////////////////// // Praser action /////////////////////////////////////////////// void addNode(Node *node, bool initialize = true); void addNodeAtFirst(Node *node, bool initialize = true); void moveNode(Node *node); void moveNodeAtFirst(Node *node); void pushNode(Node *node, int type); void popNode(); Node *getCurrentNode(); int getCurrentNodeType() const; int getPrevNodeType() const; void beginParse(); void endParse(); /////////////////////////////////////////////// // DEF /////////////////////////////////////////////// void setDefName(const char *name) { mDefName.setValue(name); } const char *getDefName() const { return mDefName.getValue(); } /////////////////////////////////////////////// // Load /////////////////////////////////////////////// void setParseringState(bool state) { mbParsering = state; } bool getParseringState() { return mbParsering; } int getNLines(const char *fileName) const; virtual bool load(const char *fileName, void (*callbackFn)(int nLine, void *info) = NULL, void *callbackFnInfo = NULL) = 0; /////////////////////////////////////////////// // DEF /////////////////////////////////////////////// DEF *getDEFs() const; const char *getDEFString(const char *name) const; void addDEF(DEF *def); void addDEF(const char *name, const char *string); void deleteDEFs(); /////////////////////////////////////////////// // PROTO /////////////////////////////////////////////// PROTO *getPROTOs() const; PROTO *getPROTO(const char *name) const; void addPROTO(PROTO *proto); void deletePROTOs(); }; } #endif
stanfortonski/Procedural-Terrain-Generator-OpenGL
src/engine/buffer/RenderBuffer.hpp
<reponame>stanfortonski/Procedural-Terrain-Generator-OpenGL /* Copyright (c) 2020 by <NAME> */ #ifndef RENDER_BUFFER_HPP #define RENDER_BUFFER_HPP 1 #include <GL/glew.h> namespace Engine { class RenderBuffer { void clear(); void swap(const RenderBuffer & fb); protected: unsigned RBO = 0; unsigned * amount; public: RenderBuffer(); RenderBuffer(const RenderBuffer & fb); RenderBuffer & operator=(const RenderBuffer & fb); virtual ~RenderBuffer(); virtual void create(const unsigned & width, const unsigned & height); virtual void remove(); virtual void attach() const; unsigned getId() const{return RBO;} bool isCreated() const{return RBO != 0;} void bind() const{glBindRenderbuffer(GL_RENDERBUFFER, RBO);} static void unbind(){glBindFramebuffer(GL_RENDERBUFFER, 0);} }; } #endif
dugenkui03/nadel
src/main/java/graphql/nadel/engine/transformation/UnapplyResult.java
package graphql.nadel.engine.transformation; import graphql.Internal; import graphql.nadel.result.ExecutionResultNode; import graphql.util.TraversalControl; @Internal public class UnapplyResult { private final ExecutionResultNode node; private final TraversalControl traversalControl; public UnapplyResult(ExecutionResultNode node, TraversalControl traversalControl) { this.node = node; this.traversalControl = traversalControl; } public ExecutionResultNode getNode() { return node; } public TraversalControl getTraversalControl() { return traversalControl; } }
lechium/iOS1351Headers
usr/libexec/CarPlay/CARHomeKitDoorStateCharacteristic.h
<reponame>lechium/iOS1351Headers // // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import "CARHomeKitCharacteristic.h" @interface CARHomeKitDoorStateCharacteristic : CARHomeKitCharacteristic { } + (id)stringForDoorState:(long long)arg1; // IMP=0x000000010007f4f0 + (id)characteristicFormats; // IMP=0x000000010007f3c4 + (id)characteristicFormat; // IMP=0x000000010007f3b8 + (void)load; // IMP=0x000000010007f384 @property(nonatomic) long long doorStateValue; - (id)formatedValue; // IMP=0x000000010007f414 @end
teslabs/sdk-trusted-firmware-m
platform/ext/target/stm/common/stm32u5xx/bl2/stm32u5xx_hal_msp.c
<reponame>teslabs/sdk-trusted-firmware-m<filename>platform/ext/target/stm/common/stm32u5xx/bl2/stm32u5xx_hal_msp.c /** ****************************************************************************** * @file stm32u5xx_hal_msp.c * @author MCD Application Team * @brief HAL MSP module. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "boot_hal_cfg.h" /** @addtogroup STM32U5xx_HAL_Examples * @{ */ /** @defgroup RTC_ActiveTamper * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constant ----------------------------------------------------------*/ /** @defgroup HAL_MSP_Private_Constant * @{ */ const RCC_OscInitTypeDef RCC_OscInitStruct_RTC = { .OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE, .HSEState = 0, #if defined(RTC_CLOCK_SOURCE_LSE) .LSEState = RCC_LSE_ON, .LSIState = RCC_LSI_OFF, #elif defined (RTC_CLOCK_SOURCE_LSI) .LSEState = RCC_LSE_OFF, .LSIState = RCC_LSI_ON, #else #error #endif /* defined (RTC_CLOCK_SOURCE_LSI) */ .HSIState = 0, .HSICalibrationValue = 0, .LSIDiv = 0, .MSIState = 0, .MSICalibrationValue = 0, .MSIClockRange = 0, .MSIKClockRange = 0, .HSI48State = 0, .SHSIState = 0, .MSIKState = 0, .PLL = { .PLLState = RCC_PLL_NONE, .PLLSource = 0, .PLLM = 0, .PLLMBOOST = 0, . PLLN = 0, .PLLP = 0, .PLLQ = 0, .PLLR = 0, .PLLRGE = 0, .PLLFRACN = 0 } }; const RCC_PeriphCLKInitTypeDef PeriphClkInitStruct_RTC = { .PeriphClockSelection = RCC_PERIPHCLK_RTC, .PLL2 = {0}, .PLL3 = {0}, .Usart1ClockSelection = 0, .Usart2ClockSelection = 0, .Usart3ClockSelection = 0, .Uart4ClockSelection = 0, .Uart5ClockSelection = 0, .Lpuart1ClockSelection = 0, .I2c1ClockSelection = 0, .I2c2ClockSelection = 0, .I2c3ClockSelection = 0, .I2c4ClockSelection = 0, .Lptim1ClockSelection = 0, .Lptim2ClockSelection = 0, .Lptim34ClockSelection = 0, .Fdcan1ClockSelection = 0, .Mdf1ClockSelection = 0, .Adf1ClockSelection = 0, .Sai1ClockSelection = 0, .Sai2ClockSelection = 0, .RngClockSelection = 0, .SaesClockSelection = 0, .Clk48ClockSelection = 0, .SdmmcClockSelection = 0, .AdcDacClockSelection = 0, .Dac1ClockSelection = 0, .OspiClockSelection = 0, .Spi1ClockSelection = 0, .Spi2ClockSelection = 0, .Spi3ClockSelection = 0, #if defined(RTC_CLOCK_SOURCE_LSE) .RTCClockSelection = RCC_RTCCLKSOURCE_LSE, #elif defined (RTC_CLOCK_SOURCE_LSI) .RTCClockSelection = RCC_RTCCLKSOURCE_LSI, #else #error #endif /* RTC_CLOCK_SOURCE_LSE */ }; /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @defgroup HAL_MSP_Private_Functions * @{ */ /** * @brief RTC MSP Initialization * This function configures the hardware resources used in this example: * - Peripheral's clock enable * @param hrtc: RTC handle pointer * @retval None */ void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc) { __HAL_RCC_PWR_CLK_ENABLE(); HAL_PWR_EnableBkUpAccess(); /* not required to be removed */ __HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_HIGH); /* Reset the whole backup domain, RTC included */ if (HAL_RCC_OscConfig((RCC_OscInitTypeDef *)&RCC_OscInitStruct_RTC) != HAL_OK) { Error_Handler(); } if (HAL_RCCEx_PeriphCLKConfig((RCC_PeriphCLKInitTypeDef *)&PeriphClkInitStruct_RTC) != HAL_OK) { Error_Handler(); } /* Enable RTC Clock */ __HAL_RCC_RTC_ENABLE(); /* Enable RTC APB clock */ __HAL_RCC_RTCAPB_CLK_ENABLE(); HAL_NVIC_SetPriority(TAMP_IRQn, 0x4, 0); HAL_NVIC_EnableIRQ(TAMP_IRQn); } /** * @brief RTC MSP De-Initialization * This function freeze the hardware resources used in this example: * - Disable the Peripheral's clock * @param hrtc: RTC handle pointer * @retval None */ void HAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc) { /*##-1- Reset peripherals ##################################################*/ __HAL_RCC_RTC_DISABLE(); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
break-through/RL_Reading_Group
RLSurveyFigFiveJava/src/rl/agents/DynaQLearningAgent.java
package rl.agents; import rl.env.IEnvironment; import rl.env.RLException; import util.EqualDistribution; import util.Pair; import java.util.*; public final class DynaQLearningAgent<S, A> extends IQLearningAgent<S, A> { private final int k; public DynaQLearningAgent( IEnvironment<S, A> environment, double alpha, double gamma, int k ) { super(environment, alpha, gamma); this.k = k; } public int getK() { return k; } @Override A policy() { try { return bestActionAtState(getCurrentState()); } catch (RLException e) { return new EqualDistribution<>(availableActions()).sample(); } } @Override protected void updateReward(S s, A a, double r) { super.updateReward(s, a, r); } @Override protected double learningRateUpdate() { // Reduce by 5 percent each time. This is arbitrary // and probably should be made into a method. // TODO: should make this into a parameter... Actually, // this is perfect for the Strategy pattern. Like, a // LearningRateStrategy. WOW! Nice idea. return -0.05 * getAlpha(); } @Override void learn() { fullBackup(lastExperience()); for (final Pair<S, A> pair : sampleKStateActionPairs()) { fullBackup(pair); } } @Override double value(S s) { return maxQAtState(s); } private List<Pair<S, A>> sampleKStateActionPairs() { final List<Pair<S, A>> state_action_pairs = new ArrayList<>( getObservedStateActionPairs() ); if (state_action_pairs.size() < k) { return state_action_pairs; } Collections.shuffle(state_action_pairs); return state_action_pairs.subList(0, k); } }
ace53thntu/cookie-sync-demo
src/pages/product/[slug].js
<gh_stars>0 import { useRouter } from "next/router"; import { useSelector } from "react-redux"; import { getProductsBySlug } from "../../common/shopUtils"; import { capitalizeFirstLetter } from "../../common/utils"; import LayoutOne from "../../components/layouts/LayoutOne"; import ProductDetailOne from "../../components/productDetail/ProductDetailOne"; import productData from "../../data/product.json"; export default function pid() { const router = useRouter(); const { slug } = router.query; const { product } = useSelector((state) => state.globalReducer); return ( <LayoutOne title={product?.name ? capitalizeFirstLetter(product.name) : ""} clearSpaceTop > {product?.name && <ProductDetailOne data={product} />} </LayoutOne> ); }
tingelst/versor
scratch/projects/groups/xSpaceGroup3D.cpp
/* * ===================================================================================== * * Filename: xSpaceGroup3D.cpp * * Description: from allo * * Version: 1.0 * Created: 04/30/2015 15:30:13 * Revision: none * Compiler: gcc * * Author: <NAME> (), gmail->wolftype * Organization: wolftype * * ===================================================================================== */ #include "vsr_app.h" #include "form/vsr_group.h" //#include "Cuttlebone/Cuttlebone.hpp" //#include "alloutil/al_OmniStereoGraphicsRenderer.hpp" //#include "horo_vsr.hpp" using namespace vsr; using namespace vsr::cga; struct State{ gfx::Pose pose; gfx::Pose model; float amt=0; float p=2; float q=2; bool pbar=false; bool qbar=false; bool pqbar=false; bool bGlideA, bGlideB, bGlideC; float glideA, glideB, glideC; Point point = Round::null(0,0,0); float xratio,yratio,zratio; int numX, numY, numZ; float bravaisType; float latticeType; }; void drawState(State * state){ State& s = *state; SpaceGroup3D<Vec>::Lattice lattice = {(int)s.bravaisType,(int)s.latticeType}; Vec ratioVec(s.xratio,s.yratio,s.zratio); SpaceGroup3D<Vec>::Glide glide = { {(int)s.glideA, s.bGlideA},{(int)s.glideB,s.bGlideB},{(int)s.glideC,s.bGlideC} }; SpaceGroup3D<Vec> sg(s.p,s.q,s.pbar,s.qbar,s.pqbar, lattice, ratioVec, glide); Draw( sg.a,1,0,0); Draw( sg.b,1,1,0); Draw( sg.c,1,0,1); Draw( sg.mB_dir ); Draw( sg.mB_length,1,0,1); Draw( sg.mC_dir, 1,.3,.1 ); Draw( sg.mC_length,0,1,1); auto dls = Round::sphere(s.point, .3); vector<Point> pnt; for (int i=0;i<4;++i){ float t = (float)i/4; Rotor r = Gen::rot( Biv::xz * PI * t); pnt.push_back( Construct::point(dls, Vec::x.spin( r ) ) ); } pnt.push_back( s.point.translate(0,.15,0) ); auto res = sg.apply( pnt ); auto latticeRes = sg.hang( res , s.numX,s.numY,s.numZ); for (int i=0;i<latticeRes.size(); i+=pnt.size() ) { auto a = latticeRes[i]; auto b = latticeRes[i+1]; auto c = latticeRes[i+2]; auto d = latticeRes[i+3]; auto e = latticeRes[i+4]; glColor3f(1,1,0); Glyph::Triangle(a,b,e); glColor3f(0,1,1); Glyph::Triangle(b,c,e); glColor3f(1,0,1); Glyph::Triangle(c,d,e); glColor3f(1,.5,.5); Glyph::Triangle(d,a,e); glColor3f(.2,1,.5); Glyph::Triangle(a,b,c); Glyph::Triangle(c,d,a); } } /*----------------------------------------------------------------------------- * SIMULATION *-----------------------------------------------------------------------------*/ struct MyApp : App { State * state; //Some Variables bool bReset = false; bool bSetMouse=false; Point mouse = Round::null(1,1,1);; float latticetype; /*----------------------------------------------------------------------------- * Setup Variables *-----------------------------------------------------------------------------*/ void setup(){ state = new State; memset(state, 0, sizeof(State)); ///Bind Gui bindGLV(); State& s = *state; ///Add Variables to GUI gui(s.amt,"amt",-100,100)(bReset,"bReset"); gui(s.p,"p",0,10); gui(s.pbar,"pbar"); gui(s.q,"q",0,10); gui(s.qbar,"qbar"); gui(s.pqbar,"pqbar"); gui(s.xratio, "xratio",1,100); gui(s.yratio, "yratio",1,100); gui(s.zratio, "zratio",1,100); gui(s.latticeType, "latticeType",1,5); gui(s.bravaisType, "bravaisType",1,7); gui(s.glideA, "glide a",0,5); gui(s.bGlideA, "glide a alt"); gui(s.glideB, "glide b",0,5); gui(s.bGlideB, "glide b alt"); gui(s.glideC, "glide c",0,5); gui(s.bGlideC, "glide c alt"); gui(s.numX, "num x",1,100); gui(s.numY, "num y",1,100); gui(s.numZ, "num z",1,100); s.xratio = s.yratio = s.zratio =1; s.p=4;s.q=2; s.pbar=s.qbar=s.pqbar=0; s.glideA = s.glideB = s.glideC = 0; s.latticeType = 1; s.bravaisType = 1; s.numX = 1; s.numY = 1; s.numZ = 1; } void onKeyDown(const gfx::Keyboard& k){ if (k.code=='s') bSetMouse = !bSetMouse; } void onAnimate(){ state -> point = mouse; state -> pose = (Pose)scene.camera; state -> model = scene.model; } /*----------------------------------------------------------------------------- * Draw Routines *-----------------------------------------------------------------------------*/ void onDraw(){ if (bSetMouse) mouse = calcMouse3D(); drawState(state); } }; int main (int argc, char *argv[]){ MyApp app; app.start(); return 0; }
OPSWAT/metadefender-menlo-integration
metadefender_menlo/api/responses/check_existing.py
<filename>metadefender_menlo/api/responses/check_existing.py<gh_stars>0 from metadefender_menlo.api.responses.base_response import BaseResponse class CheckExisting(BaseResponse): def __init__(self, allowedResponses=None): allowedResponses = [200, 500] super().__init__(allowedResponses) self._http_responses["200"] = self.__response200 def __response200(self, response, status_code): translation = { 'uuid': '{0}', 'result': '{0}' } if 'data_id' in response: self._translate('uuid', translation, response['data_id']) self._translate('result', translation, 'found') return (translation, status_code) else: return (response, 404)
KaffinPX/bedrock-protocol
src/rak.js
<reponame>KaffinPX/bedrock-protocol const { EventEmitter } = require('events') const Listener = require('jsp-raknet/listener') const EncapsulatedPacket = require('jsp-raknet/protocol/encapsulated_packet') const Reliability = require('jsp-raknet/protocol/reliability') const RakClient = require('jsp-raknet/client') const ConnWorker = require('./rakWorker') const { waitFor } = require('./datatypes/util') try { var { Client, Server, PacketPriority, PacketReliability, McPingMessage } = require('raknet-native') // eslint-disable-line } catch (e) { console.debug('[raknet] native not found, using js', e) } class RakNativeClient extends EventEmitter { constructor (options) { super() this.connected = false this.onConnected = () => { } this.onCloseConnection = () => { } this.onEncapsulated = () => { } this.raknet = new Client(options.hostname, options.port, 'minecraft') this.raknet.on('encapsulated', ({ buffer, address }) => { this.onEncapsulated(buffer, address) }) this.raknet.on('connected', () => { this.connected = true this.onConnected() }) this.raknet.on('disconnected', ({ reason }) => { this.connected = false this.onCloseConnection(reason) }) } async ping () { this.raknet.ping() return waitFor((done) => { this.raknet.on('pong', (ret) => { if (ret.extra) { done(ret.extra.toString()) } }) }, 1000) } connect () { this.raknet.connect() } close () { this.connected = false setTimeout(() => { this.raknet.close() }, 40) } sendReliable (buffer, immediate) { if (!this.connected) return const priority = immediate ? PacketPriority.IMMEDIATE_PRIORITY : PacketPriority.MEDIUM_PRIORITY return this.raknet.send(buffer, priority, PacketReliability.RELIABLE_ORDERED, 0) } } class RakNativeServer extends EventEmitter { constructor (options = {}) { super() this.onOpenConnection = () => { } this.onCloseConnection = () => { } this.onEncapsulated = () => { } this.raknet = new Server(options.hostname, options.port, { maxConnections: options.maxConnections || 3, minecraft: {}, message: new McPingMessage().toBuffer() }) this.raknet.on('openConnection', (client) => { client.sendReliable = function (buffer, immediate) { const priority = immediate ? PacketPriority.IMMEDIATE_PRIORITY : PacketPriority.MEDIUM_PRIORITY return this.send(buffer, priority, PacketReliability.RELIABLE_ORDERED, 0) } this.onOpenConnection(client) }) this.raknet.on('closeConnection', (client) => { console.warn('! Client closed connection') // TODO: need to handle this properly.. this.onCloseConnection(client) }) this.raknet.on('encapsulated', ({ buffer, address }) => { // console.log('ENCAP',thingy) this.onEncapsulated(buffer, address) }) } listen () { this.raknet.listen() } close () { this.raknet.close() } } class RakJsClient extends EventEmitter { constructor (options = {}) { super() this.onConnected = () => { } this.onEncapsulated = () => { } if (options.useWorkers) { this.connect = this.workerConnect this.sendReliable = this.workerSendReliable } else { this.connect = this.plainConnect this.sendReliable = this.plainSendReliable } } workerConnect (hostname = this.options.hostname, port = this.options.port) { this.worker = ConnWorker.connect(hostname, port) this.worker.on('message', (evt) => { switch (evt.type) { case 'connected': { this.onConnected() break } case 'encapsulated': { const [ecapsulated, address] = evt.args this.onEncapsulated(ecapsulated.buffer, address.hash) break } } }) } async plainConnect (hostname = this.options.hostname, port = this.options.port) { this.raknet = new RakClient(hostname, port) await this.raknet.connect() this.raknet.on('connecting', () => { console.log(`[client] connecting to ${hostname}/${port}`) }) this.raknet.on('connected', this.onConnected) this.raknet.on('encapsulated', (encapsulated, addr) => this.onEncapsulated(encapsulated.buffer, addr.hash)) } workerSendReliable (buffer, immediate) { this.worker.postMessage({ type: 'queueEncapsulated', packet: buffer, immediate }) } plainSendReliable (buffer, immediate) { const sendPacket = new EncapsulatedPacket() sendPacket.reliability = Reliability.ReliableOrdered sendPacket.buffer = buffer this.connection.addEncapsulatedToQueue(sendPacket) if (immediate) this.connection.sendQueue() } } class RakJsServer extends EventEmitter { constructor (options = {}) { super() this.options = options this.onOpenConnection = () => { } this.onCloseConnection = () => { } this.onEncapsulated = () => { } if (options.useWorkers) { throw Error('nyi') } else { this.listen = this.plainListen } } async plainListen () { this.raknet = new Listener() await this.raknet.listen(this.options.hostname, this.options.port) this.raknet.on('openConnection', (conn) => { conn.sendReliable = function (buffer, immediate) { const sendPacket = new EncapsulatedPacket() sendPacket.reliability = Reliability.ReliableOrdered sendPacket.buffer = buffer this.connection.addEncapsulatedToQueue(sendPacket) if (immediate) this.raknet.sendQueue() } this.onOpenConnection(conn) }) this.raknet.on('closeConnection', this.onCloseConnection) this.raknet.on('encapsulated', this.onEncapsulated) } } module.exports = { RakClient: Client ? RakNativeClient : RakJsClient, RakServer: Server ? RakNativeServer : RakJsServer }
remyvhw/passwordsync-2
SLColorArt.h
<reponame>remyvhw/passwordsync-2<gh_stars>0 // // SLColorArt.h // ColorArt // // Created by <NAME> on 12/11/12. // // Copyright (C) 2012 Panic Inc. Code by <NAME>. All rights reserved. // // Redistribution and use, with or without modification, are permitted provided that the following conditions are met: // // - Redistributions must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // // - Neither the name of Panic Inc nor the names of its contributors may be used to endorse or promote works derived from this software without specific prior written permission from Panic Inc. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PANIC INC BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Some portions of this code licensed as follows: /* * The MIT License * * Copyright (c) 2009 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ @interface SLColorArt : NSObject @property(retain, readonly) UIColor *backgroundColor; @property(retain, readonly) UIColor *primaryColor; @property(retain, readonly) UIColor *secondaryColor; @property(retain, readonly) UIColor *detailColor; @property(nonatomic, copy) UIImage *scaledImage; - (id)initWithImage:(UIImage *)image; - (id)initWithImage:(UIImage *)image scaledSize:(CGSize)size; @end
lfcabend/emvlib
src/main/scala/org/emv/tlv/Track2EquivalentData.scala
package org.emv.tlv import org.emv.tlv.EMVTLV._ import org.emv.tlv.EMVTLV.EMVTLVParser._ import org.lau.tlv.ber._ import scodec.bits.ByteVector /** * Created by lau on 2/17/17. */ case class Track2EquivalentData(override val value: ByteVector) extends EMVTLVLeaf with TemplateTag { override val tag = Track2EquivalentData.tag override val templates = Set(ResponseMessageTemplateFormat2.tag, READRECORDResponseMessageTemplate.tag) } object Track2EquivalentData extends EMVDefaultBinaryWithVarLengthSpec[Track2EquivalentData] { val tag = berTag"57" def parser = parseEMVBySpec(Track2EquivalentData, parseB(_)) override val maxLength = 19 override val minLength = 0 }
33cn/chat33-android
lib-basic/src/main/java/com/fuzamei/common/utils/AbstractConfigProperty.java
package com.fuzamei.common.utils; import android.content.Context; import com.fuzamei.commonlib.R; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Properties; /** * @author Mark * @since 2018/9/4 * Description: */ public abstract class AbstractConfigProperty { public Properties config; public AbstractConfigProperty(Context context) { try { InputStream open = context.getAssets().open(getFileName()); config = new Properties(); config.load(new InputStreamReader(open, StandardCharsets.UTF_8)); open.close(); } catch (IOException e) { e.printStackTrace(); LogUtils.e(context.getString(R.string.basic_error_open_property_file)); } } public abstract String getFileName(); }
loanselot1/IceSDK
third-party/bimg/3rdparty/astc-codec/src/decoder/test/footprint_test.cc
// Copyright 2018 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. #include "src/decoder/footprint.h" #include <array> #include <tuple> #include <vector> #include <gtest/gtest.h> namespace astc_codec { namespace { TEST(FootprintTest, ParseAstcFootprintString) { using ASTCTestPair = std::pair<std::string, Footprint>; const std::array<ASTCTestPair, Footprint::NumValidFootprints()> valid_footprints {{ std::make_pair("4x4", Footprint::Get4x4()), std::make_pair("5x4", Footprint::Get5x4()), std::make_pair("5x5", Footprint::Get5x5()), std::make_pair("6x5", Footprint::Get6x5()), std::make_pair("6x6", Footprint::Get6x6()), std::make_pair("8x5", Footprint::Get8x5()), std::make_pair("8x6", Footprint::Get8x6()), std::make_pair("8x8", Footprint::Get8x8()), std::make_pair("10x5", Footprint::Get10x5()), std::make_pair("10x6", Footprint::Get10x6()), std::make_pair("10x8", Footprint::Get10x8()), std::make_pair("10x10", Footprint::Get10x10()), std::make_pair("12x10", Footprint::Get12x10()), std::make_pair("12x12", Footprint::Get12x12()) }}; for (const auto& test : valid_footprints) { base::Optional<Footprint> footprint = Footprint::Parse(test.first.c_str()); EXPECT_TRUE(footprint); EXPECT_EQ(test.second, footprint.value()); } EXPECT_DEBUG_DEATH(EXPECT_FALSE(Footprint::Parse("")), ""); EXPECT_DEBUG_DEATH(EXPECT_FALSE(Footprint::Parse("3")), ""); EXPECT_DEBUG_DEATH(EXPECT_FALSE(Footprint::Parse("x")), ""); // Validly formed but out-of-bounds dimensions do not assert, otherwise // malformed ASTC files could crash the decoder in debug builds. EXPECT_FALSE(Footprint::Parse("9999999999x10")); EXPECT_DEBUG_DEATH(EXPECT_FALSE(Footprint::Parse("ax8")), ""); EXPECT_DEBUG_DEATH(EXPECT_FALSE(Footprint::Parse("2x3x4")), ""); EXPECT_DEBUG_DEATH(EXPECT_FALSE(Footprint::Parse("-3x4")), ""); EXPECT_FALSE(Footprint::Parse("10x4")); } TEST(FootprintTest, Bitrates) { EXPECT_NEAR(Footprint::Get4x4().Bitrate(), 8.f, 0.01f); EXPECT_NEAR(Footprint::Get5x4().Bitrate(), 6.4f, 0.01f); EXPECT_NEAR(Footprint::Get5x5().Bitrate(), 5.12f, 0.01f); EXPECT_NEAR(Footprint::Get6x5().Bitrate(), 4.27f, 0.01f); EXPECT_NEAR(Footprint::Get6x6().Bitrate(), 3.56f, 0.01f); EXPECT_NEAR(Footprint::Get8x5().Bitrate(), 3.20f, 0.01f); EXPECT_NEAR(Footprint::Get8x6().Bitrate(), 2.67f, 0.01f); EXPECT_NEAR(Footprint::Get8x8().Bitrate(), 2.00f, 0.01f); EXPECT_NEAR(Footprint::Get10x5().Bitrate(), 2.56f, 0.01f); EXPECT_NEAR(Footprint::Get10x6().Bitrate(), 2.13f, 0.01f); EXPECT_NEAR(Footprint::Get10x8().Bitrate(), 1.60f, 0.01f); EXPECT_NEAR(Footprint::Get10x10().Bitrate(), 1.28f, 0.01f); EXPECT_NEAR(Footprint::Get12x10().Bitrate(), 1.07f, 0.01f); EXPECT_NEAR(Footprint::Get12x12().Bitrate(), 0.89f, 0.01f); } TEST(FootprintTest, StorageRequirements) { auto footprint = Footprint::Get10x8(); EXPECT_EQ(footprint.Width(), 10); EXPECT_EQ(footprint.Height(), 8); // If we have 8x8 blocks, then we have 64*16 = 1024 bytes. EXPECT_EQ(footprint.StorageRequirements(80, 64), 1024); // If our block is a little smaller this still counts because we need to // cover a partial block with a fully encoded one. EXPECT_EQ(footprint.StorageRequirements(79, 63), 1024); } } // namespace } // namespace astc_codec
vadimzalunin/crammer
src/junk/java/net/sf/block/Container.java
<reponame>vadimzalunin/crammer package net.sf.block; public class Container { public int length; public long contentId; public Block[] blocks; public Container[] containers; }
nwillc/scotty
src/test/java/features/database/ValueFeature.java
/* * Copyright (c) 2015, <EMAIL> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ package features.database; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import scotty.database.Value; import static org.assertj.core.api.Assertions.assertThat; public class ValueFeature { private Value value; private String string; private boolean match; @Given("^a value of \"([^\"]*)\"$") public void a_value_of(String arg1) throws Throwable { String[] values = arg1.split(" "); value = new Value(values); assertThat(value).isNotNull(); assertThat(value.values().size()).isGreaterThan(0); } @Given("^a \"([^\"]*)\"$") public void a(String arg1) throws Throwable { string = arg1; } @When("^they are matched$") public void they_are_matched() throws Throwable { match = value.values().contains(string); } @Then("^if should return \"([^\"]*)\"$") public void if_should_return(String arg1) throws Throwable { assertThat(String.valueOf(match)).isEqualTo(arg1); } @Then("^its string representation should be \"([^\"]*)\"$") public void its_string_representation_should_be(String arg1) throws Throwable { assertThat(value.toString()).isEqualTo(arg1); } }
gegeyang0124/react-native-lib-cus-com
ui/TitleBlockTarget.js
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import { View, } from 'react-native'; import { StyleSheetAdapt, Theme, } from "./../api/api"; import {TitleBlockList} from "./TitleBlockList"; import {ItemRowTitle} from "./ItemRowTitle"; import {TitleBlock} from "./TitleBlock"; import {BarHorizontalTitleSection} from './BarHorizontalTitleSection'; /** * 目标幕模块 上部有header文本 中间有TitleBlockList * 下边有TitleBlock文本提示(下左)和BarHorizontalTitleSection(对比进程 下右) * **/ export class TitleBlockTarget extends Component { //属性注释及类型,所有的属性对象都是句柄模式(类型时number),类似C语言中的指针 static propTypes = { frameStyle:PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.array ]),//框样式 title:PropTypes.string,//头部header提示文本 // onPress:PropTypes.func,//图片点击事件 回传(成员,index) /** 成员:{ textDown:PropTypes.string,//按钮文字 下边 textCenter:PropTypes.string,//按钮文字 中间 textRight:PropTypes.string,//按钮文字 右边 } * **/ titleBlockList:PropTypes.array,//数据 /** 成员: { textTop:PropTypes.string,//按钮文字 上边 textDown:PropTypes.string,//按钮文字 下边 textCenter:PropTypes.string,//按钮文字 中间 textRight:PropTypes.string,//按钮文字 右边 color:PropTypes.string,//textCenter的文本颜色,竖杠颜色 } * **/ titleBlockOptions:PropTypes.object,//数据对象 下边有TitleBlock文本提示 不传不显示 /** 成员: { textRight:'',//进度对比条左边文本 null不显示 textLeft:'',//进度对比条右边边文本 null不显示 progress:0,//所占比值0~1 默认是1 } * **/ progressList:PropTypes.array,// 进度对比条数组 底部 /** 成员: { textRight:'',//进度对比条左边文本 null不显示 textLeft:'',//进度对比条右边边文本 null不显示 progress:0,//所占比值0~1 默认是1 } * **/ progressTopList:PropTypes.array,//进度对比条数组 顶部 children:PropTypes.object,//子UI 支持 textCenterBlockStyle:PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.array ]),//TitleBlockList 中间文本样式 textBlockStyle:PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.array ]),//TitleBlockList 文本样式 } /** * 设置默认属性 * **/ static defaultProps = { isScroll:false, } constructor(props) { super(props); } render() { const {frameStyle,title,titleBlockList,titleBlockOptions,progressList, progressTopList,children,textCenterBlockStyle,textBlockStyle} = this.props; return ( <View style={[styles.frameStyle,frameStyle]}> <ItemRowTitle text1={title} frameStyle={styles.titleFrame} isShowPillar={false}/> { progressTopList&&<BarHorizontalTitleSection options={{ sectionList:[ { progressList:progressTopList } ] }} frameBarStyle={styles.bHTSFrame2}/> } <TitleBlockList frameStyle={styles.titleBLFrame} textCenterStyle={textCenterBlockStyle} textStyle={textBlockStyle} dataList={titleBlockList}/> { (titleBlockOptions||progressList)&&<View style={styles.perDown}> { titleBlockOptions&&<TitleBlock isShowIconLeft={false} textCenter={titleBlockOptions.textCenter} textRight={titleBlockOptions.textRight} textDownStyle={styles.textTB} textDown={titleBlockOptions.textDown}/> } { progressList&&<BarHorizontalTitleSection options={{ sectionList:[ { progressList:progressList } ] }} frameStyle={styles.bHTSFrame}/> } </View> } {children} </View> ); } } const styles = StyleSheetAdapt.create({ bHTSFrame2:{ flexDirection:'row', }, bHTSFrame:{ flex:3, borderLeftWidth:Theme.Border.borderWidth, borderLeftColor:Theme.Colors.themeColor, }, perDown:{ flexDirection:'row', marginTop:10, marginBottom:10, }, textTB:{ fontSize:Theme.Font.fontSize, color:Theme.Colors.fontcolor, }, titleBLFrame:{ paddingTop:10, paddingBottom:10, }, titleFrame:{ borderBottomColor:Theme.Colors.themeColor, borderBottomWidth:Theme.Border.borderWidth, marginLeft:10, marginRight:10, }, frameStyle: { backgroundColor:Theme.Colors.foregroundColor, // flex:1, // alignItems:'center', // justifyContent:'center', // flexDirection:'row', }, });
immune-gmbh/agent
internal/testing/generators.go
<filename>internal/testing/generators.go package testing import ( "encoding/base64" "math/big" "math/rand" ) func GenerateBigInt(rand *rand.Rand, bits uint) *big.Int { ret := big.NewInt(0) one := big.NewInt(1) bound := one.Lsh(one, bits) return ret.Rand(rand, bound) } func GenerateBytes(rand *rand.Rand, min, max int) []byte { l := rand.Intn(max-min) + min b := make([]byte, l) rand.Read(b) return b } func GenerateBase64(rand *rand.Rand, min, max int) string { return base64.StdEncoding.EncodeToString(GenerateBytes(rand, min, max)) }
graphcore/poplibs
lib/popops/DynamicSliceInternal.hpp
<filename>lib/popops/DynamicSliceInternal.hpp // Copyright (c) 2019 Graphcore Ltd. All rights reserved. #ifndef DYNAMIC_SLICE_INTERNAL_HPP #define DYNAMIC_SLICE_INTERNAL_HPP #include <iostream> #include <memory> #include <vector> namespace popops { namespace sliceInternal { // How to partition work across tiles. template <typename T> struct Partition { // How much to split processing of lookup indices between tiles. T lookupSplit; // How much to split the sliced/updated dimension of the // tensor to be sliced/updated between tiles. T slicedDimSplit; // How much to split the product of dimensions that are not // sliced/updated between tiles. T unslicedDimSplit; // Grain size for no. of elements in the product of dimensions that // are not sliced/updated on each tile. T unslicedGrainSize; }; template <typename T> bool operator<(const Partition<T> &a, const Partition<T> &b) { return std::tie(a.lookupSplit, a.slicedDimSplit, a.unslicedDimSplit, a.unslicedGrainSize) < std::tie(b.lookupSplit, b.slicedDimSplit, b.unslicedDimSplit, b.unslicedGrainSize); } template <typename T> bool operator==(const Partition<T> &a, const Partition<T> &b) { return std::tie(a.lookupSplit, a.slicedDimSplit, a.unslicedDimSplit, a.unslicedGrainSize) == std::tie(b.lookupSplit, b.slicedDimSplit, b.unslicedDimSplit, b.unslicedGrainSize); } } // namespace sliceInternal class SlicePlanInternal { public: SlicePlanInternal() : isNull(true) {} public: bool isNull; bool useIndicesOrderingInfo; sliceInternal::Partition<std::size_t> partition; // For validation, to identify the restrictions on what this // plan can be used to implement, std::size_t rank; std::vector<std::size_t> slicedDims; std::vector<std::size_t> slicedDimSizes; std::unique_ptr<SlicePlanInternal> clone() const { return std::make_unique<SlicePlanInternal>(*this); }; }; bool operator<(const SlicePlanInternal &a, const SlicePlanInternal &b) noexcept { return std::tie(a.isNull, a.useIndicesOrderingInfo, a.partition, a.rank, a.slicedDims, a.slicedDimSizes) < std::tie(b.isNull, b.useIndicesOrderingInfo, b.partition, b.rank, b.slicedDims, b.slicedDimSizes); } bool operator==(const SlicePlanInternal &a, const SlicePlanInternal &b) noexcept { return std::tie(a.isNull, a.useIndicesOrderingInfo, a.partition, a.rank, a.slicedDims, a.slicedDimSizes) == std::tie(b.isNull, b.useIndicesOrderingInfo, b.partition, b.rank, b.slicedDims, b.slicedDimSizes); } std::ostream &operator<<(std::ostream &o, const SlicePlanInternal &p); } // namespace popops #endif // DYNAMIC_SLICE_INTERNAL_HPP
haizaar/crossbar-examples
iotcookbook/device/yun/ambientlight/ambientlight_yun.js
// // Copyright (C) Tavendo GmbH. Licensed under the MIT license. // // This program bridges Arduino Yun to WAMP / Crossbar.io over Firmata (https://github.com/firmata/protocol). // and sends the state of a Tinkerit LDR module as a PubSub event // // Firmata is a MIDI-based protocol for communication between MCUs and host CPUs over serial connections. // // Firmata implementations used in the bridge: // // - Linux-side: https://github.com/shokai/node-arduino-firmata // - Arduino-side: https://github.com/firmata/arduino/blob/master/examples/StandardFirmataYun/StandardFirmataYun.ino // // configuration: var router = 'ws://192.168.1.134:8080/ws'; var realm = 'iot_cookbook'; var device_id = '123456'; var device_port = '/dev/ttyATH0'; var debug = false; // var debug = true; console.log("Arduino Yun Ambientlight Sensor starting ..."); var autobahn = require('autobahn'); var firmata = require('arduino-firmata'); var arduino = new firmata(); arduino.on('connect', function () { console.log("Arduino connected (over " + arduino.serialport_name + ", board version " + arduino.boardVersion + ")"); var connection = new autobahn.Connection({url: router, realm: realm}); connection.onopen = function (session) { console.log("Router connected. Session ID:", session.id); var monitored_pins = {}; function set_mode (args) { var pin = args[0]; var mode = args[1]; if (debug) { console.log("set_mode", pin, mode); } if (mode == "in") { arduino.pinMode(pin, firmata.INPUT); monitored_pins[pin] = false; } else if (mode == "watch") { arduino.pinMode(pin, firmata.INPUT); monitored_pins[pin] = true; } else if (mode == "out") { arduino.pinMode(pin, firmata.OUTPUT); monitored_pins[pin] = false; } else { console.log("illegal pin mode", mode); throw "illegal pin mode: " + mode; } } function analog_read (args) { var pin = args[0]; if (debug) { console.log("analog_read", pin); } var value; try { value = arduino.analogRead(pin); } catch (e) { console.log(e); throw e; } return value; } /****************************************** * Ambient Light (LDR) Sensor Code * ******************************************/ var ldr_pin = 0; // change to suit your requirements: 'I0': 0, 'I1': 1, 'I2': 2, 'I3': 3, 'I4': 4, 'I5': 5, var threshold = 0; // threshold value for sending events, '0' = send any changes var ldr_min = 9; // minimum value the sensor produces at full dark var ldr_max = 880; // max value the sensor produces var ldr_last = 0; var ldr_smoothe = 1; // offset below which no value changes are sent set_mode([ldr_pin, "watch"]); var get_light_level = function () { set_mode([ldr_pin, "in"]); var normValue = normalizeValue(analog_read([ldr_pin])); set_mode([ldr_pin, "watch"]); ldr_last = normValue; return normValue; }; var normalizeValue = function (rawValue) { return parseInt(((rawValue - ldr_min) / (ldr_max - ldr_min)) * 100); }; arduino.on('analogChange', function (e) { if (ldr_pin === e.pin) { normValue = normalizeValue(e.value); if (debug) { console.log("light level changed", e.value, normValue, ldr_last); } // constant value wanted, differs from previous value by more than smoothe value if (threshold === 0 && (normValue > ldr_last + ldr_smoothe || normValue < ldr_last - ldr_smoothe)) { ldr_last = normValue; session.publish("io.crossbar.examples.yun.ambientlight.on_light_level_change", [normValue]); // is at other side of threshold value (with smoothe area around that value) } else if (normValue > threshold + ldr_smoothe && ldr_last < threshold - ldr_smoothe) { ldr_last = normValue; session.publish("io.crossbar.examples.yun.ambientlight.on_threshold_passed", [true]); } else if (normValue < threshold - ldr_smoothe && ldr_last > threshold + ldr_smoothe) { ldr_last = normValue; session.publish("io.crossbar.examples.yun.ambientlight.on_threshold_passed", [false]); } } }); session.register("io.crossbar.examples.yun.ambientlight.get_light_level", get_light_level).then(function() { console.log("io.crossbar.examples.yun.ambientlight.get_light_level registered"); }, function () { console.log("io.crossbar.examples.yun.ambientlight.get_light_level - registration error"); }); session.register("io.crossbar.examples.yun.ambientlight.set_threshold", function(args) { threshold = args[0]; }).then(function() { console.log("io.crossbar.examples.yun.ambientlight.set_threshold registered"); }, function () { console.log("io.crossbar.examples.yun.ambientlight.set_threshold - registration error"); }); }; connection.onclose = function (reason, details) { console.log("no connection", reason, details); } console.log("Connecting to router ..."); connection.open(); }); // connect to Arduino over serial speaking Firmata arduino.connect(device_port);
zcdev/project3
client/src/components/CampaignComponents/MainDisplay/CharacterListItem.js
<reponame>zcdev/project3 import React from "react"; function CharacterListItem(props) { return ( <div id={props.character._id} onClick={() => props.addCharacterToCombatants(props.character)} className={props.id % 2 === 0 ? "character-list-item light" : "character-list-item dark"} > <div> <p>Name: {props.character.name}</p> <p>Dexterity: {props.character.dexterity}</p> </div> </div> ); } export default CharacterListItem;
krisgrint/titus
packages/titus-db-manager/lambda.js
'use strict' const AWS = require('aws-sdk') const logger = require('pino')() function getSecret(secretName) { return new Promise((resolve, reject) => { const client = new AWS.SecretsManager() client.getSecretValue({ SecretId: secretName }, function (err, data) { if (err) { console.log(err) reject(err) return } const credentials = JSON.parse(data.SecretString) resolve({ host: credentials.host, port: credentials.port, database: credentials.dbname, username: credentials.username, password: <PASSWORD> }) }) }) } const start = require('./migration-start') module.exports = { handler: async () => { try { logger.info('Migration Lambda Start') logger.info('Retrieve the secrets from ', process.env.SECRET_ARN) const credentials = await getSecret(process.env.SECRET_ARN) await start('migrate', credentials) await start('seed', credentials) logger.info('Migration done successful') } catch (e) { logger.error('Migration failed') logger.error(e) } } }
dsilakov/opa-fm
Esm/ib/src/smi/sm/sm_congestion.c
<reponame>dsilakov/opa-fm /* BEGIN_ICS_COPYRIGHT2 **************************************** Copyright (c) 2015-2020, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** END_ICS_COPYRIGHT2 ****************************************/ #include "os_g.h" #include "ib_types.h" #include "ib_macros.h" #include "ib_mad.h" #include "ib_sa.h" #include "ib_status.h" #include "cs_g.h" #include "cs_csm_log.h" #include "sm_counters.h" #include "sm_l.h" #include "sa_l.h" #include "cs_queue.h" #include "cs_bitset.h" #include "topology.h" #include "sm_parallelsweep.h" #include "sm_congestion.h" #include "stl_cca.h" extern Topology_t *sm_topop; extern int topology_sweep_triggered(void); typedef struct { ParallelWorkItem_t item; Node_t *nodep; } CongestionWorkItem_t; static void _congestion_work_item_free(CongestionWorkItem_t *workitem) { vs_pool_free(&sm_pool, workitem); } static CongestionWorkItem_t * _congestion_workitem_alloc(Node_t *nodep, PsWorker_t workFunc) { CongestionWorkItem_t *workItem = NULL; if (vs_pool_alloc(&sm_pool, sizeof(CongestionWorkItem_t), (void **)&workItem) != VSTATUS_OK) { return NULL; } memset(workItem, 0, sizeof(CongestionWorkItem_t)); workItem->nodep = nodep; workItem->item.workfunc = workFunc; return workItem; } static void _congestion_worker(ParallelSweepContext_t *psc, ParallelWorkItem_t *pwi) { Node_t *nodep = NULL; Status_t status = VSTATUS_OK; IB_ENTER(__func__, psc, pwi, 0, 0); DEBUG_ASSERT(psc && pwi); CongestionWorkItem_t *CongestionWorkItem = PARENT_STRUCT(pwi, CongestionWorkItem_t, item); nodep = CongestionWorkItem->nodep; MaiPool_t *maiPoolp = NULL; if (psc) { maiPoolp = psc_get_mai(psc); if (maiPoolp == NULL) { IB_LOG_ERROR_FMT(__func__, "Failed to get MAI channel for %s\n", sm_nodeDescString(nodep)); _congestion_work_item_free(CongestionWorkItem); psc_set_status(psc, VSTATUS_BAD); psc_stop(psc); IB_EXIT(__func__, VSTATUS_BAD); return; } } else { IB_LOG_ERROR_FMT(__func__, "Invalid parallel sweep context provided for %s\n", sm_nodeDescString(nodep)); _congestion_work_item_free(CongestionWorkItem); IB_EXIT(__func__, VSTATUS_BAD); return; } psc_lock(psc); if (topology_sweep_triggered()) { IB_LOG_INFINI_INFO0("New sweep request, delaying Congestion Configuration until after next sweep"); status = VSTATUS_OK; psc_set_status(psc, status); psc_stop(psc); goto exit; } if (nodep->congConfigDone) { goto exit; } if (sm_config.congestion.enable) { Port_t *portp = sm_get_node_end_port(nodep); if (!sm_valid_port(portp) || portp->state == IB_PORT_DOWN ) { goto exit; } SmpAddr_t addr = SMP_ADDR_CREATE_LR(sm_lid, portp->portData->lid); psc_unlock(psc); status = SM_Get_CongestionInfo(maiPoolp->fd, 0, &addr, &nodep->congestionInfo); psc_lock(psc); if (status != VSTATUS_OK) { IB_LOG_ERROR_FMT(__func__, "Failed to get Congestion Info for NodeGUID "FMT_U64" [%s]; rc: %d", nodep->nodeInfo.NodeGUID, sm_nodeDescString(nodep), status); goto exit; } } /* Need to call these functions even if disabled so we can clear CCA attributes */ if (nodep->nodeInfo.NodeType == STL_NODE_SW) status = stl_sm_cca_configure_sw(psc, maiPoolp->fd, nodep); else status = stl_sm_cca_configure_hfi(psc, maiPoolp->fd, nodep); if (status != VSTATUS_OK) { IB_LOG_INFO_FMT(__func__, "Failed to configure CCA for NodeGuid "FMT_U64" [%s]; rc: %d", nodep->nodeInfo.NodeGUID, sm_nodeDescString(nodep), status); } else { nodep->congConfigDone = 1; } exit: psc_unlock(psc); psc_free_mai(psc, maiPoolp); _congestion_work_item_free(CongestionWorkItem); IB_EXIT(__func__, status); } Status_t parallel_congestion(ParallelSweepContext_t *psc) { Status_t status = VSTATUS_OK; Node_t *nodep; CongestionWorkItem_t *wip; IB_ENTER(__func__, 0, 0, 0, 0); psc_go(psc); for_all_nodes(sm_topop, nodep) { wip = _congestion_workitem_alloc(nodep, _congestion_worker); if (wip == NULL) { status = VSTATUS_NOMEM; break; } psc_add_work_item(psc, &wip->item); } if (status == VSTATUS_OK) { status = psc_wait(psc); } else { psc_stop(psc); (void)psc_wait(psc); } psc_drain_work_queue(psc); IB_EXIT(__func__, status); return status; }
fossabot/jeak-framework
src/main/java/de/fearnixx/jeak/event/bot/BotEvent.java
package de.fearnixx.jeak.event.bot; import de.fearnixx.jeak.IBot; /** * Created by MarkL4YG on 09.06.17. */ public class BotEvent implements IBotEvent { private IBot bot; public BotEvent setBot(IBot bot) { this.bot = bot; return this; } @Override public IBot getBot() { return bot; } }
SimplyVC/panic
alerter/test/channels_manager/apis/test_slack_bot_api.py
<filename>alerter/test/channels_manager/apis/test_slack_bot_api.py import unittest from unittest.mock import patch from slack_sdk import WebClient from src.channels_manager.apis.slack_bot_api import SlackBotApi class TestSlackBotApi(unittest.TestCase): def setUp(self) -> None: self.test_bot_token = '<KEY>' self.test_app_token = 'xapp-Y-XXXXXXXXXXXX-TTTTTTTTTTTTT-LLLLLLLLLLLLL' self.test_bot_channel_id = 'test_bot_channel_id' self.test_message = "This is a test message" self.test_slack_bot_api = SlackBotApi( self.test_bot_token, self.test_app_token, self.test_bot_channel_id) def tearDown(self) -> None: self.test_slack_bot_api = None def test_bot_token_returns_bot_token(self) -> None: self.assertEqual(self.test_bot_token, self.test_slack_bot_api.bot_token) def test_app_token_returns_bot_token(self) -> None: self.assertEqual(self.test_app_token, self.test_slack_bot_api.app_token) def test_bot_channel_id_returns_bot_channel_id(self) -> None: self.assertEqual(self.test_bot_channel_id, self.test_slack_bot_api.bot_channel_id) @patch('slack_bolt.app.app.App.__init__') def test_initialize_app_successfully_initializes_app(self, mock_app) -> \ None: mock_app.return_value = None result = self.test_slack_bot_api.initialize_app() self.assertTrue(result) mock_app.assert_called_once_with(token=self.test_bot_token) @patch('slack_sdk.WebClient.chat_postMessage') @patch('slack_bolt.app.app.App.__init__') def test_send_message_sends_a_message_correctly(self, mock_app, mock_chat_postMessage) -> \ None: mock_app.return_value = None # Mock slack app. self.test_slack_bot_api.initialize_app() # Create empty web client within slack app. self.test_slack_bot_api._app._client = WebClient() self.test_slack_bot_api.send_message(self.test_message) mock_chat_postMessage.assert_called_once_with( channel=self.test_bot_channel_id, text=self.test_message)
umanwizard/rust-krb5-src
krb5/src/lib/krb5/krb/auth_con.h
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef KRB5_AUTH_CONTEXT #define KRB5_AUTH_CONTEXT #include "../rcache/memrcache.h" struct _krb5_auth_context { krb5_magic magic; krb5_address * remote_addr; krb5_address * remote_port; krb5_address * local_addr; krb5_address * local_port; krb5_key key; krb5_key send_subkey; krb5_key recv_subkey; krb5_int32 auth_context_flags; krb5_ui_4 remote_seq_number; krb5_ui_4 local_seq_number; krb5_authenticator *authentp; /* mk_req, rd_req, mk_rep, ...*/ krb5_cksumtype req_cksumtype; /* mk_safe, ... */ krb5_cksumtype safe_cksumtype; /* mk_safe, ... */ krb5_data cstate; /* mk_priv, rd_priv only */ krb5_rcache rcache; k5_memrcache memrcache; krb5_enctype * permitted_etypes; /* rd_req */ krb5_mk_req_checksum_func checksum_func; void *checksum_func_data; krb5_enctype negotiated_etype; krb5_authdata_context ad_context; }; /* Internal auth_context_flags */ #define KRB5_AUTH_CONN_INITIALIZED 0x00010000 #define KRB5_AUTH_CONN_USED_W_MK_REQ 0x00020000 #define KRB5_AUTH_CONN_USED_W_RD_REQ 0x00040000 #define KRB5_AUTH_CONN_SANE_SEQ 0x00080000 #define KRB5_AUTH_CONN_HEIMDAL_SEQ 0x00100000 #endif
sfqwo/keril
client/src/App.js
import { observer } from 'mobx-react-lite'; import React, { useContext, useEffect, useState } from 'react'; import { Spinner } from 'react-bootstrap'; import { BrowserRouter } from 'react-router-dom'; import { Context } from '.'; import AppRouter from './components/AppRouter'; import NavBar from './components/NavBar'; import { check } from './http/UserAPI'; const App = observer( () => { const {user} = useContext(Context) const [loading, setLoading] = useState(true) useEffect(()=>{ check().then( data => { user.setUser(true) user.setIsAuth(true) if(data.role === 'ADMIN') user.setIsAdmin(true) }).finally(() => setLoading(false)) }, []) if(loading) { return <Spinner animation={'grow'} /> } return ( <BrowserRouter> <NavBar/> <AppRouter /> </BrowserRouter> ) }) export default App;
jprinet/opentelemetry-java-instrumentation
instrumentation/apache-httpasyncclient-4.1/javaagent/src/test/java/io/opentelemetry/javaagent/instrumentation/apachehttpasyncclient/HttpUriRequest.java
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.apachehttpasyncclient; import java.net.URI; import org.apache.http.client.methods.HttpRequestBase; final class HttpUriRequest extends HttpRequestBase { private final String methodName; HttpUriRequest(String methodName, URI uri) { this.methodName = methodName; setURI(uri); } @Override public String getMethod() { return methodName; } }
ScalablyTyped/SlinkyTyped
a/activex-word/src/main/scala/typingsSlinky/activexWord/Word/EmailAuthor.scala
<reponame>ScalablyTyped/SlinkyTyped package typingsSlinky.activexWord.Word import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait EmailAuthor extends StObject { val Application: typingsSlinky.activexWord.Word.Application = js.native val Creator: Double = js.native val Parent: js.Any = js.native val Style: typingsSlinky.activexWord.Word.Style = js.native @JSName("Word.EmailAuthor_typekey") var WordDotEmailAuthor_typekey: EmailAuthor = js.native } object EmailAuthor { @scala.inline def apply( Application: Application, Creator: Double, Parent: js.Any, Style: Style, WordDotEmailAuthor_typekey: EmailAuthor ): EmailAuthor = { val __obj = js.Dynamic.literal(Application = Application.asInstanceOf[js.Any], Creator = Creator.asInstanceOf[js.Any], Parent = Parent.asInstanceOf[js.Any], Style = Style.asInstanceOf[js.Any]) __obj.updateDynamic("Word.EmailAuthor_typekey")(WordDotEmailAuthor_typekey.asInstanceOf[js.Any]) __obj.asInstanceOf[EmailAuthor] } @scala.inline implicit class EmailAuthorMutableBuilder[Self <: EmailAuthor] (val x: Self) extends AnyVal { @scala.inline def setApplication(value: Application): Self = StObject.set(x, "Application", value.asInstanceOf[js.Any]) @scala.inline def setCreator(value: Double): Self = StObject.set(x, "Creator", value.asInstanceOf[js.Any]) @scala.inline def setParent(value: js.Any): Self = StObject.set(x, "Parent", value.asInstanceOf[js.Any]) @scala.inline def setStyle(value: Style): Self = StObject.set(x, "Style", value.asInstanceOf[js.Any]) @scala.inline def setWordDotEmailAuthor_typekey(value: EmailAuthor): Self = StObject.set(x, "Word.EmailAuthor_typekey", value.asInstanceOf[js.Any]) } }
ashendes/carbon-multitenancy
components/tenant-mgt/org.wso2.carbon.tenant.mgt.core/src/main/java/org/wso2/carbon/tenant/mgt/core/util/TenantCoreUtil.java
package org.wso2.carbon.tenant.mgt.core.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.osgi.util.tracker.ServiceTracker; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.stratos.common.util.CommonUtil; import org.wso2.carbon.user.core.UserStoreException; import org.wso2.carbon.user.core.tenant.Tenant; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.carbon.utils.AuthenticationObserver; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.stratos.common.constants.StratosConstants; import org.wso2.carbon.tenant.mgt.core.internal.TenantMgtCoreServiceComponent; /** * Tenant Core Util class - used by any service that needs to create a tenant. */ public class TenantCoreUtil { private static final Log log = LogFactory.getLog(TenantCoreUtil.class); /** * Initializes the registry for the tenant. * * @param tenantId * tenant id. */ public static void initializeRegistry(int tenantId) { BundleContext bundleContext = TenantMgtCoreServiceComponent.getBundleContext(); if (bundleContext != null) { ServiceTracker tracker = new ServiceTracker(bundleContext, AuthenticationObserver.class.getName(), null); tracker.open(); Object[] services = tracker.getServices(); if (services != null) { for (Object service : services) { ((AuthenticationObserver) service).startedAuthentication(tenantId); } } tracker.close(); } } /** * Setting the Originated * @param tenantId - tenant Id * @param originatedService - The Service from where the tenant registration was originated. * @throws Exception, Registry Exception, if error in putting the originated Service resource * to the governance registry. */ public static void setOriginatedService(int tenantId, String originatedService) throws Exception { if (originatedService != null) { String originatedServicePath = StratosConstants.ORIGINATED_SERVICE_PATH + StratosConstants.PATH_SEPARATOR + StratosConstants.ORIGINATED_SERVICE + StratosConstants.PATH_SEPARATOR + tenantId; try { Resource origServiceRes = TenantMgtCoreServiceComponent. getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID).newResource(); origServiceRes.setContent(originatedService); TenantMgtCoreServiceComponent.getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID). put(originatedServicePath, origServiceRes); } catch (RegistryException e) { String msg = "Error in putting the originated service resource " + "to the governance registry"; log.error(msg, e); throw new RegistryException(msg, e); } } } }
jparams/object-creator
src/main/java/com/jparams/object/builder/provider/QueueProvider.java
<reponame>jparams/object-creator<filename>src/main/java/com/jparams/object/builder/provider/QueueProvider.java package com.jparams.object.builder.provider; import java.util.ArrayDeque; import java.util.Queue; import com.jparams.object.builder.Context; import com.jparams.object.builder.type.Type; public class QueueProvider implements Provider { @Override public boolean supports(final Type<?> type) { return type.getJavaType().isAssignableFrom(Queue.class); } @Override public Queue<?> provide(final Context context) { final Queue<Object> queue = new ArrayDeque<>(); if (context.getPath().getType().getGenerics().isEmpty()) { context.logWarning("No generics found. Could not populate List"); return queue; } final Type<?> type = context.getPath().getType().getGenerics().get(0).getType(); queue.add(context.createChild("[0]", type)); return queue; } }
Essane/PartimeJob
src/main/java/com/essane/partimejob/service/EmployeeBookmarkedService.java
<filename>src/main/java/com/essane/partimejob/service/EmployeeBookmarkedService.java package com.essane.partimejob.service; import com.baomidou.mybatisplus.extension.service.IService; import com.essane.partimejob.domain.EmployeeBookmarked; import com.essane.partimejob.vo.EmployeeBookmarkedVo; import java.util.List; /** * 雇员收藏业务逻辑接口 * @author Essane */ public interface EmployeeBookmarkedService extends IService<EmployeeBookmarked> { /** * 雇员收藏任务 * * @param id 雇员 ID * @param taskId 任务 ID * @return */ EmployeeBookmarked bookmarked(Long id, Long taskId); /** * 获取雇员收藏任务集合 * * @param employeeId 雇员 ID * @return */ List<EmployeeBookmarkedVo> getByEmployeeId(Long employeeId); /** * 获取雇员任务 ID 集合 * * @param employeeId 雇员 ID * @return */ List<Long> getIdsByEmployeeId(Long employeeId); /** * 删除收藏信息 * * @param id 雇员 ID * @param taskId 任务 ID */ void remove(Long id, Long taskId); }
ScalablyTyped/SlinkyTyped
a/antv__g2/src/main/scala/typingsSlinky/antvG2/mod/AxisTitle.scala
<reponame>ScalablyTyped/SlinkyTyped package typingsSlinky.antvG2.mod import typingsSlinky.antvG2.antvG2Strings.center import typingsSlinky.antvG2.antvG2Strings.end import typingsSlinky.antvG2.antvG2Strings.start import typingsSlinky.antvG2.mod.Styles.text import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /** * 坐标轴线 */ @js.native trait AxisTitle extends StObject { /** * 是否需要自动旋转,默认为 `true` */ var autoRotate: js.UndefOr[Boolean] = js.native /** * 数值,设置坐标轴标题距离坐标轴线的距离 */ var offset: js.UndefOr[Double] = js.native /** * 标题的显示位置(相对于坐标轴线) */ var position: js.UndefOr[start | center | end] = js.native /** * 设置标题的文本样式 */ var textStyle: js.UndefOr[text] = js.native } object AxisTitle { @scala.inline def apply(): AxisTitle = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[AxisTitle] } @scala.inline implicit class AxisTitleMutableBuilder[Self <: AxisTitle] (val x: Self) extends AnyVal { @scala.inline def setAutoRotate(value: Boolean): Self = StObject.set(x, "autoRotate", value.asInstanceOf[js.Any]) @scala.inline def setAutoRotateUndefined: Self = StObject.set(x, "autoRotate", js.undefined) @scala.inline def setOffset(value: Double): Self = StObject.set(x, "offset", value.asInstanceOf[js.Any]) @scala.inline def setOffsetUndefined: Self = StObject.set(x, "offset", js.undefined) @scala.inline def setPosition(value: start | center | end): Self = StObject.set(x, "position", value.asInstanceOf[js.Any]) @scala.inline def setPositionUndefined: Self = StObject.set(x, "position", js.undefined) @scala.inline def setTextStyle(value: text): Self = StObject.set(x, "textStyle", value.asInstanceOf[js.Any]) @scala.inline def setTextStyleUndefined: Self = StObject.set(x, "textStyle", js.undefined) } }
zhangkn/ToolUtility
_Modules/Services/Mqtt/MQService.h
<gh_stars>0 // // MessageService.h // fallen.ink // // Created by 李杰 on 2/9/15. // #import "_greats.h" #if __has_include(<MQTTSession/MQTTSession.h>) # define __has_MQTTSession 1 # import <MQTTSession/MQTTSession.h> #elif __has_include("MQTTSession.h") # define __has_MQTTSession 1 # import "MQTTSession.h" #else # define __has_MQTTSession 0 #endif #undef NOTIF_NAME_MQTT #define NOTIF_NAME_MQTT( __command_id_ ) ([NSString stringWithFormat:@"Notification.Mqtt.%ld", (long)__command_id_]) @protocol MQTTServiceDelegate; @interface MQService : NSObject #if __has_MQTTSession < MQTTSessionDelegate > #endif @property (nonatomic, weak) id <MQTTServiceDelegate> delegate; @property (atomic, assign) BOOL isAlive; @property (atomic, assign) BOOL isSubscribe; @property (atomic, assign) BOOL mqttConfigRequesting; @property (atomic, assign) BOOL mqttIsConnecting; @singleton( MQService ) - (void)patchReconnect; - (void)patchConnect; - (void)patchDisconnect; - (void)unpackSubscribes; @end @protocol MQTTServiceDelegate <NSObject> - (void)MQTTService:(MQService *)service didConnected:(BOOL)isConnected; - (void)MQTTService:(MQService *)service didDisconnected:(BOOL)isDisconnected; - (void)MQTTService:(MQService *)service didReceiveMessage:(NSDictionary *)messageDictionary; - (BOOL)isUserLogined; @optional // 待实现 @end
SoftwareDev/mat-plot-lib
examples/api/joinstyle.py
#!/usr/bin/env python """ Illustrate the three different join styles """ import numpy as np import matplotlib.pyplot as plt def plot_angle(ax, x, y, angle, style): phi = angle/180*np.pi xx = [x+.5,x,x+.5*np.cos(phi)] yy = [y,y,y+.5*np.sin(phi)] ax.plot(xx, yy, lw=8, color='blue', solid_joinstyle=style) ax.plot(xx[1:], yy[1:], lw=1, color='black') ax.plot(xx[1::-1], yy[1::-1], lw=1, color='black') ax.plot(xx[1:2], yy[1:2], 'o', color='red', markersize=3) ax.text(x,y+.2,'%.0f degrees' % angle) fig, ax = plt.subplots() ax.set_title('Join style') for x,style in enumerate((('miter', 'round', 'bevel'))): ax.text(x, 5, style) for i in range(5): plot_angle(ax, x, i, pow(2.0,3+i), style) ax.set_xlim(-.5,2.75) ax.set_ylim(-.5,5.5) plt.show()
dovotori/dovotori.github.io
public/shaders/diorama/shadow.js
import { uniformVertShadow, fragment, shadowLocations } from '../utils/shadow'; import { locations, getNaturalHeight, getNormale } from '../utils/terrain'; const vertex = ` attribute vec3 position; uniform mat4 projection; uniform mat4 model; uniform mat4 view; uniform mat3 normalMatrix; uniform float fogStart; uniform float fogEnd; ${uniformVertShadow} ${getNaturalHeight} ${getNormale} varying vec3 fragPosition; varying vec4 fragShadow; varying vec3 fragNormale; void main() { vec3 tranformed = position; if (position.y == 0.0) { vec2 coord = position.xz + moving; tranformed.y = getNaturalHeight(coord); } vec4 pos = view * model * vec4(tranformed, 1.0); fragShadow = bias * shadowProjection * shadowView * model * vec4(tranformed, 1.0); fragNormale = normalMatrix * getNormale(position, tranformed); fragPosition = normalize(pos.xyz); gl_Position = projection * pos; } `; export default { vertex, fragment, attributes: ['position'], uniforms: ['projection', 'model', 'view', 'normalMatrix', 'resolution'] .concat(locations) .concat(shadowLocations), };
Darlingnotin/Antisocial_VR
script-archive/utilities/diagnostics/orbitingSound.js
// // orbitingSound.js // examples // // Created by <NAME> on December 4, 2014 // Copyright 2014 High Fidelity, Inc. // // An object playing a sound appears and circles you, changing brightness with the audio playing. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // var RADIUS = 2.0; var orbitCenter = Vec3.sum(Camera.position, Vec3.multiply(Quat.getFront(Camera.getOrientation()), RADIUS)); var time = 0; var SPEED = 1.0; var currentPosition = { x: 0, y: 0, z: 0 }; var trailingLoudness = 0.0; var soundClip = SoundCache.getSound("http://public.highfidelity.io/sounds/Rats_Squeaks_Active.wav"); var properties = { type: "Box", position: orbitCenter, dimensions: { x: 0.25, y: 0.25, z: 0.25 }, color: { red: 100, green: 0, blue : 0 } }; var objectId = Entities.addEntity(properties); var soundOptions = { position: orbitCenter, loop: true, volume: 0.5 }; var sound; function update(deltaTime) { if (!soundClip.downloaded) { return; } if (!sound) { sound = Audio.playSound(soundClip, soundOptions); // Not until downloaded } time += deltaTime; currentPosition = { x: orbitCenter.x + Math.cos(time * SPEED) * RADIUS, y: orbitCenter.y, z: orbitCenter.z + Math.sin(time * SPEED) * RADIUS }; trailingLoudness = 0.9 * trailingLoudness + 0.1 * sound.loudness; Entities.editEntity( objectId, { position: currentPosition, color: { red: Math.min(trailingLoudness * 2000, 255), green: 0, blue: 0 } } ); soundOptions.position = currentPosition; sound.setOptions(soundOptions); } Script.scriptEnding.connect(function() { Entities.deleteEntity(objectId); }); Script.update.connect(update);
uvbs/FullSource
Source/Source/Tools/SceneEditor/DLG_MainTool.h
<reponame>uvbs/FullSource<filename>Source/Source/Tools/SceneEditor/DLG_MainTool.h //{{AFX_INCLUDES() #include "_frmframe.h" //}}AFX_INCLUDES #if !defined(AFX_DLG_MAINTOOL_H__476D6FAB_4F4F_4D6E_91AD_CA342B0AB5DC__INCLUDED_) #define AFX_DLG_MAINTOOL_H__476D6FAB_4F4F_4D6E_91AD_CA342B0AB5DC__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // DLG_MainTool.h : header file // //#include "SceneSkinEdit.h" ///////////////////////////////////////////////////////////////////////////// // CDLG_MainTool dialog //#include "MeshTerran.h" namespace MFCFramework { class CDLG_MainTool : public CDialog { // Construction public: CDLG_MainTool(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CDLG_MainTool) enum { IDD = IDD_MAINTOOL }; MFCFramework::C_frmFrame m_MainTool; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDLG_MainTool) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CDLG_MainTool) afx_msg void OnEGroundUpFrmframe1(); afx_msg void OnEGroundDownFrmframe1(); afx_msg void OnEGroundFlatFrmframe1(); afx_msg void OnEBrush0Frmframe1(); afx_msg void OnEBrush1Frmframe1(); afx_msg void OnEBrush2Frmframe1(); afx_msg void OnEBrush3Frmframe1(); afx_msg void OnEBrush4Frmframe1(); afx_msg void OnEHeightMapFrmframe1(); afx_msg void OnETitleSetChangeFrmframe1(); afx_msg void OnEViewFrameFrmframe1(); afx_msg void OnEAdvancedSetFrmframe1(); afx_msg void OnEAlphaDownFrmframe1(); afx_msg void OnEAlphaFlatFrmframe1(); afx_msg void OnEAlphaNoiseFrmframe1(); afx_msg void OnEAlphaUpFrmframe1(); afx_msg void OnECircleSelectFrmframe1(); afx_msg void OnEGroundCaveFrmframe1(); afx_msg void OnEGroundCliffFrmframe1(); afx_msg void OnEGroundDeepWaterFrmframe1(); afx_msg void OnEGroundThinWaterFrmframe1(); afx_msg void OnELastMaterial1Frmframe1(); afx_msg void OnELastMaterial2Frmframe1(); afx_msg void OnELastMaterial3Frmframe1(); afx_msg void OnELastMaterial4Frmframe1(); afx_msg void OnEMaterialDownFrmframe1(); afx_msg void OnEMaterialUpFrmframe1(); afx_msg void OnESuckFrmframe1(); afx_msg void OnEViewTextureFrmframe1(); virtual BOOL OnInitDialog(); DECLARE_EVENTSINK_MAP() //}}AFX_MSG DECLARE_MESSAGE_MAP() //KModelTerrain* m_lpMap; }; }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DLG_MAINTOOL_H__476D6FAB_4F4F_4D6E_91AD_CA342B0AB5DC__INCLUDED_)
jxg01713/zstack
header/src/main/java/org/zstack/header/zone/ZoneState.java
package org.zstack.header.zone; public enum ZoneState { Enabled, Disabled, }
Luligabi1/CoxinhaUtilities
src/main/java/me/luligabi/coxinhautilities/common/recipe/drying/DryingRecipeJsonFormat.java
<reponame>Luligabi1/CoxinhaUtilities package me.luligabi.coxinhautilities.common.recipe.drying; import com.google.gson.JsonObject; public class DryingRecipeJsonFormat { JsonObject ingredient; String outputItem; int dryingTime; }
chrismattmann/oodt
pushpull/src/main/java/org/apache/oodt/cas/pushpull/retrievalsystem/DownloadThreadEvaluator.java
/* * 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.oodt.cas.pushpull.retrievalsystem; //OODT imports import org.apache.oodt.cas.pushpull.exceptions.ThreadEvaluatorException; //JDK imports import java.io.File; import java.util.HashMap; import java.util.LinkedList; import java.util.Set; import java.util.Map.Entry; /** * * @author bfoster * @version $Revision$ * * <p> * Describe your class here * </p>. */ public class DownloadThreadEvaluator { private HashMap<File, DownloadingFileInfo> fileAndDownloadingFileInfo; private final int MAX_THREADS; private int currentThreadCount; private double[] downloadSpeedsForEachThread; public DownloadThreadEvaluator(int maxThreads) { this.MAX_THREADS = maxThreads; downloadSpeedsForEachThread = new double[maxThreads + 1]; fileAndDownloadingFileInfo = new HashMap<File, DownloadingFileInfo>(); currentThreadCount = 0; } public synchronized void startTrackingDownloadRuntimeForFile(File file) throws ThreadEvaluatorException { long curTime = System.currentTimeMillis(); if (++this.currentThreadCount > this.MAX_THREADS) throw new ThreadEvaluatorException( "Number of threads exceeds max allows threads"); updateThreadCounts(curTime); fileAndDownloadingFileInfo.put(file, new DownloadingFileInfo(file, curTime, this.currentThreadCount)); } private void updateThreadCounts(long curTime) { Set<Entry<File, DownloadingFileInfo>> entrySet = fileAndDownloadingFileInfo .entrySet(); for (Entry<File, DownloadingFileInfo> entry : entrySet) { entry.getValue() .updateThreadCount(curTime, this.currentThreadCount); } } public synchronized void cancelRuntimeTracking(File file) { fileAndDownloadingFileInfo.remove(file); currentThreadCount--; updateThreadCounts(System.currentTimeMillis()); } public synchronized void fileDownloadComplete(File file) throws ThreadEvaluatorException { try { long finishTime = System.currentTimeMillis(); DownloadingFileInfo dfi = fileAndDownloadingFileInfo.remove(file); updateThreadCounts(finishTime); LinkedList<TimeAndThreadCount> tatcList = dfi .getTimeAndThreadInfo(); long runtime = finishTime - dfi.getStartTimeInMillis(); double total = 0; long nextTime; for (int i = 0; i < tatcList.size(); i++) { TimeAndThreadCount tatc = tatcList.get(i); if (i + 1 >= tatcList.size()) nextTime = finishTime; else nextTime = tatcList.get(i + 1).getStartTimeInMillis(); long threadCountTime = nextTime - tatc.getStartTimeInMillis(); total += ((double) (tatc.getThreadCount() * threadCountTime)) / (double) runtime; } int avgThreadCountForFile = (int) Math.rint(total); System.out.println("Recorded avg: " + avgThreadCountForFile); double downloadSpeed = (file.length() * avgThreadCountForFile) / calculateRuntime(dfi.getStartTimeInMillis()); double currentAvgSpeed = this.downloadSpeedsForEachThread[avgThreadCountForFile]; if (currentAvgSpeed == 0) this.downloadSpeedsForEachThread[avgThreadCountForFile] = downloadSpeed; else this.downloadSpeedsForEachThread[avgThreadCountForFile] = (currentAvgSpeed + downloadSpeed) / 2; } catch (Exception e) { e.printStackTrace(); throw new ThreadEvaluatorException("Failed to register file " + file + " as downloaded : " + e.getMessage()); } finally { currentThreadCount--; } } long calculateRuntime(final long startTime) { return System.currentTimeMillis() - startTime; } public synchronized int getRecommendedThreadCount() { int curRecThreadCount = 1; double curMaxSpeed = this.downloadSpeedsForEachThread[curRecThreadCount]; for (int i = 1; i < this.downloadSpeedsForEachThread.length; i++) { double curSpeed = this.downloadSpeedsForEachThread[i]; if (curSpeed > curMaxSpeed) { curMaxSpeed = curSpeed; curRecThreadCount = i; } } if (curRecThreadCount != this.MAX_THREADS && this.downloadSpeedsForEachThread[curRecThreadCount + 1] == 0) curRecThreadCount++; else if (this.downloadSpeedsForEachThread[curRecThreadCount - 1] == 0) curRecThreadCount--; System.out.print("[ "); for (double time : downloadSpeedsForEachThread) System.out.print(time + " "); System.out.println("]"); System.out.println("Recommended Threads: " + curRecThreadCount); return curRecThreadCount; } }
hrxcodes/cbftp
src/localtransfer.h
<gh_stars>1-10 #pragma once #include <string> #include <fstream> #include "core/eventreceiver.h" #include "path.h" #define CHUNK 524288 class TransferMonitor; class FTPConn; class LocalTransfer : public Core::EventReceiver { public: LocalTransfer(); bool active() const; void openFile(bool); int getPort() const; virtual unsigned long long int size() const = 0; FTPConn * getConn() const; protected: void activate(); void deactivate(); bool ssl; int sockid; bool inmemory; bool passivemode; int port; TransferMonitor * tm; bool fileopened; FTPConn * ftpconn; std::fstream filestream; Path path; std::string filename; char * buf; unsigned int buflen; unsigned int bufpos; bool timeoutticker; private: void FDNew(int sockid, int newsockid) override; void tick(int) override; bool inuse; };
ibireme/yy_music_base
yy_music_base/ym_fifo.c
// // ym_buffer.c // yy_music // // Created by ibireme on 14-4-26. // Copyright (c) 2014 ibireme. All rights reserved. // #include "ym_fifo.h" #include "ym_util.h" #define YM_FIFO_INIT_COUNT 2048 #define YM_FIFO_FACTOR 16 struct _ym_fifo { void *mem; size_t item_total; size_t item_index; size_t item_count; size_t size_per_item; }; static void _ym_fifo_dealloc(ym_fifo_ref fifo) { if (fifo->mem) free(fifo->mem); } ym_fifo_ref ym_fifo_create(size_t item_count, size_t size_per_item) { ym_fifo_ref fifo; fifo = ym_alloc(struct _ym_fifo, _ym_fifo_dealloc); if (fifo) { fifo->size_per_item = size_per_item; fifo->item_count = item_count; fifo->item_total = YM_MAX(item_count, YM_FIFO_INIT_COUNT); fifo->mem = calloc(fifo->item_total, size_per_item); if (fifo->mem == NULL) { ym_release(fifo); return NULL; } } return fifo; } size_t ym_fifo_item_count(ym_fifo_ref fifo) { return fifo->item_count; } size_t ym_fifo_size_per_item(ym_fifo_ref fifo) { return fifo->size_per_item; } bool ym_fifo_append(ym_fifo_ref fifo, void *data, size_t item_count) { if (item_count == 0) return true; if (data == NULL) return false; size_t free_all = fifo->item_total - fifo->item_count; if (free_all < item_count * YM_FIFO_FACTOR) { size_t new_count = fifo->item_count + item_count * YM_FIFO_FACTOR; void *new_mem = malloc(new_count * fifo->size_per_item); if (new_mem == NULL) return false; memcpy(new_mem, fifo->mem + fifo->item_index * fifo->size_per_item, fifo->item_count * fifo->size_per_item); free(fifo->mem); fifo->mem = new_mem; fifo->item_index = 0; fifo->item_total = new_count; } size_t free_end = fifo->item_total - fifo->item_count - fifo->item_index; if (free_end < item_count) { memmove(fifo->mem, fifo->mem + fifo->item_index * fifo->size_per_item, fifo->item_count * fifo->size_per_item); fifo->item_index = 0; } memcpy(fifo->mem + (fifo->item_index + fifo->item_count) * fifo->size_per_item, data, item_count * fifo->size_per_item); fifo->item_count += item_count; return true; } bool ym_fifo_remove(ym_fifo_ref fifo, size_t item_count) { if (item_count > fifo->item_count) return false; if (item_count == 0) return true; fifo->item_index += item_count; fifo->item_count -= item_count; return true; } void *ym_fifo_get(ym_fifo_ref fifo) { return fifo->mem + fifo->item_index * fifo->size_per_item; } void *ym_fifo_get_inner(ym_fifo_ref fifo, size_t item_index) { return fifo->mem + (fifo->item_index + item_index) * fifo->size_per_item; }
minluzhou/test1
redis/redis-console/src/test/java/com/ctrip/xpipe/redis/console/dao/OrganizationDaoTest.java
<filename>redis/redis-console/src/test/java/com/ctrip/xpipe/redis/console/dao/OrganizationDaoTest.java package com.ctrip.xpipe.redis.console.dao; import com.ctrip.xpipe.redis.console.AbstractConsoleIntegrationTest; import com.ctrip.xpipe.redis.console.model.OrganizationTbl; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; /** * @author chen.zhu * * Sep 04, 2017 */ public class OrganizationDaoTest extends AbstractConsoleIntegrationTest { @Autowired private OrganizationDao organizationDao; @Test public void testInsertBatch() { organizationDao.createBatchOrganizations(createBatchOrgTbl(5)); } @Test public void testUpdateBatch() { organizationDao.createBatchOrganizations(createBatchOrgTbl(5)); List<OrganizationTbl> orgs = organizationDao.findAllOrgs(); List<OrganizationTbl> newOrgs = orgs.stream().map(org->{ if(org.getOrgId() > 0) { org.setOrgId(org.getOrgId()).setOrgName(org.getOrgName()+"-update"); return org; } return null; }).filter(org->org != null).collect(Collectors.toList()); organizationDao.updateBatchOrganizations(newOrgs); organizationDao.findAllOrgs().forEach(org->logger.info("{}", org)); } private OrganizationTbl createOrgTbl(long orgId, String orgName) { OrganizationTbl organizationTbl = new OrganizationTbl(); organizationTbl.setOrgId(orgId).setOrgName(orgName); return organizationTbl; } private List<OrganizationTbl> createBatchOrgTbl(int count) { List<OrganizationTbl> result = new LinkedList<>(); for(int i = 1; i <= count; i++) { result.add(createOrgTbl(i, "org-"+i)); } return result; } @Test public void testFindByOrgId() { organizationDao.createBatchOrganizations(createBatchOrgTbl(5)); OrganizationTbl organizationTbl = organizationDao.findByOrgId(2L); Assert.assertEquals(2L, organizationTbl.getOrgId()); } }
jufeng98/Java-master
spring-embed-arthas/src/main/java/org/javamaster/spring/embed/arthas/service/impl/UserServiceImpl.java
package org.javamaster.spring.embed.arthas.service.impl; import lombok.extern.slf4j.Slf4j; import org.javamaster.spring.embed.arthas.model.CreateUserReqVo; import org.javamaster.spring.embed.arthas.model.SysUser; import org.javamaster.spring.embed.arthas.service.UserService; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.util.DigestUtils; import java.nio.charset.StandardCharsets; /** * @author yudong * @date 2022/6/4 */ @Slf4j @Service public class UserServiceImpl implements UserService { @Override public SysUser createUser(CreateUserReqVo reqVo) { SysUser sysUser = new SysUser(); BeanUtils.copyProperties(reqVo, sysUser); String md5Pwd = DigestUtils.md5DigestAsHex(reqVo.getPassword().getBytes(StandardCharsets.UTF_8)); sysUser.setPassword(<PASSWORD>); return sysUser; } }
Julian-Theis/AVATAR
avatar/relgan/utils/utils.py
import numpy as np import tensorflow as tf import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import os import pprint from avatar.relgan.utils.text_process import * pp = pprint.PrettyPrinter() def generate_samples(sess, gen_x, batch_size, generated_num, output_file=None, get_code=True): # Generate Samples generated_samples = [] for _ in range(int(generated_num / batch_size)): generated_samples.extend(sess.run(gen_x)) codes = list() if output_file is not None: with open(output_file, 'w') as fout: for sent in generated_samples: buffer = ' '.join([str(x) for x in sent]) + '\n' fout.write(buffer) if get_code: codes.append(sent) return np.array(codes) codes = "" for sent in generated_samples: buffer = ' '.join([str(x) for x in sent]) + '\n' codes += buffer return codes def init_sess(): config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) sess.run(tf.global_variables_initializer()) return sess def pre_train_epoch(sess, g_pretrain_op, g_pretrain_loss, x_real, data_loader): # Pre-train the generator using MLE for one epoch supervised_g_losses = [] data_loader.reset_pointer() for it in range(data_loader.num_batch): batch = data_loader.next_batch() _, g_loss = sess.run([g_pretrain_op, g_pretrain_loss], feed_dict={x_real: batch}) supervised_g_losses.append(g_loss) return np.mean(supervised_g_losses) def plot_csv(csv_file, pre_epoch_num, metrics, method): names = [str(i) for i in range(len(metrics) + 1)] data = np.genfromtxt(csv_file, delimiter=',', skip_header=0, skip_footer=0, names=names) for idx in range(len(metrics)): metric_name = metrics[idx].get_name() plt.figure() plt.plot(data[names[0]], data[names[idx + 1]], color='r', label=method) plt.axvline(x=pre_epoch_num, color='k', linestyle='--') plt.xlabel('training epochs') plt.ylabel(metric_name) plt.legend() plot_file = os.path.join(os.path.dirname(csv_file), '{}_{}.pdf'.format(method, metric_name)) print(plot_file) plt.savefig(plot_file) def get_oracle_file(data_file, oracle_file, seq_len): tokens = get_tokenlized(data_file) word_set = get_word_list(tokens) [word_index_dict, index_word_dict] = get_dict(word_set) with open(oracle_file, 'w') as outfile: outfile.write(text_to_code(tokens, word_index_dict, seq_len)) return index_word_dict def get_real_test_file(generator_file, gen_save_file, iw_dict): codes = get_tokenlized(generator_file) with open(gen_save_file, 'w') as outfile: outfile.write(code_to_text(codes=codes, dictionary=iw_dict))
ouankou/rose
projects/Rose-To-LLVM/src/rosetollvm/ConstantExpressionEvaluator.cpp
#include <rosetollvm/ConstantExpressionEvaluator.h> /** * */ ConstantValue ConstantExpressionEvaluator::getValueExpressionValue(SgValueExp *valExp) { ConstantValue subtreeVal; if (isSgCharVal(valExp)) { subtreeVal.setIntValue(isSgCharVal(valExp) -> get_value()); } else if (isSgIntVal(valExp)) { subtreeVal.setIntValue(isSgIntVal(valExp) -> get_value()); } else if (isSgEnumVal(valExp)) { subtreeVal.setIntValue(isSgEnumVal(valExp) -> get_value()); } else if (isSgLongIntVal(valExp)) { subtreeVal.setIntValue(isSgLongIntVal(valExp) -> get_value()); } else if (isSgLongLongIntVal(valExp)) { subtreeVal.setIntValue(isSgLongLongIntVal(valExp) -> get_value()); } else if (isSgShortVal(valExp)) { subtreeVal.setIntValue(isSgShortVal(valExp) -> get_value()); } else if (isSgUnsignedIntVal(valExp)) { subtreeVal.setIntValue(isSgUnsignedIntVal(valExp) -> get_value()); } else if (isSgUnsignedLongVal(valExp)) { subtreeVal.setIntValue(isSgUnsignedLongVal(valExp) -> get_value()); } else if (isSgUnsignedLongLongIntVal(valExp)) { subtreeVal.setIntValue(isSgUnsignedLongLongIntVal(valExp) -> get_value()); } else if (isSgUnsignedShortVal(valExp)) { subtreeVal.setIntValue(isSgUnsignedShortVal(valExp) -> get_value()); } else if (isSgFloatVal(valExp)) { subtreeVal.setFloatValue(isSgFloatVal(valExp) -> get_value()); } else if (isSgDoubleVal(valExp)) { subtreeVal.setDoubleValue(isSgDoubleVal(valExp) -> get_value()); } else if (isSgLongDoubleVal(valExp)) { subtreeVal.setLongDoubleValue(isSgLongDoubleVal(valExp) -> get_value()); } else if (isSgComplexVal(valExp)) { SgComplexVal *complex_val = isSgComplexVal(valExp); if (isSgTypeFloat(complex_val -> get_precisionType())) { ROSE2LLVM_ASSERT(isSgFloatVal(complex_val -> get_real_value()) && isSgFloatVal(complex_val -> get_imaginary_value())); float real_value = isSgFloatVal(complex_val -> get_real_value()) -> get_value(), imaginary_value = isSgFloatVal(complex_val -> get_imaginary_value()) -> get_value(); std::complex<float> value(real_value, imaginary_value); subtreeVal.setFloatComplexValue(value); } else if (isSgTypeDouble(complex_val -> get_precisionType())) { ROSE2LLVM_ASSERT(isSgDoubleVal(complex_val -> get_real_value()) && isSgDoubleVal(complex_val -> get_imaginary_value())); double real_value = isSgDoubleVal(complex_val -> get_real_value()) -> get_value(), imaginary_value = isSgDoubleVal(complex_val -> get_imaginary_value()) -> get_value(); std::complex<double> value(real_value, imaginary_value); subtreeVal.setDoubleComplexValue(value); } else if (isSgTypeLongDouble(complex_val -> get_precisionType())) { ROSE2LLVM_ASSERT(isSgLongDoubleVal(complex_val -> get_real_value()) && isSgLongDoubleVal(complex_val -> get_imaginary_value())); long double real_value = isSgLongDoubleVal(complex_val -> get_real_value()) -> get_value(), imaginary_value = isSgLongDoubleVal(complex_val -> get_imaginary_value()) -> get_value(); std::complex<long double> value(real_value, imaginary_value); subtreeVal.setLongDoubleComplexValue(value); } else { cout << "*** Not yet able to process Complex constant value with base type " << valExp -> class_name() << endl; cout.flush(); ROSE2LLVM_ASSERT(0); } } else if (isSgStringVal(valExp)) { subtreeVal.setStringValue(isSgStringVal(valExp)); } else if (isSgBoolValExp(valExp)) { subtreeVal.setIntValue(isSgBoolValExp(valExp) -> get_value() != 0 ? 1 : 0); } else { cout << "*** Not yet able to process constant value of type " << valExp -> class_name() << endl; cout.flush(); ROSE2LLVM_ASSERT(0); } return subtreeVal; } /** * */ ConstantValue ConstantExpressionEvaluator::evaluateVariableReference(SgVarRefExp *ref) { ConstantValue value; SgVariableSymbol *sym = ref -> get_symbol(); ROSE2LLVM_ASSERT(sym); SgInitializedName *decl = sym -> get_declaration(); ROSE2LLVM_ASSERT(decl); SgModifierType *ref_type = isSgModifierType(ref -> get_type()); if (ref_type && ref_type -> get_typeModifier().get_constVolatileModifier().isConst()) { // check if this variable was assigned to a constant. // We know that the var value is const, so get the initialized name and evaluate it SgInitializer *initializer = decl -> get_initializer(); if (initializer && isSgAssignInitializer(initializer)) { SgExpression *rhs = isSgAssignInitializer(initializer) -> get_operand(); ConstantExpressionEvaluator variableEval(attributes); value = variableEval.traverse(rhs); } } return value; } /** * */ ConstantValue ConstantExpressionEvaluator::evaluateSynthesizedAttribute(SgNode *some_node, SynthesizedAttributesList synList) { SgExpression *node = isSgExpression(some_node); ROSE2LLVM_ASSERT(node); /** * Print debugging information, if requested. */ if (attributes -> getOption().isDebugPostTraversal()) { cerr << " Constant Visitor: " << ((unsigned long) node) << " " << ((unsigned long) node -> get_parent()) << " " << node -> class_name() << endl; // Used for Debugging if (isSgValueExp(node)) { SgValueExp *n = isSgValueExp(node); cerr << " Constant is ===> " << n -> get_constant_folded_value_as_string() << endl; } cerr.flush(); } // // The value that will be returned. // ConstantValue value; // by default, a ConstantValue has no value if (isSgValueExp(node)) { value = this -> getValueExpressionValue(isSgValueExp(node)); } else if (isSgNullExpression(node)) { value.setIntValue(0); } else if (isSgVarRefExp(node)) { value = evaluateVariableReference(isSgVarRefExp(node)); } else if (isSgSizeOfOp(node)) { SgSizeOfOp *sizeof_exp = (SgSizeOfOp *) node; IntAstAttribute *size_attribute = (IntAstAttribute *) sizeof_exp -> getAttribute(Control::LLVM_SIZE); ROSE2LLVM_ASSERT(size_attribute); value.setIntValue(size_attribute -> getValue()); } else if (isSgUnaryOp(node)) { assert(synList.size() == 1); if (isSgCastExp(node)) { // C99 explicitly states that "a cast does not yield an // lvalue" and that "the operand of the unary & operator // shall be either a function designator, the result of a [] // or unary * operator, or an lvalue that designates an // object that is not a bit-field and is not declared with // the register storage-class specifier". Hopefully ROSE // never inserts an implicit SgCastExp as the child of an // SgAddressOfOp. SgType *result_type = ((SgTypeAstAttribute *) node -> getAttribute(Control::LLVM_EXPRESSION_RESULT_TYPE)) -> getType(); /* SgType *operand_type = ((SgTypeAstAttribute *) isSgCastExp(node) -> get_operand() -> getAttribute(Control::LLVM_EXPRESSION_RESULT_TYPE)) -> getType(); cout << "Casting constant expression from type " << ((StringAstAttribute *) operand_type -> getAttribute(Control::LLVM_TYPE)) -> getValue() << " to type " << ((StringAstAttribute *) result_type -> getAttribute(Control::LLVM_TYPE)) -> getValue() << endl; cout.flush(); */ if (isSgTypeFloat(result_type)) { if (synList.at(0).hasIntValue()) { value.setFloatValue((float) synList.at(0).int_value); } else if (synList.at(0).hasFloatValue()) { value = synList.at(0); } else if (synList.at(0).hasDoubleValue()) { value.setFloatValue((float) synList.at(0).double_value); } else if (synList.at(0).hasLongDoubleValue()) { value.setFloatValue((float) synList.at(0).long_double_value); } } else if (isSgTypeDouble(result_type)) { if (synList.at(0).hasIntValue()) { value.setDoubleValue((double) synList.at(0).int_value); } else if (synList.at(0).hasFloatValue()) { value.setDoubleValue((double) synList.at(0).float_value); } else if (synList.at(0).hasDoubleValue()) { value = synList.at(0); } else if (synList.at(0).hasLongDoubleValue()) { value.setDoubleValue((double) synList.at(0).long_double_value); } } else if (isSgTypeLongDouble(result_type)) { if (synList.at(0).hasIntValue()) { value.setLongDoubleValue((long double) synList.at(0).int_value); } else if (synList.at(0).hasFloatValue()) { value.setLongDoubleValue((long double) synList.at(0).float_value); } else if (synList.at(0).hasDoubleValue()) { value.setLongDoubleValue((long double) synList.at(0).double_value); } else if (synList.at(0).hasLongDoubleValue()) { value = synList.at(0); } } else if (isSgTypeComplex(result_type)) { SgType *base_type = isSgTypeComplex(result_type) -> get_base_type(); if (isSgTypeFloat(base_type)) { if (synList.at(0).hasIntValue()) { value.setFloatComplexValue((std::complex<float>) synList.at(0).int_value); } else if (synList.at(0).hasFloatValue()) { value.setFloatComplexValue((std::complex<float>) synList.at(0).float_value); } else if (synList.at(0).hasDoubleValue()) { value.setFloatComplexValue((std::complex<float>) synList.at(0).double_value); } else if (synList.at(0).hasLongDoubleValue()) { value.setFloatComplexValue((std::complex<float>) synList.at(0).long_double_value); } else if (synList.at(0).hasFloatComplexValue()) { value = synList.at(0); } else if (synList.at(0).hasDoubleComplexValue()) { value.setFloatComplexValue((std::complex<float>) synList.at(0).double_complex_value); } else if (synList.at(0).hasLongDoubleComplexValue()) { value.setFloatComplexValue((std::complex<float>) synList.at(0).long_double_complex_value); } } else if (isSgTypeDouble(base_type)) { if (synList.at(0).hasIntValue()) { value.setDoubleComplexValue((std::complex<double>) synList.at(0).int_value); } else if (synList.at(0).hasFloatValue()) { value.setDoubleComplexValue((std::complex<double>) synList.at(0).float_value); } else if (synList.at(0).hasDoubleValue()) { value.setDoubleComplexValue((std::complex<double>) synList.at(0).double_value); } else if (synList.at(0).hasLongDoubleValue()) { value.setDoubleComplexValue((std::complex<double>) synList.at(0).long_double_value); } else if (synList.at(0).hasFloatComplexValue()) { value.setDoubleComplexValue((std::complex<double>) synList.at(0).float_complex_value); } else if (synList.at(0).hasDoubleComplexValue()) { value = synList.at(0); } else if (synList.at(0).hasLongDoubleComplexValue()) { value.setDoubleComplexValue((std::complex<double>) synList.at(0).long_double_complex_value); } } else if (isSgTypeLongDouble(base_type)) { if (synList.at(0).hasIntValue()) { value.setLongDoubleComplexValue((std::complex<long double>) synList.at(0).int_value); } else if (synList.at(0).hasFloatValue()) { value.setLongDoubleComplexValue((std::complex<long double>) synList.at(0).float_value); } else if (synList.at(0).hasDoubleValue()) { value.setLongDoubleComplexValue((std::complex<long double>) synList.at(0).double_value); } else if (synList.at(0).hasLongDoubleValue()) { value.setLongDoubleComplexValue((std::complex<long double>) synList.at(0).long_double_value); } else if (synList.at(0).hasFloatComplexValue()) { value.setLongDoubleComplexValue((std::complex<long double>) synList.at(0).float_complex_value); } else if (synList.at(0).hasDoubleComplexValue()) { value.setLongDoubleComplexValue((std::complex<long double>) synList.at(0).double_complex_value); } else if (synList.at(0).hasLongDoubleComplexValue()) { value = synList.at(0); } } } else if (attributes -> isIntegerType(result_type)) { // isIntegerType includes isBooleanType. if (synList.at(0).hasFloatValue()) { value.setIntValue((long long) synList.at(0).float_value); } else if (synList.at(0).hasDoubleValue()) { value.setIntValue((long long) synList.at(0).double_value); } else if (synList.at(0).hasLongDoubleValue()) { value.setIntValue((long long) synList.at(0).long_double_value); } else if (synList.at(0).hasIntValue()) { value = synList.at(0); } else if (! synList.at(0).hasArithmeticValue()) { // // If this is a conversion to the Boolean type and the operand is not an arithmetic value... // if (attributes -> isBooleanType(result_type)) { SgExpression *operand = isSgCastExp(node) -> get_operand(); SgType *operand_type = ((SgTypeAstAttribute *) operand -> getAttribute(Control::LLVM_EXPRESSION_RESULT_TYPE)) -> getType(); if (isSgPointerType(operand_type) || isSgTypeString(operand_type)) { value.setIntValue(1); // Except for the constant NULL, all pointer values are positive. } } } } } else if (isSgUnaryAddOp(node)) { value = synList.at(0); } else if (isSgMinusOp(node)) { if (synList.at(0).hasIntValue()) { value.setIntValue(- synList.at(0).int_value); } else if (synList.at(0).hasFloatValue()) { value.setFloatValue(- synList.at(0).float_value); } else if (synList.at(0).hasDoubleValue()) { value.setDoubleValue(- synList.at(0).double_value); } else if (synList.at(0).hasLongDoubleValue()) { value.setLongDoubleValue(- synList.at(0).long_double_value); } } else if (isSgBitComplementOp(node)) { if (synList.at(0).hasIntValue()) { value.setIntValue(~ synList.at(0).int_value); } } else if (isSgNotOp(node)) { if (synList.at(0).hasIntValue()) { value.setIntValue(! synList.at(0).int_value); } } } else if (isSgBinaryOp(node)) { assert(synList.size() == 2); if (synList.at(0).hasArithmeticValue() && synList.at(1).hasArithmeticValue()) { SgType *result_type = ((SgTypeAstAttribute *) node -> getAttribute(Control::LLVM_EXPRESSION_RESULT_TYPE)) -> getType(); if (isSgTypeFloat(result_type)) { float left = (synList.at(0).hasIntValue() ? (float) synList.at(0).int_value : synList.at(0).hasFloatValue() ? (float) synList.at(0).float_value : synList.at(0).hasDoubleValue() ? (float) synList.at(0).double_value : (float) synList.at(0).long_double_value); float right = (synList.at(1).hasIntValue() ? (float) synList.at(1).int_value : synList.at(1).hasFloatValue() ? (float) synList.at(1).float_value : synList.at(1).hasDoubleValue() ? (float) synList.at(1).double_value : (float) synList.at(1).long_double_value); if (isSgAddOp(node)) { value.setFloatValue(left + right); } else if (isSgSubtractOp(node)) { value.setFloatValue(left - right); } else if (isSgMultiplyOp(node)) { value.setFloatValue(left * right); } else if (isSgDivideOp(node)) { value.setFloatValue(left / right); } else if (isSgEqualityOp(node)) { value.setIntValue(left == right); } else if (isSgNotEqualOp(node)) { value.setIntValue(left != right); } else if (isSgLessThanOp(node)) { value.setIntValue(left < right); } else if (isSgLessOrEqualOp(node)) { value.setIntValue(left <= right); } else if (isSgGreaterThanOp(node)) { value.setIntValue(left > right); } else if (isSgGreaterOrEqualOp(node)) { value.setIntValue(left >= right); } else { std::cerr << "We don't yet evaluate floating-point binary Expression " << node -> class_name() << std::endl; } } else if (isSgTypeDouble(result_type)) { double left = (synList.at(0).hasIntValue() ? (double) synList.at(0).int_value : synList.at(0).hasFloatValue() ? (double) synList.at(0).float_value : synList.at(0).hasDoubleValue() ? (double) synList.at(0).double_value : (double) synList.at(0).long_double_value); double right = (synList.at(1).hasIntValue() ? (double) synList.at(1).int_value : synList.at(1).hasFloatValue() ? (double) synList.at(1).float_value : synList.at(1).hasDoubleValue() ? (double) synList.at(1).double_value : (double) synList.at(1).long_double_value); if (isSgAddOp(node)) { value.setDoubleValue(left + right); } else if (isSgSubtractOp(node)) { value.setDoubleValue(left - right); } else if (isSgMultiplyOp(node)) { value.setDoubleValue(left * right); } else if (isSgDivideOp(node)) { value.setDoubleValue(left / right); } else if (isSgEqualityOp(node)) { value.setIntValue(left == right); } else if (isSgNotEqualOp(node)) { value.setIntValue(left != right); } else if (isSgLessThanOp(node)) { value.setIntValue(left < right); } else if (isSgLessOrEqualOp(node)) { value.setIntValue(left <= right); } else if (isSgGreaterThanOp(node)) { value.setIntValue(left > right); } else if (isSgGreaterOrEqualOp(node)) { value.setIntValue(left >= right); } else { std::cerr << "We don't yet evaluate floating-point binary Expression " << node -> class_name() << std::endl; } } else if (isSgTypeLongDouble(result_type)) { long double left = (synList.at(0).hasIntValue() ? (long double) synList.at(0).int_value : synList.at(0).hasFloatValue() ? (long double) synList.at(0).float_value : synList.at(0).hasDoubleValue() ? (long double) synList.at(0).double_value : (long double) synList.at(0).long_double_value); long double right = (synList.at(1).hasIntValue() ? (long double) synList.at(1).int_value : synList.at(1).hasFloatValue() ? (long double) synList.at(1).float_value : synList.at(1).hasDoubleValue() ? (long double) synList.at(1).double_value : (long double) synList.at(1).long_double_value); if (isSgAddOp(node)) { value.setLongDoubleValue(left + right); } else if (isSgSubtractOp(node)) { value.setLongDoubleValue(left - right); } else if (isSgMultiplyOp(node)) { value.setLongDoubleValue(left * right); } else if (isSgDivideOp(node)) { value.setLongDoubleValue(left / right); } else if (isSgEqualityOp(node)) { value.setIntValue(left == right); } else if (isSgNotEqualOp(node)) { value.setIntValue(left != right); } else if (isSgLessThanOp(node)) { value.setIntValue(left < right); } else if (isSgLessOrEqualOp(node)) { value.setIntValue(left <= right); } else if (isSgGreaterThanOp(node)) { value.setIntValue(left > right); } else if (isSgGreaterOrEqualOp(node)) { value.setIntValue(left >= right); } else { std::cerr << "We don't yet evaluate floating-point binary Expression " << node -> class_name() << std::endl; } } else if (isSgTypeComplex(result_type)) { SgType *base_type = isSgTypeComplex(result_type) -> get_base_type(); if (isSgTypeFloat(base_type)) { ROSE2LLVM_ASSERT(synList.at(0).hasFloatComplexValue() && synList.at(1).hasFloatComplexValue()); std::complex<float> left = synList.at(0).float_complex_value, right = synList.at(1).float_complex_value; if (isSgAddOp(node)) { value.setFloatComplexValue(left + right); } else if (isSgSubtractOp(node)) { value.setFloatComplexValue(left - right); } else if (isSgMultiplyOp(node)) { value.setFloatComplexValue(left * right); } else if (isSgDivideOp(node)) { value.setFloatComplexValue(left / right); } else if (isSgEqualityOp(node)) { value.setIntValue(left == right); } else if (isSgNotEqualOp(node)) { value.setIntValue(left != right); } else { std::cerr << "We don't yet evaluate floating-point binary Expression " << node -> class_name() << std::endl; } } else if (isSgTypeDouble(base_type)) { ROSE2LLVM_ASSERT(synList.at(0).hasDoubleComplexValue() && synList.at(1).hasDoubleComplexValue()); std::complex<double> left = synList.at(0).double_complex_value, right = synList.at(1).double_complex_value; if (isSgAddOp(node)) { value.setDoubleComplexValue(left + right); } else if (isSgSubtractOp(node)) { value.setDoubleComplexValue(left - right); } else if (isSgMultiplyOp(node)) { value.setDoubleComplexValue(left * right); } else if (isSgDivideOp(node)) { value.setDoubleComplexValue(left / right); } else if (isSgEqualityOp(node)) { value.setIntValue(left == right); } else if (isSgNotEqualOp(node)) { value.setIntValue(left != right); } else { std::cerr << "We don't yet evaluate floating-point binary Expression " << node -> class_name() << std::endl; } } else if (isSgTypeLongDouble(base_type)) { ROSE2LLVM_ASSERT(synList.at(0).hasLongDoubleComplexValue() && synList.at(1).hasLongDoubleComplexValue()); std::complex<long double> left = synList.at(0).long_double_complex_value, right = synList.at(1).long_double_complex_value; if (isSgAddOp(node)) { value.setLongDoubleComplexValue(left + right); } else if (isSgSubtractOp(node)) { value.setLongDoubleComplexValue(left - right); } else if (isSgMultiplyOp(node)) { value.setLongDoubleComplexValue(left * right); } else if (isSgDivideOp(node)) { value.setLongDoubleComplexValue(left / right); } else if (isSgEqualityOp(node)) { value.setIntValue(left == right); } else if (isSgNotEqualOp(node)) { value.setIntValue(left != right); } else { std::cerr << "We don't yet evaluate floating-point binary Expression " << node -> class_name() << std::endl; } } } else { ROSE2LLVM_ASSERT(attributes -> isIntegerType(result_type)); long long left = (synList.at(0).hasIntValue() ? (long long) synList.at(0).int_value : synList.at(0).hasFloatValue() ? (long long) synList.at(0).float_value : synList.at(0).hasDoubleValue() ? (long long) synList.at(0).double_value : (long long) synList.at(0).long_double_value); long long right = (synList.at(1).hasIntValue() ? (long long) synList.at(1).int_value : synList.at(1).hasFloatValue() ? (long long) synList.at(1).float_value : synList.at(1).hasDoubleValue() ? (long long) synList.at(1).double_value : (long long) synList.at(1).long_double_value); if (isSgModOp(node)) { value.setIntValue(left % right); } else if (isSgAddOp(node)) { value.setIntValue(left + right); } else if (isSgSubtractOp(node)) { value.setIntValue(left - right); } else if (isSgMultiplyOp(node)) { value.setIntValue(left * right); } else if (isSgDivideOp(node)) { value.setIntValue(left / right); } else if (isSgEqualityOp(node)) { value.setIntValue(left == right); } else if (isSgNotEqualOp(node)) { value.setIntValue(left != right); } else if (isSgLessThanOp(node)) { value.setIntValue(left < right); } else if (isSgLessOrEqualOp(node)) { value.setIntValue(left <= right); } else if (isSgGreaterThanOp(node)) { value.setIntValue(left > right); } else if (isSgGreaterOrEqualOp(node)) { value.setIntValue(left >= right); } else if (isSgOrOp(node)) { value.setIntValue(left || right); } else if (isSgAndOp(node)) { value.setIntValue(left && right); } else if (isSgBitOrOp(node)) { value.setIntValue(left | right); } else if (isSgBitXorOp(node)) { value.setIntValue(left ^ right); } else if (isSgBitAndOp(node)) { value.setIntValue(left & right); } else if (isSgLshiftOp(node)) { value.setIntValue(left << right); } else if (isSgRshiftOp(node)) { value.setIntValue(left >> right); } else { std::cerr << "We don't yet evaluate integer binary Expression " << node -> class_name() << std::endl; } } } } else if (isSgConditionalExp(node)) { assert(synList.size() == 3); if (synList.at(0).hasIntValue()) { value = (synList.at(0).int_value ? synList.at(1) : synList.at(2)); } } // // Nodes with the LLVM_BOOLEAN_CAST attribute are nodes on which a boolean operation will be // performed that had not been explicitly cast into a boolean value by Rose. // if (node -> attributeExists(Control::LLVM_BOOLEAN_CAST)) { ROSE2LLVM_ASSERT(node -> attributeExists(Control::LLVM_EXPRESSION_RESULT_TYPE)); SgType *type = ((SgTypeAstAttribute *) node -> getAttribute(Control::LLVM_EXPRESSION_RESULT_TYPE)) -> getType(); if (isSgPointerType(type) || isSgTypeString(type)) { // a pointer address is always positive. value.setIntValue(1); } else if (value.hasFloatValue()) { value.setIntValue((long long) value.float_value); } else if (value.hasDoubleValue()) { value.setIntValue((long long ) value.double_value); } else if (value.hasLongDoubleValue()) { value.setIntValue((long long) value.long_double_value); } else if (! value.hasIntValue()) { // Should not happen !!! cout << ";*** Don't know yet how to cast node " << node -> class_name() << " of type " << node -> get_type() -> class_name() << endl; cout.flush(); ROSE2LLVM_ASSERT(false); } } return value; }
masud-technope/ACER-Replication-Package-ASE2017
corpus/class/eclipse.jdt.core/1490.java
<reponame>masud-technope/ACER-Replication-Package-ASE2017 package test.tags.others; /** * @author Zhao * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class X02 { }
tioga/notify-server
tioga-notify-kernel/src/test/java/org/tiogasolutions/notify/kernel/task/TaskGeneratorTest.java
package org.tiogasolutions.notify.kernel.task; import org.springframework.beans.factory.annotation.Autowired; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.tiogasolutions.notify.kernel.domain.DomainKernel; import org.tiogasolutions.notify.kernel.execution.ExecutionContext; import org.tiogasolutions.notify.kernel.execution.ExecutionManager; import org.tiogasolutions.notify.kernel.notification.CreateNotification; import org.tiogasolutions.notify.kernel.notification.NotificationDomain; import org.tiogasolutions.notify.kernel.test.TestFactory; import org.tiogasolutions.notify.pub.notification.Notification; import org.tiogasolutions.notify.pub.route.Destination; import org.tiogasolutions.notify.pub.task.TaskStatus; import org.tiogasolutions.notify.test.AbstractSpringTest; import java.util.List; import java.util.concurrent.Future; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; // HACK - disabled because we no longer have the hack in routing, need another way to test. @Test(enabled = false) public class TaskGeneratorTest extends AbstractSpringTest { @Autowired private TaskGenerator taskGenerator; @Autowired private TestFactory testFactory; @Autowired private DomainKernel domainKernel; @Autowired private ExecutionManager executionManager; private ExecutionContext executionContext; private NotificationDomain notificationDomain; @BeforeMethod public void beforeMethod() { /* System.getProperties().put("HACK_EMAIL_RECIPIENT", "<EMAIL>"); System.getProperties().put("HACK_GTALK_RECIPIENT", "<EMAIL>"); System.getProperties().put("HACK_SMS_RECIPIENT", "1234567890"); */ executionManager.newApiContext(TestFactory.API_KEY); executionContext = executionManager.context(); notificationDomain = domainKernel.notificationDomain(executionContext); } @AfterMethod public void afterMethod() { executionManager.clearContext(); } public void testGenerateTasks_WithException() throws Exception { // HACK - this is directly tied to the hack in the NotificationDomain.findActiveRoutes() CreateNotification create = testFactory.newCreateNotificationWithException(); Notification notification = testFactory.newNotification(executionContext, create).toNotification(); Future<List<TaskEntity>> future = taskGenerator.generateTasks(notificationDomain, notification); // TODO consider using wait - future.wait(); while (future.isDone() == false) { Thread.sleep(100); } List<TaskEntity> tasks = future.get(); assertEquals(tasks.size(), 4); validateTask(notification, tasks.get(0), "emailMsg", "<EMAIL>"); validateTask(notification, tasks.get(1), "emailMsg", "<EMAIL>"); validateTask(notification, tasks.get(2), "jabberMsg", "<EMAIL>"); validateTask(notification, tasks.get(3), "smsMsg", "1234567890"); } public void testGenerateTasks_NoException() throws Exception { // HACK - this is directly tied to the hack in the NotificationDomain.findActiveRoutes() CreateNotification create = testFactory.newCreateNotificationNoException(); Notification notification = testFactory.newNotification(executionContext, create).toNotification(); Future<List<TaskEntity>> future = taskGenerator.generateTasks(notificationDomain, notification); while (future.isDone() == false) { Thread.sleep(100); } List<TaskEntity> tasks = future.get(); assertEquals(tasks.size(), 1); validateTask(notification, tasks.get(0), "jabberMsg", "<EMAIL>"); } private void validateTask(Notification notification, TaskEntity task, String type, String recipient) { assertNotNull(task); assertNotNull(task.getTaskId()); Destination destination = task.getDestination(); assertEquals(destination.getArguments().get("recipient"), recipient); assertEquals(destination.getArguments().get("type"), type); assertEquals(task.getNotificationId(), notification.getNotificationId()); assertEquals(task.getTaskStatus(), TaskStatus.PENDING); } }
lu1995happy/Leetcode
Leetcode/556_nextGreaterElementIII.java
<gh_stars>0 import java.util.Arrays; public class nextGreaterElementIII { //At first, lets look at the edge cases - //If all digits sorted in descending order, then output is always “Not Possible”. For example, 4321. //If all digits are sorted in ascending order, then we need to swap last two digits. //For example, 1234. For other cases, we need to process the number from rightmost side //(why? because we need to find the smallest of all greater numbers) //Now the main algorithm works in following steps - //I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is //smaller than the previously traversed digit. For example, if the input number is “534976”, we stop //at 4 because 4 is smaller than next digit 9. If we do not find such a digit, //then output is “Not Possible”. //II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. //For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6. //III) Swap the above found two digits, we get 536974 in above example. //IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get //after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” //which is the next greater number for input 534976. public int nextGreaterElement(int n) { char[] ch = String.valueOf(n).toCharArray(); int length = ch.length - 1; int i = 0; // I) Start from the right most digit and // find the first digit that is // smaller than the digit next to it. for (i = length; i > 0; i--) { if (ch[i] > ch[i-1]) break; } // If no such digit is found, its the edge case 1. if (i == 0) return -1; // II) Find the smallest digit on right side of (i-1)'th // digit that is greater than number[i-1] int smallest = i; int index = ch[i - 1]; for (int j = i + 1; j < ch.length; j++) { if (ch[j] <= ch[smallest] && ch[j] > index) smallest = j; } // III) Swap the above found smallest digit with // number[i-1] char tmp = ch[smallest]; ch[smallest] = ch[i - 1]; ch[i - 1] = tmp; // IV) Sort the digits after (i-1) in ascending order Arrays.sort(ch, i, ch.length); long result = Long.parseLong(new String(ch)); return (result <= Integer.MAX_VALUE) ? (int)result : -1; } public int nextGreaterElements(int n) { if(n <= 0) return -1; char[] digit = (n + "").toCharArray(); int num = digit.length; for(int i = num - 2; i >= 0; i--){ if(digit[i] >= digit[i + 1]) continue; for(int j = num - 1; j > i; j--){ if(digit[j] > digit[i]) { swap(digit, i, j); reverse(digit, i + 1); try{ return Integer.parseInt(String.valueOf(digit)); } catch(Exception e){ return -1; } } } } return -1; } private void swap(char[] digit, int s, int d){ char tmp = digit[s]; digit[s] = digit[d]; digit[d] = tmp; } private void reverse(char[] digit, int s){ int e = digit.length - 1; while(s < e){ swap(digit, s, e); s++; e--; } } public static void main(String[] args) { nextGreaterElementIII test = new nextGreaterElementIII(); System.out.println(test.nextGreaterElement(1999999999)); } }
cdsc-github/parade-ara-simulator
benchmarks/SimicsHeader.cpp
<reponame>cdsc-github/parade-ara-simulator #include "SimicsHeader.h" #include <stdint.h> #include <stdlib.h> #include "m5op.h" #define MAGIC_LWI_REGISTER 0xC000 #define MAGIC_LWI_CLEAR_INTERRUPT 0xC004 #define MAGIC_LWI_CHECK 0xC00C #define MAGIC_LCACC_RESERVE 0xC010 #define MAGIC_LCACC_REQUEST 0xC011 #define MAGIC_LCACC_COMMAND 0xC012 #define MAGIC_LCACC_DECLARE_ACC 0xC019 #define MAGIC_BIN_CURVE 0xC020 #define MAGIC_LCACC_FREE 0xC013 /** MAGIC_CMD: * This is a macro that loads the 6 arguments for the added pseudo command * 0x0F 0x04 0x58, which causes a message to be sent to the specified * accelerator. */ #define MAGIC_CMD(RET,X,A1,A2,A3,A4,A5,A6,A7) \ uint64_t ret_val; \ __asm__ __volatile__ ("movq %1,%%rdi\n\tmovq %2,%%rsi\n\tmovq %3,%%rdx\n\tmovq %4,%%rcx\n\tmovq %5,%%r8\n\tmovq %6,%%r9\n\tmovq %7,%%r10\n\tmovq %8,%%r11\n\t.byte 0x0F,0x04\n\t.word 0x58\n\tmovq %%rax,%0" : "=r" (ret_val) : "g" ((uint64_t)X), "g" ((uint64_t)A1), "g" ((uint64_t)A2), "g" ((uint64_t)A3), "g" ((uint64_t)A4), "g" ((uint64_t)A5), "g" ((uint64_t)A6), "g" ((uint64_t)A7): "rdi", "rsi", "rdx", "rcx", "r8", "r9", "r10", "r11", "rax" ); \ RET = ret_val; InterruptArgs* LWI_CheckInterrupt(uint32_t thread) { InterruptArgs* ret = NULL; uint64_t val; //std::cout << "[LWI_CheckInterrupt]MAGIC_LWI_CHECK for thread " << thread << std::endl; MAGIC_CMD(val, MAGIC_LWI_CHECK, thread, 0,0,0,0,0,0); ret = reinterpret_cast<InterruptArgs*>(val); //std::cout << "[LWI_CheckInterrupt]Returned " << ret << std::endl; //std::cout << "[LWI_CheckInterrupt]InterruptArgs[" << ret << "]" << ret->status << ", " << ret->threadID << ", " << ret->lcaccID << ", " << ret->taskIndex << ", " << ret->lcaccMode << ", " << ret->replicate << std::endl; return ret; } void LWI_RegisterInterruptHandler(InterruptArgs* argPtr) { uint32_t lcacc = argPtr->lcaccID; uint32_t threadID = argPtr->threadID; int max = sizeof(InterruptArgs); //force the OS to allocate physical pages for (int i = 0; i < max; i += 4096) { uint8_t* x = ((uint8_t*)argPtr) + i; uint8_t touched = *x; *x = touched; } // Also need to touch the last byte, previous loop may miss the last page // (unaligned case) because the step is 4096 uint8_t trashVal = *(((uint8_t*)argPtr) + max - 1); *(((uint8_t*)argPtr) + max - 1) = trashVal; for (int i = 0; i < max;) { MAGIC_CMD(i, MAGIC_LWI_REGISTER, threadID, lcacc, argPtr, i, max,0,0); } } void LWI_ClearInterrupt(uint32_t thread) { int ret; MAGIC_CMD(ret, MAGIC_LWI_CLEAR_INTERRUPT, thread, 0,0,0,0,0,0); } void LWI_ClearInterrupt(uint32_t thread, InterruptArgs* args) { int ret; MAGIC_CMD(ret, MAGIC_LWI_CLEAR_INTERRUPT, thread, args,0,0,0,0,0); } void LWI_UnregisterInterruptHandler(uint32_t threadID, int lcacc) { } void LCAcc_Reserve(uint32_t threadID, int lcaccID, uint32_t kCycles) { int ret; MAGIC_CMD(ret, MAGIC_LCACC_RESERVE, threadID, lcaccID, kCycles, 0,0,0,0); } void LCAcc_Request(uint32_t threadID, uint32_t opMode, int requestAll) { int32_t actualOpMode = (int32_t)opMode; if (requestAll) { actualOpMode *= -1; } int ret; MAGIC_CMD(ret, MAGIC_LCACC_REQUEST, threadID, actualOpMode, 0,0,0,0,0); } void LCAcc_DeclareLCAccUse(uint32_t threadID, uint32_t opMode, uint32_t accCount) { int ret; MAGIC_CMD(ret, MAGIC_LCACC_DECLARE_ACC, threadID, opMode, accCount, 0,0,0,0); } void LCAcc_SendBiNCurve(uint32_t threadID, uint32_t bufSize, uint32_t bufTime, uint32_t cacheMod) { int ret; MAGIC_CMD(ret, MAGIC_BIN_CURVE, threadID, bufSize, bufTime, cacheMod, 0,0,0); } void LCAcc_Command(uint32_t threadID, int lcaccID, int32_t action, void* addr, int32_t arg1, int32_t arg2, int32_t arg3) { int finished = 0; while (!finished) { if (addr) { char* dummy = (char*) addr; char dummy2 = *dummy; *dummy = dummy2; } MAGIC_CMD(finished, MAGIC_LCACC_COMMAND, threadID, lcaccID, action, reinterpret_cast<uint64_t>(addr), arg1, arg2, arg3); //set return addresses } } void LCAcc_Free(uint32_t threadID, int lcaccID) { uint64_t ret; MAGIC_CMD(ret, MAGIC_LCACC_FREE, threadID, lcaccID, 0,0,0,0,0); //set return addresses } void BarrierTick(int t, int id) { uint64_t ret; //__asm__ __volatile__("lduw %0, %%l3;" : :"m"(t) : "%l3"); //__asm__ __volatile__("lduw %0, %%l4;" : :"m"(id) : "%l4"); //MAGIC_CMD(0xBA00); MAGIC_CMD(ret, 0xBA00, t, id, 0,0,0,0,0); } void StartSim(uint64_t workid, uint64_t threadid) { m5_reset_stats(0, 0); m5_work_begin(workid, threadid); } void EndSim(uint64_t workid, uint64_t threadid) { m5_work_end(workid, threadid); } void ResetStats() { m5_reset_stats(0, 0); } void DumpStats() { m5_dump_stats(0, 0); } void ExitSim() { m5_exit(0); } void KillSimulation() { while (true) { ExitSim(); } } void BarrierWait(int t, int id) { int x = 1; while (x) { MAGIC_CMD(x, 0xBA01, t, id, 0,0,0,0,0); } for (x = 0; x < 10; x++); } void simics_break() { m5_debugbreak(); } void simics_debug(uint32_t thread, uint32_t marker) { uint64_t ret; MAGIC_CMD(ret, 0xCCCE, thread, marker, 0,0,0,0,0); } void Touch(int thread, void* addr, uint32_t size) { uint8_t* a = (uint8_t*) addr; uint64_t ret; for (int i = 0; i < size; i += 4096) { { //enforce OS to allocate a physical page and setup the page table uint8_t trashVal = *(a + i); *(a + i) = trashVal; } MAGIC_CMD(ret, 0xC101, thread, (a + i), i, size, 0, 0, 0); } // Also need to touch the last byte, previous loop may miss the last page // (unaligned case) because the step is 4096 uint8_t trashVal = *(a + size - 1); *(a + size - 1) = trashVal; MAGIC_CMD(ret, 0xC101, thread, (a + size - 1), size - 1, size, 0, 0, 0); }
Tavi3h/LeetCode
src/pers/tavish/solution/medium/BinaryTreeRightSideView.java
package pers.tavish.solution.medium; import java.util.LinkedList; import java.util.List; import java.util.Queue; import pers.tavish.struct.TreeNode; /* Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <--- for more information: https://leetcode.com/problems/binary-tree-right-side-view/ */ public class BinaryTreeRightSideView { // BFS public List<Integer> rightSideView(TreeNode root) { List<Integer> res = new LinkedList<>(); if (root != null) { Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { int size = queue.size(); TreeNode node = null; for (int i = 0; i < size; i++) { node = queue.poll(); if (node.left != null) { queue.add(node.left); } if (node.right != null) { queue.add(node.right); } } res.add(node.val); // store the last element of each level } } return res; } }
Zhoutall/stasis
src/stasis/operations/prepare.c
/*--- This software is copyrighted by the Regents of the University of California, and other parties. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. The authors hereby grant permission to use, copy, modify, distribute, and license this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. No written agreement, license, or royalty fee is required for any of the authorized uses. Modifications to this software may be copyrighted by their authors and need not follow the licensing terms described here, provided that the new terms are clearly indicated on the first page of each file where they apply. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. GOVERNMENT USE: If you are acquiring this software on behalf of the U.S. government, the Government shall have only "Restricted Rights" in the software and related documentation as defined in the Federal Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you are acquiring the software on behalf of the Department of Defense, the software shall be classified as "Commercial Computer Software" and the Government shall have only "Restricted Rights" as defined in Clause 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the authors grant the U.S. Government and others acting in its behalf permission to use and distribute the software in accordance with the terms specified in this license. ---*/ /********************************************** * $Id$ * * sets the given reference to dat **********************************************/ #include <stasis/operations.h> #include <stasis/logger/logger2.h> #include <assert.h> #include <stdio.h> recordid prepare_bogus_rec = { 0, 0, 0}; static int op_prepare(const LogEntry * e, Page * p) { //NO-OP. return 0; } stasis_operation_impl stasis_op_impl_prepare() { stasis_operation_impl o = { OPERATION_PREPARE, /* id */ UNKNOWN_TYPE_PAGE, OPERATION_PREPARE, OPERATION_NOOP, &op_prepare/* Function */ }; return o; } /** PrepareGuardState is 1 if the iterator should continue on the next (previous) log entry, 0 otherwise. */ typedef struct{ int continueIterating; int prevLSN; int xid; int aborted; } PrepareGuardState; void * getPrepareGuardState() { PrepareGuardState * s = malloc (sizeof(PrepareGuardState)); s->continueIterating = 1; s->prevLSN = -1; s->xid = -1; s->aborted = 0; return s; } int prepareGuard(const LogEntry * e, void * state) { PrepareGuardState * pgs = state; int ret = pgs->continueIterating; if(e->type == UPDATELOG && !pgs->aborted) { if(e->update.funcID == OPERATION_PREPARE) { pgs->continueIterating = 0; pgs->prevLSN = e->prevLSN; } } else if (e->type == XABORT) { printf("xid %d aborted.\n", e->xid); pgs->aborted = 1; } if(pgs->xid == -1) { pgs->xid = e->xid; } else { assert(pgs->xid == e->xid); } return ret; } /** @todo When fleshing out the logHandle's prepareAction interface, figure out what the return value should mean... */ int prepareAction(void * state) { PrepareGuardState * pgs = state; int ret; if(!(pgs->continueIterating || pgs->aborted)) { //assert(pgs->prevLSN != -1); abort(); // Trevive(pgs->xid, pgs->prevLSN); ret = 1; } else { ret = 0; } return ret; }