text:
package service_test
//
//import (
//	"context"
//	"encoding/json"
//	"fmt"
//	"github.com/lastbackend/lastbackend/internal/api/envs"
//	"github.com/lastbackend/lastbackend/internal/master/http/service"
//	"github.com/lastbackend/lastbackend/internal/util/resource"
//	"github.com/lastbackend/lastbackend/pkg/api/types/v1"
//	"github.com/lastbackend/lastbackend/pkg/api/types/v1/request"
//	"github.com/lastbackend/lastbackend/pkg/api/types/v1/views"
//	"github.com/spf13/viper"
//	"io/ioutil"
//	"net/http"
//	"net/http/httptest"
//	"strings"
//	"testing"
//
//	"github.com/gorilla/mux"
//	"github.com/lastbackend/lastbackend/internal/pkg/errors"
//	"github.com/lastbackend/lastbackend/internal/pkg/storage"
//	"github.com/lastbackend/lastbackend/internal/pkg/models"
//	"github.com/stretchr/testify/assert"
//)
//
//// Testing ServiceInfoH handler
//func TestServiceInfo(t *testing.T) {
//
//	var ctx = context.Background()
//
//	v := viper.New()
//	v.SetDefault("storage.driver", "mock")
//
//	stg, _ := storage.Get(v)
//	envs.Get().SetStorage(stg)
//
//	ns1 := getNamespaceAsset("demo", "")
//	ns2 := getNamespaceAsset("test", "")
//	s1 := getServiceAsset(ns1.Meta.Name, "demo", "")
//	s2 := getServiceAsset(ns1.Meta.Name, "test", "")
//
//	type fields struct {
//		stg storage.IStorage
//	}
//
//	type args struct {
//		ctx       context.Context
//		namespace *models.Namespace
//		service   *models.Service
//	}
//
//	tests := []struct {
//		name         string
//		fields       fields
//		args         args
//		headers      map[string]string
//		handler      func(http.ResponseWriter, *http.Request)
//		want         *views.Service
//		wantErr      bool
//		err          string
//		expectedCode int
//	}{
//		{
//			name:         "checking get service if not exists",
//			handler:      service.ServiceInfoH,
//			args:         args{ctx, ns1, s2},
//			fields:       fields{stg},
//			err:          "{\"code\":404,\"status\":\"Not Found\",\"message\":\"Service not found\"}",
//			wantErr:      true,
//			expectedCode: http.StatusNotFound,
//		},
//		{
//			name:         "checking get service if namespace not exists",
//			handler:      service.ServiceInfoH,
//			args:         args{ctx, ns2, s1},
//			fields:       fields{stg},
//			err:          "{\"code\":404,\"status\":\"Not Found\",\"message\":\"Namespace not found\"}",
//			wantErr:      true,
//			expectedCode: http.StatusNotFound,
//		},
//		{
//			name:         "checking get service successfully",
//			handler:      service.ServiceInfoH,
//			args:         args{ctx, ns1, s1},
//			fields:       fields{stg},
//			want:         v1.View().Service().NewWithDeployment(s1),
//			wantErr:      false,
//			expectedCode: http.StatusOK,
//		},
//	}
//
//	clear := func() {
//		err := envs.Get().GetStorage().Del(context.Background(), stg.Collection().Namespace(), models.EmptyString)
//		assert.NoError(t, err)
//
//		err = envs.Get().GetStorage().Del(context.Background(), stg.Collection().Service(), models.EmptyString)
//		assert.NoError(t, err)
//	}
//
//	for _, tc := range tests {
//
//		t.Run(tc.name, func(t *testing.T) {
//
//			clear()
//			defer clear()
//
//			err := tc.fields.stg.Put(context.Background(), stg.Collection().Namespace(), ns1.SelfLink().String(), ns1, nil)
//			assert.NoError(t, err)
//
//			err = tc.fields.stg.Put(context.Background(), stg.Collection().Service(), s1.SelfLink().String(), s1, nil)
//			assert.NoError(t, err)
//
//			// Create assert request to pass to our handler. We don't have any query parameters for now, so we'll
//			// pass 'nil' as the third parameter.
//			req, err := http.NewRequest("GET", fmt.Sprintf("/namespace/%s/service/%s", tc.args.namespace.Meta.Name, tc.args.service.Meta.Name), nil)
//			assert.NoError(t, err)
//
//			if tc.headers != nil {
//				for key, val := range tc.headers {
//					req.Header.Set(key, val)
//				}
//			}
//
//			r := mux.NewRouter()
//			r.HandleFunc("/namespace/{namespace}/service/{service}", tc.handler)
//
//			setRequestVars(r, req)
//
//			// We create assert ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
//			res := httptest.NewRecorder()
//
//			// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
//			// directly and pass in our Request and ResponseRecorder.
//			r.ServeHTTP(res, req)
//
//			// Check the status code is what we expect.
//			if !assert.Equal(t, tc.expectedCode, res.Code, "status code not equal") {
//				return
//			}
//
//			body, err := ioutil.ReadAll(res.Body)
//			assert.NoError(t, err)
//
//			if tc.wantErr {
//				assert.Equal(t, tc.err, string(body), "incorrect status code")
//			} else {
//
//				s := new(views.Service)
//				err := json.Unmarshal(body, &s)
//				assert.NoError(t, err)
//
//				assert.Equal(t, tc.want.Meta.Name, s.Meta.Name, "name not equal")
//			}
//
//		})
//	}
//
//}
//
//// Testing ServiceListH handler
//func TestServiceList(t *testing.T) {
//
//	var ctx = context.Background()
//
//	v := viper.New()
//	v.SetDefault("storage.driver", "mock")
//
//	stg, _ := storage.Get(v)
//	envs.Get().SetStorage(stg)
//
//	ns1 := getNamespaceAsset("demo", "")
//	ns2 := getNamespaceAsset("test", "")
//	s1 := getServiceAsset(ns1.Meta.Name, "demo", "")
//	s2 := getServiceAsset(ns1.Meta.Name, "test", "")
//
//	sl := models.NewServiceMap()
//	sl.Items[s1.SelfLink().String()] = s1
//	sl.Items[s2.SelfLink().String()] = s2
//
//	type fields struct {
//		stg storage.IStorage
//	}
//
//	type args struct {
//		ctx       context.Context
//		namespace *models.Namespace
//		service   *models.Service
//	}
//
//	tests := []struct {
//		name         string
//		fields       fields
//		args         args
//		headers      map[string]string
//		handler      func(http.ResponseWriter, *http.Request)
//		err          string
//		want         *models.ServiceMap
//		wantErr      bool
//		expectedCode int
//	}{
//		{
//			name:         "checking get services list if namespace not found",
//			args:         args{ctx, ns2, nil},
//			fields:       fields{stg},
//			handler:      service.ServiceListH,
//			err:          "{\"code\":404,\"status\":\"Not Found\",\"message\":\"Namespace not found\"}",
//			wantErr:      true,
//			expectedCode: http.StatusNotFound,
//		},
//		{
//			name:         "checking get services list successfully",
//			args:         args{ctx, ns1, nil},
//			fields:       fields{stg},
//			handler:      service.ServiceListH,
//			want:         sl,
//			wantErr:      false,
//			expectedCode: http.StatusOK,
//		},
//	}
//
//	clear := func() {
//		err := envs.Get().GetStorage().Del(context.Background(), stg.Collection().Namespace(), models.EmptyString)
//		assert.NoError(t, err)
//
//		err = envs.Get().GetStorage().Del(context.Background(), stg.Collection().Service(), models.EmptyString)
//		assert.NoError(t, err)
//	}
//
//	for _, tc := range tests {
//
//		t.Run(tc.name, func(t *testing.T) {
//
//			clear()
//			defer clear()
//
//			err := tc.fields.stg.Put(context.Background(), stg.Collection().Namespace(), ns1.SelfLink().String(), ns1, nil)
//			assert.NoError(t, err)
//
//			err = tc.fields.stg.Put(context.Background(), stg.Collection().Service(), s1.SelfLink().String(), s1, nil)
//			assert.NoError(t, err)
//
//			err = tc.fields.stg.Put(context.Background(), stg.Collection().Service(), s2.SelfLink().String(), s2, nil)
//			assert.NoError(t, err)
//
//			// Create assert request to pass to our handler. We don't have any query parameters for now, so we'll
//			// pass 'nil' as the third parameter.
//			req, err := http.NewRequest("GET", fmt.Sprintf("/namespace/%s", tc.args.namespace.Meta.Name), nil)
//			assert.NoError(t, err)
//
//			if tc.headers != nil {
//				for key, val := range tc.headers {
//					req.Header.Set(key, val)
//				}
//			}
//
//			r := mux.NewRouter()
//			r.HandleFunc("/namespace/{namespace}", tc.handler)
//
//			setRequestVars(r, req)
//
//			// We create assert ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
//			res := httptest.NewRecorder()
//
//			// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
//			// directly and pass in our Request and ResponseRecorder.
//			r.ServeHTTP(res, req)
//
//			// Check the status code is what we expect.
//			if !assert.Equal(t, tc.expectedCode, res.Code, "status code not equal") {
//				return
//			}
//
//			body, err := ioutil.ReadAll(res.Body)
//			assert.NoError(t, err)
//
//			if tc.wantErr {
//				assert.Equal(t, tc.err, string(body), "incorrect status code")
//			} else {
//
//				s := new(views.RouteList)
//				err := json.Unmarshal(body, &s)
//				assert.NoError(t, err)
//
//				for _, item := range *s {
//					if _, ok := tc.want.Items[item.Meta.SelfLink]; !ok {
//						assert.Error(t, errors.New("not equals"))
//					}
//				}
//			}
//
//		})
//	}
//
//}
//
//// Testing ServiceCreateH handler
//func TestServiceCreate(t *testing.T) {
//
//	var ctx = context.Background()
//
//	v := viper.New()
//	v.SetDefault("storage.driver", "mock")
//
//	stg, _ := storage.Get(v)
//	envs.Get().SetStorage(stg)
//
//	ns1 := getNamespaceAsset("demo", "")
//	ns2 := getNamespaceAsset("test", "")
//
//	ns3 := getNamespaceAsset("limits", "")
//	ns3.Spec.Resources.Limits.RAM, _ = resource.DecodeMemoryResource("1GB")
//	ns3.Spec.Resources.Limits.CPU, _ = resource.DecodeCpuResource("1")
//
//	s1 := getServiceAsset(ns1.Meta.Name, "demo", "")
//	s2 := getServiceAsset(ns1.Meta.Name, "success", "")
//	s3 := getServiceAsset(ns3.Meta.Name, "success", "")
//
//	sm1 := getServiceManifest("errored", "image")
//	sm1.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm1.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm1.Spec.Template.Containers[0].Resources.Limits.RAM = "0.5GB"
//
//	sm2 := getServiceManifest("errored", "image")
//	sm2.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm2.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm2.Spec.Template.Containers[0].Resources.Limits.RAM = "2GB"
//	sm2.Spec.Template.Containers[0].Resources.Limits.CPU = "0.5"
//
//	sm3 := getServiceManifest("errored", "image")
//	sm3.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm3.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm3.Spec.Template.Containers[0].Resources.Limits.RAM = "512MB"
//	sm3.Spec.Template.Containers[0].Resources.Limits.CPU = "1.5"
//
//	sm4 := getServiceManifest("errored", "image")
//	sm4.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm4.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm4.Spec.Template.Containers[0].Resources.Limits.RAM = "2GB"
//	sm4.Spec.Template.Containers[0].Resources.Limits.CPU = "1.5"
//
//	var rsm5 = 3
//	sm5 := getServiceManifest("errored", "image")
//	sm5.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm5.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm5.Spec.Replicas = &rsm5
//	sm5.Spec.Template.Containers[0].Resources.Limits.RAM = "128MB"
//	sm5.Spec.Template.Containers[0].Resources.Limits.CPU = "0.5"
//
//	sm6 := getServiceManifest("success", "image")
//	sm6.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm6.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm6.Spec.Template.Containers[0].Resources.Limits.RAM = "512MB"
//	sm6.Spec.Template.Containers[0].Resources.Limits.CPU = "0.5"
//
//	sm7 := getServiceManifest("success", "image")
//	sm7.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm7.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm7.Spec.Template.Containers[0].Resources.Limits.RAM = ""
//	sm7.Spec.Template.Containers[0].Resources.Limits.CPU = ""
//
//	type fields struct {
//		stg storage.IStorage
//	}
//
//	type args struct {
//		ctx       context.Context
//		namespace *models.Namespace
//		service   *models.Service
//	}
//
//	tests := []struct {
//		name         string
//		args         args
//		fields       fields
//		headers      map[string]string
//		handler      func(http.ResponseWriter, *http.Request)
//		data         *request.ServiceManifest
//		want         *views.Service
//		wantErr      bool
//		err          string
//		expectedCode int
//	}{
//		{
//			name:         "checking create service if name already exists",
//			args:         args{ctx, ns1, s1},
//			fields:       fields{stg},
//			handler:      service.ServiceCreateH,
//			data:         getServiceManifest("demo", "redis"),
//			err:          "{\"code\":400,\"status\":\"Not Unique\",\"message\":\"Name is already in use\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		{
//			name:         "checking create service if namespace not found",
//			args:         args{ctx, ns2, s2},
//			fields:       fields{stg},
//			handler:      service.ServiceCreateH,
//			data:         getServiceManifest("test", "redis"),
//			err:          "{\"code\":404,\"status\":\"Not Found\",\"message\":\"Namespace not found\"}",
//			wantErr:      true,
//			expectedCode: http.StatusNotFound,
//		},
//		{
//			name:         "checking create service with replica 1 with ram limit are higher then namespace limits",
//			args:         args{ctx, ns3, s2},
//			fields:       fields{stg},
//			handler:      service.ServiceCreateH,
//			data:         sm2,
//			err:          "{\"code\":400,\"status\":\"Bad Request\",\"message\":\"resources ram limit exceeded\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		{
//			name:         "checking create service with replica 1 with cpu limit are higher then namespace limits",
//			args:         args{ctx, ns3, s2},
//			fields:       fields{stg},
//			handler:      service.ServiceCreateH,
//			data:         sm3,
//			err:          "{\"code\":400,\"status\":\"Bad Request\",\"message\":\"resources cpu limit exceeded\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		{
//			name:         "checking create service with replica 1 with ram & cpu limits are higher then namespace limits",
//			args:         args{ctx, ns3, s2},
//			fields:       fields{stg},
//			handler:      service.ServiceCreateH,
//			data:         sm4,
//			err:          "{\"code\":400,\"status\":\"Bad Request\",\"message\":\"resources ram limit exceeded\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		{
//			name:         "checking create service with replica 3 with limits are higher then namespace limits",
//			args:         args{ctx, ns3, s2},
//			fields:       fields{stg},
//			handler:      service.ServiceCreateH,
//			data:         sm5,
//			err:          "{\"code\":400,\"status\":\"Bad Request\",\"message\":\"resources cpu limit exceeded\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		{
//			name:         "check create service if bad parameter name",
//			args:         args{ctx, ns1, s3},
//			fields:       fields{stg},
//			handler:      service.ServiceCreateH,
//			data:         getServiceManifest("_____test", "redis"),
//			err:          "{\"code\":400,\"status\":\"Bad Parameter\",\"message\":\"Bad name parameter\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		// TODO: check another spec parameters
//		{
//			name:         "check create service success",
//			args:         args{ctx, ns1, s2},
//			fields:       fields{stg},
//			handler:      service.ServiceCreateH,
//			data:         getServiceManifest("success", "redis"),
//			want:         v1.View().Service().NewWithDeployment(s2),
//			wantErr:      false,
//			expectedCode: http.StatusOK,
//		},
//		{
//			name:         "check create service success with default limits",
//			args:         args{ctx, ns3, s3},
//			fields:       fields{stg},
//			handler:      service.ServiceCreateH,
//			data:         sm7,
//			want:         v1.View().Service().NewWithDeployment(s3),
//			wantErr:      false,
//			expectedCode: http.StatusOK,
//		},
//		{
//			name:         "check create service success with limits",
//			args:         args{ctx, ns3, s3},
//			fields:       fields{stg},
//			handler:      service.ServiceCreateH,
//			data:         sm6,
//			want:         v1.View().Service().NewWithDeployment(s3),
//			wantErr:      false,
//			expectedCode: http.StatusOK,
//		},
//	}
//
//	clear := func() {
//		err := envs.Get().GetStorage().Del(context.Background(), stg.Collection().Namespace(), models.EmptyString)
//		assert.NoError(t, err)
//
//		err = envs.Get().GetStorage().Del(context.Background(), stg.Collection().Service(), models.EmptyString)
//		assert.NoError(t, err)
//	}
//
//	for _, tc := range tests {
//		t.Run(tc.name, func(t *testing.T) {
//
//			clear()
//			defer clear()
//
//			err := tc.fields.stg.Put(context.Background(), stg.Collection().Namespace(), ns1.SelfLink().String(), ns1, nil)
//			assert.NoError(t, err)
//
//			err = tc.fields.stg.Put(context.Background(), stg.Collection().Namespace(), ns3.SelfLink().String(), ns3, nil)
//			assert.NoError(t, err)
//
//			err = tc.fields.stg.Put(context.Background(), stg.Collection().Service(), s1.SelfLink().String(), s1, nil)
//			assert.NoError(t, err)
//
//			// Create assert request to pass to our handler. We don't have any query parameters for now, so we'll
//			// pass 'nil' as the third parameter.
//			bd, err := tc.data.ToJson()
//			assert.NoError(t, err)
//
//			req, err := http.NewRequest("POST", fmt.Sprintf("/namespace/%s/service", tc.args.namespace.Meta.Name), strings.NewReader(string(bd)))
//			assert.NoError(t, err)
//
//			if tc.headers != nil {
//				for key, val := range tc.headers {
//					req.Header.Set(key, val)
//				}
//			}
//
//			r := mux.NewRouter()
//			r.HandleFunc("/namespace/{namespace}/service", tc.handler)
//
//			setRequestVars(r, req)
//
//			// We create assert ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
//			res := httptest.NewRecorder()
//
//			// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
//			// directly and pass in our Request and ResponseRecorder.
//			r.ServeHTTP(res, req)
//
//			body, err := ioutil.ReadAll(res.Body)
//			assert.NoError(t, err)
//			// Check the status code is what we expect.
//			if !assert.Equal(t, tc.expectedCode, res.Code, "status code not equal") {
//				return
//			}
//
//			if tc.wantErr {
//				assert.Equal(t, tc.err, string(body), "incorrect status code")
//			} else {
//
//				got := new(models.Service)
//				err := tc.fields.stg.Get(tc.args.ctx, stg.Collection().Service(), tc.args.service.SelfLink().String(), got, nil)
//				assert.NoError(t, err)
//
//				if got == nil {
//					t.Error("can not be not nil")
//					return
//				}
//
//				assert.Equal(t, s3.Meta.Name, got.Meta.Name, "name not equal")
//				assert.Equal(t, s3.Meta.Description, got.Meta.Description, "description not equal")
//			}
//		})
//	}
//
//}
//
//// Testing ServiceUpdateH handler
//func TestServiceUpdate(t *testing.T) {
//
//	var ctx = context.Background()
//
//	v := viper.New()
//	v.SetDefault("storage.driver", "mock")
//
//	stg, _ := storage.Get(v)
//	envs.Get().SetStorage(stg)
//
//	ns1 := getNamespaceAsset("demo", "")
//	ns2 := getNamespaceAsset("test", "")
//	ns3 := getNamespaceAsset("limits", "")
//
//	ns3.Status.Resources.Allocated.RAM, _ = resource.DecodeMemoryResource("1.5GB")
//	ns3.Status.Resources.Allocated.CPU, _ = resource.DecodeCpuResource("1.5")
//
//	ns3.Spec.Resources.Limits.RAM, _ = resource.DecodeMemoryResource("2GB")
//	ns3.Spec.Resources.Limits.CPU, _ = resource.DecodeCpuResource("2")
//
//	s1 := getServiceAsset(ns1.Meta.Name, "demo", "")
//	s2 := getServiceAsset(ns1.Meta.Name, "test", "")
//	s3 := getServiceAsset(ns1.Meta.Name, "demo", "demo description")
//
//	s4 := getServiceAsset(ns3.Meta.Name, "limited", "demo description")
//	s4.Spec.Template.Containers[0].Resources.Limits.RAM, _ = resource.DecodeMemoryResource("512MB")
//	s4.Spec.Template.Containers[0].Resources.Limits.CPU, _ = resource.DecodeCpuResource("0.5")
//
//	m1 := getServiceManifest(s3.Meta.Name, "redis")
//	m1.SetServiceSpec(s1)
//
//	m3 := getServiceManifest(s3.Meta.Name, "redis")
//
//	m3.Meta.Description = &s3.Meta.Description
//	m3.Spec.Template.Containers[0].Env[0].Name = "updated"
//	m3.Spec.Template.Containers[0].Env[1].Value = "meta"
//	m3.Spec.Template.Volumes[0].Name = "secret-test"
//	m3.Spec.Template.Volumes[0].Secret.Name = "r"
//
//	m3.SetServiceSpec(s3)
//
//	sm1 := getServiceManifest("limited", "image")
//	sm1.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm1.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm1.Spec.Template.Containers[0].Resources.Limits.RAM = "0.5GB"
//
//	sm2 := getServiceManifest("limited", "image")
//	sm2.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm2.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm2.Spec.Template.Containers[0].Resources.Limits.RAM = "2GB"
//	sm2.Spec.Template.Containers[0].Resources.Limits.CPU = "0.5"
//
//	sm3 := getServiceManifest("limited", "image")
//	sm3.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm3.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm3.Spec.Template.Containers[0].Resources.Limits.RAM = "512MB"
//	sm3.Spec.Template.Containers[0].Resources.Limits.CPU = "1.5"
//
//	sm4 := getServiceManifest("limited", "image")
//	sm4.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm4.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm4.Spec.Template.Containers[0].Resources.Limits.RAM = "2GB"
//	sm4.Spec.Template.Containers[0].Resources.Limits.CPU = "1.5"
//
//	var rsm5 = 3
//	sm5 := getServiceManifest("limited", "image")
//	sm5.Spec.Replicas = &rsm5
//	sm5.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm5.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm5.Spec.Template.Containers[0].Resources.Limits.RAM = "128MB"
//	sm5.Spec.Template.Containers[0].Resources.Limits.CPU = "0.5"
//
//	sm6 := getServiceManifest("limited", "image")
//	sm6.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm6.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm6.Spec.Template.Containers[0].Resources.Limits.RAM = "600MB"
//	sm6.Spec.Template.Containers[0].Resources.Limits.CPU = "0.6"
//
//	sm7 := getServiceManifest("limited", "image")
//	sm7.Spec.Template.Containers[0].Resources = new(request.ManifestSpecTemplateContainerResources)
//	sm7.Spec.Template.Containers[0].Resources.Limits = new(request.ManifestSpecTemplateContainerResource)
//	sm7.Spec.Template.Containers[0].Resources.Limits.RAM = "512MB"
//	sm7.Spec.Template.Containers[0].Resources.Limits.CPU = "0.5"
//
//	type fields struct {
//		stg storage.IStorage
//	}
//
//	type args struct {
//		ctx       context.Context
//		namespace *models.Namespace
//		service   *models.Service
//	}
//
//	tests := []struct {
//		name         string
//		fields       fields
//		args         args
//		headers      map[string]string
//		handler      func(http.ResponseWriter, *http.Request)
//		data         *request.ServiceManifest
//		want         *views.Service
//		wantErr      bool
//		err          string
//		expectedCode int
//	}{
//		{
//			name:         "checking update service if name not exists",
//			fields:       fields{stg},
//			args:         args{ctx, ns1, s2},
//			handler:      service.ServiceUpdateH,
//			data:         getServiceManifest("test", "redis"),
//			err:          "{\"code\":404,\"status\":\"Not Found\",\"message\":\"Service not found\"}",
//			wantErr:      true,
//			expectedCode: http.StatusNotFound,
//		},
//		{
//			name:         "checking update service if namespace not found",
//			fields:       fields{stg},
//			args:         args{ctx, ns2, s1},
//			handler:      service.ServiceUpdateH,
//			data:         getServiceManifest("demo", "redis"),
//			err:          "{\"code\":404,\"status\":\"Not Found\",\"message\":\"Namespace not found\"}",
//			wantErr:      true,
//			expectedCode: http.StatusNotFound,
//		},
//		{
//			name:         "checking update service without limits if namespace with limits",
//			args:         args{ctx, ns3, s4},
//			fields:       fields{stg},
//			handler:      service.ServiceUpdateH,
//			data:         sm1,
//			err:          "{\"code\":400,\"status\":\"Bad Request\",\"message\":\"resources cpu limit is required\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		{
//			name:         "checking update service with replica 1 with ram limit are higher then namespace limits",
//			args:         args{ctx, ns3, s4},
//			fields:       fields{stg},
//			handler:      service.ServiceUpdateH,
//			data:         sm2,
//			err:          "{\"code\":400,\"status\":\"Bad Request\",\"message\":\"resources ram limit exceeded\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		{
//			name:         "checking update service with replica 1 with cpu limit are higher then namespace limits",
//			args:         args{ctx, ns3, s4},
//			fields:       fields{stg},
//			handler:      service.ServiceUpdateH,
//			data:         sm3,
//			err:          "{\"code\":400,\"status\":\"Bad Request\",\"message\":\"resources cpu limit exceeded\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		{
//			name:         "checking update service with replica 1 with ram & cpu limits are higher then namespace limits",
//			args:         args{ctx, ns3, s4},
//			fields:       fields{stg},
//			handler:      service.ServiceUpdateH,
//			data:         sm4,
//			err:          "{\"code\":400,\"status\":\"Bad Request\",\"message\":\"resources ram limit exceeded\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		{
//			name:         "checking update service with replica 3 with limits are higher then namespace limits",
//			args:         args{ctx, ns3, s4},
//			fields:       fields{stg},
//			handler:      service.ServiceUpdateH,
//			data:         sm5,
//			err:          "{\"code\":400,\"status\":\"Bad Request\",\"message\":\"resources cpu limit exceeded\"}",
//			wantErr:      true,
//			expectedCode: http.StatusBadRequest,
//		},
//		// TODO: check another spec parameters
//		{
//			name:         "check update service success",
//			fields:       fields{stg},
//			args:         args{ctx, ns1, s1},
//			handler:      service.ServiceUpdateH,
//			data:         m3,
//			want:         v1.View().Service().NewWithDeployment(s3),
//			wantErr:      false,
//			expectedCode: http.StatusOK,
//		},
//		{
//			name:         "check update service success with limits",
//			args:         args{ctx, ns3, s4},
//			fields:       fields{stg},
//			handler:      service.ServiceUpdateH,
//			data:         sm6,
//			want:         v1.View().Service().NewWithDeployment(s4),
//			wantErr:      false,
//			expectedCode: http.StatusOK,
//		},
//		{
//			name:         "check update service success with equal limits",
//			args:         args{ctx, ns3, s4},
//			fields:       fields{stg},
//			handler:      service.ServiceUpdateH,
//			data:         sm7,
//			want:         v1.View().Service().NewWithDeployment(s4),
//			wantErr:      false,
//			expectedCode: http.StatusOK,
//		},
//	}
//
//	clear := func() {
//		err := envs.Get().GetStorage().Del(context.Background(), stg.Collection().Namespace(), models.EmptyString)
//		assert.NoError(t, err)
//
//		err = envs.Get().GetStorage().Del(context.Background(), stg.Collection().Service(), models.EmptyString)
//		assert.NoError(t, err)
//	}
//
//	for _, tc := range tests {
//		t.Run(tc.name, func(t *testing.T) {
//
//			clear()
//			defer clear()
//
//			err := tc.fields.stg.Put(context.Background(), stg.Collection().Namespace(), ns1.SelfLink().String(), ns1, nil)
//			assert.NoError(t, err)
//
//			err = tc.fields.stg.Put(context.Background(), stg.Collection().Namespace(), ns3.SelfLink().String(), ns3, nil)
//			assert.NoError(t, err)
//
//			err = tc.fields.stg.Put(context.Background(), stg.Collection().Service(), s1.SelfLink().String(), s1, nil)
//			assert.NoError(t, err)
//
//			err = tc.fields.stg.Put(context.Background(), stg.Collection().Service(), s4.SelfLink().String(), s4, nil)
//			assert.NoError(t, err)
//
//			// Create assert request to pass to our handler. We don't have any query parameters for now, so we'll
//			// pass 'nil' as the third parameter.
//			bd, err := tc.data.ToJson()
//			assert.NoError(t, err)
//
//			req, err := http.NewRequest("PUT", fmt.Sprintf("/namespace/%s/service/%s", tc.args.namespace.Meta.Name, tc.args.service.Meta.Name), strings.NewReader(string(bd)))
//			assert.NoError(t, err)
//
//			if tc.headers != nil {
//				for key, val := range tc.headers {
//					req.Header.Set(key, val)
//				}
//			}
//
//			r := mux.NewRouter()
//			r.HandleFunc("/namespace/{namespace}/service/{service}", tc.handler)
//
//			setRequestVars(r, req)
//
//			// We create assert ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
//			res := httptest.NewRecorder()
//
//			// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
//			// directly and pass in our Request and ResponseRecorder.
//			r.ServeHTTP(res, req)
//
//			// Check the status code is what we expect.
//			if !assert.Equal(t, tc.expectedCode, res.Code, "status code not equal") {
//				return
//			}
//
//			body, err := ioutil.ReadAll(res.Body)
//			assert.NoError(t, err)
//
//			if tc.wantErr && res.Code != 200 {
//				assert.Equal(t, tc.err, string(body), "incorrect status code")
//			} else {
//				s := new(views.Service)
//				err := json.Unmarshal(body, &s)
//				assert.NoError(t, err)
//
//				assert.Equal(t, tc.want.Meta.Name, s.Meta.Name, "description not equal")
//				assert.Equal(t, tc.want.Meta.Description, s.Meta.Description, "description not equal")
//				assert.Equal(t, tc.want.Spec.Replicas, s.Spec.Replicas, "replicas not equal")
//				assert.Equal(t, tc.want.Spec.Network.IP, s.Spec.Network.IP, "network ip spec not equal")
//				assert.Equal(t, tc.want.Spec.Network.Ports, s.Spec.Network.Ports, "network ports spec not equal")
//				assert.Equal(t, tc.want.Spec.Strategy.Type, s.Spec.Strategy.Type, "deployment strategy not equal")
//				assert.Equal(t, tc.want.Spec.Selector.Node, s.Spec.Selector.Node, "provision node selectors not equal")
//				assert.Equal(t, len(tc.want.Spec.Selector.Labels), len(s.Spec.Selector.Labels), "provision labels selectors not equal")
//
//				assert.Equal(t, len(tc.want.Spec.Template.Containers), len(s.Spec.Template.Containers), "container spec count not equal")
//
//				for _, wcs := range tc.want.Spec.Template.Containers {
//					var f = false
//
//					for _, scs := range s.Spec.Template.Containers {
//
//						if scs.Name != wcs.Name {
//							continue
//						}
//
//						f = true
//
//						assert.Equal(t, wcs.Command, scs.Command, "container spec command not equal")
//						assert.Equal(t, wcs.Entrypoint, scs.Entrypoint, "container spec entrypoint not equal")
//						assert.Equal(t, wcs.Workdir, scs.Workdir, "container spec workdir not equal")
//
//						assert.Equal(t, strings.Join(wcs.Args, " "), strings.Join(scs.Args, " "), "container spec command args not equal")
//
//						assert.Equal(t, wcs.Resources, scs.Resources, "container resources not equal")
//						assert.Equal(t, wcs.Image, scs.Image, "container spec image not equal")
//
//						for _, wvcs := range wcs.Volumes {
//							var vf = false
//
//							for _, svcs := range scs.Volumes {
//
//								if wvcs.Name != svcs.Name {
//									continue
//								}
//
//								vf = true
//
//								assert.Equal(t, wvcs, svcs, "container volume spec not equal")
//
//							}
//
//							if !vf {
//								t.Error("container volume not found", wcs.Name)
//							}
//
//						}
//
//						for _, wecs := range wcs.Env {
//
//							var ef = false
//
//							for _, secs := range scs.Env {
//								if wecs.Name != secs.Name {
//									continue
//								}
//
//								ef = true
//
//								assert.Equal(t, wecs, secs, "container env spec not equal")
//
//							}
//
//							if !ef {
//								t.Error("container env not found", wecs.Name)
//								return
//							}
//
//						}
//
//						assert.Equal(t, len(wcs.Env), len(scs.Env), "container count spec envs not equal")
//					}
//
//					if !f {
//						assert.Error(t, errors.New("container spec not found"), wcs.Name)
//						return
//					}
//				}
//
//				if !assert.Equal(t, len(tc.want.Spec.Template.Volumes), len(s.Spec.Template.Volumes), "volumes specs count not equal") {
//					return
//				}
//
//				for _, wvs := range tc.want.Spec.Template.Volumes {
//
//					var f = false
//
//					for _, scs := range s.Spec.Template.Volumes {
//
//						if scs.Name != wvs.Name {
//							continue
//						}
//
//						f = true
//
//						assert.Equal(t, wvs.Type, scs.Type, "volume spec type not equal")
//						assert.Equal(t, wvs.Secret.Name, scs.Secret.Name, "volume spec secret name not equal")
//
//						assert.Equal(t, len(wvs.Secret.Binds), len(scs.Secret.Binds), "container spec secret binds not equal")
//
//					}
//
//					if !f {
//						t.Log("not found")
//						t.Error("volume spec not found", wvs.Name)
//						return
//					}
//
//				}
//			}
//		})
//	}
//
//}
//
//// Testing ServiceRemoveH handler
//func TestServiceRemove(t *testing.T) {
//
//	var ctx = context.Background()
//
//	v := viper.New()
//	v.SetDefault("storage.driver", "mock")
//
//	stg, _ := storage.Get(v)
//	envs.Get().SetStorage(stg)
//
//	ns1 := getNamespaceAsset("demo", "")
//	ns2 := getNamespaceAsset("test", "")
//
//	s1 := getServiceAsset(ns1.Meta.Name, "demo", "")
//	s2 := getServiceAsset(ns1.Meta.Name, "test", "")
//
//	type fields struct {
//		stg storage.IStorage
//	}
//
//	type args struct {
//		ctx       context.Context
//		namespace *models.Namespace
//		service   *models.Service
//	}
//
//	tests := []struct {
//		name         string
//		fields       fields
//		args         args
//		headers      map[string]string
//		handler      func(http.ResponseWriter, *http.Request)
//		err          string
//		want         string
//		wantErr      bool
//		expectedCode int
//	}{
//		{
//			name:         "checking get service if not exists",
//			fields:       fields{stg},
//			args:         args{ctx, ns1, s2},
//			handler:      service.ServiceRemoveH,
//			err:          "{\"code\":404,\"status\":\"Not Found\",\"message\":\"Service not found\"}",
//			wantErr:      true,
//			expectedCode: http.StatusNotFound,
//		},
//		{
//			name:         "checking get service if namespace not exists",
//			fields:       fields{stg},
//			args:         args{ctx, ns2, s1},
//			handler:      service.ServiceRemoveH,
//			err:          "{\"code\":404,\"status\":\"Not Found\",\"message\":\"Namespace not found\"}",
//			wantErr:      true,
//			expectedCode: http.StatusNotFound,
//		},
//		{
//			name:         "checking get service successfully",
//			fields:       fields{stg},
//			args:         args{ctx, ns1, s1},
//			handler:      service.ServiceRemoveH,
//			want:         "",
//			wantErr:      false,
//			expectedCode: http.StatusOK,
//		},
//	}
//
//	clear := func() {
//		err := envs.Get().GetStorage().Del(context.Background(), stg.Collection().Namespace(), models.EmptyString)
//		assert.NoError(t, err)
//
//		err = envs.Get().GetStorage().Del(context.Background(), stg.Collection().Service(), models.EmptyString)
//		assert.NoError(t, err)
//	}
//
//	for _, tc := range tests {
//		t.Run(tc.name, func(t *testing.T) {
//
//			clear()
//			defer clear()
//
//			err := tc.fields.stg.Put(context.Background(), stg.Collection().Namespace(), ns1.SelfLink().String(), ns1, nil)
//			assert.NoError(t, err)
//
//			err = tc.fields.stg.Put(context.Background(), stg.Collection().Service(), s1.SelfLink().String(), s1, nil)
//			assert.NoError(t, err)
//
//			// Create assert request to pass to our handler. We don't have any query parameters for now, so we'll
//			// pass 'nil' as the third parameter.
//			req, err := http.NewRequest("DELETE", fmt.Sprintf("/namespace/%s/service/%s", tc.args.namespace.Meta.Name, tc.args.service.Meta.Name), nil)
//			assert.NoError(t, err)
//
//			if tc.headers != nil {
//				for key, val := range tc.headers {
//					req.Header.Set(key, val)
//
//				}
//			}
//
//			r := mux.NewRouter()
//			r.HandleFunc("/namespace/{namespace}/service/{service}", tc.handler)
//
//			setRequestVars(r, req)
//
//			// We create assert ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
//			res := httptest.NewRecorder()
//
//			// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
//			// directly and pass in our Request and ResponseRecorder.
//			r.ServeHTTP(res, req)
//
//			// Check the status code is what we expect.
//			if !assert.Equal(t, tc.expectedCode, res.Code, "status code not equal") {
//				return
//			}
//
//			body, err := ioutil.ReadAll(res.Body)
//			assert.NoError(t, err)
//
//			if tc.wantErr && res.Code != 200 {
//				assert.Equal(t, tc.err, string(body), "incorrect status code")
//			} else {
//
//				got := new(models.Service)
//				err := tc.fields.stg.Get(tc.args.ctx, stg.Collection().Service(), tc.args.service.SelfLink().String(), got, nil)
//				if err != nil && !errors.Storage().IsErrEntityNotFound(err) {
//					assert.NoError(t, err)
//				}
//
//				if got != nil {
//					assert.Equal(t, got.Status.State, models.StateDestroy, "status not destroy")
//				}
//
//				assert.Equal(t, tc.want, string(body), "response not equal with want")
//			}
//
//		})
//	}
//
//}
//
//func getNamespaceAsset(name, desc string) *models.Namespace {
//	var n = models.Namespace{}
//	n.Meta.SetDefault()
//	n.Meta.Name = name
//	n.Meta.Description = desc
//	n.Meta.SelfLink = *models.NewNamespaceSelfLink(name)
//	return &n
//}
//
//func getServiceAsset(namespace, name, desc string) *models.Service {
//	var s = models.Service{}
//	s.Meta.SetDefault()
//	s.Meta.Namespace = namespace
//	s.Meta.Name = name
//	s.Meta.Description = desc
//	s.Spec.Replicas = 1
//	s.Spec.Template.Containers = make(models.SpecTemplateContainers, 0)
//	s.Spec.Template.Containers = append(s.Spec.Template.Containers, &models.SpecTemplateContainer{
//		Name: "demo",
//	})
//	s.Meta.SelfLink = *models.NewServiceSelfLink(namespace, name)
//	return &s
//}
//
//func setRequestVars(r *mux.Router, req *http.Request) {
//	var match mux.RouteMatch
//	// Take the request and match it
//	r.Match(req, &match)
//	// Push the variable onto the context
//	req = mux.SetURLVars(req, match.Vars)
//}
//
//func getServiceManifest(name, image string) *request.ServiceManifest {
//
//	var (
//		replicas  = 1
//		container = request.ManifestSpecTemplateContainer{
//			Name: image,
//			Image: &request.ManifestSpecTemplateContainerImage{
//				Name: image,
//			},
//			Env: make([]request.ManifestSpecTemplateContainerEnv, 0),
//		}
//		volume = request.ManifestSpecTemplateVolume{
//			Name: "demo",
//			Secret: &request.ManifestSpecTemplateSecretVolume{
//				Name:  "test",
//				Binds: make([]request.ManifestSpecTemplateSecretVolumeBind, 0),
//			},
//		}
//	)
//
//	volume.Secret.Binds = append(volume.Secret.Binds, request.ManifestSpecTemplateSecretVolumeBind{
//		Key:  "demo",
//		File: "test.txt",
//	})
//
//	container.Env = append(container.Env, request.ManifestSpecTemplateContainerEnv{
//		Name:  "Demo",
//		Value: "test",
//	})
//
//	container.Env = append(container.Env, request.ManifestSpecTemplateContainerEnv{
//		Name: "Secret",
//		Secret: &request.ManifestSpecTemplateContainerEnvSecret{
//			Name: "secret-name",
//			Key:  "secret-key",
//		},
//	})
//
//	mf := new(request.ServiceManifest)
//	mf.Meta.Name = &name
//	mf.Spec.Replicas = &replicas
//	mf.Spec.Template = new(request.ManifestSpecTemplate)
//	mf.Spec.Template.Containers = append(mf.Spec.Template.Containers, container)
//	mf.Spec.Template.Volumes = append(mf.Spec.Template.Volumes, volume)
//	return mf
//}


