text stringlengths 11 4.05M |
|---|
/*
* Copyright 2018- The Pixie Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package controllers
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/blang/semver"
"github.com/cenkalti/backoff/v4"
"github.com/gogo/protobuf/types"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"px.dev/pixie/src/api/proto/cloudpb"
"px.dev/pixie/src/api/proto/uuidpb"
"px.dev/pixie/src/api/proto/vizierconfigpb"
"px.dev/pixie/src/operator/apis/px.dev/v1alpha1"
version "px.dev/pixie/src/shared/goversion"
"px.dev/pixie/src/shared/services"
"px.dev/pixie/src/shared/status"
"px.dev/pixie/src/utils"
"px.dev/pixie/src/utils/shared/certs"
"px.dev/pixie/src/utils/shared/k8s"
)
const (
// This is the key for the annotation that the operator applies on all of its deployed resources for a CRD.
operatorAnnotation = "vizier-name"
clusterSecretJWTKey = "jwt-signing-key"
// updatingFailedTimeout is the amount of time we wait since an Updated started
// before we consider the Update Failed.
updatingFailedTimeout = 10 * time.Minute
// How often we should check whether a Vizier update failed.
updatingVizierCheckPeriod = 1 * time.Minute
)
// defaultClassAnnotationKey is the key in the annotation map which indicates
// a storage class is default.
var defaultClassAnnotationKeys = []string{"storageclass.kubernetes.io/is-default-class", "storageclass.beta.kubernetes.io/is-default-class"}
// VizierReconciler reconciles a Vizier object
type VizierReconciler struct {
client.Client
Scheme *runtime.Scheme
Clientset *kubernetes.Clientset
RestConfig *rest.Config
monitor *VizierMonitor
lastChecksum []byte
K8sVersion string
sentryFlush func()
}
// +kubebuilder:rbac:groups=pixie.px.dev,resources=viziers,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=pixie.px.dev,resources=viziers/status,verbs=get;update;patch
func getCloudClientConnection(cloudAddr string, devCloudNS string, extraDialOpts ...grpc.DialOption) (*grpc.ClientConn, error) {
isInternal := false
if devCloudNS != "" {
cloudAddr = fmt.Sprintf("api-service.%s.svc.cluster.local:51200", devCloudNS)
isInternal = true
}
dialOpts, err := services.GetGRPCClientDialOptsServerSideTLS(isInternal)
dialOpts = append(dialOpts, extraDialOpts...)
if err != nil {
return nil, err
}
c, err := grpc.Dial(cloudAddr, dialOpts...)
if err != nil {
return nil, err
}
return c, nil
}
func getLatestVizierVersion(ctx context.Context, client cloudpb.ArtifactTrackerClient) (string, error) {
req := &cloudpb.GetArtifactListRequest{
ArtifactName: "vizier",
ArtifactType: cloudpb.AT_CONTAINER_SET_YAMLS,
Limit: 1,
}
resp, err := client.GetArtifactList(ctx, req)
if err != nil {
return "", err
}
if len(resp.Artifact) != 1 {
return "", errors.New("Could not find Vizier artifact")
}
return resp.Artifact[0].VersionStr, nil
}
// Kubernetes used to have in-tree plugins for a variety of vendor CSI drivers.
// These provisioners had "kubernetes.io/" prefixes. Often times these provisioner names
// are still used in the storageclass but the calls are redirected to CSIDrivers under new names.
// This map maintains that list of redirects.
// See https://kubernetes.io/docs/concepts/storage/volumes and
// https://kubernetes.io/docs/concepts/storage/storage-classes/#provisioner.
var migratedCSIDrivers = map[string]string{
"kubernetes.io/aws-ebs": "ebs.csi.aws.com",
"kubernetes.io/azure-disk": "disk.csi.azure.com",
"kubernetes.io/azure-file": "file.csi.azure.com",
"kubernetes.io/cinder": "cinder.csi.openstack.org",
"kubernetes.io/gce-pd": "pd.csi.storage.gke.io",
"kubernetes.io/portworx-volume": "pxd.portworx.com",
"kubernetes.io/vsphere-volume": "csi.vsphere.vmware.com",
}
func hasCSIDriver(clientset *kubernetes.Clientset, name string) (bool, error) {
_, err := clientset.StorageV1().CSIDrivers().Get(context.Background(), name, metav1.GetOptions{})
if err != nil && !k8serrors.IsNotFound(err) {
return false, err
} else if k8serrors.IsNotFound(err) {
return false, nil
}
return true, nil
}
func defaultStorageClassHasCSIDriver(clientset *kubernetes.Clientset) (bool, error) {
storageClasses, err := clientset.StorageV1().StorageClasses().List(context.Background(), metav1.ListOptions{})
if err != nil {
return false, err
}
var defaultStorageClass *storagev1.StorageClass
// Check annotations map on each storage class to see if default is set to "true".
for _, storageClass := range storageClasses.Items {
annotationsMap := storageClass.GetAnnotations()
for _, key := range defaultClassAnnotationKeys {
if annotationsMap[key] == "true" {
defaultStorageClass = &storageClass
break
}
}
}
if defaultStorageClass == nil {
return false, errors.New("no default storage class")
}
csi := defaultStorageClass.Provisioner
if migrated, ok := migratedCSIDrivers[csi]; ok {
csi = migrated
}
// For all non-migrated kubernetes provisioners, kubernetes itself will have an internal provisioner,
// so no need to check for a CSIDriver.
if strings.HasPrefix(csi, "kubernetes.io/") {
return true, nil
}
// If the provisioner contains a "/" then we assume it is a custom provisioner that doesn't use the CSI pattern,
// so we skip checking for a CSIDriver and hope the provisioner works.
if strings.Contains(csi, "/") {
return true, nil
}
return hasCSIDriver(clientset, csi)
}
// missingNecessaryCSIDriver checks if the user is running an EKS cluster, and if so, whether they are
// missing the CSIDriver. Without the CSI driver, persistent volumes may not be able to be deployed.
func missingNecessaryCSIDriver(clientset *kubernetes.Clientset, k8sVersion string) bool {
// This check only needs to be done for eks clusters with K8s version > 1.22.0.
if !strings.Contains(k8sVersion, "-eks-") {
return false
}
parsedVersion, err := semver.ParseTolerant(k8sVersion)
if err != nil {
log.WithError(err).Error("Failed to parse K8s cluster version")
return false
}
driverVersionRange, _ := semver.ParseRange("<=1.22.0")
if driverVersionRange(parsedVersion) {
return false
}
hasDriver, err := defaultStorageClassHasCSIDriver(clientset)
if err != nil {
log.WithError(err).Warn("failed to determine if the default storage class has a valid CSI driver")
return false
}
return !hasDriver
}
// validateNumDefaultStorageClasses returns a boolean whether there is exactly
// 1 default storage class or not.
func validateNumDefaultStorageClasses(clientset *kubernetes.Clientset) (bool, error) {
storageClasses, err := clientset.StorageV1().StorageClasses().List(context.Background(), metav1.ListOptions{})
if err != nil {
return false, err
}
defaultClassCount := 0
// Check annotations map on each storage class to see if default is set to "true".
for _, storageClass := range storageClasses.Items {
annotationsMap := storageClass.GetAnnotations()
for _, key := range defaultClassAnnotationKeys {
if annotationsMap[key] == "true" {
// It is possible for some storageClasses to have both the beta/non-beta annotation.
// We break here so that we don't double count this storageClass.
defaultClassCount++
break
}
}
}
return defaultClassCount == 1, nil
}
// Reconcile updates the Vizier running in the cluster to match the expected state.
func (r *VizierReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log.WithField("req", req).Info("Reconciling Vizier...")
// Fetch vizier CRD to determine what operation should be performed.
var vizier v1alpha1.Vizier
if err := r.Get(ctx, req.NamespacedName, &vizier); err != nil {
err = r.deleteVizier(ctx, req)
if err != nil {
log.WithError(err).Info("Failed to delete Vizier instance")
}
if r.monitor != nil && r.monitor.namespace == req.Namespace {
r.monitor.Quit()
r.monitor = nil
}
// Vizier CRD deleted. The vizier instance should also be deleted.
return ctrl.Result{}, err
}
// Check if vizier already exists, if not create a new vizier.
if vizier.Status.VizierPhase == v1alpha1.VizierPhaseNone && vizier.Status.ReconciliationPhase == v1alpha1.ReconciliationPhaseNone {
// We are creating a new vizier instance.
err := r.createVizier(ctx, req, &vizier)
if err != nil {
log.WithError(err).Info("Failed to deploy new Vizier instance")
}
return ctrl.Result{}, err
}
err := r.updateVizier(ctx, req, &vizier)
if err != nil {
log.WithError(err).Info("Failed to update Vizier instance")
}
// Check if we are already monitoring this Vizier.
if r.monitor == nil || r.monitor.namespace != req.Namespace || r.monitor.devCloudNamespace != vizier.Spec.DevCloudNamespace {
if r.monitor != nil {
r.monitor.Quit()
r.monitor = nil
}
r.monitor = &VizierMonitor{
namespace: req.Namespace,
namespacedName: req.NamespacedName,
devCloudNamespace: vizier.Spec.DevCloudNamespace,
vzUpdate: r.Status().Update,
vzGet: r.Get,
clientset: r.Clientset,
vzSpecUpdate: r.Update,
restConfig: r.RestConfig,
}
cloudClient, err := getCloudClientConnection(vizier.Spec.CloudAddr, vizier.Spec.DevCloudNamespace, grpc.FailOnNonTempDialError(true), grpc.WithBlock())
if err != nil {
vizier.SetStatus(status.UnableToConnectToCloud)
err := r.Status().Update(ctx, &vizier)
if err != nil {
if strings.Contains(err.Error(), "timeout") {
log.WithError(err).Info("Timed out trying to update vizier status. K8s API server may be overloaded")
} else {
log.WithError(err).Error("Failed to update vizier status")
}
}
log.WithError(err).Error("Failed to connect to Pixie cloud")
return ctrl.Result{}, err
}
if r.sentryFlush == nil {
r.sentryFlush = setupSentry(ctx, cloudClient, r.Clientset)
}
r.monitor.InitAndStartMonitor(cloudClient)
// Update operator version
vizier.Status.OperatorVersion = version.GetVersion().ToString()
err = r.Status().Update(ctx, &vizier)
if err != nil {
if strings.Contains(err.Error(), "timeout") {
log.WithError(err).Info("Timed out trying to update vizier status. K8s API server may be overloaded")
} else {
log.WithError(err).Error("Failed to update vizier status")
}
}
}
// Vizier CRD has been updated, and we should update the running vizier accordingly.
return ctrl.Result{}, err
}
// updateVizier updates the vizier instance according to the spec.
func (r *VizierReconciler) updateVizier(ctx context.Context, req ctrl.Request, vz *v1alpha1.Vizier) error {
log.Info("Updating Vizier...")
checksum, err := getSpecChecksum(vz)
if err != nil {
return err
}
if bytes.Equal(checksum, vz.Status.Checksum) {
log.Info("Checksums matched, no need to reconcile")
return nil
}
if len(vz.Status.Checksum) == 0 && bytes.Equal(checksum, r.lastChecksum) {
log.Warn("No checksum written to status")
log.Info("Checksums matched, no need to reconcile")
return nil
}
if vz.Status.ReconciliationPhase == v1alpha1.ReconciliationPhaseUpdating {
log.Info("Already in the process of updating, nothing to do")
return nil
}
log.Infof("Status checksum '%x' does not match spec checksum '%x' - running an update", vz.Status.Checksum, checksum)
return r.deployVizier(ctx, req, vz, true)
}
// deleteVizier deletes the vizier instance in the given namespace.
func (r *VizierReconciler) deleteVizier(ctx context.Context, req ctrl.Request) error {
log.WithField("req", req).Info("Deleting Vizier...")
od := k8s.ObjectDeleter{
Namespace: req.Namespace,
Clientset: r.Clientset,
RestConfig: r.RestConfig,
Timeout: 2 * time.Minute,
}
keyValueLabel := operatorAnnotation + "=" + req.Name
_, _ = od.DeleteByLabel(keyValueLabel)
return nil
}
// createVizier deploys a new vizier instance in the given namespace.
func (r *VizierReconciler) createVizier(ctx context.Context, req ctrl.Request, vz *v1alpha1.Vizier) error {
log.Info("Creating a new vizier instance")
cloudClient, err := getCloudClientConnection(vz.Spec.CloudAddr, vz.Spec.DevCloudNamespace)
if err != nil {
vz.SetStatus(status.UnableToConnectToCloud)
err := r.Status().Update(ctx, vz)
if err != nil {
if strings.Contains(err.Error(), "timeout") {
log.WithError(err).Info("Timed out trying to update vizier status. K8s API server may be overloaded")
} else {
log.WithError(err).Error("Failed to update vizier status")
}
}
log.WithError(err).Error("Failed to connect to Pixie cloud")
return err
}
// If no version is set, we should fetch the latest version. This will trigger another reconcile that will do
// the actual vizier deployment.
if vz.Spec.Version == "" {
atClient := cloudpb.NewArtifactTrackerClient(cloudClient)
latest, err := getLatestVizierVersion(ctx, atClient)
if err != nil {
log.WithError(err).Error("Failed to get latest Vizier version")
return err
}
vz.Spec.Version = latest
err = r.Update(ctx, vz)
if err != nil {
log.WithError(err).Error("Failed to update version in Vizier spec")
return err
}
return nil
}
return r.deployVizier(ctx, req, vz, false)
}
func (r *VizierReconciler) deployVizier(ctx context.Context, req ctrl.Request, vz *v1alpha1.Vizier, update bool) error {
log.Info("Starting a vizier deploy")
cloudClient, err := getCloudClientConnection(vz.Spec.CloudAddr, vz.Spec.DevCloudNamespace)
if err != nil {
vz.SetStatus(status.UnableToConnectToCloud)
err := r.Status().Update(ctx, vz)
if err != nil {
if strings.Contains(err.Error(), "timeout") {
log.WithError(err).Info("Timed out trying to update vizier status. K8s API server may be overloaded")
} else {
log.WithError(err).Error("Failed to update vizier status")
}
}
log.WithError(err).Error("Failed to connect to Pixie cloud")
return err
}
// Set the status of the Vizier.
vz.SetReconciliationPhase(v1alpha1.ReconciliationPhaseUpdating)
err = r.Status().Update(ctx, vz)
if err != nil {
log.WithError(err).Error("Failed to update status in Vizier spec")
return err
}
// Add an additional annotation to our deployed vizier-resources, to allow easier tracking of the vizier resources.
if vz.Spec.Pod == nil {
vz.Spec.Pod = &v1alpha1.PodPolicy{}
}
if vz.Spec.Pod.Annotations == nil {
vz.Spec.Pod.Annotations = make(map[string]string)
}
if vz.Spec.Pod.Labels == nil {
vz.Spec.Pod.Labels = make(map[string]string)
}
if vz.Spec.Pod.NodeSelector == nil {
vz.Spec.Pod.NodeSelector = make(map[string]string)
}
if !vz.Spec.UseEtcdOperator && !update {
// Check if the cluster offers PVC support.
// If it does not, we should default to using the etcd operator, which does not
// require PVC support.
defaultStorageExists, err := validateNumDefaultStorageClasses(r.Clientset)
if err != nil {
log.WithError(err).Error("Error checking default storage classes")
}
missingCSIDriver := missingNecessaryCSIDriver(r.Clientset, r.K8sVersion)
if !defaultStorageExists || missingCSIDriver {
log.Warn("No default storage class detected for cluster. Deploying etcd operator instead of statefulset for metadata backend.")
vz.Spec.UseEtcdOperator = true
}
}
vz.Spec.Pod.Annotations[operatorAnnotation] = req.Name
vz.Spec.Pod.Labels[operatorAnnotation] = req.Name
// Update the spec in the k8s api as other parts of the code expect this to be true.
err = r.Update(ctx, vz)
if err != nil {
log.WithError(err).Error("Failed to update spec for Vizier CRD")
return err
}
// Get the checksum up here in case the spec changes midway through.
checksum, err := getSpecChecksum(vz)
if err != nil {
return err
}
// Get the Vizier's ID from the cluster's secrets.
vizierID, err := getVizierID(r.Clientset, req.Namespace)
if err != nil {
log.WithError(err).Error("Failed to retrieve the Vizier ID from the cluster's secrets")
}
configForVizierResp, err := generateVizierYAMLsConfig(ctx, req.Namespace, r.K8sVersion, vizierID, vz, cloudClient)
if err != nil {
log.WithError(err).Error("Failed to generate configs for Vizier YAMLs")
return err
}
yamlMap := configForVizierResp.NameToYamlContent
// Update Vizier CRD status sentryDSN so that it can be accessed by other
// vizier pods.
vz.Status.SentryDSN = configForVizierResp.SentryDSN
if !update {
err = r.deployVizierConfigs(ctx, req.Namespace, vz, yamlMap)
if err != nil {
log.WithError(err).Error("Failed to deploy Vizier configs")
return err
}
err = r.deployVizierCerts(ctx, req.Namespace, vz)
if err != nil {
log.WithError(err).Error("Failed to deploy Vizier certs")
return err
}
err = r.deployNATSStatefulset(ctx, req.Namespace, vz, yamlMap)
if err != nil {
log.WithError(err).Error("Failed to deploy NATS")
return err
}
} else {
err = r.upgradeNats(ctx, req.Namespace, vz, yamlMap)
if err != nil {
log.WithError(err).Warning("Failed to upgrade nats")
}
}
if vz.Spec.UseEtcdOperator {
err := r.Clientset.AppsV1().StatefulSets(req.Namespace).Delete(ctx, "vizier-metadata", metav1.DeleteOptions{})
if err != nil && k8serrors.IsNotFound(err) {
log.Debug("vizier-metadata statefulset not found, skipping deletion")
} else if err != nil {
log.WithError(err).Error("Failed to delete vizier-metadata statefulset")
return err
} else {
log.Info("Deleted vizier-metadata statefulset")
}
err = r.deployEtcdStatefulset(ctx, req.Namespace, vz, yamlMap)
if err != nil {
log.WithError(err).Error("Failed to deploy etcd")
return err
}
} else {
// Delete the etcd statefulset if it exists.
err := r.Clientset.AppsV1().StatefulSets(req.Namespace).Delete(ctx, "pl-etcd", metav1.DeleteOptions{})
if err != nil && k8serrors.IsNotFound(err) {
log.Debug("pl-etcd statefulset not found, skipping deletion")
} else if err != nil {
log.WithError(err).Error("Failed to delete pl-etcd statefulset")
return err
} else {
log.Info("Deleted pl-etcd statefulset")
}
err = r.Clientset.AppsV1().Deployments(req.Namespace).Delete(ctx, "vizier-metadata", metav1.DeleteOptions{})
if err != nil && k8serrors.IsNotFound(err) {
log.Debug("vizier-metadata deployment not found, skipping deletion")
} else if err != nil {
log.WithError(err).Error("Failed to delete metadata deployment")
return err
} else {
log.Info("Deleted vizier-metadata deployment")
}
}
err = r.deployVizierCore(ctx, req.Namespace, vz, yamlMap, update)
if err != nil {
log.WithError(err).Info("Failed to deploy Vizier core")
return err
}
// TODO(michellenguyen): Remove when the operator has the ability to ping CloudConn for Vizier Version.
// We are currently blindly assuming that the new version is correct.
_ = waitForCluster(r.Clientset, req.Namespace)
// Refetch the Vizier resource, as it may have changed in the time in which we were waiting for the cluster.
err = r.Get(ctx, req.NamespacedName, vz)
if err != nil {
log.WithError(err).Info("Failed to get vizier after deploy. Vizier was likely deleted")
// The Vizier was deleted in the meantime. Do nothing.
return nil
}
vz.Status.Version = vz.Spec.Version
vz.SetReconciliationPhase(v1alpha1.ReconciliationPhaseReady)
vz.Status.Checksum = checksum
r.lastChecksum = checksum
err = r.Status().Update(ctx, vz)
if err != nil {
return err
}
log.Info("Vizier deploy is complete")
return nil
}
func getSpecChecksum(vz *v1alpha1.Vizier) ([]byte, error) {
specStr, err := json.Marshal(vz.Spec)
if err != nil {
log.WithError(err).Info("Failed to marshal spec to JSON")
return nil, err
}
h := sha256.New()
h.Write([]byte(specStr))
return h.Sum(nil), nil
}
func (r *VizierReconciler) upgradeNats(ctx context.Context, namespace string, vz *v1alpha1.Vizier, yamlMap map[string]string) error {
log.Info("Upgrading NATS if necessary")
ss, err := r.Clientset.AppsV1().StatefulSets(namespace).Get(ctx, "pl-nats", metav1.GetOptions{})
if err != nil {
log.WithError(err).Info("No NATS currently running")
return r.deployNATSStatefulset(ctx, namespace, vz, yamlMap)
}
containers := ss.Spec.Template.Spec.Containers
if len(containers) == 0 {
log.Info("NATS seems to have no containers")
return r.deployNATSStatefulset(ctx, namespace, vz, yamlMap)
}
natsImage := containers[0].Image
resources, err := k8s.GetResourcesFromYAML(strings.NewReader(yamlMap["nats"]))
if err != nil {
return err
}
var newSS appsv1.StatefulSet
for _, r := range resources {
if r.GVK.Kind != "StatefulSet" {
continue
}
err = runtime.DefaultUnstructuredConverter.FromUnstructured(r.Object.UnstructuredContent(), &newSS)
if err != nil {
log.WithError(err).Info("Could not decode NATS Statefulset")
return err
}
break
}
if len(newSS.Spec.Template.Spec.Containers) == 0 {
log.Info("New NATS spec seems to have no containers")
return r.deployNATSStatefulset(ctx, namespace, vz, yamlMap)
}
if natsImage == newSS.Spec.Template.Spec.Containers[0].Image {
log.Info("NATS up to date. Nothing to do.")
return nil
}
log.Info("Will upgrade NATS")
return r.deployNATSStatefulset(ctx, namespace, vz, yamlMap)
}
func (r *VizierReconciler) deployVizierCerts(ctx context.Context, namespace string, vz *v1alpha1.Vizier) error {
return deployCerts(ctx, namespace, vz, r.Clientset, r.RestConfig, false)
}
func deployCerts(ctx context.Context, namespace string, vz *v1alpha1.Vizier, clientset kubernetes.Interface, restConfig *rest.Config, update bool) error {
log.Info("Generating certs")
// Assign JWT signing key.
jwtSigningKey := make([]byte, 64)
_, err := rand.Read(jwtSigningKey)
if err != nil {
return err
}
s := k8s.GetSecret(clientset, namespace, "pl-cluster-secrets")
if s == nil {
return errors.New("pl-cluster-secrets does not exist")
}
s.Data[clusterSecretJWTKey] = []byte(fmt.Sprintf("%x", jwtSigningKey))
_, err = clientset.CoreV1().Secrets(namespace).Update(ctx, s, metav1.UpdateOptions{})
if err != nil {
return err
}
certYAMLs, err := certs.GenerateVizierCertYAMLs(namespace)
if err != nil {
return err
}
resources, err := k8s.GetResourcesFromYAML(strings.NewReader(certYAMLs))
if err != nil {
return err
}
for _, r := range resources {
err = updateResourceConfiguration(r, vz)
if err != nil {
return err
}
}
return k8s.ApplyResources(clientset, restConfig, resources, namespace, nil, update)
}
// deployVizierConfigs deploys the secrets, configmaps, and certs that are necessary for running vizier.
func (r *VizierReconciler) deployVizierConfigs(ctx context.Context, namespace string, vz *v1alpha1.Vizier, yamlMap map[string]string) error {
log.Info("Deploying Vizier configs and secrets")
resources, err := k8s.GetResourcesFromYAML(strings.NewReader(yamlMap["secrets"]))
if err != nil {
return err
}
for _, r := range resources {
err = updateResourceConfiguration(r, vz)
if err != nil {
return err
}
}
return k8s.ApplyResources(r.Clientset, r.RestConfig, resources, namespace, nil, false)
}
// deployNATSStatefulset deploys nats to the given namespace.
func (r *VizierReconciler) deployNATSStatefulset(ctx context.Context, namespace string, vz *v1alpha1.Vizier, yamlMap map[string]string) error {
log.Info("Deploying NATS")
resources, err := k8s.GetResourcesFromYAML(strings.NewReader(yamlMap["nats"]))
if err != nil {
return err
}
for _, r := range resources {
err = updateResourceConfiguration(r, vz)
if err != nil {
return err
}
}
return retryDeploy(r.Clientset, r.RestConfig, namespace, resources, true)
}
// deployEtcdStatefulset deploys etcd to the given namespace.
func (r *VizierReconciler) deployEtcdStatefulset(ctx context.Context, namespace string, vz *v1alpha1.Vizier, yamlMap map[string]string) error {
log.Info("Deploying etcd")
resources, err := k8s.GetResourcesFromYAML(strings.NewReader(yamlMap["etcd"]))
if err != nil {
return err
}
for _, r := range resources {
err = updateResourceConfiguration(r, vz)
if err != nil {
return err
}
}
return retryDeploy(r.Clientset, r.RestConfig, namespace, resources, false)
}
// deployVizierCore deploys the core pods and services for running vizier.
func (r *VizierReconciler) deployVizierCore(ctx context.Context, namespace string, vz *v1alpha1.Vizier, yamlMap map[string]string, allowUpdate bool) error {
log.Info("Deploying Vizier")
vzYaml := "vizier_persistent"
if vz.Spec.UseEtcdOperator {
vzYaml = "vizier_etcd"
}
if vz.Spec.Autopilot {
vzYaml = fmt.Sprintf("%s_ap", vzYaml)
}
resources, err := k8s.GetResourcesFromYAML(strings.NewReader(yamlMap[vzYaml]))
if err != nil {
log.WithError(err).Error("Error getting resources from Vizier YAML")
return err
}
for _, r := range resources {
err = updateResourceConfiguration(r, vz)
if err != nil {
log.WithError(err).Error("Failed to update resource configuration for resources")
return err
}
}
err = retryDeploy(r.Clientset, r.RestConfig, namespace, resources, allowUpdate)
if err != nil {
log.WithError(err).Error("Retry deploy of Vizier failed")
return err
}
return nil
}
func updateResourceConfiguration(resource *k8s.Resource, vz *v1alpha1.Vizier) error {
// Add custom labels and annotations to the k8s resource.
addKeyValueMapToResource("labels", vz.Spec.Pod.Labels, resource.Object.Object)
addKeyValueMapToResource("annotations", vz.Spec.Pod.Annotations, resource.Object.Object)
updateResourceRequirements(vz.Spec.Pod.Resources, resource.Object.Object)
updatePodSpec(vz.Spec.Pod.NodeSelector, vz.Spec.Pod.Tolerations, vz.Spec.Pod.SecurityContext, resource.Object.Object)
return nil
}
func convertResourceType(originalLst v1.ResourceList) *vizierconfigpb.ResourceList {
transformedList := make(map[string]*vizierconfigpb.ResourceQuantity)
for rName, rQuantity := range originalLst {
transformedList[string(rName)] = &vizierconfigpb.ResourceQuantity{
Value: rQuantity.String(),
}
}
return &vizierconfigpb.ResourceList{
ResourceList: transformedList,
}
}
// generateVizierYAMLsConfig is responsible retrieving a yaml map of configurations from
// Pixie Cloud.
func generateVizierYAMLsConfig(ctx context.Context, ns string, k8sVersion string, vizierID *uuidpb.UUID, vz *v1alpha1.Vizier, conn *grpc.ClientConn) (*cloudpb.ConfigForVizierResponse,
error) {
client := cloudpb.NewConfigServiceClient(conn)
req := &cloudpb.ConfigForVizierRequest{
Namespace: ns,
K8sVersion: k8sVersion,
VizierID: vizierID,
VzSpec: &vizierconfigpb.VizierSpec{
Version: vz.Spec.Version,
DeployKey: vz.Spec.DeployKey,
CustomDeployKeySecret: vz.Spec.CustomDeployKeySecret,
DisableAutoUpdate: vz.Spec.DisableAutoUpdate,
UseEtcdOperator: vz.Spec.UseEtcdOperator,
ClusterName: vz.Spec.ClusterName,
CloudAddr: vz.Spec.CloudAddr,
DevCloudNamespace: vz.Spec.DevCloudNamespace,
PemMemoryLimit: vz.Spec.PemMemoryLimit,
PemMemoryRequest: vz.Spec.PemMemoryRequest,
ClockConverter: string(vz.Spec.ClockConverter),
DataAccess: string(vz.Spec.DataAccess),
Pod_Policy: &vizierconfigpb.PodPolicyReq{
Labels: vz.Spec.Pod.Labels,
Annotations: vz.Spec.Pod.Annotations,
Resources: &vizierconfigpb.ResourceReqs{
Limits: convertResourceType(vz.Spec.Pod.Resources.Limits),
Requests: convertResourceType(vz.Spec.Pod.Resources.Requests),
},
NodeSelector: vz.Spec.Pod.NodeSelector,
Tolerations: convertTolerations(vz.Spec.Pod.Tolerations),
},
Patches: vz.Spec.Patches,
Registry: vz.Spec.Registry,
},
}
if vz.Spec.DataCollectorParams != nil {
req.VzSpec.DataCollectorParams = &vizierconfigpb.DataCollectorParams{
DatastreamBufferSize: vz.Spec.DataCollectorParams.DatastreamBufferSize,
DatastreamBufferSpikeSize: vz.Spec.DataCollectorParams.DatastreamBufferSpikeSize,
CustomPEMFlags: vz.Spec.DataCollectorParams.CustomPEMFlags,
}
}
if vz.Spec.LeadershipElectionParams != nil {
req.VzSpec.LeadershipElectionParams = &vizierconfigpb.LeadershipElectionParams{
ElectionPeriodMs: vz.Spec.LeadershipElectionParams.ElectionPeriodMs,
}
}
resp, err := client.GetConfigForVizier(ctx, req)
if err != nil {
return nil, err
}
return resp, nil
}
// addKeyValueMapToResource adds the given keyValue map to the K8s resource.
func addKeyValueMapToResource(mapName string, keyValues map[string]string, res map[string]interface{}) {
metadata := make(map[string]interface{})
md, ok, err := unstructured.NestedFieldNoCopy(res, "metadata")
if ok && err == nil {
if mdCast, castOk := md.(map[string]interface{}); castOk {
metadata = mdCast
}
}
resLabels := make(map[string]interface{})
l, ok, err := unstructured.NestedFieldNoCopy(res, "metadata", mapName)
if ok && err == nil {
if labelsCast, castOk := l.(map[string]interface{}); castOk {
resLabels = labelsCast
}
}
for k, v := range keyValues {
resLabels[k] = v
}
metadata[mapName] = resLabels
// If it exists, recursively add the labels to the resource's template (for deployments/daemonsets).
spec, ok, err := unstructured.NestedFieldNoCopy(res, "spec", "template")
if ok && err == nil {
if specCast, castOk := spec.(map[string]interface{}); castOk {
addKeyValueMapToResource(mapName, keyValues, specCast)
}
}
res["metadata"] = metadata
}
func updateResourceRequirements(requirements v1.ResourceRequirements, res map[string]interface{}) {
// Traverse through resource object to spec.template.spec.containers. If the path does not exist,
// the resource can be ignored.
containers, ok, err := unstructured.NestedFieldNoCopy(res, "spec", "template", "spec", "containers")
if !ok || err != nil {
return
}
cList, ok := containers.([]interface{})
if !ok {
return
}
// If containers are specified in the spec, we should update the resource requirements if
// not already defined.
for _, c := range cList {
castedContainer, ok := c.(map[string]interface{})
if !ok {
continue
}
resources := make(map[string]interface{})
if r, ok := castedContainer["resources"]; ok {
castedR, castOk := r.(map[string]interface{})
if castOk {
resources = castedR
}
}
requests := make(map[string]interface{})
if req, ok := resources["requests"]; ok {
castedReq, ok := req.(map[string]interface{})
if ok {
requests = castedReq
}
}
for k, v := range requirements.Requests {
if _, ok := requests[k.String()]; ok {
continue
}
requests[k.String()] = v.String()
}
resources["requests"] = requests
limits := make(map[string]interface{})
if req, ok := resources["limits"]; ok {
castedLim, ok := req.(map[string]interface{})
if ok {
limits = castedLim
}
}
for k, v := range requirements.Limits {
if _, ok := limits[k.String()]; ok {
continue
}
limits[k.String()] = v.String()
}
resources["limits"] = limits
castedContainer["resources"] = resources
}
}
func convertTolerations(tolerations []v1.Toleration) []*vizierconfigpb.Toleration {
var castedTolerations []*vizierconfigpb.Toleration
for _, toleration := range tolerations {
castedToleration := &vizierconfigpb.Toleration{
Key: toleration.Key,
Operator: string(toleration.Operator),
Value: toleration.Value,
Effect: string(toleration.Effect),
}
if toleration.TolerationSeconds != nil {
castedToleration.TolerationSeconds = &types.Int64Value{Value: *toleration.TolerationSeconds}
}
castedTolerations = append(castedTolerations, castedToleration)
}
return castedTolerations
}
func updatePodSpec(nodeSelector map[string]string, tolerations []v1.Toleration, securityCtx *v1alpha1.PodSecurityContext, res map[string]interface{}) {
podSpec := make(map[string]interface{})
md, ok, err := unstructured.NestedFieldNoCopy(res, "spec", "template", "spec")
if ok && err == nil {
if podSpecCast, castOk := md.(map[string]interface{}); castOk {
podSpec = podSpecCast
}
}
castedNodeSelector := make(map[string]interface{})
ns, ok := podSpec["nodeSelector"].(map[string]interface{})
if ok {
castedNodeSelector = ns
}
for k, v := range nodeSelector {
if _, ok := castedNodeSelector[k]; ok {
continue
}
castedNodeSelector[k] = v
}
podSpec["nodeSelector"] = castedNodeSelector
podSpec["tolerations"] = tolerations
// Add securityContext only if enabled.
if securityCtx == nil || !securityCtx.Enabled {
return
}
sc, ok, err := unstructured.NestedFieldNoCopy(res, "spec", "template", "spec", "securityContext")
if ok && err == nil {
if scCast, castOk := sc.(map[string]interface{}); castOk && len(scCast) > 0 {
return // A security context is already specified, we should use that one.
}
}
sCtx := make(map[string]interface{})
if securityCtx.FSGroup != 0 {
sCtx["fsGroup"] = securityCtx.FSGroup
}
if securityCtx.RunAsUser != 0 {
sCtx["runAsUser"] = securityCtx.RunAsUser
}
if securityCtx.RunAsGroup != 0 {
sCtx["runAsGroup"] = securityCtx.RunAsGroup
}
podSpec["securityContext"] = sCtx
}
func waitForCluster(clientset *kubernetes.Clientset, namespace string) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
t := time.NewTicker(2 * time.Second)
defer t.Stop()
clusterID := false
for !clusterID { // Wait for secret to be updated with clusterID.
select {
case <-ctx.Done():
return errors.New("Timed out waiting for cluster ID")
case <-t.C:
s := k8s.GetSecret(clientset, namespace, "pl-cluster-secrets")
if s == nil {
return errors.New("Missing cluster secrets")
}
if _, ok := s.Data["cluster-id"]; ok {
clusterID = true
}
}
}
return nil
}
// watchForFailedVizierUpdates regularly polls for timed-out viziers
// and marks matching Viziers ReconciliationPhases as failed.
func (r *VizierReconciler) watchForFailedVizierUpdates() {
t := time.NewTicker(updatingVizierCheckPeriod)
defer t.Stop()
for range t.C {
var viziersList v1alpha1.VizierList
ctx := context.Background()
err := r.List(ctx, &viziersList)
if err != nil {
log.WithError(err).Error("Unable to list the vizier objects")
continue
}
for _, vz := range viziersList.Items {
// Set the Vizier Reconciliation phase to Failed if an Update has timed out.
if vz.Status.ReconciliationPhase != v1alpha1.ReconciliationPhaseUpdating {
continue
}
if time.Since(vz.Status.LastReconciliationPhaseTime.Time) < updatingFailedTimeout {
continue
}
log.WithField("namespace", vz.Namespace).WithField("vizier", vz.Name).Info("Marking vizier as failed")
vz.SetReconciliationPhase(v1alpha1.ReconciliationPhaseFailed)
err := r.Status().Update(ctx, &vz)
if err != nil {
log.WithError(err).Error("Unable to update vizier status")
}
}
}
}
// SetupWithManager sets up the reconciler.
func (r *VizierReconciler) SetupWithManager(mgr ctrl.Manager) error {
go r.watchForFailedVizierUpdates()
return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.Vizier{}).
Complete(r)
}
// Stop performs any necessary cleanup before shutdown.
func (r *VizierReconciler) Stop() {
if r.sentryFlush != nil {
r.sentryFlush()
}
}
// setupSentry sets up the error logging.
func setupSentry(ctx context.Context, conn *grpc.ClientConn, clientset *kubernetes.Clientset) func() {
// Use k8s UID instead of cluserID because newly deployed clusters may take some time to register and receive a clusterID
clusterUID, err := getClusterUID(clientset)
if err != nil {
log.WithError(err).Error("Failed to get Cluster UID")
return nil
}
config, err := getConfigForOperator(ctx, conn)
if err != nil {
log.WithError(err).Error("Failed to get Operator config")
return nil
}
flush := services.InitSentryWithDSN(clusterUID, config.SentryOperatorDSN)
return flush
}
// GetClusterUID gets UID for the cluster, represented by the kube-system namespace UID.
func getClusterUID(clientset *kubernetes.Clientset) (string, error) {
ksNS, err := clientset.CoreV1().Namespaces().Get(context.Background(), "kube-system", metav1.GetOptions{})
if err != nil {
return "", err
}
return string(ksNS.UID), nil
}
// getVizierID gets the ID of the cluster the Vizier is in.
func getVizierID(clientset *kubernetes.Clientset, namespace string) (*uuidpb.UUID, error) {
op := func() (*uuidpb.UUID, error) {
var vizierID *uuidpb.UUID
s := k8s.GetSecret(clientset, namespace, "pl-cluster-secrets")
if s == nil {
return nil, errors.New("Missing cluster secrets, retrying again")
}
if id, ok := s.Data["cluster-id"]; ok {
vizierID = utils.ProtoFromUUIDStrOrNil(string(id))
if vizierID == nil {
return nil, errors.New("Couldn't convert ID to proto")
}
}
return vizierID, nil
}
expBackoff := backoff.NewExponentialBackOff()
expBackoff.InitialInterval = 10 * time.Second
expBackoff.Multiplier = 2
expBackoff.MaxElapsedTime = 10 * time.Minute
vizierID, err := backoff.RetryWithData(op, expBackoff)
if err != nil {
return nil, errors.New("Timed out waiting for the Vizier ID")
}
return vizierID, nil
}
// getConfigForOperator is responsible retrieving the Operator config from from Pixie Cloud.
func getConfigForOperator(ctx context.Context, conn *grpc.ClientConn) (*cloudpb.ConfigForOperatorResponse, error) {
client := cloudpb.NewConfigServiceClient(conn)
req := &cloudpb.ConfigForOperatorRequest{}
resp, err := client.GetConfigForOperator(ctx, req)
if err != nil {
return nil, err
}
return resp, nil
}
func retryDeploy(clientset *kubernetes.Clientset, config *rest.Config, namespace string, resources []*k8s.Resource, allowUpdate bool) error {
bOpts := backoff.NewExponentialBackOff()
bOpts.InitialInterval = 15 * time.Second
bOpts.MaxElapsedTime = 5 * time.Minute
return backoff.Retry(func() error {
return k8s.ApplyResources(clientset, config, resources, namespace, nil, allowUpdate)
}, bOpts)
}
|
// 출처: https://github.com/gonet2/agent
package scommon
import (
"encoding/binary"
"errors"
"reflect"
)
// 타입의 크기를 계산한다
func Sizeof(t reflect.Type) int {
switch t.Kind() {
case reflect.Array:
//fmt.Println("reflect.Array")
if s := Sizeof(t.Elem()); s >= 0 {
return s * t.Len()
}
case reflect.Struct:
//fmt.Println("reflect.Struct")
sum := 0
for i, n := 0, t.NumField(); i < n; i++ {
s := Sizeof(t.Field(i).Type)
if s < 0 {
return -1
}
sum += s
}
return sum
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
//fmt.Println("reflect.int")
return int(t.Size())
case reflect.Slice:
//fmt.Println("reflect.Slice:", sizeof(t.Elem()))
return 0
}
return -1
}
type RawBinaryData struct {
pos int
data []byte
order binary.ByteOrder
}
func MakeBReader(buffer []byte, isLittleEndian bool) RawBinaryData {
if isLittleEndian {
return RawBinaryData{data: buffer, order: binary.LittleEndian}
}
return RawBinaryData{data: buffer, order: binary.BigEndian}
}
func MakeBWriter(buffer []byte, isLittleEndian bool) RawBinaryData {
if isLittleEndian {
return RawBinaryData{data: buffer, order: binary.LittleEndian}
}
return RawBinaryData{data: buffer, order: binary.BigEndian}
}
func (p *RawBinaryData) Data() []byte {
return p.data
}
func (p *RawBinaryData) Length() int {
return len(p.data)
}
//=============================================== Readers
func (p *RawBinaryData) ReadBool() (ret bool, err error) {
b, _err := p.ReadByte()
if b != byte(1) {
return false, _err
}
return true, _err
}
func (p *RawBinaryData) ReadS8() (ret int8, err error) {
_ret, _err := p.ReadByte()
ret = int8(_ret)
err = _err
return
}
func (p *RawBinaryData) ReadU16() (ret uint16, err error) {
if p.pos+2 > len(p.data) {
err = errors.New("read uint16 failed")
return
}
buf := p.data[p.pos : p.pos+2]
ret = p.order.Uint16(buf)
p.pos += 2
return
}
func (p *RawBinaryData) ReadS16() (ret int16, err error) {
_ret, _err := p.ReadU16()
ret = int16(_ret)
err = _err
return
}
func (p *RawBinaryData) ReadU32() (ret uint32, err error) {
if p.pos+4 > len(p.data) {
err = errors.New("read uint32 failed")
return
}
buf := p.data[p.pos : p.pos+4]
ret = p.order.Uint32(buf)
p.pos += 4
return
}
func (p *RawBinaryData) ReadS32() (ret int32, err error) {
_ret, _err := p.ReadU32()
ret = int32(_ret)
err = _err
return
}
func (p *RawBinaryData) ReadU64() (ret uint64, err error) {
if p.pos+8 > len(p.data) {
err = errors.New("read uint64 failed")
return
}
buf := p.data[p.pos : p.pos+8]
ret = p.order.Uint64(buf)
p.pos += 8
return
}
func (p *RawBinaryData) ReadS64() (ret int64, err error) {
_ret, _err := p.ReadU64()
ret = int64(_ret)
err = _err
return
}
func (p *RawBinaryData) ReadByte() (ret byte, err error) {
if p.pos >= len(p.data) {
err = errors.New("read byte failed")
return
}
ret = p.data[p.pos]
p.pos++
return
}
func (p *RawBinaryData) ReadBytes(readSize int) (refSlice []byte) {
refSlice = p.data[p.pos : p.pos+readSize]
p.pos += readSize
return
}
func (p *RawBinaryData) ReadString() (ret string, err error) {
if p.pos+2 > len(p.data) {
err = errors.New("read string header failed")
return
}
size, _ := p.ReadU16()
if p.pos+int(size) > len(p.data) {
err = errors.New("read string Data failed")
return
}
bytes := p.data[p.pos : p.pos+int(size)]
p.pos += int(size)
ret = string(bytes)
return
}
//================================================ Writers
func (p *RawBinaryData) WriteS8(v int8) {
p.data[p.pos] = (byte)(v)
p.pos++
}
func (p *RawBinaryData) WriteU16(v uint16) {
p.order.PutUint16(p.data[p.pos:], v)
p.pos += 2
}
func (p *RawBinaryData) WriteS16(v int16) {
p.WriteU16(uint16(v))
}
func (p *RawBinaryData) WriteBytes(v []byte) {
copy(p.data[p.pos:], v)
p.pos += len(v)
}
func (p *RawBinaryData) WriteU32(v uint32) {
p.order.PutUint32(p.data[p.pos:], v)
p.pos += 4
}
func (p *RawBinaryData) WriteS32(v int32) {
p.WriteU32(uint32(v))
}
func (p *RawBinaryData) WriteU64(v uint64) {
p.order.PutUint64(p.data[p.pos:], v)
p.pos += 8
}
func (p *RawBinaryData) WriteS64(v int64) {
p.WriteU64(uint64(v))
}
func (p *RawBinaryData) WriteString(v string) {
copyLen := copy(p.data[p.pos:], v)
p.pos += copyLen
}
|
package post_order_traversal
import "testing"
func TestSolve(t *testing.T) {
root := &Node{val: 1}
root.left = &Node{val: 2}
root.right = &Node{val: 3}
root.left.left = &Node{val: 4}
root.left.right = &Node{val: 5}
root.right.left = &Node{val: 6}
root.right.right = &Node{val: 7}
postOrder(root)
}
|
package main
import (
"context"
"fmt"
"net/http"
"os"
"time"
configv1client "github.com/openshift/client-go/config/clientset/versioned/typed/config/v1"
"github.com/sirupsen/logrus"
k8sscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/clientcmd"
utilclock "k8s.io/utils/clock"
"github.com/operator-framework/operator-lifecycle-manager/pkg/api/client"
"github.com/operator-framework/operator-lifecycle-manager/pkg/controller/operators/catalog"
"github.com/operator-framework/operator-lifecycle-manager/pkg/controller/operators/catalogtemplate"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/operatorclient"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/operatorstatus"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/server"
"github.com/operator-framework/operator-lifecycle-manager/pkg/metrics"
)
const (
catalogNamespaceEnvVarName = "GLOBAL_CATALOG_NAMESPACE"
defaultWakeupInterval = 15 * time.Minute
defaultCatalogNamespace = "olm"
defaultConfigMapServerImage = "quay.io/operator-framework/configmap-operator-registry:latest"
defaultOPMImage = "quay.io/operator-framework/opm:latest"
defaultUtilImage = "quay.io/operator-framework/olm:latest"
defaultOperatorName = ""
defaultWorkLoadUserID = int64(1001)
)
// config flags defined globally so that they appear on the test binary as well
func init() {
metrics.RegisterCatalog()
}
func main() {
cmd := newRootCmd()
if err := cmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func (o *options) run(ctx context.Context, logger *logrus.Logger) error {
// If the catalogNamespaceEnvVarName environment variable is set, then update the value of catalogNamespace.
if catalogNamespaceEnvVarValue := os.Getenv(catalogNamespaceEnvVarName); catalogNamespaceEnvVarValue != "" {
logger.Infof("%s environment variable is set. Updating Global Catalog Namespace to %s", catalogNamespaceEnvVarName, catalogNamespaceEnvVarValue)
o.catalogNamespace = catalogNamespaceEnvVarValue
}
listenAndServe, err := server.GetListenAndServeFunc(
server.WithLogger(logger),
server.WithTLS(&o.tlsCertPath, &o.tlsKeyPath, &o.clientCAPath),
server.WithDebug(o.debug),
)
if err != nil {
return fmt.Errorf("error setting up health/metric/pprof service: %v", err)
}
go func() {
if err := listenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error(err)
}
}()
// create a config client for operator status
config, err := clientcmd.BuildConfigFromFlags("", o.kubeconfig)
if err != nil {
return fmt.Errorf("error configuring client: %s", err.Error())
}
configClient, err := configv1client.NewForConfig(config)
if err != nil {
return fmt.Errorf("error configuring client: %s", err.Error())
}
opClient := operatorclient.NewClientFromConfig(o.kubeconfig, logger)
crClient, err := client.NewClient(o.kubeconfig)
if err != nil {
return fmt.Errorf("error configuring client: %s", err.Error())
}
workloadUserID := int64(-1)
if o.setWorkloadUserID {
workloadUserID = defaultWorkLoadUserID
}
// TODO(tflannag): Use options pattern for catalog operator
// Create a new instance of the operator.
op, err := catalog.NewOperator(
ctx,
o.kubeconfig,
utilclock.RealClock{},
logger,
o.wakeupInterval,
o.configMapServerImage,
o.opmImage,
o.utilImage,
o.catalogNamespace,
k8sscheme.Scheme,
o.installPlanTimeout,
o.bundleUnpackTimeout,
workloadUserID,
)
if err != nil {
return fmt.Errorf("error configuring catalog operator: %s", err.Error())
}
opCatalogTemplate, err := catalogtemplate.NewOperator(
ctx,
o.kubeconfig,
logger,
o.wakeupInterval,
o.catalogNamespace,
)
if err != nil {
return fmt.Errorf("error configuring catalog template operator: %s", err.Error())
}
op.Run(ctx)
<-op.Ready()
opCatalogTemplate.Run(ctx)
<-opCatalogTemplate.Ready()
if o.writeStatusName != "" {
operatorstatus.MonitorClusterStatus(o.writeStatusName, op.AtLevel(), op.Done(), opClient, configClient, crClient, logger)
}
<-op.Done()
return nil
}
|
// Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"fmt"
"os"
"os/exec"
log "github.com/cihub/seelog"
docker "github.com/fsouza/go-dockerclient"
"github.com/osrg/earthquake/earthquake-container/container"
)
func SetupNFQUEUE(c *docker.Container, queueNum int, hookInput bool, disableBypass bool) error {
err := container.EnterDockerNetNs(c)
if err != nil {
return err
}
defer container.LeaveNetNs()
chain := "OUTPUT"
if hookInput {
chain = "INPUT"
}
iptArg := []string{"-A", chain, "-j", "NFQUEUE", "--queue-num", fmt.Sprintf("%d", queueNum)}
if !disableBypass {
iptArg = append(iptArg, "--queue-bypass")
}
log.Debugf("Running `iptables` with %s", iptArg)
cmd := exec.Command("iptables", iptArg...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = os.Environ()
err = cmd.Run()
if err != nil {
return err
}
return nil
}
|
// Package models contains the types for schema 'public'.
package models
// GENERATED BY XO. DO NOT EDIT.
import (
"database/sql/driver"
"errors"
)
// ActivityType is the 'activity_type' enum type from schema 'public'.
type ActivityType uint16
const (
// ActivityTypeApplicationCreated is the 'application_created' ActivityType.
ActivityTypeApplicationCreated = ActivityType(1)
// ActivityTypeApplicationDeleted is the 'application_deleted' ActivityType.
ActivityTypeApplicationDeleted = ActivityType(2)
// ActivityTypeDeploymentStarted is the 'deployment_started' ActivityType.
ActivityTypeDeploymentStarted = ActivityType(3)
// ActivityTypeDeploymentSuccess is the 'deployment_success' ActivityType.
ActivityTypeDeploymentSuccess = ActivityType(4)
// ActivityTypeDeploymentFailure is the 'deployment_failure' ActivityType.
ActivityTypeDeploymentFailure = ActivityType(5)
// ActivityTypeEnvironmentCreated is the 'environment_created' ActivityType.
ActivityTypeEnvironmentCreated = ActivityType(6)
// ActivityTypeEnvironmentDestroyed is the 'environment_destroyed' ActivityType.
ActivityTypeEnvironmentDestroyed = ActivityType(7)
)
// String returns the string value of the ActivityType.
func (at ActivityType) String() string {
var enumVal string
switch at {
case ActivityTypeApplicationCreated:
enumVal = "application_created"
case ActivityTypeApplicationDeleted:
enumVal = "application_deleted"
case ActivityTypeDeploymentStarted:
enumVal = "deployment_started"
case ActivityTypeDeploymentSuccess:
enumVal = "deployment_success"
case ActivityTypeDeploymentFailure:
enumVal = "deployment_failure"
case ActivityTypeEnvironmentCreated:
enumVal = "environment_created"
case ActivityTypeEnvironmentDestroyed:
enumVal = "environment_destroyed"
}
return enumVal
}
// MarshalText marshals ActivityType into text.
func (at ActivityType) MarshalText() ([]byte, error) {
return []byte(at.String()), nil
}
// UnmarshalText unmarshals ActivityType from text.
func (at *ActivityType) UnmarshalText(text []byte) error {
switch string(text) {
case "application_created":
*at = ActivityTypeApplicationCreated
case "application_deleted":
*at = ActivityTypeApplicationDeleted
case "deployment_started":
*at = ActivityTypeDeploymentStarted
case "deployment_success":
*at = ActivityTypeDeploymentSuccess
case "deployment_failure":
*at = ActivityTypeDeploymentFailure
case "environment_created":
*at = ActivityTypeEnvironmentCreated
case "environment_destroyed":
*at = ActivityTypeEnvironmentDestroyed
default:
return errors.New("invalid ActivityType")
}
return nil
}
// Value satisfies the sql/driver.Valuer interface for ActivityType.
func (at ActivityType) Value() (driver.Value, error) {
return at.String(), nil
}
// Scan satisfies the database/sql.Scanner interface for ActivityType.
func (at *ActivityType) Scan(src interface{}) error {
buf, ok := src.([]byte)
if !ok {
return errors.New("invalid ActivityType")
}
return at.UnmarshalText(buf)
}
|
package prime
import ()
const testVersion = 2
// Compute the prime factors of a given natural number.
// Return prime factors in increasing order
// eg. Given 60, return 2, 2, 3, 5
// Very slow: BenchmarkPrimeFactors-4 100 11950683 ns/op
func Factors(number int64) []int64 {
ret := []int64{}
var i int64
for i = 2; i <= number; {
if number%i == 0 {
ret = append(ret, i)
number = number / i
} else {
i++
}
}
return ret
}
Sieve |
package main
import (
"net/http"
"time"
"github.com/lilwulin/lilraft"
)
func main() {
var array []int
config := lilraft.NewConfig(
lilraft.NewHTTPNode(1, "http://127.0.0.1:8787"),
lilraft.NewHTTPNode(2, "http://127.0.0.1:8788"),
lilraft.NewHTTPNode(3, "http://127.0.0.1:8789"),
)
s := lilraft.NewServer(1, &array, config, "server/")
s.SetHTTPTransport(http.DefaultServeMux, 8787)
s.Start(false)
time.Sleep(50 * time.Millisecond)
}
|
package main
// https://nick.groenen.me/posts/2017/01/09/plugins-in-go-18/
import "C"
func Greet() string {
return "Hello World"
}
|
package database
import (
"strings"
"github.com/direktiv/direktiv/pkg/flow/database/recipient"
"github.com/direktiv/direktiv/pkg/refactor/core"
)
type HasAttributes interface {
GetAttributes() map[string]string
}
func GetAttributes(recipientType recipient.RecipientType, a ...HasAttributes) map[string]string {
m := make(map[string]string)
m["recipientType"] = string(recipientType)
for _, x := range a {
y := x.GetAttributes()
for k, v := range y {
m[k] = v
}
}
return m
}
type Namespace = core.Namespace
func GetWorkflow(path string) string {
return strings.Split(path, ":")[0]
}
|
package assembler
import (
"math/rand"
"testing"
)
func ismaxtest(t *testing.T, b *testing.B) {
for j := 0; j < 100; j++ {
if b != nil {
b.StopTimer()
}
x := make([]float32, j)
for i := range x {
x[i] = float32(rand.NormFloat64())
}
if b != nil {
b.StartTimer()
for i := 0; i < b.N; i++ {
Ismax(x)
}
}
if t != nil {
ifast := ismax_asm(x)
isimple := ismax(x)
// numeric issues
if ifast != isimple {
t.Logf("%v\n", x)
t.Fatalf("maxindex do not match want %d=%f got %d=%f in vector of length %d\n", isimple, x[isimple], ifast, x[ifast], len(x))
}
}
}
}
func TestIsmax(t *testing.T) {
ismaxtest(t, nil)
}
func BenchmarkIsmax(b *testing.B) {
Init(false)
ismaxtest(nil, b)
}
func BenchmarkOptimizedIsmax(b *testing.B) {
Init(true)
ismaxtest(nil, b)
}
|
// Copyright 2017 Jeff Foley. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package sources
import (
"fmt"
"github.com/OWASP/Amass/amass/core"
"github.com/OWASP/Amass/amass/utils"
)
// PTRArchive is data source object type that implements the DataSource interface.
type PTRArchive struct {
BaseDataSource
}
// NewPTRArchive returns an initialized PTRArchive as a DataSource.
func NewPTRArchive(srv core.AmassService) DataSource {
p := new(PTRArchive)
p.BaseDataSource = *NewBaseDataSource(srv, core.SCRAPE, "PTRarchive")
return p
}
// Query returns the subdomain names discovered when querying this data source.
func (p *PTRArchive) Query(domain, sub string) []string {
var unique []string
if domain != sub {
return unique
}
url := p.getURL(domain)
page, err := utils.GetWebPage(url, nil)
if err != nil {
p.Service.Config().Log.Printf("%s: %v", url, err)
return unique
}
p.Service.SetActive()
re := utils.SubdomainRegex(domain)
for _, sd := range re.FindAllString(page, -1) {
if u := utils.NewUniqueElements(unique, sd); len(u) > 0 {
unique = append(unique, u...)
}
}
return unique
}
func (p *PTRArchive) getURL(domain string) string {
format := "http://ptrarchive.com/tools/search3.htm?label=%s&date=ALL"
return fmt.Sprintf(format, domain)
}
|
/*
Copyright 2019 Netfoundry, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package version
import (
"github.com/blang/semver"
"log"
"strings"
)
// Build information. Populated at build-time.
var (
Verbose bool
Version string
Revision string
Branch string
BuildUser string
BuildDate string
GoVersion string
OS string
Arch string
)
// Map provides the iterable version information.
var Map = map[string]string{
"version": Version,
"revision": Revision,
"branch": Branch,
"buildUser": BuildUser,
"buildDate": BuildDate,
"goVersion": GoVersion,
"os": OS,
"arch": Arch,
}
const (
VersionPrefix = ""
// TestVersion used in test cases for the current version if no
// version can be found - such as if the version property is not properly
// included in the go test flags
TestVersion = "0.0.0"
TestRevision = "unknown"
TestBranch = "unknown"
TestBuildDate = "unknown"
TestGoVersion = "unknown"
TestOs = "unknown"
TestArch = "unknown"
)
func GetBuildMetadata(verbose bool) string {
if !verbose {
return GetVersion()
}
str :=
"\n\t" + "Version: " + GetVersion() +
"\n\t" + "Build Date: " + GetBuildDate() +
"\n\t" + "Git Branch: " + GetBranch() +
"\n\t" + "Git SHA: " + GetRevision() +
"\n\t" + "Go Version: " + GetGoVersion() +
"\n\t" + "OS: " + GetOS() +
"\n\t" + "Arch: " + GetArchitecture() +
"\n"
return str
}
func GetVersion() string {
v := Map["version"]
if v == "" {
v = TestVersion
}
return v
}
func GetRevision() string {
r := Map["revision"]
if r == "" {
r = TestRevision
}
return r
}
func GetBranch() string {
b := Map["branch"]
if b == "" {
b = TestBranch
}
return b
}
func GetBuildDate() string {
d := Map["buildDate"]
if d == "" {
d = TestBuildDate
}
return d
}
func GetGoVersion() string {
g := Map["goVersion"]
if g == "" {
g = TestRevision
}
return g
}
func GetOS() string {
o := Map["os"]
if o == "" {
o = TestRevision
}
return o
}
func GetArchitecture() string {
a := Map["arch"]
if a == "" {
a = TestRevision
}
return a
}
func GetSemverVersion() (semver.Version, error) {
return semver.Make(strings.TrimPrefix(GetVersion(), VersionPrefix))
}
// VersionStringDefault returns the current version string or returns a dummy
// default value if there is an error
func VersionStringDefault(defaultValue string) string {
v, err := GetSemverVersion()
if err == nil {
return v.String()
}
log.Printf("Warning failed to load version: %s\n", err)
return defaultValue
}
|
package main
/*
All Methods which belong to the Database Communication.
*/
import (
"database/sql"
"golang.org/x/crypto/bcrypt"
"log"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
)
/*
Represents a User in the Database.
*/
type User struct {
UserID uint64
Username string
passwordHash string
sessionID string
GamesWon uint64
}
const LETTER_BYTES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789?!"
const COOKIE_NAME = "BMCookie"
func NewUser(userID uint64, username string, passwordHash string, sessionID string) *User {
return &User{UserID: userID, Username: username, passwordHash: passwordHash, sessionID: sessionID}
}
func (r *User) String() string {
return "User: {" + strconv.FormatUint(r.UserID, 10) + " | " + r.Username + "}"
}
/*
Gets a User by its Username and Password.
*/
func GetUserFromDB(db *sql.DB, username string, password string) (*User, *DetailedHttpError) {
var user User
if err := db.Ping(); err != nil {
return nil, NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
rows, err := db.Query("select * from users where username = ?", username)
if err != nil {
return nil, NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
if rows.Next() {
if err = rows.Scan(&user.UserID, &user.Username, &user.passwordHash, &user.sessionID, &user.GamesWon); err != nil {
return nil, NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
} else {
return nil, NewDetailedHttpError(http.StatusNotFound, "User not found", "User not found: "+username)
}
if err = bcrypt.CompareHashAndPassword([]byte(user.passwordHash), []byte(password)); err != nil {
return nil, NewDetailedHttpError(http.StatusBadRequest, "wrong password", "wrong password")
}
return &user, nil
}
/*
Gets a User by its SessionID.
*/
func GetUserFromSessionCookie(db *sql.DB, sessionId string) (*User, *DetailedHttpError) {
var user User
if err := db.Ping(); err != nil {
return nil, NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
rows, err := db.Query("select * from users where session_id = ?", sessionId)
if err != nil {
return nil, NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
if rows.Next() {
if err = rows.Scan(&user.UserID, &user.Username, &user.passwordHash, &user.sessionID, &user.GamesWon); err != nil {
return nil, NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
return &user, nil
}
return nil, NewDetailedHttpError(http.StatusNotFound, "No user found for this Session-ID", "No user found for this Session-ID")
}
/*
Checks if a User with the Username-String passed already exists.
*/
func UsernameExists(db *sql.DB, username string) *DetailedHttpError {
err := db.Ping()
if err != nil {
log.Println("Database connection failed" + err.Error())
return NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
rows, err := db.Query("select * from users where username = ?", username)
if err != nil {
log.Println("Something went wrong on sql.Query" + err.Error())
return NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
if rows.Next() {
return NewDetailedHttpError(http.StatusInternalServerError, "Username is already taken", err.Error())
}
return nil
}
func IsStringLegal(str string) bool {
if str == "" {
return false
}
for _, c := range str {
if !strings.Contains(LETTER_BYTES, strings.ToLower(string(c))) {
return false
}
}
return true
}
/*
Generates a SessionID and places a Cookie with this ID.
Placed Cookie lasts 2 days.
*/
func PlaceCookie(w http.ResponseWriter, db *sql.DB, username string) error {
rows, err := db.Query("select * from users where username = ?", username)
if err != nil {
return err
}
sessionId, err := generateUniqueSessionId(db)
if err != nil {
return err
}
if rows.Next() {
_, err = db.Exec("UPDATE users set Session_Id = ? where username = ?", sessionId, username)
if err != nil {
return err
}
}
expire := time.Now().AddDate(0, 0, 2)
cookie := http.Cookie{
Name: COOKIE_NAME,
Value: sessionId,
Path: "/",
Domain: "localhost",
Expires: expire,
RawExpires: expire.Format(time.UnixDate),
MaxAge: 172800,
Secure: false,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
log.Println("placed cookie successfully")
http.SetCookie(w, &cookie)
return nil
}
/*
Checks if a Cookie for the User is present.
Returns nil if everything is alright.
*/
func CheckCookie(r *http.Request, db *sql.DB, user *User) *DetailedHttpError {
cookie, err := r.Cookie(COOKIE_NAME)
if err != nil {
return NewDetailedHttpError(http.StatusNotFound, "No cookie found", err.Error())
}
rows, err := db.Query("select * from users where session_id = ?", cookie.Value)
if err != nil {
return NewDetailedHttpError(http.StatusNotFound, "Session_Id doesnt exists", err.Error())
}
if rows.Next() {
err = rows.Scan(&user.UserID, &user.Username, &user.passwordHash, &user.sessionID, &user.GamesWon)
if err != nil {
return NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
}
return nil
}
/*
Generates SessionID's until a unique one is found.
*/
func generateUniqueSessionId(db *sql.DB) (string, error) {
sessionId := generateSessionId(255)
rows, err := db.Query("select session_id from users where session_id = ?", sessionId)
if err != nil {
return "", err
}
if rows.Next() {
return generateUniqueSessionId(db)
}
return sessionId, nil
}
/*
Generates a SessionID.
*/
func generateSessionId(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = LETTER_BYTES[rand.Intn(len(LETTER_BYTES))]
}
return string(b)
}
/*
Gets a User by its ID.
*/
func getUserByID(db *sql.DB, userID uint64) (*User, *DetailedHttpError) {
var user User
if err := db.Ping(); err != nil {
return nil, NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
rows, err := db.Query("select * from users where Id = ?", userID)
if err != nil {
return nil, NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
if rows.Next() {
if err = rows.Scan(&user.UserID, &user.Username, &user.passwordHash, &user.sessionID, &user.GamesWon); err != nil {
return nil, NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
return &user, nil
}
return nil, NewDetailedHttpError(http.StatusNotFound, "No user found for this Session-ID", "No user found for this Session-ID")
}
/*
Updates the Player-Statistics in the Database.
*/
func updatePlayerStats(db *sql.DB, user User) *DetailedHttpError {
log.Println("Updating Player Statistic..")
err := db.Ping()
if err != nil {
log.Println("Database connection failed" + err.Error())
return NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
rows, err := db.Query("select * from users where Id = ?", user.UserID)
if err != nil {
return NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
log.Println(user.GamesWon)
if rows.Next() {
_, err = db.Exec("UPDATE users set Games_won = ? where ID = ?", user.GamesWon, user.UserID)
if err != nil {
return NewDetailedHttpError(http.StatusInternalServerError, INTERNAL_SERVER_ERROR_RESPONSE, err.Error())
}
}
return nil
}
|
package movie
type RegularMovie struct {
Param
}
func (r RegularMovie) GetCost(days int) float64 {
if days <= 2 {
return 2.0
}
return 2 + (float64(days) - 2) * 1.5
}
func (r RegularMovie) GetPoint(days int) int {
return 1
}
func (r RegularMovie) GetTitle() string {
return r.Title
} |
package main
import(
"fmt"
)
func main() {
a := 10.000
b := 1.2
c := 1 + 2.12i
d := "this is so random!"
e := 'x'
a = a + b
a = a - b
a = a * b
a = a / b
m := make(map[int]int)
m[1] = 2
m[2] = 4
m[3] = m[2] % m[1]
m[3] += m[2]
m[3] -= m[2]
m[3] *= m[2]
m[3] /= m[2]
m[3] %= m[2]
m[3] << 1
var ck1, ck2 bool
ck1 = true
ck2 = false
ck1 = ck2 && ck1
ck2 = ck1 || ck2
ck2 |= ck1
ck1 &= ck2
fmt.Println(a, b, c)
fmt.Println(d, e)
}
|
package run
import (
"errors"
"fmt"
"os/user"
"path/filepath"
"github.com/messagedb/messagedb/cluster"
"github.com/messagedb/messagedb/db"
"github.com/messagedb/messagedb/meta"
"github.com/messagedb/messagedb/services/admin"
"github.com/messagedb/messagedb/services/hh"
"github.com/messagedb/messagedb/services/httpd"
"github.com/messagedb/messagedb/services/retention"
)
// Config represents the configuration format for the messaged binary.
type Config struct {
Meta meta.Config `toml:"meta"`
Data db.Config `toml:"data"`
Cluster cluster.Config `toml:"cluster"`
Retention retention.Config `toml:"retention"`
Admin admin.Config `toml:"admin"`
HTTPD httpd.Config `toml:"http"`
HintedHandoff hh.Config `toml:"hinted-handoff"`
// Server reporting
ReportingDisabled bool `toml:"reporting-disabled"`
}
// NewConfig returns an instance of Config with reasonable defaults.
func NewConfig() *Config {
c := &Config{}
c.Meta = meta.NewConfig()
c.Data = db.NewConfig()
c.Cluster = cluster.NewConfig()
// c.Precreator = precreator.NewConfig()
c.Admin = admin.NewConfig()
c.HTTPD = httpd.NewConfig()
// c.Collectd = collectd.NewConfig()
// c.OpenTSDB = opentsdb.NewConfig()
// c.Graphites = append(c.Graphites, graphite.NewConfig())
// c.Monitoring = monitor.NewConfig()
// c.ContinuousQuery = continuous_querier.NewConfig()
c.Retention = retention.NewConfig()
c.HintedHandoff = hh.NewConfig()
return c
}
// NewDemoConfig returns the config that runs when no config is specified.
func NewDemoConfig() (*Config, error) {
c := NewConfig()
// By default, store meta and data files in current users home directory
u, err := user.Current()
if err != nil {
return nil, fmt.Errorf("failed to determine current user for storage")
}
c.Meta.Dir = filepath.Join(u.HomeDir, ".messagedb/meta")
c.Data.Dir = filepath.Join(u.HomeDir, ".messagedb/data")
c.HintedHandoff.Dir = filepath.Join(u.HomeDir, ".messagedb/hh")
c.Admin.Enabled = true
// c.Monitoring.Enabled = false
return c, nil
}
// Validate returns an error if the config is invalid.
func (c *Config) Validate() error {
if c.Meta.Dir == "" {
return errors.New("Meta.Dir must be specified")
} else if c.Data.Dir == "" {
return errors.New("Data.Dir must be specified")
} else if c.HintedHandoff.Dir == "" {
return errors.New("HintedHandoff.Dir must be specified")
}
// for _, g := range c.Graphites {
// if err := g.Validate(); err != nil {
// return fmt.Errorf("invalid graphite config: %v", err)
// }
// }
return nil
}
|
package main
import (
"bytes"
"fmt"
"net/http"
"net/http/httputil"
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"testing"
)
func TestBasicExample(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Basic Example Suite")
}
var _ = Describe("Basic Example", func() {
var server *ghttp.Server
var out bytes.Buffer
// Override default failure handler so it doesn't kill the process
fail = func(format string, v ...interface{}) {
Fail(fmt.Sprintf(format, v...))
}
BeforeEach(func() {
server = ghttp.NewServer()
os.Args = []string{"basic", "-insecure", "-e=dummy", "-p=dummy", "-a=42", "-h=" + server.URL()[7:]}
osStdout = &out
})
AfterEach(func() {
server.Close()
})
It("lists executions", func() {
server.AppendHandlers(
ghttp.CombineHandlers(
ghttp.VerifyRequest("POST", "/api/sessions"),
ghttp.VerifyJSONRepresenting(map[string]interface{}{
"email": "dummy",
"password": "dummy",
"account_href": "/api/accounts/42",
}),
ghttp.RespondWith(204, ""),
),
ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/api/sessions"),
ghttp.RespondWith(200, ""),
),
ghttp.CombineHandlers(
ghttp.VerifyRequest("GET", "/api/clouds"),
ghttp.RespondWith(200, responseBody),
),
)
main()
Ω(out.String()).Should(Equal(output))
})
})
// Additional handler that can be used to debug requests
func trace(rw http.ResponseWriter, req *http.Request) {
d, _ := httputil.DumpRequest(req, true)
fmt.Println(string(d) + "\n")
}
const output = `
1. EC2 us-east-1
supports_networks: true
supports_route_tables: true
supports_volume_attachments: true
supports_volume_snapshots: true
2. EC2 us-west-1
supports_networks: true
supports_route_tables: true
supports_volume_attachments: true
supports_volume_snapshots: true
3. EC2 eu-west-1
supports_networks: true
supports_route_tables: true
supports_volume_attachments: true
supports_volume_snapshots: true
`
const responseBody = `[
{
"capabilities": [
{ "name": "supports_networks", "value": "true" },
{ "name": "supports_route_tables", "value": "true" },
{ "name": "supports_volume_attachments", "value": "true" },
{ "name": "supports_volume_snapshots", "value": "true" }
],
"cloud_type": "amazon",
"description": "Amazon's US Cloud on the East Coast",
"display_name": "AWS US-East",
"links": [
{ "href": "/api/clouds/1", "rel": "self" },
{ "href": "/api/clouds/1/datacenters", "rel": "datacenters" },
{ "href": "/api/clouds/1/instance_types", "rel": "instance_types" },
{ "href": "/api/clouds/1/security_groups", "rel": "security_groups" },
{ "href": "/api/clouds/1/instances", "rel": "instances" },
{ "href": "/api/clouds/1/ssh_keys", "rel": "ssh_keys" },
{ "href": "/api/clouds/1/images", "rel": "images" },
{ "href": "/api/clouds/1/ip_addresses", "rel": "ip_addresses" },
{ "href": "/api/clouds/1/ip_address_bindings", "rel": "ip_address_bindings" },
{ "href": "/api/clouds/1/volume_attachments", "rel": "volume_attachments" },
{ "href": "/api/clouds/1/recurring_volume_attachments", "rel": "recurring_volume_attachments" },
{ "href": "/api/clouds/1/volume_snapshots", "rel": "volume_snapshots" },
{ "href": "/api/clouds/1/volume_types", "rel": "volume_types" },
{ "href": "/api/clouds/1/volumes", "rel": "volumes" },
{ "href": "/api/clouds/1/subnets", "rel": "subnets" }
],
"name": "EC2 us-east-1"
},
{
"capabilities": [
{ "name": "supports_networks", "value": "true" },
{ "name": "supports_route_tables", "value": "true" },
{ "name": "supports_volume_attachments", "value": "true" },
{ "name": "supports_volume_snapshots", "value": "true" }
],
"cloud_type": "amazon",
"description": "Amazon's US Cloud on the West Coast",
"display_name": "AWS US-West",
"links": [
{ "href": "/api/clouds/3", "rel": "self" },
{ "href": "/api/clouds/3/datacenters", "rel": "datacenters" },
{ "href": "/api/clouds/3/instance_types", "rel": "instance_types" },
{ "href": "/api/clouds/3/security_groups", "rel": "security_groups" },
{ "href": "/api/clouds/3/instances", "rel": "instances" },
{ "href": "/api/clouds/3/ssh_keys", "rel": "ssh_keys" },
{ "href": "/api/clouds/3/images", "rel": "images" },
{ "href": "/api/clouds/3/ip_addresses", "rel": "ip_addresses" },
{ "href": "/api/clouds/3/ip_address_bindings", "rel": "ip_address_bindings" },
{ "href": "/api/clouds/3/volume_attachments", "rel": "volume_attachments" },
{ "href": "/api/clouds/3/recurring_volume_attachments", "rel": "recurring_volume_attachments" },
{ "href": "/api/clouds/3/volume_snapshots", "rel": "volume_snapshots" },
{ "href": "/api/clouds/3/volume_types", "rel": "volume_types" },
{ "href": "/api/clouds/3/volumes", "rel": "volumes" },
{ "href": "/api/clouds/3/subnets", "rel": "subnets" }
],
"name": "EC2 us-west-1"
},
{
"capabilities": [
{ "name": "supports_networks", "value": "true" },
{ "name": "supports_route_tables", "value": "true" },
{ "name": "supports_volume_attachments", "value": "true" },
{ "name": "supports_volume_snapshots", "value": "true" }
],
"cloud_type": "amazon",
"description": "Amazon's Europe cloud",
"display_name": "AWS EU-Ireland",
"links": [
{ "href": "/api/clouds/2", "rel": "self" },
{ "href": "/api/clouds/2/datacenters", "rel": "datacenters" },
{ "href": "/api/clouds/2/instance_types", "rel": "instance_types" },
{ "href": "/api/clouds/2/security_groups", "rel": "security_groups" },
{ "href": "/api/clouds/2/instances", "rel": "instances" },
{ "href": "/api/clouds/2/ssh_keys", "rel": "ssh_keys" },
{ "href": "/api/clouds/2/images", "rel": "images" },
{ "href": "/api/clouds/2/ip_addresses", "rel": "ip_addresses" },
{ "href": "/api/clouds/2/ip_address_bindings", "rel": "ip_address_bindings" },
{ "href": "/api/clouds/2/volume_attachments", "rel": "volume_attachments" },
{ "href": "/api/clouds/2/recurring_volume_attachments", "rel": "recurring_volume_attachments" },
{ "href": "/api/clouds/2/volume_snapshots", "rel": "volume_snapshots" },
{ "href": "/api/clouds/2/volume_types", "rel": "volume_types" },
{ "href": "/api/clouds/2/volumes", "rel": "volumes" },
{ "href": "/api/clouds/2/subnets", "rel": "subnets" }
],
"name": "EC2 eu-west-1"
}
]`
|
package main
import (
"fmt"
"math/rand"
"os"
"sync"
"time"
)
var source = rand.NewSource(time.Now().Unix())
var randN = rand.New(source)
var choices = [3]string{"rock", "paper", "scissors"}
func main() {
opponentChoice := make(chan string, 1)
var userChoice string
var wg sync.WaitGroup
wg.Add(1)
go randomChoice(&wg, opponentChoice)
fmt.Printf("Your opponent is thinking\nPick one (rock, paper, or scissors?)\n")
fmt.Scanln(&userChoice)
contains(choices[:], userChoice)
wg.Wait()
resultChecker(userChoice, <-opponentChoice)
}
func randomChoice(wg *sync.WaitGroup, choice chan string) {
sleepTime := randN.Intn(10)
time.Sleep(time.Duration(sleepTime) * time.Second)
fmt.Printf("Your opponent is ready\n")
choice <- choices[randN.Intn(len(choices))]
defer wg.Done()
}
func resultChecker(user, opponent string) {
fmt.Printf("opponent choice: " + opponent + "\n")
if user == "scissors" && opponent == "paper" || user == "rock" && opponent == "scissors" || user == "paper" && opponent == "rock" {
fmt.Printf("result = you win!")
} else if user == "rock" && opponent == "paper" || user == "scissors" && opponent == "rock" || user == "paper" && opponent == "scissors" {
fmt.Printf("result = you lose!")
} else {
fmt.Printf("result = draw")
}
}
func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
fmt.Printf("invalid input\n")
os.Exit(1)
return false
}
|
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package validation
import (
"reflect"
"strings"
"testing"
"k8s.io/apimachinery/pkg/util/diff"
utilfeature "k8s.io/apiserver/pkg/util/feature"
featuregatetesting "k8s.io/component-base/featuregate/testing"
api "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/features"
)
func TestValidateServiceIPFamily(t *testing.T) {
ipv4 := api.IPv4Protocol
ipv6 := api.IPv6Protocol
var unknown api.IPFamily = "Unknown"
testCases := []struct {
name string
dualStackEnabled bool
ipFamilies []api.IPFamily
svc *api.Service
oldSvc *api.Service
expectErr []string
}{
{
name: "allowed ipv4",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv4Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &ipv4,
},
},
},
{
name: "allowed ipv6",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv6Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &ipv6,
},
},
},
{
name: "allowed ipv4 dual stack default IPv6",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv6Protocol, api.IPv4Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &ipv4,
},
},
},
{
name: "allowed ipv4 dual stack default IPv4",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv4Protocol, api.IPv6Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &ipv4,
},
},
},
{
name: "allowed ipv6 dual stack default IPv6",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv6Protocol, api.IPv4Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &ipv6,
},
},
},
{
name: "allowed ipv6 dual stack default IPv4",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv4Protocol, api.IPv6Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &ipv6,
},
},
},
{
name: "allow ipfamily to remain invalid if update doesn't change it",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv4Protocol, api.IPv6Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &unknown,
},
},
oldSvc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &unknown,
},
},
},
{
name: "not allowed ipfamily/clusterip mismatch",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv4Protocol, api.IPv6Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &ipv4,
ClusterIP: "ffd0::1",
},
},
expectErr: []string{"spec.ipFamily: Invalid value: \"IPv4\": does not match IPv6 cluster IP"},
},
{
name: "not allowed unknown family",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv4Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &unknown,
},
},
expectErr: []string{"spec.ipFamily: Invalid value: \"Unknown\": only the following families are allowed: IPv4"},
},
{
name: "not allowed ipv4 cluster ip without family",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv6Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
ClusterIP: "127.0.0.1",
},
},
expectErr: []string{"spec.ipFamily: Required value: programmer error, must be set or defaulted by other fields"},
},
{
name: "not allowed ipv6 cluster ip without family",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv4Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
ClusterIP: "ffd0::1",
},
},
expectErr: []string{"spec.ipFamily: Required value: programmer error, must be set or defaulted by other fields"},
},
{
name: "not allowed to change ipfamily for default type",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv4Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &ipv4,
},
},
oldSvc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &ipv6,
},
},
expectErr: []string{"spec.ipFamily: Invalid value: \"IPv4\": field is immutable"},
},
{
name: "allowed to change ipfamily for external name",
dualStackEnabled: true,
ipFamilies: []api.IPFamily{api.IPv4Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
Type: api.ServiceTypeExternalName,
IPFamily: &ipv4,
},
},
oldSvc: &api.Service{
Spec: api.ServiceSpec{
Type: api.ServiceTypeExternalName,
IPFamily: &ipv6,
},
},
},
{
name: "ipfamily allowed to be empty when dual stack is off",
dualStackEnabled: false,
ipFamilies: []api.IPFamily{api.IPv4Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
ClusterIP: "127.0.0.1",
},
},
},
{
name: "ipfamily must be empty when dual stack is off",
dualStackEnabled: false,
ipFamilies: []api.IPFamily{api.IPv4Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
IPFamily: &ipv4,
ClusterIP: "127.0.0.1",
},
},
expectErr: []string{"spec.ipFamily: Forbidden: programmer error, must be cleared when the dual-stack feature gate is off"},
},
{
name: "ipfamily allowed to be cleared when dual stack is off",
dualStackEnabled: false,
ipFamilies: []api.IPFamily{api.IPv4Protocol},
svc: &api.Service{
Spec: api.ServiceSpec{
Type: api.ServiceTypeClusterIP,
ClusterIP: "127.0.0.1",
},
},
oldSvc: &api.Service{
Spec: api.ServiceSpec{
Type: api.ServiceTypeClusterIP,
ClusterIP: "127.0.0.1",
IPFamily: &ipv4,
},
},
expectErr: nil,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.IPv6DualStack, tc.dualStackEnabled)()
oldSvc := tc.oldSvc.DeepCopy()
newSvc := tc.svc.DeepCopy()
originalNewSvc := newSvc.DeepCopy()
errs := ValidateConditionalService(newSvc, oldSvc, tc.ipFamilies)
// objects should never be changed
if !reflect.DeepEqual(oldSvc, tc.oldSvc) {
t.Errorf("old object changed: %v", diff.ObjectReflectDiff(oldSvc, tc.svc))
}
if !reflect.DeepEqual(newSvc, originalNewSvc) {
t.Errorf("new object changed: %v", diff.ObjectReflectDiff(newSvc, originalNewSvc))
}
if len(errs) != len(tc.expectErr) {
t.Fatalf("unexpected number of errors: %v", errs)
}
for i := range errs {
if !strings.Contains(errs[i].Error(), tc.expectErr[i]) {
t.Errorf("unexpected error %d: %v", i, errs[i])
}
}
})
}
}
|
package main
import "fmt"
func forDemo() {
for i := 0; i < 10; i++ {
fmt.Println(i)
}
}
// 2.8.1
func nineXnine() {
for i := 1; i <= 9; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("%d * %d = %-2d ", i, j, i*j)
}
fmt.Println()
}
}
// 4.8.1
func arraySum() {
var sum = 0
var arraySum = [...]int{1, 3, 5, 7, 8}
fmt.Println(arraySum)
fmt.Printf("%T\n", arraySum)
for i := 0; i < len(arraySum); i++ {
sum = sum + arraySum[i]
}
fmt.Println(sum)
}
// 4.8.2
func findSum() {
var sum = 8
var arraySum = [...]int{1, 3, 5, 7, 8}
for i := 0; i < len(arraySum); i++ {
for j := i + 1; j < len(arraySum); j++ {
if arraySum[i]+arraySum[j] == sum {
fmt.Printf("(%d,%d)", i, j)
}
}
}
}
// 结构体
type person struct {
name string
age int
gender bool
hobby []string
}
// main
func main() {
fmt.Println("Hello World!")
// 输出10个连续数字
//forDemo()
// 9×9口诀表
//nineXnine()
// 数组求和
//arraySum()
// 输出下标,和为8
//findSum()
var p person
p.name = "老王"
p.age = 32
p.gender = true
p.hobby = []string{
"篮球",
"跑步",
}
fmt.Println(p)
fmt.Printf("%T\n", p)
}
|
package main
import "fmt"
// 配列は固定長だが、スライスは可変長で柔軟。
//
func main() {
primes := [6]int{2, 3, 5, 7, 11, 12}
var s []int = primes[0:1]
fmt.Println(s)
}
|
package post
import "errors"
// Error codes for violation of post entity rules
var (
ErrBadPostContent = errors.New("Post: Content was not provided with the enough data")
ErrNoFoundPost = errors.New("Post: Post with id was not found")
ErrMissingPostPicture = errors.New("Post: Post picture is mandatory")
)
// Error codes for bad threatment of domain comment rules
var (
ErrBadCommentContent = errors.New("Comment: Comment was not provided with the enough data")
ErrInvalidCommentLength = errors.New("Comment: Comment cannot be longer than 256 characteres")
ErrInvalidCommentState = errors.New("Comment: Comment is in removed state")
ErrUnexistentComment = errors.New("Comment: Referenced comment doesn't exist")
ErrNoCommentOwner = errors.New("Comment: Only the comment owner can remove it")
)
// ErrInvalidTagInformation is dispatched when a tag is created incorrectly
var ErrInvalidTagInformation = errors.New(("Tag was created incorrectly"))
|
package cmd
import (
"os"
"github.com/spf13/cobra"
"github.com/Zenika/marcel/backoffice"
"github.com/Zenika/marcel/config"
)
func init() {
var cfg = config.New()
var cmd = &cobra.Command{
Use: "backoffice",
Short: "Starts Marcel's Backoffice server",
Args: cobra.NoArgs,
PreRunE: preRunForServer(cfg),
Run: func(_ *cobra.Command, _ []string) {
os.Exit(backoffice.Module().Run())
},
}
var flags = cmd.Flags()
if _, err := cfg.FlagUintP(flags, "port", "p", cfg.HTTP().Port(), "Listening port", "http.port"); err != nil {
panic(err)
}
if _, err := cfg.FlagString(flags, "basePath", cfg.Backoffice().BasePath(), "Base path", "backoffice.basePath"); err != nil {
panic(err)
}
if _, err := cfg.FlagString(flags, "apiURI", cfg.API().BasePath(), "API URI", "api.basePath"); err != nil {
panic(err)
}
if _, err := cfg.FlagString(flags, "frontendURI", cfg.Frontend().BasePath(), "Frontend URI", "frontend.basePath"); err != nil {
panic(err)
}
Marcel.AddCommand(cmd)
}
|
package main
import "fmt"
func main(){
elements := map[string]map[string]string{
"H":map[string]string{
"name":"Hydrogen",
"state":"gas",
},
"He":map[string]string{
"name":"Helium",
"state":"gas",
},
}
if el,ok:=elements["He"];ok{
fmt.Println(el["name"],el["state"])
}
}
|
package services
import (
"fmt"
"io/ioutil"
"net/http"
"sync"
"docktor/server/storage"
"docktor/server/types"
"github.com/labstack/echo/v4"
)
// getAll find all
func getAll(c echo.Context) error {
db := c.Get("DB").(*storage.Docktor)
s, err := db.Services().FindAll()
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
// To run multiple get variables at the same time
var wg sync.WaitGroup
for i := 0; i < len(s); i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
s[i].GetVariablesOfSubServices()
}(i)
}
wg.Wait()
return c.JSON(http.StatusOK, s)
}
// getByID find one by id
func getByID(c echo.Context) error {
db := c.Get("DB").(*storage.Docktor)
s, err := db.Services().FindByID(c.Param(types.SERVICE_ID_PARAM))
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, s)
}
// getBySubServiceID find one by id
func getBySubServiceID(c echo.Context) error {
db := c.Get("DB").(*storage.Docktor)
s, err := db.Services().FindBySubServiceID(c.Param(types.SUBSERVICE_ID_PARAM))
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
s.GetVariablesOfSubServices()
return c.JSON(http.StatusOK, s)
}
// save a Service server
func save(c echo.Context) error {
var u types.Service
err := c.Bind(&u)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
db := c.Get("DB").(*storage.Docktor)
u, err = db.Services().Save(u)
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, u)
}
// deleteByID delete one by id
func deleteByID(c echo.Context) error {
db := c.Get("DB").(*storage.Docktor)
err := db.Services().Delete(c.Param(types.SERVICE_ID_PARAM))
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
return c.JSON(http.StatusOK, "ok")
}
func validateTemplate(c echo.Context) error {
template, err := ioutil.ReadAll(c.Request().Body)
if err != nil {
return c.JSON(http.StatusBadRequest, fmt.Sprintf("Failed to retrieve template: %s", err))
}
daemon := types.Daemon{
DaemonLight: types.DaemonLight{
Name: "testdaemon",
Host: "testdaemon.renn.fr.ssg",
},
Docker: types.Docker{
Volume: "/data",
},
}
serv := types.Service{
Name: "TEST_SERVICE",
}
group := types.Group{
GroupLight: types.GroupLight{
Name: "TEST_PROJECT",
},
}
service := types.SubService{
Name: "Test Service",
File: string(template),
}
err = service.GetVariables()
if err != nil {
return c.JSON(http.StatusBadRequest, fmt.Sprintf("Failed to parse variables in template: %s", err))
}
for i, v := range service.Variables {
if v.Name == "zap_port" {
service.Variables[i].Value = "10000"
}
}
gs, err := service.ConvertToGroupService("ServiceTest", daemon, serv, group, false, []string{})
if err != nil {
return c.JSON(http.StatusBadRequest, fmt.Sprintf("Failed to convert to group service: %s", err))
}
return c.String(http.StatusOK, string(gs.File))
}
|
package freshdesk
import (
"testing"
"github.com/leebenson/conform"
)
func TestTicket(t *testing.T) {
t.Skip("Need account info to test this")
client, err := NewClient("", "")
if err != nil {
t.Fatalf("Could not create client: %s\n", err)
}
ticket := &Ticket{
Email: "testuser@example.com",
Name: "Cool Testuser",
Subject: "this is a test feature request",
Type: FeatureRequest,
Description: "the (HTML) content of the ticket would go here",
Status: Open,
Priority: Low,
Tags: []string{"test"},
Source: Portal,
}
// optionally check the ticket with conform
conform.Strings(ticket)
if _, err := client.CreateTicket(ticket); err != nil {
t.Fatalf("failed to create ticket: %s", err)
}
}
|
package p2pNetwork
import (
"encoding/json"
"errors"
"fmt"
"github.com/HNB-ECO/HNB-Blockchain/HNB/config"
"github.com/HNB-ECO/HNB-Blockchain/HNB/logging"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/common"
msgtypes "github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/bean"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/reqMsg"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/utils"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/peer"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/server"
"github.com/HNB-ECO/HNB-Blockchain/HNB/util"
"io/ioutil"
"math/rand"
"net"
"os"
"strconv"
"sync"
"time"
)
var P2PLog logging.LogModule
const (
LOGTABLE_NETWORK string = "network"
)
type PPNetServer struct {
network server.P2P
msgRouter *utils.MessageRouter
ReconnectAddrs
recentPeers []string
quitSyncRecent chan bool
quitOnline chan bool
quitHeartBeat chan bool
}
type ReconnectAddrs struct {
sync.RWMutex
RetryAddrs map[string]int
}
var P2PIns *PPNetServer
func NewServer() *PPNetServer {
P2PLog = logging.GetLogIns()
P2PLog.Info(LOGTABLE_NETWORK, "ready start p2p server")
n := NewNetServer()
p := &PPNetServer{
network: n,
}
p.msgRouter = utils.NewMsgRouter(p.network)
p.recentPeers = make([]string, common.RECENT_LIMIT)
p.quitSyncRecent = make(chan bool)
p.quitOnline = make(chan bool)
p.quitHeartBeat = make(chan bool)
P2PIns = p
return p
}
func (pps *PPNetServer) RegisterTxNotify() uint32 {
return pps.network.GetConnectionCnt()
}
func (pps *PPNetServer) RegisterSyncNotify() uint32 {
return pps.network.GetConnectionCnt()
}
func (pps *PPNetServer) RegisterConsNotify() uint32 {
return pps.network.GetConnectionCnt()
}
func (pps *PPNetServer) GetConnectionCnt() uint32 {
return pps.network.GetConnectionCnt()
}
func (pps *PPNetServer) Start() error {
if pps.network != nil {
pps.network.Start()
} else {
return errors.New("p2p network invalid")
}
if pps.msgRouter != nil {
pps.msgRouter.Start()
} else {
return errors.New("p2p msg router invalid")
}
pps.tryRecentPeers()
go pps.connectSeedService()
go pps.syncUpRecentPeers()
go pps.keepOnlineService()
go pps.heartBeatService()
return nil
}
func (pps *PPNetServer) Stop() {
pps.network.Halt()
pps.quitSyncRecent <- true
pps.quitOnline <- true
pps.quitHeartBeat <- true
pps.msgRouter.Stop()
}
func (pps *PPNetServer) GetNetWork() server.P2P {
return pps.network
}
func (pps *PPNetServer) GetPort() (uint16, uint16) {
return pps.network.GetSyncPort(), pps.network.GetConsPort()
}
func (pps *PPNetServer) GetVersion() uint32 {
return pps.network.GetVersion()
}
func (pps *PPNetServer) GetNeighborAddrs() []common.PeerAddr {
return pps.network.GetNeighborAddrs()
}
//func (pps *PPNetServer) Xmit(msg string, isConsensus bool){
// m := msgpack.NewTestNet(msg)
// pps.network.Xmit(m, isConsensus)
//}
func (pps *PPNetServer) Send(p *peer.Peer, msg msgtypes.Message,
isConsensus bool) error {
if pps.network.IsPeerEstablished(p) {
return pps.network.Send(p, msg, isConsensus)
}
//log.Errorf("PPNetServer send to a not ESTABLISH peer %d",
// p.GetID())
return errors.New("send to a not ESTABLISH peer")
}
func (pps *PPNetServer) GetID() uint64 {
return pps.network.GetID()
}
func (pps *PPNetServer) GetConnectionState() uint32 {
return common.INIT
}
func (pps *PPNetServer) GetTime() int64 {
return pps.network.GetTime()
}
func (pps *PPNetServer) WaitForPeersStart() {
//periodTime := time.Minute//config.DEFAULT_GEN_BLOCK_TIME / common.UPDATE_RATE_PER_BLOCK
//for {
// //log.Info("Wait for minimum connection...")
// if pps.reachMinConnection() {
// break
// }
//
// <-time.After(time.Second * (time.Duration(periodTime)))
//}
}
//链接发现种子
func (pps *PPNetServer) connectSeeds() {
seedNodes := make([]string, 0)
pList := make([]*peer.Peer, 0)
for _, n := range config.Config.SeedList {
//获取IP地址
ip, err := common.ParseIPAddr(n)
if err != nil {
P2PLog.Warningf(LOGTABLE_NETWORK, "seed peer %s address format is wrong", n)
continue
}
//host 主机与ip映射
ns, err := net.LookupHost(ip)
if err != nil {
P2PLog.Warningf(LOGTABLE_NETWORK, "resolve err: %s", err.Error())
continue
}
//获取端口号
port, err := common.ParseIPPort(n)
if err != nil {
P2PLog.Warningf(LOGTABLE_NETWORK, "seed peer %s address format is wrong", n)
continue
}
seedNodes = append(seedNodes, ns[0]+port)
}
for _, nodeAddr := range seedNodes {
var ip net.IP
np := pps.network.GetNp()
P2PLog.Infof(LOGTABLE_NETWORK, "process seedNode %v", nodeAddr)
np.Lock()
for _, tn := range np.List {
ipAddr, _ := tn.GetAddr16()
ip = ipAddr[:]
addrString := ip.To16().String() + ":" +
strconv.Itoa(int(tn.GetSyncPort()))
if nodeAddr == addrString && tn.GetSyncState() == common.ESTABLISH {
pList = append(pList, tn)
}
}
np.Unlock()
}
if len(pList) > 0 {
rand.Seed(time.Now().UnixNano())
index := rand.Intn(len(pList))
pps.reqNbrList(pList[index])
} else { //not found
for _, nodeAddr := range seedNodes {
go pps.network.Connect(nodeAddr, false)
}
}
}
func (pps *PPNetServer) getNode(id uint64) *peer.Peer {
return pps.network.GetPeer(id)
}
func (pps *PPNetServer) retryInactivePeer() {
np := pps.network.GetNp()
np.Lock()
var ip net.IP
neighborPeers := make(map[uint64]*peer.Peer)
for _, p := range np.List {
addr, _ := p.GetAddr16()
ip = addr[:]
nodeAddr := ip.To16().String() + ":" +
strconv.Itoa(int(p.GetSyncPort()))
if p.GetSyncState() == common.INACTIVITY {
//log.Infof(" try reconnect %s", nodeAddr)
pps.addToRetryList(nodeAddr)
p.CloseSync()
p.CloseCons()
} else {
pps.removeFromRetryList(nodeAddr)
neighborPeers[p.GetID()] = p
}
}
np.List = neighborPeers
np.Unlock()
connCount := uint(pps.network.GetOutConnRecordLen())
if connCount >= config.Config.MaxConnOutBound {
//log.Warnf("P2PLog.Warningf(LOGTABLE_NETWORK,: out connections(%d) reach the max limit(%d)", connCount,
// config.DefConfig.P2PNode.MaxConnOutBound)
return
}
if len(pps.RetryAddrs) > 0 {
pps.ReconnectAddrs.Lock()
list := make(map[string]int)
addrs := make([]string, 0, len(pps.RetryAddrs))
for addr, v := range pps.RetryAddrs {
v += 1
addrs = append(addrs, addr)
if v < common.MAX_RETRY_COUNT {
list[addr] = v
}
if v >= common.MAX_RETRY_COUNT {
pps.network.RemoveFromConnectingList(addr)
remotePeer := pps.network.GetPeerFromAddr(addr)
if remotePeer != nil {
if remotePeer.SyncLink.GetAddr() == addr {
pps.network.RemovePeerSyncAddress(addr)
pps.network.RemovePeerConsAddress(addr)
}
if remotePeer.ConsLink.GetAddr() == addr {
pps.network.RemovePeerConsAddress(addr)
}
pps.network.DelNbrNode(remotePeer.GetID())
}
}
}
pps.RetryAddrs = list
pps.ReconnectAddrs.Unlock()
for _, addr := range addrs {
rand.Seed(time.Now().UnixNano())
P2PLog.Infof(LOGTABLE_NETWORK, "Try to reconnect peer, peer addr is ", addr)
<-time.After(time.Duration(rand.Intn(common.CONN_MAX_BACK)) * time.Millisecond)
P2PLog.Infof(LOGTABLE_NETWORK, "Back off time`s up, start connect node")
pps.network.Connect(addr, false)
}
}
}
func (pps *PPNetServer) connectSeedService() {
t := time.NewTimer(time.Second * common.CONN_MONITOR)
for {
select {
case <-t.C:
pps.connectSeeds()
t.Stop()
t.Reset(time.Second * common.CONN_MONITOR)
case <-pps.quitOnline:
t.Stop()
break
}
}
}
func (pps *PPNetServer) keepOnlineService() {
t := time.NewTimer(time.Second * common.CONN_MONITOR)
for {
select {
case <-t.C:
pps.retryInactivePeer()
t.Stop()
t.Reset(time.Second * common.CONN_MONITOR)
case <-pps.quitOnline:
t.Stop()
break
}
}
}
func (pps *PPNetServer) reqNbrList(p *peer.Peer) {
msg := reqMsg.NewAddrReq()
go pps.Send(p, msg, false)
}
func (pps *PPNetServer) heartBeatService() {
var periodTime uint
periodTime = 10
t := time.NewTicker(time.Second * (time.Duration(periodTime)))
for {
select {
case <-t.C:
pps.ping()
pps.timeout()
case <-pps.quitHeartBeat:
t.Stop()
break
}
}
}
func (pps *PPNetServer) ping() {
peers := pps.network.GetNeighbors()
for _, p := range peers {
if p.GetSyncState() == common.ESTABLISH {
//height := pps.ledger.GetCurrentBlockHeight()
height := 0
ping := reqMsg.NewPingMsg(uint64(height))
go pps.Send(p, ping, false)
}
}
}
func (pps *PPNetServer) timeout() {
peers := pps.network.GetNeighbors()
var periodTime uint
periodTime = 10
for _, p := range peers {
if p.GetSyncState() == common.ESTABLISH {
t := p.GetContactTime()
if t.Before(time.Now().Add(-1 * time.Second *
time.Duration(periodTime) * common.KEEPALIVE_TIMEOUT)) {
//log.Warnf("keep alive timeout!!!lost remote peer %d - %s from %s", p.GetID(), p.SyncLink.GetAddr(), t.String())
p.CloseSync()
p.CloseCons()
}
}
}
}
func (pps *PPNetServer) addToRetryList(addr string) {
pps.ReconnectAddrs.Lock()
defer pps.ReconnectAddrs.Unlock()
if pps.RetryAddrs == nil {
pps.RetryAddrs = make(map[string]int)
}
if _, ok := pps.RetryAddrs[addr]; ok {
delete(pps.RetryAddrs, addr)
}
//alway set retry to 0
pps.RetryAddrs[addr] = 0
}
func (pps *PPNetServer) removeFromRetryList(addr string) {
pps.ReconnectAddrs.Lock()
defer pps.ReconnectAddrs.Unlock()
if len(pps.RetryAddrs) > 0 {
if _, ok := pps.RetryAddrs[addr]; ok {
delete(pps.RetryAddrs, addr)
}
}
}
func (pps *PPNetServer) tryRecentPeers() {
//假设在当前路径
if util.PathExists(common.RECENT_FILE_NAME) {
buf, err := ioutil.ReadFile(common.RECENT_FILE_NAME)
if err != nil {
errMsg := fmt.Sprintf("read %s fail:%s, connect recent peers cancel", common.RECENT_FILE_NAME, err.Error())
P2PLog.Warning(LOGTABLE_NETWORK, errMsg)
return
}
err = json.Unmarshal(buf, &pps.recentPeers)
if err != nil {
errMsg := fmt.Sprintf("parse recent peer file fail: %s", err.Error())
P2PLog.Warning(LOGTABLE_NETWORK, errMsg)
return
}
if len(pps.recentPeers) > 0 {
P2PLog.Infof(LOGTABLE_NETWORK, "try to connect recent peer")
}
for _, v := range pps.recentPeers {
msg := fmt.Sprintf("try to connect recent peer %s", v)
P2PLog.Info(LOGTABLE_NETWORK, msg)
go pps.network.Connect(v, false)
}
}
}
func (pps *PPNetServer) syncUpRecentPeers() {
periodTime := common.RECENT_TIMEOUT
t := time.NewTicker(time.Second * (time.Duration(periodTime)))
for {
select {
case <-t.C:
pps.syncPeerAddr()
case <-pps.quitSyncRecent:
t.Stop()
break
}
}
}
//syncPeerAddr compare snapshot of recent peer with current link,then persist the list
func (pps *PPNetServer) syncPeerAddr() {
changed := false
for i := 0; i < len(pps.recentPeers); i++ {
p := pps.network.GetPeerFromAddr(pps.recentPeers[i])
if p == nil || (p != nil && p.GetSyncState() != common.ESTABLISH) {
pps.recentPeers = append(pps.recentPeers[:i], pps.recentPeers[i+1:]...)
changed = true
i--
}
}
left := common.RECENT_LIMIT - len(pps.recentPeers)
if left > 0 {
np := pps.network.GetNp()
np.Lock()
var ip net.IP
for _, p := range np.List {
addr, _ := p.GetAddr16()
ip = addr[:]
nodeAddr := ip.To16().String() + ":" +
strconv.Itoa(int(p.GetSyncPort()))
found := false
for i := 0; i < len(pps.recentPeers); i++ {
if nodeAddr == pps.recentPeers[i] {
found = true
break
}
}
if !found {
pps.recentPeers = append(pps.recentPeers, nodeAddr)
left--
changed = true
if left == 0 {
break
}
}
}
np.Unlock()
}
if changed {
buf, err := json.Marshal(pps.recentPeers)
if err != nil {
//log.Error("package recent peer fail: ", err)
return
}
err = ioutil.WriteFile(common.RECENT_FILE_NAME, buf, os.ModePerm)
if err != nil {
//log.Error("write recent peer fail: ", err)
}
}
}
|
package secrets
import (
"fmt"
"github.com/10gen/realm-cli/internal/cli"
"github.com/10gen/realm-cli/internal/cli/user"
"github.com/10gen/realm-cli/internal/cloud/realm"
"github.com/10gen/realm-cli/internal/terminal"
"github.com/10gen/realm-cli/internal/utils/flags"
)
// CommandMetaList is the command meta for the `secrets list` command
var CommandMetaList = cli.CommandMeta{
Use: "list",
Aliases: []string{"ls"},
Display: "secrets list",
Description: "List the Secrets in your Realm app",
HelpText: `This will display the IDs and Names of the Secrets in your Realm app.`,
}
// CommandList is the `secrets list` command
type CommandList struct {
inputs listInputs
}
type listInputs struct {
cli.ProjectInputs
}
// Flags are the command flags
func (cmd *CommandList) Flags() []flags.Flag {
return []flags.Flag{
cli.AppFlagWithContext(&cmd.inputs.App, "to list its secrets"),
cli.ProjectFlag(&cmd.inputs.Project),
cli.ProductFlag(&cmd.inputs.Products),
}
}
// Inputs are the command inputs
func (cmd *CommandList) Inputs() cli.InputResolver {
return &cmd.inputs
}
// Handler is the command handler
func (cmd *CommandList) Handler(profile *user.Profile, ui terminal.UI, clients cli.Clients) error {
app, appErr := cli.ResolveApp(ui, clients.Realm, cmd.inputs.Filter())
if appErr != nil {
return appErr
}
secrets, secretsErr := clients.Realm.Secrets(app.GroupID, app.ID)
if secretsErr != nil {
return secretsErr
}
if len(secrets) == 0 {
ui.Print(terminal.NewTextLog("No available secrets to show"))
return nil
}
ui.Print(terminal.NewTableLog(
fmt.Sprintf("Found %d secrets", len(secrets)),
tableHeaders(),
tableRowsList(secrets)...,
))
return nil
}
func tableRowsList(secrets []realm.Secret) []map[string]interface{} {
rows := make([]map[string]interface{}, 0, len(secrets))
for _, secret := range secrets {
rows = append(rows, map[string]interface{}{
headerName: secret.Name,
headerID: secret.ID,
})
}
return rows
}
func (i *listInputs) Resolve(profile *user.Profile, ui terminal.UI) error {
if err := i.ProjectInputs.Resolve(ui, profile.WorkingDirectory, false); err != nil {
return err
}
return nil
}
|
package main
import "fmt"
// 结构体实现”继承“
type animal struct {
name string
}
// 给animal实现一个西东的方法
func (a animal) move() {
fmt.Printf("%s会动。", a.name)
}
// 狗类
type dog struct {
feet uint8
animal
}
// 给狗实现一个汪汪汪的方法
func (d dog) wang() {
fmt.Printf("%s会汪汪汪~", d.name)
}
func main() {
d1 := dog{
feet: 4,
animal: animal{
name: "www",
},
}
d1.wang()
d1.move()
}
|
package dcmdata
import (
"testing"
)
func TestNewDcmInputStream(t *testing.T) {
cases := []struct {
in *DcmProducer
want *DcmInputStream
}{
{new(DcmProducer), &DcmInputStream{}},
}
for _, c := range cases {
got := NewDcmInputStream(c.in)
if *got != *c.want {
t.Errorf("NewDcmInputStream(%v) == want %v got %v", c.in, c.want, got)
}
}
}
|
package sudoku
import (
"fmt"
"math/rand"
)
type xwingTechnique struct {
*basicSolveTechnique
}
func (self *xwingTechnique) humanLikelihood(step *SolveStep) float64 {
return self.difficultyHelper(50.0)
}
func (self *xwingTechnique) Description(step *SolveStep) string {
majorAxis := "NONE"
minorAxis := "NONE"
var majorGroups IntSlice
var minorGroups IntSlice
switch self.groupType {
case _GROUP_ROW:
majorAxis = "rows"
minorAxis = "columns"
majorGroups = step.PointerCells.AllRows()
minorGroups = step.PointerCells.AllCols()
case _GROUP_COL:
majorAxis = "columns"
minorAxis = "rows"
majorGroups = step.PointerCells.AllCols()
minorGroups = step.PointerCells.AllRows()
}
//Ensure a stable description; Unique() doesn't have a guranteed order.
majorGroups.Sort()
minorGroups.Sort()
return fmt.Sprintf("in %s %s, %d is only possible in %s %s, and %d must be in one of those cells per %s, so it can't be in any other cells in those %s",
majorAxis,
majorGroups.Description(),
step.TargetNums[0],
minorAxis,
minorGroups.Description(),
step.TargetNums[0],
majorAxis,
minorAxis,
)
}
func (self *xwingTechnique) Candidates(grid Grid, maxResults int) []*SolveStep {
return self.candidatesHelper(self, grid, maxResults)
}
func (self *xwingTechnique) find(grid Grid, coordinator findCoordinator) {
getter := self.getter(grid)
//For each number
for _, i := range rand.Perm(DIM) {
//In comments we'll say "Row" for the major group type, and "col" for minor group type, just for easier comprehension.
//Look for each row that has that number possible in only two cells.
if coordinator.shouldExitEarly() {
return
}
//i is zero indexed right now
i++
var majorGroups []CellRefSlice
for groupIndex := 0; groupIndex < DIM; groupIndex++ {
group := getter(groupIndex)
cells := group.FilterByPossible(i).CellReferenceSlice()
if len(cells) == 2 {
//Found a row that might fit the bill.
majorGroups = append(majorGroups, cells)
}
}
//Okay, did we have two rows?
if len(majorGroups) < 2 {
//Not enough rows
continue
}
//Now look at each pair of rows and see if their numbers line up.
for _, subsets := range subsetIndexes(len(majorGroups), 2) {
if coordinator.shouldExitEarly() {
return
}
var targetCells CellRefSlice
currentGroups := []CellRefSlice{majorGroups[subsets[0]], majorGroups[subsets[1]]}
//Are the possibilities in each row in the same column as the one above?
//We need to do this differently depending on if we're row or col.
if self.groupType == _GROUP_ROW {
//TODO: figure out a way to factor group row and col better so we don't duplicate code like this.
if currentGroups[0][0].Col != currentGroups[1][0].Col || currentGroups[0][1].Col != currentGroups[1][1].Col {
//Nope, the cells didn't line up.
continue
}
//All of the cells in those two columns
targetCells = append(col(currentGroups[0][0].Col), col(currentGroups[0][1].Col)...)
} else if self.groupType == _GROUP_COL {
if currentGroups[0][0].Row != currentGroups[1][0].Row || currentGroups[0][1].Row != currentGroups[1][1].Row {
//Nope, the cells didn't line up.
continue
}
//All of the cells in those two columns
targetCells = append(row(currentGroups[0][0].Row), row(currentGroups[0][1].Row)...)
}
//Then remove the cells that are the pointerCells
targetCells = targetCells.RemoveCells(currentGroups[0])
targetCells = targetCells.RemoveCells(currentGroups[1])
//And remove the cells that don't have the target number to remove (to keep the set tight; technically it's OK to include them it would just be a no-op for those cells)
targetCells = targetCells.CellSlice(grid).FilterByPossible(i).CellReferenceSlice()
//Okay, we found a pair that works. Create a step for it (if it's useful)
step := &SolveStep{self, targetCells, IntSlice{i}, append(currentGroups[0], currentGroups[1]...), nil, nil}
if step.IsUseful(grid) {
if coordinator.foundResult(step) {
return
}
}
}
}
}
|
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document03800105 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.038.001.05 Document"`
Message *SecuritiesSettlementTransactionModificationRequestV05 `xml:"SctiesSttlmTxModReq"`
}
func (d *Document03800105) AddMessage() *SecuritiesSettlementTransactionModificationRequestV05 {
d.Message = new(SecuritiesSettlementTransactionModificationRequestV05)
return d.Message
}
// Scope
// This message is sent by an account owner to an account servicer.
//
// The account owner will generally be:
// - a central securities depository participant which has an account with a central securities depository or a market infrastructure
// - an investment manager which has an account with a custodian acting as accounting and/or settlement agent.
//
// It is used to request the modification of non core business data (matching or non-matching) information in a pending or settled instruction. It can also be used for the enrichment of an incomplete transaction.
//
// Usage
// The modification must only contain the data to be modified.
// The message may also be used to:
// - re-send a message sent by the account owner to the account servicer,
// - provide a third party with a copy of a message being sent by the account owner for information,
// - re-send to a third party a copy of a message being sent by the account owner for information
// using the relevant elements in the Business Application Header.
type SecuritiesSettlementTransactionModificationRequestV05 struct {
// Identifies the details of the transaction that is being modified.
ModifiedTransactionDetails *iso20022.TransactionDetails76 `xml:"ModfdTxDtls"`
// Specifies the type of update requested.
UpdateType []*iso20022.UpdateType25Choice `xml:"UpdTp"`
}
func (s *SecuritiesSettlementTransactionModificationRequestV05) AddModifiedTransactionDetails() *iso20022.TransactionDetails76 {
s.ModifiedTransactionDetails = new(iso20022.TransactionDetails76)
return s.ModifiedTransactionDetails
}
func (s *SecuritiesSettlementTransactionModificationRequestV05) AddUpdateType() *iso20022.UpdateType25Choice {
newValue := new(iso20022.UpdateType25Choice)
s.UpdateType = append(s.UpdateType, newValue)
return newValue
}
|
package utils
import (
"bytes"
"fmt"
"io"
"strings"
"text/template"
"text/template/parse"
)
// PrefixRenderer writes data to pw
type PrefixRenderer = func(pw *PrefixWriter, params map[string]interface{})
// RenderTemplate renders templates respecting indentation
// Its intended use is for YAML templates
// check template_test for an example.
func RenderTemplate(
main0 *template.Template,
vmap map[string]interface{},
tmap map[string]PrefixRenderer,
wr io.Writer,
) error {
var buff bytes.Buffer
main0.Execute(&buff, vmap)
main := template.Must(template.New("main").Parse(buff.String()))
mainTree := main.Tree
lastIndent := -1
for _, node := range mainTree.Root.Nodes {
switch ty := node.Type(); ty {
case parse.NodeText:
nodeTxt := node.(*parse.TextNode)
_, err := wr.Write(nodeTxt.Text)
if err != nil {
return err
}
lastIndent = -1
lastIdx := len(nodeTxt.Text) - 1
cnt := 0
for {
if lastIdx == 0 {
break
}
lastIdx--
cnt++
if nodeTxt.Text[lastIdx] == '\n' {
lastIndent = cnt
break
}
}
case parse.NodeTemplate:
nodeTmpl := node.(*parse.TemplateNode)
renderer, ok := tmap[nodeTmpl.Name]
if !ok {
return fmt.Errorf("template %s does not exist", nodeTmpl.Name)
}
if lastIndent == -1 {
panic("NYI")
}
pw := NewPrefixWriter(wr, true)
pw.PushPrefix(strings.Repeat(" ", lastIndent))
renderer(pw, vmap)
pw.PopPrefix()
err := pw.Done()
if err != nil {
return fmt.Errorf("error terminating prefix writer: %w", err)
}
default:
panic("Unexpected node type")
}
}
return nil
}
|
package davepdf
import (
"fmt"
"strings"
)
type PdfPageTree struct {
id int
pages []*PdfPage
}
func (pdf *Pdf) newPageTree() *PdfPageTree {
pageTree := &PdfPageTree{}
pdf.newObjId()
pageTree.id = pdf.n
return pageTree
}
func (pdf *Pdf) AddPage() *PdfPage {
page := pdf.newPage()
pdf.page = page
return page
}
func (pdf *Pdf) writePageTree() {
// Kids (child pages of page tree) - e.g. /Kids [3 0 R 21 0 R]
kids := ""
for _, page := range pdf.pageTree.pages {
kids += fmt.Sprintf("%d 0 R ", page.id)
}
// Trim leading space
kids = strings.TrimSpace(kids)
pdf.newObj(pdf.pageTree.id)
pdf.outln("<<")
pdf.outln(" /Type /Pages")
pdf.outln(fmt.Sprintf(" /Count %d", len(pdf.pageTree.pages)))
pdf.outln(fmt.Sprintf(" /Kids [%s]", kids))
pdf.outln(">>")
pdf.outln("endobj\n")
}
|
package elastiwatch
import (
"context"
"fmt"
"regexp"
"time"
"github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/chat1"
"github.com/malware-unicorn/managed-bots/base"
"github.com/olivere/elastic"
)
type LogWatch struct {
*base.DebugOutput
db *DB
cli *elastic.Client
index, email string
entries []*entry
emailer base.Emailer
sendCount int
lastSend time.Time
alertConvID chat1.ConvIDStr
emailConvID chat1.ConvIDStr
shutdownCh chan struct{}
peekCh chan struct{}
}
func NewLogWatch(cli *elastic.Client, db *DB, index, email string, emailer base.Emailer,
alertConvID, emailConvID chat1.ConvIDStr, debugConfig *base.ChatDebugOutputConfig) *LogWatch {
return &LogWatch{
DebugOutput: base.NewDebugOutput("LogWatch", debugConfig),
cli: cli,
db: db,
index: index,
email: email,
emailer: emailer,
lastSend: time.Now(),
alertConvID: alertConvID,
emailConvID: emailConvID,
shutdownCh: make(chan struct{}),
peekCh: make(chan struct{}),
}
}
func (l *LogWatch) addAndCheckForSend(entries []*entry) {
l.entries = append(l.entries, l.filterEntries(entries)...)
threshold := 10000
score := 0
for _, e := range l.entries {
switch e.Severity {
case "INFO":
score++
case "WARNING":
score += 5
case "ERROR":
score += 25
case "CRITICAL":
score += 10000
}
}
if score > threshold {
entriesCopy := make([]*entry, len(l.entries))
copy(entriesCopy, l.entries)
l.entries = nil
l.Debug("threshold reached, sending: score: %d threshold: %d entries: %d",
score, threshold, len(entriesCopy))
go l.generateAndSend(entriesCopy)
}
}
const backs = "```"
func (l *LogWatch) alertFromChunk(c chunk) {
if c.Severity != "CRITICAL" {
return
}
l.ChatEcho(l.alertConvID, `%d *CRITICAL* errors received
%s%s%s`, c.Count, backs, c.Message, backs)
}
func (l *LogWatch) alertEmail(subject string, chunks []chunk) {
body := fmt.Sprintf("Email sent: %s", subject)
for _, c := range chunks {
if c.Severity == "INFO" {
continue
}
body += fmt.Sprintf("\n%s %d %s", c.Severity, c.Count, c.Message)
}
l.ChatEcho(l.emailConvID, "```"+body+"```")
}
func (l *LogWatch) filterEntries(entries []*entry) (res []*entry) {
// get regexes
deferrals, err := l.db.List()
if err != nil {
l.Errorf("failed to get filter list: %s", err)
return entries
}
if len(deferrals) == 0 {
return entries
}
var regexs []*regexp.Regexp
for _, d := range deferrals {
r, err := regexp.Compile(d.regex)
if err != nil {
l.Errorf("invalid regex: %s err: %s", d, err)
continue
}
regexs = append(regexs, r)
}
// filter
isBlocked := func(msg string) bool {
for _, r := range regexs {
if r.Match([]byte(msg)) {
l.Debug("filtering message: %s regex: %s", msg, r)
return true
}
}
return false
}
for _, e := range entries {
if !isBlocked(e.Message) {
res = append(res, e)
}
}
return res
}
func (l *LogWatch) peek() {
groupRes := newTreeifyGrouper(3).Group(l.entries)
l.alertEmail("Peek results", groupRes)
}
func (l *LogWatch) generateAndSend(entries []*entry) {
// do tree grouping
groupRes := newTreeifyGrouper(3).Group(entries)
indivRes := newTreeifyGrouper(0).Group(entries)
for _, c := range groupRes {
l.alertFromChunk(c)
}
var sections []renderSection
sections = append(sections, renderSection{
Heading: "Grouped Messages",
Chunks: groupRes,
})
sections = append(sections, renderSection{
Heading: "Individual Messages",
Chunks: indivRes,
})
renderText, err := htmlRenderer{}.Render(sections)
if err != nil {
l.Debug("error rendering chunks: %s", err.Error())
}
dur := time.Since(l.lastSend).String()
subject := fmt.Sprintf("Log Error Report - #%d - %s", l.sendCount, dur)
l.alertEmail(subject, groupRes)
if err := l.emailer.Send(l.email, subject, renderText); err != nil {
l.Debug("error sending email: %s", err.Error())
}
l.sendCount++
l.lastSend = time.Now()
}
func (l *LogWatch) runOnce() {
query := elastic.NewBoolQuery().
Must(elastic.NewRangeQuery("@timestamp").
From(time.Now().Add(-time.Minute)).
To(time.Now())).
MustNot(elastic.NewTermQuery("severity", "debug"))
res, err := l.cli.Search().
Index(l.index).
Query(query).
Pretty(true).
From(0).Size(10000).
Do(context.Background())
if err != nil {
l.Debug("failed to run Elasticsearch query: %s", err)
return
}
var entries []*entry
if res.TotalHits() > 0 {
l.Debug("query hits: %d", res.TotalHits())
for _, hit := range res.Hits.Hits {
entry, err := newEntry(*hit.Source)
if err != nil {
l.Errorf("failed to unmarshal log entry: %s", err)
continue
}
entries = append(entries, entry)
}
} else {
l.Debug("no query hits, doing nothing")
}
l.addAndCheckForSend(entries)
}
func (l *LogWatch) Run() error {
l.Debug("log watch starting up...")
if l.alertConvID != "" {
l.Debug("alerting into convID: %s", l.alertConvID)
}
if l.emailConvID != "" {
l.Debug("email notices into convID: %s", l.emailConvID)
}
l.runOnce()
for {
select {
case <-l.shutdownCh:
return nil
case <-l.peekCh:
l.peek()
case <-time.After(time.Minute):
l.runOnce()
}
}
}
func (l *LogWatch) Peek() {
l.peekCh <- struct{}{}
}
func (l *LogWatch) Shutdown() error {
close(l.shutdownCh)
return nil
}
|
package http
import (
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
func RegisterRoutes(r chi.Router, meetUpHandler *MeetupHandler) {
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Heartbeat("/health"))
r.Use(securityMiddleware)
r.Route("/meetup", func(r chi.Router) {
r.Get("/beer", meetUpHandler.calculateTotalBeers)
})
}
|
// DO NOT EDIT. This file was generated by "github.com/frk/gosql".
package testdata
import (
"github.com/frk/gosql"
"github.com/frk/gosql/internal/testdata/common"
)
func (q *UpdateFilterResultSliceQuery) Exec(c gosql.Conn) error {
var queryString = `UPDATE "test_user" AS u SET (
"email"
, "full_name"
, "is_active"
, "created_at"
, "updated_at"
) = (
$1
, $2
, $3
, $4
, $5
)` // `
filterString, params := q.Filter.ToSQL(5)
queryString += filterString
queryString += ` RETURNING
u."id"
, u."email"
, u."full_name"
, u."is_active"
, u."created_at"
, u."updated_at"` // `
params = append([]interface{}{
q.User.Email,
q.User.FullName,
q.User.IsActive,
q.User.CreatedAt,
q.User.UpdatedAt,
}, params...)
rows, err := c.Query(queryString, params...)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
v := new(common.User4)
err := rows.Scan(
&v.Id,
&v.Email,
&v.FullName,
&v.IsActive,
&v.CreatedAt,
&v.UpdatedAt,
)
if err != nil {
return err
}
q.Result = append(q.Result, v)
}
return rows.Err()
}
|
package services
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/labstack/echo"
log "github.com/sirupsen/logrus"
"github.com/Juniper/contrail/pkg/common"
"github.com/Juniper/contrail/pkg/models"
)
type metadataGetter interface {
GetMetaData(ctx context.Context, uuid string, fqName []string) (*models.MetaData, error)
}
// nolint
type ContrailService struct {
BaseService
MetadataGetter metadataGetter
TypeValidator *models.TypeValidator
}
// RESTSync handles Sync API request.
func (service *ContrailService) RESTSync(c echo.Context) error {
events := &EventList{}
if err := c.Bind(events); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("invalid JSON format: %v", err))
}
// TODO: Call events.Sort()
responses, err := events.Process(c.Request().Context(), service)
if err != nil {
return common.ToHTTPError(err)
}
return c.JSON(http.StatusOK, responses.Events)
}
// RefOperation is enum type for ref-update operation.
type RefOperation string
// RefOperation values.
const (
RefOperationAdd RefOperation = "ADD"
RefOperationDelete RefOperation = "DELETE"
)
// RefUpdate represents ref-update input data.
type RefUpdate struct {
Operation RefOperation `json:"operation"`
Type string `json:"type"`
UUID string `json:"uuid"`
RefType string `json:"ref-type"`
RefUUID string `json:"ref-uuid"`
RefFQName []string `json:"ref-fq-name"`
Attr json.RawMessage `json:"attr"`
}
func (r *RefUpdate) validate() error {
if r.UUID == "" || r.Type == "" || r.RefType == "" || r.Operation == "" {
return common.ErrorBadRequestf(
"uuid/type/ref-type/operation is null: %s, %s, %s, %s",
r.UUID, r.Type, r.RefType, r.Operation,
)
}
if r.Operation != RefOperationAdd && r.Operation != RefOperationDelete {
return common.ErrorBadRequestf("operation should be ADD or DELETE, was %s", r.Operation)
}
return nil
}
// RESTRefUpdate handles a ref-update request.
func (service *ContrailService) RESTRefUpdate(c echo.Context) error {
var data RefUpdate
if err := c.Bind(&data); err != nil {
log.WithFields(log.Fields{
"err": err,
}).Debug("bind failed on ref-update")
return echo.NewHTTPError(http.StatusBadRequest, "Invalid JSON format")
}
if err := data.validate(); err != nil {
return common.ToHTTPError(err)
}
ctx := c.Request().Context()
if data.RefUUID == "" {
m, err := service.MetadataGetter.GetMetaData(ctx, "", data.RefFQName)
if err != nil {
return common.ToHTTPError(common.ErrorBadRequestf("error resolving ref-uuid using ref-fq-name: %v", err))
}
data.RefUUID = m.UUID
}
e, err := NewEventFromRefUpdate(&data)
if err != nil {
return common.ToHTTPError(common.ErrorBadRequest(err.Error()))
}
if _, err = e.Process(ctx, service); err != nil {
return common.ToHTTPError(err)
}
return c.JSON(http.StatusOK, map[string]interface{}{"uuid": data.UUID})
}
// RefRelax represents ref-relax-for-delete input data.
type RefRelax struct {
UUID string `json:"uuid"`
RefUUID string `json:"ref-uuid"`
}
func (r *RefRelax) validate() error {
if r.UUID == "" || r.RefUUID == "" {
return common.ErrorBadRequestf(
"Bad Request: Both uuid and ref-uuid should be specified: %s, %s", r.UUID, r.RefUUID)
}
return nil
}
// RESTRefRelaxForDelete handles a ref-relax-for-delete request.
func (service *ContrailService) RESTRefRelaxForDelete(c echo.Context) error {
var data RefRelax
if err := c.Bind(&data); err != nil {
log.WithFields(log.Fields{
"err": err,
}).Debug("bind failed on ref-relax-for-delete")
return echo.NewHTTPError(http.StatusBadRequest, "Invalid JSON format")
}
if err := data.validate(); err != nil {
return common.ToHTTPError(err)
}
// TODO (Kamil): implement ref-relax logic
return c.JSON(http.StatusOK, map[string]interface{}{"uuid": data.UUID})
}
|
// The hcledit tool provides a CRUD interface to attributes within a Terraform
// file.
package main
import (
"fmt"
"os"
"go.mercari.io/hcledit/cmd/hcledit/internal/command"
)
func main() {
cmd := command.NewCmdRoot()
if err := cmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
|
package x
// GENERATED BY XO. DO NOT EDIT.
import (
"errors"
"strings"
//"time"
"strconv"
"github.com/jmoiron/sqlx"
)
// (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// Sms represents a row from 'sun.sms'.
// Manualy copy this to project
type Sms__ struct {
Id int `json:"Id"` // Id -
Hash string `json:"Hash"` // Hash -
AppUuid string `json:"AppUuid"` // AppUuid -
ClientPhone string `json:"ClientPhone"` // ClientPhone -
GenratedCode int `json:"GenratedCode"` // GenratedCode -
SmsSenderNumber string `json:"SmsSenderNumber"` // SmsSenderNumber -
SmsSendStatues string `json:"SmsSendStatues"` // SmsSendStatues -
SmsHttpBody string `json:"SmsHttpBody"` // SmsHttpBody -
Err string `json:"Err"` // Err -
Carrier string `json:"Carrier"` // Carrier -
Country []byte `json:"Country"` // Country -
IsValidPhone int `json:"IsValidPhone"` // IsValidPhone -
IsConfirmed int `json:"IsConfirmed"` // IsConfirmed -
IsLogin int `json:"IsLogin"` // IsLogin -
IsRegister int `json:"IsRegister"` // IsRegister -
RetriedCount int `json:"RetriedCount"` // RetriedCount -
TTL int `json:"TTL"` // TTL -
// xo fields
_exists, _deleted bool
}
// Exists determines if the Sms exists in the database.
func (s *Sms) Exists() bool {
return s._exists
}
// Deleted provides information if the Sms has been deleted from the database.
func (s *Sms) Deleted() bool {
return s._deleted
}
// Insert inserts the Sms to the database.
func (s *Sms) Insert(db XODB) error {
var err error
// if already exist, bail
if s._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key provided by autoincrement
const sqlstr = `INSERT INTO sun.sms (` +
`Hash, AppUuid, ClientPhone, GenratedCode, SmsSenderNumber, SmsSendStatues, SmsHttpBody, Err, Carrier, Country, IsValidPhone, IsConfirmed, IsLogin, IsRegister, RetriedCount, TTL` +
`) VALUES (` +
`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +
`)`
// run query
if LogTableSqlReq.Sms {
XOLog(sqlstr, s.Hash, s.AppUuid, s.ClientPhone, s.GenratedCode, s.SmsSenderNumber, s.SmsSendStatues, s.SmsHttpBody, s.Err, s.Carrier, s.Country, s.IsValidPhone, s.IsConfirmed, s.IsLogin, s.IsRegister, s.RetriedCount, s.TTL)
}
res, err := db.Exec(sqlstr, s.Hash, s.AppUuid, s.ClientPhone, s.GenratedCode, s.SmsSenderNumber, s.SmsSendStatues, s.SmsHttpBody, s.Err, s.Carrier, s.Country, s.IsValidPhone, s.IsConfirmed, s.IsLogin, s.IsRegister, s.RetriedCount, s.TTL)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return err
}
// set primary key and existence
s.Id = int(id)
s._exists = true
OnSms_AfterInsert(s)
return nil
}
// Insert inserts the Sms to the database.
func (s *Sms) Replace(db XODB) error {
var err error
// sql query
const sqlstr = `REPLACE INTO sun.sms (` +
`Hash, AppUuid, ClientPhone, GenratedCode, SmsSenderNumber, SmsSendStatues, SmsHttpBody, Err, Carrier, Country, IsValidPhone, IsConfirmed, IsLogin, IsRegister, RetriedCount, TTL` +
`) VALUES (` +
`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +
`)`
// run query
if LogTableSqlReq.Sms {
XOLog(sqlstr, s.Hash, s.AppUuid, s.ClientPhone, s.GenratedCode, s.SmsSenderNumber, s.SmsSendStatues, s.SmsHttpBody, s.Err, s.Carrier, s.Country, s.IsValidPhone, s.IsConfirmed, s.IsLogin, s.IsRegister, s.RetriedCount, s.TTL)
}
res, err := db.Exec(sqlstr, s.Hash, s.AppUuid, s.ClientPhone, s.GenratedCode, s.SmsSenderNumber, s.SmsSendStatues, s.SmsHttpBody, s.Err, s.Carrier, s.Country, s.IsValidPhone, s.IsConfirmed, s.IsLogin, s.IsRegister, s.RetriedCount, s.TTL)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return err
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return err
}
// set primary key and existence
s.Id = int(id)
s._exists = true
OnSms_AfterInsert(s)
return nil
}
// Update updates the Sms in the database.
func (s *Sms) Update(db XODB) error {
var err error
// if doesn't exist, bail
if !s._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if s._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE sun.sms SET ` +
`Hash = ?, AppUuid = ?, ClientPhone = ?, GenratedCode = ?, SmsSenderNumber = ?, SmsSendStatues = ?, SmsHttpBody = ?, Err = ?, Carrier = ?, Country = ?, IsValidPhone = ?, IsConfirmed = ?, IsLogin = ?, IsRegister = ?, RetriedCount = ?, TTL = ?` +
` WHERE Id = ?`
// run query
if LogTableSqlReq.Sms {
XOLog(sqlstr, s.Hash, s.AppUuid, s.ClientPhone, s.GenratedCode, s.SmsSenderNumber, s.SmsSendStatues, s.SmsHttpBody, s.Err, s.Carrier, s.Country, s.IsValidPhone, s.IsConfirmed, s.IsLogin, s.IsRegister, s.RetriedCount, s.TTL, s.Id)
}
_, err = db.Exec(sqlstr, s.Hash, s.AppUuid, s.ClientPhone, s.GenratedCode, s.SmsSenderNumber, s.SmsSendStatues, s.SmsHttpBody, s.Err, s.Carrier, s.Country, s.IsValidPhone, s.IsConfirmed, s.IsLogin, s.IsRegister, s.RetriedCount, s.TTL, s.Id)
if LogTableSqlReq.Sms {
XOLogErr(err)
}
OnSms_AfterUpdate(s)
return err
}
// Save saves the Sms to the database.
func (s *Sms) Save(db XODB) error {
if s.Exists() {
return s.Update(db)
}
return s.Replace(db)
}
// Delete deletes the Sms from the database.
func (s *Sms) Delete(db XODB) error {
var err error
// if doesn't exist, bail
if !s._exists {
return nil
}
// if deleted, bail
if s._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM sun.sms WHERE Id = ?`
// run query
if LogTableSqlReq.Sms {
XOLog(sqlstr, s.Id)
}
_, err = db.Exec(sqlstr, s.Id)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return err
}
// set deleted
s._deleted = true
OnSms_AfterDelete(s)
return nil
}
////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// Querify gen - ME /////////////////////////////////////////
//.TableNameGo= table name
// _Deleter, _Updater
// orma types
type __Sms_Deleter struct {
wheres []whereClause
whereSep string
dollarIndex int
isMysql bool
}
type __Sms_Updater struct {
wheres []whereClause
// updates map[string]interface{}
updates []updateCol
whereSep string
dollarIndex int
isMysql bool
}
type __Sms_Selector struct {
wheres []whereClause
selectCol string
whereSep string
orderBy string //" order by id desc //for ints
limit int
offset int
dollarIndex int
isMysql bool
}
func NewSms_Deleter() *__Sms_Deleter {
d := __Sms_Deleter{whereSep: " AND ", isMysql: true}
return &d
}
func NewSms_Updater() *__Sms_Updater {
u := __Sms_Updater{whereSep: " AND ", isMysql: true}
//u.updates = make(map[string]interface{},10)
return &u
}
func NewSms_Selector() *__Sms_Selector {
u := __Sms_Selector{whereSep: " AND ", selectCol: "*", isMysql: true}
return &u
}
/*/// mysql or cockroach ? or $1 handlers
func (m *__Sms_Selector)nextDollars(size int) string {
r := DollarsForSqlIn(size,m.dollarIndex,m.isMysql)
m.dollarIndex += size
return r
}
func (m *__Sms_Selector)nextDollar() string {
r := DollarsForSqlIn(1,m.dollarIndex,m.isMysql)
m.dollarIndex += 1
return r
}
*/
/////////////////////////////// Where for all /////////////////////////////
//// for ints all selector updater, deleter
/// mysql or cockroach ? or $1 handlers
func (m *__Sms_Deleter) nextDollars(size int) string {
r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql)
m.dollarIndex += size
return r
}
func (m *__Sms_Deleter) nextDollar() string {
r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql)
m.dollarIndex += 1
return r
}
////////ints
func (u *__Sms_Deleter) Or() *__Sms_Deleter {
u.whereSep = " OR "
return u
}
func (u *__Sms_Deleter) Id_In(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Id IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) Id_Ins(ins ...int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Id IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) Id_NotIn(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Id NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) Id_Eq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) Id_NotEq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) Id_LT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) Id_LE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) Id_GT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) Id_GE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) GenratedCode_In(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " GenratedCode IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) GenratedCode_Ins(ins ...int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " GenratedCode IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) GenratedCode_NotIn(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " GenratedCode NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) GenratedCode_Eq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) GenratedCode_NotEq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) GenratedCode_LT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) GenratedCode_LE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) GenratedCode_GT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) GenratedCode_GE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) IsValidPhone_In(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsValidPhone IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) IsValidPhone_Ins(ins ...int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsValidPhone IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) IsValidPhone_NotIn(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsValidPhone NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) IsValidPhone_Eq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsValidPhone_NotEq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsValidPhone_LT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsValidPhone_LE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsValidPhone_GT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsValidPhone_GE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) IsConfirmed_In(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsConfirmed IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) IsConfirmed_Ins(ins ...int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsConfirmed IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) IsConfirmed_NotIn(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsConfirmed NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) IsConfirmed_Eq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsConfirmed_NotEq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsConfirmed_LT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsConfirmed_LE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsConfirmed_GT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsConfirmed_GE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) IsLogin_In(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsLogin IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) IsLogin_Ins(ins ...int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsLogin IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) IsLogin_NotIn(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsLogin NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) IsLogin_Eq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsLogin_NotEq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsLogin_LT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsLogin_LE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsLogin_GT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsLogin_GE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) IsRegister_In(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsRegister IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) IsRegister_Ins(ins ...int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsRegister IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) IsRegister_NotIn(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsRegister NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) IsRegister_Eq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsRegister_NotEq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsRegister_LT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsRegister_LE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsRegister_GT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) IsRegister_GE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) RetriedCount_In(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " RetriedCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) RetriedCount_Ins(ins ...int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " RetriedCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) RetriedCount_NotIn(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " RetriedCount NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) RetriedCount_Eq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) RetriedCount_NotEq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) RetriedCount_LT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) RetriedCount_LE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) RetriedCount_GT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) RetriedCount_GE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) TTL_In(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " TTL IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) TTL_Ins(ins ...int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " TTL IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) TTL_NotIn(ins []int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " TTL NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) TTL_Eq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) TTL_NotEq(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) TTL_LT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) TTL_LE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) TTL_GT(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) TTL_GE(val int) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
/// mysql or cockroach ? or $1 handlers
func (m *__Sms_Updater) nextDollars(size int) string {
r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql)
m.dollarIndex += size
return r
}
func (m *__Sms_Updater) nextDollar() string {
r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql)
m.dollarIndex += 1
return r
}
////////ints
func (u *__Sms_Updater) Or() *__Sms_Updater {
u.whereSep = " OR "
return u
}
func (u *__Sms_Updater) Id_In(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Id IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) Id_Ins(ins ...int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Id IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) Id_NotIn(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Id NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) Id_Eq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) Id_NotEq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) Id_LT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) Id_LE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) Id_GT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) Id_GE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) GenratedCode_In(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " GenratedCode IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) GenratedCode_Ins(ins ...int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " GenratedCode IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) GenratedCode_NotIn(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " GenratedCode NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) GenratedCode_Eq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) GenratedCode_NotEq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) GenratedCode_LT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) GenratedCode_LE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) GenratedCode_GT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) GenratedCode_GE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) IsValidPhone_In(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsValidPhone IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) IsValidPhone_Ins(ins ...int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsValidPhone IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) IsValidPhone_NotIn(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsValidPhone NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) IsValidPhone_Eq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsValidPhone_NotEq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsValidPhone_LT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsValidPhone_LE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsValidPhone_GT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsValidPhone_GE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) IsConfirmed_In(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsConfirmed IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) IsConfirmed_Ins(ins ...int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsConfirmed IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) IsConfirmed_NotIn(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsConfirmed NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) IsConfirmed_Eq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsConfirmed_NotEq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsConfirmed_LT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsConfirmed_LE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsConfirmed_GT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsConfirmed_GE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) IsLogin_In(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsLogin IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) IsLogin_Ins(ins ...int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsLogin IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) IsLogin_NotIn(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsLogin NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) IsLogin_Eq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsLogin_NotEq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsLogin_LT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsLogin_LE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsLogin_GT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsLogin_GE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) IsRegister_In(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsRegister IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) IsRegister_Ins(ins ...int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsRegister IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) IsRegister_NotIn(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsRegister NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) IsRegister_Eq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsRegister_NotEq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsRegister_LT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsRegister_LE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsRegister_GT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) IsRegister_GE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) RetriedCount_In(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " RetriedCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) RetriedCount_Ins(ins ...int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " RetriedCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) RetriedCount_NotIn(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " RetriedCount NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) RetriedCount_Eq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) RetriedCount_NotEq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) RetriedCount_LT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) RetriedCount_LE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) RetriedCount_GT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) RetriedCount_GE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) TTL_In(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " TTL IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) TTL_Ins(ins ...int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " TTL IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) TTL_NotIn(ins []int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " TTL NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) TTL_Eq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) TTL_NotEq(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) TTL_LT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) TTL_LE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) TTL_GT(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) TTL_GE(val int) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
/// mysql or cockroach ? or $1 handlers
func (m *__Sms_Selector) nextDollars(size int) string {
r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql)
m.dollarIndex += size
return r
}
func (m *__Sms_Selector) nextDollar() string {
r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql)
m.dollarIndex += 1
return r
}
////////ints
func (u *__Sms_Selector) Or() *__Sms_Selector {
u.whereSep = " OR "
return u
}
func (u *__Sms_Selector) Id_In(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Id IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) Id_Ins(ins ...int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Id IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) Id_NotIn(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Id NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) Id_Eq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) Id_NotEq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) Id_LT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) Id_LE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) Id_GT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) Id_GE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Id >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) GenratedCode_In(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " GenratedCode IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) GenratedCode_Ins(ins ...int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " GenratedCode IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) GenratedCode_NotIn(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " GenratedCode NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) GenratedCode_Eq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) GenratedCode_NotEq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) GenratedCode_LT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) GenratedCode_LE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) GenratedCode_GT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) GenratedCode_GE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " GenratedCode >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) IsValidPhone_In(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsValidPhone IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) IsValidPhone_Ins(ins ...int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsValidPhone IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) IsValidPhone_NotIn(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsValidPhone NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) IsValidPhone_Eq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsValidPhone_NotEq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsValidPhone_LT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsValidPhone_LE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsValidPhone_GT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsValidPhone_GE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsValidPhone >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) IsConfirmed_In(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsConfirmed IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) IsConfirmed_Ins(ins ...int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsConfirmed IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) IsConfirmed_NotIn(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsConfirmed NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) IsConfirmed_Eq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsConfirmed_NotEq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsConfirmed_LT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsConfirmed_LE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsConfirmed_GT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsConfirmed_GE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsConfirmed >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) IsLogin_In(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsLogin IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) IsLogin_Ins(ins ...int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsLogin IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) IsLogin_NotIn(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsLogin NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) IsLogin_Eq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsLogin_NotEq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsLogin_LT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsLogin_LE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsLogin_GT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsLogin_GE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsLogin >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) IsRegister_In(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsRegister IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) IsRegister_Ins(ins ...int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsRegister IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) IsRegister_NotIn(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " IsRegister NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) IsRegister_Eq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsRegister_NotEq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsRegister_LT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsRegister_LE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsRegister_GT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) IsRegister_GE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " IsRegister >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) RetriedCount_In(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " RetriedCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) RetriedCount_Ins(ins ...int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " RetriedCount IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) RetriedCount_NotIn(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " RetriedCount NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) RetriedCount_Eq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) RetriedCount_NotEq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) RetriedCount_LT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) RetriedCount_LE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) RetriedCount_GT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) RetriedCount_GE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " RetriedCount >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) TTL_In(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " TTL IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) TTL_Ins(ins ...int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " TTL IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) TTL_NotIn(ins []int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " TTL NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) TTL_Eq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) TTL_NotEq(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) TTL_LT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) TTL_LE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) TTL_GT(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) TTL_GE(val int) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " TTL >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
///// for strings //copy of above with type int -> string + rm if eq + $ms_str_cond
////////ints
func (u *__Sms_Deleter) Hash_In(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) Hash_NotIn(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Hash NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Deleter) Hash_Like(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Hash LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) Hash_Eq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Hash = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) Hash_NotEq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Hash != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) AppUuid_In(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AppUuid IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) AppUuid_NotIn(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AppUuid NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Deleter) AppUuid_Like(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AppUuid LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) AppUuid_Eq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AppUuid = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) AppUuid_NotEq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AppUuid != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) ClientPhone_In(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ClientPhone IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) ClientPhone_NotIn(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ClientPhone NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Deleter) ClientPhone_Like(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ClientPhone LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) ClientPhone_Eq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ClientPhone = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) ClientPhone_NotEq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ClientPhone != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) SmsSenderNumber_In(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSenderNumber IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) SmsSenderNumber_NotIn(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSenderNumber NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Deleter) SmsSenderNumber_Like(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSenderNumber LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) SmsSenderNumber_Eq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSenderNumber = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) SmsSenderNumber_NotEq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSenderNumber != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) SmsSendStatues_In(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSendStatues IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) SmsSendStatues_NotIn(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSendStatues NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Deleter) SmsSendStatues_Like(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSendStatues LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) SmsSendStatues_Eq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSendStatues = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) SmsSendStatues_NotEq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSendStatues != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) SmsHttpBody_In(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsHttpBody IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) SmsHttpBody_NotIn(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsHttpBody NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Deleter) SmsHttpBody_Like(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsHttpBody LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) SmsHttpBody_Eq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsHttpBody = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) SmsHttpBody_NotEq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsHttpBody != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) Err_In(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Err IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) Err_NotIn(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Err NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Deleter) Err_Like(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Err LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) Err_Eq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Err = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) Err_NotEq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Err != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Deleter) Carrier_In(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Carrier IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Deleter) Carrier_NotIn(ins []string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Carrier NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Deleter) Carrier_Like(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Carrier LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Deleter) Carrier_Eq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Carrier = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Deleter) Carrier_NotEq(val string) *__Sms_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Carrier != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
////////ints
func (u *__Sms_Updater) Hash_In(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) Hash_NotIn(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Hash NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Updater) Hash_Like(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Hash LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) Hash_Eq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Hash = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) Hash_NotEq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Hash != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) AppUuid_In(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AppUuid IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) AppUuid_NotIn(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AppUuid NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Updater) AppUuid_Like(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AppUuid LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) AppUuid_Eq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AppUuid = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) AppUuid_NotEq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AppUuid != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) ClientPhone_In(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ClientPhone IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) ClientPhone_NotIn(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ClientPhone NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Updater) ClientPhone_Like(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ClientPhone LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) ClientPhone_Eq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ClientPhone = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) ClientPhone_NotEq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ClientPhone != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) SmsSenderNumber_In(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSenderNumber IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) SmsSenderNumber_NotIn(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSenderNumber NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Updater) SmsSenderNumber_Like(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSenderNumber LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) SmsSenderNumber_Eq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSenderNumber = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) SmsSenderNumber_NotEq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSenderNumber != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) SmsSendStatues_In(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSendStatues IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) SmsSendStatues_NotIn(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSendStatues NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Updater) SmsSendStatues_Like(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSendStatues LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) SmsSendStatues_Eq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSendStatues = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) SmsSendStatues_NotEq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSendStatues != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) SmsHttpBody_In(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsHttpBody IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) SmsHttpBody_NotIn(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsHttpBody NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Updater) SmsHttpBody_Like(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsHttpBody LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) SmsHttpBody_Eq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsHttpBody = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) SmsHttpBody_NotEq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsHttpBody != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) Err_In(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Err IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) Err_NotIn(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Err NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Updater) Err_Like(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Err LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) Err_Eq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Err = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) Err_NotEq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Err != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Updater) Carrier_In(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Carrier IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Updater) Carrier_NotIn(ins []string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Carrier NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Updater) Carrier_Like(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Carrier LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Updater) Carrier_Eq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Carrier = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Updater) Carrier_NotEq(val string) *__Sms_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Carrier != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
////////ints
func (u *__Sms_Selector) Hash_In(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) Hash_NotIn(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Hash NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Selector) Hash_Like(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Hash LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) Hash_Eq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Hash = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) Hash_NotEq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Hash != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) AppUuid_In(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AppUuid IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) AppUuid_NotIn(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " AppUuid NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Selector) AppUuid_Like(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AppUuid LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) AppUuid_Eq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AppUuid = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) AppUuid_NotEq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " AppUuid != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) ClientPhone_In(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ClientPhone IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) ClientPhone_NotIn(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ClientPhone NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Selector) ClientPhone_Like(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ClientPhone LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) ClientPhone_Eq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ClientPhone = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) ClientPhone_NotEq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ClientPhone != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) SmsSenderNumber_In(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSenderNumber IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) SmsSenderNumber_NotIn(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSenderNumber NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Selector) SmsSenderNumber_Like(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSenderNumber LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) SmsSenderNumber_Eq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSenderNumber = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) SmsSenderNumber_NotEq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSenderNumber != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) SmsSendStatues_In(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSendStatues IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) SmsSendStatues_NotIn(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsSendStatues NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Selector) SmsSendStatues_Like(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSendStatues LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) SmsSendStatues_Eq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSendStatues = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) SmsSendStatues_NotEq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsSendStatues != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) SmsHttpBody_In(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsHttpBody IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) SmsHttpBody_NotIn(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " SmsHttpBody NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Selector) SmsHttpBody_Like(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsHttpBody LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) SmsHttpBody_Eq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsHttpBody = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) SmsHttpBody_NotEq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " SmsHttpBody != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) Err_In(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Err IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) Err_NotIn(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Err NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Selector) Err_Like(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Err LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) Err_Eq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Err = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) Err_NotEq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Err != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Sms_Selector) Carrier_In(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Carrier IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Sms_Selector) Carrier_NotIn(ins []string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Carrier NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
//must be used like: UserName_like("hamid%")
func (u *__Sms_Selector) Carrier_Like(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Carrier LIKE " + u.nextDollar()
u.wheres = append(u.wheres, w)
return u
}
func (d *__Sms_Selector) Carrier_Eq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Carrier = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Sms_Selector) Carrier_NotEq(val string) *__Sms_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Carrier != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
/// End of wheres for selectors , updators, deletor
/////////////////////////////// Updater /////////////////////////////
//ints
func (u *__Sms_Updater) Id(newVal int) *__Sms_Updater {
up := updateCol{" Id = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Id = " + u.nextDollar()] = newVal
return u
}
func (u *__Sms_Updater) Id_Increment(count int) *__Sms_Updater {
if count > 0 {
up := updateCol{" Id = Id+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" Id = Id+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" Id = Id- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" Id = Id- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
//string
func (u *__Sms_Updater) Hash(newVal string) *__Sms_Updater {
up := updateCol{"Hash = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Hash = "+ u.nextDollar()] = newVal
return u
}
//ints
//string
func (u *__Sms_Updater) AppUuid(newVal string) *__Sms_Updater {
up := updateCol{"AppUuid = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" AppUuid = "+ u.nextDollar()] = newVal
return u
}
//ints
//string
func (u *__Sms_Updater) ClientPhone(newVal string) *__Sms_Updater {
up := updateCol{"ClientPhone = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" ClientPhone = "+ u.nextDollar()] = newVal
return u
}
//ints
func (u *__Sms_Updater) GenratedCode(newVal int) *__Sms_Updater {
up := updateCol{" GenratedCode = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" GenratedCode = " + u.nextDollar()] = newVal
return u
}
func (u *__Sms_Updater) GenratedCode_Increment(count int) *__Sms_Updater {
if count > 0 {
up := updateCol{" GenratedCode = GenratedCode+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" GenratedCode = GenratedCode+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" GenratedCode = GenratedCode- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" GenratedCode = GenratedCode- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
//string
func (u *__Sms_Updater) SmsSenderNumber(newVal string) *__Sms_Updater {
up := updateCol{"SmsSenderNumber = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" SmsSenderNumber = "+ u.nextDollar()] = newVal
return u
}
//ints
//string
func (u *__Sms_Updater) SmsSendStatues(newVal string) *__Sms_Updater {
up := updateCol{"SmsSendStatues = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" SmsSendStatues = "+ u.nextDollar()] = newVal
return u
}
//ints
//string
func (u *__Sms_Updater) SmsHttpBody(newVal string) *__Sms_Updater {
up := updateCol{"SmsHttpBody = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" SmsHttpBody = "+ u.nextDollar()] = newVal
return u
}
//ints
//string
func (u *__Sms_Updater) Err(newVal string) *__Sms_Updater {
up := updateCol{"Err = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Err = "+ u.nextDollar()] = newVal
return u
}
//ints
//string
func (u *__Sms_Updater) Carrier(newVal string) *__Sms_Updater {
up := updateCol{"Carrier = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Carrier = "+ u.nextDollar()] = newVal
return u
}
//ints
//string
//ints
func (u *__Sms_Updater) IsValidPhone(newVal int) *__Sms_Updater {
up := updateCol{" IsValidPhone = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" IsValidPhone = " + u.nextDollar()] = newVal
return u
}
func (u *__Sms_Updater) IsValidPhone_Increment(count int) *__Sms_Updater {
if count > 0 {
up := updateCol{" IsValidPhone = IsValidPhone+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" IsValidPhone = IsValidPhone+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" IsValidPhone = IsValidPhone- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" IsValidPhone = IsValidPhone- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Sms_Updater) IsConfirmed(newVal int) *__Sms_Updater {
up := updateCol{" IsConfirmed = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" IsConfirmed = " + u.nextDollar()] = newVal
return u
}
func (u *__Sms_Updater) IsConfirmed_Increment(count int) *__Sms_Updater {
if count > 0 {
up := updateCol{" IsConfirmed = IsConfirmed+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" IsConfirmed = IsConfirmed+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" IsConfirmed = IsConfirmed- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" IsConfirmed = IsConfirmed- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Sms_Updater) IsLogin(newVal int) *__Sms_Updater {
up := updateCol{" IsLogin = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" IsLogin = " + u.nextDollar()] = newVal
return u
}
func (u *__Sms_Updater) IsLogin_Increment(count int) *__Sms_Updater {
if count > 0 {
up := updateCol{" IsLogin = IsLogin+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" IsLogin = IsLogin+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" IsLogin = IsLogin- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" IsLogin = IsLogin- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Sms_Updater) IsRegister(newVal int) *__Sms_Updater {
up := updateCol{" IsRegister = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" IsRegister = " + u.nextDollar()] = newVal
return u
}
func (u *__Sms_Updater) IsRegister_Increment(count int) *__Sms_Updater {
if count > 0 {
up := updateCol{" IsRegister = IsRegister+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" IsRegister = IsRegister+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" IsRegister = IsRegister- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" IsRegister = IsRegister- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Sms_Updater) RetriedCount(newVal int) *__Sms_Updater {
up := updateCol{" RetriedCount = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" RetriedCount = " + u.nextDollar()] = newVal
return u
}
func (u *__Sms_Updater) RetriedCount_Increment(count int) *__Sms_Updater {
if count > 0 {
up := updateCol{" RetriedCount = RetriedCount+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" RetriedCount = RetriedCount+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" RetriedCount = RetriedCount- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" RetriedCount = RetriedCount- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Sms_Updater) TTL(newVal int) *__Sms_Updater {
up := updateCol{" TTL = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" TTL = " + u.nextDollar()] = newVal
return u
}
func (u *__Sms_Updater) TTL_Increment(count int) *__Sms_Updater {
if count > 0 {
up := updateCol{" TTL = TTL+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" TTL = TTL+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" TTL = TTL- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" TTL = TTL- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
/////////////////////////////////////////////////////////////////////
/////////////////////// Selector ///////////////////////////////////
//Select_* can just be used with: .GetString() , .GetStringSlice(), .GetInt() ..GetIntSlice()
func (u *__Sms_Selector) OrderBy_Id_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY Id DESC "
return u
}
func (u *__Sms_Selector) OrderBy_Id_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY Id ASC "
return u
}
func (u *__Sms_Selector) Select_Id() *__Sms_Selector {
u.selectCol = "Id"
return u
}
func (u *__Sms_Selector) OrderBy_Hash_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY Hash DESC "
return u
}
func (u *__Sms_Selector) OrderBy_Hash_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY Hash ASC "
return u
}
func (u *__Sms_Selector) Select_Hash() *__Sms_Selector {
u.selectCol = "Hash"
return u
}
func (u *__Sms_Selector) OrderBy_AppUuid_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY AppUuid DESC "
return u
}
func (u *__Sms_Selector) OrderBy_AppUuid_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY AppUuid ASC "
return u
}
func (u *__Sms_Selector) Select_AppUuid() *__Sms_Selector {
u.selectCol = "AppUuid"
return u
}
func (u *__Sms_Selector) OrderBy_ClientPhone_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY ClientPhone DESC "
return u
}
func (u *__Sms_Selector) OrderBy_ClientPhone_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY ClientPhone ASC "
return u
}
func (u *__Sms_Selector) Select_ClientPhone() *__Sms_Selector {
u.selectCol = "ClientPhone"
return u
}
func (u *__Sms_Selector) OrderBy_GenratedCode_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY GenratedCode DESC "
return u
}
func (u *__Sms_Selector) OrderBy_GenratedCode_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY GenratedCode ASC "
return u
}
func (u *__Sms_Selector) Select_GenratedCode() *__Sms_Selector {
u.selectCol = "GenratedCode"
return u
}
func (u *__Sms_Selector) OrderBy_SmsSenderNumber_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY SmsSenderNumber DESC "
return u
}
func (u *__Sms_Selector) OrderBy_SmsSenderNumber_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY SmsSenderNumber ASC "
return u
}
func (u *__Sms_Selector) Select_SmsSenderNumber() *__Sms_Selector {
u.selectCol = "SmsSenderNumber"
return u
}
func (u *__Sms_Selector) OrderBy_SmsSendStatues_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY SmsSendStatues DESC "
return u
}
func (u *__Sms_Selector) OrderBy_SmsSendStatues_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY SmsSendStatues ASC "
return u
}
func (u *__Sms_Selector) Select_SmsSendStatues() *__Sms_Selector {
u.selectCol = "SmsSendStatues"
return u
}
func (u *__Sms_Selector) OrderBy_SmsHttpBody_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY SmsHttpBody DESC "
return u
}
func (u *__Sms_Selector) OrderBy_SmsHttpBody_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY SmsHttpBody ASC "
return u
}
func (u *__Sms_Selector) Select_SmsHttpBody() *__Sms_Selector {
u.selectCol = "SmsHttpBody"
return u
}
func (u *__Sms_Selector) OrderBy_Err_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY Err DESC "
return u
}
func (u *__Sms_Selector) OrderBy_Err_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY Err ASC "
return u
}
func (u *__Sms_Selector) Select_Err() *__Sms_Selector {
u.selectCol = "Err"
return u
}
func (u *__Sms_Selector) OrderBy_Carrier_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY Carrier DESC "
return u
}
func (u *__Sms_Selector) OrderBy_Carrier_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY Carrier ASC "
return u
}
func (u *__Sms_Selector) Select_Carrier() *__Sms_Selector {
u.selectCol = "Carrier"
return u
}
func (u *__Sms_Selector) OrderBy_Country_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY Country DESC "
return u
}
func (u *__Sms_Selector) OrderBy_Country_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY Country ASC "
return u
}
func (u *__Sms_Selector) Select_Country() *__Sms_Selector {
u.selectCol = "Country"
return u
}
func (u *__Sms_Selector) OrderBy_IsValidPhone_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY IsValidPhone DESC "
return u
}
func (u *__Sms_Selector) OrderBy_IsValidPhone_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY IsValidPhone ASC "
return u
}
func (u *__Sms_Selector) Select_IsValidPhone() *__Sms_Selector {
u.selectCol = "IsValidPhone"
return u
}
func (u *__Sms_Selector) OrderBy_IsConfirmed_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY IsConfirmed DESC "
return u
}
func (u *__Sms_Selector) OrderBy_IsConfirmed_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY IsConfirmed ASC "
return u
}
func (u *__Sms_Selector) Select_IsConfirmed() *__Sms_Selector {
u.selectCol = "IsConfirmed"
return u
}
func (u *__Sms_Selector) OrderBy_IsLogin_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY IsLogin DESC "
return u
}
func (u *__Sms_Selector) OrderBy_IsLogin_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY IsLogin ASC "
return u
}
func (u *__Sms_Selector) Select_IsLogin() *__Sms_Selector {
u.selectCol = "IsLogin"
return u
}
func (u *__Sms_Selector) OrderBy_IsRegister_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY IsRegister DESC "
return u
}
func (u *__Sms_Selector) OrderBy_IsRegister_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY IsRegister ASC "
return u
}
func (u *__Sms_Selector) Select_IsRegister() *__Sms_Selector {
u.selectCol = "IsRegister"
return u
}
func (u *__Sms_Selector) OrderBy_RetriedCount_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY RetriedCount DESC "
return u
}
func (u *__Sms_Selector) OrderBy_RetriedCount_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY RetriedCount ASC "
return u
}
func (u *__Sms_Selector) Select_RetriedCount() *__Sms_Selector {
u.selectCol = "RetriedCount"
return u
}
func (u *__Sms_Selector) OrderBy_TTL_Desc() *__Sms_Selector {
u.orderBy = " ORDER BY TTL DESC "
return u
}
func (u *__Sms_Selector) OrderBy_TTL_Asc() *__Sms_Selector {
u.orderBy = " ORDER BY TTL ASC "
return u
}
func (u *__Sms_Selector) Select_TTL() *__Sms_Selector {
u.selectCol = "TTL"
return u
}
func (u *__Sms_Selector) Limit(num int) *__Sms_Selector {
u.limit = num
return u
}
func (u *__Sms_Selector) Offset(num int) *__Sms_Selector {
u.offset = num
return u
}
func (u *__Sms_Selector) Order_Rand() *__Sms_Selector {
u.orderBy = " ORDER BY RAND() "
return u
}
///////////////////////// Queryer Selector //////////////////////////////////
func (u *__Sms_Selector) _stoSql() (string, []interface{}) {
sqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep)
sqlstr := "SELECT " + u.selectCol + " FROM sun.sms"
if len(strings.Trim(sqlWherrs, " ")) > 0 { //2 for safty
sqlstr += " WHERE " + sqlWherrs
}
if u.orderBy != "" {
sqlstr += u.orderBy
}
if u.limit != 0 {
sqlstr += " LIMIT " + strconv.Itoa(u.limit)
}
if u.offset != 0 {
sqlstr += " OFFSET " + strconv.Itoa(u.offset)
}
return sqlstr, whereArgs
}
func (u *__Sms_Selector) GetRow(db *sqlx.DB) (*Sms, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Sms {
XOLog(sqlstr, whereArgs)
}
row := &Sms{}
//by Sqlx
err = db.Get(row, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return nil, err
}
row._exists = true
OnSms_LoadOne(row)
return row, nil
}
func (u *__Sms_Selector) GetRows(db *sqlx.DB) ([]*Sms, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Sms {
XOLog(sqlstr, whereArgs)
}
var rows []*Sms
//by Sqlx
err = db.Unsafe().Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return nil, err
}
/*for i:=0;i< len(rows);i++ {
rows[i]._exists = true
}*/
for i := 0; i < len(rows); i++ {
rows[i]._exists = true
}
OnSms_LoadMany(rows)
return rows, nil
}
//dep use GetRows()
func (u *__Sms_Selector) GetRows2(db *sqlx.DB) ([]Sms, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Sms {
XOLog(sqlstr, whereArgs)
}
var rows []*Sms
//by Sqlx
err = db.Unsafe().Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return nil, err
}
/*for i:=0;i< len(rows);i++ {
rows[i]._exists = true
}*/
for i := 0; i < len(rows); i++ {
rows[i]._exists = true
}
OnSms_LoadMany(rows)
rows2 := make([]Sms, len(rows))
for i := 0; i < len(rows); i++ {
cp := *rows[i]
rows2[i] = cp
}
return rows2, nil
}
func (u *__Sms_Selector) GetString(db *sqlx.DB) (string, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Sms {
XOLog(sqlstr, whereArgs)
}
var res string
//by Sqlx
err = db.Get(&res, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return "", err
}
return res, nil
}
func (u *__Sms_Selector) GetStringSlice(db *sqlx.DB) ([]string, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Sms {
XOLog(sqlstr, whereArgs)
}
var rows []string
//by Sqlx
err = db.Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return nil, err
}
return rows, nil
}
func (u *__Sms_Selector) GetIntSlice(db *sqlx.DB) ([]int, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Sms {
XOLog(sqlstr, whereArgs)
}
var rows []int
//by Sqlx
err = db.Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return nil, err
}
return rows, nil
}
func (u *__Sms_Selector) GetInt(db *sqlx.DB) (int, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Sms {
XOLog(sqlstr, whereArgs)
}
var res int
//by Sqlx
err = db.Get(&res, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return 0, err
}
return res, nil
}
///////////////////////// Queryer Update Delete //////////////////////////////////
func (u *__Sms_Updater) Update(db XODB) (int, error) {
var err error
var updateArgs []interface{}
var sqlUpdateArr []string
/*for up, newVal := range u.updates {
sqlUpdateArr = append(sqlUpdateArr, up)
updateArgs = append(updateArgs, newVal)
}*/
for _, up := range u.updates {
sqlUpdateArr = append(sqlUpdateArr, up.col)
updateArgs = append(updateArgs, up.val)
}
sqlUpdate := strings.Join(sqlUpdateArr, ",")
sqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep)
var allArgs []interface{}
allArgs = append(allArgs, updateArgs...)
allArgs = append(allArgs, whereArgs...)
sqlstr := `UPDATE sun.sms SET ` + sqlUpdate
if len(strings.Trim(sqlWherrs, " ")) > 0 { //2 for safty
sqlstr += " WHERE " + sqlWherrs
}
if LogTableSqlReq.Sms {
XOLog(sqlstr, allArgs)
}
res, err := db.Exec(sqlstr, allArgs...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return 0, err
}
num, err := res.RowsAffected()
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return 0, err
}
return int(num), nil
}
func (d *__Sms_Deleter) Delete(db XODB) (int, error) {
var err error
var wheresArr []string
for _, w := range d.wheres {
wheresArr = append(wheresArr, w.condition)
}
wheresStr := strings.Join(wheresArr, d.whereSep)
var args []interface{}
for _, w := range d.wheres {
args = append(args, w.args...)
}
sqlstr := "DELETE FROM sun.sms WHERE " + wheresStr
// run query
if LogTableSqlReq.Sms {
XOLog(sqlstr, args)
}
res, err := db.Exec(sqlstr, args...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return 0, err
}
// retrieve id
num, err := res.RowsAffected()
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return 0, err
}
return int(num), nil
}
///////////////////////// Mass insert - replace for Sms ////////////////
func MassInsert_Sms(rows []Sms, db XODB) error {
if len(rows) == 0 {
return errors.New("rows slice should not be empty - inserted nothing")
}
var err error
ln := len(rows)
s := "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)," //`(?, ?, ?, ?),`
insVals_ := strings.Repeat(s, ln)
insVals := insVals_[0 : len(insVals_)-1]
// sql query
sqlstr := "INSERT INTO sun.sms (" +
"Hash, AppUuid, ClientPhone, GenratedCode, SmsSenderNumber, SmsSendStatues, SmsHttpBody, Err, Carrier, Country, IsValidPhone, IsConfirmed, IsLogin, IsRegister, RetriedCount, TTL" +
") VALUES " + insVals
// run query
vals := make([]interface{}, 0, ln*5) //5 fields
for _, row := range rows {
// vals = append(vals,row.UserId)
vals = append(vals, row.Hash)
vals = append(vals, row.AppUuid)
vals = append(vals, row.ClientPhone)
vals = append(vals, row.GenratedCode)
vals = append(vals, row.SmsSenderNumber)
vals = append(vals, row.SmsSendStatues)
vals = append(vals, row.SmsHttpBody)
vals = append(vals, row.Err)
vals = append(vals, row.Carrier)
vals = append(vals, row.Country)
vals = append(vals, row.IsValidPhone)
vals = append(vals, row.IsConfirmed)
vals = append(vals, row.IsLogin)
vals = append(vals, row.IsRegister)
vals = append(vals, row.RetriedCount)
vals = append(vals, row.TTL)
}
if LogTableSqlReq.Sms {
XOLog(sqlstr, " MassInsert len = ", ln, vals)
}
_, err = db.Exec(sqlstr, vals...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return err
}
return nil
}
func MassReplace_Sms(rows []Sms, db XODB) error {
var err error
ln := len(rows)
s := "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)," //`(?, ?, ?, ?),`
insVals_ := strings.Repeat(s, ln)
insVals := insVals_[0 : len(insVals_)-1]
// sql query
sqlstr := "REPLACE INTO sun.sms (" +
"Hash, AppUuid, ClientPhone, GenratedCode, SmsSenderNumber, SmsSendStatues, SmsHttpBody, Err, Carrier, Country, IsValidPhone, IsConfirmed, IsLogin, IsRegister, RetriedCount, TTL" +
") VALUES " + insVals
// run query
vals := make([]interface{}, 0, ln*5) //5 fields
for _, row := range rows {
// vals = append(vals,row.UserId)
vals = append(vals, row.Hash)
vals = append(vals, row.AppUuid)
vals = append(vals, row.ClientPhone)
vals = append(vals, row.GenratedCode)
vals = append(vals, row.SmsSenderNumber)
vals = append(vals, row.SmsSendStatues)
vals = append(vals, row.SmsHttpBody)
vals = append(vals, row.Err)
vals = append(vals, row.Carrier)
vals = append(vals, row.Country)
vals = append(vals, row.IsValidPhone)
vals = append(vals, row.IsConfirmed)
vals = append(vals, row.IsLogin)
vals = append(vals, row.IsRegister)
vals = append(vals, row.RetriedCount)
vals = append(vals, row.TTL)
}
if LogTableSqlReq.Sms {
XOLog(sqlstr, " MassReplace len = ", ln, vals)
}
_, err = db.Exec(sqlstr, vals...)
if err != nil {
if LogTableSqlReq.Sms {
XOLogErr(err)
}
return err
}
return nil
}
//////////////////// Play ///////////////////////////////
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
|
package socketio
// import (
// "fmt"
// "net/http"
// engineio "github.com/googollee/go-engine.io"
// socketio "github.com/googollee/go-socket.io"
// )
// // Transport :
// type Transport struct {
// Port int
// Socket *socketio.Server
// }
// // SocketContext :
// type SocketContext struct {
// Query map[string]interface{} `json:"query"`
// Body map[string]interface{} `json:"body"`
// Header map[string]interface{} `json:"header"`
// Param map[string]string `json:"param"`
// }
// // NewSocket :
// func NewSocket(opts *engineio.Options) *Transport {
// socket, err := socketio.NewServer(opts)
// if err != nil {
// panic(err)
// }
// return &Transport{
// Socket: socket,
// Port: 3000,
// }
// }
// // UsePort :
// func (t *Transport) UsePort(port int) *Transport {
// t.Port = port
// return t
// }
// // RegisterService :
// func (t *Transport) RegisterService(srv string, route service.Route) {
// t.Socket.OnEvent(
// "/", srv+"."+route.Action,
// func(socket socketio.Conn, object string) string {
// return "SERVICE"
// },
// )
// }
// // RegisterEndpoint :
// func (t *Transport) RegisterEndpoint(endpoint string, route endpoint.Route) {
// t.Socket.OnEvent(
// "/", endpoint,
// func(socket socketio.Conn, object string) string {
// return "ENDPOINT"
// },
// )
// }
// // Start :
// func (t *Transport) Start() error {
// defer t.Socket.Close()
// go t.Socket.Serve()
// http.Handle("/socket.io/", t.Socket)
// port := fmt.Sprintf(":%d", t.Port)
// return http.ListenAndServe(port, nil)
// }
|
package main
import (
"bufio"
"crypto/hmac"
"crypto/sha256"
"encoding/base32"
"encoding/json"
"fmt"
"github.com/nu7hatch/gouuid"
"io/ioutil"
"net/http"
"strings"
)
var userTokens = map[string]string{}
var userInfos = map[string]*userInfo{}
var secretKey []byte
var dataStore = &DataStore{}
var client_id string
var client_secret string
var globalSummary = map[string]int{}
var database = NewFilebase("test.db")
var db struct {
bookmarks *Filebase
subscriptions *Filebase
users *Filebase
init bool
}
type clientSecrets struct {
Client_id string
Client_secret string
}
type userInfo struct {
subscriptions *Collection
bookmarks *Collection
summary map[string]int
userid string
name string
}
type userinfoDto struct {
Summary map[string]int
Name string
Userid string
}
type RequestContext struct {
isAuthed bool
userinfo *userInfo
}
func newUserInfo() *userInfo {
bookmarks := newCollection()
added := func(key string, value interface{}) {
bookmark, _ := value.(*Bookmark)
for _, tag := range bookmark.Tags {
globalSummary[tag] += 1
}
}
changed := func(key string, value interface{}, old interface{}) {
addedBooks, _ := value.(*Bookmark)
removedBooks, _ := old.(*Bookmark)
for _, tag := range addedBooks.Tags {
globalSummary[tag] += 1
}
for _, tag := range removedBooks.Tags {
globalSummary[tag] -= 1
}
}
removed := func(key string, value interface{}) {
bookmark, _ := value.(*Bookmark)
for _, tag := range bookmark.Tags {
globalSummary[tag] -= 1
}
}
callback := &Callback{added: added, changed: changed, removed: removed}
bookmarks.ObserveChanges(callback)
return &userInfo{subscriptions: newCollection(), bookmarks: bookmarks, summary: make(map[string]int)}
}
func makeUuid() string {
u, _ := uuid.NewV4()
return u.String()
}
func hashToken(uuid string) string {
mac := hmac.New(sha256.New, secretKey)
mac.Write([]byte(uuid))
b := mac.Sum(nil)
return base32.StdEncoding.EncodeToString(b)
}
func migrateDatabase() {
scanner := bufio.NewScanner(database.Fd)
scanner.Split(bufio.ScanLines)
db.init = true
for scanner.Scan() {
du := &DataUnion{}
b := scanner.Bytes()
err := json.Unmarshal(b, du)
if err != nil {
fmt.Println(err.Error())
fmt.Println("bad json:", string(b))
continue
}
var userinfo *userInfo
var ok bool
userid := du.UserId
if userinfo, ok = userInfos[userid]; !ok {
userinfo = newUserInfo()
userinfo.userid = du.UserId
fmt.Println("regen user", userinfo.userid)
dataStore.AddUser(userinfo, du.Token)
userinfo.subscriptions.Add(userid, userid)
userInfos[userid] = userinfo
}
if du.Bookmark != nil {
dataStore.UpsertBookmark(userinfo, du.Bookmark)
} else if du.Sub != "" {
dataStore.AddSubscription(userinfo, du.Sub, userInfos[du.Sub].name)
} else {
userTokens[du.Token] = du.UserId
userinfo.name = du.Name
}
}
db.init = false
}
func init() {
db.bookmarks = NewFilebase("bookmarks.db")
db.users = NewFilebase("users.db")
db.subscriptions = NewFilebase("subscriptions.db")
var err error
cj, err := ioutil.ReadFile("secret/clientsecrets")
if err != nil {
fmt.Println("error reading clientsecrets")
panic(err.Error())
}
clientsecrets := &clientSecrets{}
err = json.Unmarshal(cj, clientsecrets)
if err != nil {
fmt.Println("error unmarshall clientsecret")
panic(err.Error())
}
client_secret = clientsecrets.Client_secret
client_id = clientsecrets.Client_id
secretKey, err = ioutil.ReadFile("secret/secret.key")
if err != nil {
panic("i need the secret key")
}
//somehow account for trailing newline
if secretKey[len(secretKey)-1] == 10 {
secretKey = secretKey[:len(secretKey)-1]
}
fmt.Println(secretKey)
readuser := func(b []byte) {
du := &DataUnion{}
err := json.Unmarshal(b, du)
if err != nil {
return
}
var userinfo *userInfo
var ok bool
userid := du.UserId
if userinfo, ok = userInfos[userid]; !ok {
userinfo = newUserInfo()
userinfo.userid = du.UserId
userinfo.name = du.Name
dataStore.AddUser(userinfo, du.Token)
}
}
readSubscription := func(b []byte) {
du := &DataUnion{}
err := json.Unmarshal(b, du)
if err != nil {
return
}
userinfo := userInfos[du.UserId]
if du.Op == "add" {
dataStore.AddSubscription(userinfo, du.Sub, userInfos[du.Sub].name)
} else {
dataStore.DeleteSubscription(userinfo, du.Sub)
}
}
readbookmark := func(b []byte) {
du := &DataUnion{}
err := json.Unmarshal(b, du)
if err != nil {
return
}
userinfo := userInfos[du.UserId]
dataStore.UpsertBookmark(userinfo, du.Bookmark)
}
db.users.ReadRecords(readuser)
db.subscriptions.ReadRecords(readSubscription)
db.bookmarks.ReadRecords(readbookmark)
db.init = true
}
func main() {
fmt.Println(hashToken("beaabad2-03ad-4d2d-4486-e891456363d5"))
http.HandleFunc("/api/summary", summaryHandler)
http.HandleFunc("/api/img/", authed(imgHandler))
http.HandleFunc("/ws", authed(websocketHandler))
http.HandleFunc("/api/follow", authed(subscriptionHandler))
http.HandleFunc("/api/bookmarks", authed(bookmarkHandler))
http.HandleFunc("/api/user", userHandler)
http.Handle("/", http.FileServer(http.Dir("static")))
//should only bind to local since were behind nginx
http.ListenAndServe("127.0.0.1:555", nil)
}
func authed(h func(w http.ResponseWriter, r *http.Request, context *RequestContext)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Authorization")
context := &RequestContext{}
auth := r.Header.Get("Authorization")
authParams := strings.Split(auth, ":")
var userid string = ""
var token string = ""
if len(authParams) == 2 {
userid = authParams[0]
token = authParams[1]
} else {
qs := r.URL.Query()
userid = qs.Get("user")
token = qs.Get("token")
}
if userid != "" && token != "" {
fmt.Println("userid", userid, "token", token)
var githubid string
var user *userInfo
var ok bool
if githubid, ok = userTokens[userid]; ok {
tb, _ := base32.StdEncoding.DecodeString(token)
mac := hmac.New(sha256.New, secretKey)
mac.Write([]byte(userid))
expected := mac.Sum(nil)
if hmac.Equal(expected, tb) {
if user, ok = userInfos[githubid]; ok {
context.isAuthed = true
context.userinfo = user
context.userinfo.userid = githubid
fmt.Println("user authed as: ", githubid)
}
}
}
}
h(w, r, context)
}
}
|
package crawler
type Interface interface {
Scan(string, int) ([]Document, error)
}
type Document struct {
ID uint64
Title string
URL string
}
func (d Document) Ident() uint64 {
return d.ID
}
|
package repository
import (
"context"
"time"
"todo-go/config"
"todo-go/model"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
type Noter interface {
ListNote() ([]model.Note, error)
AddNote(note model.Note) (interface{}, error)
DeleteNote(id string) error
UpdateNote(id string, note model.Note) error
}
type NoteRepository struct {
ConnectionDB *mongo.Client
}
const collectionName = "note"
func (noteRepo *NoteRepository) AddNote(note model.Note) (interface{}, error) {
note.UpdateTime = time.Now()
id, err := noteRepo.ConnectionDB.Database(config.DatabaseName).Collection(collectionName).InsertOne(context.TODO(), note)
return id, err
}
func (noteRepo *NoteRepository) ListNote() ([]model.Note, error) {
var notes []model.Note
cursor, err := noteRepo.ConnectionDB.Database(config.DatabaseName).Collection(collectionName).Find(context.TODO(), bson.D{})
if err != nil {
return notes, err
}
err = cursor.All(context.TODO(), ¬es)
return notes, err
}
func (noteRepo *NoteRepository) DeleteNote(id string) error {
objectId, err := primitive.ObjectIDFromHex(id)
_, err = noteRepo.ConnectionDB.Database(config.DatabaseName).Collection(collectionName).DeleteOne(context.TODO(), bson.M{"_id": objectId})
return err
}
func (noteRepo *NoteRepository) UpdateNote(id string, note model.Note) error {
objectId, err := primitive.ObjectIDFromHex(id)
if err != nil {
return err
}
note.UpdateTime = time.Now()
update := bson.M{
"$set": note,
}
_, err = noteRepo.ConnectionDB.Database(config.DatabaseName).Collection(collectionName).UpdateOne(context.TODO(), bson.M{"_id": objectId}, update)
return err
}
|
package main
import (
"fmt"
"os"
)
func main() {
f, err := os.Create("file1.txt")
if err != nil {
fmt.Println(err)
return
}
l, err := f.WriteString("Write Line one")
if err != nil {
fmt.Println(err)
f.Close()
return
}
fmt.Println(l, "bytes written")
err = f.Close()
if err != nil {
fmt.Println(err)
return
}
}
|
package auth
import (
"errors"
"github.com/chfanghr/hydric/core/auth/models"
models2 "github.com/chfanghr/hydric/core/models"
"golang.org/x/crypto/bcrypt"
)
func ComparePasswords(hashedPwd string, plainPwd []byte) bool {
byteHash := []byte(hashedPwd)
return bcrypt.CompareHashAndPassword(byteHash, plainPwd) == nil
}
func (s *Service) GetUserByEmail(email string) (*models2.User, error) {
var user models2.User
if err := s.DB.Model(&user).First(&user, "email = ?", email).Error; err != nil {
return nil, err
}
return &user, nil
}
func (s *Service) InsertUserLoginToken(t *models.Token) error {
return s.Redis.SAdd(t.RedisKey(), t.RedisToken()).Err()
}
func (s *Service) RemoveUserLoginToken(t *models.Token) error {
return s.Redis.SRem(t.RedisKey(), t.RedisToken()).Err()
}
func (s *Service) CreateUser(u models.Signup) (*models2.User, error) {
pass, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.MinCost)
if err != nil {
return nil, err
}
newUser := models2.User{
Email: u.Email,
Password: string(pass),
}
if err := s.DB.Model(&models2.User{}).Create(&newUser).Error; err != nil {
return nil, err
}
return &newUser, nil
}
func (s *Service) GetUserByToken(t *models.Token) (*models2.User, error) {
redisRes := s.Redis.SIsMember(t.RedisKey(), t.RedisToken())
isTokenExist := redisRes.Err() == nil && redisRes.Val()
if !isTokenExist {
return nil, errors.New("login token not exists")
}
var user models2.User
if err := s.DB.Model(&models2.User{}).First(&user, t.UID).Error; err != nil {
return nil, err
}
return &user, nil
}
|
/*
This package models any old event handler.
*/
package mockingsample
import (
"fmt"
"gsamples/mockingsample/dbaccess"
)
// The event handler struct. Models event attributes
type EventHandler struct {
name string // The name of the event
actor dbaccess.SomeFunctionalityGroup // The interface for our dbaccess fucntions
}
// This creates a event handler instance, using whatever name an actor are passed in.
func NewEventHandler(actor dbaccess.SomeFunctionalityGroup, name string) EventHandler {
return EventHandler{
name: name,
actor: actor,
}
}
// This is a sample event handler - it reads from the DB does some imaginary business logic and writes the results back
// to the DB.
func (eh *EventHandler) HandleSomeEvent(action string) error {
fmt.Printf("Handling event: %s\n", action)
value, err := eh.actor.ReadSomething(action, "arg1")
if err != nil {
fmt.Printf("Use the logger to log your error here. The read error is: %+v\n", err)
return err
}
// Do some business logic here
if len(value) == 2 && value[0] == "Hello" {
value[1] = "World"
}
// Now write the result back to the database
err = eh.actor.WriteSomething(value)
if err != nil {
fmt.Printf("Use the logger to log your error here. The write error is: %+v\n", err)
}
return err
}
|
package sso
import (
"encoding/json"
"io/ioutil"
"net/http"
"golang.org/x/oauth2"
)
//GithubEnterpriseEndpoint generates an OAuth2 endpoint for a Github Enterprise installation.
func GithubEnterpriseEndpoint(domain string) oauth2.Endpoint {
return oauth2.Endpoint{
AuthURL: "https://" + domain + "/login/oauth/authorize",
TokenURL: "https://" + domain + "/login/oauth/access_token",
}
}
//GithubEnterpriseEmailLookup generated an email lookup function for the specified domain.
func GithubEnterpriseEmailLookup(domain string) func(t *oauth2.Token) (string, error) {
return func(t *oauth2.Token) (string, error) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://"+domain+"/api/v3/user/emails", nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "token "+t.AccessToken)
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
emails := []struct {
email string
verified bool
primary bool
}{}
err = json.Unmarshal(contents, &emails)
if err != nil {
return "", err
}
email := ""
for _, e := range emails {
if e.primary && e.verified {
email = e.email
}
}
return email, nil
}
}
|
package bplustree
const (
MaxKV = 255
MaxKC = 511
)
type Node interface {
count() int
find(key []byte) (int, bool)
parent() *InteriorNode
setParent(*InteriorNode)
full() bool
isDirty() bool
setDirty(bool)
cache() (bool, []byte, []byte)
largestKey() []byte
encode() (value []byte)
decode(data []byte)
//DecodeMsg(dc *msgp.Reader) (err error)
//EncodeMsg(en *msgp.Writer) (err error)
//MarshalMsg(b []byte) (o []byte, err error)
//UnmarshalMsg(bts []byte) (o []byte, err error)
//Msgsize() (s int)
}
var (
prefixLeaf = byte(0)
prefixInterior = byte(1)
suffixLeaf = byte(0)
suffixInterior = byte(1)
)
|
package color
import "fmt"
type Code int
const None Code = -1
// Attributes.
const (
Reset Code = iota
Bold
Dim
Italic
Underline
Blink
BlinkFast
Inverse
Hidden
Strikethrough
)
// Foreground colors.
const (
Black Code = iota + 30
Red
Green
Yellow
Blue
Magenta
Cyan
LightGray
)
const (
DarkGray Code = iota + 90
LightRed
LightGreen
LightYellow
LightBlue
LightMagenta
LightCyan
White
)
// Background colors.
const (
BgBlack Code = iota + 40
BgRed
BgGreen
BgYellow
BgBlue
BgMagenta
BgCyan
BgLightGray
)
const (
BgDarkGray Code = iota + 100
BgLightRed
BgLightGreen
BgLightYellow
BgLightBlue
BgLightMagenta
BgLightCyan
BgWhite
)
// String sequence for code.
func (c Code) String() string {
return fmt.Sprintf("\x1b[%dm", c)
}
// Fg256 foreground 256 colors
func Fg256(c uint8) string {
return fmt.Sprintf("\x1b[38;5;%dm", c)
}
// Bg256 background 256 colors
func Bg256(c uint8) string {
return fmt.Sprintf("\x1b[48;5;%dm", c)
}
|
package leetcode
import (
"reflect"
"testing"
)
func listEqual(h1, h2 *ListNode) bool {
p1, p2 := h1, h2
for ; p1 != nil && p2 != nil && p1.Val == p2.Val; p1, p2 = p1.Next, p2.Next {
}
if p1 != nil || p2 != nil {
return false
}
return true
}
func slice2List(slice []int) *ListNode {
var head, prev *ListNode
for _, val := range slice {
node := &ListNode{Val: val}
if head == nil {
head = node
}
if prev != nil {
prev.Next = node
}
prev = node
}
return head
}
func list2Slice(head *ListNode) []int {
var slice []int
for p := head; p != nil; p = p.Next {
slice = append(slice, p.Val)
}
return slice
}
func sort(a []int) []int {
var q PriorityQueue
for _, x := range a {
q.Push(&ListNode{Val: x})
}
b := make([]int, 0, len(a))
for q.Len() > 0 {
n := q.Pop()
b = append(b, n.Val)
}
return b
}
func TestPriorityQueue(t *testing.T) {
tests := []struct {
input []int
output []int
}{
{
input: []int{1},
output: []int{1},
},
{
input: []int{2, 1},
output: []int{1, 2},
},
{
input: []int{2, 1, 3},
output: []int{1, 2, 3},
},
}
for i, tt := range tests {
if got, want := sort(tt.input), tt.output; !reflect.DeepEqual(got, want) {
t.Errorf("%d: sort: got %v, want %v", i, got, want)
}
}
}
func TestMergeKLists(t *testing.T) {
tests := []struct {
lists []*ListNode
merge *ListNode
}{
{
lists: []*ListNode{
&ListNode{Val: 1, Next: &ListNode{Val: 4, Next: &ListNode{Val: 5}}},
&ListNode{Val: 1, Next: &ListNode{Val: 3, Next: &ListNode{Val: 4}}},
&ListNode{Val: 2, Next: &ListNode{Val: 6}},
},
merge: &ListNode{
Val: 1, Next: &ListNode{
Val: 1, Next: &ListNode{
Val: 2, Next: &ListNode{
Val: 3, Next: &ListNode{
Val: 4, Next: &ListNode{
Val: 4, Next: &ListNode{
Val: 5, Next: &ListNode{
Val: 6, Next: nil,
},
},
},
},
},
},
},
},
},
{
lists: []*ListNode{
&ListNode{Val: -2, Next: &ListNode{Val: -1, Next: &ListNode{Val: -1, Next: &ListNode{Val: -1}}}},
nil,
},
merge: &ListNode{Val: -2, Next: &ListNode{Val: -1, Next: &ListNode{Val: -1, Next: &ListNode{Val: -1}}}},
},
}
for i, tt := range tests {
if got, want := mergeKLists(tt.lists), tt.merge; !listEqual(got, want) {
t.Errorf("%d: mergeKLists: got %v, want %v", i, list2Slice(got), list2Slice(want))
}
}
}
|
package sheets
import (
"context"
"fmt"
"golang.org/x/oauth2/google"
"google.golang.org/api/sheets/v4"
"io/ioutil"
)
type SheetClient struct {
srv *sheets.Service
spreadsheetID string
}
func NewSheetClient(ctx context.Context, spreadsheetID string) (*SheetClient, error) {
b, err := ioutil.ReadFile("secret.json")
if err != nil {
return nil, err
}
// read & write permission
jwt, err := google.JWTConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets")
if err != nil {
return nil, err
}
srv, err := sheets.New(jwt.Client(ctx))
if err != nil {
return nil, err
}
return &SheetClient{
srv: srv,
spreadsheetID: spreadsheetID,
}, nil
}
func GetCsv(srv *sheets.Service, sheetID string) ([][]interface{}, error) {
resp, err := srv.Spreadsheets.Values.Get(sheetID, "シート1!A2:ZZ").Do()
if err != nil {
return nil, fmt.Errorf("get spread sheet data error: %v", err)
}
return resp.Values, nil
}
func (s *SheetClient) SheetID(sheetName string) (int64, error) {
resp, err := s.srv.Spreadsheets.Get(s.spreadsheetID).Do()
if err != nil {
return 0, err
}
for _, sheet := range resp.Sheets {
if sheet.Properties.Title == sheetName {
return sheet.Properties.SheetId, nil
}
}
return 0, fmt.Errorf("sheetName %s is not found", sheetName)
}
func (s *SheetClient) Get(range_ string) ([][]interface{}, error) {
resp, err := s.srv.Spreadsheets.Values.Get(s.spreadsheetID, range_).Do()
if err != nil {
return nil, err
}
return resp.Values, nil
}
func GetAll() [][]interface{}{
ctx := context.Background()
client, err := NewSheetClient(ctx, "1LcGnzRuKYA5SyOBGsUm1oN1r4pNX-8lmaTYT54A_RsI")
if err != nil {
fmt.Println(err)
}
values, err := client.Get("'Answer'!A2:ZZ")
return values
}
func GetCorporateSheet() [][]interface{}{
ctx := context.Background()
client, err := NewSheetClient(ctx, "1LcGnzRuKYA5SyOBGsUm1oN1r4pNX-8lmaTYT54A_RsI")
if err != nil {
fmt.Println(err)
}
values, err := client.Get("'Corporate'!A2:ZZ")
return values
}
|
package main
import (
"fmt"
"os"
"strings"
prompt "github.com/c-bata/go-prompt"
"github.com/c-bata/go-prompt/completer"
)
var filePathCompleter = completer.FilePathCompleter{
IgnoreCase: true,
Filter: func(fi os.FileInfo) bool {
return fi.IsDir() || strings.HasSuffix(fi.Name(), ".go")
},
}
func executor(in string) {
fmt.Println("Your input: " + in)
}
func completerFunc(d prompt.Document) []prompt.Suggest {
t := d.GetWordBeforeCursor()
if strings.HasPrefix(t, "--") {
return []prompt.Suggest{
{"--foo", ""},
{"--bar", ""},
{"--baz", ""},
}
}
return filePathCompleter.Complete(d)
}
func main() {
p := prompt.New(
executor,
completerFunc,
prompt.OptionPrefix(">>> "),
prompt.OptionCompletionWordSeparator(completer.FilePathCompletionSeparator),
)
p.Run()
}
|
package prompt
import (
"fmt"
"os"
"strings"
)
func Confirm(msg string) bool {
if _, err := fmt.Fprintf(os.Stderr, "%s [y/N] ", msg); err != nil {
panic(err)
}
var res string
_, _ = fmt.Scanln(&res)
if strings.HasPrefix(strings.ToLower(res), "y") {
return true
}
return false
}
|
package events
import (
"time"
"github.com/bonjourmalware/melody/internal/config"
"github.com/bonjourmalware/melody/internal/events/helpers"
"github.com/bonjourmalware/melody/internal/logdata"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
)
// ICMPv6Event describes the structure of an event generated by an ICPMv6 packet
type ICMPv6Event struct {
LogData logdata.ICMPv6EventLog
BaseEvent
helpers.IPv6Layer
helpers.ICMPv6Layer
}
// NewICMPv6Event created a new ICMPv6Event from a packet
func NewICMPv6Event(packet gopacket.Packet) (*ICMPv6Event, error) {
var ev = &ICMPv6Event{}
ev.Kind = config.ICMPv6Kind
ev.Session = "n/a"
ev.Timestamp = packet.Metadata().Timestamp
ICMPv6Header, _ := packet.Layer(layers.LayerTypeICMPv6).(*layers.ICMPv6)
ev.ICMPv6Layer = helpers.ICMPv6Layer{Header: ICMPv6Header}
IPHeader, _ := packet.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
ev.IPv6Layer = helpers.IPv6Layer{Header: IPHeader}
ev.SourceIP = ev.IPv6Layer.Header.SrcIP.String()
ev.Additional = make(map[string]string)
ev.Tags = make(Tags)
return ev, nil
}
// ToLog parses the event structure and generate an EventLog almost ready to be sent to the logging file
func (ev ICMPv6Event) ToLog() EventLog {
ev.LogData = logdata.ICMPv6EventLog{}
//ev.LogData.Timestamp = time.Now().Format(time.RFC3339)
//ev.LogData.NsTimestamp = strconv.FormatInt(time.Now().UnixNano(), 10)
ev.LogData.Timestamp = ev.Timestamp.Format(time.RFC3339Nano)
//ev.LogData.Type = ev.Kind
//ev.LogData.SourceIP = ev.SourceIP
//ev.LogData.DestPort = ev.DestPort
//ev.LogData.Session = ev.Session
//
//if len(ev.Tags) == 0 {
// ev.LogData.Tags = make(map[string][]string)
//} else {
// ev.LogData.Tags = ev.Tags
//}
ev.LogData.Init(ev.BaseEvent)
ev.LogData.ICMPv6 = logdata.ICMPv6LogData{
TypeCode: ev.ICMPv6Layer.Header.TypeCode,
Type: ev.ICMPv6Layer.Header.TypeCode.Type(),
Code: ev.ICMPv6Layer.Header.TypeCode.Code(),
TypeCodeName: ev.ICMPv6Layer.Header.TypeCode.String(),
Checksum: ev.ICMPv6Layer.Header.Checksum,
Payload: logdata.NewPayloadLogData(ev.ICMPv6Layer.Header.Payload, config.Cfg.MaxICMPv6DataSize),
}
ev.LogData.IP = logdata.IPv6LogData{
Version: ev.IPv6Layer.Header.Version,
Length: ev.IPv6Layer.Header.Length,
NextHeader: ev.IPv6Layer.Header.NextHeader,
NextHeaderName: ev.IPv6Layer.Header.NextHeader.String(),
TrafficClass: ev.IPv6Layer.Header.TrafficClass,
FlowLabel: ev.IPv6Layer.Header.FlowLabel,
HopLimit: ev.IPv6Layer.Header.HopLimit,
}
ev.LogData.Additional = ev.Additional
return ev.LogData
}
|
package base
import (
"reflect"
"strings"
"testing"
"github.com/go-test/deep"
)
func TestNewEmptyGTS(t *testing.T) {
tests := []struct {
name string
want *GTS
}{{
name: "New empty GTS",
want: >S{
ClassName: "",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{},
},
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := NewEmptyGTS()
if pErr := deep.Equal(got, tt.want); len(pErr) > 0 {
t.Errorf("NewEmptyGTS() = %+v, want %+v\n%v", got, tt.want, pErr)
}
})
}
}
func TestNewGTS(t *testing.T) {
className := "my.metric"
g := NewGTS(className)
if g.ClassName != className {
t.Fatalf("NewGTS expect %s instead of %s as name", className, g.ClassName)
}
}
func TestNewGTSWithLabels(t *testing.T) {
type args struct {
className string
labels Labels
}
tests := []struct {
name string
args args
want *GTS
}{{
name: "New GTS with labels",
args: args{
className: "my.metric",
labels: Labels{
"a": "b",
"c": "d",
},
},
want: >S{
ClassName: "my.metric",
Labels: Labels{
"a": "b",
"c": "d",
},
},
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := NewGTSWithLabels(tt.args.className, tt.args.labels)
if got.ClassName != tt.want.ClassName {
t.Errorf("NewGTSWithLabels() = %v, want %v", got.ClassName, tt.want.ClassName)
}
if !reflect.DeepEqual(got.Labels, tt.want.Labels) {
t.Errorf("NewGTSWithLabels() = %v, want %v", got.Labels, tt.want.Labels)
}
if len(tt.want.Attributes) > 0 {
if !reflect.DeepEqual(got.Attributes, tt.want.Attributes) {
t.Errorf("NewGTSWithLabels() = %v, want %v", got.Attributes, tt.want.Attributes)
}
}
})
}
}
func TestParseGTSFromString(t *testing.T) {
type args struct {
sensisionLine string
}
tests := []struct {
name string
args args
wantGts *GTS
wantErr bool
}{{
name: "simple datapoint",
args: args{
sensisionLine: "1234// my.metric{} 10",
},
wantGts: >S{
ClassName: "my.metric",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{{int64(1234), float64(0), float64(0), float64(0), 10}},
},
wantErr: false,
}, {
name: "labelled datapoint",
args: args{
sensisionLine: "1234// my.metric{a=b,c=1} 10",
},
wantGts: >S{
ClassName: "my.metric",
Labels: Labels{"a": "b", "c": "1"},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{{int64(1234), float64(0), float64(0), float64(0), 10}},
},
wantErr: false,
}, {
name: "string datapoint",
args: args{
sensisionLine: "1234// my.metric{} 'my awesome metric'",
},
wantGts: >S{
ClassName: "my.metric",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{{int64(1234), float64(0), float64(0), float64(0), "my awesome metric"}},
},
wantErr: false,
}, {
name: "Geo datapoint",
args: args{
sensisionLine: "1234/12.3456:4.345678/1230 my.metric{} 10",
},
wantGts: >S{
ClassName: "my.metric",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{{int64(1234), float64(12.3456), float64(4.345678), float64(1230), 10}},
},
wantErr: false,
}, {
name: "No value datapoint",
args: args{
sensisionLine: "1234// my.metric{}",
},
wantGts: >S{},
wantErr: true,
}, {
name: "No timestamp datapoint",
args: args{
sensisionLine: "// my.metric{} 10",
},
wantGts: >S{},
wantErr: true,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotGts, err := ParseGTSFromString(tt.args.sensisionLine)
if tt.wantErr {
if err == nil {
t.Fatalf("ParseGTSFromString() wantErr %v", tt.wantErr)
}
return
} else if gotGts == nil {
t.Fatalf("ParseGTSFromString() = return is undefined")
return
}
if gotGts == nil {
t.Fatalf("ParseGTSFromString() = return is nil")
return
}
if differences := deep.Equal(*gotGts, *tt.wantGts); differences != nil {
t.Fatalf("ParseGTSFromString() = %+v, want %+v\n%v", gotGts, tt.wantGts, differences)
}
})
}
}
func TestParseGTSFromBytes(t *testing.T) {
type args struct {
in []byte
}
tests := []struct {
name string
args args
wantGts *GTS
wantErr bool
}{{
name: "Parse bytes sensision metric",
args: args{
in: []byte("1234// my.metric{} 50"),
},
wantGts: >S{
ClassName: "my.metric",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{{int64(1234), float64(0), float64(0), float64(0), 50}},
},
wantErr: false,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotGts, err := ParseGTSFromBytes(tt.args.in)
if (err != nil) != tt.wantErr {
t.Errorf("ParseGTSFromBytes() error = %v, wantErr %v", err, tt.wantErr)
return
}
if pErr := deep.Equal(gotGts, tt.wantGts); len(pErr) > 0 {
t.Errorf("ParseGTSFromBytes() = %+v, want %+v %v", gotGts, tt.wantGts, pErr)
}
})
}
}
func TestParseGTSArrayFromString(t *testing.T) {
type args struct {
in string
}
tests := []struct {
name string
args args
wantGtss GTSList
wantErr bool
}{{
name: "Parse bytes sensision metrics",
args: args{
in: "1234// my.metric{} 50\n5678// my.metric2{} 100",
},
wantGtss: GTSList{>S{
ClassName: "my.metric",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{{int64(1234), float64(0), float64(0), float64(0), 50}},
}, >S{
ClassName: "my.metric2",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{{int64(5678), float64(0), float64(0), float64(0), 100}},
}},
wantErr: false,
}, {
name: "Parse Error bytes sensision metrics",
args: args{
in: "1234// my.metric{} 50\n5678/00",
},
wantErr: true,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotGtss, err := ParseGTSArrayFromString(tt.args.in)
if tt.wantErr {
if err == nil {
t.Errorf("ParseGTSArrayFromString() error = %v, wantErr %v", err, tt.wantErr)
}
return
}
if pErr := deep.Equal(gotGtss, tt.wantGtss); len(pErr) > 0 {
t.Errorf("ParseGTSArrayFromString() = %+v, want %+v\n%v", gotGtss, tt.wantGtss, pErr)
}
})
}
}
func Test_parseSensisionLine(t *testing.T) {
type args struct {
in string
}
tests := []struct {
name string
args args
wantTs int64
wantLat float64
wantLong float64
wantAlt float64
wantC string
wantL Labels
wantA Attributes
wantV interface{}
wantErr bool
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotTs, gotLat, gotLong, gotAlt, gotC, gotL, gotA, gotV, err := parseSensisionLine(tt.args.in)
if (err != nil) != tt.wantErr {
t.Errorf("parseSensisionLine() error = %v, wantErr %v", err, tt.wantErr)
return
}
if gotTs != tt.wantTs {
t.Errorf("parseSensisionLine() gotTs = %v, want %v", gotTs, tt.wantTs)
}
if gotLat != tt.wantLat {
t.Errorf("parseSensisionLine() gotLat = %v, want %v", gotLat, tt.wantLat)
}
if gotLong != tt.wantLong {
t.Errorf("parseSensisionLine() gotLong = %v, want %v", gotLong, tt.wantLong)
}
if gotAlt != tt.wantAlt {
t.Errorf("parseSensisionLine() gotAlt = %v, want %v", gotAlt, tt.wantAlt)
}
if gotC != tt.wantC {
t.Errorf("parseSensisionLine() gotC = %v, want %v", gotC, tt.wantC)
}
if !reflect.DeepEqual(gotL, tt.wantL) {
t.Errorf("parseSensisionLine() gotL = %v, want %v", gotL, tt.wantL)
}
if !reflect.DeepEqual(gotA, tt.wantA) {
t.Errorf("parseSensisionLine() gotA = %v, want %v", gotA, tt.wantA)
}
if !reflect.DeepEqual(gotV, tt.wantV) {
t.Errorf("parseSensisionLine() gotV = %v, want %v", gotV, tt.wantV)
}
})
}
}
func TestGTS_Sensision(t *testing.T) {
type fields struct {
ClassName string
Labels Labels
Attributes Attributes
LastActivity int64
Values [][]interface{}
}
tests := []struct {
name string
fields fields
wantS string
}{{
name: "Format metric TS + VALUE",
fields: fields{
ClassName: "my.metric",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{{1234, 100}},
},
wantS: "1234// my.metric{} 100\n",
}, {
name: "Format metric TS + LAT + LONG + VAL",
fields: fields{
ClassName: "my.metric",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{{1234, 4.086475784, -1.6497593, 100}},
},
wantS: "1234/4.086475784:-1.6497593/ my.metric{} 100\n",
}, {
name: "Format metric TS + LAT + LONG + ALT + VAL",
fields: fields{
ClassName: "my.metric",
Labels: Labels{},
Attributes: Attributes{},
LastActivity: 0,
Values: [][]interface{}{{1234, -4.086475784, 1.6497593, 12034, 100}},
},
wantS: "1234/-4.086475784:1.6497593/12034 my.metric{} 100\n",
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gts := >S{
ClassName: tt.fields.ClassName,
Labels: tt.fields.Labels,
Attributes: tt.fields.Attributes,
LastActivity: tt.fields.LastActivity,
Values: tt.fields.Values,
}
if gotS := gts.Sensision(); gotS != tt.wantS {
t.Errorf("GTS.Sensision() = %v, want %v", gotS, tt.wantS)
}
})
}
}
func Test_formatLabels(t *testing.T) {
type args struct {
labels Labels
}
tests := []struct {
name string
args args
want []string
}{{
name: "plain labels",
args: args{
labels: Labels{
"host": "serverA",
"zone": "eu-west",
},
},
want: []string{"host=serverA", "zone=eu-west"},
}, {
name: "values with like",
args: args{
labels: Labels{
"host": "~server.*",
"zone": "=eu-west",
},
},
want: []string{"host~server.*", "zone=eu-west"},
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := formatLabels(tt.args.labels)
for _, want := range tt.want {
if !strings.Contains(got, want) {
t.Errorf("formatLabels() = %v, want %v", got, tt.want)
}
}
})
}
}
|
package service
import (
"errors"
"github.com/satori/go.uuid"
"zhiyuan/scaffold/internal/model"
)
func (s *Service) CreateCamera(CameraParams model.Camera_json)(result model.Camera,err error){
//数据交换
//传入DB方法
uid, _ := uuid.NewV4()
Add_Camera := model.Camera{
Camera_type:CameraParams.Camera_type,
Camera_position:CameraParams.Camera_position,
Camera_address:CameraParams.Camera_address,
Camera_RTSP:CameraParams.Camera_RTSP,
Camera_status:2,
Camera_token:uid.String(),
}
res,err := s.dao.CheckCameras(Add_Camera.Camera_address)
if res != true{
return model.Camera{},errors.New("ip重复")
}
obj,err := s.dao.AddCamera(Add_Camera)
if err!=nil{
return model.Camera{},err
}
return obj,nil
}
func (s *Service) UpdateCamera(CameraParams model.Camera_json,id int)(result model.Camera,err error){
//数据交换
//传入DB方法
Add_Camera := model.Camera{
ID:id,
Camera_type:CameraParams.Camera_type,
Camera_position:CameraParams.Camera_position,
Camera_address:CameraParams.Camera_address,
Camera_RTSP:CameraParams.Camera_RTSP,
}
obj,err := s.dao.UpdateCamera(Add_Camera,Add_Camera.ID)
if err!=nil{
return model.Camera{},err
}
return obj,nil
}
func (s *Service) DeleteCamera(id int)(err error){
err = s.dao.DeleteCamera(id)
if err!=nil{
return err
}
return nil
}
func (s *Service) GetCameras(camera_position string,camera_status,page,size int)(result []model.Camera,err error,count int,total int){
result,err,count,total = s.dao.GetCameras(camera_position,camera_status,page,size)
if err!=nil{
return []model.Camera{},err,0,0
}
return result,nil,count,total
}
func (s *Service) GetAllCameras()(result []model.Camera,err error){
result,err = s.dao.GetAllCameras()
if err!=nil{
return []model.Camera{},err
}
return result,nil
}
|
package future
import (
"time"
"fmt"
)
/**
Go-简洁的并发
http://www.yankay.com/go-clear-concurreny/
*/
type Query struct {
sql chan string
result chan string
}
//执行query
func ExecQuery(q Query) {
go func() {
sql := <-q.sql
q.result <- "get:"+sql
}()
}
func Test1() {
q := Query{make(chan string,1), make(chan string,1)}
ExecQuery(q)
time.Sleep(time.Second * 4)
q.sql <- "select * from oil_galaxy_order limit 10"
fmt.Println(<-q.result)
fmt.Println("func end----")
}
|
package controllers
import (
"github.com/gin-gonic/gin"
"net/http"
)
// Controller implements handlers for web server requests.
type Controller struct {
betResponse BetResponse
}
// NewController creates a new instance of Controller
func NewController(betResponse BetResponse) *Controller {
return &Controller{
betResponse: betResponse,
}
}
func (e *Controller) HandleBetById() gin.HandlerFunc{
return func(ctx *gin.Context){
id := ctx.Param("id")
bet, exists, err := e.betResponse.GetBetById(ctx, id)
if err != nil {
ctx.String(http.StatusBadRequest, err.Error())
return
}
if !exists {
ctx.String(http.StatusNotFound, "failed to get bets with given id")
return
}
ctx.JSON(http.StatusOK, bet)
}
}
func (e *Controller) HandleBetsByUser() gin.HandlerFunc {
return func(ctx *gin.Context) {
userId := ctx.Param("id")
bets, err := e.betResponse.GetBetsByUser(ctx, userId)
if err != nil {
ctx.String(http.StatusBadRequest, err.Error())
return
}
if len(bets) == 0 {
ctx.String(http.StatusNotFound, "failed to get bets with given user id")
return
}
ctx.JSON(http.StatusOK, bets)
}
}
func (e *Controller) HandleBetsByStatus() gin.HandlerFunc {
return func(ctx *gin.Context) {
status := ctx.Query("status")
bets, err := e.betResponse.GetBetsByStatus(ctx, status)
if err != nil {
ctx.String(http.StatusBadRequest, err.Error())
return
}
if len(bets) == 0 {
ctx.String(http.StatusNotFound, "failed to get bets with given status")
return
}
ctx.JSON(http.StatusOK, bets)
}
}
|
package validation
import (
"fmt"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/util/validation/field"
"github.com/openshift/installer/pkg/types"
"github.com/openshift/installer/pkg/types/aws"
)
func TestValidatePlatform(t *testing.T) {
cases := []struct {
name string
platform *aws.Platform
expected string
credMode types.CredentialsMode
}{
{
name: "minimal",
platform: &aws.Platform{
Region: "us-east-1",
},
},
{
name: "invalid region",
platform: &aws.Platform{
Region: "",
},
expected: `^test-path\.region: Required value: region must be specified$`,
},
{
name: "hosted zone with subnets",
platform: &aws.Platform{
Region: "us-east-1",
Subnets: []string{"test-subnet"},
HostedZone: "test-hosted-zone",
},
},
{
name: "hosted zone without subnets",
platform: &aws.Platform{
Region: "us-east-1",
HostedZone: "test-hosted-zone",
},
expected: `^test-path\.hostedZone: Invalid value: "test-hosted-zone": may not use an existing hosted zone when not using existing subnets$`,
},
{
name: "invalid url for service endpoint",
platform: &aws.Platform{
Region: "us-east-1",
ServiceEndpoints: []aws.ServiceEndpoint{{
Name: "ec2",
URL: "/path/some",
}},
},
expected: `^test-path\.serviceEndpoints\[0\]\.url: Invalid value: "(.*)": host cannot be empty, empty host provided$`,
},
{
name: "invalid url for service endpoint",
platform: &aws.Platform{
Region: "us-east-1",
ServiceEndpoints: []aws.ServiceEndpoint{{
Name: "ec2",
URL: "https://test-ec2.random.local/path/some",
}},
},
expected: `^test-path\.serviceEndpoints\[0\]\.url: Invalid value: "(.*)": no path or request parameters must be provided, "/path/some" was provided$`,
},
{
name: "invalid url for service endpoint",
platform: &aws.Platform{
Region: "us-east-1",
ServiceEndpoints: []aws.ServiceEndpoint{{
Name: "ec2",
URL: "https://test-ec2.random.local?foo=some",
}},
},
expected: `^test-path\.serviceEndpoints\[0\]\.url: Invalid value: "(.*)": no path or request parameters must be provided, "/\?foo=some" was provided$`,
},
{
name: "valid url for service endpoint",
platform: &aws.Platform{
Region: "us-east-1",
ServiceEndpoints: []aws.ServiceEndpoint{{
Name: "ec2",
URL: "test-ec2.random.local",
}},
},
},
{
name: "valid url for service endpoint",
platform: &aws.Platform{
Region: "us-east-1",
ServiceEndpoints: []aws.ServiceEndpoint{{
Name: "ec2",
URL: "https://test-ec2.random.local",
}},
},
},
{
name: "duplicate service endpoints",
platform: &aws.Platform{
Region: "us-east-1",
ServiceEndpoints: []aws.ServiceEndpoint{{
Name: "ec2",
URL: "test-ec2.random.local",
}, {
Name: "s3",
URL: "test-ec2.random.local",
}, {
Name: "ec2",
URL: "test-ec2.random.local",
}},
},
expected: `^test-path\.serviceEndpoints\[2\]\.name: Invalid value: "ec2": duplicate service endpoint not allowed for ec2, service endpoint already defined at test-path\.serviceEndpoints\[0\]$`,
},
{
name: "valid machine pool",
platform: &aws.Platform{
Region: "us-east-1",
DefaultMachinePlatform: &aws.MachinePool{},
},
},
{
name: "invalid machine pool",
platform: &aws.Platform{
Region: "us-east-1",
DefaultMachinePlatform: &aws.MachinePool{
EC2RootVolume: aws.EC2RootVolume{
Type: "io1",
IOPS: -10,
Size: 128,
},
},
},
expected: `^test-path.*iops: Invalid value: -10: iops must be a positive number$`,
},
{
name: "invalid userTags, Name key",
platform: &aws.Platform{
Region: "us-east-1",
UserTags: map[string]string{
"Name": "test-cluster",
},
},
expected: `^\Qtest-path.userTags[Name]: Invalid value: "test-cluster": Name key is not allowed for user defined tags\E$`,
},
{
name: "invalid userTags, key with kubernetes.io/cluster/",
platform: &aws.Platform{
Region: "us-east-1",
UserTags: map[string]string{
"kubernetes.io/cluster/test-cluster": "shared",
},
},
expected: `^\Qtest-path.userTags[kubernetes.io/cluster/test-cluster]: Invalid value: "shared": Keys with prefix 'kubernetes.io/cluster/' are not allowed for user defined tags\E$`,
},
{
name: "valid userTags",
platform: &aws.Platform{
Region: "us-east-1",
UserTags: map[string]string{
"app": "production",
},
},
},
{
name: "too many userTags",
platform: &aws.Platform{
Region: "us-east-1",
UserTags: generateTooManyUserTags(),
},
expected: fmt.Sprintf(`^\Qtest-path.userTags: Too many: %d: must have at most %d items`, userTagLimit+1, userTagLimit),
},
{
name: "hosted zone role without hosted zone should error",
platform: &aws.Platform{
Region: "us-east-1",
HostedZoneRole: "test-hosted-zone-role",
},
expected: `^test-path\.hostedZoneRole: Invalid value: "test-hosted-zone-role": may not specify a role to assume for hosted zone operations without also specifying a hosted zone$`,
},
{
name: "valid hosted zone & role should not throw an error",
credMode: types.PassthroughCredentialsMode,
platform: &aws.Platform{
Region: "us-east-1",
Subnets: []string{"test-subnet"},
HostedZone: "test-hosted-zone",
HostedZoneRole: "test-hosted-zone-role",
},
},
{
name: "hosted zone role without credential mode should error",
platform: &aws.Platform{
Region: "us-east-1",
Subnets: []string{"test-subnet"},
HostedZone: "test-hosted-zone",
HostedZoneRole: "test-hosted-zone-role",
},
expected: `^test-path\.hostedZoneRole: Forbidden: when specifying a hostedZoneRole, either Passthrough or Manual credential mode must be specified$`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := ValidatePlatform(tc.platform, tc.credMode, field.NewPath("test-path")).ToAggregate()
if tc.expected == "" {
assert.NoError(t, err)
} else {
assert.Regexp(t, tc.credMode, err)
}
})
}
}
func TestValidateTag(t *testing.T) {
cases := []struct {
name string
key string
value string
expectErr bool
}{{
name: "valid",
key: "test-key",
value: "test-value",
}, {
name: "invalid characters in key",
key: "bad-key***",
value: "test-value",
expectErr: true,
}, {
name: "invalid characters in value",
key: "test-key",
value: "bad-value***",
expectErr: true,
}, {
name: "empty key",
key: "",
value: "test-value",
expectErr: true,
}, {
name: "empty value",
key: "test-key",
value: "",
expectErr: true,
}, {
name: "key too long",
key: strings.Repeat("a", 129),
value: "test-value",
expectErr: true,
}, {
name: "value too long",
key: "test-key",
value: strings.Repeat("a", 257),
expectErr: true,
}, {
name: "key in kubernetes.io namespace",
key: "kubernetes.io/cluster/some-cluster",
value: "owned",
expectErr: true,
}, {
name: "key in openshift.io namespace",
key: "openshift.io/some-key",
value: "some-value",
expectErr: true,
}, {
name: "key in openshift.io subdomain namespace",
key: "other.openshift.io/some-key",
value: "some-value",
expectErr: true,
}, {
name: "key in namespace similar to openshift.io",
key: "otheropenshift.io/some-key",
value: "some-value",
}, {
name: "key with openshift.io in path",
key: "some-domain/openshift.io/some-key",
value: "some-value",
}}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := validateTag(tc.key, tc.value)
if tc.expectErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}
func generateTooManyUserTags() map[string]string {
tags := map[string]string{}
for i := 0; i <= userTagLimit; i++ {
tags[strconv.Itoa(i)] = strconv.Itoa(i)
}
return tags
}
|
package es
import (
"context"
"errors"
"fmt"
"log"
"os"
"gopkg.in/olivere/elastic.v5"
)
func CreateNewElasticSearchClient(ctx context.Context, url *string, sniff *bool, trace *bool) *elastic.Client {
var options []elastic.ClientOptionFunc
options = append(options, elastic.SetURL(*url))
options = append(options, elastic.SetSniff(*sniff))
if *trace {
options = append(options, elastic.SetTraceLog(log.New(os.Stdout, "es: ", 0)))
}
client, err := elastic.NewClient(options...)
if err != nil {
fmt.Printf("Elasticsearch Url %s\n", *url)
panic(err)
}
defer client.Stop()
info, code, err := client.Ping(*url).Do(ctx)
if err != nil {
panic(err)
}
fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)
esversion, err := client.ElasticsearchVersion(*url)
if err != nil {
panic(err)
}
fmt.Printf("Elasticsearch version %s\n", esversion)
return client
}
func InitializeNewIndex(client *elastic.Client, ctx context.Context, indexName string, mapping string) {
exists, err := client.IndexExists(indexName).Do(ctx)
if err != nil {
panic(err)
}
if exists {
_, err := client.DeleteIndex(indexName).Do(ctx)
if err != nil {
panic(err)
}
}
createIndex, err := client.CreateIndex(indexName).BodyString(mapping).Do(ctx)
if err != nil {
panic(err)
}
if !createIndex.Acknowledged {
panic(errors.New(fmt.Sprintf("%s Index Not Created", indexName)))
}
}
|
package tool
import (
"testing"
)
func TestGzipEncodeAndDecode(t *testing.T) {
rawData := []byte(`hello, 中新经纬客户端11月6日电 据国家发改委网站6日消息,10月30日,国家发展改革委修订发布了《产业结构调整指导目录(2019年本)》(以下简称《目录(2019年本)》)。国家发改委产业发展司负责人就《目录(2019年本)》答记者问时表示,此次修订重点包含破除无效供给、推动制造业高质量发展等四方面。鼓励类新增“人力资源与人力资本服务业”、“人工智能”、“养老与托育服务”、“家政”等4个行业。`)
encodeData := GzipEncode(rawData)
decodeData := GzipDecode(encodeData)
if string(rawData) != string(decodeData) {
t.Fail()
}
t.Log("raw len: ", len(rawData), "encde len: ", len(encodeData))
}
func TestStrToByteSize(t *testing.T) {
validateArr := map[string]int64{
"2gb": 2 * 1024 * 1024 * 1024,
"2M": 2 * 1024 * 1024,
"2kb": 2 * 1024,
"2": 2,
"1dsada1": 0,
}
for k,v := range validateArr {
num := StrToByteSize(k)
if num != v {
t.Fail()
}
}
} |
package handler
import (
"mux-rest-api/domain/contact"
"mux-rest-api/domain/contact/usecase"
"net/http"
"go.mongodb.org/mongo-driver/mongo"
)
//ListContactHandler - This interface provides the object with the responsibility to handle the request to retrieve the contact list.
type ListContactHandler interface {
HandlerRoute
}
//listContactHandler - This struct provides the implementation of ListContactHandler interface.
type listContactHandler struct {
db *mongo.Database
}
//NewListContactHandler - This method provides the instance of ListContactHandler interface.
func NewListContactHandler(db *mongo.Database) ListContactHandler {
return &listContactHandler{db}
}
//Props - This method provides the path and http verb of ListContactHandler.
func (h *listContactHandler) Props() (path string, method string) {
path = "/api/v1/contact"
method = "GET"
return path, method
}
//Handler - This method provides the handling of the request to retrieve the contact list.
func (h *listContactHandler) Handler(w http.ResponseWriter, r *http.Request) {
contactRepository := contact.NewContactRepository(h.db)
contactService := contact.NewContactService(contactRepository)
listContactUseCase := usecase.NewListContactUseCase(contactService)
dataResponse, err := listContactUseCase.Execute()
if err != nil {
ResponseError(w, http.StatusNotFound, err.Error())
}
ResponseJSON(w, http.StatusOK, dataResponse)
}
|
package easygo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"runtime"
"strconv"
"strings"
"time"
)
//BuildRequest build your http request in one easy, convenient line, just return after this method.
func BuildRequest(domain string, port string, method string, endpoint string, headers map[string]string, params map[string]string, object interface{}) ([]byte, int, string, error) {
var url string
if port != "" {
if strings.HasSuffix(domain, "/") {
url = domain[:len(domain)-len("/")]
url = url + ":" + port + "/" + endpoint
} else {
url = domain + ":" + port + "/" + endpoint
}
} else {
if strings.HasSuffix(domain, "/") {
url = domain + endpoint
} else {
url = domain + "/" + endpoint
}
}
httpClient := &http.Client{}
var payload []byte
var err error
if object != nil {
payload, err = json.Marshal(object)
if err != nil {
return nil, 0, "", err
}
}
req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
if err != nil {
return nil, 0, "", err
}
if headers != nil {
for key, val := range headers {
req.Header.Set(key, val)
fmt.Println(req.Header)
}
}
if params != nil {
q := req.URL.Query()
for key, val := range params {
q.Add(key, val)
}
req.URL.RawQuery = q.Encode()
}
res, err := httpClient.Do(req)
if err != nil {
return nil, 0, "", err
}
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, 0, "", err
}
return resBody, res.StatusCode, res.Status, nil
}
//Respond used in handler functions to build responses with one line by passing in statusCode, body, and headers
func Respond(w http.ResponseWriter, r *http.Request, statusCode int, body interface{}, headers map[string]string) error {
w.WriteHeader(statusCode)
if body != nil {
res, err := json.Marshal(body)
if err != nil {
return err
}
w.Write(res)
}
if headers != nil {
// TODO: Set Headers
}
return nil
}
//RespondBasic supports: 200|ok, 201|created, 400|bad request, 401|unauthorized, 403|forbidden, 404|resource missing, 405|method not allowed, 500|internal server error
func RespondBasic(w http.ResponseWriter, r *http.Request, statusCode int) {
msg := map[string]interface{}{}
switch statusCode {
case 200:
msg["message"] = "ok"
case 201:
msg["message"] = "created"
case 400:
msg["message"] = "bad request"
case 401:
msg["message"] = "unauthorized"
case 403:
msg["message"] = "forbidden"
case 404:
msg["message"] = "resource missing"
case 405:
msg["message"] = "method not allowed"
case 500:
msg["message"] = "internal server error"
default:
msg["timestamp"] = time.Now()
res, err := json.Marshal(msg)
if err != nil {
fmt.Println(err)
}
w.WriteHeader(statusCode)
w.Write(res)
return
}
msg["timestamp"] = time.Now()
res, err := json.Marshal(msg)
if err != nil {
fmt.Println(err)
}
w.WriteHeader(statusCode)
w.Write(res)
}
// AppendStringNoDuplicates When adding a string to an array, this will check that the string doesn't all ready exist in the array
func AppendStringNoDuplicates(arr []string, str string) []string {
doIt := true
for _, arrStr := range arr {
if arrStr == str {
doIt = false
}
}
if doIt {
arr = append(arr, str)
}
fmt.Println("")
return arr
}
// AppendStringSliceNoDuplicates when combing string arrays, merges while preventing duplicates
func AppendStringSliceNoDuplicates(slice1 []string, slice2 []string) []string {
for _, str1 := range slice1 {
doIt := true
for _, str2 := range slice2 {
if str1 == str2 {
doIt = false
}
}
if doIt {
slice2 = append(slice2, str1)
}
}
return slice2
}
// ResponseObject A neat little response object for simple responses
type ResponseObject struct {
Error bool `json:"error"`
Message string `json:"message"`
Function string `json:"function"`
}
// GetDateString takes a time object and returns the date in string form. YYYY-MM-DD
func GetDateString(tme time.Time) string {
yr, mth, day := tme.Date()
var dayNumber int
dayNumber = int(day)
var dayString string
if dayNumber < 10 {
dayString = strconv.Itoa(dayNumber)
dayString = "0" + dayString
} else {
dayString = strconv.Itoa(dayNumber)
}
strconv.Itoa(dayNumber)
var mthNumber int
mthNumber = int(mth)
var mthString string
if mthNumber < 10 {
mthString = strconv.Itoa(mthNumber)
mthString = "0" + mthString
} else {
mthString = strconv.Itoa(mthNumber)
}
strconv.Itoa(dayNumber)
concatStr := strconv.Itoa(yr) + "-" + mthString + "-" + dayString
return concatStr
}
//Log Prints to stdout
func Log(msg string) {
pc, _, line, _ := runtime.Caller(1)
print := time.Now().Format(time.RFC3339) + " | " + "Log from (" + runtime.FuncForPC(pc).Name() + " on line " + strconv.Itoa(line) + ") | " + msg
fmt.Println(print)
}
//LogErr Prints to stdout
func LogErr(err error) {
pc, _, line, _ := runtime.Caller(1)
print := time.Now().Format(time.RFC3339) + " | " + "Error in (" + runtime.FuncForPC(pc).Name() + " on line " + strconv.Itoa(line) + ") | " + err.Error()
fmt.Println(print)
}
//DecodeBody reads and unmarshalls the body of a a request b into the struct at dest and returns the RAW body and unmarshalled body
func DecodeBody(b io.Reader, dest interface{}) ([]byte, error) {
byt, err := ioutil.ReadAll(b)
if err != nil {
return byt, err
}
err = json.Unmarshal(byt, &dest)
if err != nil {
return byt, err
}
return byt, nil
}
//DecodeMap converts the map provided at src into the type pointed to at dest (make sure you point to it with "&")
func DecodeMap(src, dest interface{}) error {
byt, err := json.Marshal(src)
if err != nil {
return err
}
err = json.Unmarshal(byt, &dest)
if err != nil {
return err
}
return nil
}
|
package user
import (
log "github.com/sirupsen/logrus"
"oauth-server-lite/g"
)
func CreateLock(userID, clientIP string) {
rc := g.ConnectRedis().Get()
defer rc.Close()
redisKey := g.Config().RedisNamespace.Lock + userID + ":" + clientIP
_, err := rc.Do("SET", redisKey, 1, "EX", g.Config().LockTime)
if err != nil {
log.Errorln(err)
}
return
}
func CheckLock(userID, clientIP string) (lock bool) {
rc := g.ConnectRedis().Get()
defer rc.Close()
redisKey := g.Config().RedisNamespace.Lock + userID + ":" + clientIP
res, err := rc.Do("GET", redisKey)
if err != nil {
log.Errorln(err)
return
}
if res != nil {
lock = true
return
}
return
}
|
package main
import (
"fmt"
"math"
"sort"
)
func main() {
nums := []int{0, 0, 0}
target := 1
fmt.Println(threeSumClosest(nums, target))
}
func threeSumClosest(nums []int, target int) int {
min := math.MaxInt32
sort.Ints(nums)
for i := 0; i < len(nums)-2; i++ {
left := i + 1
right := len(nums) - 1
for left < right {
sum := nums[i] + nums[left] + nums[right]
if math.Abs(float64(target-sum)) < math.Abs(float64(min)) {
min = target - sum
}
if sum < target {
left++
} else if sum > target {
right--
} else {
return target
}
}
}
return target - min
}
|
package main
import (
"MailService/Postgres"
"MailService/config"
"MailService/internal/Delivery"
"MailService/internal/Repository/LetterPostgres"
"MailService/internal/UseCase"
letterProto "MailService/proto"
"fmt"
"google.golang.org/grpc"
"log"
"net"
)
func main() {
lis, err := net.Listen("tcp", ":8083")
if err != nil {
log.Fatalln("cant listen port", err)
}
server := grpc.NewServer()
db := Postgres.DataBase{}
db.Init(config.DbUser, config.DbPassword, config.DbDB)
repo := LetterPostgres.New(db.DB)
uc := UseCase.New(repo)
letterProto.RegisterLetterServiceServer(server, Delivery.New(uc))
fmt.Println("starting File at :8083")
server.Serve(lis)
}
|
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-2019 Datadog, Inc.
package strategy
import (
"testing"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
datadoghqv1alpha1 "github.com/datadog/extendeddaemonset/pkg/apis/datadoghq/v1alpha1"
"github.com/datadog/extendeddaemonset/pkg/apis/datadoghq/v1alpha1/test"
commontest "github.com/datadog/extendeddaemonset/pkg/controller/test"
)
func Test_compareWithExtendedDaemonsetSettingOverwrite(t *testing.T) {
nodeName1 := "node1"
nodeOptions := &commontest.NewNodeOptions{}
node1 := commontest.NewNode(nodeName1, nodeOptions)
resource1 := &corev1.ResourceRequirements{
Requests: corev1.ResourceList{
"cpu": resource.MustParse("1"),
},
}
pod1Option := &commontest.NewPodOptions{Resources: *resource1}
pod1 := commontest.NewPod("bar", "pod1", nodeName1, pod1Option)
pod1.Spec.Containers[0].Resources = *resource1
edsNode1Options := &test.NewExtendedDaemonsetSettingOptions{
Resources: map[string]corev1.ResourceRequirements{
"pod1": *resource1,
},
}
extendedDaemonsetSetting1 := test.NewExtendedDaemonsetSetting("bar", "foo", "foo", edsNode1Options)
edsNode2Options := &test.NewExtendedDaemonsetSettingOptions{
Resources: map[string]corev1.ResourceRequirements{
"pod1": {
Requests: corev1.ResourceList{
"cpu": resource.MustParse("2"),
"memory": resource.MustParse("1G"),
},
},
},
}
extendedDaemonsetSetting2 := test.NewExtendedDaemonsetSetting("bar", "foo", "foo", edsNode2Options)
type args struct {
pod *corev1.Pod
node *NodeItem
}
tests := []struct {
name string
args args
want bool
}{
{
name: "empty ExtendedDaemonsetSetting",
args: args{
pod: pod1,
node: &NodeItem{
Node: node1,
},
},
want: true,
},
{
name: "ExtendedDaemonsetSetting that match",
args: args{
pod: pod1,
node: &NodeItem{
Node: node1,
ExtendedDaemonsetSetting: extendedDaemonsetSetting1,
},
},
want: true,
},
{
name: "ExtendedDaemonsetSetting doesn't match",
args: args{
pod: pod1,
node: &NodeItem{
Node: node1,
ExtendedDaemonsetSetting: extendedDaemonsetSetting2,
},
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := compareWithExtendedDaemonsetSettingOverwrite(tt.args.pod, tt.args.node); got != tt.want {
t.Errorf("compareWithExtendedDaemonsetSettingOverwrite() = %v, want %v", got, tt.want)
}
})
}
}
func Test_pauseCanaryDeployment(t *testing.T) {
s := scheme.Scheme
s.AddKnownTypes(datadoghqv1alpha1.SchemeGroupVersion, &datadoghqv1alpha1.ExtendedDaemonSet{})
daemonset := test.NewExtendedDaemonSet("test", "test", &test.NewExtendedDaemonSetOptions{})
reason := datadoghqv1alpha1.ExtendedDaemonSetStatusReasonCLB
daemonsetPaused := daemonset.DeepCopy()
daemonsetPaused.Annotations[datadoghqv1alpha1.ExtendedDaemonSetCanaryPausedAnnotationKey] = pausedValueTrue
type args struct {
client client.Client
eds *datadoghqv1alpha1.ExtendedDaemonSet
reason datadoghqv1alpha1.ExtendedDaemonSetStatusReason
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "add paused annotation without issue",
args: args{
client: fake.NewFakeClient(daemonset),
eds: daemonset,
reason: reason,
},
wantErr: false,
},
{
name: "add paused annotation when it is already paused",
args: args{
client: fake.NewFakeClient(daemonsetPaused),
eds: daemonsetPaused,
reason: reason,
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := pauseCanaryDeployment(tt.args.client, tt.args.eds, tt.args.reason); (err != nil) != tt.wantErr {
t.Errorf("pauseCanaryDeployment() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
|
func minSwapsCouples(row []int) int {
res:=0
for i:=0;i<len(row);i+=2{
if row[i+1]==row[i]^1{ continue }
for j:=i+2;j<len(row);j++{
if row[j] == row[i]^1 {
row[i+1], row[j] = row[j],row[i+1]
}
}
res++
}
return res
}
|
package govisitor
import (
"errors"
"fmt"
"go/ast"
"go/token"
"golang.org/x/tools/go/ast/astutil"
)
type Visitor struct{}
type Walker struct {
errs []error
f *ast.File
fset *token.FileSet
}
func (v *Visitor) Run(f ast.Node, fset *token.FileSet) []error {
walker := &Walker{
errs: []error{},
f: f.(*ast.File),
fset: fset,
}
ast.Walk(walker, f)
return walker.errs
}
func (v *Visitor) Name() string {
return "go"
}
func (w *Walker) Visit(n ast.Node) ast.Visitor {
switch n := n.(type) {
case *ast.GoStmt:
w.detectScope(n)
default:
return w
}
return nil
}
func (w *Walker) detectScope(n ast.Node) {
nodes, _ := astutil.PathEnclosingInterval(w.f, n.Pos(), n.End())
for _, node := range nodes {
switch x := node.(type) {
case *ast.FuncDecl:
if ast.IsExported(x.Name.Name) {
w.errs = append(w.errs, errors.New(fmt.Sprintf("%s: go statement used in exported function", w.fset.Position(x.Pos()))))
}
}
}
}
|
package json
import (
"bytes"
"testing"
. "github.com/warpfork/go-wish"
"github.com/polydawn/refmt/tok/fixtures"
)
// note: we still put all tests in one func so we control order.
// this will let us someday refactor all `fixtures.SequenceMap` refs to use a
// func which quietly records which sequences have tests aimed at them, and we
// can read that back at out the end of the tests and use the info to
// proactively warn ourselves when we have unreferenced tok fixtures.
func Test(t *testing.T) {
testBool(t)
testString(t)
testMap(t)
testArray(t)
testComposite(t)
testNumber(t)
}
func checkCanonical(t *testing.T, sequence fixtures.Sequence, serial string) {
t.Run("encode canonical", func(t *testing.T) {
checkEncoding(t, sequence, serial, nil)
})
t.Run("decode canonical", func(t *testing.T) {
checkDecoding(t, sequence, serial, nil)
})
}
func checkEncoding(t *testing.T, sequence fixtures.Sequence, expectSerial string, expectErr error) {
t.Helper()
outputBuf := &bytes.Buffer{}
tokenSink := NewEncoder(outputBuf, EncodeOptions{})
// Run steps, advancing through the token sequence.
// If it stops early, just report how many steps in; we Wish on that value.
// If it doesn't stop in time, just report that bool; we Wish on that value.
var nStep int
var done bool
var err error
for _, tok := range sequence.Tokens {
nStep++
done, err = tokenSink.Step(&tok)
if done || err != nil {
break
}
}
// Assert final result.
Wish(t, done, ShouldEqual, true)
Wish(t, nStep, ShouldEqual, len(sequence.Tokens))
Wish(t, err, ShouldEqual, expectErr)
Wish(t, outputBuf.String(), ShouldEqual, expectSerial)
}
func checkDecoding(t *testing.T, expectSequence fixtures.Sequence, serial string, expectErr error) {
// Decoding JSON is *never* going to yield length info on tokens,
// so we'll strip that here rather than forcing all our fixtures to say it.
expectSequence = expectSequence.SansLengthInfo()
t.Helper()
inputBuf := bytes.NewBufferString(serial)
tokenSrc := NewDecoder(inputBuf)
// Run steps, advancing until the decoder reports it's done.
// If the decoder keeps yielding more tokens than we expect, that's fine...
// we just keep recording them, and we'll diff later.
// There's a cutoff when it overshoots by 10 tokens because generally
// that indicates we've found some sort of loop bug and 10 extra token
// yields is typically enough info to diagnose with.
var nStep int
var done bool
var yield = make(fixtures.Tokens, len(expectSequence.Tokens)+10)
var err error
for ; nStep <= len(expectSequence.Tokens)+10; nStep++ {
done, err = tokenSrc.Step(&yield[nStep])
if done || err != nil {
break
}
}
nStep++
yield = yield[:nStep]
// Assert final result.
Wish(t, done, ShouldEqual, true)
Wish(t, nStep, ShouldEqual, len(expectSequence.Tokens))
Wish(t, yield, ShouldEqual, expectSequence.Tokens)
Wish(t, err, ShouldEqual, expectErr)
}
|
package util
import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"projja_telegram/model"
"strconv"
)
type BotUtil struct {
Message *MessageData
Bot *tgbotapi.BotAPI
Updates chan tgbotapi.Update
}
type MessageData struct {
From *tgbotapi.User
Chat *tgbotapi.Chat
}
func TgUserToModelUser(data *MessageData) *model.User {
name := data.From.FirstName
if data.From.LastName != "" {
name += " " + data.From.LastName
}
return &model.User{
Name: name,
Username: data.From.UserName,
TelegramId: strconv.Itoa(data.From.ID),
ChatId: data.Chat.ID,
}
}
|
package main
import (
"fmt"
"io"
"os"
smartling "github.com/Smartling/api-sdk-go"
"github.com/reconquest/hierr-go"
)
func doProjectsLocales(
client *smartling.Client,
config Config,
args map[string]interface{},
) error {
var (
project = config.ProjectID
short, _ = args["--short"].(bool)
source, _ = args["--source"].(bool)
)
if args["--format"] == nil {
args["--format"] = defaultProjectsLocalesFormat
}
format, err := compileFormat(args["--format"].(string))
if err != nil {
return err
}
details, err := client.GetProjectDetails(project)
if err != nil {
if _, ok := err.(smartling.NotFoundError); ok {
return ProjectNotFoundError{}
}
return hierr.Errorf(
err,
`unable to get project "%s" details`,
project,
)
}
table := NewTableWriter(os.Stdout)
if source {
if short {
fmt.Fprintf(table, "%s\n", details.SourceLocaleID)
} else {
fmt.Fprintf(
table,
"%s\t%s\n",
details.SourceLocaleID,
details.SourceLocaleDescription,
)
}
} else {
for _, locale := range details.TargetLocales {
if short {
fmt.Fprintf(table, "%s\n", locale.LocaleID)
} else {
row, err := format.Execute(locale)
if err != nil {
return err
}
_, err = io.WriteString(table, row)
if err != nil {
return hierr.Errorf(
err,
"unable to write row to output table",
)
}
}
}
}
err = RenderTable(table)
if err != nil {
return err
}
return nil
}
|
package main
import (
"encoding/json"
"io/ioutil"
"path"
)
type PassReader interface {
ReadPassword() (string, error)
}
type file_passer struct {
filename string
}
func (f *file_passer) ReadPassword() (string, error) {
cont, err := ioutil.ReadFile(f.filename)
if err != nil {
return "", err
}
var Conf struct {
Password string `json:"password"`
}
json.Unmarshal(cont, &Conf)
return Conf.Password, nil
}
var DefaultPassReader PassReader
var FilePassReader PassReader
func init() {
FilePassReader = &file_passer{path.Join(home, "pass.json")}
initDefaultPassReader()
}
|
package test
import (
"context"
"fmt"
"strings"
"testing"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/exitcode"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/filecoin-project/specs-actors/v5/actors/builtin"
"github.com/filecoin-project/specs-actors/v5/actors/builtin/miner"
"github.com/filecoin-project/specs-actors/v5/actors/builtin/power"
"github.com/filecoin-project/specs-actors/v5/actors/runtime/proof"
"github.com/filecoin-project/specs-actors/v5/actors/states"
"github.com/filecoin-project/specs-actors/v5/support/ipld"
tutil "github.com/filecoin-project/specs-actors/v5/support/testing"
vm "github.com/filecoin-project/specs-actors/v5/support/vm"
)
func TestCommitPoStFlow(t *testing.T) {
ctx := context.Background()
v := vm.NewVMWithSingletons(ctx, t, ipld.NewBlockStoreInMemory())
addrs := vm.CreateAccounts(ctx, t, v, 1, big.Mul(big.NewInt(10_000), big.NewInt(1e18)), 93837778)
minerBalance := big.Mul(big.NewInt(10_000), vm.FIL)
sealProof := abi.RegisteredSealProof_StackedDrg32GiBV1_1
// create miner
params := power.CreateMinerParams{
Owner: addrs[0],
Worker: addrs[0],
WindowPoStProofType: abi.RegisteredPoStProof_StackedDrgWindow32GiBV1,
Peer: abi.PeerID("not really a peer id"),
}
ret := vm.ApplyOk(t, v, addrs[0], builtin.StoragePowerActorAddr, minerBalance, builtin.MethodsPower.CreateMiner, ¶ms)
minerAddrs, ok := ret.(*power.CreateMinerReturn)
require.True(t, ok)
// advance vm so we can have seal randomness epoch in the past
v, err := v.WithEpoch(200)
require.NoError(t, err)
//
// precommit sector
//
sectorNumber := abi.SectorNumber(100)
sealedCid := tutil.MakeCID("100", &miner.SealedCIDPrefix)
sectorSize, err := sealProof.SectorSize()
require.NoError(t, err)
preCommitParams := miner.PreCommitSectorParams{
SealProof: sealProof,
SectorNumber: sectorNumber,
SealedCID: sealedCid,
SealRandEpoch: v.GetEpoch() - 1,
DealIDs: nil,
Expiration: v.GetEpoch() + miner.MinSectorExpiration + miner.MaxProveCommitDuration[sealProof] + 100,
}
vm.ApplyOk(t, v, addrs[0], minerAddrs.RobustAddress, big.Zero(), builtin.MethodsMiner.PreCommitSector, &preCommitParams)
// assert successful precommit invocation
vm.ExpectInvocation{
To: minerAddrs.IDAddress,
Method: builtin.MethodsMiner.PreCommitSector,
Params: vm.ExpectObject(&preCommitParams),
SubInvocations: []vm.ExpectInvocation{
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.ThisEpochReward},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.CurrentTotalPower},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.EnrollCronEvent}},
}.Matches(t, v.Invocations()[0])
balances := vm.GetMinerBalances(t, v, minerAddrs.IDAddress)
assert.True(t, balances.PreCommitDeposit.GreaterThan(big.Zero()))
// find information about precommited sector
var minerState miner.State
err = v.GetState(minerAddrs.IDAddress, &minerState)
require.NoError(t, err)
precommit, found, err := minerState.GetPrecommittedSector(v.Store(), sectorNumber)
require.NoError(t, err)
require.True(t, found)
// advance time to max seal duration
proveTime := v.GetEpoch() + miner.MaxProveCommitDuration[sealProof]
v, dlInfo := vm.AdvanceByDeadlineTillEpoch(t, v, minerAddrs.IDAddress, proveTime)
//
// overdue precommit
//
t.Run("missed prove commit results in precommit expiry", func(t *testing.T) {
// advanced one more deadline so precommit is late
tv, err := v.WithEpoch(dlInfo.Close)
require.NoError(t, err)
// run cron which should expire precommit
vm.ApplyOk(t, tv, builtin.SystemActorAddr, builtin.CronActorAddr, big.Zero(), builtin.MethodsCron.EpochTick, nil)
vm.ExpectInvocation{
To: builtin.CronActorAddr,
Method: builtin.MethodsCron.EpochTick,
SubInvocations: []vm.ExpectInvocation{
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.OnEpochTickEnd, SubInvocations: []vm.ExpectInvocation{
{To: minerAddrs.IDAddress, Method: builtin.MethodsMiner.OnDeferredCronEvent, SubInvocations: []vm.ExpectInvocation{
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.ThisEpochReward},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.CurrentTotalPower},
// The call to burnt funds indicates the overdue precommit has been penalized
{To: builtin.BurntFundsActorAddr, Method: builtin.MethodSend, Value: vm.ExpectAttoFil(precommit.PreCommitDeposit)},
// No re-enrollment of cron because burning of PCD discontinues miner cron scheduling
}},
//{To: minerAddrs.IDAddress, Method: builtin.MethodsMiner.ConfirmSectorProofsValid},
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.UpdateNetworkKPI},
}},
{To: builtin.StorageMarketActorAddr, Method: builtin.MethodsMarket.CronTick},
},
}.Matches(t, tv.Invocations()[0])
// precommit deposit has been reset
balances := vm.GetMinerBalances(t, tv, minerAddrs.IDAddress)
assert.Equal(t, big.Zero(), balances.InitialPledge)
assert.Equal(t, big.Zero(), balances.PreCommitDeposit)
// no power is added
networkStats := vm.GetNetworkStats(t, tv)
assert.Equal(t, big.Zero(), networkStats.TotalBytesCommitted)
assert.Equal(t, big.Zero(), networkStats.TotalPledgeCollateral)
assert.Equal(t, big.Zero(), networkStats.TotalRawBytePower)
assert.Equal(t, big.Zero(), networkStats.TotalQualityAdjPower)
})
//
// prove and verify
//
// Prove commit sector after max seal duration
v, err = v.WithEpoch(proveTime)
require.NoError(t, err)
proveCommitParams := miner.ProveCommitSectorParams{
SectorNumber: sectorNumber,
}
vm.ApplyOk(t, v, addrs[0], minerAddrs.RobustAddress, big.Zero(), builtin.MethodsMiner.ProveCommitSector, &proveCommitParams)
vm.ExpectInvocation{
To: minerAddrs.IDAddress,
Method: builtin.MethodsMiner.ProveCommitSector,
Params: vm.ExpectObject(&proveCommitParams),
SubInvocations: []vm.ExpectInvocation{
{To: builtin.StorageMarketActorAddr, Method: builtin.MethodsMarket.ComputeDataCommitment},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.SubmitPoRepForBulkVerify},
},
}.Matches(t, v.Invocations()[0])
// In the same epoch, trigger cron to validate prove commit
vm.ApplyOk(t, v, builtin.SystemActorAddr, builtin.CronActorAddr, big.Zero(), builtin.MethodsCron.EpochTick, nil)
vm.ExpectInvocation{
To: builtin.CronActorAddr,
Method: builtin.MethodsCron.EpochTick,
SubInvocations: []vm.ExpectInvocation{
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.OnEpochTickEnd, SubInvocations: []vm.ExpectInvocation{
// expect confirm sector proofs valid because we prove committed,
// but not an on deferred cron event because this is not a deadline boundary
{To: minerAddrs.IDAddress, Method: builtin.MethodsMiner.ConfirmSectorProofsValid, SubInvocations: []vm.ExpectInvocation{
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.ThisEpochReward},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.CurrentTotalPower},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.UpdatePledgeTotal},
}},
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.UpdateNetworkKPI},
}},
{To: builtin.StorageMarketActorAddr, Method: builtin.MethodsMarket.CronTick},
},
}.Matches(t, v.Invocations()[1])
// precommit deposit is released, ipr is added
balances = vm.GetMinerBalances(t, v, minerAddrs.IDAddress)
assert.True(t, balances.InitialPledge.GreaterThan(big.Zero()))
assert.Equal(t, big.Zero(), balances.PreCommitDeposit)
// power is unproven so network stats are unchanged
networkStats := vm.GetNetworkStats(t, v)
assert.Equal(t, big.Zero(), networkStats.TotalBytesCommitted)
assert.True(t, networkStats.TotalPledgeCollateral.GreaterThan(big.Zero()))
//
// Submit PoSt
//
// advance to proving period
dlInfo, pIdx, v := vm.AdvanceTillProvingDeadline(t, v, minerAddrs.IDAddress, sectorNumber)
err = v.GetState(minerAddrs.IDAddress, &minerState)
require.NoError(t, err)
sector, found, err := minerState.GetSector(v.Store(), sectorNumber)
require.NoError(t, err)
require.True(t, found)
t.Run("submit PoSt succeeds", func(t *testing.T) {
tv, err := v.WithEpoch(v.GetEpoch())
require.NoError(t, err)
// Submit PoSt
submitParams := miner.SubmitWindowedPoStParams{
Deadline: dlInfo.Index,
Partitions: []miner.PoStPartition{{
Index: pIdx,
Skipped: bitfield.New(),
}},
Proofs: []proof.PoStProof{{
PoStProof: abi.RegisteredPoStProof_StackedDrgWindow32GiBV1,
}},
ChainCommitEpoch: dlInfo.Challenge,
ChainCommitRand: []byte("not really random"),
}
vm.ApplyOk(t, tv, addrs[0], minerAddrs.RobustAddress, big.Zero(), builtin.MethodsMiner.SubmitWindowedPoSt, &submitParams)
sectorPower := miner.PowerForSector(sectorSize, sector)
updatePowerParams := &power.UpdateClaimedPowerParams{
RawByteDelta: sectorPower.Raw,
QualityAdjustedDelta: sectorPower.QA,
}
vm.ExpectInvocation{
To: minerAddrs.IDAddress,
Method: builtin.MethodsMiner.SubmitWindowedPoSt,
Params: vm.ExpectObject(&submitParams),
SubInvocations: []vm.ExpectInvocation{
// This call to the power actor indicates power has been added for the sector
{
To: builtin.StoragePowerActorAddr,
Method: builtin.MethodsPower.UpdateClaimedPower,
Params: vm.ExpectObject(updatePowerParams),
},
},
}.Matches(t, tv.Invocations()[0])
// miner still has initial pledge
balances = vm.GetMinerBalances(t, tv, minerAddrs.IDAddress)
assert.True(t, balances.InitialPledge.GreaterThan(big.Zero()))
// committed bytes are added (miner would have gained power if minimum requirement were met)
networkStats := vm.GetNetworkStats(t, tv)
assert.Equal(t, big.NewInt(int64(sectorSize)), networkStats.TotalBytesCommitted)
assert.True(t, networkStats.TotalPledgeCollateral.GreaterThan(big.Zero()))
// Trigger cron to keep reward accounting correct
vm.ApplyOk(t, tv, builtin.SystemActorAddr, builtin.CronActorAddr, big.Zero(), builtin.MethodsCron.EpochTick, nil)
stateTree, err := tv.GetStateTree()
require.NoError(t, err)
totalBalance, err := tv.GetTotalActorBalance()
require.NoError(t, err)
acc, err := states.CheckStateInvariants(stateTree, totalBalance, tv.GetEpoch())
require.NoError(t, err)
assert.True(t, acc.IsEmpty(), strings.Join(acc.Messages(), "\n"))
})
t.Run("skip sector", func(t *testing.T) {
tv, err := v.WithEpoch(v.GetEpoch())
require.NoError(t, err)
// Submit PoSt
submitParams := miner.SubmitWindowedPoStParams{
Deadline: dlInfo.Index,
Partitions: []miner.PoStPartition{{
Index: pIdx,
Skipped: bitfield.NewFromSet([]uint64{uint64(sectorNumber)}),
}},
Proofs: []proof.PoStProof{{
PoStProof: abi.RegisteredPoStProof_StackedDrgWindow32GiBV1,
}},
ChainCommitEpoch: dlInfo.Challenge,
ChainCommitRand: []byte("not really random"),
}
// PoSt is rejected for skipping all sectors.
_, code := tv.ApplyMessage(addrs[0], minerAddrs.RobustAddress, big.Zero(), builtin.MethodsMiner.SubmitWindowedPoSt, &submitParams)
assert.Equal(t, exitcode.ErrIllegalArgument, code)
vm.ExpectInvocation{
To: minerAddrs.IDAddress,
Method: builtin.MethodsMiner.SubmitWindowedPoSt,
Params: vm.ExpectObject(&submitParams),
Exitcode: exitcode.ErrIllegalArgument,
}.Matches(t, tv.Invocations()[0])
// miner still has initial pledge
balances = vm.GetMinerBalances(t, v, minerAddrs.IDAddress)
assert.True(t, balances.InitialPledge.GreaterThan(big.Zero()))
// network power is unchanged
networkStats := vm.GetNetworkStats(t, tv)
assert.Equal(t, big.Zero(), networkStats.TotalBytesCommitted)
assert.True(t, networkStats.TotalPledgeCollateral.GreaterThan(big.Zero()))
})
t.Run("missed first PoSt deadline", func(t *testing.T) {
// move to proving period end
tv, err := v.WithEpoch(dlInfo.Last())
require.NoError(t, err)
// Run cron to detect missing PoSt
vm.ApplyOk(t, tv, builtin.SystemActorAddr, builtin.CronActorAddr, big.Zero(), builtin.MethodsCron.EpochTick, nil)
vm.ExpectInvocation{
To: builtin.CronActorAddr,
Method: builtin.MethodsCron.EpochTick,
SubInvocations: []vm.ExpectInvocation{
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.OnEpochTickEnd, SubInvocations: []vm.ExpectInvocation{
{To: minerAddrs.IDAddress, Method: builtin.MethodsMiner.OnDeferredCronEvent, SubInvocations: []vm.ExpectInvocation{
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.ThisEpochReward},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.CurrentTotalPower},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.EnrollCronEvent},
}},
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.UpdateNetworkKPI},
}},
{To: builtin.StorageMarketActorAddr, Method: builtin.MethodsMarket.CronTick},
},
}.Matches(t, tv.Invocations()[0])
// network power is unchanged
networkStats := vm.GetNetworkStats(t, tv)
assert.Equal(t, big.Zero(), networkStats.TotalBytesCommitted)
assert.True(t, networkStats.TotalPledgeCollateral.GreaterThan(big.Zero()))
})
}
func preCommitSectors(t *testing.T, v *vm.VM, batchSize int, worker, mAddr address.Address, sealProof abi.RegisteredSealProof) ([]abi.SectorNumber, []*miner.SectorPreCommitOnChainInfo) {
sectorNumberBase := 100
precommits := make([]*miner.SectorPreCommitOnChainInfo, 0)
sectorNumbers := make([]abi.SectorNumber, 0)
invocsCommon := []vm.ExpectInvocation{
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.ThisEpochReward},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.CurrentTotalPower},
}
invocsFirst := append(invocsCommon, vm.ExpectInvocation{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.EnrollCronEvent})
for i := 0; i <= batchSize-1; i++ {
sectorNumber := abi.SectorNumber(sectorNumberBase + i)
sealedCid := tutil.MakeCID(fmt.Sprintf("%d", sectorNumber), &miner.SealedCIDPrefix)
preCommitParams := miner.PreCommitSectorParams{
SealProof: sealProof,
SectorNumber: sectorNumber,
SealedCID: sealedCid,
SealRandEpoch: v.GetEpoch() - 1,
DealIDs: nil,
Expiration: v.GetEpoch() + miner.MinSectorExpiration + miner.MaxProveCommitDuration[sealProof] + 100,
}
vm.ApplyOk(t, v, worker, mAddr, big.Zero(), builtin.MethodsMiner.PreCommitSector, &preCommitParams)
invocs := invocsCommon
if i == 0 {
invocs = invocsFirst
}
// assert successful precommit invocation
vm.ExpectInvocation{
To: mAddr,
Method: builtin.MethodsMiner.PreCommitSector,
Params: vm.ExpectObject(&preCommitParams),
SubInvocations: invocs,
}.Matches(t, v.Invocations()[i])
// find information about precommited sector
var minerState miner.State
err := v.GetState(mAddr, &minerState)
require.NoError(t, err)
precommit, found, err := minerState.GetPrecommittedSector(v.Store(), sectorNumber)
require.NoError(t, err)
require.True(t, found)
precommits = append(precommits, precommit)
sectorNumbers = append(sectorNumbers, sectorNumber)
}
return sectorNumbers, precommits
}
func TestMeasurePoRepGas(t *testing.T) {
batchSize := 819
fmt.Printf("Batch Size = %d\n", batchSize)
printPoRepMsgGas(batchSize)
ctx := context.Background()
blkStore := ipld.NewBlockStoreInMemory()
metrics := ipld.NewMetricsBlockStore(blkStore)
v := vm.NewVMWithSingletons(ctx, t, metrics)
v.SetStatsSource(metrics)
addrs := vm.CreateAccounts(ctx, t, v, 1, big.Mul(big.NewInt(10_000), big.NewInt(1e18)), 93837778)
minerBalance := big.Mul(big.NewInt(10_000), vm.FIL)
sealProof := abi.RegisteredSealProof_StackedDrg32GiBV1_1
// create miner
params := power.CreateMinerParams{
Owner: addrs[0],
Worker: addrs[0],
WindowPoStProofType: abi.RegisteredPoStProof_StackedDrgWindow32GiBV1,
Peer: abi.PeerID("not really a peer id"),
}
ret := vm.ApplyOk(t, v, addrs[0], builtin.StoragePowerActorAddr, minerBalance, builtin.MethodsPower.CreateMiner, ¶ms)
minerAddrs, ok := ret.(*power.CreateMinerReturn)
require.True(t, ok)
// advance vm so we can have seal randomness epoch in the past
v, err := v.WithEpoch(abi.ChainEpoch(200))
require.NoError(t, err)
//
// precommit sectors
//
sectorNumbers, _ := preCommitSectors(t, v, batchSize, addrs[0], minerAddrs.IDAddress, sealProof)
balances := vm.GetMinerBalances(t, v, minerAddrs.IDAddress)
assert.True(t, balances.PreCommitDeposit.GreaterThan(big.Zero()))
// advance time to max seal duration
proveTime := v.GetEpoch() + miner.MaxProveCommitDuration[sealProof]
v, _ = vm.AdvanceByDeadlineTillEpoch(t, v, minerAddrs.IDAddress, proveTime)
//
// prove and verify
//
v, err = v.WithEpoch(proveTime)
require.NoError(t, err)
for i := 0; i <= batchSize-1; i++ {
// Prove commit sector after max seal duration
proveCommitParams := miner.ProveCommitSectorParams{
SectorNumber: sectorNumbers[i],
}
vm.ApplyOk(t, v, addrs[0], minerAddrs.RobustAddress, big.Zero(), builtin.MethodsMiner.ProveCommitSector, &proveCommitParams)
vm.ExpectInvocation{
To: minerAddrs.IDAddress,
Method: builtin.MethodsMiner.ProveCommitSector,
Params: vm.ExpectObject(&proveCommitParams),
SubInvocations: []vm.ExpectInvocation{
{To: builtin.StorageMarketActorAddr, Method: builtin.MethodsMarket.ComputeDataCommitment},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.SubmitPoRepForBulkVerify},
},
}.Matches(t, v.Invocations()[i])
}
proveCommitKey := vm.MethodKey{Code: builtin.StorageMinerActorCodeID, Method: builtin.MethodsMiner.ProveCommitSector}
stats := v.GetCallStats()
printCallStats(proveCommitKey, stats[proveCommitKey], "\n")
// In the same epoch, trigger cron to validate prove commits
vm.ApplyOk(t, v, builtin.SystemActorAddr, builtin.CronActorAddr, big.Zero(), builtin.MethodsCron.EpochTick, nil)
cronKey := vm.MethodKey{Code: builtin.CronActorCodeID, Method: builtin.MethodsCron.EpochTick}
stats = v.GetCallStats()
printCallStats(cronKey, stats[cronKey], "\n")
vm.ExpectInvocation{
To: builtin.CronActorAddr,
Method: builtin.MethodsCron.EpochTick,
SubInvocations: []vm.ExpectInvocation{
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.OnEpochTickEnd, SubInvocations: []vm.ExpectInvocation{
// expect confirm sector proofs valid because we prove committed,
// but not an on deferred cron event because this is not a deadline boundary
{To: minerAddrs.IDAddress, Method: builtin.MethodsMiner.ConfirmSectorProofsValid, SubInvocations: []vm.ExpectInvocation{
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.ThisEpochReward},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.CurrentTotalPower},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.UpdatePledgeTotal},
}},
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.UpdateNetworkKPI},
}},
{To: builtin.StorageMarketActorAddr, Method: builtin.MethodsMarket.CronTick},
},
}.Matches(t, v.Invocations()[batchSize])
// precommit deposit is released, ipr is added
balances = vm.GetMinerBalances(t, v, minerAddrs.IDAddress)
assert.True(t, balances.InitialPledge.GreaterThan(big.Zero()))
assert.Equal(t, big.Zero(), balances.PreCommitDeposit)
// power is unproven so network stats are unchanged
networkStats := vm.GetNetworkStats(t, v)
assert.Equal(t, big.Zero(), networkStats.TotalBytesCommitted)
assert.True(t, networkStats.TotalPledgeCollateral.GreaterThan(big.Zero()))
}
func TestMeasureAggregatePorepGas(t *testing.T) {
batchSize := 200
fmt.Printf("batch size = %d\n", batchSize)
ctx := context.Background()
blkStore := ipld.NewBlockStoreInMemory()
metrics := ipld.NewMetricsBlockStore(blkStore)
v := vm.NewVMWithSingletons(ctx, t, metrics)
v.SetStatsSource(metrics)
addrs := vm.CreateAccounts(ctx, t, v, 1, big.Mul(big.NewInt(10_000), big.NewInt(1e18)), 93837778)
minerBalance := big.Mul(big.NewInt(10_000), vm.FIL)
sealProof := abi.RegisteredSealProof_StackedDrg32GiBV1_1
// create miner
params := power.CreateMinerParams{
Owner: addrs[0],
Worker: addrs[0],
WindowPoStProofType: abi.RegisteredPoStProof_StackedDrgWindow32GiBV1,
Peer: abi.PeerID("not really a peer id"),
}
ret := vm.ApplyOk(t, v, addrs[0], builtin.StoragePowerActorAddr, minerBalance, builtin.MethodsPower.CreateMiner, ¶ms)
minerAddrs, ok := ret.(*power.CreateMinerReturn)
require.True(t, ok)
// advance vm so we can have seal randomness epoch in the past
v, err := v.WithEpoch(abi.ChainEpoch(200))
require.NoError(t, err)
//
// precommit sectors
//
sectorNumbers, _ := preCommitSectors(t, v, batchSize, addrs[0], minerAddrs.IDAddress, sealProof)
balances := vm.GetMinerBalances(t, v, minerAddrs.IDAddress)
assert.True(t, balances.PreCommitDeposit.GreaterThan(big.Zero()))
// advance time to max seal duration
proveTime := v.GetEpoch() + miner.MaxProveCommitDuration[sealProof]
v, _ = vm.AdvanceByDeadlineTillEpoch(t, v, minerAddrs.IDAddress, proveTime)
//
// prove and verify
//
v, err = v.WithEpoch(proveTime)
require.NoError(t, err)
intSectorNumbers := make([]uint64, len(sectorNumbers))
for i := range sectorNumbers {
intSectorNumbers[i] = uint64(sectorNumbers[i])
}
sectorNosBf := bitfield.NewFromSet(intSectorNumbers)
proveCommitAggregateParams := miner.ProveCommitAggregateParams{
SectorNumbers: sectorNosBf,
}
vm.ApplyOk(t, v, addrs[0], minerAddrs.RobustAddress, big.Zero(), builtin.MethodsMiner.ProveCommitAggregate, &proveCommitAggregateParams)
vm.ExpectInvocation{
To: minerAddrs.IDAddress,
Method: builtin.MethodsMiner.ProveCommitAggregate,
Params: vm.ExpectObject(&proveCommitAggregateParams),
SubInvocations: []vm.ExpectInvocation{
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.CallerHasClaim},
{To: builtin.StorageMarketActorAddr, Method: builtin.MethodsMarket.ComputeDataCommitment},
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.ThisEpochReward},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.CurrentTotalPower},
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.UpdatePledgeTotal},
},
}.Matches(t, v.Invocations()[0])
proveCommitAggrKey := vm.MethodKey{Code: builtin.StorageMinerActorCodeID, Method: builtin.MethodsMiner.ProveCommitAggregate}
stats := v.GetCallStats()
printCallStats(proveCommitAggrKey, stats[proveCommitAggrKey], "\n")
// In the same epoch, trigger cron to
vm.ApplyOk(t, v, builtin.SystemActorAddr, builtin.CronActorAddr, big.Zero(), builtin.MethodsCron.EpochTick, nil)
cronKey := vm.MethodKey{Code: builtin.CronActorCodeID, Method: builtin.MethodsCron.EpochTick}
stats = v.GetCallStats()
printCallStats(cronKey, stats[cronKey], "\n")
vm.ExpectInvocation{
To: builtin.CronActorAddr,
Method: builtin.MethodsCron.EpochTick,
SubInvocations: []vm.ExpectInvocation{
{To: builtin.StoragePowerActorAddr, Method: builtin.MethodsPower.OnEpochTickEnd, SubInvocations: []vm.ExpectInvocation{
// expect no confirm sector proofs valid because we prove committed with aggregation.
// expect no on deferred cron event because this is not a deadline boundary
{To: builtin.RewardActorAddr, Method: builtin.MethodsReward.UpdateNetworkKPI},
}},
{To: builtin.StorageMarketActorAddr, Method: builtin.MethodsMarket.CronTick},
},
}.Matches(t, v.Invocations()[1])
// precommit deposit is released, ipr is added
balances = vm.GetMinerBalances(t, v, minerAddrs.IDAddress)
assert.True(t, balances.InitialPledge.GreaterThan(big.Zero()))
assert.Equal(t, big.Zero(), balances.PreCommitDeposit)
// power is unproven so network stats are unchanged
networkStats := vm.GetNetworkStats(t, v)
assert.Equal(t, big.Zero(), networkStats.TotalBytesCommitted)
assert.True(t, networkStats.TotalPledgeCollateral.GreaterThan(big.Zero()))
}
func printCallStats(method vm.MethodKey, stats *vm.CallStats, indent string) { // nolint:unused
fmt.Printf("%s%v:%d: calls: %d gets: %d puts: %d read: %d written: %d avg gets: %.2f, avg puts: %.2f\n",
indent, builtin.ActorNameByCode(method.Code), method.Method, stats.Calls, stats.Reads, stats.Writes,
stats.ReadBytes, stats.WriteBytes, float32(stats.Reads)/float32(stats.Calls),
float32(stats.Writes)/float32(stats.Calls))
gasGetObj := uint64(75242)
gasPutObj := uint64(84070)
gasPutPerByte := uint64(1)
gasStorageMultiplier := uint64(1300)
gasPerCall := uint64(29233)
ipldGas := stats.Reads*gasGetObj + stats.Writes*gasPutObj + stats.WriteBytes*gasPutPerByte*gasStorageMultiplier
callGas := stats.Calls * gasPerCall
fmt.Printf("%v:%d: ipld gas=%d call gas=%d\n", builtin.ActorNameByCode(method.Code), method.Method, ipldGas, callGas)
if stats.SubStats == nil {
return
}
for m, s := range stats.SubStats {
printCallStats(m, s, indent+" ")
}
}
func printPoRepMsgGas(batchSize int) {
// Ignore message fields and sector number bytes for both.
// Ignoring non-parma message fields under estimates both by the same amount
// Ignoring sector numbers/bitfields underestimates current porep compared to aggregate
// which is the right direction for finding a starting bound (we can optimize later)
onChainMessageComputeBase := 38863
onChainMessageStorageBase := 36
onChainMessageStoragePerByte := 1
storageGasMultiplier := 1300
msgBytes := 1920
msgGas := onChainMessageComputeBase + (onChainMessageStorageBase+onChainMessageStoragePerByte*msgBytes)*storageGasMultiplier
allMsgsGas := batchSize * msgGas
fmt.Printf("%d batchsize: all proof param byte gas: %d\n", batchSize, allMsgsGas)
}
|
package client
import (
"fmt"
"github.com/MagalixTechnologies/core/logger"
"runtime"
)
// Recover recover from panic used to send logs before exiting
func (client *Client) Recover() {
tears := recover()
if tears == nil {
return
}
message := fmt.Sprintf(
"PANIC OCCURRED: %v\n%s\n", tears, string(stackTrace()),
)
logger.Fatal(message)
}
func stackTrace() []byte {
buffer := make([]byte, 1024)
for {
stack := runtime.Stack(buffer, true)
if stack < len(buffer) {
return buffer[:stack]
}
buffer = make([]byte, 2*len(buffer))
}
}
|
package server
import (
"fmt"
"os"
"os/exec"
"github.com/marcomilon/ezphp/internals/output"
)
type Args struct {
Php string
Host string
Public string
}
func Run(args Args) {
output.Info("Command: " + args.Php + " -S " + args.Host + " -t " + args.Public + "\n")
output.Info("Your server url is: " + "http://" + args.Host + "\n\n")
cmd := exec.Command(args.Php, "-S", args.Host, "-t", args.Public)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
output.Error("Unable to execute PHP: " + err.Error() + "\n")
output.Error("php require to have the Visual C++ Redistributable for Visual Studio 2017\n")
output.Error("Download Visual C++ from here: https://www.microsoft.com/en-us/download/details.aspx?id=48145\n")
output.Error("Press Enter to exit... ")
fmt.Scanln()
}
}
|
package postedition
import "time"
//PostPub is post what will be publiched and displayable
type PostPub struct {
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Body string `json:"body"`
Nick string `json:"nick"`
Avatar string `json:"avatar"`
Likes int `json:"likes"`
LastComment string `json:"lastcomment"`
UserID string `json:"userid"`
Hasattach bool `json:"hasattach"`
Images []string `json:"images"`
CreatedAt time.Time `json:"createdat"`
}
|
package leetcode
import (
"container/list"
"fmt"
)
type trap struct{}
// TODO 暴力
// TODO 哈希
// TODO 双指针
// 栈
func (t trap) Do(height []int) int {
stack := list.New()
stack.PushBack(0)
var ret int
for i := 1; i < len(height); i++ {
if height[i] > height[i-1] {
for stack.Len() != 0 {
last := stack.Back()
leftI := last.Value.(int)
if height[leftI] >= height[i] {
break
}
stack.Remove(last)
if stack.Len() == 0 {
break
}
ret += (min(height[i], height[stack.Back().Value.(int)]) - height[leftI]) * (i - 1 - stack.Back().Value.(int))
fmt.Println(ret, leftI, i)
}
}
stack.PushBack(i)
}
return ret
}
|
package main
import (
"fmt"
"os"
"gopkg.in/mgo.v2"
)
type Mongo struct {
host string
port string
user string
pass string
dbname string
session *mgo.Session
db *mgo.Database
}
var (
mongodbServer string = os.Getenv("MONGODB_HOST") //"dds-2ze087e692f063041.mongodb.rds.aliyuncs.com"
mongodbPort string = os.Getenv("MONGODB_PORT")
mongodbName string = "call_center"
mongodbUser string = os.Getenv("MONGODB_USER")
mongodbPass string = os.Getenv("MONGODB_PWD")
mongodbPoolSize int = 300
)
func NewMongoClient() *Mongo {
return &Mongo{
host: mongodbServer,
port: mongodbPort,
user: mongodbUser,
pass: mongodbPass,
dbname: mongodbName,
}
}
func (this *Mongo) Connect() error {
url := fmt.Sprintf("%s:%s", this.host, this.port)
session, err := mgo.Dial(url)
if err != nil {
return err
}
session.SetMode(mgo.Monotonic, true)
session.SetPoolLimit(mongodbPoolSize)
this.session = session
this.db = session.DB(this.dbname)
admdb := session.DB("admin")
err = admdb.Login(this.user, this.pass)
return err
}
func (this *Mongo) Add(coll string, data ...interface{}) error {
return this.db.C(coll).Insert(data...)
}
func (this *Mongo) Find(coll string, query interface{}) *mgo.Query {
return this.db.C(coll).Find(query)
}
func (this *Mongo) Update(coll string, query interface{}, data interface{}) error {
return this.db.C(coll).Update(query, data)
}
func (this *Mongo) Remove(coll string, query interface{}) error {
return this.db.C(coll).Remove(query)
}
func (this *Mongo) Close() {
this.session.Close()
}
|
// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package multivaluedindex
import (
"context"
"fmt"
"testing"
"github.com/pingcap/tidb/errno"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/sessiontxn"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/testkit"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/codec"
"github.com/stretchr/testify/require"
)
func TestMultiValuedIndexDDL(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("USE test;")
tk.MustExec("create table t(a json);")
tk.MustGetErrCode("select cast(a as signed array) from t", errno.ErrNotSupportedYet)
tk.MustGetErrCode("select json_extract(cast(a as signed array), '$[0]') from t", errno.ErrNotSupportedYet)
tk.MustGetErrCode("select * from t where cast(a as signed array)", errno.ErrNotSupportedYet)
tk.MustGetErrCode("select cast('[1,2,3]' as unsigned array);", errno.ErrNotSupportedYet)
tk.MustExec("drop table t")
tk.MustGetErrCode("CREATE TABLE t(x INT, KEY k ((1 AND CAST(JSON_ARRAY(x) AS UNSIGNED ARRAY))));", errno.ErrNotSupportedYet)
tk.MustGetErrCode("CREATE TABLE t1 (f1 json, key mvi((cast(cast(f1 as unsigned array) as unsigned array))));", errno.ErrNotSupportedYet)
tk.MustGetErrCode("CREATE TABLE t1 (f1 json, primary key mvi((cast(cast(f1 as unsigned array) as unsigned array))));", errno.ErrNotSupportedYet)
tk.MustGetErrCode("CREATE TABLE t1 (f1 json, key mvi((cast(f1->>'$[*]' as unsigned array))));", errno.ErrInvalidTypeForJSON)
tk.MustGetErrCode("CREATE TABLE t1 (f1 json, key mvi((cast(f1->'$[*]' as year array))));", errno.ErrNotSupportedYet)
tk.MustGetErrCode("CREATE TABLE t1 (f1 json, key mvi((cast(f1->'$[*]' as json array))));", errno.ErrNotSupportedYet)
tk.MustGetErrCode("CREATE TABLE t1 (f1 json, key mvi((cast(f1->'$[*]' as char(10) charset gbk array))));", errno.ErrNotSupportedYet)
tk.MustGetErrCode("create table t(j json, gc json as ((concat(cast(j->'$[*]' as unsigned array),\"x\"))));", errno.ErrNotSupportedYet)
tk.MustGetErrCode("create table t(j json, gc json as (cast(j->'$[*]' as unsigned array)));", errno.ErrNotSupportedYet)
tk.MustGetErrCode(`create table t1(j json, key i1((cast(j->"$" as char array))));`, errno.ErrNotSupportedYet)
tk.MustGetErrCode(`create table t1(j json, key i1((cast(j->"$" as binary array))));`, errno.ErrNotSupportedYet)
tk.MustGetErrCode(`create table t1(j json, key i1((cast(j->"$" as float array))));`, errno.ErrNotSupportedYet)
tk.MustGetErrCode(`create table t1(j json, key i1((cast(j->"$" as decimal(4,2) array))));`, errno.ErrNotSupportedYet)
tk.MustGetErrCode("create view v as select cast('[1,2,3]' as unsigned array);", errno.ErrNotSupportedYet)
tk.MustExec("create table t(a json, index idx((cast(a as signed array))));")
tk.MustExec("drop table t;")
tk.MustExec("create table t(a json, index idx(((cast(a as signed array)))))")
tk.MustExec("drop table t;")
tk.MustExec(`create table t(j json, key i1((cast(j->"$" as double array))));`)
tk.MustExec("drop table t")
tk.MustGetErrCode("create table t(a json, b int, index idx(b, (cast(a as signed array)), (cast(a as signed array))));", errno.ErrNotSupportedYet)
tk.MustExec("create table t(a json, b int);")
tk.MustGetErrCode("create index idx on t (b, (cast(a as signed array)), (cast(a as signed array)))", errno.ErrNotSupportedYet)
tk.MustGetErrCode("alter table t add index idx(b, (cast(a as signed array)), (cast(a as signed array)))", errno.ErrNotSupportedYet)
tk.MustExec("create index idx1 on t (b, (cast(a as signed array)))")
tk.MustExec("alter table t add index idx2(b, (cast(a as signed array)))")
tk.MustExec("drop table t")
tk.MustExec("create table t(a json, b int, index idx3(b, (cast(a as signed array))));")
tk.MustExec("drop table t")
tk.MustExec("set names gbk")
tk.MustExec("create table t(a json, b int, index idx3(b, (cast(a as char(10) array))));")
tk.MustExec("CREATE TABLE users (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, doc JSON);")
tk.MustExecToErr("CREATE TABLE t (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, doc JSON, FOREIGN KEY fk_user_id ((cast(doc->'$[*]' as signed array))) REFERENCES users(id));")
}
func TestMultiValuedIndexDML(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("USE test;")
mode := []string{`''`, `default`}
for _, m := range mode {
tk.MustExec(fmt.Sprintf("set @@sql_mode=%s", m))
tk.MustExec(`drop table if exists t;`)
tk.MustExec(`create table t(a json, index idx((cast(a as unsigned array))));`)
tk.MustExec(`insert into t values ('[1,2,3]');`)
tk.MustGetErrCode(`insert into t values ('[-1]');`, errno.ErrDataOutOfRangeFunctionalIndex)
tk.MustGetErrCode(`insert into t values ('["1"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["a"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["汉字"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.2]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.0]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("11:00:00" as time)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02" as date)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02 11:00:00" as datetime)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast('{"a":1}' as json)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`drop table if exists t;`)
tk.MustExec(`create table t(a json, index idx((cast(a as signed array))));`)
tk.MustExec(`insert into t values ('[1,2,3]');`)
tk.MustExec(`insert into t values ('[-1]');`)
tk.MustGetErrCode(`insert into t values ('["1"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["a"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["汉字"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.2]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.0]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("11:00:00" as time)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02" as date)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02 11:00:00" as datetime)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast('{"a":1}' as json)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`drop table if exists t;`)
tk.MustExec(`create table t(a json, index idx((cast(a as char(1) array))));`)
tk.MustGetErrCode(`insert into t values ('[1,2,3]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[-1]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`insert into t values ('["1"]');`)
tk.MustExec(`insert into t values ('["a"]');`)
tk.MustGetErrCode(`insert into t values ('["汉字"]');`, errno.ErrFunctionalIndexDataIsTooLong)
tk.MustGetErrCode(`insert into t values ('[1.2]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.0]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("11:00:00" as time)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02" as date)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02 11:00:00" as datetime)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast('{"a":1}' as json)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`drop table if exists t;`)
tk.MustExec(`create table t(a json, index idx((cast(a as char(2) array))));`)
tk.MustGetErrCode(`insert into t values ('[1,2,3]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[-1]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`insert into t values ('["1"]');`)
tk.MustExec(`insert into t values ('["a"]');`)
tk.MustExec(`insert into t values ('["汉字"]');`)
tk.MustGetErrCode(`insert into t values ('[1.2]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.0]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("11:00:00" as time)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02" as date)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02 11:00:00" as datetime)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast('{"a":1}' as json)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`drop table if exists t;`)
tk.MustExec(`create table t(a json, index idx((cast(a as binary(1) array))));`)
tk.MustGetErrCode(`insert into t values ('[1,2,3]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[-1]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`insert into t values ('["1"]');`)
tk.MustExec(`insert into t values ('["a"]');`)
tk.MustGetErrCode(`insert into t values ('["汉字"]');`, errno.ErrFunctionalIndexDataIsTooLong)
tk.MustGetErrCode(`insert into t values ('[1.2]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.0]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("11:00:00" as time)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02" as date)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02 11:00:00" as datetime)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast('{"a":1}' as json)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`drop table if exists t;`)
tk.MustExec(`create table t(a json, index idx((cast(a as binary(2) array))));`)
tk.MustGetErrCode(`insert into t values ('[1,2,3]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[-1]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`insert into t values ('["1"]');`)
tk.MustExec(`insert into t values ('["a"]');`)
tk.MustGetErrCode(`insert into t values ('["汉字"]');`, errno.ErrFunctionalIndexDataIsTooLong)
tk.MustGetErrCode(`insert into t values ('[1.2]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.0]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("11:00:00" as time)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02" as date)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02 11:00:00" as datetime)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast('{"a":1}' as json)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`drop table if exists t;`)
tk.MustExec(`create table t(a json, index idx((cast(a as date array))));`)
tk.MustGetErrCode(`insert into t values ('[1,2,3]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[-1]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["1"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["a"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["汉字"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.2]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.0]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("11:00:00" as time)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`insert into t values (json_array(cast("2022-02-02" as date)));`)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02 11:00:00" as datetime)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast('{"a":1}' as json)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`drop table if exists t;`)
tk.MustExec(`create table t(a json, index idx((cast(a as time array))));`)
tk.MustGetErrCode(`insert into t values ('[1,2,3]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[-1]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["1"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["a"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["汉字"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.2]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.0]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`insert into t values (json_array(cast("11:00:00" as time)));`)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02" as date)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02 11:00:00" as datetime)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast('{"a":1}' as json)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`drop table if exists t;`)
tk.MustExec(`create table t(a json, index idx((cast(a as datetime array))));`)
tk.MustGetErrCode(`insert into t values ('[1,2,3]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[-1]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["1"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["a"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["汉字"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.2]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('[1.0]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("11:00:00" as time)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02" as date)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`insert into t values (json_array(cast("2022-02-02 11:00:00" as datetime)));`)
tk.MustGetErrCode(`insert into t values (json_array(cast('{"a":1}' as json)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`drop table if exists t;`)
tk.MustExec(`create table t(a json, index idx((cast(a as double array))));`)
tk.MustExec(`insert into t values ('[1,2,3]');`)
tk.MustExec(`insert into t values ('[-1]');`)
tk.MustGetErrCode(`insert into t values ('["1"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["a"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values ('["汉字"]');`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustExec(`insert into t values ('[1.2]');`)
tk.MustExec(`insert into t values ('[1.0]');`)
tk.MustGetErrCode(`insert into t values (json_array(cast("11:00:00" as time)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02" as date)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast("2022-02-02 11:00:00" as datetime)));`, errno.ErrInvalidJSONValueForFuncIndex)
tk.MustGetErrCode(`insert into t values (json_array(cast('{"a":1}' as json)));`, errno.ErrInvalidJSONValueForFuncIndex)
}
}
func TestWriteMultiValuedIndex(t *testing.T) {
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("create table t1(pk int primary key, a json, index idx((cast(a as signed array))))")
tk.MustExec("insert into t1 values (1, '[1,2,2,3]')")
tk.MustExec("insert into t1 values (2, '[1,2,3]')")
tk.MustExec("insert into t1 values (3, '[]')")
tk.MustExec("insert into t1 values (4, '[2,3,4]')")
tk.MustExec("insert into t1 values (5, null)")
tk.MustExec("insert into t1 values (6, '1')")
t1, err := dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
require.NoError(t, err)
for _, index := range t1.Indices() {
if index.Meta().MVIndex {
checkCount(t, t1.IndexPrefix(), index, store, 11)
checkKey(t, t1.IndexPrefix(), index, store, [][]types.Datum{
{types.NewDatum(nil), types.NewIntDatum(5)},
{types.NewIntDatum(1), types.NewIntDatum(1)},
{types.NewIntDatum(1), types.NewIntDatum(2)},
{types.NewIntDatum(1), types.NewIntDatum(6)},
{types.NewIntDatum(2), types.NewIntDatum(1)},
{types.NewIntDatum(2), types.NewIntDatum(2)},
{types.NewIntDatum(2), types.NewIntDatum(4)},
{types.NewIntDatum(3), types.NewIntDatum(1)},
{types.NewIntDatum(3), types.NewIntDatum(2)},
{types.NewIntDatum(3), types.NewIntDatum(4)},
{types.NewIntDatum(4), types.NewIntDatum(4)},
})
}
}
tk.MustExec("delete from t1")
for _, index := range t1.Indices() {
if index.Meta().MVIndex {
checkCount(t, t1.IndexPrefix(), index, store, 0)
}
}
tk.MustExec("drop table t1")
tk.MustExec("create table t1(pk int primary key, a json, index idx((cast(a as char(5) array))))")
tk.MustExec("insert into t1 values (1, '[\"abc\", \"abc \"]')")
tk.MustExec("insert into t1 values (2, '[\"b\"]')")
tk.MustExec("insert into t1 values (3, '[\"b \"]')")
tk.MustQuery("select pk from t1 where 'b ' member of (a)").Check(testkit.Rows("3"))
t1, err = dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
require.NoError(t, err)
for _, index := range t1.Indices() {
if index.Meta().MVIndex {
checkCount(t, t1.IndexPrefix(), index, store, 4)
checkKey(t, t1.IndexPrefix(), index, store, [][]types.Datum{
{types.NewBytesDatum([]byte("abc")), types.NewIntDatum(1)},
{types.NewBytesDatum([]byte("abc ")), types.NewIntDatum(1)},
{types.NewBytesDatum([]byte("b")), types.NewIntDatum(2)},
{types.NewBytesDatum([]byte("b ")), types.NewIntDatum(3)},
})
}
}
tk.MustExec("update t1 set a = json_array_append(a, '$', 'bcd') where pk = 1")
tk.MustExec("update t1 set a = '[]' where pk = 2")
tk.MustExec("update t1 set a = '[\"abc\"]' where pk = 3")
for _, index := range t1.Indices() {
if index.Meta().MVIndex {
checkCount(t, t1.IndexPrefix(), index, store, 4)
checkKey(t, t1.IndexPrefix(), index, store, [][]types.Datum{
{types.NewBytesDatum([]byte("abc")), types.NewIntDatum(1)},
{types.NewBytesDatum([]byte("abc")), types.NewIntDatum(3)},
{types.NewBytesDatum([]byte("abc ")), types.NewIntDatum(1)},
{types.NewBytesDatum([]byte("bcd")), types.NewIntDatum(1)},
})
}
}
tk.MustExec("delete from t1")
for _, index := range t1.Indices() {
if index.Meta().MVIndex {
checkCount(t, t1.IndexPrefix(), index, store, 0)
}
}
tk.MustExec("drop table t1")
tk.MustExec("create table t1(pk int primary key, a json, index idx((cast(a as unsigned array))))")
tk.MustExec("insert into t1 values (1, '[1,2,2,3]')")
tk.MustExec("insert into t1 values (2, '[1,2,3]')")
tk.MustExec("insert into t1 values (3, '[]')")
tk.MustExec("insert into t1 values (4, '[2,3,4]')")
tk.MustExec("insert into t1 values (5, null)")
tk.MustExec("insert into t1 values (6, '1')")
t1, err = dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
require.NoError(t, err)
for _, index := range t1.Indices() {
if index.Meta().MVIndex {
checkCount(t, t1.IndexPrefix(), index, store, 11)
checkKey(t, t1.IndexPrefix(), index, store, [][]types.Datum{
{types.NewDatum(nil), types.NewIntDatum(5)},
{types.NewUintDatum(1), types.NewIntDatum(1)},
{types.NewUintDatum(1), types.NewIntDatum(2)},
{types.NewUintDatum(1), types.NewIntDatum(6)},
{types.NewUintDatum(2), types.NewIntDatum(1)},
{types.NewUintDatum(2), types.NewIntDatum(2)},
{types.NewUintDatum(2), types.NewIntDatum(4)},
{types.NewUintDatum(3), types.NewIntDatum(1)},
{types.NewUintDatum(3), types.NewIntDatum(2)},
{types.NewUintDatum(3), types.NewIntDatum(4)},
{types.NewUintDatum(4), types.NewIntDatum(4)},
})
}
}
tk.MustExec("delete from t1")
for _, index := range t1.Indices() {
if index.Meta().MVIndex {
checkCount(t, t1.IndexPrefix(), index, store, 0)
}
}
}
func TestWriteMultiValuedIndexPartitionTable(t *testing.T) {
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec(`create table t1
(
pk int primary key,
a json,
index idx ((cast(a as signed array)))
) partition by range columns (pk) (partition p0 values less than (10), partition p1 values less than (20));`)
tk.MustExec("insert into t1 values (1, '[1,2,2,3]')")
tk.MustExec("insert into t1 values (11, '[1,2,3]')")
tk.MustExec("insert into t1 values (2, '[]')")
tk.MustExec("insert into t1 values (12, '[2,3,4]')")
tk.MustExec("insert into t1 values (3, null)")
tk.MustExec("insert into t1 values (13, null)")
t1, err := dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
require.NoError(t, err)
expect := map[string]struct {
count int
vals [][]types.Datum
}{
"p0": {4, [][]types.Datum{
{types.NewDatum(nil), types.NewIntDatum(3)},
{types.NewIntDatum(1), types.NewIntDatum(1)},
{types.NewIntDatum(2), types.NewIntDatum(1)},
{types.NewIntDatum(3), types.NewIntDatum(1)},
}},
"p1": {7, [][]types.Datum{
{types.NewDatum(nil), types.NewIntDatum(13)},
{types.NewIntDatum(1), types.NewIntDatum(11)},
{types.NewIntDatum(2), types.NewIntDatum(11)},
{types.NewIntDatum(2), types.NewIntDatum(12)},
{types.NewIntDatum(3), types.NewIntDatum(11)},
{types.NewIntDatum(3), types.NewIntDatum(12)},
{types.NewIntDatum(4), types.NewIntDatum(12)},
}},
}
for _, def := range t1.Meta().GetPartitionInfo().Definitions {
partition := t1.(table.PartitionedTable).GetPartition(def.ID)
for _, index := range partition.Indices() {
if index.Meta().MVIndex {
checkCount(t, partition.IndexPrefix(), index, store, expect[def.Name.L].count)
checkKey(t, partition.IndexPrefix(), index, store, expect[def.Name.L].vals)
}
}
}
tk.MustExec("delete from t1")
for _, def := range t1.Meta().GetPartitionInfo().Definitions {
partition := t1.(table.PartitionedTable).GetPartition(def.ID)
for _, index := range partition.Indices() {
if index.Meta().MVIndex {
checkCount(t, partition.IndexPrefix(), index, store, 0)
}
}
}
}
func TestWriteMultiValuedIndexUnique(t *testing.T) {
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("create table t1(pk int primary key, a json, unique index idx((cast(a as signed array))))")
tk.MustExec("insert into t1 values (1, '[1,2,2]')")
tk.MustGetErrCode("insert into t1 values (2, '[1]')", errno.ErrDupEntry)
tk.MustExec("insert into t1 values (3, '[3,3,4]')")
t1, err := dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
require.NoError(t, err)
for _, index := range t1.Indices() {
if index.Meta().MVIndex {
checkCount(t, t1.IndexPrefix(), index, store, 4)
checkKey(t, t1.IndexPrefix(), index, store, [][]types.Datum{
{types.NewIntDatum(1)},
{types.NewIntDatum(2)},
{types.NewIntDatum(3)},
{types.NewIntDatum(4)},
})
}
}
}
func TestWriteMultiValuedIndexComposite(t *testing.T) {
store, dom := testkit.CreateMockStoreAndDomain(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("create table t1(pk int primary key, a json, c int, d int, index idx(c, (cast(a as signed array)), d))")
tk.MustExec("insert into t1 values (1, '[1,2,2]', 1, 1)")
tk.MustExec("insert into t1 values (2, '[2,2,2]', 2, 2)")
tk.MustExec("insert into t1 values (3, '[3,3,4]', 3, 3)")
tk.MustExec("insert into t1 values (4, null, 4, 4)")
tk.MustExec("insert into t1 values (5, '[]', 5, 5)")
t1, err := dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
require.NoError(t, err)
for _, index := range t1.Indices() {
if index.Meta().MVIndex {
checkCount(t, t1.IndexPrefix(), index, store, 6)
checkKey(t, t1.IndexPrefix(), index, store, [][]types.Datum{
{types.NewIntDatum(1), types.NewIntDatum(1), types.NewIntDatum(1), types.NewIntDatum(1)},
{types.NewIntDatum(1), types.NewIntDatum(2), types.NewIntDatum(1), types.NewIntDatum(1)},
{types.NewIntDatum(2), types.NewIntDatum(2), types.NewIntDatum(2), types.NewIntDatum(2)},
{types.NewIntDatum(3), types.NewIntDatum(3), types.NewIntDatum(3), types.NewIntDatum(3)},
{types.NewIntDatum(3), types.NewIntDatum(4), types.NewIntDatum(3), types.NewIntDatum(3)},
{types.NewIntDatum(4), types.NewDatum(nil), types.NewIntDatum(4), types.NewIntDatum(4)},
})
}
}
}
func checkCount(t *testing.T, prefix kv.Key, index table.Index, store kv.Storage, except int) {
c := 0
checkIndex(t, prefix, index, store, func(it kv.Iterator) {
c++
})
require.Equal(t, except, c)
}
func checkKey(t *testing.T, prefix kv.Key, index table.Index, store kv.Storage, except [][]types.Datum) {
idx := 0
checkIndex(t, prefix, index, store, func(it kv.Iterator) {
indexKey := decodeIndexKey(t, it.Key())
require.Equal(t, except[idx], indexKey)
idx++
})
}
func checkIndex(t *testing.T, prefix kv.Key, index table.Index, store kv.Storage, fn func(kv.Iterator)) {
startKey := codec.EncodeInt(prefix, index.Meta().ID)
prefix.Next()
se := testkit.NewTestKit(t, store).Session()
err := sessiontxn.NewTxn(context.Background(), se)
require.NoError(t, err)
txn, err := se.Txn(true)
require.NoError(t, err)
it, err := txn.Iter(startKey, prefix.PrefixNext())
require.NoError(t, err)
for it.Valid() && it.Key().HasPrefix(prefix) {
fn(it)
err = it.Next()
require.NoError(t, err)
}
it.Close()
se.Close()
}
func decodeIndexKey(t *testing.T, key kv.Key) []types.Datum {
var idLen = 8
var prefixLen = 1 + idLen /*tableID*/ + 2
_, _, isRecord, err := tablecodec.DecodeKeyHead(key)
require.NoError(t, err)
require.False(t, isRecord)
indexKey := key[prefixLen+idLen:]
var datumValues []types.Datum
for len(indexKey) > 0 {
remain, d, err := codec.DecodeOne(indexKey)
require.NoError(t, err)
datumValues = append(datumValues, d)
indexKey = remain
}
return datumValues
}
|
package raw_client
import (
"context"
)
type GetPreviewAppDeployRequest struct {
Apps []string `json:"apps"`
}
type GetPreviewAppDeployResponse struct {
Apps []GetPreviewAppDeployResponseApp `json:"apps"`
}
type GetPreviewAppDeployResponseApp struct {
App string `json:"app"`
Status string `json:"status"`
}
func GetPreviewAppDeploy(ctx context.Context, apiClient *ApiClient, req GetPreviewAppDeployRequest) (*GetPreviewAppDeployResponse, error) {
apiRequest := ApiRequest{
Method: "GET",
Scheme: "https",
Path: "/k/v1/preview/app/deploy.json",
Json: req,
}
var GetAppResponse GetPreviewAppDeployResponse
if err := apiClient.Call(ctx, apiRequest, &GetAppResponse); err != nil {
return nil, err
}
return &GetAppResponse, nil
}
|
// Copyright 2009 The Go 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 bytes implements functions for the manipulation of byte slices.
// It is analogous to the facilities of the strings package.
// this is copy from `bytes/bytes.go`
package mydump
// byteSet is a 32-byte value, where each bit represents the presence of a
// given byte value in the set.
type byteSet [8]uint32
// makeByteSet creates a set of byte value.
func makeByteSet(chars []byte) (as byteSet) {
for i := 0; i < len(chars); i++ {
c := chars[i]
as[c>>5] |= 1 << uint(c&31)
}
return as
}
// contains reports whether c is inside the set.
func (as *byteSet) contains(c byte) bool {
return (as[c>>5] & (1 << uint(c&31))) != 0
}
// IndexAnyByte returns the byte index of the first occurrence in s of any of the byte
// points in chars. It returns -1 if there is no code point in common.
func IndexAnyByte(s []byte, as *byteSet) int {
for i, c := range s {
if as.contains(c) {
return i
}
}
return -1
}
|
package main
import (
"encoding/json"
"net/http"
"strconv"
"net/url"
"fmt"
"log"
"github.com/Bobochka/thumbnail_service/lib"
"github.com/Bobochka/thumbnail_service/lib/service"
"github.com/Bobochka/thumbnail_service/lib/transform"
)
type App struct {
service *service.Service
}
type params struct {
url string
width int
height int
}
func (app *App) thumbnail(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
app.renderError(w, fmt.Errorf("%s", r))
}
}()
params, err := app.thumbnailParams(r)
if err != nil {
app.renderError(w, err)
return
}
t := transform.NewLPad(params.width, params.height)
img, err := app.service.Perform(params.url, t)
if err != nil {
app.renderError(w, err)
return
}
app.renderImg(w, img)
}
const maxAllowedArea = 6000000 // px
func (app *App) thumbnailParams(r *http.Request) (params, error) {
var res params
res.url = r.URL.Query().Get("url")
_, err := url.ParseRequestURI(res.url)
if err != nil {
msg := fmt.Sprintf("url %s is not valid", res.url)
return params{}, lib.NewError(err, lib.InvalidParams, msg)
}
w := r.URL.Query().Get("width")
res.width, err = strconv.Atoi(w)
if err != nil || res.width <= 0 {
err = fmt.Errorf("width %s is not valid: should be positive integer", w)
return params{}, lib.NewError(err, lib.InvalidParams, err.Error())
}
h := r.URL.Query().Get("height")
res.height, err = strconv.Atoi(h)
if err != nil || res.height <= 0 {
err = fmt.Errorf("height %s is not valid: should be positive integer", h)
return params{}, lib.NewError(err, lib.InvalidParams, err.Error())
}
if res.height*res.width > maxAllowedArea {
err = fmt.Errorf("requested size of %v x %v is too big", res.width, res.height)
return params{}, lib.NewError(err, lib.InvalidParams, err.Error())
}
return res, nil
}
func (app *App) renderImg(w http.ResponseWriter, img []byte) {
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Content-Length", strconv.Itoa(len(img)))
w.Write(img)
}
func (app *App) renderError(w http.ResponseWriter, err error) {
code := 500
msg := lib.GenericMsg
realMsg := err.Error()
codedError, ok := err.(lib.Error)
if ok {
code = codedError.Code()
msg = codedError.Msg()
realMsg = codedError.Error()
}
log.Println("error: ", realMsg)
w.WriteHeader(code)
response := struct{ Error string }{msg}
data, e := json.Marshal(response)
if e != nil {
log.Println("error marshaling response: ", e.Error())
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
|
// A package that does modular arithmetic.
//
// Doesn't use a single % operator or any math library functions.
// This is more for experience than for actual use. There is also a variation of this for big integers,
// which can be found in the bigmod package (github.com/deanveloper/modmath/bigmod)
package bigmod
import (
"errors"
"math/big"
)
var NoSolution = errors.New("no solution")
// Solves the equation ax=b mod n. Note that
// if there are multiple LPR solutions that the
// lowest one is returned. If there are no solutions,
// then (nil, NoSolution) is returned
func Solve(a, b, m *big.Int) (*big.Int, error) {
gcd := new(big.Int).GCD(nil, nil, a, m)
// If a and m are coprime, just multiply by the inverse
if gcd.IsUint64() && gcd.Uint64() == 1 {
aInv := new(big.Int).ModInverse(a, m)
aInvB := new(big.Int).Mul(aInv, b)
return aInvB.Mod(aInvB, m), nil
}
// If gcd divides b evenly, then solve a/d x = b/d mod m/d (d = gcd)
if new(big.Int).Mod(b, gcd).Sign() == 0 {
ad := new(big.Int).Div(a, gcd)
bd := new(big.Int).Div(b, gcd)
nd := new(big.Int).Div(m, gcd)
return Solve(ad, bd, nd)
}
// else, no solution
return nil, NoSolution
}
// Deprecated: use built-in function instead: big.Int.Exp(a, b, m)
func SolveExp(a, b, m *big.Int) *big.Int {
return new(big.Int).Exp(a, b, m)
}
|
package gomonkey
import (
"fmt"
"reflect"
)
type FuncPara struct {
target interface{}
matchers []Matcher
behaviors []ReturnValue
}
type PatchBuilder struct {
patches *Patches
funcPara FuncPara
}
func NewPatchBuilder(patches *Patches) *PatchBuilder {
funcPara := FuncPara{target: nil, matchers: make([]Matcher, 0)}
return &PatchBuilder{patches: patches, funcPara: funcPara}
}
func (this *PatchBuilder) Func(target interface{}) *PatchBuilder {
this.funcPara.target = target
return this
}
func (this *PatchBuilder) Stubs() *PatchBuilder {
return this
}
func (this *PatchBuilder) With(matcher ...Matcher) *PatchBuilder {
this.funcPara.matchers = append(this.funcPara.matchers, matcher...)
return this
}
func (this *PatchBuilder) Will(behavior ReturnValue) *PatchBuilder {
this.funcPara.behaviors = append(this.funcPara.behaviors, behavior)
return this
}
func (this *PatchBuilder) End() {
funcType := reflect.TypeOf(this.funcPara.target)
t := reflect.ValueOf(this.funcPara.target)
d := reflect.MakeFunc(funcType, func(inputs []reflect.Value) []reflect.Value {
matchers := this.funcPara.matchers
for i, input := range inputs {
if !matchers[i].Matches(input.Interface()) {
info := fmt.Sprintf("input paras %v is not matched", input.Interface())
panic(info)
}
}
return getResultValues(funcType, this.funcPara.behaviors[0].rets...)
})
this.patches.applyCore(t, d)
}
func Any() Matcher {
return &AnyMatcher{}
}
func Eq(x interface{}) Matcher {
return &EqMatcher{x: x}
}
func Return(x ...interface{}) ReturnValue {
r := ReturnValue{rets: make([]interface{}, 0)}
r.rets = append(r.rets, x...)
return r
}
type ReturnValue struct {
rets []interface{}
}
type Matcher interface {
Matches(x interface{}) bool
}
type AnyMatcher struct {
}
func (this *AnyMatcher) Matches(x interface{}) bool {
return true
}
type EqMatcher struct {
x interface{}
}
func (this *EqMatcher) Matches(x interface{}) bool {
return reflect.DeepEqual(this.x, x)
}
|
// This file was generated for SObject Publisher, API Version v43.0 at 2018-07-30 03:47:25.940649177 -0400 EDT m=+12.283716535
package sobjects
import (
"fmt"
"strings"
)
type Publisher struct {
BaseSObject
DurableId string `force:",omitempty"`
Id string `force:",omitempty"`
IsSalesforce bool `force:",omitempty"`
MajorVersion int `force:",omitempty"`
MinorVersion int `force:",omitempty"`
Name string `force:",omitempty"`
NamespacePrefix string `force:",omitempty"`
}
func (t *Publisher) ApiName() string {
return "Publisher"
}
func (t *Publisher) String() string {
builder := strings.Builder{}
builder.WriteString(fmt.Sprintf("Publisher #%s - %s\n", t.Id, t.Name))
builder.WriteString(fmt.Sprintf("\tDurableId: %v\n", t.DurableId))
builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id))
builder.WriteString(fmt.Sprintf("\tIsSalesforce: %v\n", t.IsSalesforce))
builder.WriteString(fmt.Sprintf("\tMajorVersion: %v\n", t.MajorVersion))
builder.WriteString(fmt.Sprintf("\tMinorVersion: %v\n", t.MinorVersion))
builder.WriteString(fmt.Sprintf("\tName: %v\n", t.Name))
builder.WriteString(fmt.Sprintf("\tNamespacePrefix: %v\n", t.NamespacePrefix))
return builder.String()
}
type PublisherQueryResponse struct {
BaseQuery
Records []Publisher `json:"Records" force:"records"`
}
|
package es
import (
"fmt"
"strconv"
"strings"
. "github.com/Dataman-Cloud/omega-es/src/util"
"github.com/Jeffail/gabs"
log "github.com/cihub/seelog"
"github.com/gin-gonic/gin"
)
func SearchIndex(c *gin.Context) {
body, err := ReadBody(c)
if err != nil {
log.Error("searchindex can't get request body")
ReturnParamError(c, err.Error())
return
}
json, err := gabs.ParseJSON(body)
if err != nil {
log.Error("searchindex param parse json error")
ReturnParamError(c, err.Error())
return
}
clusterid, ok := json.Path("clusterid").Data().(float64)
if !ok {
log.Error("searchindex param can't found clusterid")
ReturnParamError(c, "searchindex param can't found clusterid")
return
}
appname, ok := json.Path("appname").Data().(string)
if !ok {
log.Error("searchindex param can't found appname")
ReturnParamError(c, "searchindex param can't found appname")
return
}
start, ok := json.Path("start").Data().(string)
if !ok {
log.Error("searchindex param can't found starttime")
ReturnParamError(c, "searchindex param can't found starttime")
return
}
end, ok := json.Path("end").Data().(string)
if !ok {
log.Error("searchindex param can't found endtime")
ReturnParamError(c, "searchindex param can't found endtime")
return
}
from, ok := json.Path("from").Data().(float64)
if !ok {
log.Error("searchindex param can't found from")
ReturnParamError(c, "searchindex param can't found from")
return
}
size, ok := json.Path("size").Data().(float64)
if !ok {
log.Error("searchindex param can't found size")
ReturnParamError(c, "searchindex param can't found size")
return
}
if size > 200 {
size = 200
}
ipport, err := json.Path("ipport").Children()
source, serr := json.Path("source").Children()
keyword, kok := json.Path("keyword").Data().(string)
query := `{
"query": {
"bool": {
"must": [
{
"range": {
"timestamp": {
"gte": "` + start + `",
"lte": "` + end + `"
}
}
},
{
"term": {"typename": "` + appname + `"}
},
{
"term": {"clusterid": "` + strconv.Itoa(int(clusterid)) + `"}
}`
if kok {
query += `,
{
"match": {
"msg": {
"query": "` + keyword + `",
"analyzer": "ik"
}
}
}`
}
if err == nil && len(ipport) > 0 {
var arr []string
for _, ipp := range ipport {
arr = append(arr, ipp.Data().(string))
}
query += `,
{
"terms": {
"ipport": ["` + strings.Join(arr, "\",\"") + `"]
}
}`
}
if serr == nil && len(source) > 0 {
var arr []string
for _, sour := range source {
arr = append(arr, sour.Data().(string))
}
query += `,
{
"terms": {
"source": ["` + strings.Join(arr, "\",\"") + `"]
}
}`
}
query += `
]
}
},
"sort": {"timestamp.sort": "asc"},
"from": ` + strconv.Itoa(int(from)) + `,
"size": ` + strconv.Itoa(int(size)) + `,
"fields": ["timestamp","msg","ipport","ip","taskid","counter", "typename", "source"],
"highlight": {
"require_field_match": "true",
"fields": {
"msg": {
"pre_tags": ["<em style=\"color:red;\">"],
"post_tags": ["</em>"]
}
},
"fragment_size": -1
}
}`
esindex := "dataman-app-" + fmt.Sprintf("%d", int64(clusterid)) + "-"
estype := "dataman-" + appname
//estype := ""
if start[:10] == end[:10] {
esindex += start[:10]
} else {
esindex += "*"
}
log.Debug(esindex, estype, query)
out, err := Conn.Search(esindex, estype, nil, query)
if err != nil {
log.Error("searchindex search es error: ", err)
ReturnEsError(c, err.Error())
return
}
content, _ := gabs.ParseJSON(out.RawJSON)
hits, err := content.Path("hits.hits").Children()
if err != nil {
log.Error("searchindex get hits error: ", err)
ReturnEsError(c, err.Error())
return
}
if err == nil {
if len(hits) > 0 {
for i, hit := range hits {
msgs, err := hit.Path("fields.msg").Children()
if err == nil {
msg := msgs[0].Data().(string)
msg = ReplaceHtml(msg)
hits[i].Path("fields.msg").SetIndex(msg, 0)
}
msgh, err := hit.Path("highlight.msg").Children()
if err == nil {
msg := msgh[0].Data().(string)
msg = strings.Replace(msg, "<em style=\"color:red;\">", "-emstart-", -1)
msg = strings.Replace(msg, "</em>", "-emend-", -1)
msg = ReplaceHtml(msg)
msg = strings.Replace(msg, "-emstart-", "<em style=\"color:red;\">", -1)
msg = strings.Replace(msg, "-emend-", "</em>", -1)
hits[i].Path("highlight.msg").SetIndex(msg, 0)
log.Debug("------:", msg)
}
}
}
}
ReturnOKGin(c, content.Data())
return
}
func SearchContext(c *gin.Context) {
body, err := ReadBody(c)
if err != nil {
log.Error("searchcontext can't get request body")
ReturnParamError(c, err.Error())
return
}
json, err := gabs.ParseJSON(body)
if err != nil {
log.Error("searchcontext param parse json error")
ReturnParamError(c, err.Error())
return
}
clusterid, ok := json.Path("clusterid").Data().(float64)
if !ok {
log.Error("searchcontext param can't found clusterid")
ReturnParamError(c, "searchcontext can't found clusterid")
return
}
ipport, ok := json.Path("ipport").Data().(string)
if !ok {
log.Error("searchcontext param can't found ipport")
ReturnParamError(c, "searchcontext can't found ipport")
return
}
source, sok := json.Path("source").Data().(string)
if !sok {
log.Error("searchcontext param can't found source")
}
timestamp, ok := json.Path("timestamp").Data().(string)
if !ok {
log.Error("searchcontext param can't found timestamp")
ReturnParamError(c, "searchcontext can't found timestamp")
return
}
counter, ok := json.Path("counter").Data().(float64)
if !ok {
log.Error("searchcontext param can't found counter")
ReturnParamError(c, "searchcontext can't found counter")
return
}
appname, ok := json.Path("appname").Data().(string)
if !ok {
log.Error("searchcontext param can't found appname")
ReturnParamError(c, "searchcontext can't found appname")
return
}
countergte := int(counter) - 100
if countergte < 0 {
countergte = 0
}
counterlte := int(counter) + 100
query := `{
"query": {
"bool": {
"must": [
{
"range": {
"counter": {
"gte": ` + strconv.Itoa(countergte) + `,
"lte": ` + strconv.Itoa(counterlte) + `
}
}
},
{
"term": {"typename": "` + appname + `"}
},
{
"term": {"clusterid": "` + strconv.Itoa(int(clusterid)) + `"}
},
`
if sok {
query += `
{
"term": {"source": "` + source + `"}
},
`
}
query += `
{
"term": {"ipport": "` + ipport + `"}
}
]
}
},
"sort": {"timestamp.sort": "asc"},
"from": 0,
"size": 200,
"fields": ["timestamp","msg","ipport","ip","taskid","counter"],
"highlight": {
"require_field_match": "true",
"fields": {
"msg": {
"pre_tags": ["<em style=\"color:red;\">"],
"post_tags": ["</em>"]
}
},
"fragment_size": -1
}
}`
esindex := "dataman-app-" + fmt.Sprintf("%d", int64(clusterid)) + "-" + timestamp[:10]
estype := "dataman-" + appname
//esindex := "*"
log.Debug(esindex, estype, query)
out, err := Conn.Search(esindex, estype, nil, query)
if err != nil {
log.Error("searchcontext search es error: ", err)
ReturnEsError(c, err.Error())
return
}
content, _ := gabs.ParseJSON(out.RawJSON)
hits, err := content.Path("hits.hits").Children()
if err != nil {
log.Error("searchindex get hits error: ", err)
ReturnEsError(c, err.Error())
return
}
if err == nil {
if len(hits) > 0 {
for i, hit := range hits {
msgs, err := hit.Path("fields.msg").Children()
if err == nil {
msg := msgs[0].Data().(string)
msg = ReplaceHtml(msg)
hits[i].Path("fields.msg").SetIndex(msg, 0)
}
msgh, err := hit.Path("highlight.msg").Children()
if err == nil {
msg := msgh[0].Data().(string)
msg = strings.Replace(msg, "<em style=\"color:red;\">", "-emstart-", -1)
msg = strings.Replace(msg, "</em>", "-emend-", -1)
msg = ReplaceHtml(msg)
msg = strings.Replace(msg, "-emstart-", "<em style=\"color:red;\">", -1)
msg = strings.Replace(msg, "-emend-", "</em>", -1)
hits[i].Path("highlight.msg").SetIndex(msg, 0)
log.Debug("------:", msg)
}
}
}
}
ReturnOKGin(c, content.Data())
return
}
|
package main
import ("fmt")
type Rect struct {
l, b float64
}
func calArea (R* Rect) (float64){
return R.l*R.b
}
func (R* Rect) calArea() float64 {
return R.l*R.b
}
func main() {
var R1 Rect
R1.l = 10
R1.b = 20
area := calArea(&R1)
fmt.Println(area)
area = R1.calArea()
fmt.Println(area)
return
}
|
package main
import (
"fmt"
)
func main() {
dy := map[string]int{
"Sunday": 9,
"Monday": 10,
"Tuesday": 11,
"Wednesday": 12,
"Thursday": 13,
"Friday": 14,
"Saturday": 15,
"Mayday": 16,
}
fmt.Println(dy)
fmt.Println(dy["Sunday"])
fmt.Println(dy["Holyday"])
v, ok := dy["Holyday"]
fmt.Println(v, ok)
delete(dy, "Sunday")
fmt.Println(dy)
delete(dy, "Holyday")
fmt.Println(dy)
if v, ok := dy["Wednesday"]; ok {
fmt.Println(v, ok)
delete(dy, "Wednesday")
fmt.Println(dy)
delete(dy, "Friday")
fmt.Println(dy)
delete(dy, "Saturday")
fmt.Println(dy)
delete(dy, "Sunday")
fmt.Println(dy)
delete(dy, "Tuesday")
fmt.Println(dy)
delete(dy, "Mayday")
fmt.Println(dy)
delete(dy, "Monday")
fmt.Println(dy)
delete(dy, "Thursday")
fmt.Println(dy)
}
}
|
package main
import(
"fmt"
"time"
)
func pinger(c chan <- string){ //<- makes it unidirectional (only send , no receive)
for i :=0; ;i++{
c <- "ping"
time.Sleep(time.Second*3)
}
}
func ponger(c1 chan string){
for i :=0; ;i++{
c1 <- "pong"
time.Sleep(time.Second*5)
}
}
func printer(c,c1 chan string){
/*for{
msg := <- c
//msg1 := <-d
fmt.Println("The info is : ",msg)
time.Sleep(time.Second*1)
}*/
for{
select{ //select is same as switch case but only for channels
case msg1 := <- c:
fmt.Println(msg1)
case msg2 := <-c1:
fmt.Println(msg2)
case <-time.After(time.Second*2):
fmt.Println("timeout" , time.After(time.Second*2))
}
}
}
func main() {
var c chan string=make(chan string) //using a channel between 2 goroutines to sync them
var c1 chan string=make(chan string)
//var d chan string=make(chan string)
go pinger(c)
go ponger(c1)
go printer(c,c1)
var input string
fmt.Scanln(&input)
}
|
package app
/*
主要用来格式化输入参数,用来防止sql注入,xss攻击等
*/
import (
"github.com/comdeng/HapGo/hapgo/conf"
"github.com/comdeng/HapGo/hapgo/logger"
_html "github.com/comdeng/HapGo/lib/html"
// "log"
"net/http"
"strings"
"sync"
"time"
)
const trimReg = " \t\r\n\x0b\v"
const inputConfKey = "hapgo.input"
var replacer = strings.NewReplacer(
"&", "&",
"'", "'",
`"`, """,
">", ">",
"<", "<",
"`", "E",
"{", "{",
"\r\n", "<br/>",
"\r", "<br/>",
"\n", "<br/>",
)
type inputInfo struct {
SafeCheck bool
PrefixOfHtml string
PrefixOfRaw string
PrefixOfSafe string
}
var iInfo inputInfo
func AppInputFilter(_app *WebApp) error {
start := time.Now()
var once sync.Once
once.Do(initInputConf)
_app.Request.Req.ParseForm()
encodeInput(_app.Request.Req)
end := time.Now()
logger.Trace("hapgo.filter.input end cost %dμs", end.Sub(start)/1000)
return nil
}
func initInputConf() {
iInfo = inputInfo{false, "ph_", "pr_", "ps_"}
conf.Decode(inputConfKey, &iInfo)
}
func encodeInput(r *http.Request) {
for k, v := range r.Form {
if strings.Index(k, iInfo.PrefixOfHtml) == 0 {
for _k, _v := range v {
r.Form[k][_k] = filterHtml(_v)
}
} else if strings.Index(k, iInfo.PrefixOfRaw) == 0 {
//
} else if iInfo.SafeCheck && strings.Index(k, iInfo.PrefixOfSafe) == 0 {
} else {
for _k, _v := range v {
r.Form[k][_k] = filterText(_v)
}
}
}
}
func safeCheckText(text string) string {
//TODY
return text
}
func filterHtml(html string) string {
return _html.Tidy(html)
}
func filterText(text string) string {
strings.Trim(text, trimReg)
return replacer.Replace(text)
}
|
/*
* @lc app=leetcode.cn id=297 lang=golang
*
* [297] 二叉树的序列化与反序列化
*/
package main
import (
"fmt"
"strconv"
"strings"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// @lc code=start
type Codec struct {
l []string
str strings.Builder
}
func Constructor() Codec {
return Codec{}
}
// Serializes a tree to a single string.
func (c *Codec) serialize(root *TreeNode) string {
if root == nil {
c.str.WriteString("nil,")
} else {
c.str.WriteString(strconv.Itoa(root.Val))
c.str.WriteString(",")
c.serialize(root.Left)
c.serialize(root.Right)
}
return c.str.String()
}
// Deserializes your encoded data to tree.
func (c *Codec) deserialize(data string) *TreeNode {
l := strings.Split(data, ",")
for i := 0; i < len(l); i++ {
if l[i] != "" {
c.l = append(c.l, l[i])
}
}
return c.rdeserialize()
}
func (c *Codec) rdeserialize() *TreeNode {
if c.l[0] == "nil" {
c.l = c.l[1:]
return nil
}
val, _ := strconv.Atoi(c.l[0])
root := &TreeNode{Val: val}
c.l = c.l[1:]
root.Left = c.rdeserialize()
root.Right = c.rdeserialize()
return root
}
/**
* Your Codec object will be instantiated and called as such:
* ser := Constructor();
* deser := Constructor();
* data := ser.serialize(root);
* ans := deser.deserialize(data);
*/
// @lc code=end
func main() {
c := Constructor()
fmt.Println(c.deserialize(c.serialize(&TreeNode{
Val: 1,
Left: &TreeNode{
Val: 2,
},
Right: &TreeNode{
Val: 3,
},
})))
}
|
package main
import(
"fmt"
)
func longestValidParentheses(s string) int {
if len(s) < 2 {
return 0;
}
maxLength := 0
var stack = make([]int, len(s) + 1)
stackIndex := -1
stackIndex++
stack[stackIndex] = -1
var tmpStr string
for i, tmpChar := range s[:] {
tmpStr = string(tmpChar)
if tmpStr == "(" {
stackIndex++
stack[stackIndex] = i
} else {
stackIndex--
if stackIndex < 0 {
stackIndex++
stack[stackIndex] = i
} else {
if (i - stack[stackIndex]) > maxLength {
maxLength = i - stack[stackIndex]
}
}
}
}
return maxLength
}
func main() {
fmt.Println(longestValidParentheses(")()())"));
fmt.Println(longestValidParentheses("(()"));
fmt.Println(longestValidParentheses("()(()"));
fmt.Println(longestValidParentheses("(()((((()"));
fmt.Println(longestValidParentheses(")(())))(())())"));
fmt.Println(longestValidParentheses("()(()()"));
fmt.Println(longestValidParentheses("()(())"));
fmt.Println(longestValidParentheses(""));
fmt.Println(longestValidParentheses("("));
}
|
package sqly
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
)
type dbDriver int8
const (
driverMysql dbDriver = 1
driverPostgresql dbDriver = 2
driverOthers dbDriver = 99
)
var argFmtFunc argFormat
// SqlY struct
type SqlY struct {
db *sql.DB
driver dbDriver
}
// Option sqly config option
type Option struct {
Dsn string `json:"dsn"` // database server name
DriverName string `json:"driver_name"` // database driver
MaxIdleConns int `json:"max_idle_conns"` // limit the number of idle connections
MaxOpenConns int `json:"max_open_conns"` // limit the number of total open connections
ConnMaxLifeTime time.Duration `json:"conn_max_life_time"` // maximum amount of time a connection may be reused
}
// connect to database
func conn(driverName, dsn string) (*sql.DB, error) {
db, err := sql.Open(driverName, dsn)
if err != nil {
return nil, err
}
if err = db.Ping(); err != nil {
return nil, err
}
return db, nil
}
// New init SqlY to database
func New(opt *Option) (*SqlY, error) {
db, err := conn(opt.DriverName, opt.Dsn)
if err != nil {
return nil, err
}
db.SetConnMaxLifetime(opt.ConnMaxLifeTime)
db.SetMaxIdleConns(opt.MaxIdleConns)
db.SetMaxOpenConns(opt.MaxOpenConns)
r := &SqlY{db: db}
switch opt.DriverName {
case "mysql":
r.driver = driverMysql
argFmtFunc = mysqlArgFormat
case "postgres":
r.driver = driverPostgresql
argFmtFunc = pgArgFormat
default:
r.driver = driverOthers
argFmtFunc = mysqlArgFormat
}
return r, nil
}
// exec one sql statement with context
func (s *SqlY) execOneDb(ctx context.Context, query string) (*Affected, error) {
res, err := s.db.ExecContext(ctx, query)
if err != nil {
return nil, err
}
// last row_id that affected
aff := &Affected{
result: res,
driver: s.driver,
}
return aff, nil
}
// exec sql statements
func execManyDb(ctx context.Context, db *sql.DB, queries []string) error {
// start transaction
tx, err := db.Begin()
defer func() {
_ = tx.Rollback()
}()
if err != nil {
return err
}
var errR error
for _, query := range queries {
_, errR = tx.ExecContext(ctx, query)
if errR != nil {
return errors.New("query:" + query + "; error:" + errR.Error())
}
}
return tx.Commit()
}
// Ping ping test
func (s *SqlY) Ping() error {
return s.db.Ping()
}
// Close close connection
func (s *SqlY) Close() error {
return s.db.Close()
}
// Query query the database working with results
func (s *SqlY) Query(dest interface{}, query string, args ...interface{}) error {
// query db
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
if errors.Is(err, ErrEmptyArrayInStatement) {
return nil
}
return err
}
rows, err := s.db.Query(q)
if err != nil {
return err
}
return checkAllV2(rows, dest)
}
// Get query the database working with one result
func (s *SqlY) Get(dest interface{}, query string, args ...interface{}) error {
// query db
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
if errors.Is(err, ErrEmptyArrayInStatement) {
return nil
}
return err
}
rows, err := s.db.Query(q)
if err != nil {
return err
}
return checkOneV2(rows, dest)
}
// Insert insert into the database
func (s *SqlY) Insert(query string, args ...interface{}) (*Affected, error) {
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
return nil, err
}
return s.execOneDb(context.Background(), q)
}
// InsertMany insert many values to database
func (s *SqlY) InsertMany(query string, args [][]interface{}) (*Affected, error) {
q, err := multiRowsFmt(query, argFmtFunc, args)
if err != nil {
return nil, err
}
return s.execOneDb(context.Background(), q)
}
// Update update value to database
func (s *SqlY) Update(query string, args ...interface{}) (*Affected, error) {
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
return nil, err
}
return s.execOneDb(context.Background(), q)
}
// UpdateMany update many
func (s *SqlY) UpdateMany(query string, args [][]interface{}) (*Affected, error) {
var q string
for _, arg := range args {
t, err := statementFormat(query, argFmtFunc, arg...)
if err != nil {
return nil, err
}
q += t + ";"
}
return s.execOneDb(context.Background(), q)
}
// Delete delete item from database
func (s *SqlY) Delete(query string, args ...interface{}) (*Affected, error) {
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
return nil, err
}
return s.execOneDb(context.Background(), q)
}
// Exec general sql statement execute
func (s *SqlY) Exec(query string, args ...interface{}) (*Affected, error) {
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
return nil, err
}
return s.execOneDb(context.Background(), q)
}
// ExecMany execute multi sql statement
func (s *SqlY) ExecMany(queries []string) error {
return execManyDb(context.Background(), s.db, queries)
}
// QueryCtx query the database working with results
func (s *SqlY) QueryCtx(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
// query db
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
if errors.Is(err, ErrEmptyArrayInStatement) {
return nil
}
return err
}
rows, err := s.db.QueryContext(ctx, q)
if err != nil {
return err
}
return checkAllV2(rows, dest)
}
// GetCtx query the database working with one result
func (s *SqlY) GetCtx(ctx context.Context, dest interface{}, query string, args ...interface{}) error {
// query db
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
if errors.Is(err, ErrEmptyArrayInStatement) {
return nil
}
return err
}
rows, err := s.db.QueryContext(ctx, q)
if err != nil {
return err
}
return checkOneV2(rows, dest)
}
// InsertCtx insert with context
func (s *SqlY) InsertCtx(ctx context.Context, query string, args ...interface{}) (*Affected, error) {
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
return nil, err
}
return s.execOneDb(ctx, q)
}
// InsertManyCtx insert many with context
func (s *SqlY) InsertManyCtx(ctx context.Context, query string, args [][]interface{}) (*Affected, error) {
q, err := multiRowsFmt(query, argFmtFunc, args)
if err != nil {
return nil, err
}
return s.execOneDb(ctx, q)
}
// UpdateCtx update with context
func (s *SqlY) UpdateCtx(ctx context.Context, query string, args ...interface{}) (*Affected, error) {
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
return nil, err
}
return s.execOneDb(ctx, q)
}
// UpdateManyCtx update many
func (s *SqlY) UpdateManyCtx(ctx context.Context, query string, args [][]interface{}) (*Affected, error) {
var q string
for _, arg := range args {
t, err := statementFormat(query, argFmtFunc, arg...)
if err != nil {
return nil, err
}
q += t + ";"
}
return s.execOneDb(ctx, q)
}
// DeleteCtx delete with context
func (s *SqlY) DeleteCtx(ctx context.Context, query string, args ...interface{}) (*Affected, error) {
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
return nil, err
}
return s.execOneDb(ctx, q)
}
// ExecCtx general sql statement execute with context
func (s *SqlY) ExecCtx(ctx context.Context, query string, args ...interface{}) (*Affected, error) {
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
return nil, err
}
return s.execOneDb(ctx, q)
}
// ExecManyCtx execute multi sql statement with context
func (s *SqlY) ExecManyCtx(ctx context.Context, queries []string) error {
return execManyDb(ctx, s.db, queries)
}
// TxFunc callback function definition
type TxFunc func(tx *Trans) (interface{}, error)
// Transaction start transaction with callback function
func (s *SqlY) Transaction(txFunc TxFunc) (interface{}, error) {
tx, err := s.db.Begin()
if err != nil {
return nil, err
}
// close or rollback transaction
defer func() {
_ = tx.Rollback()
}()
trans := Trans{tx: tx, driver: s.driver}
// run callback
result, errR := txFunc(&trans)
if errR != nil {
return nil, errR
}
if errC := tx.Commit(); errC != nil {
return nil, errC
}
return result, nil
}
// NewTrans start transaction
func (s *SqlY) NewTrans() (*Trans, error) {
tx, err := s.db.Begin()
if err != nil {
return nil, err
}
return &Trans{tx: tx, driver: s.driver}, nil
}
// PgExec execute statement for postgresql
func (s *SqlY) PgExec(idField, query string, args ...interface{}) (*Affected, error) {
return s.PgExecCtx(context.Background(), idField, query, args...)
}
// PgExecCtx execute statement for postgresql with context
// use this function when you want the LastInsertId
func (s *SqlY) PgExecCtx(ctx context.Context, idField, query string, args ...interface{}) (*Affected, error) {
if s.driver != driverPostgresql {
return nil, ErrNotSupportForThisDriver
}
q, err := statementFormat(query, argFmtFunc, args...)
if err != nil {
return nil, err
}
q = fmt.Sprintf("%s RETURNING %s", q, idField)
var id int64
err = s.db.QueryRowContext(ctx, q).Scan(&id)
if err != nil {
return nil, err
}
return &Affected{
lastId: id,
rowsAffected: -1,
driver: s.driver,
}, nil
}
|
package hookEvent
import (
"github.com/aws/aws-lambda-go/events"
)
type Credential struct {
Category string `json:"category"` // bitbucket:oauth
Key string `json:"key"`
Secret string `json:"secret"`
}
type Event struct {
SourceBranch string `json:"sourceBranch"`
DestinationBranch string `json:"destinationBranch"`
SkipWIP bool `json:"skipWIP"`
ReBuildComments []string `json:"rebuildComments"`
PermittedCommentUsers []string `json:"permittedCommentUsers"`
}
type QueueResult struct {
Events []Event `json:"events"`
ProjectName string `json:"projectName"`
Credential Credential `json:"credential"`
ExecutePath string `json:"ExecutePath"` //not need for codebuild
}
type PullRequestContent struct {
Comment string `json:"comment"`
CommentAuthor string `json:"commentAuthor"`
PullRequestId string `json:"pullRequestId"`
PullRequestTitle string `json:"pullRequestTitle"`
}
type HookEvent struct {
GitFlavour string `json:"gitFlavour"`
RepositoryName string `json:"repositoryName"`
RepositoryShort string `json:"repositoryShort"`
Event string `json:"event"`
SourceBranch string `json:"source"`
DestinationBranch string `json:"destination"`
CommitURL string `json:"commitURL"`
PullRequestContent `json:"pullRequestContent"`
ProjectName string `json:"projectName"`
Credential Credential `json:"credential"`
ExecutePath string `json:"ExecutePath"` //not need for codebuild
}
type HookSetter interface {
Set(*events.APIGatewayProxyRequest, *HookEvent) error
Match(*HookEvent, *QueueResult) bool
}
|
package stun
import "testing"
func TestParseURI(t *testing.T) {
for _, tc := range []struct {
name string
in string
out URI
}{
{
name: "default",
in: "stun:example.org",
out: URI{
Host: "example.org",
Scheme: Scheme,
},
},
{
name: "secure",
in: "stuns:example.org",
out: URI{
Host: "example.org",
Scheme: SchemeSecure,
},
},
{
name: "with port",
in: "stun:example.org:8000",
out: URI{
Host: "example.org",
Scheme: Scheme,
Port: 8000,
},
},
} {
t.Run(tc.name, func(t *testing.T) {
out, parseErr := ParseURI(tc.in) //nolint: scopelint
if parseErr != nil {
t.Fatal(parseErr)
}
if out != tc.out { //nolint: scopelint
t.Errorf("%s != %s", out, tc.out) //nolint: scopelint
}
})
}
t.Run("MustFail", func(t *testing.T) {
for _, tc := range []struct {
name string
in string
}{
{
name: "hierarchical",
in: "stun://example.org",
},
{
name: "bad scheme",
in: "tcp:example.org",
},
{
name: "invalid uri scheme",
in: "stun_s:test",
},
} {
t.Run(tc.name, func(t *testing.T) {
_, parseErr := ParseURI(tc.in) //nolint: scopelint
if parseErr == nil {
t.Fatal("should fail, but did not")
}
})
}
})
}
func TestURI_String(t *testing.T) {
for _, tc := range []struct {
name string
uri URI
out string
}{
{
name: "blank",
out: ":",
},
{
name: "simple",
uri: URI{
Host: "example.org",
Scheme: Scheme,
},
out: "stun:example.org",
},
{
name: "secure",
uri: URI{
Host: "example.org",
Scheme: SchemeSecure,
},
out: "stuns:example.org",
},
{
name: "secure with port",
uri: URI{
Host: "example.org",
Scheme: SchemeSecure,
Port: 443,
},
out: "stuns:example.org:443",
},
} {
t.Run(tc.name, func(t *testing.T) {
if v := tc.uri.String(); v != tc.out { //nolint: scopelint
t.Errorf("%q != %q", v, tc.out) //nolint: scopelint
}
})
}
}
|
package main
import (
"encoding/json"
"fmt"
"net/http"
"regexp"
"github.com/go-redis/redis"
)
// Server main object
type Server struct {
port int
redisDB *redis.Client
getMatch *regexp.Regexp
setMatch *regexp.Regexp
}
// NewServer creates a new server instance
func NewServer(port int, redisHost string, redisPort int) *Server {
s := Server{}
s.port = port
connection := fmt.Sprintf("%s:%d", redisHost, redisPort)
s.redisDB = redis.NewClient(&redis.Options{
Addr: connection,
Password: "",
DB: 0,
})
s.getMatch = regexp.MustCompile("/get/([a-zA-Z0-9\\._-]+)/([a-zA-Z0-9\\._-]+)/([a-zA-Z0-9\\._-]+)/?")
s.setMatch = regexp.MustCompile("/set/([a-zA-Z0-9\\._-]+)/([a-zA-Z0-9\\._-]+)/([a-zA-Z0-9\\._-]+)/?")
return &s
}
// AddConfigDirectory adds a configuration directory to load
func (s *Server) AddConfigDirectory(directory string) {
}
// Listen starts the server and listen for connections
func (s *Server) Listen() {
localServer := fmt.Sprintf(":%d", s.port)
http.ListenAndServe(localServer, s)
}
// ServeHTTP server HTTP
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
getMatches := s.getMatch.FindSubmatch([]byte(r.URL.Path))
if len(getMatches) == 4 {
s.getValue(w, string(getMatches[1]), string(getMatches[2]), string(getMatches[3]))
return
}
setMatches := s.setMatch.FindSubmatch([]byte(r.URL.Path))
if len(setMatches) == 4 {
s.setValue(w, string(setMatches[1]), string(setMatches[2]), string(setMatches[3]))
return
}
err := FailResponse()
s.processResponse(err, w)
}
// setValue expects a url in the format of // /set/server/stage/key
func (s *Server) setValue(w http.ResponseWriter, server string, stage string, key string) {
response := ValidResponse(key, "set some value")
s.processResponse(response, w)
}
func (s *Server) getValue(w http.ResponseWriter, server string, stage string, key string) {
response := ValidResponse(key, "got some value")
s.processResponse(response, w)
}
func (s *Server) processResponse(r Response, w http.ResponseWriter) {
output, err := json.Marshal(r)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(`{"status":500,"message":"Unable to process response."}`))
return
}
w.WriteHeader(r.Status)
w.Write(output)
}
|
package main
import "fmt"
//定义变量的形式为 var 变量名 变量类型 在定义的时候,如果没有进行初始化操作,会有一个默认值
func main1(){
var a int
a = 10
a = a+25
fmt.Print(a)
}
/**
计算圆的周长和面积
*/
func main2(){
//使用;=的方式定义变量
PI:=3.1415926
r:=2.5
l:=2*PI*r;
fmt.Println(l)
s:=PI*r*r
fmt.Print(s)
}
func main3(){
//自动推断类型
//w:=5.0 //float64
//p:=2; //int
/*
在go语言中不同的数据类型不能通过计算
fmt.Println(w*p)//mismatched types float64 and int
*/
}
func main() {
a:=false
b:=10
c:=3.14
d:='a'
e:="abc"
fmt.Println(a,b,c,d,e)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.