text:
using System;
using Windows.Foundation.Metadata;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Animation;
using UrbanSketchers;
using UrbanSketchers.Controls;
using UWP.Renderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;

[assembly: ExportRenderer(typeof(ConnectedImage), typeof(ConnectedImageRenderer))]

namespace UWP.Renderers
{
    /// <summary>
    ///     Connected Animation image renderer
    /// </summary>
    public class ConnectedImageRenderer : ImageRenderer
    {
        /// <summary>
        ///     Attach the Animate event handler and the Control property
        /// </summary>
        /// <param name="e">the element changed event arguments</param>
        protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement is ConnectedImage connectedImage)
            {
                connectedImage.Animate += Animate;
                connectedImage.PrepareToAnimate += Prepare;

                var nativeImage = GetNativeElement();

                connectedImage.Control = nativeImage;

                nativeImage.SetValue(NameProperty, connectedImage.Name);
            }
        }

        private void Prepare(object sender, TypedEventArgs<string> args)
        {
            if (ApiInformation.IsTypePresent("Windows.UI.Xaml.Media.Animation.ConnectedAnimationService") &&
                Control is UIElement uiElement)
                ConnectedAnimationService.GetForCurrentView().PrepareToAnimate(args.Value, uiElement);
        }

        /// <summary>
        ///     Animate the
        /// </summary>
        /// <param name="sender">the destination as a <see cref="UIElement" /></param>
        /// <param name="args">the event arguments with the name of the animation</param>
        private async void Animate(object sender, TypedEventArgs<string> args)
        {
            if (ApiInformation.IsTypePresent("Windows.UI.Xaml.Media.Animation.ConnectedAnimationService"))
                await Control.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, delegate
                {
                    var animation = ConnectedAnimationService.GetForCurrentView().GetAnimation(args.Value);

                    if (animation != null && sender is UIElement destination)
                        animation.TryStart(destination);
                });
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

//error_reporting(E_ERROR);
require_once('../../settings.inc.php');
echo $conf[$argv[1]];
?>


text:
package pl.kobietydokodu.cats.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import pl.kobietydokodu.cats.domain.Cat;

/**
 * The use of EntityManager to generate JPQL queries and standard operations on database.
 */
@Repository
public class HibernateKotDAO {

	@PersistenceContext
	EntityManager entityManager;

	/**
	 * Add cat to table 'cats'
	 */
	@Transactional
	public void addCat(Cat cat) {
		entityManager.merge(cat);
	}

	/**
	 * @return Return list of cats from table 'cats'
	 */
	public List<Cat> getCats() {

		Query query = entityManager.createQuery("SELECT k FROM Cat k");
		List<Cat> cats = query.getResultList();

		return cats;
	}

	/**
	 * @param id Unique identification number of cat
	 * @return Cat with specific id number
	 */
	public Cat getKotById(Long id) {

		Cat cat = new Cat();
		cat = entityManager.find(Cat.class, id);

		return cat;

	}

}


text:
app.factory('accountService', ['$http', '$q', '$cookies', '$rootScope', function($http, $q, $cookies, $rootScope) {
    var serverUrl = "http://api.the-mesta.com";
    return {

        statusChangeCallback: function (response) {
            if (response.status === 'connected')
            {
                console.log('Welcome!  Fetching your information.... ');
                FB.api('/me', function(response) {
                    console.log('Successful login for: ' + response.name);
                });
            }
        },

        signedIn: function (response) {
            return (response.status === 'connected');
        },

        getFBlogin: function (response) {
            if (response.status === 'connected') {
                $rootScope.$broadcast("setFBObj", response);

                // Set the API endpoint
                $cookies.put("fbLoginID", response.authResponse.userID, {domain: ".the-mesta.com"});
                $cookies.put("AccessToken", response.authResponse.accessToken, {domain: ".the-mesta.com"});

                // Request for logging in
                var req = {
                    method: 'POST',
                    url: serverUrl + '/account/fblogin',
                    headers: {
                        'Content-Type': 'application/json;',
                        "Access-Control-Request-Credentials": "true"
                    },
                    withCredentials: true,
                    data: {
                        fbLoginID: response.authResponse.userID,
                        AccessToken: response.authResponse.accessToken
                    }
                };

                return $q(function (resolve, reject) {
                    $http(req).then(function (response) {
                        $rootScope.$broadcast('signedIn', true);
                        resolve(response.data);
                    });
                });
            }
            else
            {
                return null;
            }
        }
    }
}]);


text:
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
namespace Microsoft.Hadoop.Client
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using Microsoft.WindowsAzure.Management.HDInsight.Logging;

    /// <summary>
    /// Represents the base interface of a Hadoop Client.
    /// </summary>
    [Obsolete("NOTE: This library has been deprecated. Please use the Microsoft.Azure.Management.HDInsight or Microsoft.Azure.Management.HDInsight.Job packages instead. For more information, go to: http://go.microsoft.com/fwlink/p/?LinkID=785087", false)]
    public interface IHadoopClientBase : IDisposable, ILogProvider
    {
        /// <summary>
        /// Cancel's a pending operation.
        /// </summary>
        void Cancel();

        /// <summary>
        /// Adds a log writer to the client.
        /// </summary>
        /// <param name="logWriter">
        /// The log writer.
        /// </param>
        void AddLogWriter(ILogWriter logWriter);

        /// <summary>
        /// Removes a log writer.
        /// </summary>
        /// <param name="logWriter">
        /// The log writer.
        /// </param>
        void RemoveLogWriter(ILogWriter logWriter);

        /// <summary>
        /// Gets or sets a value indicating whether or not servicer side SSL errors should be ignored.
        /// </summary>
        bool IgnoreSslErrors { get; set; }

        /// <summary>
        /// Allows a user to set a custom cancellation source.
        /// </summary>
        /// <param name="tokenSource">
        /// The cancellation source.
        /// </param>
        void SetCancellationSource(CancellationTokenSource tokenSource);
    }
}


text:
package com.thecoderscorner.groovychart.chart;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.CategoryDataset;

/**
 *
 * @author jclarke
 */
public class BarChart3D extends CategoryValueChart {

    /** Creates a new instance of AreaGraph */
    public BarChart3D() {
        super();
    }

    public JFreeChart createChart() {
        return ChartFactory.createBarChart3D(getTitle(), getCategoryAxisLabel(),
                getValueAxisLabel(), (CategoryDataset)getDataset(),
                getOrientation(), isLegend(), isTooltips(), isUrls());
    }

}


text:
'use strict';

/**
 * @ngdoc service
 * @name Memberships
 * @description
 * # Memberships
 * Factory in the mission-control app.
 */
angular.module('mission-control')
  .factory('Memberships', function ($resource, SSE_API_URLS) {
    return $resource(SSE_API_URLS.base + SSE_API_URLS.memberships);
  });


text:
package flaxbeard.sprockets.items;

import java.util.List;

import flaxbeard.sprockets.Sprockets;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;

public class ItemSprocketBase extends Item
{
	public final String name;
	public String[] subnames;

	public ItemSprocketBase(String name)
	{
		this.setRegistryName(name);
		GameRegistry.register(this);
		this.setUnlocalizedName(Sprockets.MODID + "." + name);
		this.setCreativeTab(Sprockets.creativeTab);
		this.name = name;
		subnames = new String[0];
        this.setMaxDamage(0);

	}

	@Override
	public void getSubItems(Item item, CreativeTabs tab, List list)
	{
		if (subnames.length == 0)
		{
			list.add(new ItemStack(this));
		}
		for (int i = 0; i < subnames.length; i++)
		{
			list.add(new ItemStack(this, 1, i));
		}
	}

	@Override
	public String getUnlocalizedName(ItemStack itemstack)
	{
		int damage = itemstack.getItemDamage();
		if (damage >= subnames.length)
		{
			return super.getUnlocalizedName();
		}
		return super.getUnlocalizedName(itemstack) + "." + subnames[damage];
	}

}


text:
package com.debjyotipaul.util;

/**
 * Created with IntelliJ IDEA.
 * User: debjyoti.paul
 * Date: 10/11/14
 * Time: 12:12 PM
 * To change this template use File | Settings | File Templates.
 */
import java.util.Random;

/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {

    public static final void main(String... aArgs){
        log("Generating 10 random integers in range 0..49.");

        //note a single Random object is reused here
        Random randomGenerator = new Random();
        for (int idx = 1; idx <= 10; ++idx){
            int randomInt = randomGenerator.nextInt(500);
            log("Generated : " + randomInt);
        }

        log("Done.");
    }

    private static void log(String aMessage){
        System.out.println(aMessage);
    }
}


text:
This is a simple template that deploys an Ubuntu Virtual Machine with multiple disks attached, and uses mdadm script to create a raid0 volume with all attached data disks.

This template also deploys a Storage Account, Virtual Network, Public IP addresses, and a Network Interface.


text:
require_relative '../spec_helper'

describe Archivist::Model::FormatIndex do
  let(:index) { Archivist::Model::FormatIndex.new }

  it "initializes" do
    index
  end
end


text:
/*#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <Interface.h>

void Interface::setSampleRate()
{
    printf("Sample Rate: ");
    std::cin >> sampleRate;
}

void Interface::setSamplePerChan()
{
    printf("Samples Per Channel: ");
    std::cin >> samplePerChan;
}

int Interface::getSampleRate()
{
    return sampleRate;
}

int Interface::getSamplePerChan()
{
    return samplePerChan;
}*/


text:
package com.google.cloud.apigeeregistry.v1.samples;

// [START apigeeregistry_v1_generated_Registry_DeleteApi_String_sync]
import com.google.cloud.apigeeregistry.v1.ApiName;
import com.google.cloud.apigeeregistry.v1.RegistryClient;
import com.google.protobuf.Empty;

public class SyncDeleteApiString {

  public static void main(String[] args) throws Exception {
    syncDeleteApiString();
  }

  public static void syncDeleteApiString() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (RegistryClient registryClient = RegistryClient.create()) {
      String name = ApiName.of("[PROJECT]", "[LOCATION]", "[API]").toString();
      registryClient.deleteApi(name);
    }
  }
}
// [END apigeeregistry_v1_generated_Registry_DeleteApi_String_sync]


text:
// ========================================================================
// Copyright (c) 2008-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================

package org.eclipse.jetty.security.authentication;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.Principal;
import java.security.cert.CRL;
import java.security.cert.X509Certificate;
import java.util.Collection;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.http.security.Constraint;
import org.eclipse.jetty.http.security.Password;
import org.eclipse.jetty.security.ServerAuthException;
import org.eclipse.jetty.security.UserAuthentication;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.Authentication.User;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.security.CertificateUtils;
import org.eclipse.jetty.util.security.CertificateValidator;

/**
 * @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
 */
public class ClientCertAuthenticator extends LoginAuthenticator
{
    /** String name of keystore password property. */
    private static final String PASSWORD_PROPERTY = "org.eclipse.jetty.ssl.password";

    /** Truststore path */
    private String _trustStorePath;
    /** Truststore provider name */
    private String _trustStoreProvider;
    /** Truststore type */
    private String _trustStoreType = "JKS";
    /** Truststore password */
    private transient Password _trustStorePassword;

    /** Set to true if SSL certificate validation is required */
    private boolean _validateCerts;
    /** Path to file that contains Certificate Revocation List */
    private String _crlPath;
    /** Maximum certification path length (n - number of intermediate certs, -1 for unlimited) */
    private int _maxCertPathLength = -1;
    /** CRL Distribution Points (CRLDP) support */
    private boolean _enableCRLDP = false;
    /** On-Line Certificate Status Protocol (OCSP) support */
    private boolean _enableOCSP = false;
    /** Location of OCSP Responder */
    private String _ocspResponderURL;

    public ClientCertAuthenticator()
    {
        super();
    }

    public String getAuthMethod()
    {
        return Constraint.__CERT_AUTH;
    }

    /**
     * @return Authentication for request
     * @throws ServerAuthException
     */
    public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
    {
        if (!mandatory)
            return _deferred;

        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");

        try
        {
            // Need certificates.
            if (certs != null && certs.length > 0)
            {

                if (_validateCerts)
                {
                    KeyStore trustStore = getKeyStore(null,
                            _trustStorePath, _trustStoreType, _trustStoreProvider,
                            _trustStorePassword == null ? null :_trustStorePassword.toString());
                    Collection<? extends CRL> crls = loadCRL(_crlPath);
                    CertificateValidator validator = new CertificateValidator(trustStore, crls);
                    validator.validate(certs);
                }

                for (X509Certificate cert: certs)
                {
                    if (cert==null)
                        continue;

                    Principal principal = cert.getSubjectDN();
                    if (principal == null) principal = cert.getIssuerDN();
                    final String username = principal == null ? "clientcert" : principal.getName();

                    final char[] credential = B64Code.encode(cert.getSignature());

                    UserIdentity user = _loginService.login(username,credential);
                    if (user!=null)
                    {
                        renewSessionOnAuthentication(request,response);
                        return new UserAuthentication(getAuthMethod(),user);
                    }
                }
            }

            if (!_deferred.isDeferred(response))
            {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return Authentication.SEND_FAILURE;
            }

            return Authentication.UNAUTHENTICATED;
        }
        catch (Exception e)
        {
            throw new ServerAuthException(e.getMessage());
        }
    }

    /* ------------------------------------------------------------ */
    /**
     * Loads keystore using an input stream or a file path in the same
     * order of precedence.
     *
     * Required for integrations to be able to override the mechanism
     * used to load a keystore in order to provide their own implementation.
     *
     * @param storeStream keystore input stream
     * @param storePath path of keystore file
     * @param storeType keystore type
     * @param storeProvider keystore provider
     * @param storePassword keystore password
     * @return created keystore
     * @throws Exception
     */
    protected KeyStore getKeyStore(InputStream storeStream, String storePath, String storeType, String storeProvider, String storePassword) throws Exception
    {
        return CertificateUtils.getKeyStore(storeStream, storePath, storeType, storeProvider, storePassword);
    }

    /* ------------------------------------------------------------ */
    /**
     * Loads certificate revocation list (CRL) from a file.
     *
     * Required for integrations to be able to override the mechanism used to
     * load CRL in order to provide their own implementation.
     *
     * @param crlPath path of certificate revocation list file
     * @return a (possibly empty) collection view of java.security.cert.CRL objects initialized with the data from the
     *         input stream.
     * @throws Exception
     */
    protected Collection<? extends CRL> loadCRL(String crlPath) throws Exception
    {
        return CertificateUtils.loadCRL(crlPath);
    }

    public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
    {
        return true;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return true if SSL certificate has to be validated
     */
    public boolean isValidateCerts()
    {
        return _validateCerts;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param validateCerts
     *            true if SSL certificates have to be validated
     */
    public void setValidateCerts(boolean validateCerts)
    {
        _validateCerts = validateCerts;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return The file name or URL of the trust store location
     */
    public String getTrustStore()
    {
        return _trustStorePath;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param trustStorePath
     *            The file name or URL of the trust store location
     */
    public void setTrustStore(String trustStorePath)
    {
        _trustStorePath = trustStorePath;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return The provider of the trust store
     */
    public String getTrustStoreProvider()
    {
        return _trustStoreProvider;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param trustStoreProvider
     *            The provider of the trust store
     */
    public void setTrustStoreProvider(String trustStoreProvider)
    {
        _trustStoreProvider = trustStoreProvider;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return The type of the trust store (default "JKS")
     */
    public String getTrustStoreType()
    {
        return _trustStoreType;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param trustStoreType
     *            The type of the trust store (default "JKS")
     */
    public void setTrustStoreType(String trustStoreType)
    {
        _trustStoreType = trustStoreType;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param password
     *            The password for the trust store
     */
    public void setTrustStorePassword(String password)
    {
        _trustStorePassword = Password.getPassword(PASSWORD_PROPERTY,password,null);
    }

    /* ------------------------------------------------------------ */
    /** Get the crlPath.
     * @return the crlPath
     */
    public String getCrlPath()
    {
        return _crlPath;
    }

    /* ------------------------------------------------------------ */
    /** Set the crlPath.
     * @param crlPath the crlPath to set
     */
    public void setCrlPath(String crlPath)
    {
        _crlPath = crlPath;
    }

    /**
     * @return Maximum number of intermediate certificates in
     * the certification path (-1 for unlimited)
     */
    public int getMaxCertPathLength()
    {
        return _maxCertPathLength;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param maxCertPathLength
     *            maximum number of intermediate certificates in
     *            the certification path (-1 for unlimited)
     */
    public void setMaxCertPathLength(int maxCertPathLength)
    {
        _maxCertPathLength = maxCertPathLength;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return true if CRL Distribution Points support is enabled
     */
    public boolean isEnableCRLDP()
    {
        return _enableCRLDP;
    }

    /* ------------------------------------------------------------ */
    /** Enables CRL Distribution Points Support
     * @param enableCRLDP true - turn on, false - turns off
     */
    public void setEnableCRLDP(boolean enableCRLDP)
    {
        _enableCRLDP = enableCRLDP;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return true if On-Line Certificate Status Protocol support is enabled
     */
    public boolean isEnableOCSP()
    {
        return _enableOCSP;
    }

    /* ------------------------------------------------------------ */
    /** Enables On-Line Certificate Status Protocol support
     * @param enableOCSP true - turn on, false - turn off
     */
    public void setEnableOCSP(boolean enableOCSP)
    {
        _enableOCSP = enableOCSP;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Location of the OCSP Responder
     */
    public String getOcspResponderURL()
    {
        return _ocspResponderURL;
    }

    /* ------------------------------------------------------------ */
    /** Set the location of the OCSP Responder.
     * @param ocspResponderURL location of the OCSP Responder
     */
    public void setOcspResponderURL(String ocspResponderURL)
    {
        _ocspResponderURL = ocspResponderURL;
    }
}


text:
namespace WebsitePanel.Portal.ProviderControls {

    public partial class SmarterMail100_Settings {

        /// <summary>
        /// lblServiceUrl control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblServiceUrl;

        /// <summary>
        /// txtServiceUrl control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtServiceUrl;

        /// <summary>
        /// lblPublicIP control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblPublicIP;

        /// <summary>
        /// ipAddress control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::WebsitePanel.Portal.SelectIPAddress ipAddress;

        /// <summary>
        /// lblDomainsPath control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblDomainsPath;

        /// <summary>
        /// txtDomainsFolder control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtDomainsFolder;

        /// <summary>
        /// lblAdminLogin control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblAdminLogin;

        /// <summary>
        /// txtUsername control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtUsername;

        /// <summary>
        /// rowPassword control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTableRow rowPassword;

        /// <summary>
        /// lblCurrPassword control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblCurrPassword;

        /// <summary>
        /// lblAdminPassword control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblAdminPassword;

        /// <summary>
        /// txtPassword control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtPassword;

        /// <summary>
        /// cbImportDomainAdmin control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox cbImportDomainAdmin;

        /// <summary>
        /// cbInheritDefaultLimits control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox cbInheritDefaultLimits;

        /// <summary>
        /// cbEnableDomainAdmin control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox cbEnableDomainAdmin;
    }
}


text:
/*
combined modules:
logger-manager
*/
modulex.add("logger-manager", [], function(require, exports, module) {/**
 * simple logger management.
 * @author yiminghe@gmail.com
 */

var config = {};
var loggerLevel = {
    debug: 10,
    info: 20,
    warn: 30,
    error: 40
};

var Logger;

function getLogger(logger) {
    var obj = {};
    for (var cat in loggerLevel) {
        /*jshint loopfunc: true*/
        (function (obj, cat) {
            obj[cat] = function (msg) {
                return Logger.log(msg, cat, logger);
            };
        })(obj, cat);
    }
    return obj;
}

Logger = module.exports = {
    version: '1.0.0',

    _debug: '@DEBUG@',

    config: function (cfg) {
        if (cfg) {
            config = cfg;
        }
        return config;
    },
    /**
     * Prints debug info.
     * @param msg {String} the message to log.
     * @param {String} [cat] the log category for the message. Default
     *        categories are 'info', 'warn', 'error', 'time' etc.
     * @param {String} [logger] the logger of the the message (opt)
     */
    log: function (msg, cat, logger) {
        var matched = 1;
        if (logger) {
            matched = 0;
            var list, i, l, level, minLevel, maxLevel, reg;
            cat = cat || 'debug';
            level = loggerLevel[cat] || loggerLevel.debug;
            if ((list = config.includes)) {
                matched = 0;
                for (i = 0; i < list.length; i++) {
                    l = list[i];
                    reg = l.logger;
                    maxLevel = loggerLevel[l.maxLevel] || loggerLevel.error;
                    minLevel = loggerLevel[l.minLevel] || loggerLevel.debug;
                    if (minLevel <= level && maxLevel >= level && logger.match(reg)) {
                        matched = 1;
                        break;
                    }
                }
            } else if ((list = config.excludes)) {
                matched = 1;
                for (i = 0; i < list.length; i++) {
                    l = list[i];
                    reg = l.logger;
                    maxLevel = loggerLevel[l.maxLevel] || loggerLevel.error;
                    minLevel = loggerLevel[l.minLevel] || loggerLevel.debug;
                    if (minLevel <= level && maxLevel >= level && logger.match(reg)) {
                        matched = 0;
                        break;
                    }
                }
            }
            if (matched) {
                msg = logger + ': ' + msg;
            }
        }
        /*global console*/
        if (matched) {
            if (typeof console !== 'undefined' && console.log) {
                console[cat && console[cat] ? cat : 'log'](msg);
            }
            return msg;
        }
        return undefined;
    },

    /**
     * get log instance for specified logger
     * @param {String} logger logger name
     * @returns log instance
     */
    getLogger: function (logger) {
        return getLogger(logger);
    },

    /**
     * Throws error message.
     */
    error: function (msg) {
        // with stack info!
        throw msg instanceof  Error ? msg : new Error(msg);
    }
};});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ISAAR.MSolve.PreProcessor.Interfaces;
using ISAAR.MSolve.PreProcessor.Materials;
using ISAAR.MSolve.Matrices.Interfaces;
using ISAAR.MSolve.Matrices;

namespace ISAAR.MSolve.PreProcessor.Elements
{
    public class Beam2DNL : IStructuralFiniteElement
    {
        private static readonly DOFType[] nodalDOFTypes = new DOFType[3] { DOFType.X, DOFType.Y, DOFType.RotZ };
        private static readonly DOFType[][] dofs = new DOFType[][] { nodalDOFTypes, nodalDOFTypes };
        private readonly IFiniteElementMaterial material;
        private IFiniteElementDOFEnumerator dofEnumerator = new GenericDOFEnumerator();

        public double Density { get; set; }
        public double SectionArea { get; set; }
        public double MomentOfInertia { get; set; }

        private double cosInitial, sinInitial, lengthInitial, betaAngleInitial;
        private double cosCurrent, sinCurrent, lengthCurrent, betaAngleCurrent;
        private double[] node1XYInitial, node2XYInitial, node1XYCurrent, node2XYCurrent;
        private double[] node1GlobalDisplacementVector, node2GlobalDisplacementVector;

        private bool isInitializedK = false;
        private bool isInitializedF = false;

        public Beam2DNL(IFiniteElementMaterial material)
        {
            this.material = material;
            this.node1GlobalDisplacementVector = new double[3];
            this.node2GlobalDisplacementVector = new double[3];

        }

        public Beam2DNL(IFiniteElementMaterial material, IFiniteElementDOFEnumerator dofEnumerator)
            : this(material)
        {
            this.dofEnumerator = dofEnumerator;
            this.node1GlobalDisplacementVector = new double[3];
            this.node2GlobalDisplacementVector = new double[3];
        }

        public IFiniteElementDOFEnumerator DOFEnumerator
        {
            get { return dofEnumerator; }
            set { dofEnumerator = value; }
        }

        #region IElementType Members

        public int ID
        {
            get { return 1; }
        }

        public ElementDimensions ElementDimensions
        {
            get { return ElementDimensions.TwoD; }
        }

        public IList<IList<DOFType>> GetElementDOFTypes(Element element)
        {
            return dofs;
        }

        public IList<Node> GetNodesForMatrixAssembly(Element element)
        {
            return element.Nodes;
        }

        private void GetInitialGeometricData(Element element)
        {
            node1XYInitial = new double[] { element.Nodes[0].X, element.Nodes[0].Y };
            node2XYInitial = new double[] { element.Nodes[1].X, element.Nodes[1].Y };
            lengthInitial = Math.Sqrt(Math.Pow(node2XYInitial[0] - node1XYInitial[0], 2) + Math.Pow(node2XYInitial[1] - node1XYInitial[1], 2));
            betaAngleInitial = Math.Atan2(node2XYInitial[1] - node1XYInitial[1], node2XYInitial[0] - node1XYInitial[0]);
            cosInitial = (node2XYInitial[0] - node1XYInitial[0]) / lengthInitial;
            sinInitial = (node2XYInitial[1] - node1XYInitial[1]) / lengthInitial;

            lengthCurrent = lengthInitial;
            sinCurrent = sinInitial;
            cosCurrent = cosInitial;
            betaAngleCurrent = betaAngleInitial;
        }

        private void GetCurrentGeometricalData()
        {
            node1XYCurrent = new[]
            {
                node1XYInitial[0] + node1GlobalDisplacementVector[0],
                node1XYInitial[1] + node1GlobalDisplacementVector[1]
            };

            node2XYCurrent = new[]
            {
                node2XYInitial[0] + node2GlobalDisplacementVector[0],
                node2XYInitial[1] + node2GlobalDisplacementVector[1]
            };
            betaAngleCurrent = Math.Atan2(node2XYCurrent[1] - node1XYCurrent[1], node2XYCurrent[0] - node1XYCurrent[0]);

            lengthCurrent = Math.Sqrt(Math.Pow(node2XYCurrent[0] - node1XYCurrent[0], 2) + Math.Pow(node2XYCurrent[1] - node1XYCurrent[1], 2));
            cosCurrent = (node2XYCurrent[0] - node1XYCurrent[0]) / lengthCurrent;
            sinCurrent = (node2XYCurrent[1] - node1XYCurrent[1]) / lengthCurrent;
        }

        public IMatrix2D<double> StiffnessMatrix(Element element)
        {
            if (this.isInitializedK == false)
            {
                this.GetInitialGeometricData(element);
                this.isInitializedK = true;
            }

            double sinb = sinCurrent;
            double cosb = cosCurrent;
            double cosb2 = cosCurrent * cosCurrent;
            double sinb2 = sinCurrent * sinCurrent;
            double cosbsinb = cosCurrent * sinCurrent;
            double Lc = lengthCurrent;
            double L0 = lengthInitial;
            double Lc2 = lengthCurrent * lengthCurrent;
            double E = (material as ElasticMaterial).YoungModulus;
            double I = MomentOfInertia;
            double A = SectionArea;
            double N = A * E * (lengthCurrent - lengthInitial) / lengthInitial;
            double M1 = 2 * E * I * (node2GlobalDisplacementVector[2] - betaAngleCurrent + betaAngleInitial) / lengthInitial + 4 * E * I * (node1GlobalDisplacementVector[2] - betaAngleCurrent + betaAngleInitial) / lengthInitial;
            double M2 = 4 * E * I * (node2GlobalDisplacementVector[2] - betaAngleCurrent + betaAngleInitial) / lengthInitial + 2 * E * I * (node1GlobalDisplacementVector[2] - betaAngleCurrent + betaAngleInitial) / lengthInitial;

            double[,] globalStiffnessMatrix = new double[6, 6];
            globalStiffnessMatrix[0, 0] = N * sinb2 / Lc + 12 * E * I * sinb2 / (L0 * Lc2) - 2 * (M2 + M1) * cosbsinb / Lc2 + A * E * cosb2 / L0;
            globalStiffnessMatrix[0, 1] = (M2 + M1) * (cosb2 - sinb2) / Lc2 - N * cosbsinb / Lc - 12 * E * I * cosbsinb / (L0 * Lc2) + A * E * cosbsinb / L0;
            globalStiffnessMatrix[0, 2] = -6 * E * I * sinb / (L0 * Lc);
            globalStiffnessMatrix[0, 3] = -N * sinb2 / Lc - 12 * E * I * sinb2 / (L0 * Lc2) + 2 * (M2 + M1) * cosbsinb / Lc2 - A * E * cosb2 / L0;
            globalStiffnessMatrix[0, 4] = (M2 + M1) * (sinb2 - cosb2) / Lc2 + N * cosbsinb / Lc + 12 * E * I * cosbsinb / (L0 * Lc2) - A * E * cosbsinb / L0;
            globalStiffnessMatrix[0, 5] = -6 * E * I * sinb / (L0 * Lc);

            globalStiffnessMatrix[1, 0] = globalStiffnessMatrix[0, 1];
            globalStiffnessMatrix[1, 1] = A * E * sinb2 / L0 + 2 * (M2 + M1) * cosbsinb / Lc2 + N * cosb2 / Lc + 12 * E * I * cosb2 / (L0 * Lc2);
            globalStiffnessMatrix[1, 2] = 6 * E * I * cosb / (L0 * Lc);
            globalStiffnessMatrix[1, 3] = (M2 + M1) * (sinb2 - cosb2) / Lc2 + N * cosbsinb / Lc + 12 * E * I * cosbsinb / (L0 * Lc2) - A * E * cosbsinb / L0;
            globalStiffnessMatrix[1, 4] = -A * E * sinb2 / L0 - 2 * (M2 + M1) * cosbsinb / Lc2 - N * cosb2 / Lc - 12 * E * I * cosb2 / (L0 * Lc2);
            globalStiffnessMatrix[1, 5] = 6 * E * I * cosb / (L0 * Lc);

            globalStiffnessMatrix[2, 0] = globalStiffnessMatrix[0, 2];
            globalStiffnessMatrix[2, 1] = globalStiffnessMatrix[1, 2];
            globalStiffnessMatrix[2, 2] = 4 * E * I / L0;
            globalStiffnessMatrix[2, 3] = 6 * E * I * sinb / (L0 * Lc);
            globalStiffnessMatrix[2, 4] = -6 * E * I * cosb / (L0 * Lc);
            globalStiffnessMatrix[2, 5] = 2 * E * I / L0;

            globalStiffnessMatrix[3, 0] = globalStiffnessMatrix[0, 3];
            globalStiffnessMatrix[3, 1] = globalStiffnessMatrix[1, 3];
            globalStiffnessMatrix[3, 2] = globalStiffnessMatrix[2, 3];
            globalStiffnessMatrix[3, 3] = N * sinb2 / Lc + 12 * E * I * sinb2 / (L0 * Lc2) - 2 * (M2 + M1) * cosbsinb / Lc2 + A * E * cosb2 / L0;
            globalStiffnessMatrix[3, 4] = (M2 + M1) * (cosb2 - sinb2) / Lc2 - N * cosbsinb / Lc - 12 * E * I * cosbsinb / (L0 * Lc2) + A * E * cosbsinb / L0;
            globalStiffnessMatrix[3, 5] = 6 * E * I * sinb / (L0 * Lc);

            globalStiffnessMatrix[4, 0] = globalStiffnessMatrix[0, 4];
            globalStiffnessMatrix[4, 1] = globalStiffnessMatrix[1, 4];
            globalStiffnessMatrix[4, 2] = globalStiffnessMatrix[2, 4];
            globalStiffnessMatrix[4, 3] = globalStiffnessMatrix[3, 4];
            globalStiffnessMatrix[4, 4] = A * E * sinb2 / L0 + 2 * (M2 + M1) * cosbsinb / Lc2 + N * cosb2 / Lc + 12 * E * I * cosb2 / (L0 * Lc2);
            globalStiffnessMatrix[4, 5] = -6 * E * I * cosb / (L0 * Lc);

            globalStiffnessMatrix[5, 0] = globalStiffnessMatrix[0, 5];
            globalStiffnessMatrix[5, 1] = globalStiffnessMatrix[1, 5];
            globalStiffnessMatrix[5, 2] = globalStiffnessMatrix[2, 5];
            globalStiffnessMatrix[5, 3] = globalStiffnessMatrix[3, 5];
            globalStiffnessMatrix[5, 4] = globalStiffnessMatrix[4, 5];
            globalStiffnessMatrix[5, 5] = 4 * E * I / L0;

            IMatrix2D<double> iGlobalStiffnessMatrix = new Matrix2D<double>(globalStiffnessMatrix);

            return dofEnumerator.GetTransformedMatrix(iGlobalStiffnessMatrix);
        }

        public IMatrix2D<double> MassMatrix(Element element)
        {
            double x2 = Math.Pow(element.Nodes[1].X - element.Nodes[0].X, 2);
            double y2 = Math.Pow(element.Nodes[1].Y - element.Nodes[0].Y, 2);
            double L = Math.Sqrt(x2 + y2);
            double L2 = L * L;
            double c = (element.Nodes[1].X - element.Nodes[0].X) / L;
            double c2 = c * c;
            double s = (element.Nodes[1].Y - element.Nodes[0].Y) / L;
            double s2 = s * s;
            double dAL420 = Density * SectionArea * L / 420;

            double totalMass = Density * SectionArea * L;
            double totalMassOfDiagonalTerms = 2 * dAL420 * (140 * c2 + 156 * s2) + 2 * dAL420 * (140 * s2 + 156 * c2);
            double scale = totalMass / totalMassOfDiagonalTerms;

            return new SymmetricMatrix2D<double>(new double[] { dAL420*(140*c2+156*s2)*scale, 0, 0, 0, 0, 0,
                dAL420*(140*s2+156*c2)*scale, 0, 0, 0, 0,
                0, 0, 0, 0,
                dAL420*(140*c2+156*s2)*scale, 0, 0,
                dAL420*(140*s2+156*c2)*scale, 0,
                0 });
        }

        public IMatrix2D<double> DampingMatrix(Element element)
        {
            throw new NotImplementedException();
        }

        public Tuple<double[], double[]> CalculateStresses(Element element, double[] localDisplacements, double[] localdDisplacements)
        {
            return null;
        }

        public double[] CalculateForcesForLogging(Element element, double[] localDisplacements)
        {
            return CalculateForces(element, localDisplacements, new double[localDisplacements.Length]);
        }

        public double[] CalculateForces(Element element, double[] localDisplacements, double[] localDeltaDisplacements)
        {
            if (this.isInitializedF == false)
            {
                node1GlobalDisplacementVector = new double[] { 0, 0, 0 };
                node2GlobalDisplacementVector = new double[] { 0, 0, 0 };
                isInitializedF = true;
            }
            else
            {
                //double[] totalDisplacementVector = new double[localDisplacements.Length];
                //for (int i = 0; i < localDisplacements.Length; ++i)
                //{
                //    totalDisplacementVector[i] = localDisplacements[i] + localDeltaDisplacements[i];
                //}
                node1GlobalDisplacementVector = new double[] { localDisplacements[0], localDisplacements[1], localDisplacements[2] };
                node2GlobalDisplacementVector = new double[] { localDisplacements[3], localDisplacements[4], localDisplacements[5] };
                //node1GlobalDisplacementVector = new double[] { totalDisplacementVector[0], totalDisplacementVector[1], totalDisplacementVector[2] };
                //node2GlobalDisplacementVector = new double[] { totalDisplacementVector[3], totalDisplacementVector[4], totalDisplacementVector[5] };
            }

            GetCurrentGeometricalData();
            double E = (material as ElasticMaterial).YoungModulus;
            double I = MomentOfInertia;
            double A = SectionArea;
            double N = A * E * (lengthCurrent - lengthInitial) / lengthInitial;
            double M1 = 2 * E * I * (node2GlobalDisplacementVector[2] - betaAngleCurrent + betaAngleInitial) / lengthInitial + 4 * E * I * (node1GlobalDisplacementVector[2] - betaAngleCurrent + betaAngleInitial) / lengthInitial;
            double M2 = 4 * E * I * (node2GlobalDisplacementVector[2] - betaAngleCurrent + betaAngleInitial) / lengthInitial + 2 * E * I * (node1GlobalDisplacementVector[2] - betaAngleCurrent + betaAngleInitial) / lengthInitial;
            double[] intforceV = new double[6];
            intforceV[0] = -(M2 * sinCurrent / lengthCurrent) - (M1 * sinCurrent / lengthCurrent) - N * cosCurrent;
            intforceV[1] = (M2 * cosCurrent / lengthCurrent) + (M1 * cosCurrent / lengthCurrent) - N * sinCurrent;
            intforceV[2] = M1;
            intforceV[3] = (M2 * sinCurrent / lengthCurrent) + (M1 * sinCurrent / lengthCurrent) + N * cosCurrent;
            intforceV[4] = -(M2 * cosCurrent / lengthCurrent) - (M1 * cosCurrent / lengthCurrent) + N * sinCurrent;
            intforceV[5] = M2;

            return intforceV;
        }

        public double[] CalculateAccelerationForces(Element element, IList<MassAccelerationLoad> loads)
        {
            Vector<double> accelerations = new Vector<double>(6);
            IMatrix2D<double> massMatrix = MassMatrix(element);

            int index = 0;
            foreach (MassAccelerationLoad load in loads)
                foreach (DOFType[] nodalDOFTypes in dofs)
                    foreach (DOFType dofType in nodalDOFTypes)
                    {
                        if (dofType == load.DOF) accelerations[index] += load.Amount;
                        index++;
                    }

            double[] forces = new double[6];
            massMatrix.Multiply(accelerations, forces);
            return forces;
        }

        public void SaveMaterialState()
        {

        }

        #endregion

        #region IStructuralFiniteElement Members

        public IFiniteElementMaterial Material
        {
            get { return material; }
        }

        #endregion

        #region IFiniteElement Members

        public bool MaterialModified
        {
            get { return material.Modified; }
        }

        public void ResetMaterialModified()
        {
            material.ResetModified();
        }

        #endregion

        #region IFiniteElement Members

        public void ClearMaterialState()
        {
        }

        public void ClearMaterialStresses()
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}


text:
<?php
/**
 * Contains \jamesiarmes\PhpEws\Type\TimeZoneType.
 */

namespace jamesiarmes\PhpEws\Type;

use \jamesiarmes\PhpEws\Type;

/**
 * Represents a time zone.
 *
 * @package php-ews\Type
 */
class TimeZoneType extends Type
{
    /**
     * Represents the hourly offset from UTC for the current time zone.
     *
     * @since Exchange 2007
     *
     * @var integer
     */
    public $BaseOffset;

    /**
     * Represents the date and time when the time changes from standard time to
     * daylight saving time.
     *
     * @since Exchange 2007
     *
     * @var \jamesiarmes\PhpEws\Type\TimeChangeType
     */
    public $Daylight;

    /**
     * Represents the date and time when the time changes from daylight saving
     * time to standard time.
     *
     * @since Exchange 2007
     *
     * @var \jamesiarmes\PhpEws\Type\TimeChangeType
     */
    public $Standard;

    /**
     * The name of the time zone.
     *
     * @since Exchange 2007
     *
     * @var string
     */
    public $TimeZoneName;
}


text:
declare interface ISpCrudStrings {
  PropertyPaneDescription: string;
  BasicGroupName: string;
  ListsFieldLabel: string;
  ListsOperationsFieldLabel: string;
}

declare module 'spCrudStrings' {
  const strings: ISpCrudStrings;
  export = strings;
}


text:
**EXPERIMENTAL: NOT INTENDED FOR PRODUCTION** There are definitely better solutions out there. Find one or build your own.

# Front-end Boilerplate

A full set of front-end development tools, based around NPM and Gulp.

[NPM](http://npmjs.org) is the standard package manager for Node. [Go here](http://nodejs.org) and click "Install" to get Node and NPM if you don't already have them. You won't need to use Node directly if you don't want to, so don't be concerned if you want to use something else as your back-end solution.

[Gulp](http://gulpjs.com) is a task management tool for building, testing and optimizing your web app projects. It takes care of all the boring-but-necessary tasks required to make high-quality web apps. Use ```npm install gulp -g``` to make Gulp available everywhere in your system.

## Features

Gulp gives you a bunch of great stuff without lifting a finger. It just happens every time you save your files.

- Sass compilation (to CSS)
- CSS autoprefixing
- CSS minification
- JSHint alerts
- JS uglification/minification/concatenation
- Image optimization
- Live Reload in the browser (no more refreshing!)
- Karma + Jasmine for JavaScript testing
- Built-in web server

## Coming Soon

- Cache-busting
- Gzipped assets
- UnCSS (removing unused rules on-the-fly)
- Browserify for client-side dependencies
- Hapi.js starter kit for Node dev

## Installation

- Clone this repo to your local system under your chosen project name
- Delete the ```.git``` directory
- ```git init; git add --all; git commit -m "Initial commit"``` to start a new, clean repo for your project
- ```npm init``` will prompt you for information about your project.
- ```npm install gulp gulp-ruby-sass gulp-autoprefixer gulp-minify-css gulp-jshint gulp-concat gulp-uglify gulp-imagemin gulp-notify gulp-rename gulp-livereload gulp-connect del karma karma-jasmine karma-chrome-launcher --save-dev``` will load all the components into a ```node_modules``` directory where NPM and Gulp can find them.
- ```gulp watch``` will start a server to serve your content on [http://localhost:8080](http://localhost:8080), live-reloading all your changes as you save your files. You'll need the [Chrome LiveReload extension](https://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei) for this to work. **NOTE** livereload only picks up edits to existing files: use ctrl-c to stop the watcher and restart to capture new html/js/img/styles.
- The code you edit is in the ```src``` directory structure:
  - ```html``` for HTML
  - ```scripts``` for Javascript
  - ```styles``` for Sass/CSS
  - ```images``` for images

  It will all be optimized and copied into the ```dist``` directory as you develop.
- Your Jasmine specs go in the ```test``` directory structure. An example has been provided. All specs will be rerun when your scripts or specs change.
- When you're ready to push your code to an actual web server, everything you need is in the ```dist``` directory: don't push the rest.


text:
//
//  PPSPingServices.h
//  PPS
//
//  Created by 羊谦 on 2016/12/9.
//  Copyright © 2016年 羊谦. All rights reserved.
//

#import <Foundation/Foundation.h>
//#import <CoreGraphics/CoreGraphics.h>

@class PPSPingSummary;

typedef void(^PingsBackHandler)(PPSPingSummary *pingItem, NSArray *pingItems);

@interface PPSPingServices : NSObject

+ (instancetype)serviceWithAddress:(NSString *)address;

+ (instancetype)serviceWithAddress:(NSString *)address
                  maximumPingTimes:(NSInteger)count;

/**
 开始收集

 @param handler 回调处理
 */
- (void)startWithCallbackHandler:(PingsBackHandler)handler;

- (void)cancel;

/**
 计算丢包率

 @param pingItems 传入包
 数组
 @return 返回丢包率字符串描述
 */
//+ (NSString *)statisticsStringWithPingItems:(NSArray *)pingItems;

/**
 计算丢包率

 @param pingItems 传入包数组
 @return 直接返回计算后得到的丢包率
 */
//+ (CGFloat)statisticsWithPingItems:(NSArray *)pingItems;

@end


text:
crits-hubot
===========

Hubot script for CRITs

This script is very alpha. Getting it out there so people can start to make
changes, expand upon available commands, and turn it into something super
useful.


text:
package com.squareup.wire.protos.custom_options;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyMessageOptionTwoOption {
  float value();
}


text:
using System;
using System.Linq;
using InEngine.Commands;
using InEngine.Core.Commands;
using InEngine.Core.Exceptions;
using InEngineTesting;
using InEngine.Core.Queuing.Commands;

namespace InEngine.Core.Test.Queuing.Commands;

[TestFixture]
public class PublishTest : TestBase<Publish>
{
    [SetUp]
    public void Setup() => InEngineSettings.BasePath = TestContext.CurrentContext.TestDirectory;
}


text:
class CreateCylons < ActiveRecord::Migration
  def self.up
    create_table :cylons do |t|
      t.string :name
      t.string :email

      t.timestamps
    end
  end

  def self.down
    drop_table :cylons
  end
end